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(
30243024
30253025 #[cfg(test)]
30263026 record_predicted_bits(crate::tile::predicted_coeff_bits_sb(&superblocks, base_q_idx));
3027- let tile = crate::tile::sb_coeff_key_frame_tile_tx(
3028- header.mi_cols,
3029- header.mi_rows,
3027+ let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
3028+ let mut tile = crate::tile::sb_coeff_key_frame_tile_tx(
3029+ mi_cols,
3030+ mi_rows,
30303031 base_q_idx,
30313032 &superblocks,
30323033 tx_select,
@@ -3042,9 +3043,21 @@ pub(crate) fn encode_key_frame_inner(
30423043 &mut chroma,
30433044 [&picture_y8, &picture_u8, &picture_v8],
30443045 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| {
30463059 crate::decode::decode_key_frame_tile(
3047- &tile,
3060+ tile,
30483061 h.mi_cols,
30493062 h.mi_rows,
30503063 base_q_idx,
@@ -3107,7 +3120,14 @@ fn pick_and_apply_filters(
31073120 chroma: &mut [Plane<'_>; 2],
31083121 source: [&[u8]; 3],
31093122 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>,
31113131 ) -> Result<()> {
31123132 if !search {
31133133 return Ok(());
@@ -3117,15 +3137,27 @@ fn pick_and_apply_filters(
31173137 // libaom `av1_pick_filter_level`'s sibling `av1_cdef_search`:
31183138 // `cdef_damping = 3 + (base_qindex >> 6)`, never searched.
31193139 let damping = 3 + (header.quantization.base_q_idx >> 6);
3120- let (lf, cdef, filtered) = crate::filter_search::pick_filters(
3121- |lf, cdef| decode(lf, cdef, &hdr),
3140+ let (cols32, rows32) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
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),
31223144 source,
31233145 luma.width,
31243146 (fw, fh),
31253147 damping,
3148+ (sb_cols, sb_rows),
3149+ lambda,
31263150 )?;
31273151 header.loop_filter = lf;
31283152 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+ };
31293161 let dec_cw = filtered.width.div_ceil(2);
31303162 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));
31313163 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(
41944226 / modes.len() as f64;
41954227 #[cfg(test)]
41964228 record_predicted_bits(crate::tile::predicted_coeff_bits(&blocks, base_q_idx));
4197- let tile = crate::tile::sb_coeff_inter_frame_tile_tx(
4198- header.mi_cols,
4199- header.mi_rows,
4229+ let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
4230+ let mut tile = crate::tile::sb_coeff_inter_frame_tile_tx(
4231+ mi_cols,
4232+ mi_rows,
42004233 base_q_idx,
42014234 &blocks,
42024235 tx_select,
@@ -4234,9 +4267,21 @@ pub(crate) fn encode_inter_frame(
42344267 // `TxMode::Select` too (it used to skip and leave every inter frame
42354268 // unfiltered once Select became the default).
42364269 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| {
42384283 crate::decode::decode_inter_frame_tile(
4239- &tile,
4284+ tile,
42404285 h.mi_cols,
42414286 h.mi_rows,
42424287 base_q_idx,
@@ -7218,6 +7263,30 @@ mod tests {
72187263 mean(|l| l.2.0),
72197264 mean(|l| l.2.1),
72207265 );
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+ );
72217290 // Which chroma modes the search actually wins with, against the
72227291 // unconditional DC_PRED that was the only outcome before
72237292 // (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))> {
4040 })
4141 }
4242
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+
4357 /// Squared error between a decoded plane and the source it was coded from,
4458 /// over the frame's own cropped `w x h` (the two planes have different
4559 /// 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
5569 sse
5670 }
5771
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+
5897 /// CDEF primary strengths tried (libaom's own range is 0..15 for 8-bit
5998 /// content) and the secondary ladder, whose only legal values are 0, 1, 2
6099 /// and 4 -- 3 is not codeable (spec 5.9.19 codes a secondary strength of 4
@@ -82,6 +121,10 @@ struct Trial {
82121 picture: Picture,
83122 sse_y: u64,
84123 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>,
85128 }
86129
87130 /// Picks this frame's deblocking levels and CDEF strengths and hands back
@@ -111,8 +154,11 @@ pub(crate) fn pick_filters(
111154 src_w: usize,
112155 (fw, fh): (usize, usize),
113156 damping: u8,
114-) -> Result<(LoopFilterParams, CdefParams, Picture)> {
157+ (sb_cols, sb_rows): (usize, usize),
158+ lambda: f64,
159+) -> Result<(LoopFilterParams, CdefParams, Vec<u8>, Picture)> {
115160 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));
161+ let nsb = sb_cols * sb_rows;
116162 let mut trials: Vec<Trial> = Vec::new();
117163 let eval = |cand: Cand, trials: &mut Vec<Trial>| -> Result<usize> {
118164 if let Some(i) = trials.iter().position(|t| t.cand == cand) {
@@ -123,7 +169,11 @@ pub(crate) fn pick_filters(
123169 let sse_y = plane_sse(&picture.y, picture.width, source[0], src_w, fw, fh);
124170 let sse_uv = plane_sse(&picture.u, dec_cw, source[1], src_w / 2, cw, ch)
125171 + 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 });
127177 Ok(trials.len() - 1)
128178 };
129179 // One stage of the coordinate search: try `values` in the slot `set`
@@ -168,11 +218,100 @@ pub(crate) fn pick_filters(
168218 stage(&mut best, &CDEF_SEC, |c, v| c.uv.1 = v, |t| t.sse_uv, &mut trials)?;
169219
170220 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+
171310 let win = trials
172311 .into_iter()
173312 .find(|t| t.cand == best)
174313 .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))
176315 }
177316
178317 /// 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};
1919 use crate::msac::SymbolEncoder;
2020 use crate::mvstack::{MiGrid, MiInfo, NO_REF1, find_mv_stack, mv16, single_ref_ctx};
2121
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+
2294 /// round-4 av1-truesize debugging aid: prints `msg()` to stderr when the
2395 /// `EC_RNG` environment variable is set, mirroring the `EC_PART`/`EC_TOK`
2496 /// trace `/tmp/libaom-src`'s debug `aomdec` build already emits under the
@@ -1040,6 +1112,8 @@ pub fn sb_coeff_key_frame_tile_tx(
10401112 superblocks: &[Superblock],
10411113 tx_select: bool,
10421114 ) -> Result<Vec<u8>> {
1115+ // Consumes whatever `arm_cdef_idx` armed, on every exit path.
1116+ let _cdef_idx = CdefIdxGuard;
10431117 check_blocks(mi_cols, mi_rows)?;
10441118 let (cols, rows) = block_grid(mi_cols, mi_rows);
10451119 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
@@ -1490,9 +1564,13 @@ fn write_intra_mode(
14901564 above_mode: usize,
14911565 left_mode: usize,
14921566 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),
14931570 ) -> usize {
14941571 let mode = usize::from(block.mode);
14951572 enc.symbol(0, &mut cdfs.skip[0]);
1573+ write_cdef_idx(enc, mi, false);
14961574 enc.symbol(
14971575 mode,
14981576 &mut cdfs.kf_y_mode[INTRA_MODE_CTX[above_mode]][INTRA_MODE_CTX[left_mode]],
@@ -1540,6 +1618,7 @@ fn write_block(
15401618 all_scans: &[Vec<u16>; 4],
15411619 ) -> Result<()> {
15421620 let (r, c) = at;
1621+ let at_mi = (r * (SUB / MI), c * (SUB / MI));
15431622 let mode = write_intra_mode(
15441623 enc,
15451624 cdfs,
@@ -1547,8 +1626,8 @@ fn write_block(
15471626 neighbours.above_mode[c],
15481627 neighbours.left_mode[r],
15491628 cfl,
1629+ at_mi,
15501630 );
1551- let at_mi = (r * (SUB / MI), c * (SUB / MI));
15521631 let split = if tx_select {
15531632 let tx = write_luma_select(
15541633 enc,
@@ -1622,7 +1701,7 @@ fn write_leaf8(
16221701 // true first divergence (a differently-sized alphabet under the same
16231702 // DC_PRED decision desyncs the coder even though the decoded mode is
16241703 // 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);
16261705 let planes = [TxbSet::Luma8, TxbSet::Chroma4, TxbSet::Chroma4];
16271706 let split = if tx_select {
16281707 let tx = write_luma_select(
@@ -2685,6 +2764,8 @@ pub fn sb_coeff_inter_frame_tile_tx(
26852764 blocks: &[Quadrant],
26862765 tx_select: bool,
26872766 ) -> Result<Vec<u8>> {
2767+ // Consumes whatever `arm_cdef_idx` armed, on every exit path.
2768+ let _cdef_idx = CdefIdxGuard;
26882769 check_blocks(mi_cols, mi_rows)?;
26892770 // `block_grid`'s ceiling, not a plain division: a true frame size that is
26902771 // 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(
30023083 let skip_ctx = usize::from(neighbours.above_skip[mi_c])
30033084 + usize::from(neighbours.left_skip[mi_r]);
30043085 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
3086+ write_cdef_idx(&mut enc, (mi_r, mi_c), block.skip);
30053087
30063088 let is_inter = block.inter.is_some();
30073089 let (above_inter, left_inter) =
@@ -3237,6 +3319,7 @@ fn write_inter_frame_leaf(
32373319 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
32383320 let skip_ctx = usize::from(neighbours.above_skip[mi_c]) + usize::from(neighbours.left_skip[mi_r]);
32393321 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
3322+ write_cdef_idx(enc, (mi_r, mi_c), block.skip);
32403323
32413324 let (has_above, has_left) = (r > 0, c > 0);
32423325 let (above_inter, left_inter) = (neighbours.above_inter[mi_c], neighbours.left_inter[mi_r]);
@@ -3458,6 +3541,7 @@ fn write_inter_frame_leaf8(
34583541 let left_inter = neighbours.left_inter[leaf_mi.0];
34593542 let skip_ctx = usize::from(above_skip) + usize::from(left_skip);
34603543 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
3544+ write_cdef_idx(enc, leaf_mi, block.skip);
34613545
34623546 let (has_above, has_left) = (leaf_mi.0 > 0, leaf_mi.1 > 0);
34633547 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);