forge
Explore
Log in

Don't you dare go Hollow

Per-superblock delta_qindex from the tpl map

Browse files at this commit

1c072fa506f4ef8952add123ef536d813c1bc9a1Ahmet Kaan GümüşParent: 977fcdd
  • feat
    • per-superblock delta_qindex from the tpl map
Show full message
feat(av1): per-superblock delta_qindex from the tpl map

The tpl map only scaled LAMBDA per superblock, so it could move mode
decisions but never the quantizer where the map says a superblock is
worth more. This codes the spec's own per-superblock syntax instead:
delta_q_present with delta_q_res in the frame header, a delta_qindex
symbol group at the first coded block of every superblock, and the
search quantizing (luma and chroma) at that superblock's own qindex.

The mapping is derived, not fitted: RD lambda goes as the square of the
quantizer step, so a superblock the map gives a lambda factor f wants
the qindex whose ac_q is sqrt(f) times the frame's -- inverted through
the ac_q table itself. EC_AV1_DELTAQ (res log2, 0 = off), _K, _CLAMP.

Also: decode_inter_frame_tiles_lr hard-coded DeltaParams::default(),
the stale-header class its own three parameters above it document, so
the encoder's trial decode desynced at the first superblock.
crates/ec-av1/src/decode.rsmodified+13 -2
@@ -34115,7 +34115,7 @@ pub(crate) fn decode_inter_frame_tile(
3411534115 &LoopRestorationParams::default(), initial_cdfs, NO_SIGN_BIAS, false,
3411634116 // `enable_filter_intra`: as the `false`s beside it, this convenience
3411734117 // entry names a stream written without the sequence bit (lane-fintra).
34118- switchable_motion_mode, false, false, fctx,
34118+ switchable_motion_mode, false, false, DeltaParams::default(), fctx,
3411934119 )
3412034120 }
3412134121
@@ -34169,6 +34169,8 @@ pub(crate) fn decode_inter_frame_tile_lr(
3416934169 allow_warped_motion: bool,
3417034170 // lane-fintra: see [`decode_inter_frame_tiles_lr`]'s own parameter.
3417134171 enable_filter_intra: bool,
34172+ // lane-deltaq: see [`decode_inter_frame_tiles_lr`]'s own parameter.
34173+ delta: DeltaParams,
3417234174 fctx: &crate::decode::FrameCtx,
3417334175 ) -> Result<Picture> {
3417434176 let single_tile = TileInfo {
@@ -34200,6 +34202,7 @@ pub(crate) fn decode_inter_frame_tile_lr(
3420034202 switchable_motion_mode,
3420134203 allow_warped_motion,
3420234204 enable_filter_intra,
34205+ delta,
3420334206 fctx,
3420434207 )
3420534208 }
@@ -34247,6 +34250,12 @@ pub(crate) fn decode_inter_frame_tiles_lr(
3424734250 // encoder's own trial decode desyncs at the first intra-in-inter DC_PRED
3424834251 // block the moment its sequence header sets the bit.
3424934252 enable_filter_intra: bool,
34253+ // lane-deltaq: this frame header's own `delta_q_params`/`delta_lf_params`
34254+ // (spec 5.9.17/5.9.18) -- the same stale-header class as the three
34255+ // parameters above. Hard-coded `DeltaParams::default()` here until this
34256+ // lane, which desyncs the encoder's own trial decode at the first
34257+ // superblock the moment its header sets `delta_q_present`.
34258+ delta: DeltaParams,
3425034259 fctx: &crate::decode::FrameCtx,
3425134260 ) -> Result<Picture> {
3425234261 decode_inter_frame_tile_with_cdfs(
@@ -34284,7 +34293,7 @@ pub(crate) fn decode_inter_frame_tiles_lr(
3428434293 switchable_motion_mode,
3428534294 allow_warped_motion,
3428634295 allow_screen_content_tools,
34287- DeltaParams::default(),
34296+ delta,
3428834297 enable_filter_intra,
3428934298 None,
3429034299 fctx,
@@ -38916,6 +38925,7 @@ mod tests {
3891638925 // lane-fintra: the sequence bit the encoder wrote this tile
3891738926 // under -- same stale-header class as the warp bit above.
3891838927 crate::encode::filter_intra_on(),
38928+ frame.delta.clone(),
3891938929 fctx,
3892038930 )
3892138931 .unwrap();
@@ -39260,6 +39270,7 @@ mod tests {
3926039270 // lane-fintra: the sequence bit the encoder wrote this tile
3926139271 // under -- same stale-header class as the warp bit above.
3926239272 crate::encode::filter_intra_on(),
39273+ frame.delta.clone(),
3926339274 fctx,
3926439275 )
3926539276 .unwrap();
crates/ec-av1/src/encode.rsmodified+169 -0
@@ -1073,6 +1073,7 @@ pub(crate) fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> En
10731073 loop_filter: encoded.loop_filter,
10741074 loop_restoration: encoded.loop_restoration,
10751075 allow_intrabc: encoded.allow_intrabc,
1076+ delta: encoded.delta.clone(),
10761077 cdef: encoded.cdef,
10771078 }
10781079 }
@@ -1163,6 +1164,12 @@ pub struct Encoded {
11631164 /// guessed `false` would desync at the first block (same class as
11641165 /// `screen`/`tx_select`).
11651166 pub(crate) allow_intrabc: bool,
1167+ /// This frame header's `delta_q_params`/`delta_lf_params` (spec
1168+ /// 5.9.17/5.9.18) -- with `delta_q_present` every superblock's first
1169+ /// coded block carries a `delta_qindex` symbol group, so a raw tile
1170+ /// decode that guessed the defaults desyncs at the first superblock
1171+ /// (same class as `screen`/`tx_select`).
1172+ pub(crate) delta: ec_av1_syntax::DeltaParams,
11661173 }
11671174
11681175 thread_local! {
@@ -6858,6 +6865,7 @@ pub(crate) fn encode_key_frame_inner(
68586865 cdef: header.cdef,
68596866 loop_restoration: header.loop_restoration,
68606867 allow_intrabc,
6868+ delta: header.delta.clone(),
68616869 })
68626870 }
68636871
@@ -8850,6 +8858,105 @@ fn search_inter_block(
88508858 /// it costs 1.5 ms per 1920x1024 frame against a ~0.8 s encode (0.2%).
88518859 const TPL_STRENGTH: f64 = 0.5;
88528860
8861+/// lane-deltaq: the per-superblock quantizer, `delta_q_present` (spec
8862+/// 5.9.17/5.11.10). `EC_AV1_DELTAQ=0` switches it off (the stream is then
8863+/// byte-identical to the pre-lane one); anything else is the `delta_q_res`
8864+/// LOG2, so `2` is a step of 4 and `3` a step of 8. `None` = off.
8865+///
8866+/// A frame with no tpl map (no lookahead picture, or `EC_AV1_TPL=0`) has
8867+/// nothing to vary the quantizer BY and codes no delta syntax at all.
8868+fn deltaq_res_log2() -> Option<u8> {
8869+ match crate::envflags::var("EC_AV1_DELTAQ").ok().as_deref().map(str::trim) {
8870+ Some("0") => None,
8871+ Some(v) => v.parse::<u8>().ok().filter(|r| *r <= 3),
8872+ None => Some(crate::speed::at(&crate::speed::DELTAQ_RES)).filter(|r| *r < 4),
8873+ }
8874+}
8875+
8876+/// How much of the derived qindex step is actually taken
8877+/// (`EC_AV1_DELTAQ_K`, default 1.0 = the full derivation).
8878+fn deltaq_k() -> f64 {
8879+ crate::envflags::var("EC_AV1_DELTAQ_K")
8880+ .ok()
8881+ .and_then(|v| v.trim().parse::<f64>().ok())
8882+ .filter(|k| k.is_finite() && *k >= 0.0)
8883+ .unwrap_or(1.0)
8884+}
8885+
8886+/// The largest qindex the map may move a superblock by, either way
8887+/// (`EC_AV1_DELTAQ_CLAMP`, default 16 -- libaom clamps its own objective
8888+/// deltaq around a quarter of the base qindex).
8889+fn deltaq_clamp() -> i32 {
8890+ crate::envflags::var("EC_AV1_DELTAQ_CLAMP")
8891+ .ok()
8892+ .and_then(|v| v.trim().parse::<i32>().ok())
8893+ .filter(|c| (0..=63).contains(c))
8894+ .unwrap_or(16)
8895+}
8896+
8897+/// The qindex a lambda factor `f` asks for, derived rather than fitted.
8898+///
8899+/// The tpl map hands out a factor on LAMBDA, and RD lambda goes as the
8900+/// square of the quantizer step (`encode_inter_frame`'s own
8901+/// `lambda = .. * step * step`), so the step this superblock wants is
8902+/// `sqrt(f)` times the frame's. `ac_q` is not linear in the index, so the
8903+/// step ratio is inverted through the table itself -- the index whose `ac_q`
8904+/// is closest to `ac_q(base) * sqrt(f)` -- rather than through a fitted
8905+/// constant. `k` scales the resulting step (1.0 takes all of it), `clamp`
8906+/// bounds it, and the answer is snapped onto the `res` grid so that every
8907+/// superblock's qindex is congruent to `base` and the coded delta is a whole
8908+/// number of steps.
8909+fn deltaq_for_factor(base: u8, f: f64, k: f64, clamp: i32, res: i32) -> u8 {
8910+ let base_ac = f64::from(ac_q(8, i32::from(base)));
8911+ let target = base_ac * f.max(1e-6).sqrt();
8912+ let exact = (1..=255)
8913+ .min_by(|&a, &b| {
8914+ let d = |q: i32| (f64::from(ac_q(8, q)) - target).abs();
8915+ d(a).partial_cmp(&d(b)).expect("ac_q is finite")
8916+ })
8917+ .expect("the qindex range is not empty")
8918+ - i32::from(base);
8919+ let want = (exact as f64 * k).round() as i32;
8920+ // Snapped to the `res` grid BEFORE the clamp: `clamp` is a qindex bound
8921+ // and need not be a whole number of steps, and clamping afterwards would
8922+ // hand back a qindex that is not congruent to `base`.
8923+ let max_steps = clamp / res;
8924+ let steps = (want as f64 / f64::from(res)).round() as i32;
8925+ let delta = steps.clamp(-max_steps, max_steps) * res;
8926+ (i32::from(base) + delta).clamp(1, 255) as u8
8927+}
8928+
8929+/// How many DISTINCT per-superblock quantizer levels the last inter frame's
8930+/// [`sb_q`](encode_inter_frame) grid carried -- lane-deltaq's fire counter
8931+/// (class `gate-blind-to-feature`: every exactness assert below passes on a
8932+/// grid that is one flat value, i.e. on no delta_q at all). Process-global
8933+/// like [`TX_DEPTH_HITS`], and read through [`take_deltaq_levels`], which
8934+/// keeps the LARGEST count seen since the last read.
8935+static DELTAQ_LEVELS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
8936+
8937+/// [`DELTAQ_LEVELS`], reset to 0.
8938+#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
8939+pub(crate) fn take_deltaq_levels() -> usize {
8940+ DELTAQ_LEVELS.swap(0, std::sync::atomic::Ordering::Relaxed)
8941+}
8942+
8943+/// This superblock's search state: the quantizer it is coded at, and the
8944+/// lambda that quantizer implies. RD lambda goes as the square of the step,
8945+/// which is exactly the relation [`deltaq_for_factor`] inverted, so with no
8946+/// `sb_q` grid the caller keeps the tpl LAMBDA factor alone (the behaviour
8947+/// before lane-deltaq).
8948+fn sb_q_search<'m>(
8949+ sb_q: &[u8],
8950+ sb_cols: usize,
8951+ base_q_idx: u8,
8952+ (sb_r, sb_c): (usize, usize),
8953+ base: Search<'m>,
8954+) -> Search<'m> {
8955+ let q = sb_q[sb_r * sb_cols + sb_c];
8956+ let ratio = f64::from(ac_q(8, i32::from(q))) / f64::from(ac_q(8, i32::from(base_q_idx)));
8957+ Search { base_q_idx: q, lambda: base.lambda * ratio * ratio, ..base }
8958+}
8959+
88538960 fn tpl_strength() -> f64 {
88548961 std::env::var("EC_AV1_TPL")
88558962 .ok()
@@ -9516,6 +9623,47 @@ pub(crate) fn encode_inter_frame(
95169623 let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
95179624 let (cols, rows) = (cols as usize, rows as usize);
95189625 let (sb_cols, _sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
9626+ // lane-deltaq: one absolute qindex per 64x64 superblock, from the same
9627+ // tpl map the lambda factor comes from ([`deltaq_for_factor`]). Present
9628+ // only when the map is, and `delta_q_res` follows straight into the frame
9629+ // header (`write_delta_q_params`) and into the tile writer's own plan.
9630+ let deltaq_res: Option<i32> = tpl_factors
9631+ .as_ref()
9632+ .and(deltaq_res_log2().map(|r| 1i32 << r));
9633+ let sb_q: Option<Vec<u8>> = match (&tpl_factors, deltaq_res) {
9634+ (Some(f), Some(res)) => {
9635+ let (k, clamp) = (deltaq_k(), deltaq_clamp());
9636+ Some(
9637+ (0..sb_cols * _sb_rows)
9638+ .map(|sb| {
9639+ let (sb_r, sb_c) = (sb / sb_cols, sb % sb_cols);
9640+ // The same 16-cell mean the superblock's own lambda
9641+ // takes, clamped to the map the frame actually has.
9642+ let mean = (0..16)
9643+ .map(|i| {
9644+ let (cy, cx) = (sb_r * 4 + i / 4, sb_c * 4 + i % 4);
9645+ f[(cy.min(f.len() / tpl_cells_x - 1)) * tpl_cells_x
9646+ + cx.min(tpl_cells_x - 1)]
9647+ })
9648+ .sum::<f64>()
9649+ / 16.0;
9650+ deltaq_for_factor(base_q_idx, mean, k, clamp, res)
9651+ })
9652+ .collect(),
9653+ )
9654+ }
9655+ _ => None,
9656+ };
9657+ if let Some(res) = deltaq_res.filter(|_| sb_q.is_some()) {
9658+ header.delta.q_present = true;
9659+ header.delta.q_res = res.trailing_zeros() as u8;
9660+ }
9661+ if let Some(g) = &sb_q {
9662+ let mut levels: Vec<u8> = g.clone();
9663+ levels.sort_unstable();
9664+ levels.dedup();
9665+ DELTAQ_LEVELS.fetch_max(levels.len(), std::sync::atomic::Ordering::Relaxed);
9666+ }
95199667 let (mi_cols, mi_rows) = (header.mi_cols as usize, header.mi_rows as usize);
95209668 // This frame's tile grid, as in `encode_key_frame_inner`.
95219669 let (tile_cols_log2, tile_rows_log2) = armed_tiles();
@@ -9607,6 +9755,10 @@ pub(crate) fn encode_inter_frame(
96079755 // comparison below weighs one cost against four, so both sides
96089756 // have to be priced at the same lambda.
96099757 let sb_search = match &tpl_factors {
9758+ // lane-deltaq: with a per-superblock quantizer the lambda
9759+ // comes from that quantizer, not from the raw map factor --
9760+ // the two agree exactly at `EC_AV1_DELTAQ_K=1` unclamped.
9761+ Some(_) if sb_q.is_some() => sb_q_search(sb_q.as_ref().expect("armed"), sb_cols, base_q_idx, (sb_r, sb_c), search),
96109762 Some(f) if sb64_legal => {
96119763 let mean = (0..16)
96129764 .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4])
@@ -9705,6 +9857,12 @@ pub(crate) fn encode_inter_frame(
97059857 // one 32x32 cost against four 16x16 ones: a per-leaf lambda
97069858 // would make those two numbers incomparable.
97079859 let search = match &tpl_factors {
9860+ // lane-deltaq: the quantizer is a SUPERBLOCK-level
9861+ // symbol, so all four quadrants take their superblock's
9862+ // own qindex and the lambda it implies. No granularity is
9863+ // lost: the shipped map (`EC_AV1_TPL_SB`) is already one
9864+ // factor per superblock, shared by its sixteen cells.
9865+ Some(_) if sb_q.is_some() => sb_q_search(sb_q.as_ref().expect("armed"), sb_cols, base_q_idx, (sb_r, sb_c), search),
97089866 Some(f) => {
97099867 let mean = (0..4)
97109868 .map(|i| f[(r32 * 2 + i / 2) * tpl_cells_x + c32 * 2 + i % 2])
@@ -10205,6 +10363,12 @@ pub(crate) fn encode_inter_frame(
1020510363 -> Result<Vec<Vec<u8>>> {
1020610364 let (out, stored) = write_tiles(layout.count(), store_tile, |index| {
1020710365 crate::tile::arm_cdef_idx(bits, sb_cols, cdef_grid.to_vec());
10366+ crate::tile::arm_delta_q(
10367+ deltaq_res.filter(|_| sb_q.is_some()).unwrap_or(0),
10368+ sb_cols,
10369+ sb_q.clone().unwrap_or_default(),
10370+ base_q_idx,
10371+ );
1020810372 crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());
1020910373 crate::tile::arm_sign_bias(sign_bias);
1021010374 // Thread-locals: every tile job arms its own worker.
@@ -10341,6 +10505,10 @@ pub(crate) fn encode_inter_frame(
1034110505 switchable_motion_mode,
1034210506 h.allow_warped_motion,
1034310507 seq.enable_filter_intra,
10508+ // lane-deltaq: this frame's own delta_q/delta_lf params, so
10509+ // the trial decode reads the per-superblock `delta_qindex`
10510+ // syntax the writer just wrote.
10511+ h.delta.clone(),
1034410512 fctx,
1034510513 )
1034610514 },
@@ -10383,6 +10551,7 @@ pub(crate) fn encode_inter_frame(
1038310551 // An inter frame never allows intrabc (spec 5.9.2 codes the bit on
1038410552 // intra frames only).
1038510553 allow_intrabc: false,
10554+ delta: header.delta.clone(),
1038610555 })
1038710556 }
1038810557
crates/ec-av1/src/encoder.rsmodified+73 -0
@@ -3466,6 +3466,79 @@ mod tests {
34663466 }
34673467 }
34683468
3469+ /// lane-deltaq's three-way witness: a clip with a real gradient of tpl
3470+ /// factors -- a moving detail region over a flat background, so the
3471+ /// superblocks the NEXT picture predicts from are worth more than the
3472+ /// ones it does not -- codes at least two distinct per-superblock
3473+ /// quantizer levels (the fire count, class `gate-blind-to-feature`), and
3474+ /// both decoders reconstruct every frame sample-exact from the
3475+ /// `delta_qindex` syntax that carries them.
3476+ #[test]
3477+ fn a_moving_detail_clip_codes_two_delta_q_levels_both_decoders_read_exactly() {
3478+ let _knobs = crate::speed::knob_read();
3479+ let _gate_lock = crate::stream::tests::lock_gate_counters();
3480+ let (width, height) = (640usize, 384usize);
3481+ // The gate's own moving test card, with a 128x128 patch of fine
3482+ // detail travelling right by 32 samples a frame laid over it: the
3483+ // patch is what the tpl pass finds worth propagating and the card
3484+ // around it is not, so the map -- and with it the quantizer grid --
3485+ // is a gradient and not one flat number.
3486+ let sources: Vec<Picture> = (0..4)
3487+ .map(|t| {
3488+ let mut p = test_card(width, height, t * 3);
3489+ let x0 = 32 + t * 32;
3490+ for y in 128..256 {
3491+ for x in x0..x0 + 128 {
3492+ p.y[y * width + x] =
3493+ if (x / 2 + y / 3) % 2 == 0 { 40 } else { 210 };
3494+ }
3495+ }
3496+ p
3497+ })
3498+ .collect();
3499+ let config = EncoderConfig {
3500+ width,
3501+ height,
3502+ base_q_idx: 120,
3503+ gop: 4,
3504+ colour: Colour::Bt709Limited,
3505+ tile_cols_log2: 0,
3506+ tile_rows_log2: 0,
3507+ };
3508+ let mut enc = Av1Encoder::new(config).unwrap();
3509+ let _ = crate::encode::take_deltaq_levels();
3510+ let mut stream = Vec::new();
3511+ for packet in encode_all(&mut enc, &sources) {
3512+ stream.extend_from_slice(&packet.data);
3513+ }
3514+ let levels = crate::encode::take_deltaq_levels();
3515+ assert!(
3516+ levels >= 2,
3517+ "the quantizer grid was flat ({levels} level(s)): no delta_qindex was coded"
3518+ );
3519+ let ours = crate::stream::decode_stream(&stream).expect("our decoder");
3520+ assert_eq!(ours.len(), sources.len(), "our decoder's frames");
3521+ if have_ffmpeg() {
3522+ let theirs = ffmpeg_decode_luma(&stream, width, height);
3523+ assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
3524+ for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
3525+ let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
3526+ if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
3527+ panic!(
3528+ "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
3529+ at % width,
3530+ at / width,
3531+ got[at],
3532+ b[at],
3533+ );
3534+ }
3535+ }
3536+ } else {
3537+ eprintln!("SKIP the ffmpeg half: no ffmpeg");
3538+ }
3539+ eprintln!("delta_q witness: {levels} quantizer levels, {} bytes", stream.len());
3540+ }
3541+
34693542 /// Every SHIPPED SPEED PRESET codes a stream both decoders reconstruct
34703543 /// sample-exact -- ours and ffmpeg's -- and codes a DIFFERENT stream from
34713544 /// its neighbour (a preset that changes no byte is a preset that buys no
crates/ec-av1/src/speed.rsmodified+5 -0
@@ -169,6 +169,11 @@ pub(crate) fn at<T: Copy>(table: &[T; 11]) -> T {
169169 /// (screen). So it is on at every preset.
170170 pub(crate) const B64_ROOT: [bool; 11] = [crate::encode::B64_ROOT; 11];
171171
172+/// `encode::deltaq_res_log2`: the per-superblock quantizer's `delta_q_res`
173+/// LOG2 (2 = a step of 4 qindex), or `4` for "no delta_q syntax at all".
174+/// It rides the tpl map, which every preset that keeps the map keeps.
175+pub(crate) const DELTAQ_RES: [u8; 11] = [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2];
176+
172177 /// `encode::SPLIT_RD_THRESHOLD`: how cheap a block has to be before its split
173178 /// trial is withheld. The single biggest wall lever in the tile search.
174179 pub(crate) const SPLIT_RD: [f64; 11] = [
crates/ec-av1/src/tile.rsmodified+87 -0
@@ -282,6 +282,39 @@ pub(crate) fn arm_cdef_idx(bits: u8, sb_cols: usize, grid: Vec<u8>) {
282282 });
283283 }
284284
285+/// One frame's per-superblock quantizer plan (lane-deltaq, see
286+/// [`arm_delta_q`]): the writer side of decode.rs `maybe_read_delta_q`.
287+struct DeltaQPlan {
288+ /// `1 << delta_q_res`, the multiplier the coded symbol is scaled by --
289+ /// every `grid` entry is congruent to `base` modulo it, so the delta the
290+ /// writer codes is always a whole number of steps.
291+ res: i32,
292+ /// Superblocks per row, the stride of `grid`.
293+ sb_cols: usize,
294+ /// The absolute `qindex` each 64x64 superblock is coded at, raster order.
295+ grid: Vec<u8>,
296+ /// The spec's `CurrentQIndex`, carried across the superblocks of THIS
297+ /// tile -- armed at the frame's `base_q_idx` because a tile writer is
298+ /// armed once per tile (`encode_inter_frame`'s `code_tiles`), which is
299+ /// exactly the spec's own per-tile reset.
300+ cur: i32,
301+}
302+
303+thread_local! {
304+ static DELTA_Q: std::cell::RefCell<Option<DeltaQPlan>> =
305+ const { std::cell::RefCell::new(None) };
306+}
307+
308+/// Arms the next tile write with one absolute `qindex` per 64x64 superblock.
309+/// Disarmed (a plain no-op writer, byte for byte what this crate wrote before
310+/// lane-deltaq) when `res == 0`.
311+pub(crate) fn arm_delta_q(res: i32, sb_cols: usize, grid: Vec<u8>, base: u8) {
312+ DELTA_Q.with(|c| {
313+ *c.borrow_mut() =
314+ (res > 0).then(|| DeltaQPlan { res, sb_cols, grid, cur: i32::from(base) });
315+ });
316+}
317+
285318 thread_local! {
286319 static SIGN_BIAS: std::cell::Cell<crate::mvstack::SignBiasTable> =
287320 const { std::cell::Cell::new(crate::mvstack::NO_SIGN_BIAS) };
@@ -1004,6 +1037,7 @@ struct CdefIdxGuard;
10041037 impl Drop for CdefIdxGuard {
10051038 fn drop(&mut self) {
10061039 CDEF_IDX.with(|c| *c.borrow_mut() = None);
1040+ DELTA_Q.with(|c| *c.borrow_mut() = None);
10071041 LR_PLAN.with(|c| *c.borrow_mut() = None);
10081042 SIGN_BIAS.with(|c| c.set(crate::mvstack::NO_SIGN_BIAS));
10091043 SCREEN.with(|c| c.set(false));
@@ -1039,6 +1073,55 @@ fn write_cdef_idx(enc: &mut SymbolEncoder, mi: (usize, usize), skip: bool) {
10391073 });
10401074 }
10411075
1076+/// `read_delta_qindex`'s write side (spec 5.11.10), called right after every
1077+/// block's [`write_cdef_idx`] -- the spec's own `skip -> cdef -> delta_q`
1078+/// order, and decode.rs `maybe_read_delta_q` is the reader this mirrors
1079+/// symbol for symbol. A no-op unless this block sits at its superblock's own
1080+/// top-left mode-info position, and (the one case the reader skips too) when
1081+/// that block IS the whole superblock and is skipped, in which case
1082+/// `CurrentQIndex` carries over unchanged on both sides.
1083+fn write_delta_q(
1084+ enc: &mut SymbolEncoder,
1085+ cdfs: &mut Cdfs,
1086+ mi: (usize, usize),
1087+ is_whole_sb: bool,
1088+ skip: bool,
1089+) {
1090+ DELTA_Q.with(|c| {
1091+ let mut plan = c.borrow_mut();
1092+ let Some(plan) = plan.as_mut() else { return };
1093+ if mi.0 % SB_MI as usize != 0 || mi.1 % SB_MI as usize != 0 {
1094+ return;
1095+ }
1096+ if is_whole_sb && skip {
1097+ return;
1098+ }
1099+ let sb = (mi.0 / SB_MI as usize) * plan.sb_cols + (mi.1 / SB_MI as usize);
1100+ let target = i32::from(plan.grid.get(sb).copied().unwrap_or(0));
1101+ // `reduced` is the spec's `delta_q_abs`/`delta_q_sign_bit` pair: the
1102+ // step count, not the qindex difference.
1103+ let reduced = (target - plan.cur) / plan.res;
1104+ let abs = reduced.unsigned_abs() as usize;
1105+ /// spec `DELTA_Q_SMALL`: the largest `delta_q_abs` symbol that is not
1106+ /// an escape into the literal pair below.
1107+ const DELTA_Q_SMALL: usize = 3;
1108+ enc.symbol(abs.min(DELTA_Q_SMALL), &mut cdfs.delta_q);
1109+ if abs >= DELTA_Q_SMALL {
1110+ // libaom `write_delta_qindex`: `rem_bits = get_msb(abs - 1)`,
1111+ // written one less in three bits, and the value offset by the
1112+ // threshold `(1 << rem_bits) + 1` the reader adds back.
1113+ let rem_bits = 31 - ((abs as u32) - 1).leading_zeros();
1114+ let thr = (1u32 << rem_bits) + 1;
1115+ enc.literal(rem_bits - 1, 3);
1116+ enc.literal(abs as u32 - thr, rem_bits);
1117+ }
1118+ if abs != 0 {
1119+ enc.literal(u32::from(reduced < 0), 1);
1120+ }
1121+ plan.cur = (plan.cur + reduced * plan.res).clamp(1, 255);
1122+ });
1123+}
1124+
10421125 /// round-4 av1-truesize debugging aid: prints `msg()` to stderr when the
10431126 /// `EC_RNG` environment variable is set, mirroring the `EC_PART`/`EC_TOK`
10441127 /// trace `/tmp/libaom-src`'s debug `aomdec` build already emits under the
@@ -5659,6 +5742,7 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
56595742 + usize::from(neighbours.left_skip[mi_r]);
56605743 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
56615744 write_cdef_idx(&mut enc, (mi_r, mi_c), block.skip);
5745+ write_delta_q(&mut enc, &mut cdfs, (mi_r, mi_c), true, block.skip);
56625746 let ii_ctx = intra_inter_ctx(
56635747 has_above,
56645748 has_left,
@@ -6054,6 +6138,7 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
60546138 + usize::from(neighbours.left_skip[mi_r]);
60556139 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
60566140 write_cdef_idx(&mut enc, (mi_r, mi_c), block.skip);
6141+ write_delta_q(&mut enc, &mut cdfs, (mi_r, mi_c), false, block.skip);
60576142
60586143 let is_inter = block.inter.is_some();
60596144 let (above_inter, left_inter) =
@@ -6314,6 +6399,7 @@ fn write_inter_frame_leaf(
63146399 let skip_ctx = usize::from(neighbours.above_skip[mi_c]) + usize::from(neighbours.left_skip[mi_r]);
63156400 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
63166401 write_cdef_idx(enc, (mi_r, mi_c), block.skip);
6402+ write_delta_q(enc, cdfs, (mi_r, mi_c), false, block.skip);
63176403
63186404 let (has_above, has_left) = (neighbours.has_above(mi_r), neighbours.has_left(mi_c));
63196405 let (above_inter, left_inter) = (neighbours.above_inter[mi_c], neighbours.left_inter[mi_r]);
@@ -6564,6 +6650,7 @@ fn write_inter_frame_leaf8(
65646650 let skip_ctx = usize::from(above_skip) + usize::from(left_skip);
65656651 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
65666652 write_cdef_idx(enc, leaf_mi, block.skip);
6653+ write_delta_q(enc, cdfs, leaf_mi, false, block.skip);
65676654
65686655 let (has_above, has_left) = (neighbours.has_above(leaf_mi.0), neighbours.has_left(leaf_mi.1));
65696656 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);