forge
Explore
Log in

Don't you dare go Hollow

Encoder picks per-frame deblocking levels by re-decoding its own tile

Browse files at this commit

873a1fb776723844a4aa03d3f65699ba1bcfe5fbAhmet Kaan GümüşParent: b4e787d
  • feat
    • encoder picks per-frame deblocking levels by re-decoding its own tile
Show full message
feat(av1): encoder picks per-frame deblocking levels by re-decoding its own tile

The encoder runs no loop filter of its own: filter_search hands the coded
tile back to this crate's decoder under each candidate loop_filter_level and
keeps the winning picture as the reconstruction, so the reference frame stays
identical to what a decoder produces. Encoded now carries the chosen
LoopFilterParams and every test that decodes Encoded::tile takes them from
there (class: test asserts against a stale header).
crates/ec-av1/src/decode.rsmodified+8 -7
@@ -36619,6 +36619,7 @@ mod tests {
3661936619 mi_rows,
3662036620 base_q_idx,
3662136621 tx_select,
36622+ loop_filter,
3662236623 ..
3662336624 }: Encoded = crate::encode::encode_key_frame_with_modes_with_ctx(&picture, 40, 0.0, modes, fctx).unwrap();
3662436625 let decoded = decode_key_frame_tile(
@@ -36630,7 +36631,7 @@ mod tests {
3663036631 h as u32,
3663136632 false,
3663236633 &CdefParams::default(),
36633- &LoopFilterParams::default(),
36634+ &loop_filter,
3663436635 tx_select,
3663536636 true,
3663636637 false,
@@ -36995,7 +36996,7 @@ mod tests {
3699536996 coded_h,
3699636997 false,
3699736998 &CdefParams::default(),
36998- &LoopFilterParams::default(),
36999+ &encoded.loop_filter,
3699937000 encoded.tx_select,
3700037001 true,
3700137002 false,
@@ -37038,7 +37039,7 @@ mod tests {
3703837039 height as u32,
3703937040 false,
3704037041 &CdefParams::default(),
37041- &LoopFilterParams::default(),
37042+ &encoded.loop_filter,
3704237043 tx_select,
3704337044 true,
3704437045 false,
@@ -37122,7 +37123,7 @@ mod tests {
3712237123 height as u32,
3712337124 false,
3712437125 &CdefParams::default(),
37125- &LoopFilterParams::default(),
37126+ &key.loop_filter,
3712637127 key.tx_select,
3712737128 true,
3712837129 false,
@@ -37152,7 +37153,7 @@ mod tests {
3715237153 height as u32,
3715337154 &last_only(&reference),
3715437155 &CdefParams::default(),
37155- &LoopFilterParams::default(),
37156+ &frame.loop_filter,
3715637157 false,
3715737158 false,
3715837159 Some(mc::InterpFilterKind::Regular),
@@ -37442,7 +37443,7 @@ mod tests {
3744237443 coded_h,
3744337444 false,
3744437445 &CdefParams::default(),
37445- &LoopFilterParams::default(),
37446+ &key.loop_filter,
3744637447 key.tx_select,
3744737448 true,
3744837449 false,
@@ -37461,7 +37462,7 @@ mod tests {
3746137462 coded_h,
3746237463 &last_only(&reference),
3746337464 &CdefParams::default(),
37464- &LoopFilterParams::default(),
37465+ &frame.loop_filter,
3746537466 false,
3746637467 false,
3746737468 Some(mc::InterpFilterKind::Regular),
crates/ec-av1/src/encode.rsmodified+134 -2
@@ -19,8 +19,8 @@
1919 use crate::decode::WithRef;
2020 use ec_av1_syntax::sequence::{ColorConfig, OperatingPoint, SequenceHeader};
2121 use ec_av1_syntax::{
22- ChromaSamplePosition, FrameHeader, FrameType, PRIMARY_REF_NONE, QuantizationParams, TileInfo,
23- TxMode,
22+ CdefParams, ChromaSamplePosition, FrameHeader, FrameType, LoopFilterParams, PRIMARY_REF_NONE,
23+ QuantizationParams, TileInfo, TxMode,
2424 };
2525 use ec_core::{Error, Result};
2626
@@ -474,6 +474,7 @@ pub(crate) fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> En
474474 mi_rows: encoded.mi_rows,
475475 base_q_idx: encoded.base_q_idx,
476476 tx_select: encoded.tx_select,
477+ loop_filter: encoded.loop_filter,
477478 }
478479 }
479480
@@ -510,6 +511,12 @@ pub struct Encoded {
510511 /// a `tx_depth` frame as a `TxMode::Largest` one and desyncs at the first
511512 /// block.
512513 pub(crate) tx_select: bool,
514+ /// This frame header's chosen deblocking parameters
515+ /// ([`crate::filter_search::pick_deblock`]) — `reconstruction` is the
516+ /// picture the decoder produces UNDER them, so a test that decodes
517+ /// `tile` directly must pass these along, exactly as it must `tx_select`
518+ /// (class: test asserts against a stale header).
519+ pub(crate) loop_filter: LoopFilterParams,
513520 }
514521
515522 /// The sequence and frame headers a picture of this size is coded under: one
@@ -2901,6 +2908,36 @@ pub(crate) fn encode_key_frame_inner(
29012908 &superblocks,
29022909 tx_select,
29032910 )?;
2911+ // spec 7.14 deblocking: pick this frame's `loop_filter_level` by handing
2912+ // the tile just coded back to the decoder under each candidate (see
2913+ // `crate::filter_search`), and keep the filtered picture that wins as
2914+ // the reconstruction -- what a decoder outputs, and what the next
2915+ // frame predicts from.
2916+ pick_and_apply_deblock(
2917+ &mut header,
2918+ &mut luma,
2919+ &mut chroma,
2920+ [&picture_y8, &picture_u8, &picture_v8],
2921+ true,
2922+ |lf, h| {
2923+ crate::decode::decode_key_frame_tile(
2924+ &tile,
2925+ h.mi_cols,
2926+ h.mi_rows,
2927+ base_q_idx,
2928+ h.frame_width,
2929+ h.frame_height,
2930+ seq.enable_filter_intra,
2931+ &CdefParams::default(),
2932+ lf,
2933+ tx_select,
2934+ h.reduced_tx_set,
2935+ h.allow_screen_content_tools,
2936+ h.allow_intrabc,
2937+ fctx,
2938+ )
2939+ },
2940+ )?;
29042941 let mut stream = temporal_delimiter();
29052942 stream.extend_from_slice(&sequence_header_obu(&seq)?);
29062943 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
@@ -2922,9 +2959,51 @@ pub(crate) fn encode_key_frame_inner(
29222959 mi_rows: header.mi_rows,
29232960 base_q_idx,
29242961 tx_select,
2962+ loop_filter: header.loop_filter,
29252963 })
29262964 }
29272965
2966+/// Chooses this frame's deblocking levels, writes them into `header` and
2967+/// replaces the frame's own region of the encoder's reconstruction with the
2968+/// filtered picture the decoder produced under them
2969+/// ([`crate::filter_search::pick_deblock`]).
2970+///
2971+/// `search == false` leaves the header at level 0 (deblocking off) and the
2972+/// reconstruction untouched: the caller's stream is one this crate's own
2973+/// decoder cannot read back, so there is nothing to search against.
2974+///
2975+/// # Errors
2976+/// 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 propagated
2978+/// rather than swallowed into "no deblocking".
2979+fn pick_and_apply_deblock(
2980+ header: &mut FrameHeader,
2981+ luma: &mut Plane<'_>,
2982+ chroma: &mut [Plane<'_>; 2],
2983+ source: [&[u8]; 3],
2984+ search: bool,
2985+ decode: impl Fn(&LoopFilterParams, &FrameHeader) -> Result<Picture>,
2986+) -> Result<()> {
2987+ if !search {
2988+ return Ok(());
2989+ }
2990+ let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);
2991+ let hdr = header.clone();
2992+ let (lf, filtered) = crate::filter_search::pick_deblock(
2993+ |lf| decode(lf, &hdr),
2994+ source,
2995+ luma.width,
2996+ (fw, fh),
2997+ )?;
2998+ header.loop_filter = lf;
2999+ let dec_cw = filtered.width.div_ceil(2);
3000+ 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);
3002+ crate::filter_search::splice(&mut chroma[0].reconstruction, chroma[0].width, &filtered.u, dec_cw, cw, ch);
3003+ crate::filter_search::splice(&mut chroma[1].reconstruction, chroma[1].width, &filtered.v, dec_cw, cw, ch);
3004+ Ok(())
3005+}
3006+
29283007 /// `Y_MODE`'s size group (spec `Size_Group`) for a 32x32 block: the only
29293008 /// group an inter frame's intra branch codes (spec `inter_frame_mode_info`),
29303009 /// since every block this crate's inter tile writer codes is 32x32.
@@ -3992,6 +4071,58 @@ pub(crate) fn encode_inter_frame(
39924071 &blocks,
39934072 tx_select,
39944073 )?;
4074+ // Deblocking, as in `encode_key_frame_inner`: the decoder reconstructs
4075+ // this tile against the same single-slot reference this encoder predicted
4076+ // from, under each candidate level.
4077+ // The reference a DECODER holds is this frame's cropped size, not the
4078+ // encoder's padded coding surface -- `decode_inter_frame_tile` refuses a
4079+ // reference whose height is not the header's own `frame_height` (spec
4080+ // 7.9's compatible-size rule), and the chained-decode round trips prove
4081+ // the two predict identically.
4082+ let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);
4083+ let trial_ref = if (reference.width, reference.height) == (fw, fh) {
4084+ reference.clone()
4085+ } else {
4086+ Picture {
4087+ width: fw,
4088+ height: fh,
4089+ y: crop_plane(&reference.y, reference.width, fw, fh),
4090+ u: crop_plane(&reference.u, reference.width / 2, fw / 2, fh / 2),
4091+ v: crop_plane(&reference.v, reference.width / 2, fw / 2, fh / 2),
4092+ }
4093+ };
4094+ let mut refs: [Option<&Picture>; 8] = [None; 8];
4095+ refs[1] = Some(&trial_ref);
4096+ let refpix = crate::decode::RefPix::ready(refs);
4097+ pick_and_apply_deblock(
4098+ &mut header,
4099+ &mut luma,
4100+ &mut chroma,
4101+ [&picture_y8, &picture_u8, &picture_v8],
4102+ // `decode_inter_frame_tile` reads an inter tile as `TxMode::Largest`;
4103+ // under the (default-off) inter `TxMode::Select` knob there is no
4104+ // decoder to search against, so that stream keeps level 0.
4105+ !tx_select,
4106+ |lf, h| {
4107+ crate::decode::decode_inter_frame_tile(
4108+ &tile,
4109+ h.mi_cols,
4110+ h.mi_rows,
4111+ base_q_idx,
4112+ h.frame_width,
4113+ h.frame_height,
4114+ &refpix,
4115+ &CdefParams::default(),
4116+ lf,
4117+ h.allow_high_precision_mv,
4118+ h.force_integer_mv,
4119+ Some(mc::InterpFilterKind::Regular),
4120+ seq.enable_dual_filter,
4121+ h.reference_select,
4122+ fctx,
4123+ )
4124+ },
4125+ )?;
39954126 let mut stream = temporal_delimiter();
39964127 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
39974128
@@ -4012,6 +4143,7 @@ pub(crate) fn encode_inter_frame(
40124143 mi_rows: header.mi_rows,
40134144 base_q_idx,
40144145 tx_select,
4146+ loop_filter: header.loop_filter,
40154147 })
40164148 }
40174149
crates/ec-av1/src/filter_search.rsadded+150 -0
@@ -0,0 +1,150 @@
1+//! Encoder-side in-loop filter parameter search (spec 7.14 deblocking).
2+//!
3+//! The encoder does not carry a second implementation of the loop filters:
4+//! it hands its own coded tile back to this crate's DECODER with candidate
5+//! filter parameters ([`crate::decode::decode_key_frame_tile`] /
6+//! [`crate::decode::decode_inter_frame_tile`]) and keeps the picture that
7+//! comes out. That is what keeps the encoder's reference frame identical to
8+//! what a decoder reconstructs -- a hand-written encoder-side deblock would
9+//! be a second implementation to drift from the first, and the BD gate's
10+//! ffmpeg-decodes-sample-exact assertion is what would find the drift, one
11+//! lane later. The cost is one tile decode per candidate; the tile itself is
12+//! coded once (loop filter parameters live in the frame header, never in the
13+//! tile payload, so no candidate re-runs the search or the entropy coder).
14+
15+use crate::encode::Picture;
16+use ec_av1_syntax::LoopFilterParams;
17+use ec_core::Result;
18+
19+/// Luma deblocking levels tried at the coarse stage, refined by +-1/+-2
20+/// around the winner (libaom's `av1_pick_filter_level` runs a golden-section
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];
23+
24+/// 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 different
26+/// strides: the source is the encoder's padded coding surface).
27+fn plane_sse(dec: &[u16], dec_w: usize, src: &[u8], src_w: usize, w: usize, h: usize) -> u64 {
28+ let mut sse = 0u64;
29+ for row in 0..h {
30+ let (d, s) = (&dec[row * dec_w..][..w], &src[row * src_w..][..w]);
31+ for (&a, &b) in d.iter().zip(s) {
32+ let diff = i64::from(a) - i64::from(b);
33+ sse += (diff * diff) as u64;
34+ }
35+ }
36+ sse
37+}
38+
39+/// One evaluated candidate: the decoded picture and its luma / chroma error.
40+struct Trial {
41+ level: (u8, u8),
42+ picture: Picture,
43+ sse_y: u64,
44+ sse_uv: u64,
45+}
46+
47+/// Picks `loop_filter_level[0..4]` for one frame and hands back the filtered
48+/// reconstruction that goes with the winner.
49+///
50+/// `decode` reconstructs this frame's already-coded tile under the candidate
51+/// 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 true
53+/// size, which is what `decode` crops to.
54+///
55+/// Luma (`level[0..2]`, kept equal -- this encoder has no reason to filter
56+/// vertical and horizontal edges differently) is chosen on luma SSE with the
57+/// chroma levels riding along, then chroma (`level[2..4]`) is chosen on
58+/// chroma SSE with luma fixed. `sharpness` stays 0 and the ref/mode deltas
59+/// stay off, as [`LoopFilterParams::default`] has them.
60+///
61+/// # Errors
62+/// Whatever `decode` returns: a stream this crate's own decoder refuses is
63+/// a caller's cue to keep its unfiltered reconstruction.
64+pub(crate) fn pick_deblock(
65+ decode: impl Fn(&LoopFilterParams) -> Result<Picture>,
66+ source: [&[u8]; 3],
67+ src_w: usize,
68+ (fw, fh): (usize, usize),
69+) -> Result<(LoopFilterParams, Picture)> {
70+ let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));
71+ let mut trials: Vec<Trial> = Vec::new();
72+ let eval = |level: (u8, u8), trials: &mut Vec<Trial>| -> Result<usize> {
73+ if let Some(i) = trials.iter().position(|t| t.level == level) {
74+ return Ok(i);
75+ }
76+ let lf = LoopFilterParams {
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);
82+ 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)
84+ + plane_sse(&picture.v, dec_cw, source[2], src_w / 2, cw, ch);
85+ trials.push(Trial { level, picture, sse_y, sse_uv });
86+ Ok(trials.len() - 1)
87+ };
88+
89+ // Luma: the coarse ladder, then +-1/+-2 around its winner.
90+ let mut best_y = 0u8;
91+ let mut best_sse = u64::MAX;
92+ for l in COARSE {
93+ let i = eval((l, l), &mut trials)?;
94+ if trials[i].sse_y < best_sse {
95+ best_sse = trials[i].sse_y;
96+ best_y = l;
97+ }
98+ }
99+ for delta in [-2i32, -1, 1, 2] {
100+ let Ok(l) = u8::try_from(i32::from(best_y) + delta) else {
101+ continue;
102+ };
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+
113+ // Chroma: three points around the luma winner. A chroma level of 0 with
114+ // luma non-zero is a real outcome (flat chroma has no edges to soften),
115+ // which is why `level[2..4]` is searched at all rather than tied to
116+ // `level[0]`.
117+ let mut best_uv = best_y;
118+ let mut best_sse_uv = u64::MAX;
119+ for c in [0, best_y / 2, best_y] {
120+ let i = eval((best_y, c), &mut trials)?;
121+ if trials[i].sse_uv < best_sse_uv {
122+ best_sse_uv = trials[i].sse_uv;
123+ best_uv = c;
124+ }
125+ }
126+
127+ let win = trials
128+ .into_iter()
129+ .find(|t| t.level == (best_y, best_uv))
130+ .expect("the winning pair was evaluated");
131+ Ok((
132+ LoopFilterParams {
133+ level: [best_y, best_y, best_uv, best_uv],
134+ ..LoopFilterParams::default()
135+ },
136+ win.picture,
137+ ))
138+}
139+
140+/// Writes the frame's own (cropped) region of `filtered` back over the
141+/// encoder's padded reconstruction planes, leaving whatever lies past the
142+/// frame edge untouched -- those columns/rows are the encoder's private
143+/// coding surface, never anything a decoder outputs.
144+pub(crate) fn splice(dst: &mut [u8], dst_w: usize, src: &[u16], src_w: usize, w: usize, h: usize) {
145+ for row in 0..h {
146+ for col in 0..w {
147+ dst[row * dst_w + col] = src[row * src_w + col] as u8;
148+ }
149+ }
150+}
crates/ec-av1/src/lib.rsmodified+1 -0
@@ -32,6 +32,7 @@ pub mod encode;
3232 pub mod encoder;
3333 mod envflags;
3434 mod film_grain;
35+mod filter_search;
3536 pub mod frame;
3637 mod gate_coverage;
3738 mod hits;
crates/ec-av1/src/stream.rsmodified+1 -1
@@ -2995,7 +2995,7 @@ mod tests {
29952995 height as u32,
29962996 false,
29972997 &ec_av1_syntax::CdefParams::default(),
2998- &ec_av1_syntax::LoopFilterParams::default(),
2998+ &encoded.loop_filter,
29992999 encoded.tx_select,
30003000 // Our own encoder always writes `reduced_tx_set: true`.
30013001 true,