Libaom's objective per-SB delta_q mapping behind EC_AV1_DQ_TPL, plus an EC_AV1_DQ_CENSUS instrument
Browse files at this commit4cfdb9d9fd0071869b42af1bf84f2e6f82c72931Parent: 19e7ef8- feat
- libaom's objective per-SB delta_q mapping behind EC_AV1_DQ_TPL, plus an EC_AV1_DQ_CENSUS instrument
1 changed file +170 -27
- crates/ec-av1/src/encode.rs +170 -27
crates/ec-av1/src/encode.rsmodified+170 -27
| @@ -10435,6 +10435,97 @@ fn deltaq_for_factor(base: u8, f: f64, k: f64, clamp: i32, res: i32) -> u8 { | |||
| 10435 | (i32::from(base) + delta).clamp(1, 255) as u8 | 10435 | (i32::from(base) + delta).clamp(1, 255) as u8 |
| 10436 | } | 10436 | } |
| 10437 | 10437 | ||
| 10438 | +/// lane-dq: derive the per-superblock qindex libaom's `deltaq-mode 1` | ||
| 10439 | +/// objective would, from the SAME tpl dependence ratio our own map already | ||
| 10440 | +/// carries (`EC_AV1_DQ_TPL=1`). | ||
| 10441 | +/// | ||
| 10442 | +/// libaom (`av1_get_q_for_deltaq_objective`, encodeframe_utils.c) forms a | ||
| 10443 | +/// superblock dependence ratio `rk = exp((intra_cost - mc_dep_cost)/w)` in the | ||
| 10444 | +/// LOG domain, divides the frame-level `r0` (`encoder_utils.c:627`, the very | ||
| 10445 | +/// same expression at frame scope) by it, and asks | ||
| 10446 | +/// `av1_get_deltaq_offset(bit_depth, base, beta)` for the qindex whose | ||
| 10447 | +/// **DC** step is `dc_q(base)/sqrt(beta)`. With per-cell costs `intra` and | ||
| 10448 | +/// `intra + mc_dep`, `rk` is `1/(1 + r)` for this crate's `r = mc_dep/intra`, | ||
| 10449 | +/// so `beta = (1 + r_sb) / (1 + r_frame)` with `r_frame` read the log-mean way | ||
| 10450 | +/// libaom reads `r0`. The offset is clamped to libaom's own | ||
| 10451 | +/// `+-(delta_q_res * 9 - 1)`, which at `res = 4` is +-8 steps -- more than | ||
| 10452 | +/// twice the +-16 qindex [`deltaq_for_factor`] allows. | ||
| 10453 | +/// | ||
| 10454 | +/// Two things differ from [`deltaq_for_factor`] and both are the point of the | ||
| 10455 | +/// arm: the table inverted is `dc_q` not `ac_q`, and the ratio is read raw | ||
| 10456 | +/// (`sqrt(1 + r)`) rather than through the map's `log2`-compressed, | ||
| 10457 | +/// `TPL_POWER`-flattened, mean-normalised lambda factor -- so this mapping is | ||
| 10458 | +/// much stronger for the same map. `strength` scales the offset. | ||
| 10459 | +fn deltaq_libaom(base: u8, r_sb: f64, r_frame: f64, strength: f64, res: i32) -> u8 { | ||
| 10460 | + let beta = ((1.0 + r_sb.max(0.0)) / (1.0 + r_frame.max(0.0))).max(1e-6); | ||
| 10461 | + let target = f64::from(crate::quant::dc_q(8, i32::from(base))) / beta.sqrt(); | ||
| 10462 | + let exact = (1..=255) | ||
| 10463 | + .min_by(|&a, &b| { | ||
| 10464 | + let d = |q: i32| (f64::from(crate::quant::dc_q(8, q)) - target).abs(); | ||
| 10465 | + d(a).partial_cmp(&d(b)).expect("dc_q is finite") | ||
| 10466 | + }) | ||
| 10467 | + .expect("the qindex range is not empty") | ||
| 10468 | + - i32::from(base); | ||
| 10469 | + let want = exact as f64 * strength; | ||
| 10470 | + // Snapped onto the `res` grid first, so the coded delta is a whole number | ||
| 10471 | + // of steps, then bounded by libaom's own `res * 9 - 1`. | ||
| 10472 | + let max_steps = (res * 9 - 1) / res; | ||
| 10473 | + let steps = (want / f64::from(res)).round() as i32; | ||
| 10474 | + let delta = steps.clamp(-max_steps, max_steps) * res; | ||
| 10475 | + (i32::from(base) + delta).clamp(1, 255) as u8 | ||
| 10476 | +} | ||
| 10477 | + | ||
| 10478 | +/// The frame-level `r0` libaom's objective divides by: the log-mean of | ||
| 10479 | +/// `1 + r` over the frame's cells, minus 1. | ||
| 10480 | +fn tpl_frame_ratio(ratio: &[f64]) -> f64 { | ||
| 10481 | + if ratio.is_empty() { | ||
| 10482 | + return 0.0; | ||
| 10483 | + } | ||
| 10484 | + let m = ratio.iter().map(|&r| (1.0 + r.max(0.0)).ln()).sum::<f64>() / ratio.len() as f64; | ||
| 10485 | + m.exp() - 1.0 | ||
| 10486 | +} | ||
| 10487 | + | ||
| 10488 | +/// `EC_AV1_DQ_TPL=1`: take the per-superblock qindex from [`deltaq_libaom`] | ||
| 10489 | +/// instead of [`deltaq_for_factor`]. Off by default. | ||
| 10490 | +fn dq_tpl() -> bool { | ||
| 10491 | + crate::envflags::var("EC_AV1_DQ_TPL").ok().as_deref().map(str::trim) == Some("1") | ||
| 10492 | +} | ||
| 10493 | + | ||
| 10494 | +/// The [`deltaq_libaom`] strength multiplier (`EC_AV1_DQ_TPL_K`, default 1.0 | ||
| 10495 | +/// = libaom's own offset). | ||
| 10496 | +fn dq_tpl_k() -> f64 { | ||
| 10497 | + crate::envflags::var("EC_AV1_DQ_TPL_K") | ||
| 10498 | + .ok() | ||
| 10499 | + .and_then(|v| v.trim().parse::<f64>().ok()) | ||
| 10500 | + .filter(|k| k.is_finite() && *k >= 0.0) | ||
| 10501 | + .unwrap_or(1.0) | ||
| 10502 | +} | ||
| 10503 | + | ||
| 10504 | +/// `EC_AV1_DQ_CENSUS=1`: per inter frame, one line comparing the offsets the | ||
| 10505 | +/// shipped mapping ([`deltaq_for_factor`]) WOULD emit against the ones | ||
| 10506 | +/// libaom's objective ([`deltaq_libaom`]) gives for the same superblocks and | ||
| 10507 | +/// the same tpl map -- and which of the two the frame actually coded. | ||
| 10508 | +fn dq_census() -> bool { | ||
| 10509 | + crate::envflags::var("EC_AV1_DQ_CENSUS").ok().as_deref().map(str::trim) == Some("1") | ||
| 10510 | +} | ||
| 10511 | + | ||
| 10512 | +/// The histogram/extent summary [`dq_census`] prints for one set of offsets. | ||
| 10513 | +fn dq_summary(offsets: &[i32]) -> String { | ||
| 10514 | + let n = offsets.len().max(1); | ||
| 10515 | + let (lo, hi) = offsets.iter().fold((0i32, 0i32), |(l, h), &o| (l.min(o), h.max(o))); | ||
| 10516 | + let nz = offsets.iter().filter(|&&o| o != 0).count(); | ||
| 10517 | + let mean = offsets.iter().map(|&o| f64::from(o)).sum::<f64>() / n as f64; | ||
| 10518 | + let absmean = offsets.iter().map(|&o| f64::from(o.abs())).sum::<f64>() / n as f64; | ||
| 10519 | + let mut levels: Vec<i32> = offsets.to_vec(); | ||
| 10520 | + levels.sort_unstable(); | ||
| 10521 | + levels.dedup(); | ||
| 10522 | + format!( | ||
| 10523 | + "range {lo}..{hi} mean {mean:+.2} |mean| {absmean:.2} nonzero {nz}/{} levels {}", | ||
| 10524 | + offsets.len(), | ||
| 10525 | + levels.len() | ||
| 10526 | + ) | ||
| 10527 | +} | ||
| 10528 | + | ||
| 10438 | /// How many DISTINCT per-superblock quantizer levels the last inter frame's | 10529 | /// How many DISTINCT per-superblock quantizer levels the last inter frame's |
| 10439 | /// [`sb_q`](encode_inter_frame) grid carried -- lane-deltaq's fire counter | 10530 | /// [`sb_q`](encode_inter_frame) grid carried -- lane-deltaq's fire counter |
| 10440 | /// (class `gate-blind-to-feature`: every exactness assert below passes on a | 10531 | /// (class `gate-blind-to-feature`: every exactness assert below passes on a |
| @@ -10743,7 +10834,16 @@ fn tpl_sb_factors(map: &[f64], cells_x: usize, cells_y: usize, k: f64) -> Vec<f6 | |||
| 10743 | /// more distortion-averse (smaller lambda), and the frame's TOTAL lambda | 10834 | /// more distortion-averse (smaller lambda), and the frame's TOTAL lambda |
| 10744 | /// scale only moves around, never up or down -- a global move is what | 10835 | /// scale only moves around, never up or down -- a global move is what |
| 10745 | /// lane-av1lambda already measured inert. | 10836 | /// lane-av1lambda already measured inert. |
| 10746 | -fn tpl_lambda_factors(frames: &[&[u8]], width: usize, height: usize, k: f64) -> Vec<f64> { | 10837 | +/// Returns the per-cell lambda factors AND the per-cell dependence ratio |
| 10838 | +/// `mc_dep / intra` they were derived from -- the second half is what | ||
| 10839 | +/// [`deltaq_libaom`] needs, since the factor alone has been through a | ||
| 10840 | +/// mean normalisation the raw ratio cannot be recovered across. | ||
| 10841 | +fn tpl_lambda_factors( | ||
| 10842 | + frames: &[&[u8]], | ||
| 10843 | + width: usize, | ||
| 10844 | + height: usize, | ||
| 10845 | + k: f64, | ||
| 10846 | +) -> (Vec<f64>, Vec<f64>) { | ||
| 10747 | let start = std::time::Instant::now(); | 10847 | let start = std::time::Instant::now(); |
| 10748 | let (cells_x, cells_y) = (width / 16, height / 16); | 10848 | let (cells_x, cells_y) = (width / 16, height / 16); |
| 10749 | let cells = cells_x * cells_y; | 10849 | let cells = cells_x * cells_y; |
| @@ -10862,7 +10962,7 @@ fn tpl_lambda_factors(frames: &[&[u8]], width: usize, height: usize, k: f64) -> | |||
| 10862 | TPL_NANOS.load(std::sync::atomic::Ordering::Relaxed) as f64 / 1e6, | 10962 | TPL_NANOS.load(std::sync::atomic::Ordering::Relaxed) as f64 / 1e6, |
| 10863 | ); | 10963 | ); |
| 10864 | } | 10964 | } |
| 10865 | - out | 10965 | + (out, ratio) |
| 10866 | } | 10966 | } |
| 10867 | 10967 | ||
| 10868 | /// Where one inter frame sits in a coding-order pyramid: which DPB slots its | 10968 | /// Where one inter frame sits in a coding-order pyramid: which DPB slots its |
| @@ -11134,11 +11234,15 @@ pub(crate) fn encode_inter_frame( | |||
| 11134 | let tpl_sources: Vec<Vec<u8>> = | 11234 | let tpl_sources: Vec<Vec<u8>> = |
| 11135 | window.iter().map(|n| n.y.iter().map(|&v| v as u8).collect()).collect(); | 11235 | window.iter().map(|n| n.y.iter().map(|&v| v as u8).collect()).collect(); |
| 11136 | let tpl_cells_x = picture.width / 16; | 11236 | let tpl_cells_x = picture.width / 16; |
| 11137 | - let tpl_factors: Option<Vec<f64>> = (tpl_k > 0.0 && !tpl_sources.is_empty()).then(|| { | 11237 | + // `.1` is the propagating map's raw per-cell dependence ratio, which only |
| 11238 | + // [`deltaq_libaom`] reads; the one-frame area map has no such ratio. | ||
| 11239 | + let tpl_both: Option<(Vec<f64>, Option<Vec<f64>>)> = | ||
| 11240 | + (tpl_k > 0.0 && !tpl_sources.is_empty()).then(|| { | ||
| 11138 | if tpl_propagating() { | 11241 | if tpl_propagating() { |
| 11139 | let mut frames: Vec<&[u8]> = vec![&picture_y8]; | 11242 | let mut frames: Vec<&[u8]> = vec![&picture_y8]; |
| 11140 | frames.extend(tpl_sources.iter().map(Vec::as_slice)); | 11243 | frames.extend(tpl_sources.iter().map(Vec::as_slice)); |
| 11141 | - tpl_lambda_factors(&frames, picture.width, picture.height, tpl_k) | 11244 | + let (f, r) = tpl_lambda_factors(&frames, picture.width, picture.height, tpl_k); |
| 11245 | + (f, Some(r)) | ||
| 11142 | } else { | 11246 | } else { |
| 11143 | // The shipped map is one factor per 64x64; it is spread over that | 11247 | // The shipped map is one factor per 64x64; it is spread over that |
| 11144 | // superblock's own 16 cells so the application site below (which | 11248 | // superblock's own 16 cells so the application site below (which |
| @@ -11148,11 +11252,16 @@ pub(crate) fn encode_inter_frame( | |||
| 11148 | tpl_area_map(&picture_y8, &tpl_sources[0], picture.width, picture.height); | 11252 | tpl_area_map(&picture_y8, &tpl_sources[0], picture.width, picture.height); |
| 11149 | let cells_y = picture.height / 16; | 11253 | let cells_y = picture.height / 16; |
| 11150 | let sb = tpl_sb_factors(&map, tpl_cells_x, cells_y, tpl_k); | 11254 | let sb = tpl_sb_factors(&map, tpl_cells_x, cells_y, tpl_k); |
| 11151 | - (0..tpl_cells_x * cells_y) | 11255 | + let f: Vec<f64> = (0..tpl_cells_x * cells_y) |
| 11152 | .map(|c| sb[(c / tpl_cells_x / 4) * (tpl_cells_x / 4) + (c % tpl_cells_x) / 4]) | 11256 | .map(|c| sb[(c / tpl_cells_x / 4) * (tpl_cells_x / 4) + (c % tpl_cells_x) / 4]) |
| 11153 | - .collect() | 11257 | + .collect(); |
| 11258 | + (f, None) | ||
| 11154 | } | 11259 | } |
| 11155 | }); | 11260 | }); |
| 11261 | + let (tpl_factors, tpl_ratio) = match tpl_both { | ||
| 11262 | + Some((f, r)) => (Some(f), r), | ||
| 11263 | + None => (None, None), | ||
| 11264 | + }; | ||
| 11156 | 11265 | ||
| 11157 | // The true grid ([`crate::tile::block_grid`]'s ceiling), not the padded | 11266 | // The true grid ([`crate::tile::block_grid`]'s ceiling), not the padded |
| 11158 | // coding surface's: `blocks` carries one entry per 32x32 block the tile | 11267 | // coding surface's: `blocks` carries one entry per 32x32 block the tile |
| @@ -11175,30 +11284,64 @@ pub(crate) fn encode_inter_frame( | |||
| 11175 | .as_ref() | 11284 | .as_ref() |
| 11176 | .filter(|_| !screen) | 11285 | .filter(|_| !screen) |
| 11177 | .and(deltaq_res_log2().map(|r| 1i32 << r)); | 11286 | .and(deltaq_res_log2().map(|r| 1i32 << r)); |
| 11287 | + // The same 16-cell mean the superblock's own lambda takes, clamped to the | ||
| 11288 | + // map the frame actually has -- read over the factors or over the raw | ||
| 11289 | + // dependence ratios, whichever mapping is asking. | ||
| 11290 | + let sb_mean = |m: &[f64], sb: usize| { | ||
| 11291 | + let (sb_r, sb_c) = (sb / sb_cols, sb % sb_cols); | ||
| 11292 | + (0..16) | ||
| 11293 | + .map(|i| { | ||
| 11294 | + let (cy, cx) = (sb_r * 4 + i / 4, sb_c * 4 + i % 4); | ||
| 11295 | + m[(cy.min(m.len() / tpl_cells_x - 1)) * tpl_cells_x + cx.min(tpl_cells_x - 1)] | ||
| 11296 | + }) | ||
| 11297 | + .sum::<f64>() | ||
| 11298 | + / 16.0 | ||
| 11299 | + }; | ||
| 11300 | + // lane-dq: `EC_AV1_DQ_TPL=1` takes libaom's own objective mapping off the | ||
| 11301 | + // raw dependence ratio; without it (and always without a ratio map, i.e. | ||
| 11302 | + // on the one-frame area map) the shipped derivation stands. | ||
| 11303 | + let r_frame = tpl_ratio.as_deref().map(tpl_frame_ratio); | ||
| 11304 | + let sb_qindex = |f: &[f64], res: i32, sb: usize, libaom: bool| -> u8 { | ||
| 11305 | + match (libaom, tpl_ratio.as_deref(), r_frame) { | ||
| 11306 | + (true, Some(r), Some(rf)) => { | ||
| 11307 | + deltaq_libaom(base_q_idx, sb_mean(r, sb), rf, dq_tpl_k(), res) | ||
| 11308 | + } | ||
| 11309 | + _ => deltaq_for_factor(base_q_idx, sb_mean(f, sb), deltaq_k(), deltaq_clamp(), res), | ||
| 11310 | + } | ||
| 11311 | + }; | ||
| 11178 | let sb_q: Option<Vec<u8>> = match (&tpl_factors, deltaq_res) { | 11312 | let sb_q: Option<Vec<u8>> = match (&tpl_factors, deltaq_res) { |
| 11179 | (Some(f), Some(res)) => { | 11313 | (Some(f), Some(res)) => { |
| 11180 | - let (k, clamp) = (deltaq_k(), deltaq_clamp()); | 11314 | + let libaom = dq_tpl(); |
| 11181 | - Some( | 11315 | + Some((0..sb_cols * _sb_rows).map(|sb| sb_qindex(f, res, sb, libaom)).collect()) |
| 11182 | - (0..sb_cols * _sb_rows) | ||
| 11183 | - .map(|sb| { | ||
| 11184 | - let (sb_r, sb_c) = (sb / sb_cols, sb % sb_cols); | ||
| 11185 | - // The same 16-cell mean the superblock's own lambda | ||
| 11186 | - // takes, clamped to the map the frame actually has. | ||
| 11187 | - let mean = (0..16) | ||
| 11188 | - .map(|i| { | ||
| 11189 | - let (cy, cx) = (sb_r * 4 + i / 4, sb_c * 4 + i % 4); | ||
| 11190 | - f[(cy.min(f.len() / tpl_cells_x - 1)) * tpl_cells_x | ||
| 11191 | - + cx.min(tpl_cells_x - 1)] | ||
| 11192 | - }) | ||
| 11193 | - .sum::<f64>() | ||
| 11194 | - / 16.0; | ||
| 11195 | - deltaq_for_factor(base_q_idx, mean, k, clamp, res) | ||
| 11196 | - }) | ||
| 11197 | - .collect(), | ||
| 11198 | - ) | ||
| 11199 | } | 11316 | } |
| 11200 | _ => None, | 11317 | _ => None, |
| 11201 | }; | 11318 | }; |
| 11319 | + // lane-dq census: both mappings on the SAME superblocks, whether or not | ||
| 11320 | + // the frame codes any delta syntax (`deltaq_res` is `None` with the lever | ||
| 11321 | + // off, and the census then prices the default `res = 4` grid). | ||
| 11322 | + if dq_census() { | ||
| 11323 | + if let Some(f) = &tpl_factors { | ||
| 11324 | + let res = deltaq_res.unwrap_or(4); | ||
| 11325 | + let off = |libaom: bool| -> Vec<i32> { | ||
| 11326 | + (0..sb_cols * _sb_rows) | ||
| 11327 | + .map(|sb| i32::from(sb_qindex(f, res, sb, libaom)) - i32::from(base_q_idx)) | ||
| 11328 | + .collect() | ||
| 11329 | + }; | ||
| 11330 | + let (ours, aom) = (off(false), off(true)); | ||
| 11331 | + let coded = if deltaq_res.is_some() { | ||
| 11332 | + if dq_tpl() { "libaom" } else { "ours" } | ||
| 11333 | + } else { | ||
| 11334 | + "none" | ||
| 11335 | + }; | ||
| 11336 | + eprintln!( | ||
| 11337 | + "dq census: base={base_q_idx} res={res} sbs={} coded={coded} r_frame={:.4}\n ours {}\n libaom {}", | ||
| 11338 | + sb_cols * _sb_rows, | ||
| 11339 | + r_frame.unwrap_or(f64::NAN), | ||
| 11340 | + dq_summary(&ours), | ||
| 11341 | + dq_summary(&aom), | ||
| 11342 | + ); | ||
| 11343 | + } | ||
| 11344 | + } | ||
| 11202 | if let Some(res) = deltaq_res.filter(|_| sb_q.is_some()) { | 11345 | if let Some(res) = deltaq_res.filter(|_| sb_q.is_some()) { |
| 11203 | header.delta.q_present = true; | 11346 | header.delta.q_present = true; |
| 11204 | header.delta.q_res = res.trailing_zeros() as u8; | 11347 | header.delta.q_res = res.trailing_zeros() as u8; |
| @@ -12651,7 +12794,7 @@ mod tests { | |||
| 12651 | let (w, h) = (256usize, 64usize); | 12794 | let (w, h) = (256usize, 64usize); |
| 12652 | let uniform: Vec<u8> = (0..w * h).map(|i| ((i * 37) % 251) as u8).collect(); | 12795 | let uniform: Vec<u8> = (0..w * h).map(|i| ((i * 37) % 251) as u8).collect(); |
| 12653 | let frames: Vec<&[u8]> = vec![&uniform, &uniform, &uniform]; | 12796 | let frames: Vec<&[u8]> = vec![&uniform, &uniform, &uniform]; |
| 12654 | - let f = super::tpl_lambda_factors(&frames, w, h, 1.0); | 12797 | + let (f, _) = super::tpl_lambda_factors(&frames, w, h, 1.0); |
| 12655 | assert_eq!(f.len(), 64, "16x4 cells of 16x16"); | 12798 | assert_eq!(f.len(), 64, "16x4 cells of 16x16"); |
| 12656 | for (i, &v) in f.iter().enumerate() { | 12799 | for (i, &v) in f.iter().enumerate() { |
| 12657 | assert!((v - 1.0).abs() < 1e-6, "cell {i} factor {v}, a flat map must move no lambda"); | 12800 | assert!((v - 1.0).abs() < 1e-6, "cell {i} factor {v}, a flat map must move no lambda"); |
| @@ -12665,7 +12808,7 @@ mod tests { | |||
| 12665 | let frames: Vec<&[u8]> = vec![&split, &split, &split]; | 12808 | let frames: Vec<&[u8]> = vec![&split, &split, &split]; |
| 12666 | let cells_x = w / 16; | 12809 | let cells_x = w / 16; |
| 12667 | for k in [0.25f64, 0.5, 1.0, 2.0] { | 12810 | for k in [0.25f64, 0.5, 1.0, 2.0] { |
| 12668 | - let f = super::tpl_lambda_factors(&frames, w, h, k); | 12811 | + let (f, _) = super::tpl_lambda_factors(&frames, w, h, k); |
| 12669 | for r in 0..h / 16 { | 12812 | for r in 0..h / 16 { |
| 12670 | let (lean, idle) = (f[r * cells_x], f[r * cells_x + cells_x - 1]); | 12813 | let (lean, idle) = (f[r * cells_x], f[r * cells_x + cells_x - 1]); |
| 12671 | assert!(lean < 1.0, "k={k} row {r}: leaned-on cell factor {lean} must be < 1"); | 12814 | assert!(lean < 1.0, "k={k} row {r}: leaned-on cell factor {lean} must be < 1"); |