forge
Explore
Log in

Don't you dare go Hollow

The chroma search offers UV_CFL_PRED, alpha searched and coded

Browse files at this commit

f9449108b932f6277061362d12c6afd36804a7c3Ahmet Kaan GümüşParent: 77aeca1
  • feat
    • the chroma search offers UV_CFL_PRED, alpha searched and coded
Show full message
feat(av1): the chroma search offers UV_CFL_PRED, alpha searched and coded

The encoder never coded chroma-from-luma: every intra block's chroma came
off DC/V/H/SMOOTH*/PAETH while the decoder has read `cfl_alpha_signs` and
scaled the luma AC since lane-cfl. The chroma search now builds the
decoder's own CfL candidate -- `cfl_ac_q3_at` (the shared body behind
`cfl_ac_q3`/`cfl_ac_q3_rect`) over the committed luma reconstruction, the
decoder's `cfl_scaled` nudge on a DC_PRED base -- picks each plane's
alpha_q3 from the least-squares optimum and its two neighbours, and prices
the three sign combinations against the best ordinary chroma mode and the
chroma palette. Offered only where `is_cfl_allowed` does (<=32x32).

The writer codes `uv_mode = UV_CFL_PRED` plus the joint sign and magnitude
symbols at all four uv_mode sites; the three intra-in-inter sites needed it
too (without them the inter path desynced at picture 8).

5-row native gate, EC_AV1_CFL=0 -> default:
  bars 1080p +15.6/-1.7 -> +0.3/-15.5, bars 2160p +46.5/+18.8 -> +16.8/-6.5,
  film A +69.0/+37.5 -> +67.7/+36.3, film B +100.0/+61.5 -> +99.6/+61.2,
  screen +51.0/-14.5 -> +50.4/-15.1.
