forge
Explore
Log in

Don't you dare go Hollow

Encoder enables CDEF and searches its strengths (cdef_bits = 0)

Browse files at this commit

df76271b5b7f5d8fda9707574c4678d46d953592Ahmet Kaan GümüşParent: 873a1fb
  • feat
    • encoder enables CDEF and searches its strengths (cdef_bits = 0)
Show full message
feat(av1): encoder enables CDEF and searches its strengths (cdef_bits = 0)

The sequence header now sets enable_cdef and every frame header carries one
strength pair per plane type, chosen by the same re-decode search as the
deblocking levels -- cdef_bits = 0 means no cdef_idx literal is read in the
tile, so this costs no tile-writer change. Encoded carries the chosen
CdefParams and the tests that decode Encoded::tile take them from there.

BD-rate vs libaom 198.2/218.1/136.9 -> 143.6/179.5/88.0 (1080p/2160p/screen),
vs rav1e 143.1/162.4/52.7 -> 94.0/128.8/21.5.
crates/ec-av1/src/decode.rsmodified+8 -7
@@ -36620,6 +36620,7 @@ mod tests {
36620 base_q_idx,36620 base_q_idx,
36621 tx_select,36621 tx_select,
36622 loop_filter,36622 loop_filter,
36623+ cdef,
36623 ..36624 ..
36624 }: Encoded = crate::encode::encode_key_frame_with_modes_with_ctx(&picture, 40, 0.0, modes, fctx).unwrap();36625 }: Encoded = crate::encode::encode_key_frame_with_modes_with_ctx(&picture, 40, 0.0, modes, fctx).unwrap();
36625 let decoded = decode_key_frame_tile(36626 let decoded = decode_key_frame_tile(
@@ -36630,7 +36631,7 @@ mod tests {
36630 w as u32,36631 w as u32,
36631 h as u32,36632 h as u32,
36632 false,36633 false,
36633- &CdefParams::default(),36634+ &cdef,
36634 &loop_filter,36635 &loop_filter,
36635 tx_select,36636 tx_select,
36636 true,36637 true,
@@ -36995,7 +36996,7 @@ mod tests {
36995 coded_w,36996 coded_w,
36996 coded_h,36997 coded_h,
36997 false,36998 false,
36998- &CdefParams::default(),36999+ &encoded.cdef,
36999 &encoded.loop_filter,37000 &encoded.loop_filter,
37000 encoded.tx_select,37001 encoded.tx_select,
37001 true,37002 true,
@@ -37038,7 +37039,7 @@ mod tests {
37038 width as u32,37039 width as u32,
37039 height as u32,37040 height as u32,
37040 false,37041 false,
37041- &CdefParams::default(),37042+ &encoded.cdef,
37042 &encoded.loop_filter,37043 &encoded.loop_filter,
37043 tx_select,37044 tx_select,
37044 true,37045 true,
@@ -37122,7 +37123,7 @@ mod tests {
37122 width as u32,37123 width as u32,
37123 height as u32,37124 height as u32,
37124 false,37125 false,
37125- &CdefParams::default(),37126+ &key.cdef,
37126 &key.loop_filter,37127 &key.loop_filter,
37127 key.tx_select,37128 key.tx_select,
37128 true,37129 true,
@@ -37152,7 +37153,7 @@ mod tests {
37152 width as u32,37153 width as u32,
37153 height as u32,37154 height as u32,
37154 &last_only(&reference),37155 &last_only(&reference),
37155- &CdefParams::default(),37156+ &frame.cdef,
37156 &frame.loop_filter,37157 &frame.loop_filter,
37157 false,37158 false,
37158 false,37159 false,
@@ -37442,7 +37443,7 @@ mod tests {
37442 coded_w,37443 coded_w,
37443 coded_h,37444 coded_h,
37444 false,37445 false,
37445- &CdefParams::default(),37446+ &key.cdef,
37446 &key.loop_filter,37447 &key.loop_filter,
37447 key.tx_select,37448 key.tx_select,
37448 true,37449 true,
@@ -37461,7 +37462,7 @@ mod tests {
37461 coded_w,37462 coded_w,
37462 coded_h,37463 coded_h,
37463 &last_only(&reference),37464 &last_only(&reference),
37464- &CdefParams::default(),37465+ &frame.cdef,
37465 &frame.loop_filter,37466 &frame.loop_filter,
37466 false,37467 false,
37467 false,37468 false,
crates/ec-av1/src/encode.rsmodified+47 -12
@@ -475,6 +475,7 @@ pub(crate) fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> En
475 base_q_idx: encoded.base_q_idx,475 base_q_idx: encoded.base_q_idx,
476 tx_select: encoded.tx_select,476 tx_select: encoded.tx_select,
477 loop_filter: encoded.loop_filter,477 loop_filter: encoded.loop_filter,
478+ cdef: encoded.cdef,
478 }479 }
479 }480 }
480 481
@@ -517,6 +518,9 @@ pub struct Encoded {
517 /// `tile` directly must pass these along, exactly as it must `tx_select`518 /// `tile` directly must pass these along, exactly as it must `tx_select`
518 /// (class: test asserts against a stale header).519 /// (class: test asserts against a stale header).
519 pub(crate) loop_filter: LoopFilterParams,520 pub(crate) loop_filter: LoopFilterParams,
521+ /// This frame header's chosen CDEF parameters, threaded for the same
522+ /// reason as `loop_filter`.
523+ pub(crate) cdef: CdefParams,
520 }524 }
521 525
522 /// The sequence and frame headers a picture of this size is coded under: one526 /// The sequence and frame headers a picture of this size is coded under: one
@@ -593,7 +597,12 @@ pub(crate) fn key_frame_headers_colour(
593 enable_order_hint: true,597 enable_order_hint: true,
594 order_hint_bits: 7,598 order_hint_bits: 7,
595 enable_superres: false,599 enable_superres: false,
596- enable_cdef: false,600+ // spec 5.9.19: with the sequence bit set every frame header carries
601+ // `cdef_params`. This encoder writes `cdef_bits == 0` -- one strength
602+ // pair for the whole frame, chosen by `crate::filter_search` -- so no
603+ // `cdef_idx` literal is coded in the tile and a frame that wants no
604+ // CDEF simply carries zero strengths.
605+ enable_cdef: true,
597 enable_restoration: false,606 enable_restoration: false,
598 seq_force_screen_content_tools: 0,607 seq_force_screen_content_tools: 0,
599 seq_force_integer_mv: 0,608 seq_force_integer_mv: 0,
@@ -2913,13 +2922,13 @@ pub(crate) fn encode_key_frame_inner(
2913 // `crate::filter_search`), and keep the filtered picture that wins as2922 // `crate::filter_search`), and keep the filtered picture that wins as
2914 // the reconstruction -- what a decoder outputs, and what the next2923 // the reconstruction -- what a decoder outputs, and what the next
2915 // frame predicts from.2924 // frame predicts from.
2916- pick_and_apply_deblock(2925+ pick_and_apply_filters(
2917 &mut header,2926 &mut header,
2918 &mut luma,2927 &mut luma,
2919 &mut chroma,2928 &mut chroma,
2920 [&picture_y8, &picture_u8, &picture_v8],2929 [&picture_y8, &picture_u8, &picture_v8],
2921 true,2930 true,
2922- |lf, h| {2931+ |lf, cdef, h| {
2923 crate::decode::decode_key_frame_tile(2932 crate::decode::decode_key_frame_tile(
2924 &tile,2933 &tile,
2925 h.mi_cols,2934 h.mi_cols,
@@ -2928,7 +2937,7 @@ pub(crate) fn encode_key_frame_inner(
2928 h.frame_width,2937 h.frame_width,
2929 h.frame_height,2938 h.frame_height,
2930 seq.enable_filter_intra,2939 seq.enable_filter_intra,
2931- &CdefParams::default(),2940+ cdef,
2932 lf,2941 lf,
2933 tx_select,2942 tx_select,
2934 h.reduced_tx_set,2943 h.reduced_tx_set,
@@ -2960,10 +2969,12 @@ pub(crate) fn encode_key_frame_inner(
2960 base_q_idx,2969 base_q_idx,
2961 tx_select,2970 tx_select,
2962 loop_filter: header.loop_filter,2971 loop_filter: header.loop_filter,
2972+ cdef: header.cdef,
2963 })2973 })
2964 }2974 }
2965 2975
2966-/// Chooses this frame's deblocking levels, writes them into `header` and2976+/// Chooses this frame's deblocking levels and CDEF strengths, writes them
2977+/// into `header` and
2967 /// replaces the frame's own region of the encoder's reconstruction with the2978 /// replaces the frame's own region of the encoder's reconstruction with the
2968 /// filtered picture the decoder produced under them2979 /// filtered picture the decoder produced under them
2969 /// ([`crate::filter_search::pick_deblock`]).2980 /// ([`crate::filter_search::pick_deblock`]).
@@ -2976,26 +2987,31 @@ pub(crate) fn encode_key_frame_inner(
2976 /// The decoder's own error, when it refuses the tile the encoder just wrote2987 /// The decoder's own error, when it refuses the tile the encoder just wrote
2977 /// -- that is an encoder defect, not a filter one, so it is propagated2988 /// -- that is an encoder defect, not a filter one, so it is propagated
2978 /// rather than swallowed into "no deblocking".2989 /// rather than swallowed into "no deblocking".
2979-fn pick_and_apply_deblock(2990+fn pick_and_apply_filters(
2980 header: &mut FrameHeader,2991 header: &mut FrameHeader,
2981 luma: &mut Plane<'_>,2992 luma: &mut Plane<'_>,
2982 chroma: &mut [Plane<'_>; 2],2993 chroma: &mut [Plane<'_>; 2],
2983 source: [&[u8]; 3],2994 source: [&[u8]; 3],
2984 search: bool,2995 search: bool,
2985- decode: impl Fn(&LoopFilterParams, &FrameHeader) -> Result<Picture>,2996+ decode: impl Fn(&LoopFilterParams, &CdefParams, &FrameHeader) -> Result<Picture>,
2986 ) -> Result<()> {2997 ) -> Result<()> {
2987 if !search {2998 if !search {
2988 return Ok(());2999 return Ok(());
2989 }3000 }
2990 let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);3001 let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);
2991 let hdr = header.clone();3002 let hdr = header.clone();
2992- let (lf, filtered) = crate::filter_search::pick_deblock(3003+ // libaom `av1_pick_filter_level`'s sibling `av1_cdef_search`:
2993- |lf| decode(lf, &hdr),3004+ // `cdef_damping = 3 + (base_qindex >> 6)`, never searched.
3005+ let damping = 3 + (header.quantization.base_q_idx >> 6);
3006+ let (lf, cdef, filtered) = crate::filter_search::pick_filters(
3007+ |lf, cdef| decode(lf, cdef, &hdr),
2994 source,3008 source,
2995 luma.width,3009 luma.width,
2996 (fw, fh),3010 (fw, fh),
3011+ damping,
2997 )?;3012 )?;
2998 header.loop_filter = lf;3013 header.loop_filter = lf;
3014+ header.cdef = cdef;
2999 let dec_cw = filtered.width.div_ceil(2);3015 let dec_cw = filtered.width.div_ceil(2);
3000 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));3016 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));
3001 crate::filter_search::splice(&mut luma.reconstruction, luma.width, &filtered.y, filtered.width, fw, fh);3017 crate::filter_search::splice(&mut luma.reconstruction, luma.width, &filtered.y, filtered.width, fw, fh);
@@ -4094,7 +4110,7 @@ pub(crate) fn encode_inter_frame(
4094 let mut refs: [Option<&Picture>; 8] = [None; 8];4110 let mut refs: [Option<&Picture>; 8] = [None; 8];
4095 refs[1] = Some(&trial_ref);4111 refs[1] = Some(&trial_ref);
4096 let refpix = crate::decode::RefPix::ready(refs);4112 let refpix = crate::decode::RefPix::ready(refs);
4097- pick_and_apply_deblock(4113+ pick_and_apply_filters(
4098 &mut header,4114 &mut header,
4099 &mut luma,4115 &mut luma,
4100 &mut chroma,4116 &mut chroma,
@@ -4103,7 +4119,7 @@ pub(crate) fn encode_inter_frame(
4103 // under the (default-off) inter `TxMode::Select` knob there is no4119 // under the (default-off) inter `TxMode::Select` knob there is no
4104 // decoder to search against, so that stream keeps level 0.4120 // decoder to search against, so that stream keeps level 0.
4105 !tx_select,4121 !tx_select,
4106- |lf, h| {4122+ |lf, cdef, h| {
4107 crate::decode::decode_inter_frame_tile(4123 crate::decode::decode_inter_frame_tile(
4108 &tile,4124 &tile,
4109 h.mi_cols,4125 h.mi_cols,
@@ -4112,7 +4128,7 @@ pub(crate) fn encode_inter_frame(
4112 h.frame_width,4128 h.frame_width,
4113 h.frame_height,4129 h.frame_height,
4114 &refpix,4130 &refpix,
4115- &CdefParams::default(),4131+ cdef,
4116 lf,4132 lf,
4117 h.allow_high_precision_mv,4133 h.allow_high_precision_mv,
4118 h.force_integer_mv,4134 h.force_integer_mv,
@@ -4144,6 +4160,7 @@ pub(crate) fn encode_inter_frame(
4144 base_q_idx,4160 base_q_idx,
4145 tx_select,4161 tx_select,
4146 loop_filter: header.loop_filter,4162 loop_filter: header.loop_filter,
4163+ cdef: header.cdef,
4147 })4164 })
4148 }4165 }
4149 4166
@@ -6963,6 +6980,24 @@ mod tests {
6963 whole16 + split16,6980 whole16 + split16,
6964 100.0 * split16 as f64 / (whole16 + split16).max(1) as f646981 100.0 * split16 as f64 / (whole16 + split16).max(1) as f64
6965 );6982 );
6983+ // The deblocking level each of this clip's frames chose
6984+ // (lane-av1filt): 0 everywhere would mean the filter never fires.
6985+ let levels = crate::filter_search::take_chosen_levels();
6986+ type Chosen = ((u8, u8), (u8, u8), (u8, u8));
6987+ let mean = |f: fn(&Chosen) -> u8| {
6988+ levels.iter().map(|l| f(l) as f64).sum::<f64>() / levels.len().max(1) as f64
6989+ };
6990+ eprintln!(
6991+ "{name}: over {} frames -- deblock luma mean {:.1} chroma {:.1}; \
6992+ cdef luma pri {:.1}/sec {:.1}, chroma pri {:.1}/sec {:.1}",
6993+ levels.len(),
6994+ mean(|l| l.0.0),
6995+ mean(|l| l.0.1),
6996+ mean(|l| l.1.0),
6997+ mean(|l| l.1.1),
6998+ mean(|l| l.2.0),
6999+ mean(|l| l.2.1),
7000+ );
6966 // Which chroma modes the search actually wins with, against the7001 // Which chroma modes the search actually wins with, against the
6967 // unconditional DC_PRED that was the only outcome before7002 // unconditional DC_PRED that was the only outcome before
6968 // (gate-blind-to-feature).7003 // (gate-blind-to-feature).
crates/ec-av1/src/filter_search.rsmodified+122 -65
@@ -13,7 +13,7 @@
13 //! tile payload, so no candidate re-runs the search or the entropy coder).13 //! tile payload, so no candidate re-runs the search or the entropy coder).
14 14
15 use crate::encode::Picture;15 use crate::encode::Picture;
16-use ec_av1_syntax::LoopFilterParams;16+use ec_av1_syntax::{CdefParams, LoopFilterParams};
17 use ec_core::Result;17 use ec_core::Result;
18 18
19 /// Luma deblocking levels tried at the coarse stage, refined by +-1/+-219 /// Luma deblocking levels tried at the coarse stage, refined by +-1/+-2
@@ -21,6 +21,25 @@ use ec_core::Result;
21 /// search over the same 0..63 range; this ladder is the charter's).21 /// search over the same 0..63 range; this ladder is the charter's).
22 const COARSE: [u8; 7] = [0, 4, 8, 16, 24, 32, 48];22 const COARSE: [u8; 7] = [0, 4, 8, 16, 24, 32, 48];
23 23
24+thread_local! {
25+ /// Every frame's chosen filter parameters, in coding
26+ /// order -- the BD gate prints the distribution once per clip
27+ /// (gate-blind-to-feature: a filter nobody counts is a filter that may
28+ /// never fire).
29+ static CHOSEN: std::cell::RefCell<Vec<Cand>> = const { std::cell::RefCell::new(Vec::new()) };
30+}
31+
32+/// Takes and clears [`CHOSEN`].
33+#[allow(dead_code)] // read from the `#[cfg(test)]` BD gate
34+pub(crate) fn take_chosen_levels() -> Vec<((u8, u8), (u8, u8), (u8, u8))> {
35+ CHOSEN.with(|c| {
36+ std::mem::take(&mut *c.borrow_mut())
37+ .into_iter()
38+ .map(|c| (c.lf, c.y, c.uv))
39+ .collect()
40+ })
41+}
42+
24 /// Squared error between a decoded plane and the source it was coded from,43 /// Squared error between a decoded plane and the source it was coded from,
25 /// over the frame's own cropped `w x h` (the two planes have different44 /// over the frame's own cropped `w x h` (the two planes have different
26 /// strides: the source is the encoder's padded coding surface).45 /// strides: the source is the encoder's padded coding surface).
@@ -36,105 +55,143 @@ fn plane_sse(dec: &[u16], dec_w: usize, src: &[u8], src_w: usize, w: usize, h: u
36 sse55 sse
37 }56 }
38 57
58+/// CDEF primary strengths tried (libaom's own range is 0..15 for 8-bit
59+/// content) and the secondary ladder, whose only legal values are 0, 1, 2
60+/// and 4 -- 3 is not codeable (spec 5.9.19 codes a secondary strength of 4
61+/// as 3).
62+const CDEF_PRI: [u8; 5] = [0, 1, 2, 4, 8];
63+const CDEF_SEC: [u8; 4] = [0, 1, 2, 4];
64+
65+/// One point of the filter search: the deblocking levels and the single
66+/// CDEF strength pair per plane type this encoder writes (`cdef_bits == 0`,
67+/// so no `cdef_idx` literal is coded in the tile at all and the choice is
68+/// purely a frame-header one).
69+#[derive(Clone, Copy, PartialEq, Eq)]
70+struct Cand {
71+ /// `(luma, chroma)` deblocking level.
72+ lf: (u8, u8),
73+ /// Luma `(primary, secondary)` CDEF strength.
74+ y: (u8, u8),
75+ /// Chroma `(primary, secondary)` CDEF strength.
76+ uv: (u8, u8),
77+}
78+
39 /// One evaluated candidate: the decoded picture and its luma / chroma error.79 /// One evaluated candidate: the decoded picture and its luma / chroma error.
40 struct Trial {80 struct Trial {
41- level: (u8, u8),81+ cand: Cand,
42 picture: Picture,82 picture: Picture,
43 sse_y: u64,83 sse_y: u64,
44 sse_uv: u64,84 sse_uv: u64,
45 }85 }
46 86
47-/// Picks `loop_filter_level[0..4]` for one frame and hands back the filtered87+/// Picks this frame's deblocking levels and CDEF strengths and hands back
48-/// reconstruction that goes with the winner.88+/// the filtered reconstruction that goes with the winner.
49 ///89 ///
50 /// `decode` reconstructs this frame's already-coded tile under the candidate90 /// `decode` reconstructs this frame's already-coded tile under the candidate
51 /// parameters; `source` is the encoder's padded (luma, U, V) coding surface91 /// parameters; `source` is the encoder's padded (luma, U, V) coding surface
52-/// with luma stride `src_w`, and `(fw, fh)` the frame header's own true92+/// with luma stride `src_w`, `(fw, fh)` the frame header's own true size,
53-/// size, which is what `decode` crops to.93+/// which is what `decode` crops to, and `damping` the CDEF damping the
94+/// caller's header carries.
54 ///95 ///
55-/// Luma (`level[0..2]`, kept equal -- this encoder has no reason to filter96+/// A coordinate search, in the decoder's own filter order and each stage on
56-/// vertical and horizontal edges differently) is chosen on luma SSE with the97+/// the plane it moves: deblocking luma (`level[0..2]`, kept equal -- nothing
57-/// chroma levels riding along, then chroma (`level[2..4]`) is chosen on98+/// here filters vertical and horizontal edges differently), deblocking
58-/// chroma SSE with luma fixed. `sharpness` stays 0 and the ref/mode deltas99+/// chroma (`level[2..4]`, a real choice of its own: flat chroma has no edges
59-/// stay off, as [`LoopFilterParams::default`] has them.100+/// to soften), then CDEF's luma and chroma primary/secondary strengths.
101+/// `sharpness` stays 0, the loop-filter deltas stay off, and `cdef_bits`
102+/// stays 0 -- one strength pair for the whole frame, which is the only CDEF
103+/// shape that costs no `cdef_idx` literal in the tile payload.
60 ///104 ///
61 /// # Errors105 /// # Errors
62 /// Whatever `decode` returns: a stream this crate's own decoder refuses is106 /// Whatever `decode` returns: a stream this crate's own decoder refuses is
63 /// a caller's cue to keep its unfiltered reconstruction.107 /// a caller's cue to keep its unfiltered reconstruction.
64-pub(crate) fn pick_deblock(108+pub(crate) fn pick_filters(
65- decode: impl Fn(&LoopFilterParams) -> Result<Picture>,109+ decode: impl Fn(&LoopFilterParams, &CdefParams) -> Result<Picture>,
66 source: [&[u8]; 3],110 source: [&[u8]; 3],
67 src_w: usize,111 src_w: usize,
68 (fw, fh): (usize, usize),112 (fw, fh): (usize, usize),
69-) -> Result<(LoopFilterParams, Picture)> {113+ damping: u8,
114+) -> Result<(LoopFilterParams, CdefParams, Picture)> {
70 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));115 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));
71 let mut trials: Vec<Trial> = Vec::new();116 let mut trials: Vec<Trial> = Vec::new();
72- let eval = |level: (u8, u8), trials: &mut Vec<Trial>| -> Result<usize> {117+ let eval = |cand: Cand, trials: &mut Vec<Trial>| -> Result<usize> {
73- if let Some(i) = trials.iter().position(|t| t.level == level) {118+ if let Some(i) = trials.iter().position(|t| t.cand == cand) {
74 return Ok(i);119 return Ok(i);
75 }120 }
76- let lf = LoopFilterParams {121+ let picture = decode(&loop_filter(cand), &cdef(cand, damping))?;
77- level: [level.0, level.0, level.1, level.1],
78- ..LoopFilterParams::default()
79- };
80- let picture = decode(&lf)?;
81 let dec_cw = picture.width.div_ceil(2);122 let dec_cw = picture.width.div_ceil(2);
82 let sse_y = plane_sse(&picture.y, picture.width, source[0], src_w, fw, fh);123 let sse_y = plane_sse(&picture.y, picture.width, source[0], src_w, fw, fh);
83 let sse_uv = plane_sse(&picture.u, dec_cw, source[1], src_w / 2, cw, ch)124 let sse_uv = plane_sse(&picture.u, dec_cw, source[1], src_w / 2, cw, ch)
84 + plane_sse(&picture.v, dec_cw, source[2], src_w / 2, cw, ch);125 + plane_sse(&picture.v, dec_cw, source[2], src_w / 2, cw, ch);
85- trials.push(Trial { level, picture, sse_y, sse_uv });126+ trials.push(Trial { cand, picture, sse_y, sse_uv });
86 Ok(trials.len() - 1)127 Ok(trials.len() - 1)
87 };128 };
88-129+ // One stage of the coordinate search: try `values` in the slot `set`
89- // Luma: the coarse ladder, then +-1/+-2 around its winner.130+ // moves and keep the one with the lowest error `sse` reads.
90- let mut best_y = 0u8;131+ let stage = |best: &mut Cand,
91- let mut best_sse = u64::MAX;132+ values: &[u8],
92- for l in COARSE {133+ set: fn(&mut Cand, u8),
93- let i = eval((l, l), &mut trials)?;134+ sse: fn(&Trial) -> u64,
94- if trials[i].sse_y < best_sse {135+ trials: &mut Vec<Trial>|
95- best_sse = trials[i].sse_y;136+ -> Result<()> {
96- best_y = l;137+ let mut winner = *best;
97- }138+ let mut lowest = u64::MAX;
98- }139+ for &v in values {
99- for delta in [-2i32, -1, 1, 2] {140+ let mut cand = *best;
100- let Ok(l) = u8::try_from(i32::from(best_y) + delta) else {141+ set(&mut cand, v);
101- continue;142+ let i = eval(cand, trials)?;
143+ if sse(&trials[i]) < lowest {
144+ lowest = sse(&trials[i]);
145+ winner = cand;
146+ }
147+ }
148+ *best = winner;
149+ Ok(())
102 };150 };
103- if l > 63 {
104- continue;
105- }
106- let i = eval((l, l), &mut trials)?;
107- if trials[i].sse_y < best_sse {
108- best_sse = trials[i].sse_y;
109- best_y = l;
110- }
111- }
112 151
113- // Chroma: three points around the luma winner. A chroma level of 0 with152+ let mut best = Cand { lf: (0, 0), y: (0, 0), uv: (0, 0) };
114- // luma non-zero is a real outcome (flat chroma has no edges to soften),153+ // Deblocking luma: the coarse ladder, then +-1/+-2 around its winner.
115- // which is why `level[2..4]` is searched at all rather than tied to154+ stage(&mut best, &COARSE, |c, v| c.lf = (v, v), |t| t.sse_y, &mut trials)?;
116- // `level[0]`.155+ let refine: Vec<u8> = [-2i32, -1, 1, 2]
117- let mut best_uv = best_y;156+ .iter()
118- let mut best_sse_uv = u64::MAX;157+ .filter_map(|d| u8::try_from(i32::from(best.lf.0) + d).ok())
119- for c in [0, best_y / 2, best_y] {158+ .filter(|&l| l <= 63)
120- let i = eval((best_y, c), &mut trials)?;159+ .collect();
121- if trials[i].sse_uv < best_sse_uv {160+ stage(&mut best, &refine, |c, v| c.lf = (v, v), |t| t.sse_y, &mut trials)?;
122- best_sse_uv = trials[i].sse_uv;161+ // Deblocking chroma, three points around the luma winner.
123- best_uv = c;162+ let chroma_levels = [0, best.lf.0 / 2, best.lf.0];
124- }163+ stage(&mut best, &chroma_levels, |c, v| c.lf.1 = v, |t| t.sse_uv, &mut trials)?;
125- }164+ // CDEF, primary then secondary, luma on luma error and chroma on chroma.
165+ stage(&mut best, &CDEF_PRI, |c, v| c.y.0 = v, |t| t.sse_y, &mut trials)?;
166+ stage(&mut best, &CDEF_SEC, |c, v| c.y.1 = v, |t| t.sse_y, &mut trials)?;
167+ stage(&mut best, &CDEF_PRI, |c, v| c.uv.0 = v, |t| t.sse_uv, &mut trials)?;
168+ stage(&mut best, &CDEF_SEC, |c, v| c.uv.1 = v, |t| t.sse_uv, &mut trials)?;
126 169
170+ CHOSEN.with(|c| c.borrow_mut().push(best));
127 let win = trials171 let win = trials
128 .into_iter()172 .into_iter()
129- .find(|t| t.level == (best_y, best_uv))173+ .find(|t| t.cand == best)
130- .expect("the winning pair was evaluated");174+ .expect("the winning candidate was evaluated");
131- Ok((175+ Ok((loop_filter(best), cdef(best, damping), win.picture))
176+}
177+
178+/// The header's `loop_filter_params` for one candidate.
179+fn loop_filter(cand: Cand) -> LoopFilterParams {
132 LoopFilterParams {180 LoopFilterParams {
133- level: [best_y, best_y, best_uv, best_uv],181+ level: [cand.lf.0, cand.lf.0, cand.lf.1, cand.lf.1],
134 ..LoopFilterParams::default()182 ..LoopFilterParams::default()
135- },183+ }
136- win.picture,184+}
137- ))185+
186+/// The header's `cdef_params` for one candidate: a single strength pair per
187+/// plane type (`bits == 0`).
188+fn cdef(cand: Cand, damping: u8) -> CdefParams {
189+ let mut cdef = CdefParams { damping, bits: 0, ..CdefParams::default() };
190+ cdef.y_pri_strength[0] = cand.y.0;
191+ cdef.y_sec_strength[0] = cand.y.1;
192+ cdef.uv_pri_strength[0] = cand.uv.0;
193+ cdef.uv_sec_strength[0] = cand.uv.1;
194+ cdef
138 }195 }
139 196
140 /// Writes the frame's own (cropped) region of `filtered` back over the197 /// Writes the frame's own (cropped) region of `filtered` back over the
crates/ec-av1/src/stream.rsmodified+1 -1
@@ -2994,7 +2994,7 @@ mod tests {
2994 width as u32,2994 width as u32,
2995 height as u32,2995 height as u32,
2996 false,2996 false,
2997- &ec_av1_syntax::CdefParams::default(),2997+ &encoded.cdef,
2998 &encoded.loop_filter,2998 &encoded.loop_filter,
2999 encoded.tx_select,2999 encoded.tx_select,
3000 // Our own encoder always writes `reduced_tx_set: true`.3000 // Our own encoder always writes `reduced_tx_set: true`.