diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 88baa2db..e66c67d8 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -10627,6 +10627,100 @@ fn deltaq_for_factor(base: u8, f: f64, k: f64, clamp: i32, res: i32) -> u8 { (i32::from(base) + delta).clamp(1, 255) as u8 } +/// lane-dq: derive the per-superblock qindex libaom's `deltaq-mode 1` +/// objective would, from the SAME tpl dependence ratio our own map already +/// carries (`EC_AV1_DQ_TPL=1`). +/// +/// libaom (`av1_get_q_for_deltaq_objective`, encodeframe_utils.c) forms a +/// superblock dependence ratio `rk = exp((intra_cost - mc_dep_cost)/w)` in the +/// LOG domain, divides the frame-level `r0` (`encoder_utils.c:627`, the very +/// same expression at frame scope) by it, and asks +/// `av1_get_deltaq_offset(bit_depth, base, beta)` for the qindex whose +/// **DC** step is `dc_q(base)/sqrt(beta)`. With per-cell costs `intra` and +/// `intra + mc_dep`, `rk` is `1/(1 + r)` for this crate's `r = mc_dep/intra`, +/// so `beta = (1 + r_sb) / (1 + r_frame)` with `r_frame` read the log-mean way +/// libaom reads `r0`. The offset is clamped to libaom's own +/// `+-(delta_q_res * 9 - 1)`, which at `res = 4` is +-8 steps -- more than +/// twice the +-16 qindex [`deltaq_for_factor`] allows. +/// +/// Two things differ from [`deltaq_for_factor`] and both are the point of the +/// arm: the table inverted is `dc_q` not `ac_q`, and the ratio is read raw +/// (`sqrt(1 + r)`) rather than through the map's `log2`-compressed, +/// `TPL_POWER`-flattened, mean-normalised lambda factor -- so this mapping is +/// much stronger for the same map. `strength` scales the offset. +fn deltaq_libaom(base: u8, r_sb: f64, r_frame: f64, strength: f64, res: i32) -> u8 { + let beta = ((1.0 + r_sb.max(0.0)) / (1.0 + r_frame.max(0.0))).max(1e-6); + let target = f64::from(crate::quant::dc_q(8, i32::from(base))) / beta.sqrt(); + let exact = (1..=255) + .min_by(|&a, &b| { + let d = |q: i32| (f64::from(crate::quant::dc_q(8, q)) - target).abs(); + d(a).partial_cmp(&d(b)).expect("dc_q is finite") + }) + .expect("the qindex range is not empty") + - i32::from(base); + let want = exact as f64 * strength; + // Snapped onto the `res` grid first, so the coded delta is a whole number + // of steps, then bounded by libaom's own `res * 9 - 1`. + let max_steps = (res * 9 - 1) / res; + let steps = (want / f64::from(res)).round() as i32; + let delta = steps.clamp(-max_steps, max_steps) * res; + (i32::from(base) + delta).clamp(1, 255) as u8 +} + +/// The frame-level `r0` libaom's objective divides by: the log-mean of +/// `1 + r` over the frame's cells, minus 1. +fn tpl_frame_ratio(ratio: &[f64]) -> f64 { + if ratio.is_empty() { + return 0.0; + } + let m = ratio.iter().map(|&r| (1.0 + r.max(0.0)).ln()).sum::() / ratio.len() as f64; + m.exp() - 1.0 +} + +/// The [`deltaq_libaom`] strength, or `None` to keep the shipped +/// [`deltaq_for_factor`] derivation. +/// +/// `EC_AV1_DQ_TPL=0`/`1` forces the mapping either way and `EC_AV1_DQ_TPL_K` +/// the strength (default 1.0 = libaom's own offset when the flag armed it); +/// with neither set the preset decides, see [`crate::speed::DQ_TPL_K`]. +fn dq_tpl_strength() -> Option { + let env_k = crate::envflags::var("EC_AV1_DQ_TPL_K") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .filter(|k| k.is_finite() && *k >= 0.0); + match crate::envflags::var("EC_AV1_DQ_TPL").ok().as_deref().map(str::trim) { + Some("0") => return None, + Some(_) => return Some(env_k.unwrap_or(1.0)), + None => {} + } + env_k.or_else(|| Some(crate::speed::at(&crate::speed::DQ_TPL_K))).filter(|k| *k > 0.0) +} + +/// `EC_AV1_DQ_CENSUS=1`: per inter frame, one line comparing the offsets the +/// shipped mapping ([`deltaq_for_factor`]) WOULD emit against the ones +/// libaom's objective ([`deltaq_libaom`]) gives for the same superblocks and +/// the same tpl map -- and which of the two the frame actually coded. +fn dq_census() -> bool { + crate::envflags::var("EC_AV1_DQ_CENSUS").ok().as_deref().map(str::trim) == Some("1") +} + +/// The histogram/extent summary [`dq_census`] prints for one set of offsets. +fn dq_summary(offsets: &[i32]) -> String { + let n = offsets.len().max(1); + let (lo, hi) = offsets.iter().fold((0i32, 0i32), |(l, h), &o| (l.min(o), h.max(o))); + let nz = offsets.iter().filter(|&&o| o != 0).count(); + let mean = offsets.iter().map(|&o| f64::from(o)).sum::() / n as f64; + let absmean = offsets.iter().map(|&o| f64::from(o.abs())).sum::() / n as f64; + let mut levels: Vec = offsets.to_vec(); + levels.sort_unstable(); + levels.dedup(); + format!( + "range {lo}..{hi} mean {mean:+.2} |mean| {absmean:.2} nonzero {nz}/{} levels {}", + offsets.len(), + levels.len() + ) +} + /// How many DISTINCT per-superblock quantizer levels the last inter frame's /// [`sb_q`](encode_inter_frame) grid carried -- lane-deltaq's fire counter /// (class `gate-blind-to-feature`: every exactness assert below passes on a @@ -10935,7 +11029,16 @@ fn tpl_sb_factors(map: &[f64], cells_x: usize, cells_y: usize, k: f64) -> Vec Vec { +/// Returns the per-cell lambda factors AND the per-cell dependence ratio +/// `mc_dep / intra` they were derived from -- the second half is what +/// [`deltaq_libaom`] needs, since the factor alone has been through a +/// mean normalisation the raw ratio cannot be recovered across. +fn tpl_lambda_factors( + frames: &[&[u8]], + width: usize, + height: usize, + k: f64, +) -> (Vec, Vec) { let start = std::time::Instant::now(); let (cells_x, cells_y) = (width / 16, height / 16); let cells = cells_x * cells_y; @@ -11054,7 +11157,7 @@ fn tpl_lambda_factors(frames: &[&[u8]], width: usize, height: usize, k: f64) -> TPL_NANOS.load(std::sync::atomic::Ordering::Relaxed) as f64 / 1e6, ); } - out + (out, ratio) } /// Where one inter frame sits in a coding-order pyramid: which DPB slots its @@ -11326,11 +11429,15 @@ pub(crate) fn encode_inter_frame( let tpl_sources: Vec> = window.iter().map(|n| n.y.iter().map(|&v| v as u8).collect()).collect(); let tpl_cells_x = picture.width / 16; - let tpl_factors: Option> = (tpl_k > 0.0 && !tpl_sources.is_empty()).then(|| { + // `.1` is the propagating map's raw per-cell dependence ratio, which only + // [`deltaq_libaom`] reads; the one-frame area map has no such ratio. + let tpl_both: Option<(Vec, Option>)> = + (tpl_k > 0.0 && !tpl_sources.is_empty()).then(|| { if tpl_propagating() { let mut frames: Vec<&[u8]> = vec![&picture_y8]; frames.extend(tpl_sources.iter().map(Vec::as_slice)); - tpl_lambda_factors(&frames, picture.width, picture.height, tpl_k) + let (f, r) = tpl_lambda_factors(&frames, picture.width, picture.height, tpl_k); + (f, Some(r)) } else { // The shipped map is one factor per 64x64; it is spread over that // superblock's own 16 cells so the application site below (which @@ -11340,11 +11447,16 @@ pub(crate) fn encode_inter_frame( tpl_area_map(&picture_y8, &tpl_sources[0], picture.width, picture.height); let cells_y = picture.height / 16; let sb = tpl_sb_factors(&map, tpl_cells_x, cells_y, tpl_k); - (0..tpl_cells_x * cells_y) + let f: Vec = (0..tpl_cells_x * cells_y) .map(|c| sb[(c / tpl_cells_x / 4) * (tpl_cells_x / 4) + (c % tpl_cells_x) / 4]) - .collect() + .collect(); + (f, None) } }); + let (tpl_factors, tpl_ratio) = match tpl_both { + Some((f, r)) => (Some(f), r), + None => (None, None), + }; // The true grid ([`crate::tile::block_grid`]'s ceiling), not the padded // coding surface's: `blocks` carries one entry per 32x32 block the tile @@ -11367,30 +11479,63 @@ pub(crate) fn encode_inter_frame( .as_ref() .filter(|_| !screen) .and(deltaq_res_log2().map(|r| 1i32 << r)); + // The same 16-cell mean the superblock's own lambda takes, clamped to the + // map the frame actually has -- read over the factors or over the raw + // dependence ratios, whichever mapping is asking. + let sb_mean = |m: &[f64], sb: usize| { + let (sb_r, sb_c) = (sb / sb_cols, sb % sb_cols); + (0..16) + .map(|i| { + let (cy, cx) = (sb_r * 4 + i / 4, sb_c * 4 + i % 4); + m[(cy.min(m.len() / tpl_cells_x - 1)) * tpl_cells_x + cx.min(tpl_cells_x - 1)] + }) + .sum::() + / 16.0 + }; + // lane-dq: `EC_AV1_DQ_TPL=1` takes libaom's own objective mapping off the + // raw dependence ratio; without it (and always without a ratio map, i.e. + // on the one-frame area map) the shipped derivation stands. + let r_frame = tpl_ratio.as_deref().map(tpl_frame_ratio); + let sb_qindex = |f: &[f64], res: i32, sb: usize, libaom: Option| -> u8 { + match (libaom, tpl_ratio.as_deref(), r_frame) { + (Some(k), Some(r), Some(rf)) => deltaq_libaom(base_q_idx, sb_mean(r, sb), rf, k, res), + _ => deltaq_for_factor(base_q_idx, sb_mean(f, sb), deltaq_k(), deltaq_clamp(), res), + } + }; let sb_q: Option> = match (&tpl_factors, deltaq_res) { (Some(f), Some(res)) => { - let (k, clamp) = (deltaq_k(), deltaq_clamp()); - Some( - (0..sb_cols * _sb_rows) - .map(|sb| { - let (sb_r, sb_c) = (sb / sb_cols, sb % sb_cols); - // The same 16-cell mean the superblock's own lambda - // takes, clamped to the map the frame actually has. - let mean = (0..16) - .map(|i| { - let (cy, cx) = (sb_r * 4 + i / 4, sb_c * 4 + i % 4); - f[(cy.min(f.len() / tpl_cells_x - 1)) * tpl_cells_x - + cx.min(tpl_cells_x - 1)] - }) - .sum::() - / 16.0; - deltaq_for_factor(base_q_idx, mean, k, clamp, res) - }) - .collect(), - ) + let libaom = dq_tpl_strength(); + Some((0..sb_cols * _sb_rows).map(|sb| sb_qindex(f, res, sb, libaom)).collect()) } _ => None, }; + // lane-dq census: both mappings on the SAME superblocks, whether or not + // the frame codes any delta syntax (`deltaq_res` is `None` with the lever + // off, and the census then prices the default `res = 4` grid). + if dq_census() { + if let Some(f) = &tpl_factors { + let res = deltaq_res.unwrap_or(4); + let off = |libaom: Option| -> Vec { + (0..sb_cols * _sb_rows) + .map(|sb| i32::from(sb_qindex(f, res, sb, libaom)) - i32::from(base_q_idx)) + .collect() + }; + let strength = dq_tpl_strength(); + let (ours, aom) = (off(None), off(Some(strength.unwrap_or(1.0)))); + let coded = match (deltaq_res.is_some(), strength) { + (false, _) => "none".to_string(), + (true, None) => "ours".to_string(), + (true, Some(k)) => format!("libaom k={k}"), + }; + eprintln!( + "dq census: base={base_q_idx} res={res} sbs={} coded={coded} r_frame={:.4}\n ours {}\n libaom {}", + sb_cols * _sb_rows, + r_frame.unwrap_or(f64::NAN), + dq_summary(&ours), + dq_summary(&aom), + ); + } + } if let Some(res) = deltaq_res.filter(|_| sb_q.is_some()) { header.delta.q_present = true; header.delta.q_res = res.trailing_zeros() as u8; @@ -12834,6 +12979,40 @@ mod tests { assert_eq!(plane.block_sse(32, 32, 16, &block), (190.0 * 190.0) * 64.0); } + /// lane-dq: libaom's objective mapping ([`super::deltaq_libaom`]) must + /// spend WHERE THE WINDOW LEANS, stay congruent to the base on the + /// `delta_q_res` grid, and stop at libaom's own `+-(res * 9 - 1)` bound. + #[test] + fn the_objective_delta_q_mapping_leans_the_right_way_and_stops_at_libaom_s_clamp() { + let (base, res) = (162u8, 4i32); + let rf = 2.0; + // A superblock the window leans on more than the frame average is + // coded FINER (lower qindex); a slack one coarser; the average one + // exactly at the base. + assert!(super::deltaq_libaom(base, 8.0, rf, 1.0, res) < base, "leaned-on SB must go finer"); + assert!(super::deltaq_libaom(base, 0.2, rf, 1.0, res) > base, "idle SB must go coarser"); + assert_eq!(super::deltaq_libaom(base, rf, rf, 1.0, res), base, "the average SB moves 0"); + // Every offset is a whole number of steps and inside +-(res * 9 - 1). + let max = ((res * 9 - 1) / res) * res; + for r in [0.0f64, 0.01, 0.5, 1.0, 3.0, 50.0, 1e6] { + for k in [0.5f64, 1.0, 1.5] { + let q = i32::from(super::deltaq_libaom(base, r, rf, k, res)); + let d = q - i32::from(base); + assert_eq!(d % res, 0, "r={r} k={k}: offset {d} is not a whole {res}-step"); + assert!(d.abs() <= max, "r={r} k={k}: offset {d} past libaom's +-{max}"); + } + } + // The clamp is REACHED from both ends, so the bound is a real bound + // and not a formula that never gets there. + assert_eq!(i32::from(super::deltaq_libaom(base, 1e9, rf, 1.0, res)) - i32::from(base), -max); + assert_eq!(i32::from(super::deltaq_libaom(base, 0.0, 1e9, 1.0, res)) - i32::from(base), max); + // A stronger `k` never moves less than a weaker one. + let d = |k: f64| (i32::from(super::deltaq_libaom(base, 8.0, rf, k, res)) - i32::from(base)).abs(); + assert!(d(0.5) <= d(1.0) && d(1.0) <= d(1.5), "strength must be monotone: {} {} {}", d(0.5), d(1.0), d(1.5)); + // The frame reference is libaom's log-mean: flat in, the same value out. + assert!((super::tpl_frame_ratio(&[2.5; 16]) - 2.5).abs() < 1e-9); + } + #[test] fn tpl_factors_are_flat_on_a_uniform_repeat_and_fall_where_the_window_leans() { // Four 64x64 superblocks across: the shipped map forms its ratio per @@ -12843,7 +13022,7 @@ mod tests { let (w, h) = (256usize, 64usize); let uniform: Vec = (0..w * h).map(|i| ((i * 37) % 251) as u8).collect(); let frames: Vec<&[u8]> = vec![&uniform, &uniform, &uniform]; - let f = super::tpl_lambda_factors(&frames, w, h, 1.0); + let (f, _) = super::tpl_lambda_factors(&frames, w, h, 1.0); assert_eq!(f.len(), 64, "16x4 cells of 16x16"); for (i, &v) in f.iter().enumerate() { assert!((v - 1.0).abs() < 1e-6, "cell {i} factor {v}, a flat map must move no lambda"); @@ -12857,7 +13036,7 @@ mod tests { let frames: Vec<&[u8]> = vec![&split, &split, &split]; let cells_x = w / 16; for k in [0.25f64, 0.5, 1.0, 2.0] { - let f = super::tpl_lambda_factors(&frames, w, h, k); + let (f, _) = super::tpl_lambda_factors(&frames, w, h, k); for r in 0..h / 16 { let (lean, idle) = (f[r * cells_x], f[r * cells_x + cells_x - 1]); assert!(lean < 1.0, "k={k} row {r}: leaned-on cell factor {lean} must be < 1"); @@ -16565,8 +16744,12 @@ mod tests { // ([`crate::motion::MV_SUBPEL_ITERS`]), so every inter block's vector // -- and with it its residual -- moved: 8325 -> 8288 bytes at q=150 // and 33014 -> 33090 at q=60. - let pins: [(u8, usize, u64); 2] = - [(150, 8288, 0x241d_8115_0a6d_0f34), (60, 33090, 0x7e02_777c_01b4_f035)]; + // Re-taken on lane-dq: preset 0 codes a per-superblock `delta_qindex` + // from libaom's objective tpl mapping, so every inter picture's + // quantizer grid -- and every decision priced against it -- moved + // (8325 -> 8419 / 33014 -> 33029 on its own base); re-taken once more + // at the merge of both lanes. + let pins: [(u8, usize, u64); 2] = [(150, 8252, 0x5b6e40a2b5498988), (60, 33053, 0x9a0abfc234eccc37)]; let coded: Vec<(u8, usize, u64)> = pins .iter() .map(|&(q, _, _)| { diff --git a/crates/ec-av1/src/speed.rs b/crates/ec-av1/src/speed.rs index a5b5b19d..8f766189 100644 --- a/crates/ec-av1/src/speed.rs +++ b/crates/ec-av1/src/speed.rs @@ -308,7 +308,35 @@ pub(crate) const I64_ROOT: [bool; 11] = [crate::encode::I64_ROOT; 11]; /// `EC_AV1_DELTAQ=2` forces it on at any preset, `EC_AV1_DELTAQ=0` off. /// Above preset 6 it is inert anyway -- [`TPL_DEPTH`] cuts the lookahead to /// one picture there, so there is no map to vary the quantizer by. -pub(crate) const DELTAQ_RES: [u8; 11] = [4, 4, 4, 4, 4, 2, 2, 4, 4, 4, 4]; +pub(crate) const DELTAQ_RES: [u8; 11] = [2, 4, 4, 4, 4, 2, 2, 4, 4, 4, 4]; + +/// lane-dq: the strength of libaom's OBJECTIVE per-superblock mapping +/// ([`crate::encode::deltaq_libaom`]) -- `0` keeps the shipped +/// `deltaq_for_factor` derivation, anything above it takes that fraction of +/// libaom's own offset. Only meaningful where [`DELTAQ_RES`] is on. +/// +/// Preset 0 only, at 0.25. The census (`EC_AV1_DQ_CENSUS=1`) says the two +/// mappings read the SAME tpl map into offsets an order of magnitude apart -- +/// on film B's 12-frame window, ours is `-4..8` with `|mean| 3.0` while +/// libaom's is `-24..32` with `|mean| 14` -- so a strength is the only honest +/// knob between them. Measured on the 48-picture long-GOP gate (BD vs libaom +/// / rav1e), which is the shape his exports have: +/// +/// | arm | film A | film B | +/// |---|---|---| +/// | control (no delta_q) | +25.2/-7.2 | +86.7/+7.3 | +/// | shipped mapping | +24.6/-7.3 | +86.1/+7.5 | +/// | **objective, 0.25** | **+24.4/-7.5** | **+86.0/+7.3** | +/// | objective, 0.5 | +23.8/-7.6 | +86.5/+7.9 | +/// | objective, 1.0 | +24.0/-7.0 | +88.4/+9.7 | +/// +/// 0.25 is the only arm down on both films on the libaom column with neither +/// rav1e column worse; 0.5 buys film A another 0.6 and gives film B back 0.6. +/// The 12-frame gate reads the same arm as flat (film A +21.0/-4.8 -> +/// +20.7/-4.8, film B +24.9/-1.9 -> +24.8/-1.7) and the screen capture is +/// BYTE-IDENTICAL at every arm -- `encode_inter_frame` codes no delta syntax +/// on a screen frame at all (lane-dq3's content gate). +pub(crate) const DQ_TPL_K: [f64; 11] = [0.25, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]; /// `encode::SPLIT_RD_THRESHOLD`: how cheap a block has to be before its split /// trial is withheld. The single biggest wall lever in the tile search. diff --git a/lanes/dq.report.md b/lanes/dq.report.md new file mode 100644 index 00000000..5dd8c0ce --- /dev/null +++ b/lanes/dq.report.md @@ -0,0 +1,154 @@ +# lane-dq — the per-superblock `delta_q` mapping, ours vs libaom's objective + +## 0. The charter's premise, corrected first + +The charter asked what the existing `delta_q` derives its offsets from and +"whether the tpl map feeds it at all". It does, and has since lane-deltaq: +`encode::deltaq_for_factor` inverts the tpl LAMBDA factor through the `ac_q` +table. Nothing was variance-driven and no map was inert. What was never +measured is that OUR mapping and LIBAOM's read the same map into offsets an +order of magnitude apart — that is this lane's finding, and the strength +between them is what shipped. + +## 1. Census instrument — `EC_AV1_DQ_CENSUS=1` + +One line per inter frame from `encode_inter_frame`, printing, for the SAME +superblocks and the same tpl map, the offsets the shipped mapping +(`deltaq_for_factor`) emits and the ones libaom's objective +(`deltaq_libaom`, new) would, plus which of the two the frame actually coded +(`coded=none` when the lever is off — the census then prices a hypothetical +`res = 4` grid). Zero cost when unset. + +Film B, native gate crop `1920x1024` at `00:40:00`, 12 frames, q=150, +preset 0, lever OFF (`enc_probe … gate 0 12 150`, 27634 B = the gate's own +q150 point). 480 superblocks per frame, `base=162`, `res=4`: + +| frame | r_frame | ours (range, \|mean\|, nonzero, levels) | libaom (same) | +|---|---|---|---| +| … | 2.70 | −4..8, 3.04, 321/480, 4 | −24..32, 13.97, 450/480, 15 | +| … | 2.85 | −4..8, 2.81, 308/480, 4 | −28..32, 14.94, 454/480, 16 | +| … | 2.83 | −4..8, 2.86, 307/480, 4 | −24..32, 14.32, 448/480, 15 | +| … | 2.51 | −4..8, 2.88, 305/480, 4 | −24..32, 14.45, 451/480, 15 | +| … | 2.06 | −4..8, 2.93, 312/480, 4 | −24..32, 13.84, 449/480, 15 | +| … | 1.74 | −4..8, 2.60, 294/480, 4 | −24..32, 13.58, 447/480, 15 | +| … | 1.27 | −4..8, 2.39, 280/480, 4 | −20..32, 12.03, 448/480, 14 | +| … | 0.91 | −4..4, 1.76, 211/480, 3 | −20..28, 11.07, 450/480, 13 | +| … | 0.45 | −4..4, 1.38, 166/480, 3 | −12..12, 5.87, 409/480, 7 | + +**The shipped mapping moves ~5x less quantizer than libaom's on the identical +map**, and it never reaches its own `±16` clamp (its widest offset is `+8`), +so the clamp is NOT what bounds it: the `log2(1+r)` compression plus +`TPL_POWER = 0.5` plus the mean normalisation is. libaom's own clamp +(`±(delta_q_res * 9 − 1)`, `±32` at `res = 4`) IS reached. The census matches +lane-cen3's census fact that libaom codes `delta_q` in every inter frame while +we coded it in none at preset 0. + +The census's `libaom` column prints the strength actually in force, so it is +raw libaom (`k = 1`) whenever the lever is off and the shipped `k = 0.25` +otherwise — the shipped default on the same clip prints +`coded=libaom k=0.25 … libaom range −4..4 |mean| 1.21..1.83`, i.e. the +strength brings the objective mapping down to the shipped mapping's own +extent while keeping its SHAPE (different superblocks, 145..220 nonzero vs +166..211), and codes 28304 B against the control's 27634 B. + +`aomdec -EC_TRACE_TPL` was not used: it exposes no per-SB qindex, so libaom's +mapping is reimplemented on OUR map instead, which is also the only way to +compare the two mappings at one map (class `shared-oracle blindness` cuts the +other way here — one map, two mappings, is exactly the controlled comparison). + +## 2. The mapping, from libaom's source + +`av1_get_q_for_deltaq_objective` (`av1/encoder/encodeframe_utils.c:893`) forms +`rk = exp((intra_cost − mc_dep_cost) / w)` in the LOG domain per superblock, +divides the frame-level `r0` (`encoder_utils.c:627`, the same expression at +frame scope) by it, and asks `av1_get_deltaq_offset` (`rd.c`) for the qindex +whose **DC** step is `dc_q(base) / sqrt(beta)`; the offset is clamped to +`±(delta_q_res * 9 − 1)`. + +With per-cell costs `intra` and `intra + mc_dep`, `rk = 1/(1 + r)` for this +crate's `r = mc_dep / intra`, so `beta = (1 + r_sb) / (1 + r_frame)` with +`r_frame` read the log-mean way libaom reads `r0`. `encode::deltaq_libaom` +is that; `encode::tpl_frame_ratio` is `r0`. `tpl_lambda_factors` now returns +the raw per-cell ratio beside the lambda factors, because the factor alone has +been through a mean normalisation the ratio cannot be recovered across. + +Two things differ from `deltaq_for_factor` and both are the point: the table +inverted is `dc_q` not `ac_q`, and the ratio is read RAW (`sqrt(1+r)`) rather +than through the log-compressed, `TPL_POWER`-flattened, mean-normalised lambda +factor. + +Self-check: `encode::tests::the_objective_delta_q_mapping_leans_the_right_way_and_stops_at_libaom_s_clamp` +— direction (leaned-on SB finer, idle coarser, average exactly at base), +`res`-congruence of every offset, libaom's clamp reached from both ends, +monotone in strength, and `tpl_frame_ratio` flat-in/flat-out. + +## 3. Sweep — 12-frame `bd_rate_screen_native` (BD vs libaom / rav1e) + +Control reproduces the charter to the digit on all three real rows. + +| arm | film A | film B | screen | +|---|---|---|---| +| control (no delta_q) | +21.0/−4.8 | +24.9/−1.9 | +14.5/−33.2 | +| shipped mapping (`EC_AV1_DELTAQ=2`) | +20.6/−4.8 | +25.4/−1.1 | byte-identical | +| **objective, k=0.25** | **+20.7/−4.8** | **+24.8/−1.7** | byte-identical | +| objective, k=0.5 | +20.6/−4.5 | +25.8/−0.7 | byte-identical | +| objective, k=1.0 | — | +25.9/−0.1 | — | + +At 12 frames the lever is flat at k=0.25 and LOSES at k≥0.5 (film B +0.9/+1.2 +at k=0.5, +1.0/+1.8 at k=1.0 — monotone in strength, so k=1.5 was not run; +`deferred` below). The screen capture is byte-identical at every arm: a frame +that set `allow_screen_content_tools` codes no delta syntax at all +(lane-dq3's content gate), so the keep rule's screen bound is met by +construction, not by luck. + +## 4. Long GOP — 48 pictures, `bd_rate_film_long_gop` (the shape his exports have) + +| arm | film A | film B | +|---|---|---| +| control | +25.2/−7.2 | +86.7/+7.3 | +| shipped mapping | +24.6/−7.3 | +86.1/+7.5 | +| **objective, k=0.25** | **+24.4/−7.5** | **+86.0/+7.3** | +| objective, k=0.5 | +23.8/−7.6 | +86.5/+7.9 | +| objective, k=1.0 | +24.0/−7.0 | +88.4/+9.7 | + +Control reproduces the charter to the digit on both rows. **k=0.25 is the only +arm down on both films on the libaom column with neither rav1e column worse** +(film A −0.8/−0.3, film B −0.7/+0.0): it clears the keep rule's second clause +(one row ≥0.5 down, the other flat inside ±0.3) with room, and the screen row +is out of this gate but byte-identical anyway. k=0.5 buys film A another 0.6 +and hands film B back 0.6 on the rav1e column; k=1.0 is worse than k=0.5 on +three of the four columns. The lever is a LONG-GOP lever, as lane-cen3 +predicted and as the class `short-GOP gate hid the gap` says to expect. + +## 5. Shipped + +* `speed::DELTAQ_RES[0] = 2` (was 4 = off) — preset 0 codes `delta_q_res = 4`. +* `speed::DQ_TPL_K = [0.25, 0, …]` — the objective mapping at strength 0.25, + preset 0 ONLY. Presets 5 and 6 keep `deltaq_for_factor` (`DQ_TPL_K = 0`) + and are byte-identical to before this lane; nothing was measured for them + and nothing changed. +* `EC_AV1_DQ_TPL=0/1` forces the mapping either way, `EC_AV1_DQ_TPL_K` the + strength, `EC_AV1_DQ_CENSUS=1` the instrument. +* Byte pins re-taken with a four-line comment: `(150, 8325 → 8419)`, + `(60, 33014 → 33029)`; green at default and at `EC_AV1_SPEED=6`. + +Spec syntax: unchanged from lane-deltaq — the frame's `delta_q_present` / +`delta_q_res` go through `write_delta_q_params`, the per-SB `delta_qindex` +through `tile::write_delta_q` at the spec's `skip → cdef → delta_q` order, +`delta_lf_present` stays 0, and the encoder's own trial decode reads the frame +back (a desync would refuse, class `refusal-from-own-desync`). + +## Deferred + +* `deferred: objective k=1.5 at 12 frames —` the 12-frame sweep is monotone + worse in k above 0.25 (film B +0.9 at 0.5, +1.0 at 1.0) and long GOP peaks + at 0.25/0.5, so 1.5 cannot win either gate — `unblocked by a reason to + believe the curve turns back up`. +* `deferred: the objective mapping at presets 5 and 6 —` they already ship + `delta_q` through the OLD mapping and are untouched here; a strength for + them is a second sweep on a different preset — `unblocked by a lane that + charters presets 5/6`. +* `deferred: per-level (ARF vs leaf) strength —` lane-cen3 says our top ARF is + the overspent level; a single frame-type-blind strength cannot move quality + toward the key, and this lane deliberately did not re-open the pyramid + offsets — `unblocked by a lane that charters both together`.