merge main a6649c4e (lane-av1filt): thread this frame's start_cdfs into the filter search's trial decode
Browse files at this commit5 changed files +466 -26
- crates/ec-av1/src/decode.rs +16 -14
- crates/ec-av1/src/encode.rs +240 -10
- crates/ec-av1/src/filter_search.rs +207 -0
- crates/ec-av1/src/lib.rs +1 -0
- crates/ec-av1/src/stream.rs +2 -2
crates/ec-av1/src/decode.rsmodified+16 -14
| @@ -36628,6 +36628,8 @@ mod tests { | ||
| 36628 | 36628 | mi_rows, |
| 36629 | 36629 | base_q_idx, |
| 36630 | 36630 | tx_select, |
| 36631 | + loop_filter, | |
| 36632 | + cdef, | |
| 36631 | 36633 | .. |
| 36632 | 36634 | }: Encoded = crate::encode::encode_key_frame_with_modes_with_ctx(&picture, 40, 0.0, modes, fctx).unwrap(); |
| 36633 | 36635 | let decoded = decode_key_frame_tile( |
| @@ -36638,8 +36640,8 @@ mod tests { | ||
| 36638 | 36640 | w as u32, |
| 36639 | 36641 | h as u32, |
| 36640 | 36642 | false, |
| 36641 | - &CdefParams::default(), | |
| 36642 | - &LoopFilterParams::default(), | |
| 36643 | + &cdef, | |
| 36644 | + &loop_filter, | |
| 36643 | 36645 | tx_select, |
| 36644 | 36646 | true, |
| 36645 | 36647 | false, |
| @@ -37006,8 +37008,8 @@ mod tests { | ||
| 37006 | 37008 | coded_w, |
| 37007 | 37009 | coded_h, |
| 37008 | 37010 | false, |
| 37009 | - &CdefParams::default(), | |
| 37010 | - &LoopFilterParams::default(), | |
| 37011 | + &encoded.cdef, | |
| 37012 | + &encoded.loop_filter, | |
| 37011 | 37013 | encoded.tx_select, |
| 37012 | 37014 | true, |
| 37013 | 37015 | false, |
| @@ -37049,8 +37051,8 @@ mod tests { | ||
| 37049 | 37051 | width as u32, |
| 37050 | 37052 | height as u32, |
| 37051 | 37053 | false, |
| 37052 | - &CdefParams::default(), | |
| 37053 | - &LoopFilterParams::default(), | |
| 37054 | + &encoded.cdef, | |
| 37055 | + &encoded.loop_filter, | |
| 37054 | 37056 | tx_select, |
| 37055 | 37057 | true, |
| 37056 | 37058 | false, |
| @@ -37133,8 +37135,8 @@ mod tests { | ||
| 37133 | 37135 | width as u32, |
| 37134 | 37136 | height as u32, |
| 37135 | 37137 | false, |
| 37136 | - &CdefParams::default(), | |
| 37137 | - &LoopFilterParams::default(), | |
| 37138 | + &key.cdef, | |
| 37139 | + &key.loop_filter, | |
| 37138 | 37140 | key.tx_select, |
| 37139 | 37141 | true, |
| 37140 | 37142 | false, |
| @@ -37163,8 +37165,8 @@ mod tests { | ||
| 37163 | 37165 | width as u32, |
| 37164 | 37166 | height as u32, |
| 37165 | 37167 | &last_only(&reference), |
| 37166 | - &CdefParams::default(), | |
| 37167 | - &LoopFilterParams::default(), | |
| 37168 | + &frame.cdef, | |
| 37169 | + &frame.loop_filter, | |
| 37168 | 37170 | false, |
| 37169 | 37171 | false, |
| 37170 | 37172 | Some(mc::InterpFilterKind::Regular), |
| @@ -37456,8 +37458,8 @@ mod tests { | ||
| 37456 | 37458 | coded_w, |
| 37457 | 37459 | coded_h, |
| 37458 | 37460 | false, |
| 37459 | - &CdefParams::default(), | |
| 37460 | - &LoopFilterParams::default(), | |
| 37461 | + &key.cdef, | |
| 37462 | + &key.loop_filter, | |
| 37461 | 37463 | key.tx_select, |
| 37462 | 37464 | true, |
| 37463 | 37465 | false, |
| @@ -37475,8 +37477,8 @@ mod tests { | ||
| 37475 | 37477 | coded_w, |
| 37476 | 37478 | coded_h, |
| 37477 | 37479 | &last_only(&reference), |
| 37478 | - &CdefParams::default(), | |
| 37479 | - &LoopFilterParams::default(), | |
| 37480 | + &frame.cdef, | |
| 37481 | + &frame.loop_filter, | |
| 37480 | 37482 | false, |
| 37481 | 37483 | false, |
| 37482 | 37484 | Some(mc::InterpFilterKind::Regular), |
crates/ec-av1/src/encode.rsmodified+240 -10
| @@ -19,8 +19,8 @@ | ||
| 19 | 19 | use crate::decode::WithRef; |
| 20 | 20 | use ec_av1_syntax::sequence::{ColorConfig, OperatingPoint, SequenceHeader}; |
| 21 | 21 | 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, | |
| 24 | 24 | }; |
| 25 | 25 | use ec_core::{Error, Result}; |
| 26 | 26 | |
| @@ -479,6 +479,8 @@ pub(crate) fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> En | ||
| 479 | 479 | tx_select: encoded.tx_select, |
| 480 | 480 | start_cdfs: encoded.start_cdfs.clone(), |
| 481 | 481 | next_cdfs: encoded.next_cdfs.clone(), |
| 482 | + loop_filter: encoded.loop_filter, | |
| 483 | + cdef: encoded.cdef, | |
| 482 | 484 | } |
| 483 | 485 | } |
| 484 | 486 | |
| @@ -538,10 +540,21 @@ pub struct Encoded { | ||
| 538 | 540 | /// counts reset when `disable_frame_end_update_cdf` is off, and what it |
| 539 | 541 | /// started from when it is on. |
| 540 | 542 | pub(crate) next_cdfs: CdfSnapshot, |
| 543 | + /// This frame header's chosen deblocking parameters | |
| 544 | + /// ([`crate::filter_search::pick_deblock`]) — `reconstruction` is the | |
| 545 | + /// picture the decoder produces UNDER them, so a test that decodes | |
| 546 | + /// `tile` directly must pass these along, exactly as it must `tx_select` | |
| 547 | + /// (class: test asserts against a stale header). | |
| 548 | + pub(crate) loop_filter: LoopFilterParams, | |
| 549 | + /// This frame header's chosen CDEF parameters, threaded for the same | |
| 550 | + /// reason as `loop_filter`. | |
| 551 | + pub(crate) cdef: CdefParams, | |
| 541 | 552 | } |
| 542 | 553 | |
| 543 | 554 | /// The sequence and frame headers a picture of this size is coded under: one |
| 544 | -/// tile, one transform size per block, no in-loop filtering, no CDF adaptation | |
| 555 | +/// tile, one transform size per block, no in-loop filter parameters yet | |
| 556 | +/// (`crate::encode::pick_and_apply_filters` fills the deblocking levels and | |
| 557 | +/// CDEF strengths in once the tile is coded), no CDF adaptation | |
| 545 | 558 | /// and no tool the tile writer does not code. |
| 546 | 559 | /// |
| 547 | 560 | /// # Errors |
| @@ -614,7 +627,12 @@ pub(crate) fn key_frame_headers_colour( | ||
| 614 | 627 | enable_order_hint: true, |
| 615 | 628 | order_hint_bits: 7, |
| 616 | 629 | enable_superres: false, |
| 617 | - enable_cdef: false, | |
| 630 | + // spec 5.9.19: with the sequence bit set every frame header carries | |
| 631 | + // `cdef_params`. This encoder writes `cdef_bits == 0` -- one strength | |
| 632 | + // pair for the whole frame, chosen by `crate::filter_search` -- so no | |
| 633 | + // `cdef_idx` literal is coded in the tile and a frame that wants no | |
| 634 | + // CDEF simply carries zero strengths. | |
| 635 | + enable_cdef: true, | |
| 618 | 636 | enable_restoration: false, |
| 619 | 637 | seq_force_screen_content_tools: 0, |
| 620 | 638 | seq_force_integer_mv: 0, |
| @@ -3051,6 +3069,36 @@ pub(crate) fn encode_key_frame_inner( | ||
| 3051 | 3069 | tx_select, |
| 3052 | 3070 | &mut cdfs, |
| 3053 | 3071 | )?; |
| 3072 | + // spec 7.14 deblocking: pick this frame's `loop_filter_level` by handing | |
| 3073 | + // the tile just coded back to the decoder under each candidate (see | |
| 3074 | + // `crate::filter_search`), and keep the filtered picture that wins as | |
| 3075 | + // the reconstruction -- what a decoder outputs, and what the next | |
| 3076 | + // frame predicts from. | |
| 3077 | + pick_and_apply_filters( | |
| 3078 | + &mut header, | |
| 3079 | + &mut luma, | |
| 3080 | + &mut chroma, | |
| 3081 | + [&picture_y8, &picture_u8, &picture_v8], | |
| 3082 | + true, | |
| 3083 | + |lf, cdef, h| { | |
| 3084 | + crate::decode::decode_key_frame_tile( | |
| 3085 | + &tile, | |
| 3086 | + h.mi_cols, | |
| 3087 | + h.mi_rows, | |
| 3088 | + base_q_idx, | |
| 3089 | + h.frame_width, | |
| 3090 | + h.frame_height, | |
| 3091 | + seq.enable_filter_intra, | |
| 3092 | + cdef, | |
| 3093 | + lf, | |
| 3094 | + tx_select, | |
| 3095 | + h.reduced_tx_set, | |
| 3096 | + h.allow_screen_content_tools, | |
| 3097 | + h.allow_intrabc, | |
| 3098 | + fctx, | |
| 3099 | + ) | |
| 3100 | + }, | |
| 3101 | + )?; | |
| 3054 | 3102 | let mut stream = temporal_delimiter(); |
| 3055 | 3103 | stream.extend_from_slice(&sequence_header_obu(&seq)?); |
| 3056 | 3104 | stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?); |
| @@ -3074,9 +3122,58 @@ pub(crate) fn encode_key_frame_inner( | ||
| 3074 | 3122 | tx_select, |
| 3075 | 3123 | next_cdfs: start_cdfs.clone(), |
| 3076 | 3124 | start_cdfs, |
| 3125 | + loop_filter: header.loop_filter, | |
| 3126 | + cdef: header.cdef, | |
| 3077 | 3127 | }) |
| 3078 | 3128 | } |
| 3079 | 3129 | |
| 3130 | +/// Chooses this frame's deblocking levels and CDEF strengths, writes them | |
| 3131 | +/// into `header` and | |
| 3132 | +/// replaces the frame's own region of the encoder's reconstruction with the | |
| 3133 | +/// filtered picture the decoder produced under them | |
| 3134 | +/// ([`crate::filter_search::pick_deblock`]). | |
| 3135 | +/// | |
| 3136 | +/// `search == false` leaves the header at level 0 (deblocking off) and the | |
| 3137 | +/// reconstruction untouched: the caller's stream is one this crate's own | |
| 3138 | +/// decoder cannot read back, so there is nothing to search against. | |
| 3139 | +/// | |
| 3140 | +/// # Errors | |
| 3141 | +/// The decoder's own error, when it refuses the tile the encoder just wrote | |
| 3142 | +/// -- that is an encoder defect, not a filter one, so it is propagated | |
| 3143 | +/// rather than swallowed into "no deblocking". | |
| 3144 | +fn pick_and_apply_filters( | |
| 3145 | + header: &mut FrameHeader, | |
| 3146 | + luma: &mut Plane<'_>, | |
| 3147 | + chroma: &mut [Plane<'_>; 2], | |
| 3148 | + source: [&[u8]; 3], | |
| 3149 | + search: bool, | |
| 3150 | + decode: impl Fn(&LoopFilterParams, &CdefParams, &FrameHeader) -> Result<Picture>, | |
| 3151 | +) -> Result<()> { | |
| 3152 | + if !search { | |
| 3153 | + return Ok(()); | |
| 3154 | + } | |
| 3155 | + let (fw, fh) = (header.frame_width as usize, header.frame_height as usize); | |
| 3156 | + let hdr = header.clone(); | |
| 3157 | + // libaom `av1_pick_filter_level`'s sibling `av1_cdef_search`: | |
| 3158 | + // `cdef_damping = 3 + (base_qindex >> 6)`, never searched. | |
| 3159 | + let damping = 3 + (header.quantization.base_q_idx >> 6); | |
| 3160 | + let (lf, cdef, filtered) = crate::filter_search::pick_filters( | |
| 3161 | + |lf, cdef| decode(lf, cdef, &hdr), | |
| 3162 | + source, | |
| 3163 | + luma.width, | |
| 3164 | + (fw, fh), | |
| 3165 | + damping, | |
| 3166 | + )?; | |
| 3167 | + header.loop_filter = lf; | |
| 3168 | + header.cdef = cdef; | |
| 3169 | + let dec_cw = filtered.width.div_ceil(2); | |
| 3170 | + let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2)); | |
| 3171 | + crate::filter_search::splice(&mut luma.reconstruction, luma.width, &filtered.y, filtered.width, fw, fh); | |
| 3172 | + crate::filter_search::splice(&mut chroma[0].reconstruction, chroma[0].width, &filtered.u, dec_cw, cw, ch); | |
| 3173 | + crate::filter_search::splice(&mut chroma[1].reconstruction, chroma[1].width, &filtered.v, dec_cw, cw, ch); | |
| 3174 | + Ok(()) | |
| 3175 | +} | |
| 3176 | + | |
| 3080 | 3177 | /// `Y_MODE`'s size group (spec `Size_Group`) for a 32x32 block: the only |
| 3081 | 3178 | /// group an inter frame's intra branch codes (spec `inter_frame_mode_info`), |
| 3082 | 3179 | /// since every block this crate's inter tile writer codes is 32x32. |
| @@ -4143,6 +4240,64 @@ pub(crate) fn encode_inter_frame( | ||
| 4143 | 4240 | tx_select, |
| 4144 | 4241 | &mut cdfs, |
| 4145 | 4242 | )?; |
| 4243 | + // Deblocking, as in `encode_key_frame_inner`: the decoder reconstructs | |
| 4244 | + // this tile against the same single-slot reference this encoder predicted | |
| 4245 | + // from, under each candidate level. | |
| 4246 | + // The reference a DECODER holds is this frame's cropped size, not the | |
| 4247 | + // encoder's padded coding surface -- `decode_inter_frame_tile` refuses a | |
| 4248 | + // reference whose height is not the header's own `frame_height` (spec | |
| 4249 | + // 7.9's compatible-size rule), and the chained-decode round trips prove | |
| 4250 | + // the two predict identically. | |
| 4251 | + let (fw, fh) = (header.frame_width as usize, header.frame_height as usize); | |
| 4252 | + let trial_ref = if (reference.width, reference.height) == (fw, fh) { | |
| 4253 | + reference.clone() | |
| 4254 | + } else { | |
| 4255 | + Picture { | |
| 4256 | + width: fw, | |
| 4257 | + height: fh, | |
| 4258 | + y: crop_plane(&reference.y, reference.width, fw, fh), | |
| 4259 | + u: crop_plane(&reference.u, reference.width / 2, fw / 2, fh / 2), | |
| 4260 | + v: crop_plane(&reference.v, reference.width / 2, fw / 2, fh / 2), | |
| 4261 | + } | |
| 4262 | + }; | |
| 4263 | + let mut refs: [Option<&Picture>; 8] = [None; 8]; | |
| 4264 | + refs[1] = Some(&trial_ref); | |
| 4265 | + let refpix = crate::decode::RefPix::ready(refs); | |
| 4266 | + pick_and_apply_filters( | |
| 4267 | + &mut header, | |
| 4268 | + &mut luma, | |
| 4269 | + &mut chroma, | |
| 4270 | + [&picture_y8, &picture_u8, &picture_v8], | |
| 4271 | + // Merge of lane-av1filt with lane-av1tx2: the trial decoder takes | |
| 4272 | + // this frame's own `tx_select`, so the search runs under inter | |
| 4273 | + // `TxMode::Select` too (it used to skip and leave every inter frame | |
| 4274 | + // unfiltered once Select became the default). | |
| 4275 | + true, | |
| 4276 | + |lf, cdef, h| { | |
| 4277 | + crate::decode::decode_inter_frame_tile( | |
| 4278 | + &tile, | |
| 4279 | + h.mi_cols, | |
| 4280 | + h.mi_rows, | |
| 4281 | + base_q_idx, | |
| 4282 | + h.frame_width, | |
| 4283 | + h.frame_height, | |
| 4284 | + &refpix, | |
| 4285 | + cdef, | |
| 4286 | + lf, | |
| 4287 | + h.allow_high_precision_mv, | |
| 4288 | + h.force_integer_mv, | |
| 4289 | + Some(mc::InterpFilterKind::Regular), | |
| 4290 | + seq.enable_dual_filter, | |
| 4291 | + h.reference_select, | |
| 4292 | + tx_select, | |
| 4293 | + // The trial decode re-reads the tile the writer just wrote, | |
| 4294 | + // so it starts from the same tables the writer did (this | |
| 4295 | + // frame's `start_cdfs`), not from the defaults. | |
| 4296 | + Some(start_cdfs.0.clone()), | |
| 4297 | + fctx, | |
| 4298 | + ) | |
| 4299 | + }, | |
| 4300 | + )?; | |
| 4146 | 4301 | cdfs.reset_counts(); |
| 4147 | 4302 | let next_cdfs = CdfSnapshot(cdfs); |
| 4148 | 4303 | let mut stream = temporal_delimiter(); |
| @@ -4167,6 +4322,8 @@ pub(crate) fn encode_inter_frame( | ||
| 4167 | 4322 | tx_select, |
| 4168 | 4323 | start_cdfs, |
| 4169 | 4324 | next_cdfs, |
| 4325 | + loop_filter: header.loop_filter, | |
| 4326 | + cdef: header.cdef, | |
| 4170 | 4327 | }) |
| 4171 | 4328 | } |
| 4172 | 4329 | |
| @@ -4488,6 +4645,46 @@ mod tests { | ||
| 4488 | 4645 | /// A picture with something of everything in it: a gradient, an edge, a |
| 4489 | 4646 | /// ripple and a block of flat colour, none of them aligned to the block |
| 4490 | 4647 | /// grid. |
| 4648 | + /// The in-loop filters actually FIRE and the stream still decodes to | |
| 4649 | + /// exactly what the encoder kept as its reconstruction | |
| 4650 | + /// (gate-blind-to-feature: a filter search that always answered "off" | |
| 4651 | + /// would leave every other test just as green, and the BD gate that | |
| 4652 | + /// would notice is `#[ignore]`d). | |
| 4653 | + /// | |
| 4654 | + /// Run: | |
| 4655 | + /// cargo test -p ec-av1 --release --lib -- \ | |
| 4656 | + /// encode::tests::the_filter_search_picks_real_filters | |
| 4657 | + #[test] | |
| 4658 | + fn the_filter_search_picks_real_filters() { | |
| 4659 | + let fctx = &crate::decode::FrameCtx::new(); | |
| 4660 | + let pictures: Vec<_> = (0..3).map(|i| panned_test_card(128, 128, i * 3)).collect(); | |
| 4661 | + let encoded = encode_sequence_with_ctx(&pictures, 120, 0.5, fctx).unwrap(); | |
| 4662 | + let fired = encoded | |
| 4663 | + .frames | |
| 4664 | + .iter() | |
| 4665 | + .filter(|f| f.loop_filter.level[0] > 0 || f.cdef.y_pri_strength[0] > 0) | |
| 4666 | + .count(); | |
| 4667 | + assert!( | |
| 4668 | + fired > 0, | |
| 4669 | + "no frame of this sequence chose any in-loop filtering: {:?}", | |
| 4670 | + encoded | |
| 4671 | + .frames | |
| 4672 | + .iter() | |
| 4673 | + .map(|f| (f.loop_filter.level, f.cdef.y_pri_strength[0])) | |
| 4674 | + .collect::<Vec<_>>() | |
| 4675 | + ); | |
| 4676 | + // The reconstruction the encoder predicts from is the FILTERED one, | |
| 4677 | + // and it is what a decoder of the stream produces -- byte for byte, | |
| 4678 | + // frame for frame. | |
| 4679 | + let decoded = crate::stream::decode_stream(&encoded.stream).unwrap(); | |
| 4680 | + assert_eq!(decoded.len(), encoded.frames.len()); | |
| 4681 | + for (i, (dec, enc)) in decoded.iter().zip(&encoded.frames).enumerate() { | |
| 4682 | + assert_eq!(dec.y, enc.reconstruction.y, "frame {i} luma"); | |
| 4683 | + assert_eq!(dec.u, enc.reconstruction.u, "frame {i} U"); | |
| 4684 | + assert_eq!(dec.v, enc.reconstruction.v, "frame {i} V"); | |
| 4685 | + } | |
| 4686 | + } | |
| 4687 | + | |
| 4491 | 4688 | fn test_card(width: usize, height: usize) -> Picture { |
| 4492 | 4689 | let mut picture = Picture::grey(width, height); |
| 4493 | 4690 | for y in 0..height { |
| @@ -6936,15 +7133,30 @@ mod tests { | ||
| 6936 | 7133 | /// ours: `base_q_idx {60,90,120,150}`. Every PSNR is all-plane, on |
| 6937 | 7134 | /// ffmpeg-decoded frames of each encoder's own stream. |
| 6938 | 7135 | /// |
| 6939 | - /// Measured 2026-09-06 after the inter partition search (lane-av1rd2), | |
| 6940 | - /// 12 frames, this box (wall = the four encodes of that ladder | |
| 6941 | - /// together): | |
| 7136 | + /// Measured 2026-09-06 after the in-loop filters (lane-av1filt: per-frame | |
| 7137 | + /// deblocking levels and CDEF strengths, both chosen by re-decoding the | |
| 7138 | + /// coded tile -- `crate::filter_search`), 12 frames, this box (wall = the | |
| 7139 | + /// four encodes of that ladder together): | |
| 6942 | 7140 | /// |
| 6943 | 7141 | /// | clip | ours (q 150/120/90/60) | BD-rate vs libaom | vs rav1e | wall ours:aom:rav1e | |
| 6944 | 7142 | /// |---|---|---|---|---| |
| 6945 | - /// | 1080p fixture | 41.16 dB/22349 B .. 49.97 dB/83178 B | +234.0% | +171.9% | 9.8s:1.1s:2.6s | | |
| 6946 | - /// | 2160p fixture | 42.01 dB/14687 B .. 50.82 dB/52415 B | +260.3% | +203.2% | 9.3s:1.0s:2.2s | | |
| 6947 | - /// | screen capture | 37.49 dB/12797 B .. 46.19 dB/50643 B | +318.5% | +155.3% | 9.1s:1.0s:2.1s | | |
| 7143 | + /// | 1080p fixture | 42.11 dB/17774 B .. 50.99 dB/76838 B | +143.6% | +94.0% | 9.2s:1.1s:2.6s | | |
| 7144 | + /// | 2160p fixture | 42.84 dB/12480 B .. 51.43 dB/46557 B | +179.5% | +128.8% | 8.6s:1.0s:2.2s | | |
| 7145 | + /// | screen capture | 39.76 dB/9536 B .. 48.87 dB/29189 B | +88.0% | +21.5% | 7.2s:1.0s:2.1s | | |
| 7146 | + /// | |
| 7147 | + /// The three steps of that lane, same recipe (vs libaom, then vs rav1e): | |
| 7148 | + /// | |
| 7149 | + /// | step | 1080p | 2160p | screen | | |
| 7150 | + /// |---|---|---|---| | |
| 7151 | + /// | no in-loop filter | +234.0 / +171.9 | +260.3 / +203.2 | +318.5 / +155.3 | | |
| 7152 | + /// | + deblocking | +198.2 / +143.1 | +218.1 / +162.4 | +136.9 / +52.7 | | |
| 7153 | + /// | + CDEF | +143.6 / +94.0 | +179.5 / +128.8 | +88.0 / +21.5 | | |
| 7154 | + /// | |
| 7155 | + /// Loop restoration is NOT in yet: it is the one filter whose parameters | |
| 7156 | + /// are per restoration UNIT inside the tile payload, so it needs both | |
| 7157 | + /// tile writers to code `lr` syntax and an encoder-visible post-CDEF | |
| 7158 | + /// buffer to solve against -- neither of which this frame-header-level | |
| 7159 | + /// search reaches. | |
| 6948 | 7160 | /// |
| 6949 | 7161 | /// The baseline it replaced, before an inter frame's blocks chose their |
| 6950 | 7162 | /// own partition, was +501.4/+504.4/+440.9 against libaom and |
| @@ -7057,6 +7269,24 @@ mod tests { | ||
| 7057 | 7269 | whole16 + split16, |
| 7058 | 7270 | 100.0 * split16 as f64 / (whole16 + split16).max(1) as f64 |
| 7059 | 7271 | ); |
| 7272 | + // The deblocking level each of this clip's frames chose | |
| 7273 | + // (lane-av1filt): 0 everywhere would mean the filter never fires. | |
| 7274 | + let levels = crate::filter_search::take_chosen_levels(); | |
| 7275 | + type Chosen = ((u8, u8), (u8, u8), (u8, u8)); | |
| 7276 | + let mean = |f: fn(&Chosen) -> u8| { | |
| 7277 | + levels.iter().map(|l| f(l) as f64).sum::<f64>() / levels.len().max(1) as f64 | |
| 7278 | + }; | |
| 7279 | + eprintln!( | |
| 7280 | + "{name}: over {} frames -- deblock luma mean {:.1} chroma {:.1}; \ | |
| 7281 | + cdef luma pri {:.1}/sec {:.1}, chroma pri {:.1}/sec {:.1}", | |
| 7282 | + levels.len(), | |
| 7283 | + mean(|l| l.0.0), | |
| 7284 | + mean(|l| l.0.1), | |
| 7285 | + mean(|l| l.1.0), | |
| 7286 | + mean(|l| l.1.1), | |
| 7287 | + mean(|l| l.2.0), | |
| 7288 | + mean(|l| l.2.1), | |
| 7289 | + ); | |
| 7060 | 7290 | // Which chroma modes the search actually wins with, against the |
| 7061 | 7291 | // unconditional DC_PRED that was the only outcome before |
| 7062 | 7292 | // (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 | 32 | pub mod encoder; |
| 33 | 33 | mod envflags; |
| 34 | 34 | mod film_grain; |
| 35 | +mod filter_search; | |
| 35 | 36 | pub mod frame; |
| 36 | 37 | mod gate_coverage; |
| 37 | 38 | mod hits; |
crates/ec-av1/src/stream.rsmodified+2 -2
| @@ -2994,8 +2994,8 @@ mod tests { | ||
| 2994 | 2994 | width as u32, |
| 2995 | 2995 | height as u32, |
| 2996 | 2996 | false, |
| 2997 | - &ec_av1_syntax::CdefParams::default(), | |
| 2998 | - &ec_av1_syntax::LoopFilterParams::default(), | |
| 2997 | + &encoded.cdef, | |
| 2998 | + &encoded.loop_filter, | |
| 2999 | 2999 | encoded.tx_select, |
| 3000 | 3000 | // Our own encoder always writes `reduced_tx_set: true`. |
| 3001 | 3001 | true, |