crates/ec-av1/src/decode.rsmodified+27 -30
@@ -9043,25 +9043,7 @@ fn tx_size_context_rect(
90439043
90449044 /// [`cfl_ac_q3`] for a true `bw`x`bh` rect strip (lane-intradisp r1).
90459045 fn cfl_ac_q3_rect(y: &PlaneBuf<'_>, px: usize, py: usize, bw: usize, bh: usize) -> Vec<i32> {
9046- let (cw, ch) = (bw / 2, bh / 2);
9047- let mut ac = vec![0i32; cw * ch];
9048- let mut sum = 0i32;
9049- for cy in 0..ch {
9050- for cx in 0..cw {
9051- let (lx, ly) = (px + cx * 2, py + cy * 2);
9052- let q3 = (i32::from(y.data[ly * y.width + lx])
9053- + i32::from(y.data[ly * y.width + lx + 1])
9054- + i32::from(y.data[(ly + 1) * y.width + lx])
9055- + i32::from(y.data[(ly + 1) * y.width + lx + 1]))
9056- << 1;
9057- ac[cy * cw + cx] = q3;
9058- sum += q3;
9059- }
9060- }
9061- let num_pel = (cw * ch) as i32;
9062- let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
9063- ac.iter_mut().for_each(|v| *v -= avg);
9064- ac
9046+ cfl_ac_q3_at(px, py, bw, bh, |lx, ly| i32::from(y.data[ly * y.width + lx]))
90659047 }
90669048
90679049 /// Everything a rect strip already read out of the stream before its luma
@@ -13104,22 +13086,37 @@ fn read_cfl_alphas(dec: &mut SymbolDecoder, cdfs: &mut Cdfs) -> (i32, i32) {
1310413086 /// subtracted (`round_offset = num_pel/2`, right-shifted by `log2(num_pel)`)
1310513087 /// to give the AC values [`cfl_scaled`] scales by alpha.
1310613088 fn cfl_ac_q3(y: &PlaneBuf<'_>, px: usize, py: usize, side: usize) -> Vec<i32> {
13107- let cside = side / 2;
13108- let mut ac = vec![0i32; cside * cside];
13089+ cfl_ac_q3_at(px, py, side, side, |lx, ly| i32::from(y.data[ly * y.width + lx]))
13090+}
13091+
13092+/// The one body [`cfl_ac_q3`] and [`cfl_ac_q3_rect`] share, reading its luma
13093+/// samples through `sample(x, y)` instead of a [`PlaneBuf`] -- so the encoder
13094+/// (lane-av1cfl) builds a CfL candidate's AC signal from its own `u8`
13095+/// reconstruction through THIS function rather than a second transcription of
13096+/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c`.
13097+pub(crate) fn cfl_ac_q3_at(
13098+ px: usize,
13099+ py: usize,
13100+ bw: usize,
13101+ bh: usize,
13102+ sample: impl Fn(usize, usize) -> i32,
13103+) -> Vec<i32> {
13104+ let (cw, ch) = (bw / 2, bh / 2);
13105+ let mut ac = vec![0i32; cw * ch];
1310913106 let mut sum = 0i32;
13110- for cy in 0..cside {
13111- for cx in 0..cside {
13107+ for cy in 0..ch {
13108+ for cx in 0..cw {
1311213109 let (lx, ly) = (px + cx * 2, py + cy * 2);
13113- let q3 = (i32::from(y.data[ly * y.width + lx])
13114- + i32::from(y.data[ly * y.width + lx + 1])
13115- + i32::from(y.data[(ly + 1) * y.width + lx])
13116- + i32::from(y.data[(ly + 1) * y.width + lx + 1]))
13110+ let q3 = (sample(lx, ly)
13111+ + sample(lx + 1, ly)
13112+ + sample(lx, ly + 1)
13113+ + sample(lx + 1, ly + 1))
1311713114 << 1;
13118- ac[cy * cside + cx] = q3;
13115+ ac[cy * cw + cx] = q3;
1311913116 sum += q3;
1312013117 }
1312113118 }
13122- let num_pel = (cside * cside) as i32;
13119+ let num_pel = (cw * ch) as i32;
1312313120 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
1312413121 ac.iter_mut().for_each(|v| *v -= avg);
1312513122 ac
@@ -13128,7 +13125,7 @@ fn cfl_ac_q3(y: &PlaneBuf<'_>, px: usize, py: usize, side: usize) -> Vec<i32> {
1312813125 /// `get_scaled_luma_q0` (libaom cfl.h): `alpha_q3 * ac_q3`, rounded from Q6
1312913126 /// back to whole samples with `ROUND_POWER_OF_TWO_SIGNED` (round-to-nearest,
1313013127 /// ties away from zero on the shifted-out sign).
13131-fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 {
13128+pub(crate) fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 {
1313213129 let v = alpha_q3 * ac_q3;
1313313130 if v >= 0 {
1313413131 (v + 32) >> 6
crates/ec-av1/src/encode.rsmodified+198 -9
@@ -3798,8 +3798,8 @@ fn code_square(
37983798
37993799 // Chroma searches its own mode over [`CHROMA_MODES`], one symbol for both
38003800 // planes; what it costs still counts towards the partition decision.
3801- let ([u, v], uv_mode, chroma_cost, palette_uv) =
3802- search_chroma(chroma, (x, y), side, chroma_set, search, mode, fctx);
3801+ let ([u, v], uv_mode, chroma_cost, palette_uv, cfl_alphas) =
3802+ search_chroma(chroma, luma, (x, y), side, chroma_set, search, mode, fctx);
38033803 cost += chroma_cost;
38043804
38053805 // The intrabc arm is priced against the WHOLE block -- luma and both
@@ -3834,6 +3834,7 @@ fn code_square(
38343834 tx_depth,
38353835 palette,
38363836 palette_uv,
3837+ cfl_alphas,
38373838 ..BlockCoeffs::default()
38383839 },
38393840 cost,
@@ -3858,21 +3859,42 @@ const CHROMA_MODES: [u8; 7] = [
38583859
38593860 /// The thirteen intra mode names, for the chroma fire count's print.
38603861 #[cfg(test)]
3861-const UV_MODE_NAMES: [&str; 13] = [
3862+const UV_MODE_NAMES: [&str; 14] = [
38623863 "DC", "V", "H", "D45", "D135", "D113", "D157", "D203", "D67", "SMOOTH", "SMOOTH_V",
3863- "SMOOTH_H", "PAETH",
3864+ "SMOOTH_H", "PAETH", "CFL",
38643865 ];
38653866
38663867 /// How many blocks each chroma mode has won, indexed by the mode itself --
38673868 /// the fire count that says whether the search below reaches its candidates
38683869 /// at all (the `gate-blind-to-feature` class), printed once per gate run.
3869-static UV_MODE_HITS: [std::sync::atomic::AtomicUsize; 13] =
3870- [const { std::sync::atomic::AtomicUsize::new(0) }; 13];
3870+static UV_MODE_HITS: [std::sync::atomic::AtomicUsize; 14] =
3871+ [const { std::sync::atomic::AtomicUsize::new(0) }; 14];
3872+
3873+/// How many blocks each CfL alpha magnitude (`1..=16`, indexed `mag - 1`) has
3874+/// won, summed over both chroma planes -- the alpha histogram the gate prints
3875+/// beside the CfL share (`gate-blind-to-feature`: a tool that fires at one
3876+/// magnitude only is a search that never left its first candidate).
3877+static CFL_ALPHA_HITS: [std::sync::atomic::AtomicUsize; 17] =
3878+ [const { std::sync::atomic::AtomicUsize::new(0) }; 17];
3879+
3880+/// Reads [`CFL_ALPHA_HITS`] and zeroes it. Index 0 is "this plane took alpha
3881+/// zero on a CfL block", `1..=16` the magnitudes.
3882+#[cfg(test)]
3883+pub(crate) fn take_cfl_alpha_hits() -> [usize; 17] {
3884+ std::array::from_fn(|m| CFL_ALPHA_HITS[m].swap(0, std::sync::atomic::Ordering::Relaxed))
3885+}
3886+
3887+/// Whether the chroma search offers `UV_CFL_PRED` at all (`EC_AV1_CFL=0`
3888+/// switches it off, which is how the lane measured its own on/off pair).
3889+fn cfl_on() -> bool {
3890+ static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
3891+ *ON.get_or_init(|| std::env::var("EC_AV1_CFL").as_deref() != Ok("0"))
3892+}
38713893
38723894 /// Reads [`UV_MODE_HITS`] and zeroes it, so a gate can attribute the counts
38733895 /// to its own encode.
38743896 #[cfg(test)]
3875-pub(crate) fn take_uv_mode_hits() -> [usize; 13] {
3897+pub(crate) fn take_uv_mode_hits() -> [usize; 14] {
38763898 std::array::from_fn(|m| UV_MODE_HITS[m].swap(0, std::sync::atomic::Ordering::Relaxed))
38773899 }
38783900
@@ -3920,13 +3942,22 @@ const CHROMA_TOP_K: Option<usize> = None;
39203942
39213943 fn search_chroma(
39223944 chroma: &mut [Plane; 2],
3945+ // The luma plane's RECONSTRUCTION under this block, already committed by
3946+ // [`Plane::search_block`] -- the signal a `UV_CFL_PRED` candidate scales.
3947+ luma: &Plane,
39233948 (x, y): (usize, usize),
39243949 side: usize,
39253950 set: TxbSet,
39263951 search: &Search,
39273952 luma_mode: u8,
39283953 fctx: &crate::decode::FrameCtx,
3929-) -> ([Vec<Coeff>; 2], u8, f64, Option<crate::tile::PaletteUv>) {
3954+) -> (
3955+ [Vec<Coeff>; 2],
3956+ u8,
3957+ f64,
3958+ Option<crate::tile::PaletteUv>,
3959+ Option<(i32, i32)>,
3960+) {
39303961 let at = At {
39313962 x: x / 2,
39323963 y: y / 2,
@@ -4047,6 +4078,134 @@ fn search_chroma(
40474078 }
40484079 }
40494080 }
4081+ // The chroma-from-luma arm (spec 5.11.45, libaom `cfl_rd_pick_alpha`):
4082+ // `UV_CFL_PRED` predicts as `DC_PRED` (`get_uv_mode`, spec 9.3) and then
4083+ // nudges every sample by `alpha_q3` times the block's subsampled,
4084+ // average-subtracted luma reconstruction. Offered only where
4085+ // `is_cfl_allowed` (spec 5.11.5) does -- a luma block at most 32x32 --
4086+ // and priced against the best ordinary chroma mode above, palette
4087+ // included, so a block only takes it when it beats both.
4088+ let mut cfl_alphas = None;
4089+ if side <= 32 && cfl_on() {
4090+ // The AC signal, through the decoder's own
4091+ // `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` body.
4092+ let ac = crate::decode::cfl_ac_q3_at(x, y, side, side, |lx, ly| {
4093+ i32::from(luma.reconstruction[ly * luma.width + lx])
4094+ });
4095+ let dc_prediction = |plane: &Plane| -> Vec<u8> {
4096+ let (mut above_buf, mut left_buf) = ([0u8; 2 * BLOCK], [0u8; 2 * BLOCK]);
4097+ let (above, left, corner) =
4098+ plane.edges_into(at.x, at.y, at.side, at.reach, &mut above_buf, &mut left_buf);
4099+ let mut prediction = vec![0u8; at.side * at.side];
4100+ intra_predict_u8(
4101+ DC_PRED, 0, above, left, corner, at.side, at.side, false, false, &mut prediction,
4102+ fctx,
4103+ );
4104+ prediction
4105+ };
4106+ let bases = [dc_prediction(&chroma[0]), dc_prediction(&chroma[1])];
4107+ // `av1_cfl_predict_block` (cfl.c): clip the nudged prediction, then
4108+ // add the residual -- which is what [`Plane::code_from_prediction`]
4109+ // does with what this returns.
4110+ let apply = |base: &[u8], alpha: i32| -> Vec<u8> {
4111+ base.iter()
4112+ .zip(ac.iter())
4113+ .map(|(&b, &a)| {
4114+ (i32::from(b) + crate::decode::cfl_scaled(alpha, a)).clamp(0, 255) as u8
4115+ })
4116+ .collect()
4117+ };
4118+ // The least-squares alpha, then its two neighbours: minimising
4119+ // `sum (source - base - alpha*ac/64)^2` over a continuous alpha is one
4120+ // dot-product ratio, and the quantised optimum is one of the two
4121+ // integers around it (the clamp and the Q6 rounding are what the SSE
4122+ // check below re-decides). libaom sweeps all sixteen magnitudes under
4123+ // full RD; three predictions per plane buy nearly the same alpha for a
4124+ // thirtieth of the search.
4125+ let pick_alpha = |plane: &Plane, base: &[u8]| -> i32 {
4126+ let (mut num, mut den) = (0.0f64, 0.0f64);
4127+ for row in 0..at.side {
4128+ for col in 0..at.side {
4129+ let i = row * at.side + col;
4130+ let d = f64::from(plane.source[(at.y + row) * plane.width + at.x + col])
4131+ - f64::from(base[i]);
4132+ num += d * f64::from(ac[i]);
4133+ den += f64::from(ac[i]) * f64::from(ac[i]);
4134+ }
4135+ }
4136+ if den == 0.0 {
4137+ return 0;
4138+ }
4139+ let ideal = 64.0 * num / den;
4140+ let mut best = (plane.block_sse(at.x, at.y, at.side, base), 0i32);
4141+ for alpha in [ideal.floor() as i64, ideal.ceil() as i64] {
4142+ let alpha = alpha.clamp(-16, 16) as i32;
4143+ if alpha == 0 {
4144+ continue;
4145+ }
4146+ let sse = plane.block_sse(at.x, at.y, at.side, &apply(base, alpha));
4147+ if sse < best.0 {
4148+ best = (sse, alpha);
4149+ }
4150+ }
4151+ best.1
4152+ };
4153+ let picked = [
4154+ pick_alpha(&chroma[0], &bases[0]),
4155+ pick_alpha(&chroma[1], &bases[1]),
4156+ ];
4157+ if picked != [0, 0] {
4158+ let cfl_bits = symbol_bits(uv_cdf, crate::tile::UV_CFL_PRED) - dc_bits;
4159+ let trial = |plane_idx: usize, alpha: i32| -> Trial {
4160+ let prediction = if alpha == 0 {
4161+ bases[plane_idx].clone()
4162+ } else {
4163+ apply(&bases[plane_idx], alpha)
4164+ };
4165+ chroma[plane_idx].code_from_prediction(
4166+ at.x,
4167+ at.y,
4168+ at.side,
4169+ &prediction,
4170+ false,
4171+ search.base_q_idx,
4172+ search.deadzone,
4173+ set,
4174+ )
4175+ };
4176+ // At least one alpha must be nonzero: `cfl_alpha_signs` has no
4177+ // (ZERO, ZERO) joint value ([`crate::tile::cfl_joint_sign`]).
4178+ let combos: [(i32, i32); 3] = [
4179+ (picked[0], picked[1]),
4180+ (picked[0], 0),
4181+ (0, picked[1]),
4182+ ];
4183+ for &(alpha_u, alpha_v) in &combos {
4184+ if (alpha_u, alpha_v) == (0, 0) {
4185+ continue;
4186+ }
4187+ let cu = trial(0, alpha_u);
4188+ let cv = trial(1, alpha_v);
4189+ let bits =
4190+ cfl_bits + crate::tile::cfl_alpha_bits(alpha_u, alpha_v) + cu.bits + cv.bits;
4191+ let cost_cfl = cu.sse + cv.sse + search.lambda * bits;
4192+ if cost_cfl < cost {
4193+ cost = cost_cfl;
4194+ mode = crate::tile::UV_CFL_PRED as u8;
4195+ u = cu;
4196+ v = cv;
4197+ palette_uv = None;
4198+ cfl_alphas = Some((alpha_u, alpha_v));
4199+ }
4200+ }
4201+ }
4202+ }
4203+ if let Some((alpha_u, alpha_v)) = cfl_alphas {
4204+ for alpha in [alpha_u, alpha_v] {
4205+ CFL_ALPHA_HITS[alpha.unsigned_abs() as usize]
4206+ .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4207+ }
4208+ }
40504209 if census_on() {
40514210 CHROMA_RANK[sad_rank(&ranking, mode).min(6)]
40524211 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
@@ -4059,6 +4218,7 @@ fn search_chroma(
40594218 mode,
40604219 cost,
40614220 palette_uv,
4221+ cfl_alphas,
40624222 )
40634223 }
40644224
@@ -4840,6 +5000,7 @@ fn code_square_inter(
48405000 chroma[1].commit(x / 2, y / 2, side / 2, &v_new);
48415001 return (
48425002 BlockCoeffs {
5003+ cfl_alphas: None,
48435004 luma: coeffs(&levels, side),
48445005 u: coeffs(&u_new.levels, side / 2),
48455006 v: coeffs(&v_new.levels, side / 2),
@@ -4873,6 +5034,7 @@ fn code_square_inter(
48735034 chroma[0].commit(x / 2, y / 2, side / 2, &u);
48745035 chroma[1].commit(x / 2, y / 2, side / 2, &v);
48755036 (BlockCoeffs {
5037+ cfl_alphas: None,
48765038 luma: coeffs(&levels, side),
48775039 u: coeffs(&u.levels, side / 2),
48785040 v: coeffs(&v.levels, side / 2),
@@ -7576,6 +7738,7 @@ fn search_inter_block(
75767738 chroma[1].commit(x / 2, y / 2, BLOCK / 2, &best.v);
75777739 (
75787740 BlockCoeffs {
7741+ cfl_alphas: None,
75797742 luma: coeffs(&levels, BLOCK),
75807743 u: coeffs(&best.u.levels, BLOCK / 2),
75817744 v: coeffs(&best.v.levels, BLOCK / 2),
@@ -9828,6 +9991,7 @@ mod tests {
98289991 let (_, inter_header) = inter_frame_headers(width, height, 100, 1, 0).unwrap();
98299992
98309993 let residual_block = BlockCoeffs {
9994+ cfl_alphas: None,
98319995 luma: vec![Coeff {
98329996 row: 0,
98339997 col: 0,
@@ -11489,8 +11653,12 @@ mod tests {
1148911653 // 3-value alphabet where a warp sample exists) on the DEFAULT path --
1149011654 // +34.9% here, one point past the OBMC reading above. The bound moves
1149111655 // with it; `EC_AV1_WARP=0` restores the +32.6% no-motion_mode number.
11656+ // lane-av1cfl: a `UV_CFL_PRED` block carries a `cfl_alpha_signs`
11657+ // symbol and one or two magnitude symbols, none of which the
11658+ // coefficient sum counts either -- +36.9% here against the same
11659+ // fixture's +34.9% with `EC_AV1_CFL=0`.
1149211660 assert!(
11493- worst_under <= 0.36,
11661+ worst_under <= 0.38,
1149411662 "the writer spent {:.2}% more than the search priced -- more than \
1149511663 the mode/mv syntax outside the coefficient sum explains",
1149611664 worst_under * 100.0
@@ -12541,6 +12709,10 @@ mod tests {
1254112709 /// and the two var-tx depth searches ([`tx32_depth_search`],
1254212710 /// [`compound_var_tx`]) are on by default, all three re-judged on the
1254312711 /// native gate's real film rows.
12712+ /// Re-pinned on lane-av1cfl: the chroma search offers `UV_CFL_PRED`, so
12713+ /// every block whose chroma takes it codes a different mode symbol, two
12714+ /// alpha symbols and different chroma coefficients. `EC_AV1_CFL=0`
12715+ /// restores the previous streams.
1254412716 #[test]
1254512717 fn the_encoders_own_streams_are_byte_identical_to_their_pins() {
1254612718 if !have_ffmpeg() {
@@ -13046,6 +13218,23 @@ mod tests {
1304613218 .collect::<Vec<_>>()
1304713219 .join(" ")
1304813220 );
13221+ // The CfL alpha histogram (lane-av1cfl): one entry per chroma
13222+ // plane of every `UV_CFL_PRED` block, by |alpha_q3|. A tool that
13223+ // only ever fires at one magnitude is a search that never left
13224+ // its first candidate (gate-blind-to-feature).
13225+ let alphas = take_cfl_alpha_hits();
13226+ if alphas.iter().sum::<usize>() > 0 {
13227+ eprintln!(
13228+ "{name}: cfl |alpha| {}",
13229+ alphas
13230+ .iter()
13231+ .enumerate()
13232+ .filter(|&(_, &n)| n > 0)
13233+ .map(|(a, &n)| format!("{a}={n}"))
13234+ .collect::<Vec<_>>()
13235+ .join(" ")
13236+ );
13237+ }
1304913238 let palette_uv = crate::tile::take_palette_uv_hits();
1305013239 eprintln!(
1305113240 "{name}: chroma palette blocks {} sizes {}",
crates/ec-av1/src/tile.rsmodified+94 -0
@@ -1446,6 +1446,12 @@ pub struct BlockCoeffs {
14461446 /// `luma` then carries the whole block's levels in BLOCK coordinates,
14471447 /// which the writer slices per transform unit.
14481448 pub tx_depth: u8,
1449+ /// This block's `UV_CFL_PRED` alphas (`alpha_q3` for U and V, spec
1450+ /// 5.11.45's `cfl_alpha_signs`/`cfl_alpha_u`/`cfl_alpha_v`), or `None` for
1451+ /// any other chroma mode. `Some` iff [`Self::uv_mode`] is
1452+ /// [`UV_CFL_PRED`]; at least one of the pair is nonzero, since the joint
1453+ /// sign symbol has no (ZERO, ZERO) value.
1454+ pub cfl_alphas: Option<(i32, i32)>,
14491455 /// This block's intra block-copy vector (spec 5.11.13 `use_intrabc` ->
14501456 /// `assign_dv`), in the spec's 1/8-pel `(row, col)` units, or `None` for
14511457 /// an ordinary intra block. Only a key frame whose header set
@@ -3292,6 +3298,77 @@ fn write_intrabc_block(
32923298 Ok(())
32933299 }
32943300
3301+/// `UV_CFL_PRED` (spec 6.10.19's chroma mode enum), the fourteenth entry of
3302+/// [`crate::cdf::UV_MODE_CFL`] -- the writer's twin of the decoder's own
3303+/// constant.
3304+pub(crate) const UV_CFL_PRED: usize = 13;
3305+
3306+/// The `cfl_alpha_signs` joint value (0..8) that codes this signed alpha pair,
3307+/// inverting the decoder's own `read_cfl_alphas` split (`sign_u =
3308+/// ((joint+1)*11)>>5`, `sign_v = (joint+1) - 3*sign_u`, with 0 ZERO, 1 NEG,
3309+/// 2 POS). There is no (ZERO, ZERO) joint value, so at least one alpha of a
3310+/// CfL block is nonzero by construction.
3311+pub(crate) fn cfl_joint_sign(alpha_u: i32, alpha_v: i32) -> usize {
3312+ let sign = |a: i32| match a.signum() {
3313+ 0 => 0,
3314+ -1 => 1,
3315+ _ => 2,
3316+ };
3317+ let (want_u, want_v) = (sign(alpha_u), sign(alpha_v));
3318+ (0..8)
3319+ .find(|&j| {
3320+ let su = ((j + 1) * 11) >> 5;
3321+ (su, (j + 1) - 3 * su) == (want_u, want_v)
3322+ })
3323+ .expect("cfl_alpha_signs covers every pair but (ZERO, ZERO)") as usize
3324+}
3325+
3326+/// The `cfl_alpha_u`/`cfl_alpha_v` magnitude CDF row for one plane, by the
3327+/// same `CFL_CONTEXT_U`/`CFL_CONTEXT_V` derivation the decoder reads with
3328+/// (libaom cfl.h). `joint` is [`cfl_joint_sign`]'s value.
3329+fn cfl_alpha_ctx(joint: usize, plane: usize) -> usize {
3330+ let joint = joint as i32;
3331+ let su = ((joint + 1) * 11) >> 5;
3332+ let sv = (joint + 1) - 3 * su;
3333+ if plane == 0 {
3334+ (joint + 1 - 3) as usize
3335+ } else {
3336+ (sv * 3 + su - 3) as usize
3337+ }
3338+}
3339+
3340+/// What [`write_cfl_alphas`] will spend on this alpha pair, through the same
3341+/// tables -- the encoder's RD price for the CfL arm.
3342+pub(crate) fn cfl_alpha_bits(alpha_u: i32, alpha_v: i32) -> f64 {
3343+ use crate::encode::symbol_bits;
3344+ let joint = cfl_joint_sign(alpha_u, alpha_v);
3345+ let mut bits = symbol_bits(&crate::cdf::CFL_SIGN, joint);
3346+ for (plane, alpha) in [alpha_u, alpha_v].into_iter().enumerate() {
3347+ if alpha != 0 {
3348+ bits += symbol_bits(
3349+ &crate::cdf::CFL_ALPHA[cfl_alpha_ctx(joint, plane)],
3350+ (alpha.unsigned_abs() - 1) as usize,
3351+ );
3352+ }
3353+ }
3354+ bits
3355+}
3356+
3357+/// `read_cfl_alphas` (spec 5.11.45) written: the joint sign, then each
3358+/// plane's magnitude where its sign is nonzero.
3359+fn write_cfl_alphas(enc: &mut SymbolEncoder, cdfs: &mut Cdfs, (alpha_u, alpha_v): (i32, i32)) {
3360+ let joint = cfl_joint_sign(alpha_u, alpha_v);
3361+ enc.symbol(joint, &mut cdfs.cfl_sign);
3362+ for (plane, alpha) in [alpha_u, alpha_v].into_iter().enumerate() {
3363+ if alpha != 0 {
3364+ enc.symbol(
3365+ (alpha.unsigned_abs() - 1) as usize,
3366+ &mut cdfs.cfl_alpha[cfl_alpha_ctx(joint, plane)],
3367+ );
3368+ }
3369+ }
3370+}
3371+
32953372 fn write_intra_mode(
32963373 enc: &mut SymbolEncoder,
32973374 cdfs: &mut Cdfs,
@@ -3334,8 +3411,16 @@ fn write_intra_mode(
33343411 if cfl {
33353412 enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]);
33363413 } else {
3414+ debug_assert_ne!(uv_mode, UV_CFL_PRED, "is_cfl_allowed excludes this block");
33373415 enc.symbol(uv_mode, &mut cdfs.uv_mode_no_cfl[mode]);
33383416 }
3417+ if uv_mode == UV_CFL_PRED {
3418+ write_cfl_alphas(
3419+ enc,
3420+ cdfs,
3421+ block.cfl_alphas.expect("a UV_CFL_PRED block carries its alphas"),
3422+ );
3423+ }
33393424 // `angle_delta_uv` (spec `read_intra_angle_info`) off the same CDF array
33403425 // the luma delta reads, indexed by the chroma mode.
33413426 if (V_PRED..=D67_PRED).contains(&uv_mode) {
@@ -5710,6 +5795,9 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
57105795 }
57115796 let uv_mode = usize::from(block.uv_mode);
57125797 enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]);
5798+ if uv_mode == UV_CFL_PRED {
5799+ write_cfl_alphas(&mut enc, &mut cdfs, block.cfl_alphas.expect("cfl"));
5800+ }
57135801 if (V_PRED..=D67_PRED).contains(&uv_mode) {
57145802 enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]);
57155803 }
@@ -5945,6 +6033,9 @@ fn write_inter_frame_leaf(
59456033 }
59466034 let uv_mode = usize::from(block.uv_mode);
59476035 enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]);
6036+ if uv_mode == UV_CFL_PRED {
6037+ write_cfl_alphas(enc, cdfs, block.cfl_alphas.expect("cfl"));
6038+ }
59486039 if (V_PRED..=D67_PRED).contains(&uv_mode) {
59496040 enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]);
59506041 }
@@ -6186,6 +6277,9 @@ fn write_inter_frame_leaf8(
61866277 }
61876278 let uv_mode = usize::from(block.uv_mode);
61886279 enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]);
6280+ if uv_mode == UV_CFL_PRED {
6281+ write_cfl_alphas(enc, cdfs, block.cfl_alphas.expect("cfl"));
6282+ }
61896283 if (V_PRED..=D67_PRED).contains(&uv_mode) {
61906284 enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]);
61916285 }