From 873a1fb776723844a4aa03d3f65699ba1bcfe5fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 6 Sep 2026 06:54:33 +0300 Subject: [PATCH] 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.rs | 15 +-- crates/ec-av1/src/encode.rs | 136 +++++++++++++++++++++++++- crates/ec-av1/src/filter_search.rs | 150 +++++++++++++++++++++++++++++ crates/ec-av1/src/lib.rs | 1 + crates/ec-av1/src/stream.rs | 2 +- 5 files changed, 294 insertions(+), 10 deletions(-) create mode 100644 crates/ec-av1/src/filter_search.rs diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index e30bcee4..bf0fdbac 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -36619,6 +36619,7 @@ mod tests { mi_rows, base_q_idx, tx_select, + loop_filter, .. }: Encoded = crate::encode::encode_key_frame_with_modes_with_ctx(&picture, 40, 0.0, modes, fctx).unwrap(); let decoded = decode_key_frame_tile( @@ -36630,7 +36631,7 @@ mod tests { h as u32, false, &CdefParams::default(), - &LoopFilterParams::default(), + &loop_filter, tx_select, true, false, @@ -36995,7 +36996,7 @@ mod tests { coded_h, false, &CdefParams::default(), - &LoopFilterParams::default(), + &encoded.loop_filter, encoded.tx_select, true, false, @@ -37038,7 +37039,7 @@ mod tests { height as u32, false, &CdefParams::default(), - &LoopFilterParams::default(), + &encoded.loop_filter, tx_select, true, false, @@ -37122,7 +37123,7 @@ mod tests { height as u32, false, &CdefParams::default(), - &LoopFilterParams::default(), + &key.loop_filter, key.tx_select, true, false, @@ -37152,7 +37153,7 @@ mod tests { height as u32, &last_only(&reference), &CdefParams::default(), - &LoopFilterParams::default(), + &frame.loop_filter, false, false, Some(mc::InterpFilterKind::Regular), @@ -37442,7 +37443,7 @@ mod tests { coded_h, false, &CdefParams::default(), - &LoopFilterParams::default(), + &key.loop_filter, key.tx_select, true, false, @@ -37461,7 +37462,7 @@ mod tests { coded_h, &last_only(&reference), &CdefParams::default(), - &LoopFilterParams::default(), + &frame.loop_filter, false, false, Some(mc::InterpFilterKind::Regular), diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index f9030e40..129ac842 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -19,8 +19,8 @@ use crate::decode::WithRef; use ec_av1_syntax::sequence::{ColorConfig, OperatingPoint, SequenceHeader}; use ec_av1_syntax::{ - ChromaSamplePosition, FrameHeader, FrameType, PRIMARY_REF_NONE, QuantizationParams, TileInfo, - TxMode, + CdefParams, ChromaSamplePosition, FrameHeader, FrameType, LoopFilterParams, PRIMARY_REF_NONE, + QuantizationParams, TileInfo, TxMode, }; use ec_core::{Error, Result}; @@ -474,6 +474,7 @@ pub(crate) fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> En mi_rows: encoded.mi_rows, base_q_idx: encoded.base_q_idx, tx_select: encoded.tx_select, + loop_filter: encoded.loop_filter, } } @@ -510,6 +511,12 @@ pub struct Encoded { /// a `tx_depth` frame as a `TxMode::Largest` one and desyncs at the first /// block. pub(crate) tx_select: bool, + /// This frame header's chosen deblocking parameters + /// ([`crate::filter_search::pick_deblock`]) — `reconstruction` is the + /// picture the decoder produces UNDER them, so a test that decodes + /// `tile` directly must pass these along, exactly as it must `tx_select` + /// (class: test asserts against a stale header). + pub(crate) loop_filter: LoopFilterParams, } /// 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( &superblocks, tx_select, )?; + // spec 7.14 deblocking: pick this frame's `loop_filter_level` by handing + // the tile just coded back to the decoder under each candidate (see + // `crate::filter_search`), and keep the filtered picture that wins as + // the reconstruction -- what a decoder outputs, and what the next + // frame predicts from. + pick_and_apply_deblock( + &mut header, + &mut luma, + &mut chroma, + [&picture_y8, &picture_u8, &picture_v8], + true, + |lf, h| { + crate::decode::decode_key_frame_tile( + &tile, + h.mi_cols, + h.mi_rows, + base_q_idx, + h.frame_width, + h.frame_height, + seq.enable_filter_intra, + &CdefParams::default(), + lf, + tx_select, + h.reduced_tx_set, + h.allow_screen_content_tools, + h.allow_intrabc, + fctx, + ) + }, + )?; let mut stream = temporal_delimiter(); stream.extend_from_slice(&sequence_header_obu(&seq)?); stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?); @@ -2922,9 +2959,51 @@ pub(crate) fn encode_key_frame_inner( mi_rows: header.mi_rows, base_q_idx, tx_select, + loop_filter: header.loop_filter, }) } +/// Chooses this frame's deblocking levels, writes them into `header` and +/// replaces the frame's own region of the encoder's reconstruction with the +/// filtered picture the decoder produced under them +/// ([`crate::filter_search::pick_deblock`]). +/// +/// `search == false` leaves the header at level 0 (deblocking off) and the +/// reconstruction untouched: the caller's stream is one this crate's own +/// decoder cannot read back, so there is nothing to search against. +/// +/// # Errors +/// The decoder's own error, when it refuses the tile the encoder just wrote +/// -- that is an encoder defect, not a filter one, so it is propagated +/// rather than swallowed into "no deblocking". +fn pick_and_apply_deblock( + header: &mut FrameHeader, + luma: &mut Plane<'_>, + chroma: &mut [Plane<'_>; 2], + source: [&[u8]; 3], + search: bool, + decode: impl Fn(&LoopFilterParams, &FrameHeader) -> Result, +) -> Result<()> { + if !search { + return Ok(()); + } + let (fw, fh) = (header.frame_width as usize, header.frame_height as usize); + let hdr = header.clone(); + let (lf, filtered) = crate::filter_search::pick_deblock( + |lf| decode(lf, &hdr), + source, + luma.width, + (fw, fh), + )?; + header.loop_filter = lf; + let dec_cw = filtered.width.div_ceil(2); + let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2)); + crate::filter_search::splice(&mut luma.reconstruction, luma.width, &filtered.y, filtered.width, fw, fh); + crate::filter_search::splice(&mut chroma[0].reconstruction, chroma[0].width, &filtered.u, dec_cw, cw, ch); + crate::filter_search::splice(&mut chroma[1].reconstruction, chroma[1].width, &filtered.v, dec_cw, cw, ch); + Ok(()) +} + /// `Y_MODE`'s size group (spec `Size_Group`) for a 32x32 block: the only /// group an inter frame's intra branch codes (spec `inter_frame_mode_info`), /// since every block this crate's inter tile writer codes is 32x32. @@ -3992,6 +4071,58 @@ pub(crate) fn encode_inter_frame( &blocks, tx_select, )?; + // Deblocking, as in `encode_key_frame_inner`: the decoder reconstructs + // this tile against the same single-slot reference this encoder predicted + // from, under each candidate level. + // The reference a DECODER holds is this frame's cropped size, not the + // encoder's padded coding surface -- `decode_inter_frame_tile` refuses a + // reference whose height is not the header's own `frame_height` (spec + // 7.9's compatible-size rule), and the chained-decode round trips prove + // the two predict identically. + let (fw, fh) = (header.frame_width as usize, header.frame_height as usize); + let trial_ref = if (reference.width, reference.height) == (fw, fh) { + reference.clone() + } else { + Picture { + width: fw, + height: fh, + y: crop_plane(&reference.y, reference.width, fw, fh), + u: crop_plane(&reference.u, reference.width / 2, fw / 2, fh / 2), + v: crop_plane(&reference.v, reference.width / 2, fw / 2, fh / 2), + } + }; + let mut refs: [Option<&Picture>; 8] = [None; 8]; + refs[1] = Some(&trial_ref); + let refpix = crate::decode::RefPix::ready(refs); + pick_and_apply_deblock( + &mut header, + &mut luma, + &mut chroma, + [&picture_y8, &picture_u8, &picture_v8], + // `decode_inter_frame_tile` reads an inter tile as `TxMode::Largest`; + // under the (default-off) inter `TxMode::Select` knob there is no + // decoder to search against, so that stream keeps level 0. + !tx_select, + |lf, h| { + crate::decode::decode_inter_frame_tile( + &tile, + h.mi_cols, + h.mi_rows, + base_q_idx, + h.frame_width, + h.frame_height, + &refpix, + &CdefParams::default(), + lf, + h.allow_high_precision_mv, + h.force_integer_mv, + Some(mc::InterpFilterKind::Regular), + seq.enable_dual_filter, + h.reference_select, + fctx, + ) + }, + )?; let mut stream = temporal_delimiter(); stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?); @@ -4012,6 +4143,7 @@ pub(crate) fn encode_inter_frame( mi_rows: header.mi_rows, base_q_idx, tx_select, + loop_filter: header.loop_filter, }) } diff --git a/crates/ec-av1/src/filter_search.rs b/crates/ec-av1/src/filter_search.rs new file mode 100644 index 00000000..a063e8c3 --- /dev/null +++ b/crates/ec-av1/src/filter_search.rs @@ -0,0 +1,150 @@ +//! Encoder-side in-loop filter parameter search (spec 7.14 deblocking). +//! +//! The encoder does not carry a second implementation of the loop filters: +//! it hands its own coded tile back to this crate's DECODER with candidate +//! filter parameters ([`crate::decode::decode_key_frame_tile`] / +//! [`crate::decode::decode_inter_frame_tile`]) and keeps the picture that +//! comes out. That is what keeps the encoder's reference frame identical to +//! what a decoder reconstructs -- a hand-written encoder-side deblock would +//! be a second implementation to drift from the first, and the BD gate's +//! ffmpeg-decodes-sample-exact assertion is what would find the drift, one +//! lane later. The cost is one tile decode per candidate; the tile itself is +//! coded once (loop filter parameters live in the frame header, never in the +//! tile payload, so no candidate re-runs the search or the entropy coder). + +use crate::encode::Picture; +use ec_av1_syntax::LoopFilterParams; +use ec_core::Result; + +/// Luma deblocking levels tried at the coarse stage, refined by +-1/+-2 +/// around the winner (libaom's `av1_pick_filter_level` runs a golden-section +/// search over the same 0..63 range; this ladder is the charter's). +const COARSE: [u8; 7] = [0, 4, 8, 16, 24, 32, 48]; + +/// Squared error between a decoded plane and the source it was coded from, +/// over the frame's own cropped `w x h` (the two planes have different +/// strides: the source is the encoder's padded coding surface). +fn plane_sse(dec: &[u16], dec_w: usize, src: &[u8], src_w: usize, w: usize, h: usize) -> u64 { + let mut sse = 0u64; + for row in 0..h { + let (d, s) = (&dec[row * dec_w..][..w], &src[row * src_w..][..w]); + for (&a, &b) in d.iter().zip(s) { + let diff = i64::from(a) - i64::from(b); + sse += (diff * diff) as u64; + } + } + sse +} + +/// One evaluated candidate: the decoded picture and its luma / chroma error. +struct Trial { + level: (u8, u8), + picture: Picture, + sse_y: u64, + sse_uv: u64, +} + +/// Picks `loop_filter_level[0..4]` for one frame and hands back the filtered +/// reconstruction that goes with the winner. +/// +/// `decode` reconstructs this frame's already-coded tile under the candidate +/// parameters; `source` is the encoder's padded (luma, U, V) coding surface +/// with luma stride `src_w`, and `(fw, fh)` the frame header's own true +/// size, which is what `decode` crops to. +/// +/// Luma (`level[0..2]`, kept equal -- this encoder has no reason to filter +/// vertical and horizontal edges differently) is chosen on luma SSE with the +/// chroma levels riding along, then chroma (`level[2..4]`) is chosen on +/// chroma SSE with luma fixed. `sharpness` stays 0 and the ref/mode deltas +/// stay off, as [`LoopFilterParams::default`] has them. +/// +/// # Errors +/// Whatever `decode` returns: a stream this crate's own decoder refuses is +/// a caller's cue to keep its unfiltered reconstruction. +pub(crate) fn pick_deblock( + decode: impl Fn(&LoopFilterParams) -> Result, + source: [&[u8]; 3], + src_w: usize, + (fw, fh): (usize, usize), +) -> Result<(LoopFilterParams, Picture)> { + let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2)); + let mut trials: Vec = Vec::new(); + let eval = |level: (u8, u8), trials: &mut Vec| -> Result { + if let Some(i) = trials.iter().position(|t| t.level == level) { + return Ok(i); + } + let lf = LoopFilterParams { + level: [level.0, level.0, level.1, level.1], + ..LoopFilterParams::default() + }; + let picture = decode(&lf)?; + let dec_cw = picture.width.div_ceil(2); + let sse_y = plane_sse(&picture.y, picture.width, source[0], src_w, fw, fh); + let sse_uv = plane_sse(&picture.u, dec_cw, source[1], src_w / 2, cw, ch) + + plane_sse(&picture.v, dec_cw, source[2], src_w / 2, cw, ch); + trials.push(Trial { level, picture, sse_y, sse_uv }); + Ok(trials.len() - 1) + }; + + // Luma: the coarse ladder, then +-1/+-2 around its winner. + let mut best_y = 0u8; + let mut best_sse = u64::MAX; + for l in COARSE { + let i = eval((l, l), &mut trials)?; + if trials[i].sse_y < best_sse { + best_sse = trials[i].sse_y; + best_y = l; + } + } + for delta in [-2i32, -1, 1, 2] { + let Ok(l) = u8::try_from(i32::from(best_y) + delta) else { + continue; + }; + if l > 63 { + continue; + } + let i = eval((l, l), &mut trials)?; + if trials[i].sse_y < best_sse { + best_sse = trials[i].sse_y; + best_y = l; + } + } + + // Chroma: three points around the luma winner. A chroma level of 0 with + // luma non-zero is a real outcome (flat chroma has no edges to soften), + // which is why `level[2..4]` is searched at all rather than tied to + // `level[0]`. + let mut best_uv = best_y; + let mut best_sse_uv = u64::MAX; + for c in [0, best_y / 2, best_y] { + let i = eval((best_y, c), &mut trials)?; + if trials[i].sse_uv < best_sse_uv { + best_sse_uv = trials[i].sse_uv; + best_uv = c; + } + } + + let win = trials + .into_iter() + .find(|t| t.level == (best_y, best_uv)) + .expect("the winning pair was evaluated"); + Ok(( + LoopFilterParams { + level: [best_y, best_y, best_uv, best_uv], + ..LoopFilterParams::default() + }, + win.picture, + )) +} + +/// Writes the frame's own (cropped) region of `filtered` back over the +/// encoder's padded reconstruction planes, leaving whatever lies past the +/// frame edge untouched -- those columns/rows are the encoder's private +/// coding surface, never anything a decoder outputs. +pub(crate) fn splice(dst: &mut [u8], dst_w: usize, src: &[u16], src_w: usize, w: usize, h: usize) { + for row in 0..h { + for col in 0..w { + dst[row * dst_w + col] = src[row * src_w + col] as u8; + } + } +} diff --git a/crates/ec-av1/src/lib.rs b/crates/ec-av1/src/lib.rs index b614c19d..4ff9d097 100644 --- a/crates/ec-av1/src/lib.rs +++ b/crates/ec-av1/src/lib.rs @@ -32,6 +32,7 @@ pub mod encode; pub mod encoder; mod envflags; mod film_grain; +mod filter_search; pub mod frame; mod gate_coverage; mod hits; diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index f7ee04fb..1b4bc737 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -2995,7 +2995,7 @@ mod tests { height as u32, false, &ec_av1_syntax::CdefParams::default(), - &ec_av1_syntax::LoopFilterParams::default(), + &encoded.loop_filter, encoded.tx_select, // Our own encoder always writes `reduced_tx_set: true`. true,