forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-av1filt' (193d9a9e): the encoder searches deblock levels and CDEF strengths by re-decoding its own tile

Browse files at this commit

1b6265b4504fec9e419c78e55cbc5b931d9513c2Ahmet Kaan GümüşParent: 2d62fa606cf00e
Merge resolution: the trial decoder now takes the frame's own tx_select bit
(c78863b8), so the filter search runs under inter TxMode::Select too instead
of skipping -- with Select the default since lane-av1tx2, the lane's own skip
would have left every inter frame unfiltered (class: merge cross-product).
crates/ec-av1/src/decode.rsmodified+16 -14
@@ -36623,6 +36623,8 @@ mod tests {
36623 mi_rows,36623 mi_rows,
36624 base_q_idx,36624 base_q_idx,
36625 tx_select,36625 tx_select,
36626+ loop_filter,
36627+ cdef,
36626 ..36628 ..
36627 }: Encoded = crate::encode::encode_key_frame_with_modes_with_ctx(&picture, 40, 0.0, modes, fctx).unwrap();36629 }: Encoded = crate::encode::encode_key_frame_with_modes_with_ctx(&picture, 40, 0.0, modes, fctx).unwrap();
36628 let decoded = decode_key_frame_tile(36630 let decoded = decode_key_frame_tile(
@@ -36633,8 +36635,8 @@ mod tests {
36633 w as u32,36635 w as u32,
36634 h as u32,36636 h as u32,
36635 false,36637 false,
36636- &CdefParams::default(),36638+ &cdef,
36637- &LoopFilterParams::default(),36639+ &loop_filter,
36638 tx_select,36640 tx_select,
36639 true,36641 true,
36640 false,36642 false,
@@ -37000,8 +37002,8 @@ mod tests {
37000 coded_w,37002 coded_w,
37001 coded_h,37003 coded_h,
37002 false,37004 false,
37003- &CdefParams::default(),37005+ &encoded.cdef,
37004- &LoopFilterParams::default(),37006+ &encoded.loop_filter,
37005 encoded.tx_select,37007 encoded.tx_select,
37006 true,37008 true,
37007 false,37009 false,
@@ -37043,8 +37045,8 @@ mod tests {
37043 width as u32,37045 width as u32,
37044 height as u32,37046 height as u32,
37045 false,37047 false,
37046- &CdefParams::default(),37048+ &encoded.cdef,
37047- &LoopFilterParams::default(),37049+ &encoded.loop_filter,
37048 tx_select,37050 tx_select,
37049 true,37051 true,
37050 false,37052 false,
@@ -37127,8 +37129,8 @@ mod tests {
37127 width as u32,37129 width as u32,
37128 height as u32,37130 height as u32,
37129 false,37131 false,
37130- &CdefParams::default(),37132+ &key.cdef,
37131- &LoopFilterParams::default(),37133+ &key.loop_filter,
37132 key.tx_select,37134 key.tx_select,
37133 true,37135 true,
37134 false,37136 false,
@@ -37157,8 +37159,8 @@ mod tests {
37157 width as u32,37159 width as u32,
37158 height as u32,37160 height as u32,
37159 &last_only(&reference),37161 &last_only(&reference),
37160- &CdefParams::default(),37162+ &frame.cdef,
37161- &LoopFilterParams::default(),37163+ &frame.loop_filter,
37162 false,37164 false,
37163 false,37165 false,
37164 Some(mc::InterpFilterKind::Regular),37166 Some(mc::InterpFilterKind::Regular),
@@ -37449,8 +37451,8 @@ mod tests {
37449 coded_w,37451 coded_w,
37450 coded_h,37452 coded_h,
37451 false,37453 false,
37452- &CdefParams::default(),37454+ &key.cdef,
37453- &LoopFilterParams::default(),37455+ &key.loop_filter,
37454 key.tx_select,37456 key.tx_select,
37455 true,37457 true,
37456 false,37458 false,
@@ -37468,8 +37470,8 @@ mod tests {
37468 coded_w,37470 coded_w,
37469 coded_h,37471 coded_h,
37470 &last_only(&reference),37472 &last_only(&reference),
37471- &CdefParams::default(),37473+ &frame.cdef,
37472- &LoopFilterParams::default(),37474+ &frame.loop_filter,
37473 false,37475 false,
37474 false,37476 false,
37475 Some(mc::InterpFilterKind::Regular),37477 Some(mc::InterpFilterKind::Regular),
crates/ec-av1/src/encode.rsmodified+236 -10
@@ -19,8 +19,8 @@
19 use crate::decode::WithRef;19 use crate::decode::WithRef;
20 use ec_av1_syntax::sequence::{ColorConfig, OperatingPoint, SequenceHeader};20 use ec_av1_syntax::sequence::{ColorConfig, OperatingPoint, SequenceHeader};
21 use ec_av1_syntax::{21 use ec_av1_syntax::{
22- ChromaSamplePosition, FrameHeader, FrameType, PRIMARY_REF_NONE, QuantizationParams, TileInfo,22+ CdefParams, ChromaSamplePosition, FrameHeader, FrameType, LoopFilterParams, PRIMARY_REF_NONE,
23- TxMode,23+ QuantizationParams, TileInfo, TxMode,
24 };24 };
25 use ec_core::{Error, Result};25 use ec_core::{Error, Result};
26 26
@@ -477,6 +477,8 @@ pub(crate) fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> En
477 mi_rows: encoded.mi_rows,477 mi_rows: encoded.mi_rows,
478 base_q_idx: encoded.base_q_idx,478 base_q_idx: encoded.base_q_idx,
479 tx_select: encoded.tx_select,479 tx_select: encoded.tx_select,
480+ loop_filter: encoded.loop_filter,
481+ cdef: encoded.cdef,
480 }482 }
481 }483 }
482 484
@@ -513,10 +515,21 @@ pub struct Encoded {
513 /// a `tx_depth` frame as a `TxMode::Largest` one and desyncs at the first515 /// a `tx_depth` frame as a `TxMode::Largest` one and desyncs at the first
514 /// block.516 /// block.
515 pub(crate) tx_select: bool,517 pub(crate) tx_select: bool,
518+ /// This frame header's chosen deblocking parameters
519+ /// ([`crate::filter_search::pick_deblock`]) — `reconstruction` is the
520+ /// picture the decoder produces UNDER them, so a test that decodes
521+ /// `tile` directly must pass these along, exactly as it must `tx_select`
522+ /// (class: test asserts against a stale header).
523+ pub(crate) loop_filter: LoopFilterParams,
524+ /// This frame header's chosen CDEF parameters, threaded for the same
525+ /// reason as `loop_filter`.
526+ pub(crate) cdef: CdefParams,
516 }527 }
517 528
518 /// The sequence and frame headers a picture of this size is coded under: one529 /// The sequence and frame headers a picture of this size is coded under: one
519-/// tile, one transform size per block, no in-loop filtering, no CDF adaptation530+/// tile, one transform size per block, no in-loop filter parameters yet
531+/// (`crate::encode::pick_and_apply_filters` fills the deblocking levels and
532+/// CDEF strengths in once the tile is coded), no CDF adaptation
520 /// and no tool the tile writer does not code.533 /// and no tool the tile writer does not code.
521 ///534 ///
522 /// # Errors535 /// # Errors
@@ -589,7 +602,12 @@ pub(crate) fn key_frame_headers_colour(
589 enable_order_hint: true,602 enable_order_hint: true,
590 order_hint_bits: 7,603 order_hint_bits: 7,
591 enable_superres: false,604 enable_superres: false,
592- enable_cdef: false,605+ // spec 5.9.19: with the sequence bit set every frame header carries
606+ // `cdef_params`. This encoder writes `cdef_bits == 0` -- one strength
607+ // pair for the whole frame, chosen by `crate::filter_search` -- so no
608+ // `cdef_idx` literal is coded in the tile and a frame that wants no
609+ // CDEF simply carries zero strengths.
610+ enable_cdef: true,
593 enable_restoration: false,611 enable_restoration: false,
594 seq_force_screen_content_tools: 0,612 seq_force_screen_content_tools: 0,
595 seq_force_integer_mv: 0,613 seq_force_integer_mv: 0,
@@ -3013,6 +3031,36 @@ pub(crate) fn encode_key_frame_inner(
3013 &superblocks,3031 &superblocks,
3014 tx_select,3032 tx_select,
3015 )?;3033 )?;
3034+ // spec 7.14 deblocking: pick this frame's `loop_filter_level` by handing
3035+ // the tile just coded back to the decoder under each candidate (see
3036+ // `crate::filter_search`), and keep the filtered picture that wins as
3037+ // the reconstruction -- what a decoder outputs, and what the next
3038+ // frame predicts from.
3039+ pick_and_apply_filters(
3040+ &mut header,
3041+ &mut luma,
3042+ &mut chroma,
3043+ [&picture_y8, &picture_u8, &picture_v8],
3044+ true,
3045+ |lf, cdef, h| {
3046+ crate::decode::decode_key_frame_tile(
3047+ &tile,
3048+ h.mi_cols,
3049+ h.mi_rows,
3050+ base_q_idx,
3051+ h.frame_width,
3052+ h.frame_height,
3053+ seq.enable_filter_intra,
3054+ cdef,
3055+ lf,
3056+ tx_select,
3057+ h.reduced_tx_set,
3058+ h.allow_screen_content_tools,
3059+ h.allow_intrabc,
3060+ fctx,
3061+ )
3062+ },
3063+ )?;
3016 let mut stream = temporal_delimiter();3064 let mut stream = temporal_delimiter();
3017 stream.extend_from_slice(&sequence_header_obu(&seq)?);3065 stream.extend_from_slice(&sequence_header_obu(&seq)?);
3018 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);3066 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
@@ -3034,9 +3082,58 @@ pub(crate) fn encode_key_frame_inner(
3034 mi_rows: header.mi_rows,3082 mi_rows: header.mi_rows,
3035 base_q_idx,3083 base_q_idx,
3036 tx_select,3084 tx_select,
3085+ loop_filter: header.loop_filter,
3086+ cdef: header.cdef,
3037 })3087 })
3038 }3088 }
3039 3089
3090+/// Chooses this frame's deblocking levels and CDEF strengths, writes them
3091+/// into `header` and
3092+/// replaces the frame's own region of the encoder's reconstruction with the
3093+/// filtered picture the decoder produced under them
3094+/// ([`crate::filter_search::pick_deblock`]).
3095+///
3096+/// `search == false` leaves the header at level 0 (deblocking off) and the
3097+/// reconstruction untouched: the caller's stream is one this crate's own
3098+/// decoder cannot read back, so there is nothing to search against.
3099+///
3100+/// # Errors
3101+/// The decoder's own error, when it refuses the tile the encoder just wrote
3102+/// -- that is an encoder defect, not a filter one, so it is propagated
3103+/// rather than swallowed into "no deblocking".
3104+fn pick_and_apply_filters(
3105+ header: &mut FrameHeader,
3106+ luma: &mut Plane<'_>,
3107+ chroma: &mut [Plane<'_>; 2],
3108+ source: [&[u8]; 3],
3109+ search: bool,
3110+ decode: impl Fn(&LoopFilterParams, &CdefParams, &FrameHeader) -> Result<Picture>,
3111+) -> Result<()> {
3112+ if !search {
3113+ return Ok(());
3114+ }
3115+ let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);
3116+ let hdr = header.clone();
3117+ // libaom `av1_pick_filter_level`'s sibling `av1_cdef_search`:
3118+ // `cdef_damping = 3 + (base_qindex >> 6)`, never searched.
3119+ let damping = 3 + (header.quantization.base_q_idx >> 6);
3120+ let (lf, cdef, filtered) = crate::filter_search::pick_filters(
3121+ |lf, cdef| decode(lf, cdef, &hdr),
3122+ source,
3123+ luma.width,
3124+ (fw, fh),
3125+ damping,
3126+ )?;
3127+ header.loop_filter = lf;
3128+ header.cdef = cdef;
3129+ let dec_cw = filtered.width.div_ceil(2);
3130+ let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));
3131+ crate::filter_search::splice(&mut luma.reconstruction, luma.width, &filtered.y, filtered.width, fw, fh);
3132+ crate::filter_search::splice(&mut chroma[0].reconstruction, chroma[0].width, &filtered.u, dec_cw, cw, ch);
3133+ crate::filter_search::splice(&mut chroma[1].reconstruction, chroma[1].width, &filtered.v, dec_cw, cw, ch);
3134+ Ok(())
3135+}
3136+
3040 /// `Y_MODE`'s size group (spec `Size_Group`) for a 32x32 block: the only3137 /// `Y_MODE`'s size group (spec `Size_Group`) for a 32x32 block: the only
3041 /// group an inter frame's intra branch codes (spec `inter_frame_mode_info`),3138 /// group an inter frame's intra branch codes (spec `inter_frame_mode_info`),
3042 /// since every block this crate's inter tile writer codes is 32x32.3139 /// since every block this crate's inter tile writer codes is 32x32.
@@ -4104,6 +4201,60 @@ pub(crate) fn encode_inter_frame(
4104 &blocks,4201 &blocks,
4105 tx_select,4202 tx_select,
4106 )?;4203 )?;
4204+ // Deblocking, as in `encode_key_frame_inner`: the decoder reconstructs
4205+ // this tile against the same single-slot reference this encoder predicted
4206+ // from, under each candidate level.
4207+ // The reference a DECODER holds is this frame's cropped size, not the
4208+ // encoder's padded coding surface -- `decode_inter_frame_tile` refuses a
4209+ // reference whose height is not the header's own `frame_height` (spec
4210+ // 7.9's compatible-size rule), and the chained-decode round trips prove
4211+ // the two predict identically.
4212+ let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);
4213+ let trial_ref = if (reference.width, reference.height) == (fw, fh) {
4214+ reference.clone()
4215+ } else {
4216+ Picture {
4217+ width: fw,
4218+ height: fh,
4219+ y: crop_plane(&reference.y, reference.width, fw, fh),
4220+ u: crop_plane(&reference.u, reference.width / 2, fw / 2, fh / 2),
4221+ v: crop_plane(&reference.v, reference.width / 2, fw / 2, fh / 2),
4222+ }
4223+ };
4224+ let mut refs: [Option<&Picture>; 8] = [None; 8];
4225+ refs[1] = Some(&trial_ref);
4226+ let refpix = crate::decode::RefPix::ready(refs);
4227+ pick_and_apply_filters(
4228+ &mut header,
4229+ &mut luma,
4230+ &mut chroma,
4231+ [&picture_y8, &picture_u8, &picture_v8],
4232+ // Merge of lane-av1filt with lane-av1tx2: the trial decoder takes
4233+ // this frame's own `tx_select`, so the search runs under inter
4234+ // `TxMode::Select` too (it used to skip and leave every inter frame
4235+ // unfiltered once Select became the default).
4236+ true,
4237+ |lf, cdef, h| {
4238+ crate::decode::decode_inter_frame_tile(
4239+ &tile,
4240+ h.mi_cols,
4241+ h.mi_rows,
4242+ base_q_idx,
4243+ h.frame_width,
4244+ h.frame_height,
4245+ &refpix,
4246+ cdef,
4247+ lf,
4248+ h.allow_high_precision_mv,
4249+ h.force_integer_mv,
4250+ Some(mc::InterpFilterKind::Regular),
4251+ seq.enable_dual_filter,
4252+ h.reference_select,
4253+ tx_select,
4254+ fctx,
4255+ )
4256+ },
4257+ )?;
4107 let mut stream = temporal_delimiter();4258 let mut stream = temporal_delimiter();
4108 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);4259 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
4109 4260
@@ -4124,6 +4275,8 @@ pub(crate) fn encode_inter_frame(
4124 mi_rows: header.mi_rows,4275 mi_rows: header.mi_rows,
4125 base_q_idx,4276 base_q_idx,
4126 tx_select,4277 tx_select,
4278+ loop_filter: header.loop_filter,
4279+ cdef: header.cdef,
4127 })4280 })
4128 }4281 }
4129 4282
@@ -4442,6 +4595,46 @@ mod tests {
4442 /// A picture with something of everything in it: a gradient, an edge, a4595 /// A picture with something of everything in it: a gradient, an edge, a
4443 /// ripple and a block of flat colour, none of them aligned to the block4596 /// ripple and a block of flat colour, none of them aligned to the block
4444 /// grid.4597 /// grid.
4598+ /// The in-loop filters actually FIRE and the stream still decodes to
4599+ /// exactly what the encoder kept as its reconstruction
4600+ /// (gate-blind-to-feature: a filter search that always answered "off"
4601+ /// would leave every other test just as green, and the BD gate that
4602+ /// would notice is `#[ignore]`d).
4603+ ///
4604+ /// Run:
4605+ /// cargo test -p ec-av1 --release --lib -- \
4606+ /// encode::tests::the_filter_search_picks_real_filters
4607+ #[test]
4608+ fn the_filter_search_picks_real_filters() {
4609+ let fctx = &crate::decode::FrameCtx::new();
4610+ let pictures: Vec<_> = (0..3).map(|i| panned_test_card(128, 128, i * 3)).collect();
4611+ let encoded = encode_sequence_with_ctx(&pictures, 120, 0.5, fctx).unwrap();
4612+ let fired = encoded
4613+ .frames
4614+ .iter()
4615+ .filter(|f| f.loop_filter.level[0] > 0 || f.cdef.y_pri_strength[0] > 0)
4616+ .count();
4617+ assert!(
4618+ fired > 0,
4619+ "no frame of this sequence chose any in-loop filtering: {:?}",
4620+ encoded
4621+ .frames
4622+ .iter()
4623+ .map(|f| (f.loop_filter.level, f.cdef.y_pri_strength[0]))
4624+ .collect::<Vec<_>>()
4625+ );
4626+ // The reconstruction the encoder predicts from is the FILTERED one,
4627+ // and it is what a decoder of the stream produces -- byte for byte,
4628+ // frame for frame.
4629+ let decoded = crate::stream::decode_stream(&encoded.stream).unwrap();
4630+ assert_eq!(decoded.len(), encoded.frames.len());
4631+ for (i, (dec, enc)) in decoded.iter().zip(&encoded.frames).enumerate() {
4632+ assert_eq!(dec.y, enc.reconstruction.y, "frame {i} luma");
4633+ assert_eq!(dec.u, enc.reconstruction.u, "frame {i} U");
4634+ assert_eq!(dec.v, enc.reconstruction.v, "frame {i} V");
4635+ }
4636+ }
4637+
4445 fn test_card(width: usize, height: usize) -> Picture {4638 fn test_card(width: usize, height: usize) -> Picture {
4446 let mut picture = Picture::grey(width, height);4639 let mut picture = Picture::grey(width, height);
4447 for y in 0..height {4640 for y in 0..height {
@@ -6888,15 +7081,30 @@ mod tests {
6888 /// ours: `base_q_idx {60,90,120,150}`. Every PSNR is all-plane, on7081 /// ours: `base_q_idx {60,90,120,150}`. Every PSNR is all-plane, on
6889 /// ffmpeg-decoded frames of each encoder's own stream.7082 /// ffmpeg-decoded frames of each encoder's own stream.
6890 ///7083 ///
6891- /// Measured 2026-09-06 after the inter partition search (lane-av1rd2),7084+ /// Measured 2026-09-06 after the in-loop filters (lane-av1filt: per-frame
6892- /// 12 frames, this box (wall = the four encodes of that ladder7085+ /// deblocking levels and CDEF strengths, both chosen by re-decoding the
6893- /// together):7086+ /// coded tile -- `crate::filter_search`), 12 frames, this box (wall = the
7087+ /// four encodes of that ladder together):
6894 ///7088 ///
6895 /// | clip | ours (q 150/120/90/60) | BD-rate vs libaom | vs rav1e | wall ours:aom:rav1e |7089 /// | clip | ours (q 150/120/90/60) | BD-rate vs libaom | vs rav1e | wall ours:aom:rav1e |
6896 /// |---|---|---|---|---|7090 /// |---|---|---|---|---|
6897- /// | 1080p fixture | 41.16 dB/22349 B .. 49.97 dB/83178 B | +234.0% | +171.9% | 9.8s:1.1s:2.6s |7091+ /// | 1080p fixture | 42.11 dB/17774 B .. 50.99 dB/76838 B | +143.6% | +94.0% | 9.2s:1.1s:2.6s |
6898- /// | 2160p fixture | 42.01 dB/14687 B .. 50.82 dB/52415 B | +260.3% | +203.2% | 9.3s:1.0s:2.2s |7092+ /// | 2160p fixture | 42.84 dB/12480 B .. 51.43 dB/46557 B | +179.5% | +128.8% | 8.6s:1.0s:2.2s |
6899- /// | screen capture | 37.49 dB/12797 B .. 46.19 dB/50643 B | +318.5% | +155.3% | 9.1s:1.0s:2.1s |7093+ /// | screen capture | 39.76 dB/9536 B .. 48.87 dB/29189 B | +88.0% | +21.5% | 7.2s:1.0s:2.1s |
7094+ ///
7095+ /// The three steps of that lane, same recipe (vs libaom, then vs rav1e):
7096+ ///
7097+ /// | step | 1080p | 2160p | screen |
7098+ /// |---|---|---|---|
7099+ /// | no in-loop filter | +234.0 / +171.9 | +260.3 / +203.2 | +318.5 / +155.3 |
7100+ /// | + deblocking | +198.2 / +143.1 | +218.1 / +162.4 | +136.9 / +52.7 |
7101+ /// | + CDEF | +143.6 / +94.0 | +179.5 / +128.8 | +88.0 / +21.5 |
7102+ ///
7103+ /// Loop restoration is NOT in yet: it is the one filter whose parameters
7104+ /// are per restoration UNIT inside the tile payload, so it needs both
7105+ /// tile writers to code `lr` syntax and an encoder-visible post-CDEF
7106+ /// buffer to solve against -- neither of which this frame-header-level
7107+ /// search reaches.
6900 ///7108 ///
6901 /// The baseline it replaced, before an inter frame's blocks chose their7109 /// The baseline it replaced, before an inter frame's blocks chose their
6902 /// own partition, was +501.4/+504.4/+440.9 against libaom and7110 /// own partition, was +501.4/+504.4/+440.9 against libaom and
@@ -6992,6 +7200,24 @@ mod tests {
6992 whole16 + split16,7200 whole16 + split16,
6993 100.0 * split16 as f64 / (whole16 + split16).max(1) as f647201 100.0 * split16 as f64 / (whole16 + split16).max(1) as f64
6994 );7202 );
7203+ // The deblocking level each of this clip's frames chose
7204+ // (lane-av1filt): 0 everywhere would mean the filter never fires.
7205+ let levels = crate::filter_search::take_chosen_levels();
7206+ type Chosen = ((u8, u8), (u8, u8), (u8, u8));
7207+ let mean = |f: fn(&Chosen) -> u8| {
7208+ levels.iter().map(|l| f(l) as f64).sum::<f64>() / levels.len().max(1) as f64
7209+ };
7210+ eprintln!(
7211+ "{name}: over {} frames -- deblock luma mean {:.1} chroma {:.1}; \
7212+ cdef luma pri {:.1}/sec {:.1}, chroma pri {:.1}/sec {:.1}",
7213+ levels.len(),
7214+ mean(|l| l.0.0),
7215+ mean(|l| l.0.1),
7216+ mean(|l| l.1.0),
7217+ mean(|l| l.1.1),
7218+ mean(|l| l.2.0),
7219+ mean(|l| l.2.1),
7220+ );
6995 // Which chroma modes the search actually wins with, against the7221 // Which chroma modes the search actually wins with, against the
6996 // unconditional DC_PRED that was the only outcome before7222 // unconditional DC_PRED that was the only outcome before
6997 // (gate-blind-to-feature).7223 // (gate-blind-to-feature).
crates/ec-av1/src/filter_search.rsadded+207 -0
@@ -0,0 +1,207 @@
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::{CdefParams, 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+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+
43+/// Squared error between a decoded plane and the source it was coded from,
44+/// over the frame's own cropped `w x h` (the two planes have different
45+/// strides: the source is the encoder's padded coding surface).
46+fn plane_sse(dec: &[u16], dec_w: usize, src: &[u8], src_w: usize, w: usize, h: usize) -> u64 {
47+ let mut sse = 0u64;
48+ for row in 0..h {
49+ let (d, s) = (&dec[row * dec_w..][..w], &src[row * src_w..][..w]);
50+ for (&a, &b) in d.iter().zip(s) {
51+ let diff = i64::from(a) - i64::from(b);
52+ sse += (diff * diff) as u64;
53+ }
54+ }
55+ sse
56+}
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+
79+/// One evaluated candidate: the decoded picture and its luma / chroma error.
80+struct Trial {
81+ cand: Cand,
82+ picture: Picture,
83+ sse_y: u64,
84+ sse_uv: u64,
85+}
86+
87+/// Picks this frame's deblocking levels and CDEF strengths and hands back
88+/// the filtered reconstruction that goes with the winner.
89+///
90+/// `decode` reconstructs this frame's already-coded tile under the candidate
91+/// parameters; `source` is the encoder's padded (luma, U, V) coding surface
92+/// with luma stride `src_w`, `(fw, fh)` the frame header's own true size,
93+/// which is what `decode` crops to, and `damping` the CDEF damping the
94+/// caller's header carries.
95+///
96+/// A coordinate search, in the decoder's own filter order and each stage on
97+/// the plane it moves: deblocking luma (`level[0..2]`, kept equal -- nothing
98+/// here filters vertical and horizontal edges differently), deblocking
99+/// chroma (`level[2..4]`, a real choice of its own: flat chroma has no edges
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.
104+///
105+/// # Errors
106+/// Whatever `decode` returns: a stream this crate's own decoder refuses is
107+/// a caller's cue to keep its unfiltered reconstruction.
108+pub(crate) fn pick_filters(
109+ decode: impl Fn(&LoopFilterParams, &CdefParams) -> Result<Picture>,
110+ source: [&[u8]; 3],
111+ src_w: usize,
112+ (fw, fh): (usize, usize),
113+ damping: u8,
114+) -> Result<(LoopFilterParams, CdefParams, Picture)> {
115+ let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));
116+ let mut trials: Vec<Trial> = Vec::new();
117+ let eval = |cand: Cand, trials: &mut Vec<Trial>| -> Result<usize> {
118+ if let Some(i) = trials.iter().position(|t| t.cand == cand) {
119+ return Ok(i);
120+ }
121+ let picture = decode(&loop_filter(cand), &cdef(cand, damping))?;
122+ let dec_cw = picture.width.div_ceil(2);
123+ let sse_y = plane_sse(&picture.y, picture.width, source[0], src_w, fw, fh);
124+ let sse_uv = plane_sse(&picture.u, dec_cw, source[1], src_w / 2, cw, ch)
125+ + plane_sse(&picture.v, dec_cw, source[2], src_w / 2, cw, ch);
126+ trials.push(Trial { cand, picture, sse_y, sse_uv });
127+ Ok(trials.len() - 1)
128+ };
129+ // One stage of the coordinate search: try `values` in the slot `set`
130+ // moves and keep the one with the lowest error `sse` reads.
131+ let stage = |best: &mut Cand,
132+ values: &[u8],
133+ set: fn(&mut Cand, u8),
134+ sse: fn(&Trial) -> u64,
135+ trials: &mut Vec<Trial>|
136+ -> Result<()> {
137+ let mut winner = *best;
138+ let mut lowest = u64::MAX;
139+ for &v in values {
140+ let mut cand = *best;
141+ set(&mut cand, v);
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(())
150+ };
151+
152+ let mut best = Cand { lf: (0, 0), y: (0, 0), uv: (0, 0) };
153+ // Deblocking luma: the coarse ladder, then +-1/+-2 around its winner.
154+ stage(&mut best, &COARSE, |c, v| c.lf = (v, v), |t| t.sse_y, &mut trials)?;
155+ let refine: Vec<u8> = [-2i32, -1, 1, 2]
156+ .iter()
157+ .filter_map(|d| u8::try_from(i32::from(best.lf.0) + d).ok())
158+ .filter(|&l| l <= 63)
159+ .collect();
160+ stage(&mut best, &refine, |c, v| c.lf = (v, v), |t| t.sse_y, &mut trials)?;
161+ // Deblocking chroma, three points around the luma winner.
162+ let chroma_levels = [0, best.lf.0 / 2, best.lf.0];
163+ stage(&mut best, &chroma_levels, |c, v| c.lf.1 = v, |t| t.sse_uv, &mut trials)?;
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)?;
169+
170+ CHOSEN.with(|c| c.borrow_mut().push(best));
171+ let win = trials
172+ .into_iter()
173+ .find(|t| t.cand == best)
174+ .expect("the winning candidate was evaluated");
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 {
180+ LoopFilterParams {
181+ level: [cand.lf.0, cand.lf.0, cand.lf.1, cand.lf.1],
182+ ..LoopFilterParams::default()
183+ }
184+}
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
195+}
196+
197+/// Writes the frame's own (cropped) region of `filtered` back over the
198+/// encoder's padded reconstruction planes, leaving whatever lies past the
199+/// frame edge untouched -- those columns/rows are the encoder's private
200+/// coding surface, never anything a decoder outputs.
201+pub(crate) fn splice(dst: &mut [u8], dst_w: usize, src: &[u16], src_w: usize, w: usize, h: usize) {
202+ for row in 0..h {
203+ for col in 0..w {
204+ dst[row * dst_w + col] = src[row * src_w + col] as u8;
205+ }
206+ }
207+}
crates/ec-av1/src/lib.rsmodified+1 -0
@@ -32,6 +32,7 @@ pub mod encode;
32 pub mod encoder;32 pub mod encoder;
33 mod envflags;33 mod envflags;
34 mod film_grain;34 mod film_grain;
35+mod filter_search;
35 pub mod frame;36 pub mod frame;
36 mod gate_coverage;37 mod gate_coverage;
37 mod hits;38 mod hits;
crates/ec-av1/src/stream.rsmodified+2 -2
@@ -2994,8 +2994,8 @@ 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- &ec_av1_syntax::LoopFilterParams::default(),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`.
3001 true,3001 true,