forge
Explore
Log in

Don't you dare go Hollow

The encoder codes one CDEF strength per 64x64 superblock

Browse files at this commit

93429cb5f55047a0bd1f01ef2a58e784aa68cd36Ahmet Kaan GümüşParent: 1b6265b
  • feat
    • the encoder codes one CDEF strength per 64x64 superblock
Show full message
feat(av1): the encoder codes one CDEF strength per 64x64 superblock

The filter search only ever wrote `cdef_bits = 0`: one strength pair for
the whole frame, because a per-unit choice needs a `cdef_idx` literal in
the tile payload and the whole-frame re-decode the search runs cannot
reach one.

It can. Every candidate the coordinate search already decodes carries
its own error PER 64x64 unit, so the pool of strength pairs tried under
the winning deblocking levels doubles as libaom `av1_cdef_search`'s
preset list: the units vote, the list grows by that histogram, and the
cheapest list length wins on error plus lambda times the literals it
costs. The tile is then written a second time with those literals
(`tile::arm_cdef_idx`, mirroring the decoder's own `cdef_transmitted`
slot) and the winner re-decoded from it, so the encoder's reference
frame is still exactly what a decoder reconstructs.

The BD gate prints the per-clip `cdef_bits` distribution and how many
64x64 units left the default preset.
crates/ec-av1/src/encode.rsmodified+82 -13
@@ -3024,9 +3024,10 @@ pub(crate) fn encode_key_frame_inner(
3024 3024
3025 #[cfg(test)]3025 #[cfg(test)]
3026 record_predicted_bits(crate::tile::predicted_coeff_bits_sb(&superblocks, base_q_idx));3026 record_predicted_bits(crate::tile::predicted_coeff_bits_sb(&superblocks, base_q_idx));
3027- let tile = crate::tile::sb_coeff_key_frame_tile_tx(3027+ let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
3028- header.mi_cols,3028+ let mut tile = crate::tile::sb_coeff_key_frame_tile_tx(
3029- header.mi_rows,3029+ mi_cols,
3030+ mi_rows,
3030 base_q_idx,3031 base_q_idx,
3031 &superblocks,3032 &superblocks,
3032 tx_select,3033 tx_select,
@@ -3042,9 +3043,21 @@ pub(crate) fn encode_key_frame_inner(
3042 &mut chroma,3043 &mut chroma,
3043 [&picture_y8, &picture_u8, &picture_v8],3044 [&picture_y8, &picture_u8, &picture_v8],
3044 true,3045 true,
3045- |lf, cdef, h| {3046+ &mut tile,
3047+ search.lambda,
3048+ |bits, sb_cols, grid| {
3049+ crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());
3050+ crate::tile::sb_coeff_key_frame_tile_tx(
3051+ mi_cols,
3052+ mi_rows,
3053+ base_q_idx,
3054+ &superblocks,
3055+ tx_select,
3056+ )
3057+ },
3058+ |lf, cdef, h, tile| {
3046 crate::decode::decode_key_frame_tile(3059 crate::decode::decode_key_frame_tile(
3047- &tile,3060+ tile,
3048 h.mi_cols,3061 h.mi_cols,
3049 h.mi_rows,3062 h.mi_rows,
3050 base_q_idx,3063 base_q_idx,
@@ -3107,7 +3120,14 @@ fn pick_and_apply_filters(
3107 chroma: &mut [Plane<'_>; 2],3120 chroma: &mut [Plane<'_>; 2],
3108 source: [&[u8]; 3],3121 source: [&[u8]; 3],
3109 search: bool,3122 search: bool,
3110- decode: impl Fn(&LoopFilterParams, &CdefParams, &FrameHeader) -> Result<Picture>,3123+ // The coded tile, replaced in place when the search chooses a per-64x64
3124+ // `cdef_idx` list (`cdef_bits > 0`): those literals live in the tile
3125+ // payload, so the tile is written a second time under `recode` and the
3126+ // winner re-decoded from it.
3127+ tile: &mut Vec<u8>,
3128+ lambda: f64,
3129+ recode: impl Fn(u8, usize, &[u8]) -> Result<Vec<u8>>,
3130+ decode: impl Fn(&LoopFilterParams, &CdefParams, &FrameHeader, &[u8]) -> Result<Picture>,
3111 ) -> Result<()> {3131 ) -> Result<()> {
3112 if !search {3132 if !search {
3113 return Ok(());3133 return Ok(());
@@ -3117,15 +3137,27 @@ fn pick_and_apply_filters(
3117 // libaom `av1_pick_filter_level`'s sibling `av1_cdef_search`:3137 // libaom `av1_pick_filter_level`'s sibling `av1_cdef_search`:
3118 // `cdef_damping = 3 + (base_qindex >> 6)`, never searched.3138 // `cdef_damping = 3 + (base_qindex >> 6)`, never searched.
3119 let damping = 3 + (header.quantization.base_q_idx >> 6);3139 let damping = 3 + (header.quantization.base_q_idx >> 6);
3120- let (lf, cdef, filtered) = crate::filter_search::pick_filters(3140+ let (cols32, rows32) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
3121- |lf, cdef| decode(lf, cdef, &hdr),3141+ let (sb_cols, sb_rows) = (cols32.div_ceil(2) as usize, rows32.div_ceil(2) as usize);
3142+ let (lf, cdef, idx_grid, picture) = crate::filter_search::pick_filters(
3143+ |lf, cdef| decode(lf, cdef, &hdr, tile),
3122 source,3144 source,
3123 luma.width,3145 luma.width,
3124 (fw, fh),3146 (fw, fh),
3125 damping,3147 damping,
3148+ (sb_cols, sb_rows),
3149+ lambda,
3126 )?;3150 )?;
3127 header.loop_filter = lf;3151 header.loop_filter = lf;
3128 header.cdef = cdef;3152 header.cdef = cdef;
3153+ let filtered = if idx_grid.is_empty() {
3154+ picture
3155+ } else {
3156+ let coded = recode(cdef.bits, sb_cols, &idx_grid)?;
3157+ let picture = decode(&lf, &cdef, &hdr, &coded)?;
3158+ *tile = coded;
3159+ picture
3160+ };
3129 let dec_cw = filtered.width.div_ceil(2);3161 let dec_cw = filtered.width.div_ceil(2);
3130 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));3162 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));
3131 crate::filter_search::splice(&mut luma.reconstruction, luma.width, &filtered.y, filtered.width, fw, fh);3163 crate::filter_search::splice(&mut luma.reconstruction, luma.width, &filtered.y, filtered.width, fw, fh);
@@ -4194,9 +4226,10 @@ pub(crate) fn encode_inter_frame(
4194 / modes.len() as f64;4226 / modes.len() as f64;
4195 #[cfg(test)]4227 #[cfg(test)]
4196 record_predicted_bits(crate::tile::predicted_coeff_bits(&blocks, base_q_idx));4228 record_predicted_bits(crate::tile::predicted_coeff_bits(&blocks, base_q_idx));
4197- let tile = crate::tile::sb_coeff_inter_frame_tile_tx(4229+ let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
4198- header.mi_cols,4230+ let mut tile = crate::tile::sb_coeff_inter_frame_tile_tx(
4199- header.mi_rows,4231+ mi_cols,
4232+ mi_rows,
4200 base_q_idx,4233 base_q_idx,
4201 &blocks,4234 &blocks,
4202 tx_select,4235 tx_select,
@@ -4234,9 +4267,21 @@ pub(crate) fn encode_inter_frame(
4234 // `TxMode::Select` too (it used to skip and leave every inter frame4267 // `TxMode::Select` too (it used to skip and leave every inter frame
4235 // unfiltered once Select became the default).4268 // unfiltered once Select became the default).
4236 true,4269 true,
4237- |lf, cdef, h| {4270+ &mut tile,
4271+ search.lambda,
4272+ |bits, sb_cols, grid| {
4273+ crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());
4274+ crate::tile::sb_coeff_inter_frame_tile_tx(
4275+ mi_cols,
4276+ mi_rows,
4277+ base_q_idx,
4278+ &blocks,
4279+ tx_select,
4280+ )
4281+ },
4282+ |lf, cdef, h, tile| {
4238 crate::decode::decode_inter_frame_tile(4283 crate::decode::decode_inter_frame_tile(
4239- &tile,4284+ tile,
4240 h.mi_cols,4285 h.mi_cols,
4241 h.mi_rows,4286 h.mi_rows,
4242 base_q_idx,4287 base_q_idx,
@@ -7218,6 +7263,30 @@ mod tests {
7218 mean(|l| l.2.0),7263 mean(|l| l.2.0),
7219 mean(|l| l.2.1),7264 mean(|l| l.2.1),
7220 );7265 );
7266+ // How many strength presets each frame's CDEF list carried and
7267+ // how the 64x64 units spread over them (lane-av1lr): `bits 0`
7268+ // everywhere would mean the per-unit choice never fires.
7269+ let presets = crate::filter_search::take_cdef_presets();
7270+ let mut by_bits = [0usize; 4];
7271+ for (b, _) in &presets {
7272+ by_bits[usize::from(*b)] += 1;
7273+ }
7274+ let units: usize = presets.iter().flat_map(|(_, c)| c).sum();
7275+ let on_extra: usize = presets
7276+ .iter()
7277+ .flat_map(|(_, c)| c.iter().skip(1))
7278+ .sum();
7279+ eprintln!(
7280+ "{name}: cdef_bits frames {}/{}/{}/{} (0/1/2/3); {} of {} 64x64 units \
7281+ on a non-default preset ({:.1}%)",
7282+ by_bits[0],
7283+ by_bits[1],
7284+ by_bits[2],
7285+ by_bits[3],
7286+ on_extra,
7287+ units,
7288+ 100.0 * on_extra as f64 / units.max(1) as f64
7289+ );
7221 // Which chroma modes the search actually wins with, against the7290 // Which chroma modes the search actually wins with, against the
7222 // unconditional DC_PRED that was the only outcome before7291 // unconditional DC_PRED that was the only outcome before
7223 // (gate-blind-to-feature).7292 // (gate-blind-to-feature).
crates/ec-av1/src/filter_search.rsmodified+142 -3
@@ -40,6 +40,20 @@ pub(crate) fn take_chosen_levels() -> Vec<((u8, u8), (u8, u8), (u8, u8))> {
40 })40 })
41 }41 }
42 42
43+thread_local! {
44+ /// Per frame, in coding order: the `cdef_bits` chosen and how many 64x64
45+ /// superblocks ended up on each strength preset -- the BD gate prints the
46+ /// distribution once per clip (gate-blind-to-feature).
47+ static PRESET_COUNTS: std::cell::RefCell<Vec<(u8, Vec<usize>)>> =
48+ const { std::cell::RefCell::new(Vec::new()) };
49+}
50+
51+/// Takes and clears [`PRESET_COUNTS`].
52+#[allow(dead_code)] // read from the `#[cfg(test)]` BD gate
53+pub(crate) fn take_cdef_presets() -> Vec<(u8, Vec<usize>)> {
54+ PRESET_COUNTS.with(|c| std::mem::take(&mut *c.borrow_mut()))
55+}
56+
43 /// Squared error between a decoded plane and the source it was coded from,57 /// Squared error between a decoded plane and the source it was coded from,
44 /// over the frame's own cropped `w x h` (the two planes have different58 /// over the frame's own cropped `w x h` (the two planes have different
45 /// strides: the source is the encoder's padded coding surface).59 /// strides: the source is the encoder's padded coding surface).
@@ -55,6 +69,31 @@ fn plane_sse(dec: &[u16], dec_w: usize, src: &[u8], src_w: usize, w: usize, h: u
55 sse69 sse
56 }70 }
57 71
72+/// [`plane_sse`], accumulated per CDEF unit instead of over the frame: `out`
73+/// is one entry per 64x64 SUPERBLOCK (stride `sb_cols`) and `unit` is the
74+/// unit side in this plane's own samples (64 for luma, 32 for 4:2:0 chroma),
75+/// which is what makes the luma and chroma sums land in the same slot.
76+fn unit_sse(
77+ dec: &[u16],
78+ dec_w: usize,
79+ src: &[u8],
80+ src_w: usize,
81+ w: usize,
82+ h: usize,
83+ unit: usize,
84+ sb_cols: usize,
85+ out: &mut [u64],
86+) {
87+ for row in 0..h {
88+ let base = (row / unit) * sb_cols;
89+ let (d, s) = (&dec[row * dec_w..][..w], &src[row * src_w..][..w]);
90+ for (col, (&a, &b)) in d.iter().zip(s).enumerate() {
91+ let diff = i64::from(a) - i64::from(b);
92+ out[base + col / unit] += (diff * diff) as u64;
93+ }
94+ }
95+}
96+
58 /// CDEF primary strengths tried (libaom's own range is 0..15 for 8-bit97 /// CDEF primary strengths tried (libaom's own range is 0..15 for 8-bit
59 /// content) and the secondary ladder, whose only legal values are 0, 1, 298 /// content) and the secondary ladder, whose only legal values are 0, 1, 2
60 /// and 4 -- 3 is not codeable (spec 5.9.19 codes a secondary strength of 499 /// and 4 -- 3 is not codeable (spec 5.9.19 codes a secondary strength of 4
@@ -82,6 +121,10 @@ struct Trial {
82 picture: Picture,121 picture: Picture,
83 sse_y: u64,122 sse_y: u64,
84 sse_uv: u64,123 sse_uv: u64,
124+ /// Luma + chroma error per 64x64 CDEF unit, in the tile writer's own
125+ /// superblock raster order -- what the per-unit `cdef_idx` choice below
126+ /// is made on.
127+ sse64: Vec<u64>,
85 }128 }
86 129
87 /// Picks this frame's deblocking levels and CDEF strengths and hands back130 /// Picks this frame's deblocking levels and CDEF strengths and hands back
@@ -111,8 +154,11 @@ pub(crate) fn pick_filters(
111 src_w: usize,154 src_w: usize,
112 (fw, fh): (usize, usize),155 (fw, fh): (usize, usize),
113 damping: u8,156 damping: u8,
114-) -> Result<(LoopFilterParams, CdefParams, Picture)> {157+ (sb_cols, sb_rows): (usize, usize),
158+ lambda: f64,
159+) -> Result<(LoopFilterParams, CdefParams, Vec<u8>, Picture)> {
115 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));160 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));
161+ let nsb = sb_cols * sb_rows;
116 let mut trials: Vec<Trial> = Vec::new();162 let mut trials: Vec<Trial> = Vec::new();
117 let eval = |cand: Cand, trials: &mut Vec<Trial>| -> Result<usize> {163 let eval = |cand: Cand, trials: &mut Vec<Trial>| -> Result<usize> {
118 if let Some(i) = trials.iter().position(|t| t.cand == cand) {164 if let Some(i) = trials.iter().position(|t| t.cand == cand) {
@@ -123,7 +169,11 @@ pub(crate) fn pick_filters(
123 let sse_y = plane_sse(&picture.y, picture.width, source[0], src_w, fw, fh);169 let sse_y = plane_sse(&picture.y, picture.width, source[0], src_w, fw, fh);
124 let sse_uv = plane_sse(&picture.u, dec_cw, source[1], src_w / 2, cw, ch)170 let sse_uv = plane_sse(&picture.u, dec_cw, source[1], src_w / 2, cw, ch)
125 + plane_sse(&picture.v, dec_cw, source[2], src_w / 2, cw, ch);171 + plane_sse(&picture.v, dec_cw, source[2], src_w / 2, cw, ch);
126- trials.push(Trial { cand, picture, sse_y, sse_uv });172+ let mut sse64 = vec![0u64; nsb];
173+ unit_sse(&picture.y, picture.width, source[0], src_w, fw, fh, 64, sb_cols, &mut sse64);
174+ unit_sse(&picture.u, dec_cw, source[1], src_w / 2, cw, ch, 32, sb_cols, &mut sse64);
175+ unit_sse(&picture.v, dec_cw, source[2], src_w / 2, cw, ch, 32, sb_cols, &mut sse64);
176+ trials.push(Trial { cand, picture, sse_y, sse_uv, sse64 });
127 Ok(trials.len() - 1)177 Ok(trials.len() - 1)
128 };178 };
129 // One stage of the coordinate search: try `values` in the slot `set`179 // One stage of the coordinate search: try `values` in the slot `set`
@@ -168,11 +218,100 @@ pub(crate) fn pick_filters(
168 stage(&mut best, &CDEF_SEC, |c, v| c.uv.1 = v, |t| t.sse_uv, &mut trials)?;218 stage(&mut best, &CDEF_SEC, |c, v| c.uv.1 = v, |t| t.sse_uv, &mut trials)?;
169 219
170 CHOSEN.with(|c| c.borrow_mut().push(best));220 CHOSEN.with(|c| c.borrow_mut().push(best));
221+
222+ // libaom `av1_cdef_search`'s shape, on the candidates this coordinate
223+ // search already decoded: every trial that ran under the WINNING
224+ // deblocking levels is a legal strength pair for this frame, and each
225+ // one already carries its own per-64x64 error. Pick up to eight of them
226+ // as the header's strength list and give every superblock the one that
227+ // costs it least -- the `cdef_idx` literal the tile writer then codes
228+ // (`crate::tile::arm_cdef_idx`).
229+ let mut presets: Vec<Cand> = vec![best];
230+ let pool: Vec<Cand> = trials
231+ .iter()
232+ .map(|t| t.cand)
233+ .filter(|c| c.lf == best.lf && *c != best)
234+ .collect();
235+ // How often each pool candidate would win a superblock outright, which
236+ // is the order the list is grown in (libaom picks its presets by the
237+ // same per-unit histogram, not by frame-level error).
238+ let sse_of = |c: &Cand| -> &Vec<u64> {
239+ &trials
240+ .iter()
241+ .find(|t| t.cand == *c)
242+ .expect("every pool candidate was evaluated")
243+ .sse64
244+ };
245+ let mut counts = vec![0usize; pool.len()];
246+ let best_sse = sse_of(&best).clone();
247+ for sb in 0..nsb {
248+ let mut winner = (best_sse[sb], usize::MAX);
249+ for (i, c) in pool.iter().enumerate() {
250+ if sse_of(c)[sb] < winner.0 {
251+ winner = (sse_of(c)[sb], i);
252+ }
253+ }
254+ if winner.1 != usize::MAX {
255+ counts[winner.1] += 1;
256+ }
257+ }
258+ let mut order: Vec<usize> = (0..pool.len()).collect();
259+ order.sort_by_key(|&i| std::cmp::Reverse(counts[i]));
260+ presets.extend(order.iter().take(7).map(|&i| pool[i]));
261+ // The cheapest list length: `bits` costs one literal per superblock plus
262+ // twelve header bits per extra pair, and buys whatever per-unit error the
263+ // wider choice removes.
264+ let unit_min = |n: usize, sb: usize| -> u64 {
265+ presets[..n].iter().map(|c| sse_of(c)[sb]).min().unwrap_or(0)
266+ };
267+ let mut bits = 0u8;
268+ let mut cost = best_sse.iter().sum::<u64>() as f64;
269+ for b in 1..=3u8 {
270+ let n = 1usize << b;
271+ if n > presets.len() {
272+ break;
273+ }
274+ let sse: u64 = (0..nsb).map(|sb| unit_min(n, sb)).sum();
275+ let c = sse as f64 + lambda * ((b as usize * nsb) as f64 + 12.0 * (n - 1) as f64);
276+ if c < cost {
277+ cost = c;
278+ bits = b;
279+ }
280+ }
281+ let grid: Vec<u8> = if bits == 0 {
282+ Vec::new()
283+ } else {
284+ let n = 1usize << bits;
285+ (0..nsb)
286+ .map(|sb| {
287+ (0..n)
288+ .min_by_key(|&i| sse_of(&presets[i])[sb])
289+ .expect("at least one preset") as u8
290+ })
291+ .collect()
292+ };
293+ let mut params = cdef(best, damping);
294+ params.bits = bits;
295+ for (i, c) in presets.iter().take(1usize << bits).enumerate() {
296+ params.y_pri_strength[i] = c.y.0;
297+ params.y_sec_strength[i] = c.y.1;
298+ params.uv_pri_strength[i] = c.uv.0;
299+ params.uv_sec_strength[i] = c.uv.1;
300+ }
301+ let mut counts_used = vec![0usize; 1usize << bits];
302+ for &g in &grid {
303+ counts_used[usize::from(g)] += 1;
304+ }
305+ if grid.is_empty() {
306+ counts_used = vec![nsb];
307+ }
308+ PRESET_COUNTS.with(|c| c.borrow_mut().push((bits, counts_used)));
309+
171 let win = trials310 let win = trials
172 .into_iter()311 .into_iter()
173 .find(|t| t.cand == best)312 .find(|t| t.cand == best)
174 .expect("the winning candidate was evaluated");313 .expect("the winning candidate was evaluated");
175- Ok((loop_filter(best), cdef(best, damping), win.picture))314+ Ok((loop_filter(best), params, grid, win.picture))
176 }315 }
177 316
178 /// The header's `loop_filter_params` for one candidate.317 /// The header's `loop_filter_params` for one candidate.
crates/ec-av1/src/tile.rsmodified+86 -2
@@ -19,6 +19,78 @@ use crate::decode::{TXFM_CTX_INIT, txfm_partition_ctx_rect};
19 use crate::msac::SymbolEncoder;19 use crate::msac::SymbolEncoder;
20 use crate::mvstack::{MiGrid, MiInfo, NO_REF1, find_mv_stack, mv16, single_ref_ctx};20 use crate::mvstack::{MiGrid, MiInfo, NO_REF1, find_mv_stack, mv16, single_ref_ctx};
21 21
22+// ---------------------------------------------------------------------------
23+// lane-av1lr: per-64x64 `cdef_idx` (spec 5.11.56, `read_cdef`). The decoder
24+// reads ONE `cdef_idx` literal per 64x64 superblock, at that superblock's
25+// first non-skip block, and only when the frame header's `cdef_bits > 0`
26+// (`crate::decode::maybe_read_cdef_idx`). The writers below mirror that from
27+// a plan the filter search hands over, kept in a thread-local rather than
28+// threaded through every `write_*` signature -- the same shape the decoder's
29+// own `FrameCtx::cdef_transmitted` uses, and the encoder codes one tile at a
30+// time on one thread. The plan is CONSUMED by the tile writer that runs next
31+// ([`CdefIdxGuard`] clears it on every exit path, error included), so a frame
32+// that arms nothing writes no literals.
33+
34+/// One frame's per-superblock `cdef_idx` plan (see [`arm_cdef_idx`]).
35+struct CdefIdxPlan {
36+ /// The header's `cdef_bits`; never 0 while armed.
37+ bits: u8,
38+ /// Superblocks per row, the stride of `grid`.
39+ sb_cols: usize,
40+ /// One index per 64x64 superblock, in raster order.
41+ grid: Vec<u8>,
42+ /// The superblock whose literal was already written -- the decoder's
43+ /// `cdef_transmitted`, which resets at every superblock and which coding
44+ /// order (each superblock's blocks are contiguous) makes a single slot.
45+ last: Option<usize>,
46+}
47+
48+thread_local! {
49+ static CDEF_IDX: std::cell::RefCell<Option<CdefIdxPlan>> =
50+ const { std::cell::RefCell::new(None) };
51+}
52+
53+/// Arms the next tile write with one `cdef_idx` per 64x64 superblock.
54+/// `bits == 0` disarms (the header codes a single strength pair, so the tile
55+/// carries no literal at all).
56+pub(crate) fn arm_cdef_idx(bits: u8, sb_cols: usize, grid: Vec<u8>) {
57+ CDEF_IDX.with(|c| {
58+ *c.borrow_mut() = (bits > 0).then(|| CdefIdxPlan { bits, sb_cols, grid, last: None });
59+ });
60+}
61+
62+/// Clears the armed plan when the tile writer that consumed it returns.
63+struct CdefIdxGuard;
64+
65+impl Drop for CdefIdxGuard {
66+ fn drop(&mut self) {
67+ CDEF_IDX.with(|c| *c.borrow_mut() = None);
68+ }
69+}
70+
71+/// `read_cdef`'s write side, called right after every block's `skip` symbol:
72+/// writes this superblock's `cdef_idx` literal the first time a non-skip
73+/// block of it is coded. `mi` is the block's own position in 4x4 mode-info
74+/// units.
75+fn write_cdef_idx(enc: &mut SymbolEncoder, mi: (usize, usize), skip: bool) {
76+ if skip {
77+ return;
78+ }
79+ CDEF_IDX.with(|c| {
80+ let mut plan = c.borrow_mut();
81+ let Some(plan) = plan.as_mut() else { return };
82+ let sb = (mi.0 / 16) * plan.sb_cols + (mi.1 / 16);
83+ if plan.last == Some(sb) {
84+ return;
85+ }
86+ plan.last = Some(sb);
87+ enc.literal(
88+ u32::from(plan.grid.get(sb).copied().unwrap_or(0)),
89+ u32::from(plan.bits),
90+ );
91+ });
92+}
93+
22 /// round-4 av1-truesize debugging aid: prints `msg()` to stderr when the94 /// round-4 av1-truesize debugging aid: prints `msg()` to stderr when the
23 /// `EC_RNG` environment variable is set, mirroring the `EC_PART`/`EC_TOK`95 /// `EC_RNG` environment variable is set, mirroring the `EC_PART`/`EC_TOK`
24 /// trace `/tmp/libaom-src`'s debug `aomdec` build already emits under the96 /// trace `/tmp/libaom-src`'s debug `aomdec` build already emits under the
@@ -1040,6 +1112,8 @@ pub fn sb_coeff_key_frame_tile_tx(
1040 superblocks: &[Superblock],1112 superblocks: &[Superblock],
1041 tx_select: bool,1113 tx_select: bool,
1042 ) -> Result<Vec<u8>> {1114 ) -> Result<Vec<u8>> {
1115+ // Consumes whatever `arm_cdef_idx` armed, on every exit path.
1116+ let _cdef_idx = CdefIdxGuard;
1043 check_blocks(mi_cols, mi_rows)?;1117 check_blocks(mi_cols, mi_rows)?;
1044 let (cols, rows) = block_grid(mi_cols, mi_rows);1118 let (cols, rows) = block_grid(mi_cols, mi_rows);
1045 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));1119 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
@@ -1490,9 +1564,13 @@ fn write_intra_mode(
1490 above_mode: usize,1564 above_mode: usize,
1491 left_mode: usize,1565 left_mode: usize,
1492 cfl: bool,1566 cfl: bool,
1567+ // This block's own position in 4x4 mode-info units, for the `cdef_idx`
1568+ // literal that follows the `skip` symbol (see [`write_cdef_idx`]).
1569+ mi: (usize, usize),
1493 ) -> usize {1570 ) -> usize {
1494 let mode = usize::from(block.mode);1571 let mode = usize::from(block.mode);
1495 enc.symbol(0, &mut cdfs.skip[0]);1572 enc.symbol(0, &mut cdfs.skip[0]);
1573+ write_cdef_idx(enc, mi, false);
1496 enc.symbol(1574 enc.symbol(
1497 mode,1575 mode,
1498 &mut cdfs.kf_y_mode[INTRA_MODE_CTX[above_mode]][INTRA_MODE_CTX[left_mode]],1576 &mut cdfs.kf_y_mode[INTRA_MODE_CTX[above_mode]][INTRA_MODE_CTX[left_mode]],
@@ -1540,6 +1618,7 @@ fn write_block(
1540 all_scans: &[Vec<u16>; 4],1618 all_scans: &[Vec<u16>; 4],
1541 ) -> Result<()> {1619 ) -> Result<()> {
1542 let (r, c) = at;1620 let (r, c) = at;
1621+ let at_mi = (r * (SUB / MI), c * (SUB / MI));
1543 let mode = write_intra_mode(1622 let mode = write_intra_mode(
1544 enc,1623 enc,
1545 cdfs,1624 cdfs,
@@ -1547,8 +1626,8 @@ fn write_block(
1547 neighbours.above_mode[c],1626 neighbours.above_mode[c],
1548 neighbours.left_mode[r],1627 neighbours.left_mode[r],
1549 cfl,1628 cfl,
1629+ at_mi,
1550 );1630 );
1551- let at_mi = (r * (SUB / MI), c * (SUB / MI));
1552 let split = if tx_select {1631 let split = if tx_select {
1553 let tx = write_luma_select(1632 let tx = write_luma_select(
1554 enc,1633 enc,
@@ -1622,7 +1701,7 @@ fn write_leaf8(
1622 // true first divergence (a differently-sized alphabet under the same1701 // true first divergence (a differently-sized alphabet under the same
1623 // DC_PRED decision desyncs the coder even though the decoded mode is1702 // DC_PRED decision desyncs the coder even though the decoded mode is
1624 // unchanged).1703 // unchanged).
1625- let mode = write_intra_mode(enc, cdfs, block, above_mode, left_mode, true);1704+ let mode = write_intra_mode(enc, cdfs, block, above_mode, left_mode, true, leaf_mi);
1626 let planes = [TxbSet::Luma8, TxbSet::Chroma4, TxbSet::Chroma4];1705 let planes = [TxbSet::Luma8, TxbSet::Chroma4, TxbSet::Chroma4];
1627 let split = if tx_select {1706 let split = if tx_select {
1628 let tx = write_luma_select(1707 let tx = write_luma_select(
@@ -2685,6 +2764,8 @@ pub fn sb_coeff_inter_frame_tile_tx(
2685 blocks: &[Quadrant],2764 blocks: &[Quadrant],
2686 tx_select: bool,2765 tx_select: bool,
2687 ) -> Result<Vec<u8>> {2766 ) -> Result<Vec<u8>> {
2767+ // Consumes whatever `arm_cdef_idx` armed, on every exit path.
2768+ let _cdef_idx = CdefIdxGuard;
2688 check_blocks(mi_cols, mi_rows)?;2769 check_blocks(mi_cols, mi_rows)?;
2689 // `block_grid`'s ceiling, not a plain division: a true frame size that is2770 // `block_grid`'s ceiling, not a plain division: a true frame size that is
2690 // not a whole number of 32x32 blocks (or of 64x64 superblocks) still has2771 // not a whole number of 32x32 blocks (or of 64x64 superblocks) still has
@@ -3002,6 +3083,7 @@ pub fn sb_coeff_inter_frame_tile_tx(
3002 let skip_ctx = usize::from(neighbours.above_skip[mi_c])3083 let skip_ctx = usize::from(neighbours.above_skip[mi_c])
3003 + usize::from(neighbours.left_skip[mi_r]);3084 + usize::from(neighbours.left_skip[mi_r]);
3004 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);3085 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
3086+ write_cdef_idx(&mut enc, (mi_r, mi_c), block.skip);
3005 3087
3006 let is_inter = block.inter.is_some();3088 let is_inter = block.inter.is_some();
3007 let (above_inter, left_inter) =3089 let (above_inter, left_inter) =
@@ -3237,6 +3319,7 @@ fn write_inter_frame_leaf(
3237 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));3319 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
3238 let skip_ctx = usize::from(neighbours.above_skip[mi_c]) + usize::from(neighbours.left_skip[mi_r]);3320 let skip_ctx = usize::from(neighbours.above_skip[mi_c]) + usize::from(neighbours.left_skip[mi_r]);
3239 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);3321 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
3322+ write_cdef_idx(enc, (mi_r, mi_c), block.skip);
3240 3323
3241 let (has_above, has_left) = (r > 0, c > 0);3324 let (has_above, has_left) = (r > 0, c > 0);
3242 let (above_inter, left_inter) = (neighbours.above_inter[mi_c], neighbours.left_inter[mi_r]);3325 let (above_inter, left_inter) = (neighbours.above_inter[mi_c], neighbours.left_inter[mi_r]);
@@ -3458,6 +3541,7 @@ fn write_inter_frame_leaf8(
3458 let left_inter = neighbours.left_inter[leaf_mi.0];3541 let left_inter = neighbours.left_inter[leaf_mi.0];
3459 let skip_ctx = usize::from(above_skip) + usize::from(left_skip);3542 let skip_ctx = usize::from(above_skip) + usize::from(left_skip);
3460 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);3543 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
3544+ write_cdef_idx(enc, leaf_mi, block.skip);
3461 3545
3462 let (has_above, has_left) = (leaf_mi.0 > 0, leaf_mi.1 > 0);3546 let (has_above, has_left) = (leaf_mi.0 > 0, leaf_mi.1 > 0);
3463 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);3547 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);