diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 0bc7ab30..c5d89bdf 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -36628,6 +36628,8 @@ mod tests { mi_rows, base_q_idx, tx_select, + loop_filter, + cdef, .. }: Encoded = crate::encode::encode_key_frame_with_modes_with_ctx(&picture, 40, 0.0, modes, fctx).unwrap(); let decoded = decode_key_frame_tile( @@ -36638,8 +36640,8 @@ mod tests { w as u32, h as u32, false, - &CdefParams::default(), - &LoopFilterParams::default(), + &cdef, + &loop_filter, tx_select, true, false, @@ -37006,8 +37008,8 @@ mod tests { coded_w, coded_h, false, - &CdefParams::default(), - &LoopFilterParams::default(), + &encoded.cdef, + &encoded.loop_filter, encoded.tx_select, true, false, @@ -37049,8 +37051,8 @@ mod tests { width as u32, height as u32, false, - &CdefParams::default(), - &LoopFilterParams::default(), + &encoded.cdef, + &encoded.loop_filter, tx_select, true, false, @@ -37133,8 +37135,8 @@ mod tests { width as u32, height as u32, false, - &CdefParams::default(), - &LoopFilterParams::default(), + &key.cdef, + &key.loop_filter, key.tx_select, true, false, @@ -37163,8 +37165,8 @@ mod tests { width as u32, height as u32, &last_only(&reference), - &CdefParams::default(), - &LoopFilterParams::default(), + &frame.cdef, + &frame.loop_filter, false, false, Some(mc::InterpFilterKind::Regular), @@ -37456,8 +37458,8 @@ mod tests { coded_w, coded_h, false, - &CdefParams::default(), - &LoopFilterParams::default(), + &key.cdef, + &key.loop_filter, key.tx_select, true, false, @@ -37475,8 +37477,8 @@ mod tests { coded_w, coded_h, &last_only(&reference), - &CdefParams::default(), - &LoopFilterParams::default(), + &frame.cdef, + &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 c5f736ca..6adb1492 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}; @@ -479,6 +479,8 @@ pub(crate) fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> En tx_select: encoded.tx_select, start_cdfs: encoded.start_cdfs.clone(), next_cdfs: encoded.next_cdfs.clone(), + loop_filter: encoded.loop_filter, + cdef: encoded.cdef, } } @@ -538,10 +540,21 @@ pub struct Encoded { /// counts reset when `disable_frame_end_update_cdf` is off, and what it /// started from when it is on. pub(crate) next_cdfs: CdfSnapshot, + /// 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, + /// This frame header's chosen CDEF parameters, threaded for the same + /// reason as `loop_filter`. + pub(crate) cdef: CdefParams, } /// The sequence and frame headers a picture of this size is coded under: one -/// tile, one transform size per block, no in-loop filtering, no CDF adaptation +/// tile, one transform size per block, no in-loop filter parameters yet +/// (`crate::encode::pick_and_apply_filters` fills the deblocking levels and +/// CDEF strengths in once the tile is coded), no CDF adaptation /// and no tool the tile writer does not code. /// /// # Errors @@ -614,7 +627,12 @@ pub(crate) fn key_frame_headers_colour( enable_order_hint: true, order_hint_bits: 7, enable_superres: false, - enable_cdef: false, + // spec 5.9.19: with the sequence bit set every frame header carries + // `cdef_params`. This encoder writes `cdef_bits == 0` -- one strength + // pair for the whole frame, chosen by `crate::filter_search` -- so no + // `cdef_idx` literal is coded in the tile and a frame that wants no + // CDEF simply carries zero strengths. + enable_cdef: true, enable_restoration: false, seq_force_screen_content_tools: 0, seq_force_integer_mv: 0, @@ -3051,6 +3069,36 @@ pub(crate) fn encode_key_frame_inner( tx_select, &mut cdfs, )?; + // 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_filters( + &mut header, + &mut luma, + &mut chroma, + [&picture_y8, &picture_u8, &picture_v8], + true, + |lf, cdef, 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, + cdef, + 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)?); @@ -3074,9 +3122,58 @@ pub(crate) fn encode_key_frame_inner( tx_select, next_cdfs: start_cdfs.clone(), start_cdfs, + loop_filter: header.loop_filter, + cdef: header.cdef, }) } +/// Chooses this frame's deblocking levels and CDEF strengths, 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_filters( + header: &mut FrameHeader, + luma: &mut Plane<'_>, + chroma: &mut [Plane<'_>; 2], + source: [&[u8]; 3], + search: bool, + decode: impl Fn(&LoopFilterParams, &CdefParams, &FrameHeader) -> Result, +) -> Result<()> { + if !search { + return Ok(()); + } + let (fw, fh) = (header.frame_width as usize, header.frame_height as usize); + let hdr = header.clone(); + // libaom `av1_pick_filter_level`'s sibling `av1_cdef_search`: + // `cdef_damping = 3 + (base_qindex >> 6)`, never searched. + let damping = 3 + (header.quantization.base_q_idx >> 6); + let (lf, cdef, filtered) = crate::filter_search::pick_filters( + |lf, cdef| decode(lf, cdef, &hdr), + source, + luma.width, + (fw, fh), + damping, + )?; + header.loop_filter = lf; + header.cdef = cdef; + 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. @@ -4143,6 +4240,64 @@ pub(crate) fn encode_inter_frame( tx_select, &mut cdfs, )?; + // 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_filters( + &mut header, + &mut luma, + &mut chroma, + [&picture_y8, &picture_u8, &picture_v8], + // Merge of lane-av1filt with lane-av1tx2: the trial decoder takes + // this frame's own `tx_select`, so the search runs under inter + // `TxMode::Select` too (it used to skip and leave every inter frame + // unfiltered once Select became the default). + true, + |lf, cdef, h| { + crate::decode::decode_inter_frame_tile( + &tile, + h.mi_cols, + h.mi_rows, + base_q_idx, + h.frame_width, + h.frame_height, + &refpix, + cdef, + lf, + h.allow_high_precision_mv, + h.force_integer_mv, + Some(mc::InterpFilterKind::Regular), + seq.enable_dual_filter, + h.reference_select, + tx_select, + // The trial decode re-reads the tile the writer just wrote, + // so it starts from the same tables the writer did (this + // frame's `start_cdfs`), not from the defaults. + Some(start_cdfs.0.clone()), + fctx, + ) + }, + )?; cdfs.reset_counts(); let next_cdfs = CdfSnapshot(cdfs); let mut stream = temporal_delimiter(); @@ -4167,6 +4322,8 @@ pub(crate) fn encode_inter_frame( tx_select, start_cdfs, next_cdfs, + loop_filter: header.loop_filter, + cdef: header.cdef, }) } @@ -4488,6 +4645,46 @@ mod tests { /// A picture with something of everything in it: a gradient, an edge, a /// ripple and a block of flat colour, none of them aligned to the block /// grid. + /// The in-loop filters actually FIRE and the stream still decodes to + /// exactly what the encoder kept as its reconstruction + /// (gate-blind-to-feature: a filter search that always answered "off" + /// would leave every other test just as green, and the BD gate that + /// would notice is `#[ignore]`d). + /// + /// Run: + /// cargo test -p ec-av1 --release --lib -- \ + /// encode::tests::the_filter_search_picks_real_filters + #[test] + fn the_filter_search_picks_real_filters() { + let fctx = &crate::decode::FrameCtx::new(); + let pictures: Vec<_> = (0..3).map(|i| panned_test_card(128, 128, i * 3)).collect(); + let encoded = encode_sequence_with_ctx(&pictures, 120, 0.5, fctx).unwrap(); + let fired = encoded + .frames + .iter() + .filter(|f| f.loop_filter.level[0] > 0 || f.cdef.y_pri_strength[0] > 0) + .count(); + assert!( + fired > 0, + "no frame of this sequence chose any in-loop filtering: {:?}", + encoded + .frames + .iter() + .map(|f| (f.loop_filter.level, f.cdef.y_pri_strength[0])) + .collect::>() + ); + // The reconstruction the encoder predicts from is the FILTERED one, + // and it is what a decoder of the stream produces -- byte for byte, + // frame for frame. + let decoded = crate::stream::decode_stream(&encoded.stream).unwrap(); + assert_eq!(decoded.len(), encoded.frames.len()); + for (i, (dec, enc)) in decoded.iter().zip(&encoded.frames).enumerate() { + assert_eq!(dec.y, enc.reconstruction.y, "frame {i} luma"); + assert_eq!(dec.u, enc.reconstruction.u, "frame {i} U"); + assert_eq!(dec.v, enc.reconstruction.v, "frame {i} V"); + } + } + fn test_card(width: usize, height: usize) -> Picture { let mut picture = Picture::grey(width, height); for y in 0..height { @@ -6936,15 +7133,30 @@ mod tests { /// ours: `base_q_idx {60,90,120,150}`. Every PSNR is all-plane, on /// ffmpeg-decoded frames of each encoder's own stream. /// - /// Measured 2026-09-06 after the inter partition search (lane-av1rd2), - /// 12 frames, this box (wall = the four encodes of that ladder - /// together): + /// Measured 2026-09-06 after the in-loop filters (lane-av1filt: per-frame + /// deblocking levels and CDEF strengths, both chosen by re-decoding the + /// coded tile -- `crate::filter_search`), 12 frames, this box (wall = the + /// four encodes of that ladder together): /// /// | clip | ours (q 150/120/90/60) | BD-rate vs libaom | vs rav1e | wall ours:aom:rav1e | /// |---|---|---|---|---| - /// | 1080p fixture | 41.16 dB/22349 B .. 49.97 dB/83178 B | +234.0% | +171.9% | 9.8s:1.1s:2.6s | - /// | 2160p fixture | 42.01 dB/14687 B .. 50.82 dB/52415 B | +260.3% | +203.2% | 9.3s:1.0s:2.2s | - /// | screen capture | 37.49 dB/12797 B .. 46.19 dB/50643 B | +318.5% | +155.3% | 9.1s:1.0s:2.1s | + /// | 1080p fixture | 42.11 dB/17774 B .. 50.99 dB/76838 B | +143.6% | +94.0% | 9.2s:1.1s:2.6s | + /// | 2160p fixture | 42.84 dB/12480 B .. 51.43 dB/46557 B | +179.5% | +128.8% | 8.6s:1.0s:2.2s | + /// | screen capture | 39.76 dB/9536 B .. 48.87 dB/29189 B | +88.0% | +21.5% | 7.2s:1.0s:2.1s | + /// + /// The three steps of that lane, same recipe (vs libaom, then vs rav1e): + /// + /// | step | 1080p | 2160p | screen | + /// |---|---|---|---| + /// | no in-loop filter | +234.0 / +171.9 | +260.3 / +203.2 | +318.5 / +155.3 | + /// | + deblocking | +198.2 / +143.1 | +218.1 / +162.4 | +136.9 / +52.7 | + /// | + CDEF | +143.6 / +94.0 | +179.5 / +128.8 | +88.0 / +21.5 | + /// + /// Loop restoration is NOT in yet: it is the one filter whose parameters + /// are per restoration UNIT inside the tile payload, so it needs both + /// tile writers to code `lr` syntax and an encoder-visible post-CDEF + /// buffer to solve against -- neither of which this frame-header-level + /// search reaches. /// /// The baseline it replaced, before an inter frame's blocks chose their /// own partition, was +501.4/+504.4/+440.9 against libaom and @@ -7057,6 +7269,24 @@ mod tests { whole16 + split16, 100.0 * split16 as f64 / (whole16 + split16).max(1) as f64 ); + // The deblocking level each of this clip's frames chose + // (lane-av1filt): 0 everywhere would mean the filter never fires. + let levels = crate::filter_search::take_chosen_levels(); + type Chosen = ((u8, u8), (u8, u8), (u8, u8)); + let mean = |f: fn(&Chosen) -> u8| { + levels.iter().map(|l| f(l) as f64).sum::() / levels.len().max(1) as f64 + }; + eprintln!( + "{name}: over {} frames -- deblock luma mean {:.1} chroma {:.1}; \ + cdef luma pri {:.1}/sec {:.1}, chroma pri {:.1}/sec {:.1}", + levels.len(), + mean(|l| l.0.0), + mean(|l| l.0.1), + mean(|l| l.1.0), + mean(|l| l.1.1), + mean(|l| l.2.0), + mean(|l| l.2.1), + ); // Which chroma modes the search actually wins with, against the // unconditional DC_PRED that was the only outcome before // (gate-blind-to-feature). diff --git a/crates/ec-av1/src/filter_search.rs b/crates/ec-av1/src/filter_search.rs new file mode 100644 index 00000000..7a40e1b9 --- /dev/null +++ b/crates/ec-av1/src/filter_search.rs @@ -0,0 +1,207 @@ +//! 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::{CdefParams, 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]; + +thread_local! { + /// Every frame's chosen filter parameters, in coding + /// order -- the BD gate prints the distribution once per clip + /// (gate-blind-to-feature: a filter nobody counts is a filter that may + /// never fire). + static CHOSEN: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; +} + +/// Takes and clears [`CHOSEN`]. +#[allow(dead_code)] // read from the `#[cfg(test)]` BD gate +pub(crate) fn take_chosen_levels() -> Vec<((u8, u8), (u8, u8), (u8, u8))> { + CHOSEN.with(|c| { + std::mem::take(&mut *c.borrow_mut()) + .into_iter() + .map(|c| (c.lf, c.y, c.uv)) + .collect() + }) +} + +/// 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 +} + +/// CDEF primary strengths tried (libaom's own range is 0..15 for 8-bit +/// content) and the secondary ladder, whose only legal values are 0, 1, 2 +/// and 4 -- 3 is not codeable (spec 5.9.19 codes a secondary strength of 4 +/// as 3). +const CDEF_PRI: [u8; 5] = [0, 1, 2, 4, 8]; +const CDEF_SEC: [u8; 4] = [0, 1, 2, 4]; + +/// One point of the filter search: the deblocking levels and the single +/// CDEF strength pair per plane type this encoder writes (`cdef_bits == 0`, +/// so no `cdef_idx` literal is coded in the tile at all and the choice is +/// purely a frame-header one). +#[derive(Clone, Copy, PartialEq, Eq)] +struct Cand { + /// `(luma, chroma)` deblocking level. + lf: (u8, u8), + /// Luma `(primary, secondary)` CDEF strength. + y: (u8, u8), + /// Chroma `(primary, secondary)` CDEF strength. + uv: (u8, u8), +} + +/// One evaluated candidate: the decoded picture and its luma / chroma error. +struct Trial { + cand: Cand, + picture: Picture, + sse_y: u64, + sse_uv: u64, +} + +/// Picks this frame's deblocking levels and CDEF strengths 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`, `(fw, fh)` the frame header's own true size, +/// which is what `decode` crops to, and `damping` the CDEF damping the +/// caller's header carries. +/// +/// A coordinate search, in the decoder's own filter order and each stage on +/// the plane it moves: deblocking luma (`level[0..2]`, kept equal -- nothing +/// here filters vertical and horizontal edges differently), deblocking +/// chroma (`level[2..4]`, a real choice of its own: flat chroma has no edges +/// to soften), then CDEF's luma and chroma primary/secondary strengths. +/// `sharpness` stays 0, the loop-filter deltas stay off, and `cdef_bits` +/// stays 0 -- one strength pair for the whole frame, which is the only CDEF +/// shape that costs no `cdef_idx` literal in the tile payload. +/// +/// # 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_filters( + decode: impl Fn(&LoopFilterParams, &CdefParams) -> Result, + source: [&[u8]; 3], + src_w: usize, + (fw, fh): (usize, usize), + damping: u8, +) -> Result<(LoopFilterParams, CdefParams, Picture)> { + let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2)); + let mut trials: Vec = Vec::new(); + let eval = |cand: Cand, trials: &mut Vec| -> Result { + if let Some(i) = trials.iter().position(|t| t.cand == cand) { + return Ok(i); + } + let picture = decode(&loop_filter(cand), &cdef(cand, damping))?; + 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 { cand, picture, sse_y, sse_uv }); + Ok(trials.len() - 1) + }; + // One stage of the coordinate search: try `values` in the slot `set` + // moves and keep the one with the lowest error `sse` reads. + let stage = |best: &mut Cand, + values: &[u8], + set: fn(&mut Cand, u8), + sse: fn(&Trial) -> u64, + trials: &mut Vec| + -> Result<()> { + let mut winner = *best; + let mut lowest = u64::MAX; + for &v in values { + let mut cand = *best; + set(&mut cand, v); + let i = eval(cand, trials)?; + if sse(&trials[i]) < lowest { + lowest = sse(&trials[i]); + winner = cand; + } + } + *best = winner; + Ok(()) + }; + + let mut best = Cand { lf: (0, 0), y: (0, 0), uv: (0, 0) }; + // Deblocking luma: the coarse ladder, then +-1/+-2 around its winner. + stage(&mut best, &COARSE, |c, v| c.lf = (v, v), |t| t.sse_y, &mut trials)?; + let refine: Vec = [-2i32, -1, 1, 2] + .iter() + .filter_map(|d| u8::try_from(i32::from(best.lf.0) + d).ok()) + .filter(|&l| l <= 63) + .collect(); + stage(&mut best, &refine, |c, v| c.lf = (v, v), |t| t.sse_y, &mut trials)?; + // Deblocking chroma, three points around the luma winner. + let chroma_levels = [0, best.lf.0 / 2, best.lf.0]; + stage(&mut best, &chroma_levels, |c, v| c.lf.1 = v, |t| t.sse_uv, &mut trials)?; + // CDEF, primary then secondary, luma on luma error and chroma on chroma. + stage(&mut best, &CDEF_PRI, |c, v| c.y.0 = v, |t| t.sse_y, &mut trials)?; + stage(&mut best, &CDEF_SEC, |c, v| c.y.1 = v, |t| t.sse_y, &mut trials)?; + stage(&mut best, &CDEF_PRI, |c, v| c.uv.0 = v, |t| t.sse_uv, &mut trials)?; + stage(&mut best, &CDEF_SEC, |c, v| c.uv.1 = v, |t| t.sse_uv, &mut trials)?; + + CHOSEN.with(|c| c.borrow_mut().push(best)); + let win = trials + .into_iter() + .find(|t| t.cand == best) + .expect("the winning candidate was evaluated"); + Ok((loop_filter(best), cdef(best, damping), win.picture)) +} + +/// The header's `loop_filter_params` for one candidate. +fn loop_filter(cand: Cand) -> LoopFilterParams { + LoopFilterParams { + level: [cand.lf.0, cand.lf.0, cand.lf.1, cand.lf.1], + ..LoopFilterParams::default() + } +} + +/// The header's `cdef_params` for one candidate: a single strength pair per +/// plane type (`bits == 0`). +fn cdef(cand: Cand, damping: u8) -> CdefParams { + let mut cdef = CdefParams { damping, bits: 0, ..CdefParams::default() }; + cdef.y_pri_strength[0] = cand.y.0; + cdef.y_sec_strength[0] = cand.y.1; + cdef.uv_pri_strength[0] = cand.uv.0; + cdef.uv_sec_strength[0] = cand.uv.1; + cdef +} + +/// 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 96d19465..675cb1a2 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -2994,8 +2994,8 @@ mod tests { width as u32, height as u32, false, - &ec_av1_syntax::CdefParams::default(), - &ec_av1_syntax::LoopFilterParams::default(), + &encoded.cdef, + &encoded.loop_filter, encoded.tx_select, // Our own encoder always writes `reduced_tx_set: true`. true,