forge
Explore
Log in

Don't you dare go Hollow

The inter luma transform-type search (IDTX vs DCT_DCT), off by default

Browse files at this commit

044aeb2c3ac27de6dd60e6794768e7268581ba55Ahmet Kaan GümüşParent: 5b25319
  • feat
    • the inter luma transform-type search (IDTX vs DCT_DCT), off by default
Show full message
feat(av1): the inter luma transform-type search (IDTX vs DCT_DCT), off by default

The writer has coded a two-symbol tx_type for every inter luma transform
unit at 32x32 and below since the inter coefficient tables landed, and always
named DCT_DCT. commit_inter_luma now prices both members of TX_SET_INTER_3
for the whole-block residual and for each var-tx split unit, by the same
sse + lambda * bits rule the intra search uses, and the winners reach the
writer through BlockCoeffs::luma_tx_types.

Off at every preset (speed::TX_TYPE_SEARCH_INTER) until the gate says
otherwise; EC_AV1_TXSET_INTER turns it on.
crates/ec-av1/src/encode.rsmodified+282 -39
@@ -41,10 +41,11 @@ use crate::tile::{
41 BlockCoeffs, Coeff, INTRA_MODE_CTX, InterInfo, InterMode, Quadrant, Superblock, partition_bits,41 BlockCoeffs, Coeff, INTRA_MODE_CTX, InterInfo, InterMode, Quadrant, Superblock, partition_bits,
42 };42 };
43 use crate::transform::{43 use crate::transform::{
44- TxType, dequant_and_inverse_typed_wh, forward_and_quantize,44+ TxType, dequant_and_inverse_typed_wh, forward_and_quantize_typed,
45- forward_and_quantize_scaled, forward_and_quantize_typed,
46 forward_and_quantize_typed_scaled,45 forward_and_quantize_typed_scaled,
47 };46 };
47+#[cfg(test)]
48+use crate::transform::forward_and_quantize;
48 49
49 /// The side of the larger of the two luma blocks this encoder codes, in50 /// The side of the larger of the two luma blocks this encoder codes, in
50 /// samples.51 /// samples.
@@ -285,6 +286,90 @@ pub(crate) fn tx_type_candidates(set: TxbSet, screen: bool) -> &'static [TxType]
285 }286 }
286 }287 }
287 288
289+/// The transform types an INTER luma transform unit of `set` may be coded
290+/// with (lane-txset2). Under this encoder's `reduced_tx_set` header bit every
291+/// inter luma set at 16x16 and below is the two-type `TX_SET_INTER_3`
292+/// (`IDTX`, `DCT_DCT`) and 32x32 is `EXT_TX_SET_DCT_IDTX` -- the same two
293+/// types, a symbol the writer already codes and never varied. 64x64 codes no
294+/// `tx_type` symbol at all, so it is not offered one.
295+/// `EC_AV1_TXSET_INTER`: `0`/`off`, `screen` (screen frames only), anything
296+/// else on for every frame.
297+pub(crate) fn inter_tx_type_candidates(set: TxbSet, screen: bool) -> &'static [TxType] {
298+ const DCT: [TxType; 1] = [TxType::DctDct];
299+ const INTER3: [TxType; 2] = [TxType::DctDct, TxType::Idtx];
300+ let on = match inter_tx_type_search() {
301+ InterTxSearch::Off => false,
302+ InterTxSearch::Screen => screen,
303+ InterTxSearch::All => true,
304+ };
305+ match set {
306+ TxbSet::Luma32Inter | TxbSet::Luma16Inter | TxbSet::Luma8Inter | TxbSet::Luma4Inter
307+ if on =>
308+ {
309+ &INTER3
310+ }
311+ _ => &DCT,
312+ }
313+}
314+
315+#[derive(Clone, Copy, PartialEq)]
316+pub(crate) enum InterTxSearch {
317+ Off,
318+ Screen,
319+ All,
320+}
321+
322+/// A PROCESS-GLOBAL [`inter_tx_type_search`] override that wins over both the
323+/// environment and the preset (`u8::MAX` = unset), the shape
324+/// [`set_deltaq_res`] has: the lever is OFF at every preset, so the witness
325+/// that has to see a non-`DCT_DCT` inter unit turns it on through this while
326+/// holding [`crate::speed::knob_write`].
327+static INTER_TX_OVERRIDE: std::sync::atomic::AtomicU8 =
328+ std::sync::atomic::AtomicU8::new(u8::MAX);
329+
330+/// Sets [`INTER_TX_OVERRIDE`]; `None` clears it.
331+#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
332+pub(crate) fn set_inter_tx_search(on: Option<bool>) {
333+ INTER_TX_OVERRIDE.store(
334+ on.map_or(u8::MAX, u8::from),
335+ std::sync::atomic::Ordering::Relaxed,
336+ );
337+}
338+
339+fn inter_tx_type_search() -> InterTxSearch {
340+ match INTER_TX_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
341+ 0 => return InterTxSearch::Off,
342+ 1 => return InterTxSearch::All,
343+ _ => {}
344+ }
345+ static ENV: std::sync::LazyLock<Option<InterTxSearch>> = std::sync::LazyLock::new(|| {
346+ crate::envflags::var("EC_AV1_TXSET_INTER").ok().map(|v| match v.as_str() {
347+ "0" | "off" => InterTxSearch::Off,
348+ "screen" => InterTxSearch::Screen,
349+ _ => InterTxSearch::All,
350+ })
351+ });
352+ ENV.unwrap_or_else(|| {
353+ if crate::speed::at(&crate::speed::TX_TYPE_SEARCH_INTER) {
354+ InterTxSearch::All
355+ } else {
356+ InterTxSearch::Off
357+ }
358+ })
359+}
360+
361+/// The inter luma [`TxbSet`] a `tx`-sided transform unit reads, `None` for the
362+/// 64-point one (it codes no `tx_type` symbol).
363+fn inter_luma_set(tx: usize) -> Option<TxbSet> {
364+ Some(match tx {
365+ 4 => TxbSet::Luma4Inter,
366+ 8 => TxbSet::Luma8Inter,
367+ 16 => TxbSet::Luma16Inter,
368+ 32 => TxbSet::Luma32Inter,
369+ _ => return None,
370+ })
371+}
372+
288 fn tx_type_search() -> bool {373 fn tx_type_search() -> bool {
289 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {374 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
290 crate::envflags::var("EC_AV1_TXSET")375 crate::envflags::var("EC_AV1_TXSET")
@@ -2262,6 +2347,28 @@ impl Plane<'_> {
2262 base_q_idx: u8,2347 base_q_idx: u8,
2263 deadzone: f64,2348 deadzone: f64,
2264 set: TxbSet,2349 set: TxbSet,
2350+ ) -> Trial {
2351+ self.code_from_prediction_typed(
2352+ x, y, side, prediction, skip, base_q_idx, deadzone, set, TxType::DctDct,
2353+ )
2354+ }
2355+
2356+ /// [`Self::code_from_prediction`] coding the residual with a NAMED
2357+ /// transform type (lane-txset2): the inter luma sets carry a two-type
2358+ /// alphabet (`TX_SET_INTER_3`, `IDTX`/`DCT_DCT`) the writer already codes
2359+ /// a symbol for, and [`commit_inter_luma`] prices both through this.
2360+ #[allow(clippy::too_many_arguments)]
2361+ fn code_from_prediction_typed(
2362+ &self,
2363+ x: usize,
2364+ y: usize,
2365+ side: usize,
2366+ prediction: &[u8],
2367+ skip: bool,
2368+ base_q_idx: u8,
2369+ deadzone: f64,
2370+ set: TxbSet,
2371+ tx_type: TxType,
2265 ) -> Trial {2372 ) -> Trial {
2266 if skip {2373 if skip {
2267 let sse = self.block_sse(x, y, side, prediction);2374 let sse = self.block_sse(x, y, side, prediction);
@@ -2298,16 +2405,20 @@ impl Plane<'_> {
2298 // lane-rdoq, as in [`Self::trial_typed`].2405 // lane-rdoq, as in [`Self::trial_typed`].
2299 let (levels, rdoq_bits) = if rdoq_on() {2406 let (levels, rdoq_bits) = if rdoq_on() {
2300 let (mut levels, scaled) =2407 let (mut levels, scaled) =
2301- forward_and_quantize_scaled(residual, side, 8, i32::from(base_q_idx), deadzone);2408+ forward_and_quantize_typed_scaled(
2409+ residual, side, 8, i32::from(base_q_idx), deadzone, tx_type,
2410+ );
2302 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, set);2411 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, set);
2303 let bits = crate::tile::rdoq(2412 let bits = crate::tile::rdoq(
2304 &mut levels, &scaled, side, base_q_idx, set, skip_ctx, sign_ctx, rdoq_lambda(),2413 &mut levels, &scaled, side, base_q_idx, set, skip_ctx, sign_ctx, rdoq_lambda(),
2305- TxType::DctDct,2414+ tx_type,
2306 );2415 );
2307 (levels, Some(bits))2416 (levels, Some(bits))
2308 } else {2417 } else {
2309 (2418 (
2310- forward_and_quantize(residual, side, 8, i32::from(base_q_idx), deadzone),2419+ forward_and_quantize_typed(
2420+ residual, side, 8, i32::from(base_q_idx), deadzone, tx_type,
2421+ ),
2311 None,2422 None,
2312 )2423 )
2313 };2424 };
@@ -2320,7 +2431,7 @@ impl Plane<'_> {
2320 i32::from(base_q_idx),2431 i32::from(base_q_idx),
2321 0,2432 0,
2322 0,2433 0,
2323- TxType::DctDct,2434+ tx_type,
2324 );2435 );
2325 #[cfg(test)]2436 #[cfg(test)]
2326 stage_since(2, t);2437 stage_since(2, t);
@@ -2357,12 +2468,13 @@ impl Plane<'_> {
2357 } else {2468 } else {
2358 {2469 {
2359 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, set);2470 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, set);
2360- crate::tile::coeff_bits(2471+ crate::tile::coeff_bits_typed(
2361 &levels,2472 &levels,
2362 set,2473 set,
2363 crate::decode::q_ctx_of(base_q_idx),2474 crate::decode::q_ctx_of(base_q_idx),
2364 skip_ctx,2475 skip_ctx,
2365 sign_ctx,2476 sign_ctx,
2477+ tx_type,
2366 )2478 )
2367 }2479 }
2368 };2480 };
@@ -3673,6 +3785,17 @@ fn tx_depth_bits(side: usize, depth: usize) -> f64 {
3673 }3785 }
3674 }3786 }
3675 3787
3788+/// [`TX_TYPE_HITS`] for the INTER luma units (lane-txset2), counted apart so
3789+/// the intra witness's fire count stays its own.
3790+pub(crate) static INTER_TX_TYPE_HITS: [std::sync::atomic::AtomicUsize; 16] =
3791+ [const { std::sync::atomic::AtomicUsize::new(0) }; 16];
3792+
3793+/// Reads [`INTER_TX_TYPE_HITS`] and zeroes it.
3794+#[cfg(test)]
3795+pub(crate) fn take_inter_tx_type_hits() -> [usize; 16] {
3796+ std::array::from_fn(|t| INTER_TX_TYPE_HITS[t].swap(0, std::sync::atomic::Ordering::Relaxed))
3797+}
3798+
3676 /// How many luma transform units resolved to each [`TxType`], indexed by the3799 /// How many luma transform units resolved to each [`TxType`], indexed by the
3677 /// enum's own discriminant (lane-txset): the fire count a witness asserts on,3800 /// enum's own discriminant (lane-txset): the fire count a witness asserts on,
3678 /// and the instrument that says which types the search actually reaches.3801 /// and the instrument that says which types the search actually reaches.
@@ -3821,7 +3944,52 @@ fn commit_inter_luma(
3821 // `comp_group_idx == 0` average). `None` is the single-reference block.3944 // `comp_group_idx == 0` average). `None` is the single-reference block.
3822 second: Option<((i32, i32), (&[u16], usize, usize, usize))>,3945 second: Option<((i32, i32), (&[u16], usize, usize, usize))>,
3823 fctx: &crate::decode::FrameCtx,3946 fctx: &crate::decode::FrameCtx,
3824-) -> (Vec<i32>, u8, f64) {3947+) -> (Vec<i32>, u8, f64, Vec<TxType>) {
3948+ // lane-txset2 step 1: the whole-block (depth 0) residual picks its own
3949+ // type out of the two-type inter set the writer already codes a symbol
3950+ // for, priced the same way the intra search is (sse + lambda * bits, the
3951+ // bits carrying the `tx_type` symbol itself through RDOQ). A skipped
3952+ // block codes no residual and the 64-point transform names no type.
3953+ let mut flat_typed: Option<Trial> = None;
3954+ let mut flat_type = TxType::DctDct;
3955+ if !skip {
3956+ if let Some(fset) = inter_luma_set(side) {
3957+ let cost = |t: &Trial| t.sse + search.lambda * t.bits;
3958+ for &tx_type in inter_tx_type_candidates(fset, search.screen) {
3959+ if tx_type == TxType::DctDct {
3960+ continue;
3961+ }
3962+ let candidate = match second {
3963+ Some((mv1, ref1)) => mc_trial_compound_typed(
3964+ luma, x, y, side, (mv, mv1), true, reference, ref1, search.base_q_idx,
3965+ search.deadzone, fset, tx_type, fctx,
3966+ ),
3967+ None => mc_trial_typed(
3968+ luma, x, y, side, mv, true, reference.0, reference.1, reference.2,
3969+ reference.3, false, search.base_q_idx, search.deadzone, fset, tx_type,
3970+ fctx,
3971+ ),
3972+ };
3973+ if cost(&candidate) < cost(flat_typed.as_ref().unwrap_or(flat)) {
3974+ flat_type = tx_type;
3975+ flat_typed = Some(candidate);
3976+ }
3977+ }
3978+ }
3979+ }
3980+ // Counted at the return points, so the census names the types the block
3981+ // really CODES -- a split unit's winner that the flat cost then beats was
3982+ // never written (class `counter from refused stream`).
3983+ let count = |types: &[TxType]| {
3984+ for &t in types {
3985+ INTER_TX_TYPE_HITS[t as usize].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3986+ }
3987+ };
3988+ let flat_ref: &Trial = flat_typed.as_ref().unwrap_or(flat);
3989+ // What the caller's already-counted `flat` cost has to be corrected by
3990+ // when a non-`DCT_DCT` type won it, the same way the split delta below is.
3991+ let flat_gain = (flat_ref.sse + search.lambda * flat_ref.bits)
3992+ - (flat.sse + search.lambda * flat.bits);
3825 let eligible = tx_select()3993 let eligible = tx_select()
3826 && tx_select_inter()3994 && tx_select_inter()
3827 && !skip3995 && !skip
@@ -3831,8 +3999,9 @@ fn commit_inter_luma(
3831 && x + side <= luma.true_width3999 && x + side <= luma.true_width
3832 && y + side <= luma.true_height;4000 && y + side <= luma.true_height;
3833 if !eligible {4001 if !eligible {
3834- luma.commit(x, y, side, flat);4002+ luma.commit(x, y, side, flat_ref);
3835- return (flat.levels.clone(), 0, 0.0);4003+ count(&[flat_type]);
4004+ return (flat_ref.levels.clone(), 0, flat_gain, vec![flat_type]);
3836 }4005 }
3837 let tx = side / 2;4006 let tx = side / 2;
3838 let set = if tx >= 32 {4007 let set = if tx >= 32 {
@@ -3850,19 +4019,32 @@ fn commit_inter_luma(
3850 // context is the neighbour magnitude table ([`Plane::coef_ctx`]) -- and4019 // context is the neighbour magnitude table ([`Plane::coef_ctx`]) -- and
3851 // each unit's own commit publishes what the next one reads, coding order.4020 // each unit's own commit publishes what the next one reads, coding order.
3852 luma.ctx.tu_split = true;4021 luma.ctx.tu_split = true;
4022+ // One type per unit in the writer's own raster order (tile.rs
4023+ // `write_luma_tus`), all `DCT_DCT` when nothing else is offered.
4024+ let mut split_types = vec![TxType::DctDct; 4];
3853 for tu_row in 0..2 {4025 for tu_row in 0..2 {
3854 for tu_col in 0..2 {4026 for tu_col in 0..2 {
3855 let (tu_x, tu_y) = (x + tu_col * tx, y + tu_row * tx);4027 let (tu_x, tu_y) = (x + tu_col * tx, y + tu_row * tx);
3856- let trial = match second {4028+ let unit = |tx_type: TxType| match second {
3857- Some((mv1, ref1)) => mc_trial_compound(4029+ Some((mv1, ref1)) => mc_trial_compound_typed(
3858 luma, tu_x, tu_y, tx, (mv, mv1), true, reference, ref1,4030 luma, tu_x, tu_y, tx, (mv, mv1), true, reference, ref1,
3859- search.base_q_idx, search.deadzone, set, fctx,4031+ search.base_q_idx, search.deadzone, set, tx_type, fctx,
3860 ),4032 ),
3861- None => mc_trial(4033+ None => mc_trial_typed(
3862 luma, tu_x, tu_y, tx, mv, true, reference.0, reference.1, reference.2,4034 luma, tu_x, tu_y, tx, mv, true, reference.0, reference.1, reference.2,
3863- reference.3, false, search.base_q_idx, search.deadzone, set, fctx,4035+ reference.3, false, search.base_q_idx, search.deadzone, set, tx_type, fctx,
3864 ),4036 ),
3865 };4037 };
4038+ let mut best: Option<(f64, TxType, Trial)> = None;
4039+ for &tx_type in inter_tx_type_candidates(set, search.screen) {
4040+ let candidate = unit(tx_type);
4041+ let cost = candidate.sse + search.lambda * candidate.bits;
4042+ if best.as_ref().is_none_or(|(b, _, _)| cost < *b) {
4043+ best = Some((cost, tx_type, candidate));
4044+ }
4045+ }
4046+ let (_, tx_type, trial) = best.expect("the candidate list is never empty");
4047+ split_types[tu_row * 2 + tu_col] = tx_type;
3866 sse += trial.sse;4048 sse += trial.sse;
3867 bits += trial.bits;4049 bits += trial.bits;
3868 for row in 0..tx {4050 for row in 0..tx {
@@ -3874,7 +4056,7 @@ fn commit_inter_luma(
3874 }4056 }
3875 luma.ctx.tu_split = false;4057 luma.ctx.tu_split = false;
3876 let split_cost = sse + search.lambda * (bits + txfm_split_bits(side, 1));4058 let split_cost = sse + search.lambda * (bits + txfm_split_bits(side, 1));
3877- let flat_cost = flat.sse + search.lambda * (flat.bits + txfm_split_bits(side, 0));4059+ let flat_cost = flat_ref.sse + search.lambda * (flat_ref.bits + txfm_split_bits(side, 0));
3878 let class = usize::from(side == BLOCK) * 4 + usize::from(second.is_some()) * 2;4060 let class = usize::from(side == BLOCK) * 4 + usize::from(second.is_some()) * 2;
3879 // The depth census has a leaf row and a 32x32 row and no 64 one, so the4061 // The depth census has a leaf row and a 32x32 row and no 64 one, so the
3880 // 64x64 root counts itself ([`take_b64_var_tx_hits`]) instead of landing4062 // 64x64 root counts itself ([`take_b64_var_tx_hits`]) instead of landing
@@ -3887,13 +4069,15 @@ fn commit_inter_luma(
3887 if counted {4069 if counted {
3888 INTER_TX_SPLIT_HITS[class + 1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);4070 INTER_TX_SPLIT_HITS[class + 1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3889 }4071 }
3890- return (levels, 1, split_cost - flat_cost);4072+ count(&split_types);
4073+ return (levels, 1, flat_gain + split_cost - flat_cost, split_types);
3891 }4074 }
3892 if counted {4075 if counted {
3893 INTER_TX_SPLIT_HITS[class].fetch_add(1, std::sync::atomic::Ordering::Relaxed);4076 INTER_TX_SPLIT_HITS[class].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3894 }4077 }
3895- luma.commit(x, y, side, flat);4078+ luma.commit(x, y, side, flat_ref);
3896- (flat.levels.clone(), 0, 0.0)4079+ count(&[flat_type]);
4080+ (flat_ref.levels.clone(), 0, flat_gain, vec![flat_type])
3897 }4081 }
3898 4082
3899 /// The largest distinct-colour count a block may hold and still be offered a4083 /// The largest distinct-colour count a block may hold and still be offered a
@@ -5932,11 +6116,11 @@ fn code_square_inter(
5932 )6116 )
5933 })6117 })
5934 });6118 });
5935- let (levels, tx_depth, dcost) = if motion_won != 06119+ let (levels, tx_depth, dcost, luma_tx_types) = if motion_won != 0
5936 || (info.ref1.is_some() && second.is_none())6120 || (info.ref1.is_some() && second.is_none())
5937 {6121 {
5938 luma.commit(x, y, side, &luma_new);6122 luma.commit(x, y, side, &luma_new);
5939- (luma_new.levels.clone(), 0, 0.0)6123+ (luma_new.levels.clone(), 0, 0.0, Vec::new())
5940 } else {6124 } else {
5941 commit_inter_luma(6125 commit_inter_luma(
5942 luma, (x, y), side, info.mv,6126 luma, (x, y), side, info.mv,
@@ -5962,7 +6146,7 @@ fn code_square_inter(
5962 palette: None,6146 palette: None,
5963 palette_uv: None,6147 palette_uv: None,
5964 tx_depth,6148 tx_depth,
5965- luma_tx_types: Vec::new(),6149+ luma_tx_types,
5966 inter: Some(info),6150 inter: Some(info),
5967 motion_mode: motion_won,6151 motion_mode: motion_won,
5968 },6152 },
@@ -5979,13 +6163,13 @@ fn code_square_inter(
5979 census_add(9, 1);6163 census_add(9, 1);
5980 }6164 }
5981 if inter_cost < intra_cost {6165 if inter_cost < intra_cost {
5982- let (levels, tx_depth, dcost) = commit_inter_luma(6166+ let (levels, tx_depth, dcost, luma_tx_types) = commit_inter_luma(
5983 luma, (x, y), side, mv, (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), search, &luma_trial, skip, None, fctx,6167 luma, (x, y), side, mv, (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), search, &luma_trial, skip, None, fctx,
5984 );6168 );
5985 chroma[0].commit(x / 2, y / 2, side / 2, &u);6169 chroma[0].commit(x / 2, y / 2, side / 2, &u);
5986 chroma[1].commit(x / 2, y / 2, side / 2, &v);6170 chroma[1].commit(x / 2, y / 2, side / 2, &v);
5987 (BlockCoeffs {6171 (BlockCoeffs {
5988- luma_tx_types: Vec::new(),6172+ luma_tx_types,
5989 angle_delta_y: 0,6173 angle_delta_y: 0,
5990 cfl_alphas: None,6174 cfl_alphas: None,
5991 filter_intra: None,6175 filter_intra: None,
@@ -7817,7 +8001,34 @@ fn mc_trial(
7817 skip: bool,8001 skip: bool,
7818 base_q_idx: u8,8002 base_q_idx: u8,
7819 deadzone: f64,8003 deadzone: f64,
7820- set: TxbSet, fctx: &crate::decode::FrameCtx,8004+ set: TxbSet,
8005+ fctx: &crate::decode::FrameCtx,
8006+) -> Trial {
8007+ mc_trial_typed(
8008+ plane, x, y, side, mv, luma, reference, stride, ref_width, ref_height, skip, base_q_idx,
8009+ deadzone, set, TxType::DctDct, fctx,
8010+ )
8011+}
8012+
8013+/// [`mc_trial`] coding its residual with a named transform type (lane-txset2).
8014+#[allow(clippy::too_many_arguments)]
8015+fn mc_trial_typed(
8016+ plane: &Plane,
8017+ x: usize,
8018+ y: usize,
8019+ side: usize,
8020+ mv: (i32, i32),
8021+ luma: bool,
8022+ reference: &[u16],
8023+ stride: usize,
8024+ ref_width: usize,
8025+ ref_height: usize,
8026+ skip: bool,
8027+ base_q_idx: u8,
8028+ deadzone: f64,
8029+ set: TxbSet,
8030+ tx_type: TxType,
8031+ fctx: &crate::decode::FrameCtx,
7821 ) -> Trial {8032 ) -> Trial {
7822 let x_q4 = mv_to_q4(x, mv.1, luma);8033 let x_q4 = mv_to_q4(x, mv.1, luma);
7823 let y_q4 = mv_to_q4(y, mv.0, luma);8034 let y_q4 = mv_to_q4(y, mv.0, luma);
@@ -7846,7 +8057,9 @@ fn mc_trial(
7846 for (dst, &src) in prediction.iter_mut().zip(prediction16.iter()) {8057 for (dst, &src) in prediction.iter_mut().zip(prediction16.iter()) {
7847 *dst = src as u8;8058 *dst = src as u8;
7848 }8059 }
7849- plane.code_from_prediction(x, y, side, prediction, skip, base_q_idx, deadzone, set)8060+ plane.code_from_prediction_typed(
8061+ x, y, side, prediction, skip, base_q_idx, deadzone, set, tx_type,
8062+ )
7850 }8063 }
7851 8064
7852 /// [`mc_trial`]'s compound counterpart (spec 7.11.3.1's compound path): both8065 /// [`mc_trial`]'s compound counterpart (spec 7.11.3.1's compound path): both
@@ -7857,6 +8070,28 @@ fn mc_trial(
7857 /// block, so the encoder's reconstruction is the decoder's.8070 /// block, so the encoder's reconstruction is the decoder's.
7858 #[allow(clippy::too_many_arguments)]8071 #[allow(clippy::too_many_arguments)]
7859 fn mc_trial_compound(8072 fn mc_trial_compound(
8073+ plane: &Plane,
8074+ x: usize,
8075+ y: usize,
8076+ side: usize,
8077+ mvs: ((i32, i32), (i32, i32)),
8078+ luma: bool,
8079+ ref0: (&[u16], usize, usize, usize),
8080+ ref1: (&[u16], usize, usize, usize),
8081+ base_q_idx: u8,
8082+ deadzone: f64,
8083+ set: TxbSet,
8084+ fctx: &crate::decode::FrameCtx,
8085+) -> Trial {
8086+ mc_trial_compound_typed(
8087+ plane, x, y, side, mvs, luma, ref0, ref1, base_q_idx, deadzone, set, TxType::DctDct, fctx,
8088+ )
8089+}
8090+
8091+/// [`mc_trial_compound`] coding its residual with a named transform type
8092+/// (lane-txset2).
8093+#[allow(clippy::too_many_arguments)]
8094+fn mc_trial_compound_typed(
7860 plane: &Plane,8095 plane: &Plane,
7861 x: usize,8096 x: usize,
7862 y: usize,8097 y: usize,
@@ -7867,7 +8102,9 @@ fn mc_trial_compound(
7867 ref1: (&[u16], usize, usize, usize),8102 ref1: (&[u16], usize, usize, usize),
7868 base_q_idx: u8,8103 base_q_idx: u8,
7869 deadzone: f64,8104 deadzone: f64,
7870- set: TxbSet, fctx: &crate::decode::FrameCtx,8105+ set: TxbSet,
8106+ tx_type: TxType,
8107+ fctx: &crate::decode::FrameCtx,
7871 ) -> Trial {8108 ) -> Trial {
7872 let mut inter0 = [0i32; BLOCK * BLOCK];8109 let mut inter0 = [0i32; BLOCK * BLOCK];
7873 let mut inter1 = [0i32; BLOCK * BLOCK];8110 let mut inter1 = [0i32; BLOCK * BLOCK];
@@ -7896,7 +8133,9 @@ fn mc_trial_compound(
7896 for (dst, &src) in prediction.iter_mut().zip(blended16.iter()) {8133 for (dst, &src) in prediction.iter_mut().zip(blended16.iter()) {
7897 *dst = src as u8;8134 *dst = src as u8;
7898 }8135 }
7899- plane.code_from_prediction(x, y, side, prediction, false, base_q_idx, deadzone, set)8136+ plane.code_from_prediction_typed(
8137+ x, y, side, prediction, false, base_q_idx, deadzone, set, tx_type,
8138+ )
7900 }8139 }
7901 8140
7902 /// Codes one 32x32 block of an inter frame as whichever costs least of: each8141 /// Codes one 32x32 block of an inter frame as whichever costs least of: each
@@ -8262,7 +8501,7 @@ fn search_skip_64(
8262 // The residual arm's luma levels and the `txfm_split` depth the writer8501 // The residual arm's luma levels and the `txfm_split` depth the writer
8263 // codes: depth 0 is the TX_64X64 corner in 32x32 coordinates, depth 1 is8502 // codes: depth 0 is the TX_64X64 corner in 32x32 coordinates, depth 1 is
8264 // four TX_32X32 units in 64x64 ones.8503 // four TX_32X32 units in 64x64 ones.
8265- let mut luma_levels: Option<(Vec<i32>, u8)> = None;8504+ let mut luma_levels: Option<(Vec<i32>, u8, Vec<TxType>)> = None;
8266 if residual {8505 if residual {
8267 let sets = [TxbSet::Luma64, TxbSet::Chroma32, TxbSet::Chroma32];8506 let sets = [TxbSet::Luma64, TxbSet::Chroma32, TxbSet::Chroma32];
8268 let residual_trials = [0usize, 1, 2].map(|plane| {8507 let residual_trials = [0usize, 1, 2].map(|plane| {
@@ -8288,7 +8527,7 @@ fn search_skip_64(
8288 // four TX_32X32 units of `txfm_split = 1`, taken by the same8527 // four TX_32X32 units of `txfm_split = 1`, taken by the same
8289 // `commit_inter_luma` every other inter block's is (it commits the8528 // `commit_inter_luma` every other inter block's is (it commits the
8290 // winner and hands back the cost it took off the flat arm).8529 // winner and hands back the cost it took off the flat arm).
8291- let (levels, depth, gain) = if b64_var_tx() {8530+ let (levels, depth, gain, tx_types) = if b64_var_tx() {
8292 let second = info.ref1.and_then(|r1| {8531 let second = info.ref1.and_then(|r1| {
8293 compound.iter().find(|(r, _, _)| *r == r1).map(|&(_, g, _)| {8532 compound.iter().find(|(r, _, _)| *r == r1).map(|&(_, g, _)| {
8294 (8533 (
@@ -8311,7 +8550,7 @@ fn search_skip_64(
8311 fctx,8550 fctx,
8312 )8551 )
8313 } else {8552 } else {
8314- (residual_trials[0].levels.clone(), 0, 0.0)8553+ (residual_trials[0].levels.clone(), 0, 0.0, Vec::new())
8315 };8554 };
8316 let cost = residual_trials.iter().map(|t| t.sse).sum::<f64>()8555 let cost = residual_trials.iter().map(|t| t.sse).sum::<f64>()
8317 + search.lambda * (syntax + unskip + coeff_bits)8556 + search.lambda * (syntax + unskip + coeff_bits)
@@ -8321,7 +8560,7 @@ fn search_skip_64(
8321 if depth == 1 {8560 if depth == 1 {
8322 B64_VAR_TX_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);8561 B64_VAR_TX_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8323 }8562 }
8324- luma_levels = Some((levels, depth));8563+ luma_levels = Some((levels, depth, tx_types));
8325 chosen = (cost, false, residual_trials);8564 chosen = (cost, false, residual_trials);
8326 }8565 }
8327 }8566 }
@@ -8342,11 +8581,15 @@ fn search_skip_64(
8342 // The chroma grids are whole TX_32X32; the luma one is the8581 // The chroma grids are whole TX_32X32; the luma one is the
8343 // 64-point transform's coded 32x32 corner at depth 0 and the8582 // 64-point transform's coded 32x32 corner at depth 0 and the
8344 // whole 64-sided block at depth 1 (lane-b64b).8583 // whole 64-sided block at depth 1 (lane-b64b).
8345- tx_depth: luma_levels.as_ref().map_or(0, |&(_, d)| d),8584+ tx_depth: luma_levels.as_ref().map_or(0, |(_, d, _)| *d),
8585+ luma_tx_types: match (skip, &luma_levels) {
8586+ (false, Some((_, _, types))) => types.clone(),
8587+ _ => Vec::new(),
8588+ },
8346 luma: match (skip, &luma_levels) {8589 luma: match (skip, &luma_levels) {
8347 (true, _) => Vec::new(),8590 (true, _) => Vec::new(),
8348- (false, Some((levels, 1))) => coeffs(levels, SUPERBLOCK),8591+ (false, Some((levels, 1, _))) => coeffs(levels, SUPERBLOCK),
8349- (false, Some((levels, _))) => coeffs(levels, BLOCK),8592+ (false, Some((levels, _, _))) => coeffs(levels, BLOCK),
8350 (false, None) => coeffs(&trials[0].levels, BLOCK),8593 (false, None) => coeffs(&trials[0].levels, BLOCK),
8351 },8594 },
8352 u: if skip { Vec::new() } else { coeffs(&trials[1].levels, side / 2) },8595 u: if skip { Vec::new() } else { coeffs(&trials[1].levels, side / 2) },
@@ -9200,7 +9443,7 @@ fn search_inter_block(
9200 // compound winner the same offer behind `EC_AV1_COMP_VARTX`. An OBMC/warp9443 // compound winner the same offer behind `EC_AV1_COMP_VARTX`. An OBMC/warp
9201 // winner still commits flat: `commit_inter_luma` re-predicts each unit by9444 // winner still commits flat: `commit_inter_luma` re-predicts each unit by
9202 // plain translation, which is not the prediction it was priced from.9445 // plain translation, which is not the prediction it was priced from.
9203- let (levels, tx_depth, dcost) = match best.inter.filter(|_| motion_won == 0) {9446+ let (levels, tx_depth, dcost, luma_tx_types) = match best.inter.filter(|_| motion_won == 0) {
9204 Some(info) => {9447 Some(info) => {
9205 let own = match extra.iter().find(|(r, _, _)| *r == info.ref_frame) {9448 let own = match extra.iter().find(|(r, _, _)| *r == info.ref_frame) {
9206 Some(&(_, g, _)) => (g.y.as_slice(), g.width, luma.true_width, luma.true_height),9449 Some(&(_, g, _)) => (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
@@ -9217,7 +9460,7 @@ fn search_inter_block(
9217 match info.ref1.is_some() && second.is_none() {9460 match info.ref1.is_some() && second.is_none() {
9218 true => {9461 true => {
9219 luma.commit(x, y, BLOCK, &best.luma);9462 luma.commit(x, y, BLOCK, &best.luma);
9220- (best.luma.levels.clone(), 0, 0.0)9463+ (best.luma.levels.clone(), 0, 0.0, Vec::new())
9221 }9464 }
9222 false => commit_inter_luma(9465 false => commit_inter_luma(
9223 luma, (x, y), BLOCK, info.mv, own, search, &best.luma, best.skip, second,9466 luma, (x, y), BLOCK, info.mv, own, search, &best.luma, best.skip, second,
@@ -9227,14 +9470,14 @@ fn search_inter_block(
9227 }9470 }
9228 None => {9471 None => {
9229 luma.commit(x, y, BLOCK, &best.luma);9472 luma.commit(x, y, BLOCK, &best.luma);
9230- (best.luma.levels.clone(), 0, 0.0)9473+ (best.luma.levels.clone(), 0, 0.0, Vec::new())
9231 }9474 }
9232 };9475 };
9233 chroma[0].commit(x / 2, y / 2, BLOCK / 2, &best.u);9476 chroma[0].commit(x / 2, y / 2, BLOCK / 2, &best.u);
9234 chroma[1].commit(x / 2, y / 2, BLOCK / 2, &best.v);9477 chroma[1].commit(x / 2, y / 2, BLOCK / 2, &best.v);
9235 (9478 (
9236 BlockCoeffs {9479 BlockCoeffs {
9237- luma_tx_types: Vec::new(),9480+ luma_tx_types,
9238 angle_delta_y: 0,9481 angle_delta_y: 0,
9239 cfl_alphas: None,9482 cfl_alphas: None,
9240 filter_intra: None,9483 filter_intra: None,
crates/ec-av1/src/encoder.rsmodified+84 -0
@@ -3727,6 +3727,90 @@ mod tests {
3727 eprintln!("tx_type witness: hits {hits:?}, {} bytes", stream.len());3727 eprintln!("tx_type witness: hits {hits:?}, {} bytes", stream.len());
3728 }3728 }
3729 3729
3730+ /// lane-txset2's witness: an INTER frame's luma transform units take BOTH
3731+ /// types of the two-type inter set the writer already codes a symbol for
3732+ /// (`TX_SET_INTER_3`: `IDTX` and `DCT_DCT`) at least once -- the fire
3733+ /// count, class `gate-blind-to-feature` -- and both decoders reconstruct
3734+ /// every frame sample-exact from the `tx_type` symbols that name them.
3735+ /// Before this lane every inter luma unit was coded `DCT_DCT`.
3736+ #[test]
3737+ fn an_inter_clip_codes_both_inter_set_tx_types_both_decoders_read_exactly() {
3738+ // The lever is OFF at every preset (`speed::TX_TYPE_SEARCH_INTER`), so
3739+ // this turns it on process-globally under the same exclusive lock the
3740+ // presets take.
3741+ let _knobs = crate::speed::knob_write();
3742+ let _gate_lock = crate::stream::tests::lock_gate_counters();
3743+ crate::encode::set_inter_tx_search(Some(true));
3744+ let (width, height) = (320usize, 192usize);
3745+ // Sharp steps that MOVE: the motion-compensated residual along a
3746+ // moving edge is exactly where the identity transform beats a DCT,
3747+ // and the flat plateaus between them predict to nothing at all.
3748+ let sources: Vec<Picture> = (0..4)
3749+ .map(|t| {
3750+ let mut p = test_card(width, height, t * 3);
3751+ for y in 0..height {
3752+ for x in 0..width {
3753+ let v = match ((x + t * 5) / 16 % 2, (y + t * 3) / 16 % 2) {
3754+ (0, 0) => 16u16,
3755+ (1, 0) => 235,
3756+ (0, 1) => ((x + t) % 64 * 3) as u16,
3757+ _ => ((y + t) % 64 * 3) as u16,
3758+ };
3759+ p.y[y * width + x] = v;
3760+ }
3761+ }
3762+ p
3763+ })
3764+ .collect();
3765+ let config = EncoderConfig {
3766+ width,
3767+ height,
3768+ base_q_idx: 90,
3769+ gop: 4,
3770+ colour: Colour::Bt709Limited,
3771+ tile_cols_log2: 0,
3772+ tile_rows_log2: 0,
3773+ };
3774+ let mut enc = Av1Encoder::new(config).unwrap();
3775+ let _ = crate::encode::take_inter_tx_type_hits();
3776+ let mut stream = Vec::new();
3777+ for packet in encode_all(&mut enc, &sources) {
3778+ stream.extend_from_slice(&packet.data);
3779+ }
3780+ let hits = crate::encode::take_inter_tx_type_hits();
3781+ crate::encode::set_inter_tx_search(None);
3782+ for (name, ty) in [
3783+ ("DCT_DCT", crate::transform::TxType::DctDct),
3784+ ("IDTX", crate::transform::TxType::Idtx),
3785+ ] {
3786+ assert!(
3787+ hits[ty as usize] > 0,
3788+ "no inter luma transform unit was CODED {name}: {hits:?}"
3789+ );
3790+ }
3791+ let ours = crate::stream::decode_stream(&stream).expect("our decoder");
3792+ assert_eq!(ours.len(), sources.len(), "our decoder's frames");
3793+ if have_ffmpeg() {
3794+ let theirs = ffmpeg_decode_luma(&stream, width, height);
3795+ assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
3796+ for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
3797+ let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
3798+ if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
3799+ panic!(
3800+ "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
3801+ at % width,
3802+ at / width,
3803+ got[at],
3804+ b[at],
3805+ );
3806+ }
3807+ }
3808+ } else {
3809+ eprintln!("SKIP the ffmpeg half: no ffmpeg");
3810+ }
3811+ eprintln!("inter tx_type witness: hits {hits:?}, {} bytes", stream.len());
3812+ }
3813+
3730 /// Every SHIPPED SPEED PRESET codes a stream both decoders reconstruct3814 /// Every SHIPPED SPEED PRESET codes a stream both decoders reconstruct
3731 /// sample-exact -- ours and ffmpeg's -- and codes a DIFFERENT stream from3815 /// sample-exact -- ours and ffmpeg's -- and codes a DIFFERENT stream from
3732 /// its neighbour (a preset that changes no byte is a preset that buys no3816 /// its neighbour (a preset that changes no byte is a preset that buys no
crates/ec-av1/src/speed.rsmodified+6 -0
@@ -491,6 +491,12 @@ pub(crate) const TX_TYPE_SEARCH: [bool; 11] = [
491 true, true, true, true, true, true, true, false, false, false, false,491 true, true, true, true, true, true, true, false, false, false, false,
492 ];492 ];
493 493
494+/// `tx_type_candidates`: whether an INTER luma transform unit searches the
495+/// two-type `TX_SET_INTER_3` (`IDTX` vs `DCT_DCT`) the writer already codes a
496+/// symbol for, instead of always coding `DCT_DCT` (lane-txset2). Off at every
497+/// preset until the gate says otherwise; `EC_AV1_TXSET_INTER` overrides.
498+pub(crate) const TX_TYPE_SEARCH_INTER: [bool; 11] = [false; 11];
499+
494 /// `filter_search`: whether the deblock ladder's +-1/+-2 refinement stage runs.500 /// `filter_search`: whether the deblock ladder's +-1/+-2 refinement stage runs.
495 pub(crate) const DEBLOCK_REFINE: [bool; 11] = [501 pub(crate) const DEBLOCK_REFINE: [bool; 11] = [
496 true, true, true, true, true, true, true, false, false, false, false,502 true, true, true, true, true, true, true, false, false, false, false,
crates/ec-av1/src/tile.rsmodified+4 -1
@@ -4724,6 +4724,9 @@ fn scan_of(side: usize) -> &'static Vec<u16> {
4724 }4724 }
4725 }4725 }
4726 4726
4727+/// [`coeff_bits_typed`] at `DCT_DCT`, the only type the test-only pricers
4728+/// ([`predicted_coeff_bits`]) model.
4729+#[cfg(test)]
4727 pub(crate) fn coeff_bits(4730 pub(crate) fn coeff_bits(
4728 grid: &[i32],4731 grid: &[i32],
4729 set: TxbSet,4732 set: TxbSet,
@@ -4734,7 +4737,7 @@ pub(crate) fn coeff_bits(
4734 coeff_bits_typed(grid, set, q_ctx, skip_ctx, sign_ctx, TxType::DctDct)4737 coeff_bits_typed(grid, set, q_ctx, skip_ctx, sign_ctx, TxType::DctDct)
4735 }4738 }
4736 4739
4737-/// [`coeff_bits`] for levels a named transform type produced: the `tx_type`4740+/// What levels a named transform type produced cost: the `tx_type`
4738 /// symbol is part of what the block spends, so a search comparing types has4741 /// 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).4742 /// to see each one's own symbol priced (lane-txset).
4740 pub(crate) fn coeff_bits_typed(4743 pub(crate) fn coeff_bits_typed(
lanes/txset2.report.mdadded+32 -0
@@ -0,0 +1,32 @@
1+# lane-txset2 -- the inter transform-type search, and reduced_tx_set=0
2+
3+Branch `lane-txset2` off main `5e923074`. Predecessor: `lanes/txset.report.md`
4+(intra 5-type reduced set, screen-gated).
5+
6+## Step 1 -- inter luma IDTX vs DCT_DCT (`TX_SET_INTER_3`)
7+
8+The writer already codes a two-symbol `tx_type` for every inter luma unit at
9+32x32 and below (`TxbSet::Luma{4,8,16,32}Inter`) and always named `DCT_DCT`.
10+
11+* `encode::inter_tx_type_candidates(set, screen)` -- `[DCT_DCT, IDTX]` for
12+ those four sets, `[DCT_DCT]` for the 64-point transform (no symbol) and for
13+ chroma.
14+* `Plane::code_from_prediction_typed` / `mc_trial_typed` /
15+ `mc_trial_compound_typed`: the untyped entries are now `DCT_DCT` wrappers,
16+ so no call site outside the search moved.
17+* `commit_inter_luma` prices the candidates twice: once for the whole-block
18+ (depth 0) residual, once per var-tx split unit, both by `sse + lambda *
19+ bits` with the bits carrying the `tx_type` symbol through RDOQ -- the same
20+ rule the intra search uses. The chosen types leave through the new fourth
21+ element of its return and reach the writer as `BlockCoeffs::luma_tx_types`
22+ (flat = one entry, split = four in the writer's raster order).
23+* Levers: `speed::TX_TYPE_SEARCH_INTER` (OFF at every preset until the gate
24+ says otherwise), `EC_AV1_TXSET_INTER=0|screen|1`, plus a test-only
25+ process-global override (`encode::set_inter_tx_search`).
26+* Census: `encode::INTER_TX_TYPE_HITS`, counted at the COMMIT points only, so
27+ a split unit's winner the flat cost then beats is not counted.
28+
29+Witness: `encoder::tests::an_inter_clip_codes_both_inter_set_tx_types_both_decoders_read_exactly`
30+-- PASS, hits `[DCT_DCT 154 .., IDTX 1368 ..]`, ours == ffmpeg every sample.
31+
32+Gate rows: see below (arms running).