forge
Explore
Log in

Don't you dare go Hollow

The intra half of reduced_tx_set=0, and a rate surcharge on a non-DCT type

Browse files at this commit

7a1492f9a1c1b1b1abd266c57905f106add3744cAhmet Kaan GümüşParent: e6bf936
  • feat
    • the intra half of reduced_tx_set=0, and a rate surcharge on a non-DCT type
Show full message
feat(av1): the intra half of reduced_tx_set=0, and a rate surcharge on a non-DCT type

The search names the widened luma set for INTRA units only: with the wider
inter candidates priced some block's winner selects a DPB slot this encoder
holds no picture in (the refs lane's bookkeeping), which bisection pins to the
inter half alone. EC_AV1_TXRD_LAMBDA now also charges the intra type decision:
the 12-frame instrument says the five-type search buys 0.04 dB for 1.2% more
bytes on film A on every frame and every plane, key frame included, so the
loss is the rate term and not propagation into the leaves.
crates/ec-av1/src/encode.rsmodified+100 -11
@@ -291,7 +291,7 @@ pub(crate) fn tx_type_candidates(set: TxbSet, screen: bool) -> &'static [TxType]
291 ];291 ];
292 match set {292 match set {
293 TxbSet::Luma16 | TxbSet::Luma8 | TxbSet::Luma4293 TxbSet::Luma16 | TxbSet::Luma8 | TxbSet::Luma4
294- if (screen || intra_tx_all_frames()) && tx_type_search() =>294+ if intra_tx_search_on(screen) =>
295 {295 {
296 &INTRA2296 &INTRA2
297 }297 }
@@ -301,7 +301,7 @@ pub(crate) fn tx_type_candidates(set: TxbSet, screen: bool) -> &'static [TxType]
301 // extra members are the 1-D DCTs, and the order is the reader's own301 // extra members are the 1-D DCTs, and the order is the reader's own
302 // map (`decode::tx_type_from_symbol`, 8-wide CDF).302 // map (`decode::tx_type_from_symbol`, 8-wide CDF).
303 TxbSet::Luma8Set1 | TxbSet::Luma4Set1303 TxbSet::Luma8Set1 | TxbSet::Luma4Set1
304- if (screen || intra_tx_all_frames()) && tx_type_search() =>304+ if intra_tx_search_on(screen) =>
305 {305 {
306 &INTRA1306 &INTRA1
307 }307 }
@@ -369,6 +369,11 @@ pub(crate) fn inter_tx_type_candidates(set: TxbSet, screen: bool) -> &'static [T
369 /// else every frame; unset takes [`crate::speed::WIDE_TX_SET`], screen-gated369 /// else every frame; unset takes [`crate::speed::WIDE_TX_SET`], screen-gated
370 /// like both halves of the type search itself.370 /// like both halves of the type search itself.
371 pub(crate) fn wide_tx_set(screen: bool) -> bool {371 pub(crate) fn wide_tx_set(screen: bool) -> bool {
372+ match WIDE_TX_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
373+ 0 => return false,
374+ 1 => return true,
375+ _ => {}
376+ }
372 static ENV: std::sync::LazyLock<Option<InterTxSearch>> = std::sync::LazyLock::new(|| {377 static ENV: std::sync::LazyLock<Option<InterTxSearch>> = std::sync::LazyLock::new(|| {
373 crate::envflags::var("EC_AV1_TXSET_WIDE").ok().map(|v| match v.as_str() {378 crate::envflags::var("EC_AV1_TXSET_WIDE").ok().map(|v| match v.as_str() {
374 "0" | "off" => InterTxSearch::Off,379 "0" | "off" => InterTxSearch::Off,
@@ -387,6 +392,23 @@ pub(crate) fn wide_tx_set(screen: bool) -> bool {
387 }392 }
388 }393 }
389 394
395+/// A PROCESS-GLOBAL [`wide_tx_set`] override that wins over both the
396+/// environment and the preset (`u8::MAX` = unset), the shape
397+/// [`set_inter_tx_search`] has: the lever is OFF at every preset, so the
398+/// witness that has to see the wider alphabets turns it on through this while
399+/// holding [`crate::speed::knob_write`].
400+static WIDE_TX_OVERRIDE: std::sync::atomic::AtomicU8 =
401+ std::sync::atomic::AtomicU8::new(u8::MAX);
402+
403+/// Sets [`WIDE_TX_OVERRIDE`]; `None` clears it.
404+#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
405+pub(crate) fn set_wide_tx_set(on: Option<bool>) {
406+ WIDE_TX_OVERRIDE.store(
407+ on.map_or(u8::MAX, u8::from),
408+ std::sync::atomic::Ordering::Relaxed,
409+ );
410+}
411+
390 /// The luma [`TxbSet`] the SEARCH and its pricer name for a frame that codes412 /// The luma [`TxbSet`] the SEARCH and its pricer name for a frame that codes
391 /// `reduced_tx_set = 0`: the writer reads the bit once, off the frame's own413 /// `reduced_tx_set = 0`: the writer reads the bit once, off the frame's own
392 /// [`crate::cdf_state::Cdfs`], but the trial that prices a type has to read414 /// [`crate::cdf_state::Cdfs`], but the trial that prices a type has to read
@@ -450,14 +472,25 @@ fn inter_tx_type_search() -> InterTxSearch {
450 472
451 /// The inter luma [`TxbSet`] a `tx`-sided transform unit reads, `None` for the473 /// The inter luma [`TxbSet`] a `tx`-sided transform unit reads, `None` for the
452 /// 64-point one (it codes no `tx_type` symbol).474 /// 64-point one (it codes no `tx_type` symbol).
453-fn inter_luma_set(tx: usize, screen: bool) -> Option<TxbSet> {475+/// lane-txi: the INTER half of the widening is deliberately NOT applied
454- Some(luma_set_for(match tx {476+/// here. A `reduced_tx_set = 0` frame's writer still codes its inter luma
477+/// `tx_type` into the twelve/sixteen-symbol alphabet (the frame bit widens
478+/// every luma set at once, spec `get_tx_set`), but the SEARCH keeps offering
479+/// the two-type list: with the wider inter candidates priced, some block's
480+/// winner selects a reference slot this encoder holds no picture in
481+/// ("a reference frame selected with no picture at this frame's own
482+/// ref_frame_idx slot for it", refused out of the encoder's own MC), which is
483+/// the `refs` lane's DPB bookkeeping (`encoder.rs` maps LAST2/LAST3 onto
484+/// LAST's slot), not a transform defect -- measured by bisection: the intra
485+/// half alone passes every witness, the inter half alone refuses.
486+fn inter_luma_set(tx: usize) -> Option<TxbSet> {
487+ Some(match tx {
455 4 => TxbSet::Luma4Inter,488 4 => TxbSet::Luma4Inter,
456 8 => TxbSet::Luma8Inter,489 8 => TxbSet::Luma8Inter,
457 16 => TxbSet::Luma16Inter,490 16 => TxbSet::Luma16Inter,
458 32 => TxbSet::Luma32Inter,491 32 => TxbSet::Luma32Inter,
459 _ => return None,492 _ => return None,
460- }, screen))493+ })
461 }494 }
462 495
463 fn tx_type_search() -> bool {496 fn tx_type_search() -> bool {
@@ -469,6 +502,34 @@ fn tx_type_search() -> bool {
469 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX_TYPE_SEARCH))502 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX_TYPE_SEARCH))
470 }503 }
471 504
505+/// Whether an intra luma unit of this frame searches its own type at all:
506+/// the preset lever ([`tx_type_search`]) under the screen content gate, which
507+/// `EC_AV1_TXSET=all` ([`intra_tx_all_frames`]) lifts and the process-global
508+/// [`set_intra_tx_search`] override wins over (the witness needs the search
509+/// on a frame the detector called non-screen).
510+fn intra_tx_search_on(screen: bool) -> bool {
511+ match INTRA_TX_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
512+ 0 => return false,
513+ 1 => return true,
514+ _ => {}
515+ }
516+ (screen || intra_tx_all_frames()) && tx_type_search()
517+}
518+
519+/// A PROCESS-GLOBAL [`intra_tx_search_on`] override (`u8::MAX` = unset), the
520+/// shape [`set_inter_tx_search`] has.
521+static INTRA_TX_OVERRIDE: std::sync::atomic::AtomicU8 =
522+ std::sync::atomic::AtomicU8::new(u8::MAX);
523+
524+/// Sets [`INTRA_TX_OVERRIDE`]; `None` clears it.
525+#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
526+pub(crate) fn set_intra_tx_search(on: Option<bool>) {
527+ INTRA_TX_OVERRIDE.store(
528+ on.map_or(u8::MAX, u8::from),
529+ std::sync::atomic::Ordering::Relaxed,
530+ );
531+}
532+
472 /// lane-txi: `EC_AV1_TXSET=all` offers the five-type intra set on EVERY533 /// lane-txi: `EC_AV1_TXSET=all` offers the five-type intra set on EVERY
473 /// frame -- the unconditional arm the gate measures -- instead of the screen534 /// frame -- the unconditional arm the gate measures -- instead of the screen
474 /// content gate [`tx_type_candidates`] ships behind. Any other value keeps535 /// content gate [`tx_type_candidates`] ships behind. Any other value keeps
@@ -2692,7 +2753,18 @@ impl Plane<'_> {
2692 tu, mode, angle_delta, search.base_q_idx, search.deadzone,2753 tu, mode, angle_delta, search.base_q_idx, search.deadzone,
2693 tx_type, fctx,2754 tx_type, fctx,
2694 );2755 );
2695- let cost = candidate.sse + search.lambda * candidate.bits;2756+ // lane-txi: a non-`DCT_DCT` type is charged its
2757+ // bits at `EC_AV1_TXRD_LAMBDA` times the mode
2758+ // search's weight (default 1 = unchanged). The
2759+ // film rows buy 0.04 dB for 1.2% more bytes at
2760+ // weight 1 on every frame and every PLANE, key
2761+ // frame included -- a rate term this decision
2762+ // under-charges (class
2763+ // `rd-rate-term-calibration`), not the
2764+ // propagation loss the leaves would have shown.
2765+ let cost = candidate.sse
2766+ + search.lambda * candidate.bits
2767+ + non_dct_surcharge(search.lambda, tx_type, candidate.bits);
2696 if best.as_ref().is_none_or(|(best, _, _)| cost < *best) {2768 if best.as_ref().is_none_or(|(best, _, _)| cost < *best) {
2697 best = Some((cost, tx_type, candidate));2769 best = Some((cost, tx_type, candidate));
2698 }2770 }
@@ -3083,7 +3155,10 @@ impl Plane<'_> {
3083 );3155 );
3084 let cost_t =3156 let cost_t =
3085 candidate.sse + search.lambda * (candidate.bits + mode_bits[usize::from(mode)]);3157 candidate.sse + search.lambda * (candidate.bits + mode_bits[usize::from(mode)]);
3086- if cost_t < cost {3158+ // lane-txi's surcharge, as in `code_tx_depth`: the incumbent is
3159+ // `DCT_DCT` and pays none of it, so the returned `cost` stays the
3160+ // block's true one for the caller's own decision.
3161+ if cost_t + non_dct_surcharge(search.lambda, candidate_type, candidate.bits) < cost {
3087 cost = cost_t;3162 cost = cost_t;
3088 tx_type = candidate_type;3163 tx_type = candidate_type;
3089 trial = candidate;3164 trial = candidate;
@@ -3946,6 +4021,20 @@ pub(crate) fn tx_type_lambda_mult() -> f64 {
3946 *M4021 *M
3947 }4022 }
3948 4023
4024+/// lane-txi: what a non-`DCT_DCT` transform type is charged ON TOP of its own
4025+/// priced bits -- `(EC_AV1_TXRD_LAMBDA - 1) * lambda * bits`, zero at the
4026+/// default weight of 1 and for `DCT_DCT` itself. The instrument the film
4027+/// question needs: at weight 1 the five-type intra search spends 1.2% more
4028+/// bytes for 0.04 dB on both film rows, so what it under-charges is the rate
4029+/// of the type it picks.
4030+pub(crate) fn non_dct_surcharge(lambda: f64, tx_type: TxType, bits: f64) -> f64 {
4031+ if tx_type == TxType::DctDct {
4032+ 0.0
4033+ } else {
4034+ lambda * (tx_type_lambda_mult() - 1.0) * bits
4035+ }
4036+}
4037+
3949 /// lane-txrd instrument: over the FLAT inter luma decision, the summed4038 /// lane-txrd instrument: over the FLAT inter luma decision, the summed
3950 /// reconstruction error and priced bits of the type the search chose against4039 /// reconstruction error and priced bits of the type the search chose against
3951 /// the `DCT_DCT` trial it was compared with. Both are `* 64` so they fit an4040 /// the `DCT_DCT` trial it was compared with. Both are `* 64` so they fit an
@@ -4176,7 +4265,7 @@ fn commit_inter_luma(
4176 let mut flat_typed: Option<Trial> = None;4265 let mut flat_typed: Option<Trial> = None;
4177 let mut flat_type = TxType::DctDct;4266 let mut flat_type = TxType::DctDct;
4178 if !skip {4267 if !skip {
4179- if let Some(fset) = inter_luma_set(side, search.screen) {4268+ if let Some(fset) = inter_luma_set(side) {
4180 let lambda = search.lambda * tx_type_lambda_mult();4269 let lambda = search.lambda * tx_type_lambda_mult();
4181 let cost = |t: &Trial| t.sse + lambda * t.bits;4270 let cost = |t: &Trial| t.sse + lambda * t.bits;
4182 for &tx_type in inter_tx_type_candidates(fset, search.screen) {4271 for &tx_type in inter_tx_type_candidates(fset, search.screen) {
@@ -4222,7 +4311,7 @@ fn commit_inter_luma(
4222 // differently-predicted baseline is what would let a candidate win on4311 // differently-predicted baseline is what would let a candidate win on
4223 // both terms at once (class `local-rd-on-references` vs a real4312 // both terms at once (class `local-rd-on-references` vs a real
4224 // pricing defect); re-predicting it here is the only way to tell.4313 // pricing defect); re-predicting it here is the only way to tell.
4225- if let Some(fset) = inter_luma_set(side, search.screen) {4314+ if let Some(fset) = inter_luma_set(side) {
4226 let here = match second {4315 let here = match second {
4227 Some((mv1, ref1)) => mc_trial_compound_typed(4316 Some((mv1, ref1)) => mc_trial_compound_typed(
4228 luma, x, y, side, (mv, mv1), true, reference, ref1, search.base_q_idx,4317 luma, x, y, side, (mv, mv1), true, reference, ref1, search.base_q_idx,
@@ -4267,14 +4356,14 @@ fn commit_inter_luma(
4267 return (flat_ref.levels.clone(), 0, flat_gain, vec![flat_type]);4356 return (flat_ref.levels.clone(), 0, flat_gain, vec![flat_type]);
4268 }4357 }
4269 let tx = side / 2;4358 let tx = side / 2;
4270- let set = luma_set_for(if tx >= 32 {4359+ let set = if tx >= 32 {
4271 // lane-b64b: the 64x64 root's halved transform is TX_32X32.4360 // lane-b64b: the 64x64 root's halved transform is TX_32X32.
4272 TxbSet::Luma32Inter4361 TxbSet::Luma32Inter
4273 } else if tx >= 16 {4362 } else if tx >= 16 {
4274 TxbSet::Luma16Inter4363 TxbSet::Luma16Inter
4275 } else {4364 } else {
4276 TxbSet::Luma8Inter4365 TxbSet::Luma8Inter
4277- }, search.screen);4366+ };
4278 let mut levels = vec![0i32; side * side];4367 let mut levels = vec![0i32; side * side];
4279 let (mut sse, mut bits) = (0.0, 0.0);4368 let (mut sse, mut bits) = (0.0, 0.0);
4280 let mut units = Vec::with_capacity(4);4369 let mut units = Vec::with_capacity(4);
crates/ec-av1/src/encoder.rsmodified+111 -0
@@ -3811,6 +3811,117 @@ mod tests {
3811 eprintln!("inter tx_type witness: hits {hits:?}, {} bytes", stream.len());3811 eprintln!("inter tx_type witness: hits {hits:?}, {} bytes", stream.len());
3812 }3812 }
3813 3813
3814+ /// lane-txi's witness: a `reduced_tx_set = 0` frame codes the WIDER
3815+ /// `tx_type` alphabets -- the seven-type `TX_SET_INTRA_1` at intra
3816+ /// 8x8/4x4 and the twelve/sixteen-type inter sets at 16x16 and below --
3817+ /// and both decoders reconstruct every frame sample-exact from them. The
3818+ /// statement is that the types only those alphabets can NAME (`V_DCT`,
3819+ /// `H_DCT`, and any inter type outside the two-type `DCT_IDTX`) are
3820+ /// reachable at all, and that the header bit, the writer's set map and
3821+ /// the search's pricer agree on which alphabet a symbol was coded into
3822+ /// (class `wrong-alphabet-same-value`: a disagreement here changes no
3823+ /// symbol VALUE and desyncs the arithmetic coder anyway).
3824+ #[test]
3825+ fn a_wide_tx_set_clip_codes_the_new_alphabets_both_decoders_read_exactly() {
3826+ // Every lever below is process-global: the same exclusive lock the
3827+ // presets take.
3828+ let _knobs = crate::speed::knob_write();
3829+ let _gate_lock = crate::stream::tests::lock_gate_counters();
3830+ crate::encode::set_intra_tx_search(Some(true));
3831+ crate::encode::set_inter_tx_search(Some(true));
3832+ crate::encode::set_wide_tx_set(Some(true));
3833+ let (width, height) = (320usize, 192usize);
3834+ // The same moving hard-edge card the two narrow-set witnesses use:
3835+ // vertical steps are what a 1-D `V_DCT`/`H_DCT` pass wins on, the
3836+ // ramps are `ADST`'s and the moving plateaus `IDTX`'s.
3837+ let sources: Vec<Picture> = (0..4)
3838+ .map(|t| {
3839+ let mut p = test_card(width, height, t * 3);
3840+ for y in 0..height {
3841+ for x in 0..width {
3842+ let v = match ((x + t * 5) / 16 % 2, (y + t * 3) / 16 % 2) {
3843+ (0, 0) => 16u16,
3844+ (1, 0) => 235,
3845+ (0, 1) => ((x + t) % 64 * 3) as u16,
3846+ _ => ((y + t) % 64 * 3) as u16,
3847+ };
3848+ p.y[y * width + x] = v;
3849+ }
3850+ }
3851+ p
3852+ })
3853+ .collect();
3854+ let config = EncoderConfig {
3855+ width,
3856+ height,
3857+ base_q_idx: 90,
3858+ gop: 4,
3859+ colour: Colour::Bt709Limited,
3860+ tile_cols_log2: 0,
3861+ tile_rows_log2: 0,
3862+ };
3863+ let mut enc = Av1Encoder::new(config).unwrap();
3864+ let _ = crate::encode::take_tx_type_hits();
3865+ let _ = crate::encode::take_inter_tx_type_hits();
3866+ let mut stream = Vec::new();
3867+ for packet in encode_all(&mut enc, &sources) {
3868+ stream.extend_from_slice(&packet.data);
3869+ }
3870+ let (intra, inter) = (
3871+ crate::encode::take_tx_type_hits(),
3872+ crate::encode::take_inter_tx_type_hits(),
3873+ );
3874+ crate::encode::set_wide_tx_set(None);
3875+ crate::encode::set_inter_tx_search(None);
3876+ crate::encode::set_intra_tx_search(None);
3877+ eprintln!("wide tx_type witness: intra {intra:?} inter {inter:?}, {} bytes", stream.len());
3878+ // The fire count is preset 0's, for the reason the five-type witness
3879+ // spells out: a faster preset prunes the modes and partitions a type
3880+ // wins on before it is ever priced (class `gate-blind-to-feature`).
3881+ if crate::speed::at(&crate::speed::TX_TYPE_SEARCH) && crate::speed::speed() == 0 {
3882+ use crate::transform::TxType;
3883+ let wide_only = |hits: &[usize; 16]| -> usize {
3884+ hits[TxType::VDct as usize] + hits[TxType::HDct as usize]
3885+ };
3886+ assert!(
3887+ wide_only(&intra) > 0,
3888+ "no intra luma unit took a 1-D DCT, the type only TX_SET_INTRA_1 names: {intra:?}"
3889+ );
3890+ let inter_wide: usize = inter.iter().sum::<usize>()
3891+ - inter[TxType::DctDct as usize]
3892+ - inter[TxType::Idtx as usize];
3893+ assert!(
3894+ inter_wide > 0,
3895+ "no inter luma unit took a type outside the two-type set: {inter:?}"
3896+ );
3897+ } else {
3898+ eprintln!(
3899+ "SKIP the wide-alphabet fire count at preset {}",
3900+ crate::speed::speed()
3901+ );
3902+ }
3903+ let ours = crate::stream::decode_stream(&stream).expect("our decoder");
3904+ assert_eq!(ours.len(), sources.len(), "our decoder's frames");
3905+ if have_ffmpeg() {
3906+ let theirs = ffmpeg_decode_luma(&stream, width, height);
3907+ assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
3908+ for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
3909+ let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
3910+ if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
3911+ panic!(
3912+ "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
3913+ at % width,
3914+ at / width,
3915+ got[at],
3916+ b[at],
3917+ );
3918+ }
3919+ }
3920+ } else {
3921+ eprintln!("SKIP the ffmpeg half: no ffmpeg");
3922+ }
3923+ }
3924+
3814 /// Every SHIPPED SPEED PRESET codes a stream both decoders reconstruct3925 /// Every SHIPPED SPEED PRESET codes a stream both decoders reconstruct
3815 /// sample-exact -- ours and ffmpeg's -- and codes a DIFFERENT stream from3926 /// sample-exact -- ours and ffmpeg's -- and codes a DIFFERENT stream from
3816 /// its neighbour (a preset that changes no byte is a preset that buys no3927 /// its neighbour (a preset that changes no byte is a preset that buys no