diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 0c655fef..e8f0b2c4 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -3802,6 +3802,40 @@ fn tx_depth_bits(side: usize, depth: usize) -> f64 { pub(crate) static INTER_TX_TYPE_HITS: [std::sync::atomic::AtomicUsize; 16] = [const { std::sync::atomic::AtomicUsize::new(0) }; 16]; +/// lane-txrd: a multiplier on the rate term of the TRANSFORM-TYPE decision +/// only (`EC_AV1_TXRD_LAMBDA`, default 1.0 = the mode search's own weight). +/// `0` compares types on reconstruction error alone, which is what separates +/// a rate-term calibration (class `rd-rate-term-calibration`) from a +/// distortion the trial mis-measures. +pub(crate) fn tx_type_lambda_mult() -> f64 { + static M: std::sync::LazyLock = std::sync::LazyLock::new(|| { + crate::envflags::var("EC_AV1_TXRD_LAMBDA") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(1.0) + }); + *M +} + +/// lane-txrd instrument: over the FLAT inter luma decision, the summed +/// reconstruction error and priced bits of the type the search chose against +/// the `DCT_DCT` trial it was compared with. Both are `* 64` so they fit an +/// integer counter. `EC_AV1_TXRD_CENSUS`. +pub(crate) static TXRD_STATS: [std::sync::atomic::AtomicU64; 7] = [ + std::sync::atomic::AtomicU64::new(0), + std::sync::atomic::AtomicU64::new(0), + std::sync::atomic::AtomicU64::new(0), + std::sync::atomic::AtomicU64::new(0), + std::sync::atomic::AtomicU64::new(0), + std::sync::atomic::AtomicU64::new(0), + std::sync::atomic::AtomicU64::new(0), +]; + +/// Reads [`TXRD_STATS`] and zeroes it. +pub(crate) fn take_txrd_stats() -> [u64; 7] { + std::array::from_fn(|i| TXRD_STATS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) +} + /// Reads [`INTER_TX_TYPE_HITS`] and zeroes it. #[cfg(test)] pub(crate) fn take_inter_tx_type_hits() -> [usize; 16] { @@ -3966,7 +4000,8 @@ fn commit_inter_luma( let mut flat_type = TxType::DctDct; if !skip { if let Some(fset) = inter_luma_set(side) { - let cost = |t: &Trial| t.sse + search.lambda * t.bits; + let lambda = search.lambda * tx_type_lambda_mult(); + let cost = |t: &Trial| t.sse + lambda * t.bits; for &tx_type in inter_tx_type_candidates(fset, search.screen) { if tx_type == TxType::DctDct { continue; @@ -3998,6 +4033,45 @@ fn commit_inter_luma( } }; let flat_ref: &Trial = flat_typed.as_ref().unwrap_or(flat); + if crate::envflags::env_flag!("EC_AV1_TXRD_CENSUS") && !skip { + use std::sync::atomic::Ordering::Relaxed; + TXRD_STATS[0].fetch_add(1, Relaxed); + TXRD_STATS[1].fetch_add(flat_ref.sse as u64, Relaxed); + TXRD_STATS[2].fetch_add(flat.sse as u64, Relaxed); + TXRD_STATS[3].fetch_add((flat_ref.bits * 64.0) as u64, Relaxed); + TXRD_STATS[4].fetch_add((flat.bits * 64.0) as u64, Relaxed); + // Is the `DCT_DCT` baseline the search compares against the trial + // THIS function would build for the same block? A stale or + // differently-predicted baseline is what would let a candidate win on + // both terms at once (class `local-rd-on-references` vs a real + // pricing defect); re-predicting it here is the only way to tell. + if let Some(fset) = inter_luma_set(side) { + let here = match second { + Some((mv1, ref1)) => mc_trial_compound_typed( + luma, x, y, side, (mv, mv1), true, reference, ref1, search.base_q_idx, + search.deadzone, fset, TxType::DctDct, fctx, + ), + None => mc_trial_typed( + luma, x, y, side, mv, true, reference.0, reference.1, reference.2, + reference.3, false, search.base_q_idx, search.deadzone, fset, + TxType::DctDct, fctx, + ), + }; + TXRD_STATS[5].fetch_add(here.sse as u64, Relaxed); + TXRD_STATS[6].fetch_add((here.bits * 64.0) as u64, Relaxed); + static DUMPED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = TXRD_STATS[0].load(Relaxed); + if here.sse * 2.0 < flat.sse && DUMPED.fetch_add(1, Relaxed) < 30 { + eprintln!( + "TXRD block {n} at ({x},{y}) side={side} compound={} mv={mv:?} \ + flat sse={:.0} bits={:.1} | here sse={:.0} bits={:.1} | chosen {flat_type:?} \ + sse={:.0} bits={:.1}", + second.is_some(), flat.sse, flat.bits, here.sse, here.bits, + flat_ref.sse, flat_ref.bits, + ); + } + } + } // What the caller's already-counted `flat` cost has to be corrected by // when a non-`DCT_DCT` type won it, the same way the split delta below is. let flat_gain = (flat_ref.sse + search.lambda * flat_ref.bits) @@ -4050,7 +4124,7 @@ fn commit_inter_luma( let mut best: Option<(f64, TxType, Trial)> = None; for &tx_type in inter_tx_type_candidates(set, search.screen) { let candidate = unit(tx_type); - let cost = candidate.sse + search.lambda * candidate.bits; + let cost = candidate.sse + search.lambda * tx_type_lambda_mult() * candidate.bits; if best.as_ref().is_none_or(|(b, _, _)| cost < *b) { best = Some((cost, tx_type, candidate)); } @@ -11157,6 +11231,41 @@ pub(crate) fn encode_inter_frame( refs[4] = trial_golden.as_ref(); refs[7] = trial_altref.as_ref(); let refpix = crate::decode::RefPix::ready(refs); + // lane-txrd: the frame's luma error BEFORE the loop filters, i.e. the + // sum the block search believed it was minimising. Against the + // post-filter per-frame PSNR the gate prints, this separates a trial + // whose reconstruction is a lie from a filter stage that undoes the win. + if crate::envflags::env_flag!("EC_AV1_FRAME_PSNR") { + let sse: u64 = luma + .reconstruction + .chunks(luma.width) + .take(luma.true_height) + .zip(picture_y8.chunks(luma.width)) + .flat_map(|(r, s)| r[..luma.true_width].iter().zip(&s[..luma.true_width])) + .map(|(&r, &s)| { + let d = i64::from(r) - i64::from(s); + (d * d) as u64 + }) + .sum(); + eprintln!("EC_PREFILTER q={base_q_idx} luma sse={sse}"); + } + let post = |luma: &Plane<'_>, tag: &str| { + if !crate::envflags::env_flag!("EC_AV1_FRAME_PSNR") { + return; + } + let sse: u64 = luma + .reconstruction + .chunks(luma.width) + .take(luma.true_height) + .zip(picture_y8.chunks(luma.width)) + .flat_map(|(r, s)| r[..luma.true_width].iter().zip(&s[..luma.true_width])) + .map(|(&r, &s)| { + let d = i64::from(r) - i64::from(s); + (d * d) as u64 + }) + .sum(); + eprintln!("{tag} q={base_q_idx} luma sse={sse}"); + }; pick_and_apply_filters( &mut header, &mut luma, @@ -11212,6 +11321,7 @@ pub(crate) fn encode_inter_frame( ) }, )?; + post(&luma, "EC_POSTFILTER"); let mut cdfs = end_cdfs .into_inner() .unwrap_or_else(|| start_cdfs.0.clone()); @@ -14849,12 +14959,15 @@ mod tests { ); } } - let mean: f64 = decoded - .iter() - .zip(source) - .map(|(d, s)| psnr_all(d, s)) - .sum::() - / source.len() as f64; + let per_frame: Vec = decoded.iter().zip(source).map(|(d, s)| psnr_all(d, s)).collect(); + // lane-txrd: does a tool's loss start at the FIRST inter frame + // (a local mispricing) or grow down the GOP (propagation into + // the reference chain)? One line per q point answers it. + if crate::envflags::env_flag!("EC_AV1_FRAME_PSNR") { + let row: Vec = per_frame.iter().map(|p| format!("{p:.2}")).collect(); + eprintln!("{name}: q={q} per-frame PSNR {}", row.join(" ")); + } + let mean: f64 = per_frame.iter().sum::() / source.len() as f64; ladder.push((mean, (encoded.stream.len() as f64).log10())); } // What this clip asked for and what the content gate left it coding @@ -15938,6 +16051,42 @@ mod tests { row("32x32 single", 4), row("32x32 compound", 6), ); + // lane-txrd: which types the two searches actually COMMITTED over + // this row's four encodes -- the gate could not say whether a type + // search fired at all (class `gate-blind-to-feature`). + const NAMES: [&str; 16] = [ + "IDTX", "DCT_DCT", "ADST_ADST", "ADST_DCT", "DCT_ADST", "V_DCT", "H_DCT", + "FLIPADST_DCT", "DCT_FLIPADST", "FLIPADST_FLIPADST", "ADST_FLIPADST", + "FLIPADST_ADST", "V_ADST", "H_ADST", "V_FLIPADST", "H_FLIPADST", + ]; + let name_of = |t: usize| NAMES[t]; + for (label, hits) in [("inter", take_inter_tx_type_hits()), ("intra", take_tx_type_hits())] { + let total: usize = hits.iter().sum(); + let live: Vec = hits + .iter() + .enumerate() + .filter(|&(_, &n)| n > 0) + .map(|(t, &n)| format!("{}={n} ({:.1}%)", name_of(t), 100.0 * n as f64 / total.max(1) as f64)) + .collect(); + eprintln!("{name}: {label} tx_type of {total} units -- {}", live.join(" ")); + } + let t = take_txrd_stats(); + if t[0] > 0 { + eprintln!( + "{name}: txrd flat decisions={} chosen sse={} bits={:.0} | DCT_DCT sse={} \ + bits={:.0} (dsse {:+.2}%, dbits {:+.2}%)", + t[0], t[1], t[3] as f64 / 64.0, t[2], t[4] as f64 / 64.0, + 100.0 * (t[1] as f64 - t[2] as f64) / t[2].max(1) as f64, + 100.0 * (t[3] as f64 - t[4] as f64) / t[4].max(1) as f64, + ); + eprintln!( + "{name}: txrd DCT_DCT re-predicted HERE sse={} bits={:.0} (vs the passed-in \ + flat: dsse {:+.2}%, dbits {:+.2}%)", + t[5], t[6] as f64 / 64.0, + 100.0 * (t[5] as f64 - t[2] as f64) / t[2].max(1) as f64, + 100.0 * (t[6] as f64 - t[4] as f64) / t[4].max(1) as f64, + ); + } } /// The video stream's coded size, from ffprobe. diff --git a/crates/ec-av1/src/transform.rs b/crates/ec-av1/src/transform.rs index 1d40feb9..36bfdef9 100644 --- a/crates/ec-av1/src/transform.rs +++ b/crates/ec-av1/src/transform.rs @@ -2152,6 +2152,42 @@ mod tests { } } + #[test] + #[ignore] + fn txrd_gain_probe() { + for side in [4usize, 8, 16, 32] { + let residual: Vec = + noise(side * side, 7 + side as u64).iter().map(|&v| v / 4).collect(); + let all = [ + TxType::DctDct, + TxType::AdstDct, + TxType::DctAdst, + TxType::AdstAdst, + TxType::Idtx, + TxType::VDct, + TxType::HDct, + TxType::VAdst, + TxType::HAdst, + ]; + for &tx in &all { + if side > 16 && !matches!(tx, TxType::DctDct | TxType::Idtx) { + continue; + } + let levels = forward_and_quantize_typed(&residual, side, 8, 20, 0.5, tx); + let back = dequant_and_inverse_typed(&levels, side, 8, 20, 0, 0, tx); + let num: f64 = + residual.iter().zip(&back).map(|(&a, &b)| f64::from(a) * f64::from(b)).sum(); + let den: f64 = residual.iter().map(|&a| f64::from(a) * f64::from(a)).sum(); + let nz = levels.iter().filter(|&&l| l != 0).count(); + let energy: f64 = levels.iter().map(|&l| f64::from(l.abs())).sum(); + println!( + "{side}x{side} {tx:?} alpha={:.4} nz={nz} sum|l|={energy}", + num / den + ); + } + } + } + /// The typed forward transform is the decoder's exact inverse undone: /// quantized and taken back, an ADST-typed residual returns with the same /// error a `DCT_DCT` one does. This is what pins the *gain* of the ADST