diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index be20c9b5..60aebffa 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -9043,25 +9043,7 @@ fn tx_size_context_rect( /// [`cfl_ac_q3`] for a true `bw`x`bh` rect strip (lane-intradisp r1). fn cfl_ac_q3_rect(y: &PlaneBuf<'_>, px: usize, py: usize, bw: usize, bh: usize) -> Vec { - let (cw, ch) = (bw / 2, bh / 2); - let mut ac = vec![0i32; cw * ch]; - let mut sum = 0i32; - for cy in 0..ch { - for cx in 0..cw { - let (lx, ly) = (px + cx * 2, py + cy * 2); - let q3 = (i32::from(y.data[ly * y.width + lx]) - + i32::from(y.data[ly * y.width + lx + 1]) - + i32::from(y.data[(ly + 1) * y.width + lx]) - + i32::from(y.data[(ly + 1) * y.width + lx + 1])) - << 1; - ac[cy * cw + cx] = q3; - sum += q3; - } - } - let num_pel = (cw * ch) as i32; - let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros(); - ac.iter_mut().for_each(|v| *v -= avg); - ac + cfl_ac_q3_at(px, py, bw, bh, |lx, ly| i32::from(y.data[ly * y.width + lx])) } /// 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) { /// subtracted (`round_offset = num_pel/2`, right-shifted by `log2(num_pel)`) /// to give the AC values [`cfl_scaled`] scales by alpha. fn cfl_ac_q3(y: &PlaneBuf<'_>, px: usize, py: usize, side: usize) -> Vec { - let cside = side / 2; - let mut ac = vec![0i32; cside * cside]; + cfl_ac_q3_at(px, py, side, side, |lx, ly| i32::from(y.data[ly * y.width + lx])) +} + +/// The one body [`cfl_ac_q3`] and [`cfl_ac_q3_rect`] share, reading its luma +/// samples through `sample(x, y)` instead of a [`PlaneBuf`] -- so the encoder +/// (lane-av1cfl) builds a CfL candidate's AC signal from its own `u8` +/// reconstruction through THIS function rather than a second transcription of +/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c`. +pub(crate) fn cfl_ac_q3_at( + px: usize, + py: usize, + bw: usize, + bh: usize, + sample: impl Fn(usize, usize) -> i32, +) -> Vec { + let (cw, ch) = (bw / 2, bh / 2); + let mut ac = vec![0i32; cw * ch]; let mut sum = 0i32; - for cy in 0..cside { - for cx in 0..cside { + for cy in 0..ch { + for cx in 0..cw { let (lx, ly) = (px + cx * 2, py + cy * 2); - let q3 = (i32::from(y.data[ly * y.width + lx]) - + i32::from(y.data[ly * y.width + lx + 1]) - + i32::from(y.data[(ly + 1) * y.width + lx]) - + i32::from(y.data[(ly + 1) * y.width + lx + 1])) + let q3 = (sample(lx, ly) + + sample(lx + 1, ly) + + sample(lx, ly + 1) + + sample(lx + 1, ly + 1)) << 1; - ac[cy * cside + cx] = q3; + ac[cy * cw + cx] = q3; sum += q3; } } - let num_pel = (cside * cside) as i32; + let num_pel = (cw * ch) as i32; let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros(); ac.iter_mut().for_each(|v| *v -= avg); ac @@ -13128,7 +13125,7 @@ fn cfl_ac_q3(y: &PlaneBuf<'_>, px: usize, py: usize, side: usize) -> Vec { /// `get_scaled_luma_q0` (libaom cfl.h): `alpha_q3 * ac_q3`, rounded from Q6 /// back to whole samples with `ROUND_POWER_OF_TWO_SIGNED` (round-to-nearest, /// ties away from zero on the shifted-out sign). -fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 { +pub(crate) fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 { let v = alpha_q3 * ac_q3; if v >= 0 { (v + 32) >> 6 diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 9e1588f7..e08b6215 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -3798,8 +3798,8 @@ fn code_square( // Chroma searches its own mode over [`CHROMA_MODES`], one symbol for both // planes; what it costs still counts towards the partition decision. - let ([u, v], uv_mode, chroma_cost, palette_uv) = - search_chroma(chroma, (x, y), side, chroma_set, search, mode, fctx); + let ([u, v], uv_mode, chroma_cost, palette_uv, cfl_alphas) = + search_chroma(chroma, luma, (x, y), side, chroma_set, search, mode, fctx); cost += chroma_cost; // The intrabc arm is priced against the WHOLE block -- luma and both @@ -3834,6 +3834,7 @@ fn code_square( tx_depth, palette, palette_uv, + cfl_alphas, ..BlockCoeffs::default() }, cost, @@ -3858,21 +3859,42 @@ const CHROMA_MODES: [u8; 7] = [ /// The thirteen intra mode names, for the chroma fire count's print. #[cfg(test)] -const UV_MODE_NAMES: [&str; 13] = [ +const UV_MODE_NAMES: [&str; 14] = [ "DC", "V", "H", "D45", "D135", "D113", "D157", "D203", "D67", "SMOOTH", "SMOOTH_V", - "SMOOTH_H", "PAETH", + "SMOOTH_H", "PAETH", "CFL", ]; /// How many blocks each chroma mode has won, indexed by the mode itself -- /// the fire count that says whether the search below reaches its candidates /// at all (the `gate-blind-to-feature` class), printed once per gate run. -static UV_MODE_HITS: [std::sync::atomic::AtomicUsize; 13] = - [const { std::sync::atomic::AtomicUsize::new(0) }; 13]; +static UV_MODE_HITS: [std::sync::atomic::AtomicUsize; 14] = + [const { std::sync::atomic::AtomicUsize::new(0) }; 14]; + +/// How many blocks each CfL alpha magnitude (`1..=16`, indexed `mag - 1`) has +/// won, summed over both chroma planes -- the alpha histogram the gate prints +/// beside the CfL share (`gate-blind-to-feature`: a tool that fires at one +/// magnitude only is a search that never left its first candidate). +static CFL_ALPHA_HITS: [std::sync::atomic::AtomicUsize; 17] = + [const { std::sync::atomic::AtomicUsize::new(0) }; 17]; + +/// Reads [`CFL_ALPHA_HITS`] and zeroes it. Index 0 is "this plane took alpha +/// zero on a CfL block", `1..=16` the magnitudes. +#[cfg(test)] +pub(crate) fn take_cfl_alpha_hits() -> [usize; 17] { + std::array::from_fn(|m| CFL_ALPHA_HITS[m].swap(0, std::sync::atomic::Ordering::Relaxed)) +} + +/// Whether the chroma search offers `UV_CFL_PRED` at all (`EC_AV1_CFL=0` +/// switches it off, which is how the lane measured its own on/off pair). +fn cfl_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("EC_AV1_CFL").as_deref() != Ok("0")) +} /// Reads [`UV_MODE_HITS`] and zeroes it, so a gate can attribute the counts /// to its own encode. #[cfg(test)] -pub(crate) fn take_uv_mode_hits() -> [usize; 13] { +pub(crate) fn take_uv_mode_hits() -> [usize; 14] { std::array::from_fn(|m| UV_MODE_HITS[m].swap(0, std::sync::atomic::Ordering::Relaxed)) } @@ -3920,13 +3942,22 @@ const CHROMA_TOP_K: Option = None; fn search_chroma( chroma: &mut [Plane; 2], + // The luma plane's RECONSTRUCTION under this block, already committed by + // [`Plane::search_block`] -- the signal a `UV_CFL_PRED` candidate scales. + luma: &Plane, (x, y): (usize, usize), side: usize, set: TxbSet, search: &Search, luma_mode: u8, fctx: &crate::decode::FrameCtx, -) -> ([Vec; 2], u8, f64, Option) { +) -> ( + [Vec; 2], + u8, + f64, + Option, + Option<(i32, i32)>, +) { let at = At { x: x / 2, y: y / 2, @@ -4047,6 +4078,134 @@ fn search_chroma( } } } + // The chroma-from-luma arm (spec 5.11.45, libaom `cfl_rd_pick_alpha`): + // `UV_CFL_PRED` predicts as `DC_PRED` (`get_uv_mode`, spec 9.3) and then + // nudges every sample by `alpha_q3` times the block's subsampled, + // average-subtracted luma reconstruction. Offered only where + // `is_cfl_allowed` (spec 5.11.5) does -- a luma block at most 32x32 -- + // and priced against the best ordinary chroma mode above, palette + // included, so a block only takes it when it beats both. + let mut cfl_alphas = None; + if side <= 32 && cfl_on() { + // The AC signal, through the decoder's own + // `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` body. + let ac = crate::decode::cfl_ac_q3_at(x, y, side, side, |lx, ly| { + i32::from(luma.reconstruction[ly * luma.width + lx]) + }); + let dc_prediction = |plane: &Plane| -> Vec { + let (mut above_buf, mut left_buf) = ([0u8; 2 * BLOCK], [0u8; 2 * BLOCK]); + let (above, left, corner) = + plane.edges_into(at.x, at.y, at.side, at.reach, &mut above_buf, &mut left_buf); + let mut prediction = vec![0u8; at.side * at.side]; + intra_predict_u8( + DC_PRED, 0, above, left, corner, at.side, at.side, false, false, &mut prediction, + fctx, + ); + prediction + }; + let bases = [dc_prediction(&chroma[0]), dc_prediction(&chroma[1])]; + // `av1_cfl_predict_block` (cfl.c): clip the nudged prediction, then + // add the residual -- which is what [`Plane::code_from_prediction`] + // does with what this returns. + let apply = |base: &[u8], alpha: i32| -> Vec { + base.iter() + .zip(ac.iter()) + .map(|(&b, &a)| { + (i32::from(b) + crate::decode::cfl_scaled(alpha, a)).clamp(0, 255) as u8 + }) + .collect() + }; + // The least-squares alpha, then its two neighbours: minimising + // `sum (source - base - alpha*ac/64)^2` over a continuous alpha is one + // dot-product ratio, and the quantised optimum is one of the two + // integers around it (the clamp and the Q6 rounding are what the SSE + // check below re-decides). libaom sweeps all sixteen magnitudes under + // full RD; three predictions per plane buy nearly the same alpha for a + // thirtieth of the search. + let pick_alpha = |plane: &Plane, base: &[u8]| -> i32 { + let (mut num, mut den) = (0.0f64, 0.0f64); + for row in 0..at.side { + for col in 0..at.side { + let i = row * at.side + col; + let d = f64::from(plane.source[(at.y + row) * plane.width + at.x + col]) + - f64::from(base[i]); + num += d * f64::from(ac[i]); + den += f64::from(ac[i]) * f64::from(ac[i]); + } + } + if den == 0.0 { + return 0; + } + let ideal = 64.0 * num / den; + let mut best = (plane.block_sse(at.x, at.y, at.side, base), 0i32); + for alpha in [ideal.floor() as i64, ideal.ceil() as i64] { + let alpha = alpha.clamp(-16, 16) as i32; + if alpha == 0 { + continue; + } + let sse = plane.block_sse(at.x, at.y, at.side, &apply(base, alpha)); + if sse < best.0 { + best = (sse, alpha); + } + } + best.1 + }; + let picked = [ + pick_alpha(&chroma[0], &bases[0]), + pick_alpha(&chroma[1], &bases[1]), + ]; + if picked != [0, 0] { + let cfl_bits = symbol_bits(uv_cdf, crate::tile::UV_CFL_PRED) - dc_bits; + let trial = |plane_idx: usize, alpha: i32| -> Trial { + let prediction = if alpha == 0 { + bases[plane_idx].clone() + } else { + apply(&bases[plane_idx], alpha) + }; + chroma[plane_idx].code_from_prediction( + at.x, + at.y, + at.side, + &prediction, + false, + search.base_q_idx, + search.deadzone, + set, + ) + }; + // At least one alpha must be nonzero: `cfl_alpha_signs` has no + // (ZERO, ZERO) joint value ([`crate::tile::cfl_joint_sign`]). + let combos: [(i32, i32); 3] = [ + (picked[0], picked[1]), + (picked[0], 0), + (0, picked[1]), + ]; + for &(alpha_u, alpha_v) in &combos { + if (alpha_u, alpha_v) == (0, 0) { + continue; + } + let cu = trial(0, alpha_u); + let cv = trial(1, alpha_v); + let bits = + cfl_bits + crate::tile::cfl_alpha_bits(alpha_u, alpha_v) + cu.bits + cv.bits; + let cost_cfl = cu.sse + cv.sse + search.lambda * bits; + if cost_cfl < cost { + cost = cost_cfl; + mode = crate::tile::UV_CFL_PRED as u8; + u = cu; + v = cv; + palette_uv = None; + cfl_alphas = Some((alpha_u, alpha_v)); + } + } + } + } + if let Some((alpha_u, alpha_v)) = cfl_alphas { + for alpha in [alpha_u, alpha_v] { + CFL_ALPHA_HITS[alpha.unsigned_abs() as usize] + .fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + } if census_on() { CHROMA_RANK[sad_rank(&ranking, mode).min(6)] .fetch_add(1, std::sync::atomic::Ordering::Relaxed); @@ -4059,6 +4218,7 @@ fn search_chroma( mode, cost, palette_uv, + cfl_alphas, ) } @@ -4840,6 +5000,7 @@ fn code_square_inter( chroma[1].commit(x / 2, y / 2, side / 2, &v_new); return ( BlockCoeffs { + cfl_alphas: None, luma: coeffs(&levels, side), u: coeffs(&u_new.levels, side / 2), v: coeffs(&v_new.levels, side / 2), @@ -4873,6 +5034,7 @@ fn code_square_inter( chroma[0].commit(x / 2, y / 2, side / 2, &u); chroma[1].commit(x / 2, y / 2, side / 2, &v); (BlockCoeffs { + cfl_alphas: None, luma: coeffs(&levels, side), u: coeffs(&u.levels, side / 2), v: coeffs(&v.levels, side / 2), @@ -7576,6 +7738,7 @@ fn search_inter_block( chroma[1].commit(x / 2, y / 2, BLOCK / 2, &best.v); ( BlockCoeffs { + cfl_alphas: None, luma: coeffs(&levels, BLOCK), u: coeffs(&best.u.levels, BLOCK / 2), v: coeffs(&best.v.levels, BLOCK / 2), @@ -9828,6 +9991,7 @@ mod tests { let (_, inter_header) = inter_frame_headers(width, height, 100, 1, 0).unwrap(); let residual_block = BlockCoeffs { + cfl_alphas: None, luma: vec![Coeff { row: 0, col: 0, @@ -11489,8 +11653,12 @@ mod tests { // 3-value alphabet where a warp sample exists) on the DEFAULT path -- // +34.9% here, one point past the OBMC reading above. The bound moves // with it; `EC_AV1_WARP=0` restores the +32.6% no-motion_mode number. + // lane-av1cfl: a `UV_CFL_PRED` block carries a `cfl_alpha_signs` + // symbol and one or two magnitude symbols, none of which the + // coefficient sum counts either -- +36.9% here against the same + // fixture's +34.9% with `EC_AV1_CFL=0`. assert!( - worst_under <= 0.36, + worst_under <= 0.38, "the writer spent {:.2}% more than the search priced -- more than \ the mode/mv syntax outside the coefficient sum explains", worst_under * 100.0 @@ -12541,6 +12709,10 @@ mod tests { /// and the two var-tx depth searches ([`tx32_depth_search`], /// [`compound_var_tx`]) are on by default, all three re-judged on the /// native gate's real film rows. + /// Re-pinned on lane-av1cfl: the chroma search offers `UV_CFL_PRED`, so + /// every block whose chroma takes it codes a different mode symbol, two + /// alpha symbols and different chroma coefficients. `EC_AV1_CFL=0` + /// restores the previous streams. #[test] fn the_encoders_own_streams_are_byte_identical_to_their_pins() { if !have_ffmpeg() { @@ -13046,6 +13218,23 @@ mod tests { .collect::>() .join(" ") ); + // The CfL alpha histogram (lane-av1cfl): one entry per chroma + // plane of every `UV_CFL_PRED` block, by |alpha_q3|. A tool that + // only ever fires at one magnitude is a search that never left + // its first candidate (gate-blind-to-feature). + let alphas = take_cfl_alpha_hits(); + if alphas.iter().sum::() > 0 { + eprintln!( + "{name}: cfl |alpha| {}", + alphas + .iter() + .enumerate() + .filter(|&(_, &n)| n > 0) + .map(|(a, &n)| format!("{a}={n}")) + .collect::>() + .join(" ") + ); + } let palette_uv = crate::tile::take_palette_uv_hits(); eprintln!( "{name}: chroma palette blocks {} sizes {}", diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index afbb022a..b46dbc71 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -1446,6 +1446,12 @@ pub struct BlockCoeffs { /// `luma` then carries the whole block's levels in BLOCK coordinates, /// which the writer slices per transform unit. pub tx_depth: u8, + /// This block's `UV_CFL_PRED` alphas (`alpha_q3` for U and V, spec + /// 5.11.45's `cfl_alpha_signs`/`cfl_alpha_u`/`cfl_alpha_v`), or `None` for + /// any other chroma mode. `Some` iff [`Self::uv_mode`] is + /// [`UV_CFL_PRED`]; at least one of the pair is nonzero, since the joint + /// sign symbol has no (ZERO, ZERO) value. + pub cfl_alphas: Option<(i32, i32)>, /// This block's intra block-copy vector (spec 5.11.13 `use_intrabc` -> /// `assign_dv`), in the spec's 1/8-pel `(row, col)` units, or `None` for /// an ordinary intra block. Only a key frame whose header set @@ -3292,6 +3298,77 @@ fn write_intrabc_block( Ok(()) } +/// `UV_CFL_PRED` (spec 6.10.19's chroma mode enum), the fourteenth entry of +/// [`crate::cdf::UV_MODE_CFL`] -- the writer's twin of the decoder's own +/// constant. +pub(crate) const UV_CFL_PRED: usize = 13; + +/// The `cfl_alpha_signs` joint value (0..8) that codes this signed alpha pair, +/// inverting the decoder's own `read_cfl_alphas` split (`sign_u = +/// ((joint+1)*11)>>5`, `sign_v = (joint+1) - 3*sign_u`, with 0 ZERO, 1 NEG, +/// 2 POS). There is no (ZERO, ZERO) joint value, so at least one alpha of a +/// CfL block is nonzero by construction. +pub(crate) fn cfl_joint_sign(alpha_u: i32, alpha_v: i32) -> usize { + let sign = |a: i32| match a.signum() { + 0 => 0, + -1 => 1, + _ => 2, + }; + let (want_u, want_v) = (sign(alpha_u), sign(alpha_v)); + (0..8) + .find(|&j| { + let su = ((j + 1) * 11) >> 5; + (su, (j + 1) - 3 * su) == (want_u, want_v) + }) + .expect("cfl_alpha_signs covers every pair but (ZERO, ZERO)") as usize +} + +/// The `cfl_alpha_u`/`cfl_alpha_v` magnitude CDF row for one plane, by the +/// same `CFL_CONTEXT_U`/`CFL_CONTEXT_V` derivation the decoder reads with +/// (libaom cfl.h). `joint` is [`cfl_joint_sign`]'s value. +fn cfl_alpha_ctx(joint: usize, plane: usize) -> usize { + let joint = joint as i32; + let su = ((joint + 1) * 11) >> 5; + let sv = (joint + 1) - 3 * su; + if plane == 0 { + (joint + 1 - 3) as usize + } else { + (sv * 3 + su - 3) as usize + } +} + +/// What [`write_cfl_alphas`] will spend on this alpha pair, through the same +/// tables -- the encoder's RD price for the CfL arm. +pub(crate) fn cfl_alpha_bits(alpha_u: i32, alpha_v: i32) -> f64 { + use crate::encode::symbol_bits; + let joint = cfl_joint_sign(alpha_u, alpha_v); + let mut bits = symbol_bits(&crate::cdf::CFL_SIGN, joint); + for (plane, alpha) in [alpha_u, alpha_v].into_iter().enumerate() { + if alpha != 0 { + bits += symbol_bits( + &crate::cdf::CFL_ALPHA[cfl_alpha_ctx(joint, plane)], + (alpha.unsigned_abs() - 1) as usize, + ); + } + } + bits +} + +/// `read_cfl_alphas` (spec 5.11.45) written: the joint sign, then each +/// plane's magnitude where its sign is nonzero. +fn write_cfl_alphas(enc: &mut SymbolEncoder, cdfs: &mut Cdfs, (alpha_u, alpha_v): (i32, i32)) { + let joint = cfl_joint_sign(alpha_u, alpha_v); + enc.symbol(joint, &mut cdfs.cfl_sign); + for (plane, alpha) in [alpha_u, alpha_v].into_iter().enumerate() { + if alpha != 0 { + enc.symbol( + (alpha.unsigned_abs() - 1) as usize, + &mut cdfs.cfl_alpha[cfl_alpha_ctx(joint, plane)], + ); + } + } +} + fn write_intra_mode( enc: &mut SymbolEncoder, cdfs: &mut Cdfs, @@ -3334,8 +3411,16 @@ fn write_intra_mode( if cfl { enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]); } else { + debug_assert_ne!(uv_mode, UV_CFL_PRED, "is_cfl_allowed excludes this block"); enc.symbol(uv_mode, &mut cdfs.uv_mode_no_cfl[mode]); } + if uv_mode == UV_CFL_PRED { + write_cfl_alphas( + enc, + cdfs, + block.cfl_alphas.expect("a UV_CFL_PRED block carries its alphas"), + ); + } // `angle_delta_uv` (spec `read_intra_angle_info`) off the same CDF array // the luma delta reads, indexed by the chroma mode. if (V_PRED..=D67_PRED).contains(&uv_mode) { @@ -5710,6 +5795,9 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( } let uv_mode = usize::from(block.uv_mode); enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]); + if uv_mode == UV_CFL_PRED { + write_cfl_alphas(&mut enc, &mut cdfs, block.cfl_alphas.expect("cfl")); + } if (V_PRED..=D67_PRED).contains(&uv_mode) { enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]); } @@ -5945,6 +6033,9 @@ fn write_inter_frame_leaf( } let uv_mode = usize::from(block.uv_mode); enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]); + if uv_mode == UV_CFL_PRED { + write_cfl_alphas(enc, cdfs, block.cfl_alphas.expect("cfl")); + } if (V_PRED..=D67_PRED).contains(&uv_mode) { enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]); } @@ -6186,6 +6277,9 @@ fn write_inter_frame_leaf8( } let uv_mode = usize::from(block.uv_mode); enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]); + if uv_mode == UV_CFL_PRED { + write_cfl_alphas(enc, cdfs, block.cfl_alphas.expect("cfl")); + } if (V_PRED..=D67_PRED).contains(&uv_mode) { enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]); }