forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-av1cfl' (012f8eab): chroma-from-luma and luma angle deltas in the intra search; the rate loop's per-slot acquisition step

Browse files at this commit

5546c56c1c343ffc009dbc929057439ec6bc8c62Ahmet Kaan GümüşParent: 77aeca19a6b2f7
Native rows: film A +54.1/+24.2 -> +53.2/+23.4, film B +82.6/+47.4 ->
+81.5/+46.5, screen +50.1/-15.4 -> +49.3/-16.0, bars -17/-29 points (CfL
wins half their chroma blocks). The bitrate undershoot at 1536k with the
pyramid was convergence lag (STEP_CLAMP walked 12 q-steps a frame): one
unclamped acquisition step per slot, -10.2% -> -2.7%. Pins 7321 / 27285.
crates/ec-av1/src/decode.rsmodified+27 -30
@@ -9043,25 +9043,7 @@ fn tx_size_context_rect(
9043 9043
9044 /// [`cfl_ac_q3`] for a true `bw`x`bh` rect strip (lane-intradisp r1).9044 /// [`cfl_ac_q3`] for a true `bw`x`bh` rect strip (lane-intradisp r1).
9045 fn cfl_ac_q3_rect(y: &PlaneBuf<'_>, px: usize, py: usize, bw: usize, bh: usize) -> Vec<i32> {9045 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);9046+ cfl_ac_q3_at(px, py, bw, bh, |lx, ly| i32::from(y.data[ly * y.width + lx]))
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
9065 }9047 }
9066 9048
9067 /// Everything a rect strip already read out of the stream before its luma9049 /// 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) {
13104 /// subtracted (`round_offset = num_pel/2`, right-shifted by `log2(num_pel)`)13086 /// subtracted (`round_offset = num_pel/2`, right-shifted by `log2(num_pel)`)
13105 /// to give the AC values [`cfl_scaled`] scales by alpha.13087 /// to give the AC values [`cfl_scaled`] scales by alpha.
13106 fn cfl_ac_q3(y: &PlaneBuf<'_>, px: usize, py: usize, side: usize) -> Vec<i32> {13088 fn cfl_ac_q3(y: &PlaneBuf<'_>, px: usize, py: usize, side: usize) -> Vec<i32> {
13107- let cside = side / 2;13089+ cfl_ac_q3_at(px, py, side, side, |lx, ly| i32::from(y.data[ly * y.width + lx]))
13108- let mut ac = vec![0i32; cside * cside];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];
13109 let mut sum = 0i32;13106 let mut sum = 0i32;
13110- for cy in 0..cside {13107+ for cy in 0..ch {
13111- for cx in 0..cside {13108+ for cx in 0..cw {
13112 let (lx, ly) = (px + cx * 2, py + cy * 2);13109 let (lx, ly) = (px + cx * 2, py + cy * 2);
13113- let q3 = (i32::from(y.data[ly * y.width + lx])13110+ let q3 = (sample(lx, ly)
13114- + i32::from(y.data[ly * y.width + lx + 1])13111+ + sample(lx + 1, ly)
13115- + i32::from(y.data[(ly + 1) * y.width + lx])13112+ + sample(lx, ly + 1)
13116- + i32::from(y.data[(ly + 1) * y.width + lx + 1]))13113+ + sample(lx + 1, ly + 1))
13117 << 1;13114 << 1;
13118- ac[cy * cside + cx] = q3;13115+ ac[cy * cw + cx] = q3;
13119 sum += q3;13116 sum += q3;
13120 }13117 }
13121 }13118 }
13122- let num_pel = (cside * cside) as i32;13119+ let num_pel = (cw * ch) as i32;
13123 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();13120 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
13124 ac.iter_mut().for_each(|v| *v -= avg);13121 ac.iter_mut().for_each(|v| *v -= avg);
13125 ac13122 ac
@@ -13128,7 +13125,7 @@ fn cfl_ac_q3(y: &PlaneBuf<'_>, px: usize, py: usize, side: usize) -> Vec<i32> {
13128 /// `get_scaled_luma_q0` (libaom cfl.h): `alpha_q3 * ac_q3`, rounded from Q613125 /// `get_scaled_luma_q0` (libaom cfl.h): `alpha_q3 * ac_q3`, rounded from Q6
13129 /// back to whole samples with `ROUND_POWER_OF_TWO_SIGNED` (round-to-nearest,13126 /// back to whole samples with `ROUND_POWER_OF_TWO_SIGNED` (round-to-nearest,
13130 /// ties away from zero on the shifted-out sign).13127 /// 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 {
13132 let v = alpha_q3 * ac_q3;13129 let v = alpha_q3 * ac_q3;
13133 if v >= 0 {13130 if v >= 0 {
13134 (v + 32) >> 613131 (v + 32) >> 6
crates/ec-av1/src/encode.rsmodified+325 -21
@@ -1561,8 +1561,8 @@ impl Plane<'_> {
1561 /// Codes one block under one mode without committing it: hands back the1561 /// Codes one block under one mode without committing it: hands back the
1562 /// levels, the block the decoder would reconstruct, the squared error1562 /// levels, the block the decoder would reconstruct, the squared error
1563 /// against the source and an estimate of what the levels cost in bits.1563 /// against the source and an estimate of what the levels cost in bits.
1564- fn trial(&self, at: At, mode: u8, base_q_idx: u8, deadzone: f64, fctx: &crate::decode::FrameCtx) -> Trial {1564+ fn trial(&self, at: At, mode: u8, angle_delta: i32, base_q_idx: u8, deadzone: f64, fctx: &crate::decode::FrameCtx) -> Trial {
1565- self.trial_typed(at, mode, base_q_idx, deadzone, TxType::DctDct, fctx)1565+ self.trial_typed(at, mode, angle_delta, base_q_idx, deadzone, TxType::DctDct, fctx)
1566 }1566 }
1567 1567
1568 /// [`Self::trial`] under a named transform type -- what an intra chroma1568 /// [`Self::trial`] under a named transform type -- what an intra chroma
@@ -1609,6 +1609,10 @@ impl Plane<'_> {
1609 &self,1609 &self,
1610 at: At,1610 at: At,
1611 mode: u8,1611 mode: u8,
1612+ // This block's `angle_delta_y`/`angle_delta_uv` (spec
1613+ // `read_intra_angle_info`, -3..=3), zero for every non-directional
1614+ // mode -- the predictor's own `angle_delta` argument.
1615+ angle_delta: i32,
1612 base_q_idx: u8,1616 base_q_idx: u8,
1613 deadzone: f64,1617 deadzone: f64,
1614 tx_type: TxType,1618 tx_type: TxType,
@@ -1627,7 +1631,7 @@ impl Plane<'_> {
1627 let prediction = &mut prediction[..side * side];1631 let prediction = &mut prediction[..side * side];
1628 intra_predict_u8(1632 intra_predict_u8(
1629 mode,1633 mode,
1630- 0,1634+ angle_delta,
1631 above,1635 above,
1632 left,1636 left,
1633 corner,1637 corner,
@@ -1815,6 +1819,7 @@ impl Plane<'_> {
1815 &mut self,1819 &mut self,
1816 at: At,1820 at: At,
1817 mode: u8,1821 mode: u8,
1822+ angle_delta: i32,
1818 depth: usize,1823 depth: usize,
1819 search: &Search, fctx: &crate::decode::FrameCtx,1824 search: &Search, fctx: &crate::decode::FrameCtx,
1820 ) -> (Vec<i32>, f64, f64) {1825 ) -> (Vec<i32>, f64, f64) {
@@ -1843,7 +1848,7 @@ impl Plane<'_> {
1843 reach: Reach::of_tu(side, side, col_off, row_off, tx, tx, reach),1848 reach: Reach::of_tu(side, side, col_off, row_off, tx, tx, reach),
1844 set,1849 set,
1845 };1850 };
1846- let trial = self.trial(tu, mode, search.base_q_idx, search.deadzone, fctx);1851+ let trial = self.trial(tu, mode, angle_delta, search.base_q_idx, search.deadzone, fctx);
1847 sse += trial.sse;1852 sse += trial.sse;
1848 bits += trial.bits;1853 bits += trial.bits;
1849 self.commit(tu.x, tu.y, tx, &trial);1854 self.commit(tu.x, tu.y, tx, &trial);
@@ -2072,7 +2077,7 @@ impl Plane<'_> {
2072 at: At,2077 at: At,
2073 search: &Search,2078 search: &Search,
2074 mode_bits: &[f64; 13], fctx: &crate::decode::FrameCtx,2079 mode_bits: &[f64; 13], fctx: &crate::decode::FrameCtx,
2075- ) -> (Vec<Coeff>, u8, f64) {2080+ ) -> (Vec<Coeff>, u8, i32, f64) {
2076 let At {2081 let At {
2077 x, y, side, reach, ..2082 x, y, side, reach, ..
2078 } = at;2083 } = at;
@@ -2155,13 +2160,69 @@ impl Plane<'_> {
2155 best = Some((cost, mode, trial));2160 best = Some((cost, mode, trial));
2156 }2161 }
2157 }2162 }
2158- let (cost, mode, trial) = best.expect("the search offers at least one mode");2163+ let (mut cost, mode, mut trial) = best.expect("the search offers at least one mode");
2164+ // `angle_delta_y` (spec `read_intra_angle_info`): the eight
2165+ // directional modes each carry a -3..=3 delta, three degrees a step,
2166+ // which the writer has always coded as ZERO because nothing searched
2167+ // it. Refined on the winning mode only -- libaom's own ordering, and
2168+ // six extra trials on the directional blocks instead of on every
2169+ // block times every mode. The edges are the ones the base angle
2170+ // already read (`enable_intra_edge_filter` is off in this encoder's
2171+ // sequence header, so no delta changes which samples exist), and the
2172+ // predictor is the decoder's, `angle_delta` argument and all.
2173+ let mut angle_delta = 0i32;
2174+ // Not on a screen frame: measured on the 5-row native gate, the
2175+ // refinement is worth -0.6/-0.6 on the 2160p film row and flat on the
2176+ // 1080p one, but +0.7/+0.3 the WRONG way on the screen capture --
2177+ // synthetic edges land on the base angles, so every delta there buys
2178+ // a symbol and no prediction. Same `search.screen` gate palette and
2179+ // intrabc already stand behind.
2180+ if angle_delta_on() && !search.screen && (V_PRED..=D67_PRED).contains(&mode) {
2181+ let row = &cdf::ANGLE_DELTA[usize::from(mode - V_PRED)];
2182+ let zero_bits = symbol_bits(row, crate::tile::ANGLE_DELTA_ZERO);
2183+ let mut prediction = vec![0u8; side * side];
2184+ for delta in [-3i32, -2, -1, 1, 2, 3] {
2185+ intra_predict_u8(
2186+ mode,
2187+ delta,
2188+ above,
2189+ left,
2190+ corner,
2191+ side,
2192+ side,
2193+ false,
2194+ false,
2195+ &mut prediction, fctx,
2196+ );
2197+ let candidate = self.code_from_prediction(
2198+ x,
2199+ y,
2200+ side,
2201+ &prediction,
2202+ false,
2203+ search.base_q_idx,
2204+ search.deadzone,
2205+ at.set,
2206+ );
2207+ let bits = symbol_bits(row, (crate::tile::ANGLE_DELTA_ZERO as i32 + delta) as usize)
2208+ - zero_bits;
2209+ let cost_d = candidate.sse
2210+ + search.lambda * (candidate.bits + mode_bits[usize::from(mode)] + bits);
2211+ if cost_d < cost {
2212+ cost = cost_d;
2213+ angle_delta = delta;
2214+ trial = candidate;
2215+ }
2216+ }
2217+ ANGLE_DELTA_HITS[(crate::tile::ANGLE_DELTA_ZERO as i32 + angle_delta) as usize]
2218+ .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2219+ }
2159 if census_on() {2220 if census_on() {
2160 LUMA_RANK[sad_rank(&ranking, mode).min(12)]2221 LUMA_RANK[sad_rank(&ranking, mode).min(12)]
2161 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);2222 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2162 }2223 }
2163 self.commit(x, y, side, &trial);2224 self.commit(x, y, side, &trial);
2164- (coeffs(&trial.levels, side), mode, cost)2225+ (coeffs(&trial.levels, side), mode, angle_delta, cost)
2165 }2226 }
2166 }2227 }
2167 2228
@@ -3720,7 +3781,8 @@ fn code_square(
3720 reach: Reach::of(side, x, y, luma.true_width, luma.true_height, fctx),3781 reach: Reach::of(side, x, y, luma.true_width, luma.true_height, fctx),
3721 set: luma_set,3782 set: luma_set,
3722 };3783 };
3723- let (mut luma_coeffs, mode, mut cost) = luma.search_block(at, search, mode_bits, fctx);3784+ let (mut luma_coeffs, mode, angle_delta, mut cost) =
3785+ luma.search_block(at, search, mode_bits, fctx);
3724 // The depth search runs on the mode the whole-block transform picked --3786 // The depth search runs on the mode the whole-block transform picked --
3725 // libaom's own ordering, and the reason it costs one extra pass per depth3787 // libaom's own ordering, and the reason it costs one extra pass per depth
3726 // rather than one per (mode, depth) pair.3788 // rather than one per (mode, depth) pair.
@@ -3733,7 +3795,7 @@ fn code_square(
3733 luma_coeffs,3795 luma_coeffs,
3734 );3796 );
3735 for depth in 1..=max_tx_depth(side) {3797 for depth in 1..=max_tx_depth(side) {
3736- let (levels, sse, bits) = luma.code_tx_depth(at, mode, depth, search, fctx);3798+ let (levels, sse, bits) = luma.code_tx_depth(at, mode, angle_delta, depth, search, fctx);
3737 let cost_d = sse3799 let cost_d = sse
3738 + search.lambda3800 + search.lambda
3739 * (bits + mode_bits[usize::from(mode)] + tx_depth_bits(side, depth));3801 * (bits + mode_bits[usize::from(mode)] + tx_depth_bits(side, depth));
@@ -3753,6 +3815,7 @@ fn code_square(
3753 // A palette block is `DC_PRED` with `tx_depth` 0 by construction: its3815 // A palette block is `DC_PRED` with `tx_depth` 0 by construction: its
3754 // prediction is the colour map, not the DC of its neighbours.3816 // prediction is the colour map, not the DC of its neighbours.
3755 let mut mode = mode;3817 let mut mode = mode;
3818+ let mut angle_delta = angle_delta;
3756 let mut palette = None;3819 let mut palette = None;
3757 if search.screen && crate::decode::palette_bsize_ctx(side).is_some() {3820 if search.screen && crate::decode::palette_bsize_ctx(side).is_some() {
3758 let source: Vec<u8> = (y..y + side)3821 let source: Vec<u8> = (y..y + side)
@@ -3785,6 +3848,7 @@ fn code_square(
3785 if cost_p < cost {3848 if cost_p < cost {
3786 cost = cost_p;3849 cost = cost_p;
3787 mode = DC_PRED as u8;3850 mode = DC_PRED as u8;
3851+ angle_delta = 0;
3788 tx_depth = 0;3852 tx_depth = 0;
3789 luma_coeffs = coeffs(&trial.levels, side);3853 luma_coeffs = coeffs(&trial.levels, side);
3790 luma.commit(x, y, side, &trial);3854 luma.commit(x, y, side, &trial);
@@ -3798,8 +3862,8 @@ fn code_square(
3798 3862
3799 // Chroma searches its own mode over [`CHROMA_MODES`], one symbol for both3863 // Chroma searches its own mode over [`CHROMA_MODES`], one symbol for both
3800 // planes; what it costs still counts towards the partition decision.3864 // planes; what it costs still counts towards the partition decision.
3801- let ([u, v], uv_mode, chroma_cost, palette_uv) =3865+ let ([u, v], uv_mode, chroma_cost, palette_uv, cfl_alphas) =
3802- search_chroma(chroma, (x, y), side, chroma_set, search, mode, fctx);3866+ search_chroma(chroma, luma, (x, y), side, chroma_set, search, mode, fctx);
3803 cost += chroma_cost;3867 cost += chroma_cost;
3804 3868
3805 // The intrabc arm is priced against the WHOLE block -- luma and both3869 // The intrabc arm is priced against the WHOLE block -- luma and both
@@ -3834,6 +3898,8 @@ fn code_square(
3834 tx_depth,3898 tx_depth,
3835 palette,3899 palette,
3836 palette_uv,3900 palette_uv,
3901+ cfl_alphas,
3902+ angle_delta_y: angle_delta as i8,
3837 ..BlockCoeffs::default()3903 ..BlockCoeffs::default()
3838 },3904 },
3839 cost,3905 cost,
@@ -3858,21 +3924,61 @@ const CHROMA_MODES: [u8; 7] = [
3858 3924
3859 /// The thirteen intra mode names, for the chroma fire count's print.3925 /// The thirteen intra mode names, for the chroma fire count's print.
3860 #[cfg(test)]3926 #[cfg(test)]
3861-const UV_MODE_NAMES: [&str; 13] = [3927+const UV_MODE_NAMES: [&str; 14] = [
3862 "DC", "V", "H", "D45", "D135", "D113", "D157", "D203", "D67", "SMOOTH", "SMOOTH_V",3928 "DC", "V", "H", "D45", "D135", "D113", "D157", "D203", "D67", "SMOOTH", "SMOOTH_V",
3863- "SMOOTH_H", "PAETH",3929+ "SMOOTH_H", "PAETH", "CFL",
3864 ];3930 ];
3865 3931
3866 /// How many blocks each chroma mode has won, indexed by the mode itself --3932 /// How many blocks each chroma mode has won, indexed by the mode itself --
3867 /// the fire count that says whether the search below reaches its candidates3933 /// the fire count that says whether the search below reaches its candidates
3868 /// at all (the `gate-blind-to-feature` class), printed once per gate run.3934 /// at all (the `gate-blind-to-feature` class), printed once per gate run.
3869-static UV_MODE_HITS: [std::sync::atomic::AtomicUsize; 13] =3935+static UV_MODE_HITS: [std::sync::atomic::AtomicUsize; 14] =
3870- [const { std::sync::atomic::AtomicUsize::new(0) }; 13];3936+ [const { std::sync::atomic::AtomicUsize::new(0) }; 14];
3937+
3938+/// How many blocks each CfL alpha magnitude (`1..=16`, indexed `mag - 1`) has
3939+/// won, summed over both chroma planes -- the alpha histogram the gate prints
3940+/// beside the CfL share (`gate-blind-to-feature`: a tool that fires at one
3941+/// magnitude only is a search that never left its first candidate).
3942+static CFL_ALPHA_HITS: [std::sync::atomic::AtomicUsize; 17] =
3943+ [const { std::sync::atomic::AtomicUsize::new(0) }; 17];
3944+
3945+/// Reads [`CFL_ALPHA_HITS`] and zeroes it. Index 0 is "this plane took alpha
3946+/// zero on a CfL block", `1..=16` the magnitudes.
3947+#[cfg(test)]
3948+pub(crate) fn take_cfl_alpha_hits() -> [usize; 17] {
3949+ std::array::from_fn(|m| CFL_ALPHA_HITS[m].swap(0, std::sync::atomic::Ordering::Relaxed))
3950+}
3951+
3952+/// How many directional luma blocks won at each `angle_delta_y`, indexed
3953+/// `delta + 3` -- the histogram that says whether the refinement below ever
3954+/// leaves zero (`gate-blind-to-feature`).
3955+static ANGLE_DELTA_HITS: [std::sync::atomic::AtomicUsize; 7] =
3956+ [const { std::sync::atomic::AtomicUsize::new(0) }; 7];
3957+
3958+/// Reads [`ANGLE_DELTA_HITS`] and zeroes it.
3959+#[cfg(test)]
3960+pub(crate) fn take_angle_delta_hits() -> [usize; 7] {
3961+ std::array::from_fn(|d| ANGLE_DELTA_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed))
3962+}
3963+
3964+/// Whether the luma search refines a directional winner's `angle_delta_y`
3965+/// (`EC_AV1_ANGLE=0` switches it off, the lane's own on/off pair).
3966+fn angle_delta_on() -> bool {
3967+ static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
3968+ *ON.get_or_init(|| std::env::var("EC_AV1_ANGLE").as_deref() != Ok("0"))
3969+}
3970+
3971+/// Whether the chroma search offers `UV_CFL_PRED` at all (`EC_AV1_CFL=0`
3972+/// switches it off, which is how the lane measured its own on/off pair).
3973+fn cfl_on() -> bool {
3974+ static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
3975+ *ON.get_or_init(|| std::env::var("EC_AV1_CFL").as_deref() != Ok("0"))
3976+}
3871 3977
3872 /// Reads [`UV_MODE_HITS`] and zeroes it, so a gate can attribute the counts3978 /// Reads [`UV_MODE_HITS`] and zeroes it, so a gate can attribute the counts
3873 /// to its own encode.3979 /// to its own encode.
3874 #[cfg(test)]3980 #[cfg(test)]
3875-pub(crate) fn take_uv_mode_hits() -> [usize; 13] {3981+pub(crate) fn take_uv_mode_hits() -> [usize; 14] {
3876 std::array::from_fn(|m| UV_MODE_HITS[m].swap(0, std::sync::atomic::Ordering::Relaxed))3982 std::array::from_fn(|m| UV_MODE_HITS[m].swap(0, std::sync::atomic::Ordering::Relaxed))
3877 }3983 }
3878 3984
@@ -3920,13 +4026,22 @@ const CHROMA_TOP_K: Option<usize> = None;
3920 4026
3921 fn search_chroma(4027 fn search_chroma(
3922 chroma: &mut [Plane; 2],4028 chroma: &mut [Plane; 2],
4029+ // The luma plane's RECONSTRUCTION under this block, already committed by
4030+ // [`Plane::search_block`] -- the signal a `UV_CFL_PRED` candidate scales.
4031+ luma: &Plane,
3923 (x, y): (usize, usize),4032 (x, y): (usize, usize),
3924 side: usize,4033 side: usize,
3925 set: TxbSet,4034 set: TxbSet,
3926 search: &Search,4035 search: &Search,
3927 luma_mode: u8,4036 luma_mode: u8,
3928 fctx: &crate::decode::FrameCtx,4037 fctx: &crate::decode::FrameCtx,
3929-) -> ([Vec<Coeff>; 2], u8, f64, Option<crate::tile::PaletteUv>) {4038+) -> (
4039+ [Vec<Coeff>; 2],
4040+ u8,
4041+ f64,
4042+ Option<crate::tile::PaletteUv>,
4043+ Option<(i32, i32)>,
4044+) {
3930 let at = At {4045 let at = At {
3931 x: x / 2,4046 x: x / 2,
3932 y: y / 2,4047 y: y / 2,
@@ -3967,8 +4082,8 @@ fn search_chroma(
3967 bits += symbol_bits(&cdf::ANGLE_DELTA[usize::from(mode - V_PRED)], 3);4082 bits += symbol_bits(&cdf::ANGLE_DELTA[usize::from(mode - V_PRED)], 3);
3968 }4083 }
3969 let tx_type = crate::decode::default_intra_tx_type(mode);4084 let tx_type = crate::decode::default_intra_tx_type(mode);
3970- let u = chroma[0].trial_typed(at, mode, search.base_q_idx, search.deadzone, tx_type, fctx);4085+ let u = chroma[0].trial_typed(at, mode, 0, search.base_q_idx, search.deadzone, tx_type, fctx);
3971- let v = chroma[1].trial_typed(at, mode, search.base_q_idx, search.deadzone, tx_type, fctx);4086+ let v = chroma[1].trial_typed(at, mode, 0, search.base_q_idx, search.deadzone, tx_type, fctx);
3972 let cost = u.sse + v.sse + search.lambda * (bits + u.bits + v.bits);4087 let cost = u.sse + v.sse + search.lambda * (bits + u.bits + v.bits);
3973 if best.as_ref().is_none_or(|(b, ..)| cost < *b) {4088 if best.as_ref().is_none_or(|(b, ..)| cost < *b) {
3974 best = Some((cost, mode, u, v));4089 best = Some((cost, mode, u, v));
@@ -4047,6 +4162,134 @@ fn search_chroma(
4047 }4162 }
4048 }4163 }
4049 }4164 }
4165+ // The chroma-from-luma arm (spec 5.11.45, libaom `cfl_rd_pick_alpha`):
4166+ // `UV_CFL_PRED` predicts as `DC_PRED` (`get_uv_mode`, spec 9.3) and then
4167+ // nudges every sample by `alpha_q3` times the block's subsampled,
4168+ // average-subtracted luma reconstruction. Offered only where
4169+ // `is_cfl_allowed` (spec 5.11.5) does -- a luma block at most 32x32 --
4170+ // and priced against the best ordinary chroma mode above, palette
4171+ // included, so a block only takes it when it beats both.
4172+ let mut cfl_alphas = None;
4173+ if side <= 32 && cfl_on() {
4174+ // The AC signal, through the decoder's own
4175+ // `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` body.
4176+ let ac = crate::decode::cfl_ac_q3_at(x, y, side, side, |lx, ly| {
4177+ i32::from(luma.reconstruction[ly * luma.width + lx])
4178+ });
4179+ let dc_prediction = |plane: &Plane| -> Vec<u8> {
4180+ let (mut above_buf, mut left_buf) = ([0u8; 2 * BLOCK], [0u8; 2 * BLOCK]);
4181+ let (above, left, corner) =
4182+ plane.edges_into(at.x, at.y, at.side, at.reach, &mut above_buf, &mut left_buf);
4183+ let mut prediction = vec![0u8; at.side * at.side];
4184+ intra_predict_u8(
4185+ DC_PRED, 0, above, left, corner, at.side, at.side, false, false, &mut prediction,
4186+ fctx,
4187+ );
4188+ prediction
4189+ };
4190+ let bases = [dc_prediction(&chroma[0]), dc_prediction(&chroma[1])];
4191+ // `av1_cfl_predict_block` (cfl.c): clip the nudged prediction, then
4192+ // add the residual -- which is what [`Plane::code_from_prediction`]
4193+ // does with what this returns.
4194+ let apply = |base: &[u8], alpha: i32| -> Vec<u8> {
4195+ base.iter()
4196+ .zip(ac.iter())
4197+ .map(|(&b, &a)| {
4198+ (i32::from(b) + crate::decode::cfl_scaled(alpha, a)).clamp(0, 255) as u8
4199+ })
4200+ .collect()
4201+ };
4202+ // The least-squares alpha, then its two neighbours: minimising
4203+ // `sum (source - base - alpha*ac/64)^2` over a continuous alpha is one
4204+ // dot-product ratio, and the quantised optimum is one of the two
4205+ // integers around it (the clamp and the Q6 rounding are what the SSE
4206+ // check below re-decides). libaom sweeps all sixteen magnitudes under
4207+ // full RD; three predictions per plane buy nearly the same alpha for a
4208+ // thirtieth of the search.
4209+ let pick_alpha = |plane: &Plane, base: &[u8]| -> i32 {
4210+ let (mut num, mut den) = (0.0f64, 0.0f64);
4211+ for row in 0..at.side {
4212+ for col in 0..at.side {
4213+ let i = row * at.side + col;
4214+ let d = f64::from(plane.source[(at.y + row) * plane.width + at.x + col])
4215+ - f64::from(base[i]);
4216+ num += d * f64::from(ac[i]);
4217+ den += f64::from(ac[i]) * f64::from(ac[i]);
4218+ }
4219+ }
4220+ if den == 0.0 {
4221+ return 0;
4222+ }
4223+ let ideal = 64.0 * num / den;
4224+ let mut best = (plane.block_sse(at.x, at.y, at.side, base), 0i32);
4225+ for alpha in [ideal.floor() as i64, ideal.ceil() as i64] {
4226+ let alpha = alpha.clamp(-16, 16) as i32;
4227+ if alpha == 0 {
4228+ continue;
4229+ }
4230+ let sse = plane.block_sse(at.x, at.y, at.side, &apply(base, alpha));
4231+ if sse < best.0 {
4232+ best = (sse, alpha);
4233+ }
4234+ }
4235+ best.1
4236+ };
4237+ let picked = [
4238+ pick_alpha(&chroma[0], &bases[0]),
4239+ pick_alpha(&chroma[1], &bases[1]),
4240+ ];
4241+ if picked != [0, 0] {
4242+ let cfl_bits = symbol_bits(uv_cdf, crate::tile::UV_CFL_PRED) - dc_bits;
4243+ let trial = |plane_idx: usize, alpha: i32| -> Trial {
4244+ let prediction = if alpha == 0 {
4245+ bases[plane_idx].clone()
4246+ } else {
4247+ apply(&bases[plane_idx], alpha)
4248+ };
4249+ chroma[plane_idx].code_from_prediction(
4250+ at.x,
4251+ at.y,
4252+ at.side,
4253+ &prediction,
4254+ false,
4255+ search.base_q_idx,
4256+ search.deadzone,
4257+ set,
4258+ )
4259+ };
4260+ // At least one alpha must be nonzero: `cfl_alpha_signs` has no
4261+ // (ZERO, ZERO) joint value ([`crate::tile::cfl_joint_sign`]).
4262+ let combos: [(i32, i32); 3] = [
4263+ (picked[0], picked[1]),
4264+ (picked[0], 0),
4265+ (0, picked[1]),
4266+ ];
4267+ for &(alpha_u, alpha_v) in &combos {
4268+ if (alpha_u, alpha_v) == (0, 0) {
4269+ continue;
4270+ }
4271+ let cu = trial(0, alpha_u);
4272+ let cv = trial(1, alpha_v);
4273+ let bits =
4274+ cfl_bits + crate::tile::cfl_alpha_bits(alpha_u, alpha_v) + cu.bits + cv.bits;
4275+ let cost_cfl = cu.sse + cv.sse + search.lambda * bits;
4276+ if cost_cfl < cost {
4277+ cost = cost_cfl;
4278+ mode = crate::tile::UV_CFL_PRED as u8;
4279+ u = cu;
4280+ v = cv;
4281+ palette_uv = None;
4282+ cfl_alphas = Some((alpha_u, alpha_v));
4283+ }
4284+ }
4285+ }
4286+ }
4287+ if let Some((alpha_u, alpha_v)) = cfl_alphas {
4288+ for alpha in [alpha_u, alpha_v] {
4289+ CFL_ALPHA_HITS[alpha.unsigned_abs() as usize]
4290+ .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4291+ }
4292+ }
4050 if census_on() {4293 if census_on() {
4051 CHROMA_RANK[sad_rank(&ranking, mode).min(6)]4294 CHROMA_RANK[sad_rank(&ranking, mode).min(6)]
4052 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);4295 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
@@ -4059,6 +4302,7 @@ fn search_chroma(
4059 mode,4302 mode,
4060 cost,4303 cost,
4061 palette_uv,4304 palette_uv,
4305+ cfl_alphas,
4062 )4306 )
4063 }4307 }
4064 4308
@@ -4840,6 +5084,8 @@ fn code_square_inter(
4840 chroma[1].commit(x / 2, y / 2, side / 2, &v_new);5084 chroma[1].commit(x / 2, y / 2, side / 2, &v_new);
4841 return (5085 return (
4842 BlockCoeffs {5086 BlockCoeffs {
5087+ angle_delta_y: 0,
5088+ cfl_alphas: None,
4843 luma: coeffs(&levels, side),5089 luma: coeffs(&levels, side),
4844 u: coeffs(&u_new.levels, side / 2),5090 u: coeffs(&u_new.levels, side / 2),
4845 v: coeffs(&v_new.levels, side / 2),5091 v: coeffs(&v_new.levels, side / 2),
@@ -4873,6 +5119,8 @@ fn code_square_inter(
4873 chroma[0].commit(x / 2, y / 2, side / 2, &u);5119 chroma[0].commit(x / 2, y / 2, side / 2, &u);
4874 chroma[1].commit(x / 2, y / 2, side / 2, &v);5120 chroma[1].commit(x / 2, y / 2, side / 2, &v);
4875 (BlockCoeffs {5121 (BlockCoeffs {
5122+ angle_delta_y: 0,
5123+ cfl_alphas: None,
4876 luma: coeffs(&levels, side),5124 luma: coeffs(&levels, side),
4877 u: coeffs(&u.levels, side / 2),5125 u: coeffs(&u.levels, side / 2),
4878 v: coeffs(&v.levels, side / 2),5126 v: coeffs(&v.levels, side / 2),
@@ -6788,6 +7036,7 @@ fn search_inter_block(
6788 set: chroma_set,7036 set: chroma_set,
6789 },7037 },
6790 DC_PRED,7038 DC_PRED,
7039+ 0,
6791 search.base_q_idx,7040 search.base_q_idx,
6792 search.deadzone, fctx,7041 search.deadzone, fctx,
6793 );7042 );
@@ -6800,6 +7049,7 @@ fn search_inter_block(
6800 set: chroma_set,7049 set: chroma_set,
6801 },7050 },
6802 DC_PRED,7051 DC_PRED,
7052+ 0,
6803 search.base_q_idx,7053 search.base_q_idx,
6804 search.deadzone, fctx,7054 search.deadzone, fctx,
6805 );7055 );
@@ -6834,6 +7084,7 @@ fn search_inter_block(
6834 set: luma_set,7084 set: luma_set,
6835 },7085 },
6836 mode,7086 mode,
7087+ 0,
6837 search.base_q_idx,7088 search.base_q_idx,
6838 search.deadzone, fctx,7089 search.deadzone, fctx,
6839 );7090 );
@@ -7576,6 +7827,8 @@ fn search_inter_block(
7576 chroma[1].commit(x / 2, y / 2, BLOCK / 2, &best.v);7827 chroma[1].commit(x / 2, y / 2, BLOCK / 2, &best.v);
7577 (7828 (
7578 BlockCoeffs {7829 BlockCoeffs {
7830+ angle_delta_y: 0,
7831+ cfl_alphas: None,
7579 luma: coeffs(&levels, BLOCK),7832 luma: coeffs(&levels, BLOCK),
7580 u: coeffs(&best.u.levels, BLOCK / 2),7833 u: coeffs(&best.u.levels, BLOCK / 2),
7581 v: coeffs(&best.v.levels, BLOCK / 2),7834 v: coeffs(&best.v.levels, BLOCK / 2),
@@ -9828,6 +10081,8 @@ mod tests {
9828 let (_, inter_header) = inter_frame_headers(width, height, 100, 1, 0).unwrap();10081 let (_, inter_header) = inter_frame_headers(width, height, 100, 1, 0).unwrap();
9829 10082
9830 let residual_block = BlockCoeffs {10083 let residual_block = BlockCoeffs {
10084+ angle_delta_y: 0,
10085+ cfl_alphas: None,
9831 luma: vec![Coeff {10086 luma: vec![Coeff {
9832 row: 0,10087 row: 0,
9833 col: 0,10088 col: 0,
@@ -11489,8 +11744,14 @@ mod tests {
11489 // 3-value alphabet where a warp sample exists) on the DEFAULT path --11744 // 3-value alphabet where a warp sample exists) on the DEFAULT path --
11490 // +34.9% here, one point past the OBMC reading above. The bound moves11745 // +34.9% here, one point past the OBMC reading above. The bound moves
11491 // with it; `EC_AV1_WARP=0` restores the +32.6% no-motion_mode number.11746 // with it; `EC_AV1_WARP=0` restores the +32.6% no-motion_mode number.
11747+ // lane-av1cfl: a `UV_CFL_PRED` block carries a `cfl_alpha_signs`
11748+ // symbol and one or two magnitude symbols, none of which the
11749+ // coefficient sum counts either -- +36.9% here against the same
11750+ // fixture's +34.9% with `EC_AV1_CFL=0`.
11751+ // ... and a directional block whose `angle_delta_y` is no longer
11752+ // always ZERO codes a costlier symbol off the same CDF -- +39.1%.
11492 assert!(11753 assert!(
11493- worst_under <= 0.36,11754+ worst_under <= 0.40,
11494 "the writer spent {:.2}% more than the search priced -- more than \11755 "the writer spent {:.2}% more than the search priced -- more than \
11495 the mode/mv syntax outside the coefficient sum explains",11756 the mode/mv syntax outside the coefficient sum explains",
11496 worst_under * 100.011757 worst_under * 100.0
@@ -12541,6 +12802,12 @@ mod tests {
12541 /// and the two var-tx depth searches ([`tx32_depth_search`],12802 /// and the two var-tx depth searches ([`tx32_depth_search`],
12542 /// [`compound_var_tx`]) are on by default, all three re-judged on the12803 /// [`compound_var_tx`]) are on by default, all three re-judged on the
12543 /// native gate's real film rows.12804 /// native gate's real film rows.
12805+ /// Re-pinned on lane-av1cfl: the chroma search offers `UV_CFL_PRED`, so
12806+ /// every block whose chroma takes it codes a different mode symbol, two
12807+ /// alpha symbols and different chroma coefficients. `EC_AV1_CFL=0`
12808+ /// restores the previous streams. Re-pinned again in the same lane once
12809+ /// directional luma winners searched their `angle_delta_y`
12810+ /// (`EC_AV1_ANGLE=0` restores that half).
12544 #[test]12811 #[test]
12545 fn the_encoders_own_streams_are_byte_identical_to_their_pins() {12812 fn the_encoders_own_streams_are_byte_identical_to_their_pins() {
12546 if !have_ffmpeg() {12813 if !have_ffmpeg() {
@@ -12568,8 +12835,13 @@ mod tests {
12568 // four frames; four pictures is one short mini-GOP, which is the12835 // four frames; four pictures is one short mini-GOP, which is the
12569 // shape that pays least (the ARF's own quality has no later group to12836 // shape that pays least (the ARF's own quality has no later group to
12570 // carry it), so this is not the BD gate's number.12837 // carry it), so this is not the BD gate's number.
12838+ // Re-taken again on lane-av1cfl: the chroma search offers
12839+ // `UV_CFL_PRED` and directional luma winners search `angle_delta_y`,
12840+ // so every block taking either codes different syntax and different
12841+ // coefficients -- 8194 -> 7321 at q=150 and 28285 -> 27285 at q=60.
12842+ // `EC_AV1_CFL=0` / `EC_AV1_ANGLE=0` restore each half.
12571 let pins: [(u8, usize, u64); 2] =12843 let pins: [(u8, usize, u64); 2] =
12572- [(150, 8194, 0x08ba_a7a8_26f6_f414), (60, 28285, 0x64af_fc52_eef6_2967)];12844+ [(150, 7321, 0x34e2_e4e0_d7c5_09f3), (60, 27285, 0xbfd2_41af_dcac_a0c6)];
12573 for (q, bytes, hash) in pins {12845 for (q, bytes, hash) in pins {
12574 let encoded = encode_sequence(&source, q, 0.5).unwrap();12846 let encoded = encode_sequence(&source, q, 0.5).unwrap();
12575 assert_eq!(12847 assert_eq!(
@@ -13046,6 +13318,38 @@ mod tests {
13046 .collect::<Vec<_>>()13318 .collect::<Vec<_>>()
13047 .join(" ")13319 .join(" ")
13048 );13320 );
13321+ // The CfL alpha histogram (lane-av1cfl): one entry per chroma
13322+ // plane of every `UV_CFL_PRED` block, by |alpha_q3|. A tool that
13323+ // only ever fires at one magnitude is a search that never left
13324+ // its first candidate (gate-blind-to-feature).
13325+ // The luma angle-delta histogram (lane-av1cfl): how many
13326+ // directional blocks won at each delta. All-zero would mean the
13327+ // refinement never beat the base angle.
13328+ let deltas = take_angle_delta_hits();
13329+ if deltas.iter().sum::<usize>() > 0 {
13330+ eprintln!(
13331+ "{name}: angle_delta_y {}",
13332+ deltas
13333+ .iter()
13334+ .enumerate()
13335+ .map(|(d, &n)| format!("{:+}={n}", d as i32 - 3))
13336+ .collect::<Vec<_>>()
13337+ .join(" ")
13338+ );
13339+ }
13340+ let alphas = take_cfl_alpha_hits();
13341+ if alphas.iter().sum::<usize>() > 0 {
13342+ eprintln!(
13343+ "{name}: cfl |alpha| {}",
13344+ alphas
13345+ .iter()
13346+ .enumerate()
13347+ .filter(|&(_, &n)| n > 0)
13348+ .map(|(a, &n)| format!("{a}={n}"))
13349+ .collect::<Vec<_>>()
13350+ .join(" ")
13351+ );
13352+ }
13049 let palette_uv = crate::tile::take_palette_uv_hits();13353 let palette_uv = crate::tile::take_palette_uv_hits();
13050 eprintln!(13354 eprintln!(
13051 "{name}: chroma palette blocks {} sizes {}",13355 "{name}: chroma palette blocks {} sizes {}",
crates/ec-av1/src/encoder.rsmodified+50 -7
@@ -191,6 +191,10 @@ struct RateLoop {
191 /// one shared controller (the flat path, unchanged from before levels191 /// one shared controller (the flat path, unchanged from before levels
192 /// existed).192 /// existed).
193 per_level: bool,193 per_level: bool,
194+ /// Whether each slot has already steered off a real coded frame. The
195+ /// FIRST update of a slot is the seeding one and takes the model's whole
196+ /// step ([`RateLoop::update`]); every later one is clamped.
197+ seeded: [bool; 3],
194 }198 }
195 199
196 impl RateLoop {200 impl RateLoop {
@@ -209,6 +213,7 @@ impl RateLoop {
209 target: [target_bytes; 3],213 target: [target_bytes; 3],
210 q: [start_q; 3],214 q: [start_q; 3],
211 per_level: false,215 per_level: false,
216+ seeded: [false; 3],
212 };217 };
213 };218 };
214 // A group of `m` pictures gets `m * target_bytes`, split one219 // A group of `m` pictures gets `m * target_bytes`, split one
@@ -219,6 +224,7 @@ impl RateLoop {
219 target: [target_bytes * KEY_WEIGHT, share * ARF_WEIGHT, share],224 target: [target_bytes * KEY_WEIGHT, share * ARF_WEIGHT, share],
220 q: [start_q; 3],225 q: [start_q; 3],
221 per_level: true,226 per_level: true,
227+ seeded: [false; 3],
222 }228 }
223 }229 }
224 230
@@ -249,7 +255,23 @@ impl RateLoop {
249 return;255 return;
250 }256 }
251 let ratio = actual_bytes as f64 / self.target[slot];257 let ratio = actual_bytes as f64 / self.target[slot];
252- let step = (ratio.ln() * Self::GAIN).clamp(-Self::STEP_CLAMP, Self::STEP_CLAMP);258+ // `STEP_CLAMP` protects an operating point this slot has not found
259+ // yet: its `q` is still the caller's `base_q_idx` guess, and the
260+ // clamp makes the loop WALK to the right quantizer at twelve steps a
261+ // frame. Measured on the 48-frame bitrate gate, the pyramid's ARF
262+ // slot spent five of its twelve frames pinned at `-STEP_CLAMP` and
263+ // the stream landed -10.2% under target -- convergence lag, not a
264+ // steady-state offset (the fixed point of this loop is `actual ==
265+ // target` exactly). So a slot's FIRST frame takes the model's whole
266+ // step and seeds `q` where the log-linear slope says it belongs; from
267+ // the second frame on the clamp is back, and nothing is accumulated
268+ // between frames, so [[vorbis-rate-loop-windup]]'s bound still holds.
269+ let raw = ratio.ln() * Self::GAIN;
270+ let step = if std::mem::replace(&mut self.seeded[slot], true) {
271+ raw.clamp(-Self::STEP_CLAMP, Self::STEP_CLAMP)
272+ } else {
273+ raw
274+ };
253 self.q[slot] = (self.q[slot] + step).clamp(0.0, 255.0);275 self.q[slot] = (self.q[slot] + step).clamp(0.0, 255.0);
254 }276 }
255 }277 }
@@ -1914,6 +1936,13 @@ mod tests {
1914 /// `base_q_idx` step exceeds [`RateLoop::STEP_CLAMP`], across a real1936 /// `base_q_idx` step exceeds [`RateLoop::STEP_CLAMP`], across a real
1915 /// clip's full range of content (so a scene cut can't be the one frame1937 /// clip's full range of content (so a scene cut can't be the one frame
1916 /// that breaks the bound).1938 /// that breaks the bound).
1939+ ///
1940+ /// The SEEDING frame is the one exemption ([`RateLoop::update`]): a slot
1941+ /// that has coded nothing yet is still sitting on the caller's
1942+ /// `base_q_idx` guess, and its first step is the acquisition jump, not
1943+ /// windup. Exactly one frame is exempt -- the loop below asserts the
1944+ /// bound on every frame after it, which is where a scene cut would
1945+ /// break it.
1917 #[test]1946 #[test]
1918 fn bytes_per_frame_controller_never_oscillates_past_its_clamp() {1947 fn bytes_per_frame_controller_never_oscillates_past_its_clamp() {
1919 let Some(pictures) = h264_clip_frames(640, 384, 24) else {1948 let Some(pictures) = h264_clip_frames(640, 384, 24) else {
@@ -1934,17 +1963,31 @@ mod tests {
1934 let mut enc =1963 let mut enc =
1935 Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(4_000)).unwrap();1964 Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(4_000)).unwrap();
1936 let mut prev_q = enc.rate_loop.as_ref().unwrap().q_idx(Level::Leaf);1965 let mut prev_q = enc.rate_loop.as_ref().unwrap().q_idx(Level::Leaf);
1937- for picture in &pictures {1966+ // The first frame this encoder EMITS is several `encode_frames` calls
1967+ // in (the lookahead queue holds the earlier ones), so the seeding
1968+ // step is not frame zero -- it is the first frame `q` moves at all.
1969+ let mut seeded = false;
1970+ let mut seed_frame = None;
1971+ for (frame, picture) in pictures.iter().enumerate() {
1938 enc.encode_frames(picture).unwrap();1972 enc.encode_frames(picture).unwrap();
1939 let q = enc.rate_loop.as_ref().unwrap().q_idx(Level::Leaf);1973 let q = enc.rate_loop.as_ref().unwrap().q_idx(Level::Leaf);
1940 let step = (i32::from(q) - i32::from(prev_q)).abs();1974 let step = (i32::from(q) - i32::from(prev_q)).abs();
1941- assert!(1975+ if step > 0 && !seeded {
1942- f64::from(step) <= RateLoop::STEP_CLAMP + 1.0, // +1 for u8 rounding1976+ seeded = true;
1943- "q stepped from {prev_q} to {q}, past the {} clamp",1977+ seed_frame = Some(frame);
1944- RateLoop::STEP_CLAMP1978+ } else {
1945- );1979+ assert!(
1980+ f64::from(step) <= RateLoop::STEP_CLAMP + 1.0, // +1 for u8 rounding
1981+ "frame {frame}: q stepped from {prev_q} to {q}, past the {} clamp",
1982+ RateLoop::STEP_CLAMP
1983+ );
1984+ }
1946 prev_q = q;1985 prev_q = q;
1947 }1986 }
1987+ assert!(
1988+ seed_frame.is_some(),
1989+ "the controller never steered at all -- the bound below is vacuous"
1990+ );
1948 }1991 }
1949 1992
1950 fn psnr(a: &[u16], b: &[u16]) -> f64 {1993 fn psnr(a: &[u16], b: &[u16]) -> f64 {
crates/ec-av1/src/tile.rsmodified+115 -5
@@ -1053,7 +1053,7 @@ pub(crate) const INTRA_MODE_CTX: [usize; INTRA_MODES] = [0, 1, 2, 3, 4, 4, 4, 4,
1053 1053
1054 /// The symbol an angle delta of zero codes as: the alphabet runs from -3 to1054 /// The symbol an angle delta of zero codes as: the alphabet runs from -3 to
1055 /// +3, so `MAX_ANGLE_DELTA` is the middle of it.1055 /// +3, so `MAX_ANGLE_DELTA` is the middle of it.
1056-const ANGLE_DELTA_ZERO: usize = 3;1056+pub(crate) const ANGLE_DELTA_ZERO: usize = 3;
1057 /// Side of a superblock in 4x4 mode-info units when 128x128 superblocks are off.1057 /// Side of a superblock in 4x4 mode-info units when 128x128 superblocks are off.
1058 const SB_MI: u32 = 16;1058 const SB_MI: u32 = 16;
1059 1059
@@ -1446,6 +1446,16 @@ pub struct BlockCoeffs {
1446 /// `luma` then carries the whole block's levels in BLOCK coordinates,1446 /// `luma` then carries the whole block's levels in BLOCK coordinates,
1447 /// which the writer slices per transform unit.1447 /// which the writer slices per transform unit.
1448 pub tx_depth: u8,1448 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)>,
1455+ /// This block's `angle_delta_y` (spec `read_intra_angle_info`, -3..=3),
1456+ /// zero for every non-directional luma mode -- which is what
1457+ /// [`Default`] gives, and what every writer coded before lane-av1cfl.
1458+ pub angle_delta_y: i8,
1449 /// This block's intra block-copy vector (spec 5.11.13 `use_intrabc` ->1459 /// This block's intra block-copy vector (spec 5.11.13 `use_intrabc` ->
1450 /// `assign_dv`), in the spec's 1/8-pel `(row, col)` units, or `None` for1460 /// `assign_dv`), in the spec's 1/8-pel `(row, col)` units, or `None` for
1451 /// an ordinary intra block. Only a key frame whose header set1461 /// an ordinary intra block. Only a key frame whose header set
@@ -3292,6 +3302,77 @@ fn write_intrabc_block(
3292 Ok(())3302 Ok(())
3293 }3303 }
3294 3304
3305+/// `UV_CFL_PRED` (spec 6.10.19's chroma mode enum), the fourteenth entry of
3306+/// [`crate::cdf::UV_MODE_CFL`] -- the writer's twin of the decoder's own
3307+/// constant.
3308+pub(crate) const UV_CFL_PRED: usize = 13;
3309+
3310+/// The `cfl_alpha_signs` joint value (0..8) that codes this signed alpha pair,
3311+/// inverting the decoder's own `read_cfl_alphas` split (`sign_u =
3312+/// ((joint+1)*11)>>5`, `sign_v = (joint+1) - 3*sign_u`, with 0 ZERO, 1 NEG,
3313+/// 2 POS). There is no (ZERO, ZERO) joint value, so at least one alpha of a
3314+/// CfL block is nonzero by construction.
3315+pub(crate) fn cfl_joint_sign(alpha_u: i32, alpha_v: i32) -> usize {
3316+ let sign = |a: i32| match a.signum() {
3317+ 0 => 0,
3318+ -1 => 1,
3319+ _ => 2,
3320+ };
3321+ let (want_u, want_v) = (sign(alpha_u), sign(alpha_v));
3322+ (0..8)
3323+ .find(|&j| {
3324+ let su = ((j + 1) * 11) >> 5;
3325+ (su, (j + 1) - 3 * su) == (want_u, want_v)
3326+ })
3327+ .expect("cfl_alpha_signs covers every pair but (ZERO, ZERO)") as usize
3328+}
3329+
3330+/// The `cfl_alpha_u`/`cfl_alpha_v` magnitude CDF row for one plane, by the
3331+/// same `CFL_CONTEXT_U`/`CFL_CONTEXT_V` derivation the decoder reads with
3332+/// (libaom cfl.h). `joint` is [`cfl_joint_sign`]'s value.
3333+fn cfl_alpha_ctx(joint: usize, plane: usize) -> usize {
3334+ let joint = joint as i32;
3335+ let su = ((joint + 1) * 11) >> 5;
3336+ let sv = (joint + 1) - 3 * su;
3337+ if plane == 0 {
3338+ (joint + 1 - 3) as usize
3339+ } else {
3340+ (sv * 3 + su - 3) as usize
3341+ }
3342+}
3343+
3344+/// What [`write_cfl_alphas`] will spend on this alpha pair, through the same
3345+/// tables -- the encoder's RD price for the CfL arm.
3346+pub(crate) fn cfl_alpha_bits(alpha_u: i32, alpha_v: i32) -> f64 {
3347+ use crate::encode::symbol_bits;
3348+ let joint = cfl_joint_sign(alpha_u, alpha_v);
3349+ let mut bits = symbol_bits(&crate::cdf::CFL_SIGN, joint);
3350+ for (plane, alpha) in [alpha_u, alpha_v].into_iter().enumerate() {
3351+ if alpha != 0 {
3352+ bits += symbol_bits(
3353+ &crate::cdf::CFL_ALPHA[cfl_alpha_ctx(joint, plane)],
3354+ (alpha.unsigned_abs() - 1) as usize,
3355+ );
3356+ }
3357+ }
3358+ bits
3359+}
3360+
3361+/// `read_cfl_alphas` (spec 5.11.45) written: the joint sign, then each
3362+/// plane's magnitude where its sign is nonzero.
3363+fn write_cfl_alphas(enc: &mut SymbolEncoder, cdfs: &mut Cdfs, (alpha_u, alpha_v): (i32, i32)) {
3364+ let joint = cfl_joint_sign(alpha_u, alpha_v);
3365+ enc.symbol(joint, &mut cdfs.cfl_sign);
3366+ for (plane, alpha) in [alpha_u, alpha_v].into_iter().enumerate() {
3367+ if alpha != 0 {
3368+ enc.symbol(
3369+ (alpha.unsigned_abs() - 1) as usize,
3370+ &mut cdfs.cfl_alpha[cfl_alpha_ctx(joint, plane)],
3371+ );
3372+ }
3373+ }
3374+}
3375+
3295 fn write_intra_mode(3376 fn write_intra_mode(
3296 enc: &mut SymbolEncoder,3377 enc: &mut SymbolEncoder,
3297 cdfs: &mut Cdfs,3378 cdfs: &mut Cdfs,
@@ -3326,7 +3407,10 @@ fn write_intra_mode(
3326 );3407 );
3327 ec_rng_trace(|| format!("EC_YMODE mode={mode} tell={} rng={}", enc.tell(), enc.rng()));3408 ec_rng_trace(|| format!("EC_YMODE mode={mode} tell={} rng={}", enc.tell(), enc.rng()));
3328 if (V_PRED..=D67_PRED).contains(&mode) {3409 if (V_PRED..=D67_PRED).contains(&mode) {
3329- enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[mode - V_PRED]);3410+ enc.symbol(
3411+ (ANGLE_DELTA_ZERO as i32 + i32::from(block.angle_delta_y)) as usize,
3412+ &mut cdfs.angle_delta[mode - V_PRED],
3413+ );
3330 }3414 }
3331 // A block small enough to be offered chroma from luma reads the wider3415 // A block small enough to be offered chroma from luma reads the wider
3332 // table even when it does not take the mode.3416 // table even when it does not take the mode.
@@ -3334,8 +3418,16 @@ fn write_intra_mode(
3334 if cfl {3418 if cfl {
3335 enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]);3419 enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]);
3336 } else {3420 } else {
3421+ debug_assert_ne!(uv_mode, UV_CFL_PRED, "is_cfl_allowed excludes this block");
3337 enc.symbol(uv_mode, &mut cdfs.uv_mode_no_cfl[mode]);3422 enc.symbol(uv_mode, &mut cdfs.uv_mode_no_cfl[mode]);
3338 }3423 }
3424+ if uv_mode == UV_CFL_PRED {
3425+ write_cfl_alphas(
3426+ enc,
3427+ cdfs,
3428+ block.cfl_alphas.expect("a UV_CFL_PRED block carries its alphas"),
3429+ );
3430+ }
3339 // `angle_delta_uv` (spec `read_intra_angle_info`) off the same CDF array3431 // `angle_delta_uv` (spec `read_intra_angle_info`) off the same CDF array
3340 // the luma delta reads, indexed by the chroma mode.3432 // the luma delta reads, indexed by the chroma mode.
3341 if (V_PRED..=D67_PRED).contains(&uv_mode) {3433 if (V_PRED..=D67_PRED).contains(&uv_mode) {
@@ -5706,10 +5798,16 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
5706 let mode = usize::from(block.mode);5798 let mode = usize::from(block.mode);
5707 enc.symbol(mode, &mut cdfs.y_mode[SIZE_GROUP_32]);5799 enc.symbol(mode, &mut cdfs.y_mode[SIZE_GROUP_32]);
5708 if (V_PRED..=D67_PRED).contains(&mode) {5800 if (V_PRED..=D67_PRED).contains(&mode) {
5709- enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[mode - V_PRED]);5801+ enc.symbol(
5802+ (ANGLE_DELTA_ZERO as i32 + i32::from(block.angle_delta_y)) as usize,
5803+ &mut cdfs.angle_delta[mode - V_PRED],
5804+ );
5710 }5805 }
5711 let uv_mode = usize::from(block.uv_mode);5806 let uv_mode = usize::from(block.uv_mode);
5712 enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]);5807 enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]);
5808+ if uv_mode == UV_CFL_PRED {
5809+ write_cfl_alphas(&mut enc, &mut cdfs, block.cfl_alphas.expect("cfl"));
5810+ }
5713 if (V_PRED..=D67_PRED).contains(&uv_mode) {5811 if (V_PRED..=D67_PRED).contains(&uv_mode) {
5714 enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]);5812 enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]);
5715 }5813 }
@@ -5941,10 +6039,16 @@ fn write_inter_frame_leaf(
5941 let mode = usize::from(block.mode);6039 let mode = usize::from(block.mode);
5942 enc.symbol(mode, &mut cdfs.y_mode[SIZE_GROUP_16]);6040 enc.symbol(mode, &mut cdfs.y_mode[SIZE_GROUP_16]);
5943 if (V_PRED..=D67_PRED).contains(&mode) {6041 if (V_PRED..=D67_PRED).contains(&mode) {
5944- enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[mode - V_PRED]);6042+ enc.symbol(
6043+ (ANGLE_DELTA_ZERO as i32 + i32::from(block.angle_delta_y)) as usize,
6044+ &mut cdfs.angle_delta[mode - V_PRED],
6045+ );
5945 }6046 }
5946 let uv_mode = usize::from(block.uv_mode);6047 let uv_mode = usize::from(block.uv_mode);
5947 enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]);6048 enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]);
6049+ if uv_mode == UV_CFL_PRED {
6050+ write_cfl_alphas(enc, cdfs, block.cfl_alphas.expect("cfl"));
6051+ }
5948 if (V_PRED..=D67_PRED).contains(&uv_mode) {6052 if (V_PRED..=D67_PRED).contains(&uv_mode) {
5949 enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]);6053 enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]);
5950 }6054 }
@@ -6182,10 +6286,16 @@ fn write_inter_frame_leaf8(
6182 let mode = usize::from(block.mode);6286 let mode = usize::from(block.mode);
6183 enc.symbol(mode, &mut cdfs.y_mode[SIZE_GROUP_8]);6287 enc.symbol(mode, &mut cdfs.y_mode[SIZE_GROUP_8]);
6184 if (V_PRED..=D67_PRED).contains(&mode) {6288 if (V_PRED..=D67_PRED).contains(&mode) {
6185- enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[mode - V_PRED]);6289+ enc.symbol(
6290+ (ANGLE_DELTA_ZERO as i32 + i32::from(block.angle_delta_y)) as usize,
6291+ &mut cdfs.angle_delta[mode - V_PRED],
6292+ );
6186 }6293 }
6187 let uv_mode = usize::from(block.uv_mode);6294 let uv_mode = usize::from(block.uv_mode);
6188 enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]);6295 enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]);
6296+ if uv_mode == UV_CFL_PRED {
6297+ write_cfl_alphas(enc, cdfs, block.cfl_alphas.expect("cfl"));
6298+ }
6189 if (V_PRED..=D67_PRED).contains(&uv_mode) {6299 if (V_PRED..=D67_PRED).contains(&uv_mode) {
6190 enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]);6300 enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]);
6191 }6301 }