diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index b18a709f..747ed67a 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -40,7 +40,34 @@ use ec_core::{Error, Result}; /// /// `Cell`/`RefCell` make this `!Sync` on purpose: a `FrameCtx` belongs to /// exactly one thread's decode, and is never shared between workers. +/// One frame's in-loop filter intermediates, as [`FrameCtx::capture_stages`] +/// asks for them: each plane's post-deblock (pre-CDEF) and post-CDEF +/// (pre-restoration) samples, at the decoder's own plane stride. +pub(crate) struct FilterStages { + /// Post-deblock, pre-CDEF planes (Y, U, V). + pub(crate) deblocked: [Vec; 3], + /// Post-CDEF, pre-restoration planes (Y, U, V). + pub(crate) cdefed: [Vec; 3], + /// Each plane's stride (and so its width in the buffers above). + pub(crate) stride: [usize; 3], +} + +/// Takes whatever the last capturing decode left (see +/// [`FrameCtx::capture_stages`]). +#[allow(dead_code)] // read from the encoder's loop restoration search +pub(crate) fn take_filter_stages(fctx: &FrameCtx) -> Option { + fctx.stages.borrow_mut().take() +} + pub(crate) struct FrameCtx { + /// lane-av1lr: when set, the frame filter chain leaves its post-deblock + /// and post-CDEF planes in [`FrameCtx::stages`] for the ENCODER's loop + /// restoration search (spec 7.17 reads both: the stripe interior from + /// the post-CDEF plane, its 3-row border from the post-deblock one). + /// Off for every decode but that search, and off it costs one bool read + /// per frame and not a single copy. + pub(crate) capture_stages: std::cell::Cell, + pub(crate) stages: std::cell::RefCell>, pub(crate) sb128_flag: std::cell::Cell, pub(crate) cdef_bits: std::cell::Cell, pub(crate) bit_depth: std::cell::Cell, @@ -130,6 +157,8 @@ impl FrameCtx { superres: std::cell::Cell::new((0, 8)), cdef_transmitted: std::cell::Cell::new(false), cdef_sb_cols: std::cell::Cell::new(0), + capture_stages: std::cell::Cell::new(false), + stages: std::cell::RefCell::new(None), cdef_idx_grid: std::cell::RefCell::new(Vec::new()), delta_q_present: std::cell::Cell::new(false), delta_q_res: std::cell::Cell::new(1), @@ -20431,6 +20460,37 @@ fn apply_cdef( scratch_return(src_v); } +/// [`FrameCtx::capture_stages`]'s write side, called between CDEF and loop +/// restoration on both tile paths: hands the encoder's restoration search the +/// two pictures spec 7.17 filters from. `deblocked` is the decoder's own +/// stripe-boundary snapshot ([`plane_snapshot`], only the rows LR reads), so +/// a capture is worth three plane copies and nothing else -- and when the +/// capture flag is off (every decode but that search) it is worth a bool. +fn capture_stages( + y: &PlaneBuf<'_>, + u: &PlaneBuf<'_>, + v: &PlaneBuf<'_>, + deblocked: Option<&(PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>, + fctx: &FrameCtx, +) { + if !fctx.capture_stages.get() { + return; + } + // Without an active restoration type the decoder took no pre-CDEF + // snapshot; the post-CDEF plane then stands in for it, which is exact + // everywhere but LR's own 3-row stripe borders (the encoder's search + // always asks with a type set, so this is the defensive arm). + let db = |i: usize, p: &PlaneBuf<'_>| match deblocked { + Some((a, b, c)) => [a, b, c][i].data.to_vec(), + None => p.data.to_vec(), + }; + *fctx.stages.borrow_mut() = Some(FilterStages { + deblocked: [db(0, y), db(1, u), db(2, v)], + cdefed: [y.data.to_vec(), u.data.to_vec(), v.data.to_vec()], + stride: [y.width, u.width, v.width], + }); +} + /// Spec 7.17: loop restoration, run after [`apply_cdef`] (a sibling lane's /// ordering note: libaom also runs `superres_post_decode` between the two, /// but this decoder never implements super-resolution, so there is nothing @@ -20546,6 +20606,34 @@ pub(crate) fn decode_key_frame_tile( reduced_tx_set: bool, allow_screen_content_tools: bool, allow_intrabc: bool, fctx: &crate::decode::FrameCtx, +) -> Result { + decode_key_frame_tile_lr( + data, mi_cols, mi_rows, base_q_idx, frame_width, frame_height, enable_filter_intra, + cdef, loop_filter, tx_select, reduced_tx_set, allow_screen_content_tools, allow_intrabc, + &LoopRestorationParams::default(), fctx, + ) +} + +/// [`decode_key_frame_tile`] with this frame header's own `lr_params` (spec +/// 5.9.20) instead of the no-restoration default -- the per-unit filters +/// themselves live in the tile payload, so the header is all this needs. +#[allow(clippy::too_many_arguments)] +pub(crate) fn decode_key_frame_tile_lr( + data: &[u8], + mi_cols: u32, + mi_rows: u32, + base_q_idx: u8, + frame_width: u32, + frame_height: u32, + enable_filter_intra: bool, + cdef: &CdefParams, + loop_filter: &LoopFilterParams, + tx_select: bool, + reduced_tx_set: bool, + allow_screen_content_tools: bool, + allow_intrabc: bool, + lr: &LoopRestorationParams, + fctx: &crate::decode::FrameCtx, ) -> Result { let delta = DeltaParams::default(); let single_tile = TileInfo { @@ -20566,7 +20654,7 @@ pub(crate) fn decode_key_frame_tile( false, cdef, loop_filter, - &LoopRestorationParams::default(), + lr, None, tx_select, reduced_tx_set, @@ -22883,6 +22971,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( ); dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v); dump_stage16("EC_AV1_POSTCDEF_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize); + capture_stages(&y, &u, &v, deblocked.as_ref(), fctx); // spec 7.16 (libaom `superres_post_decode`, decodeframe.c: called // between `av1_cdef_frame` and `av1_loop_restoration_filter_frame`): // the horizontal upscale runs HERE -- after CDEF, before loop @@ -32639,6 +32728,36 @@ pub(crate) fn decode_inter_frame_tile( // stale header, second instance). tx_select: bool, fctx: &crate::decode::FrameCtx, +) -> Result { + decode_inter_frame_tile_lr( + data, mi_cols, mi_rows, base_q_idx, frame_width, frame_height, refpix, cdef, + loop_filter, allow_high_precision_mv, force_integer_mv, interp_fixed, + enable_dual_filter, reference_select, tx_select, + &LoopRestorationParams::default(), fctx, + ) +} + +/// [`decode_inter_frame_tile`] with this frame header's own `lr_params`, the +/// inter sibling of [`decode_key_frame_tile_lr`]. +#[allow(clippy::too_many_arguments)] +pub(crate) fn decode_inter_frame_tile_lr( + data: &[u8], + mi_cols: u32, + mi_rows: u32, + base_q_idx: u8, + frame_width: u32, + frame_height: u32, + refpix: &RefPix<'_>, + cdef: &CdefParams, + loop_filter: &LoopFilterParams, + allow_high_precision_mv: bool, + force_integer_mv: bool, + interp_fixed: Option, + enable_dual_filter: bool, + reference_select: bool, + tx_select: bool, + lr: &LoopRestorationParams, + fctx: &crate::decode::FrameCtx, ) -> Result { let single_tile = TileInfo { mi_col_starts: vec![0, mi_cols], @@ -32657,7 +32776,7 @@ pub(crate) fn decode_inter_frame_tile( refpix, cdef, loop_filter, - &LoopRestorationParams::default(), + lr, None, allow_high_precision_mv, force_integer_mv, @@ -35498,6 +35617,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( } dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v); dump_stage16("EC_AV1_POSTCDEF_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize); + capture_stages(&y, &u, &v, deblocked.as_ref(), fctx); // spec 7.16 (libaom `superres_post_decode`, decodeframe.c: called // between `av1_cdef_frame` and `av1_loop_restoration_filter_frame`): // the horizontal upscale runs HERE -- after CDEF, before loop @@ -36625,9 +36745,10 @@ mod tests { tx_select, loop_filter, cdef, + loop_restoration, .. }: Encoded = crate::encode::encode_key_frame_with_modes_with_ctx(&picture, 40, 0.0, modes, fctx).unwrap(); - let decoded = decode_key_frame_tile( + let decoded = decode_key_frame_tile_lr( &tile, mi_cols, mi_rows, @@ -36640,7 +36761,8 @@ mod tests { tx_select, true, false, - false, fctx, + false, + &loop_restoration, fctx, ) .unwrap(); assert_eq!(decoded.width, w, "{w}x{h}: decoded width"); @@ -36994,7 +37116,7 @@ mod tests { let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); let (coded_w, coded_h) = ffprobe_size(&encoded.stream); let ffmpeg_decoded = ffmpeg_decode(&encoded.stream, coded_w as usize, coded_h as usize); - let ours = decode_key_frame_tile( + let ours = decode_key_frame_tile_lr( &encoded.tile, encoded.mi_cols, encoded.mi_rows, @@ -37007,7 +37129,8 @@ mod tests { encoded.tx_select, true, false, - false, fctx, + false, + &encoded.loop_restoration, fctx, ) .unwrap(); assert_eq!(ours.y, ffmpeg_decoded.y, "{width}x{height}: luma vs ffmpeg"); @@ -37037,7 +37160,7 @@ mod tests { gate's premise moved, not the decoder" ); let decode = |tx_select: bool| { - decode_key_frame_tile( + decode_key_frame_tile_lr( &encoded.tile, encoded.mi_cols, encoded.mi_rows, @@ -37051,6 +37174,7 @@ mod tests { true, false, false, + &encoded.loop_restoration, fctx, ) }; @@ -37121,7 +37245,7 @@ mod tests { assert_eq!(encoded.frames.len(), 4); let key = &encoded.frames[0]; - let mut reference = decode_key_frame_tile( + let mut reference = decode_key_frame_tile_lr( &key.tile, key.mi_cols, key.mi_rows, @@ -37134,7 +37258,8 @@ mod tests { key.tx_select, true, false, - false, fctx, + false, + &key.loop_restoration, fctx, ) .unwrap(); assert_eq!( @@ -37151,7 +37276,7 @@ mod tests { ); for (i, frame) in encoded.frames.iter().enumerate().skip(1) { - let decoded = decode_inter_frame_tile( + let decoded = decode_inter_frame_tile_lr( &frame.tile, frame.mi_cols, frame.mi_rows, @@ -37167,6 +37292,7 @@ mod tests { false, false, frame.tx_select, + &frame.loop_restoration, fctx, ) .unwrap(); @@ -37443,7 +37569,7 @@ mod tests { ffmpeg_decode_sequence(&encoded.stream, coded_w as usize, coded_h as usize, 3); let key = &encoded.frames[0]; - let mut reference = decode_key_frame_tile( + let mut reference = decode_key_frame_tile_lr( &key.tile, key.mi_cols, key.mi_rows, @@ -37456,13 +37582,14 @@ mod tests { key.tx_select, true, false, - false, fctx, + false, + &key.loop_restoration, fctx, ) .unwrap(); assert_eq!(reference.y, ffmpeg_frames[0].y, "frame 0 luma vs ffmpeg"); for (i, frame) in encoded.frames.iter().enumerate().skip(1) { - let decoded = decode_inter_frame_tile( + let decoded = decode_inter_frame_tile_lr( &frame.tile, frame.mi_cols, frame.mi_rows, @@ -37478,6 +37605,7 @@ mod tests { false, false, frame.tx_select, + &frame.loop_restoration, fctx, ) .unwrap(); diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 9a48c010..c28b472e 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::{ - CdefParams, ChromaSamplePosition, FrameHeader, FrameType, LoopFilterParams, PRIMARY_REF_NONE, - QuantizationParams, TileInfo, TxMode, + CdefParams, ChromaSamplePosition, FrameHeader, FrameType, LoopFilterParams, + LoopRestorationParams, PRIMARY_REF_NONE, QuantizationParams, TileInfo, TxMode, }; use ec_core::{Error, Result}; @@ -190,6 +190,20 @@ fn split_inter_blocks() -> bool { } } +/// Whether the encoder searches loop restoration at all (spec 7.17): one +/// Wiener filter per 64x64 luma restoration unit, picked from +/// [`crate::filter_search::WIENER_CANDIDATES`]. Swept by `EC_AV1_LR` in a +/// test build, like [`lambda_scale`]. +const RESTORATION: bool = true; + +/// [`RESTORATION`], or what `EC_AV1_LR` names in a test build. +fn restoration_enabled() -> bool { + match std::env::var("EC_AV1_LR").ok() { + Some(v) if cfg!(test) => v != "0", + _ => RESTORATION, + } +} + /// libaom's `partition_search_breakout` shape: how many non-zero luma /// coefficients per 256 luma samples a block may code and still be judged /// well enough predicted that the split below it is not worth trying. `0` @@ -478,6 +492,7 @@ pub(crate) fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> En base_q_idx: encoded.base_q_idx, tx_select: encoded.tx_select, loop_filter: encoded.loop_filter, + loop_restoration: encoded.loop_restoration, cdef: encoded.cdef, } } @@ -524,6 +539,11 @@ pub struct Encoded { /// This frame header's chosen CDEF parameters, threaded for the same /// reason as `loop_filter`. pub(crate) cdef: CdefParams, + /// This frame header's chosen loop restoration parameters, threaded for + /// the same reason as `loop_filter` -- and doubly so: the per-unit + /// filters themselves are coded in `tile`, so a decode of it under a + /// stale `RESTORE_NONE` header desyncs at the first superblock. + pub(crate) loop_restoration: LoopRestorationParams, } /// The sequence and frame headers a picture of this size is coded under: one @@ -608,7 +628,7 @@ pub(crate) fn key_frame_headers_colour( // `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, + enable_restoration: true, seq_force_screen_content_tools: 0, seq_force_integer_mv: 0, color_config, @@ -3037,6 +3057,12 @@ pub(crate) fn encode_key_frame_inner( // `crate::filter_search`), and keep the filtered picture that wins as // the reconstruction -- what a decoder outputs, and what the next // frame predicts from. + // The luma restoration-unit grid this frame's `lr_params` implies + // (`av1_lr_count_units` rounds to nearest, so a short last unit is + // swallowed by the one before it), for the tile writer's own per-unit + // walk. + let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32; + let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32; pick_and_apply_filters( &mut header, &mut luma, @@ -3045,8 +3071,10 @@ pub(crate) fn encode_key_frame_inner( true, &mut tile, search.lambda, - |bits, sb_cols, grid| { + fctx, + |bits, sb_cols, grid, units| { crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec()); + crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec()); crate::tile::sb_coeff_key_frame_tile_tx( mi_cols, mi_rows, @@ -3055,8 +3083,8 @@ pub(crate) fn encode_key_frame_inner( tx_select, ) }, - |lf, cdef, h, tile| { - crate::decode::decode_key_frame_tile( + |lf, cdef, h, tile, lr| { + crate::decode::decode_key_frame_tile_lr( tile, h.mi_cols, h.mi_rows, @@ -3070,6 +3098,7 @@ pub(crate) fn encode_key_frame_inner( h.reduced_tx_set, h.allow_screen_content_tools, h.allow_intrabc, + lr, fctx, ) }, @@ -3097,6 +3126,7 @@ pub(crate) fn encode_key_frame_inner( tx_select, loop_filter: header.loop_filter, cdef: header.cdef, + loop_restoration: header.loop_restoration, }) } @@ -3126,8 +3156,15 @@ fn pick_and_apply_filters( // winner re-decoded from it. tile: &mut Vec, lambda: f64, - recode: impl Fn(u8, usize, &[u8]) -> Result>, - decode: impl Fn(&LoopFilterParams, &CdefParams, &FrameHeader, &[u8]) -> Result, + fctx: &crate::decode::FrameCtx, + recode: impl Fn(u8, usize, &[u8], &[Option]) -> Result>, + decode: impl Fn( + &LoopFilterParams, + &CdefParams, + &FrameHeader, + &[u8], + &LoopRestorationParams, + ) -> Result, ) -> Result<()> { if !search { return Ok(()); @@ -3139,8 +3176,9 @@ fn pick_and_apply_filters( let damping = 3 + (header.quantization.base_q_idx >> 6); let (cols32, rows32) = crate::tile::block_grid(header.mi_cols, header.mi_rows); let (sb_cols, sb_rows) = (cols32.div_ceil(2) as usize, rows32.div_ceil(2) as usize); + let none_lr = LoopRestorationParams::default(); let (lf, cdef, idx_grid, picture) = crate::filter_search::pick_filters( - |lf, cdef| decode(lf, cdef, &hdr, tile), + |lf, cdef| decode(lf, cdef, &hdr, tile, &none_lr), source, luma.width, (fw, fh), @@ -3150,14 +3188,61 @@ fn pick_and_apply_filters( )?; header.loop_filter = lf; header.cdef = cdef; - let filtered = if idx_grid.is_empty() { - picture + // spec 7.17: loop restoration. Its per-unit filters live in the TILE, so + // this stage codes the tile a second time no matter what -- first with + // every unit at `RESTORE_NONE`, which is the shape whose decode hands + // back the post-deblock and post-CDEF pictures the search needs (and + // whose output IS the post-CDEF picture), then again with the filters it + // picked. + let mut lr = LoopRestorationParams::default(); + if restoration_enabled() { + lr.frame_restoration_type[0] = ec_av1_syntax::RestorationType::Wiener; + lr.loop_restoration_size = [64, 64, 64]; + lr.uses_lr = true; + } + let grid_dims = crate::restoration::RestorationGrid::new(&lr, fw as u32, fh as u32); + let n_units = if lr.uses_lr { + grid_dims.horz_units[0] * grid_dims.vert_units[0] } else { - let coded = recode(cdef.bits, sb_cols, &idx_grid)?; - let picture = decode(&lf, &cdef, &hdr, &coded)?; - *tile = coded; + 0 + }; + let filtered = if idx_grid.is_empty() && n_units == 0 { picture + } else { + let probe = recode(cdef.bits, sb_cols, &idx_grid, &vec![None; n_units])?; + fctx.capture_stages.set(n_units > 0); + let probe_picture = decode(&lf, &cdef, &hdr, &probe, &lr)?; + fctx.capture_stages.set(false); + let units = match crate::decode::take_filter_stages(fctx) { + Some(stages) => crate::filter_search::pick_restoration( + &stages, + source[0], + luma.width, + (fw, fh), + &lr, + lambda, + fctx, + ), + None => Vec::new(), + }; + if units.iter().any(Option::is_some) { + let coded = recode(cdef.bits, sb_cols, &idx_grid, &units)?; + let picture = decode(&lf, &cdef, &hdr, &coded, &lr)?; + *tile = coded; + picture + } else { + // Nothing to restore: code the frame with `RESTORE_NONE` on every + // plane instead of a tile full of `restore_wiener = 0` symbols + // (worth ~1 bit per 64x64, which the BD gate saw on a clip whose + // units never take a filter). The probe's picture already IS the + // unrestored one -- a grid of `RESTORE_NONE` units restores + // nothing -- so this costs one tile write and no decode. + lr = LoopRestorationParams::default(); + *tile = recode(cdef.bits, sb_cols, &idx_grid, &[])?; + probe_picture + } }; + header.loop_restoration = lr; 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); @@ -4257,6 +4342,12 @@ pub(crate) fn encode_inter_frame( let mut refs: [Option<&Picture>; 8] = [None; 8]; refs[1] = Some(&trial_ref); let refpix = crate::decode::RefPix::ready(refs); + // The luma restoration-unit grid this frame's `lr_params` implies + // (`av1_lr_count_units` rounds to nearest, so a short last unit is + // swallowed by the one before it), for the tile writer's own per-unit + // walk. + let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32; + let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32; pick_and_apply_filters( &mut header, &mut luma, @@ -4269,8 +4360,10 @@ pub(crate) fn encode_inter_frame( true, &mut tile, search.lambda, - |bits, sb_cols, grid| { + fctx, + |bits, sb_cols, grid, units| { crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec()); + crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec()); crate::tile::sb_coeff_inter_frame_tile_tx( mi_cols, mi_rows, @@ -4279,8 +4372,8 @@ pub(crate) fn encode_inter_frame( tx_select, ) }, - |lf, cdef, h, tile| { - crate::decode::decode_inter_frame_tile( + |lf, cdef, h, tile, lr| { + crate::decode::decode_inter_frame_tile_lr( tile, h.mi_cols, h.mi_rows, @@ -4296,6 +4389,7 @@ pub(crate) fn encode_inter_frame( seq.enable_dual_filter, h.reference_select, tx_select, + lr, fctx, ) }, @@ -4322,6 +4416,7 @@ pub(crate) fn encode_inter_frame( tx_select, loop_filter: header.loop_filter, cdef: header.cdef, + loop_restoration: header.loop_restoration, }) } @@ -7287,6 +7382,13 @@ mod tests { units, 100.0 * on_extra as f64 / units.max(1) as f64 ); + // How the 64x64 luma restoration units split between + // RESTORE_NONE and Wiener (lane-av1lr). + let (lr_none, lr_wiener) = crate::filter_search::take_lr_histogram(); + eprintln!( + "{name}: lr units none={lr_none} wiener={lr_wiener} ({:.1}% restored)", + 100.0 * lr_wiener as f64 / (lr_none + lr_wiener).max(1) as f64 + ); // 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 index 65067b91..3c20d7b7 100644 --- a/crates/ec-av1/src/filter_search.rs +++ b/crates/ec-av1/src/filter_search.rs @@ -344,3 +344,139 @@ pub(crate) fn splice(dst: &mut [u8], dst_w: usize, src: &[u16], src_w: usize, w: } } } + +// --------------------------------------------------------------------------- +// lane-av1lr: loop restoration (spec 7.17). Unlike deblocking and CDEF, whose +// parameters live in the frame header, a restoration unit's filter is coded +// in the TILE payload, so a whole-frame re-decode cannot search it: the +// search runs here, on the two pictures the decoder captured between its own +// filter stages (`crate::decode::FrameCtx::capture_stages`), through the +// decoder's OWN Wiener kernel (`crate::restoration:: +// apply_loop_restoration_plane`) -- never a second implementation. + +/// The Wiener filters offered per unit, as the three free taps of a +/// direction (the centre tap is derived). Both directions take the same +/// candidate, so a unit picks one of four separable filters: two strengths +/// of low pass, one wider low pass, and one sharpener. +/// +/// corner-cut: libaom's `av1_pick_filter_restoration` SOLVES for each unit's +/// taps (the Wiener-Hopf normal equations over that unit's autocorrelation) +/// instead of picking from a ladder, and also offers self-guided restoration. +/// The ceiling is whatever a four-point ladder leaves on the table; the +/// upgrade path is a per-unit solve feeding the same `write_wiener_filter` +/// syntax this already writes, plus `RestorationType::Switchable` for the +/// SGR arm. +const WIENER_CANDIDATES: [[i32; 3]; 4] = [[0, 0, 8], [0, 0, 16], [0, 4, 12], [0, 0, -8]]; + +/// What a unit spends on its own syntax, for the RD choice below: one +/// `restore_wiener` symbol for `RESTORE_NONE`, and roughly the two +/// directions' three subexp-coded taps when it takes a filter. +const LR_NONE_BITS: f64 = 1.0; +const LR_WIENER_BITS: f64 = 25.0; + +/// Picks each luma restoration unit's filter, on the frame the decoder +/// captured after CDEF (with its post-deblock stripe borders), against the +/// source it was coded from. Returns one entry per unit in `rcol + rrow * +/// horz_units` order -- what `crate::tile::arm_lr` writes. +pub(crate) fn pick_restoration( + stages: &crate::decode::FilterStages, + source: &[u8], + src_w: usize, + (fw, fh): (usize, usize), + lr: &ec_av1_syntax::LoopRestorationParams, + lambda: f64, + fctx: &crate::decode::FrameCtx, +) -> Vec> { + let grid_dims = crate::restoration::RestorationGrid::new(lr, fw as u32, fh as u32); + let (horz, vert) = (grid_dims.horz_units[0], grid_dims.vert_units[0]); + let unit = lr.loop_restoration_size[0] as usize; + let stride = stages.stride[0]; + let rows = crate::restoration::lr_unit_rows(fh, unit as u32, 0, lr.frame_restoration_type[0]); + if rows.len() != vert { + return Vec::new(); + } + // Each unit's own sample span: the row walk's (a short last row is + // swallowed by the one above it), and the column mirror of it. + let span = |rrow: usize, rcol: usize| -> (usize, usize, usize, usize) { + let (r0, r1) = rows[rrow]; + let c0 = rcol * unit; + let c1 = if rcol + 1 == horz { fw } else { (rcol + 1) * unit }; + (r0 as usize, r1 as usize, c0, c1) + }; + let unit_sse = |plane: &[u16], rrow: usize, rcol: usize| -> u64 { + let (r0, r1, c0, c1) = span(rrow, rcol); + let mut sse = 0u64; + for row in r0..r1 { + for col in c0..c1 { + let diff = i64::from(plane[row * stride + col]) - i64::from(source[row * src_w + col]); + sse += (diff * diff) as u64; + } + } + sse + }; + // Cost of leaving every unit alone, then one whole-plane pass per + // candidate to price taking it. + let mut best: Vec<(f64, Option)> = (0..horz * vert) + .map(|i| { + let sse = unit_sse(&stages.cdefed[0], i / horz, i % horz) as f64; + (sse + lambda * LR_NONE_BITS, None) + }) + .collect(); + let mut out = Vec::new(); + for taps in WIENER_CANDIDATES { + let info = crate::restoration::wiener_from_taps(taps, taps); + let mut grid = crate::restoration::RestorationGrid::new(lr, fw as u32, fh as u32); + for rrow in 0..vert { + for rcol in 0..horz { + grid.set(0, rrow, rcol, crate::restoration::UnitFilter::Wiener(info)); + } + } + crate::restoration::apply_loop_restoration_plane( + &stages.cdefed[0], + &stages.deblocked[0], + stride, + fw, + fh, + 0, + lr.frame_restoration_type[0], + lr.loop_restoration_size[0], + &grid, + 0, + &mut out, + None, + fctx, + ); + for rrow in 0..vert { + for rcol in 0..horz { + let cost = unit_sse(&out, rrow, rcol) as f64 + lambda * LR_WIENER_BITS; + let slot = &mut best[rcol + rrow * horz]; + if cost < slot.0 { + *slot = (cost, Some(info)); + } + } + } + } + let chosen: Vec> = + best.into_iter().map(|(_, f)| f).collect(); + LR_CHOSEN.with(|c| { + let mut hist = c.borrow_mut(); + for f in &chosen { + hist.0 += usize::from(f.is_none()); + hist.1 += usize::from(f.is_some()); + } + }); + chosen +} + +thread_local! { + /// `(RESTORE_NONE units, Wiener units)` over every frame since the last + /// [`take_lr_histogram`] -- the BD gate's own proof the feature fires. + static LR_CHOSEN: std::cell::RefCell<(usize, usize)> = + const { std::cell::RefCell::new((0, 0)) }; +} + +/// Takes and clears [`LR_CHOSEN`]. +#[allow(dead_code)] // read from the `#[cfg(test)]` BD gate +pub(crate) fn take_lr_histogram() -> (usize, usize) { + LR_CHOSEN.with(|c| std::mem::take(&mut *c.borrow_mut())) +} diff --git a/crates/ec-av1/src/restoration.rs b/crates/ec-av1/src/restoration.rs index 1436d29a..959a992f 100644 --- a/crates/ec-av1/src/restoration.rs +++ b/crates/ec-av1/src/restoration.rs @@ -80,6 +80,139 @@ fn decode_signed_subexp_with_ref_msac(dec: &mut SymbolDecoder, low: i32, high: i decode_unsigned_subexp_with_ref_msac(dec, n, k, r) as i32 + low } +// --------------------------------------------------------------------------- +// lane-av1lr: the WRITE side of the three primitives above, for the encoder's +// per-restoration-unit syntax (`crate::tile`). Each is libaom's own writer +// (`aom_dsp/bitwriter.h`'s `write_primitive_*`) and the exact inverse of the +// reader it sits under; `wiener_filter_roundtrips` below pins the pair. + +/// `aom_write_primitive_quniform`, the inverse of [`ns_msac`]. +fn write_ns(enc: &mut crate::msac::SymbolEncoder, n: u32, v: u32) { + if n <= 1 { + return; + } + let w = floor_log2(n) + 1; + let m = (1u32 << w) - n; + if v < m { + enc.literal(v, w - 1); + } else { + enc.literal(m + ((v - m) >> 1), w - 1); + enc.literal((v - m) & 1, 1); + } +} + +/// `aom_write_primitive_subexpfin`, the inverse of [`decode_subexp_msac`]. +fn write_subexp(enc: &mut crate::msac::SymbolEncoder, num_syms: u32, k: u32, v: u32) { + let mut i = 0u32; + let mut mk = 0u32; + loop { + let b = if i > 0 { k + i - 1 } else { k }; + let a = 1u32 << b; + if num_syms <= mk + 3 * a { + write_ns(enc, num_syms - mk, v - mk); + return; + } + if v < mk + a { + enc.literal(0, 1); + enc.literal(v - mk, b); + return; + } + enc.literal(1, 1); + i += 1; + mk += a; + } +} + +/// `recenter_nonneg`, the inverse of [`inverse_recenter`]. +fn recenter(r: u32, v: u32) -> u32 { + if v > 2 * r { + v + } else if v >= r { + (v - r) << 1 + } else { + ((r - v) << 1) - 1 + } +} + +/// Inverse of [`decode_unsigned_subexp_with_ref_msac`]. +fn write_unsigned_subexp_with_ref( + enc: &mut crate::msac::SymbolEncoder, + n: u32, + k: u32, + reference: u32, + v: u32, +) { + let recentred = if (reference << 1) <= n { + recenter(reference, v) + } else { + recenter(n - 1 - reference, n - 1 - v) + }; + write_subexp(enc, n, k, recentred); +} + +/// Inverse of [`decode_signed_subexp_with_ref_msac`]. +fn write_signed_subexp_with_ref( + enc: &mut crate::msac::SymbolEncoder, + low: i32, + high: i32, + k: u32, + reference: i32, + v: i32, +) { + let n = (high - low) as u32; + let r = (reference - low).clamp(0, n as i32) as u32; + write_unsigned_subexp_with_ref(enc, n, k, r, (v - low).clamp(0, n as i32 - 1) as u32); +} + +/// Inverse of [`read_wiener_filter`]: writes one unit's two directions and +/// advances the caller's running per-plane reference, exactly as the reader +/// advances its own. +pub(crate) fn write_wiener_filter( + enc: &mut crate::msac::SymbolEncoder, + chroma: bool, + reference: &mut WienerInfo, + info: &WienerInfo, +) { + write_wiener_direction(enc, chroma, &reference.vfilter, &info.vfilter); + write_wiener_direction(enc, chroma, &reference.hfilter, &info.hfilter); + *reference = *info; +} + +/// Inverse of [`read_wiener_direction`]. +fn write_wiener_direction( + enc: &mut crate::msac::SymbolEncoder, + chroma: bool, + reference: &[i32; 7], + taps: &[i32; 7], +) { + for i in 0..3 { + if i == 0 && chroma { + continue; + } + write_signed_subexp_with_ref( + enc, + WIENER_TAP_MINV[i], + WIENER_TAP_MAXV[i] + 1, + WIENER_TAP_K[i], + reference[i], + taps[i], + ); + } +} + +/// A Wiener unit's three free taps per direction, as [`WienerInfo`] (the +/// centre tap is derived, spec 7.17.4). +pub(crate) fn wiener_from_taps(v: [i32; 3], h: [i32; 3]) -> WienerInfo { + let fill = |t: [i32; 3]| { + let centre = 128 - 2 * (t[0] + t[1] + t[2]); + [t[0], t[1], t[2], centre, t[2], t[1], t[0]] + }; + WienerInfo { + vfilter: fill(v), + hfilter: fill(h), + } +} + #[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live const WIENER_HALFWIN: usize = 3; #[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live @@ -291,7 +424,7 @@ impl RestorationGrid { } } - fn set(&mut self, plane: usize, rrow: usize, rcol: usize, filter: UnitFilter) { + pub(crate) fn set(&mut self, plane: usize, rrow: usize, rcol: usize, filter: UnitFilter) { let idx = rcol + rrow * self.horz_units[plane]; self.units[plane][idx] = filter; } @@ -303,7 +436,7 @@ impl RestorationGrid { } /// `av1_lr_count_units` (restoration.c:63): round, not ceil, to nearest. -fn count_units(plane_size: u32, unit_size: u32) -> usize { +pub(crate) fn count_units(plane_size: u32, unit_size: u32) -> usize { (((plane_size + (unit_size >> 1)) / unit_size).max(1)) as usize } @@ -1366,63 +1499,10 @@ mod tests { use super::*; use crate::msac::{SymbolDecoder, SymbolEncoder}; - /// `write_primitive_quniform`, the exact inverse of [`ns_msac`] -- used - /// only to build roundtrip fixtures for the decode-only helpers above - /// (this decoder never writes loop restoration itself). - fn write_ns(enc: &mut SymbolEncoder, n: u32, v: u32) { - if n <= 1 { - return; - } - let w = floor_log2(n) + 1; - let m = (1u32 << w) - n; - if v < m { - enc.literal(v, w - 1); - } else { - enc.literal((v + m) >> 1, w - 1); - enc.literal((v + m) & 1, 1); - } - } - - fn write_subexp(enc: &mut SymbolEncoder, num_syms: u32, k: u32, v: u32) { - let mut i = 0u32; - let mut mk = 0u32; - loop { - let b = if i > 0 { k + i - 1 } else { k }; - let a = 1u32 << b; - if num_syms <= mk + 3 * a { - write_ns(enc, num_syms - mk, v - mk); - return; - } - if v < mk + a { - enc.literal(0, 1); - enc.literal(v - mk, b); - return; - } - enc.literal(1, 1); - i += 1; - mk += a; - } - } - - fn recenter(r: u32, v: u32) -> u32 { - if v > 2 * r { - v - } else if v >= r { - (v - r) << 1 - } else { - ((r - v) << 1) - 1 - } - } - - fn write_unsigned_subexp_with_ref(enc: &mut SymbolEncoder, n: u32, k: u32, reference: u32, v: u32) { - let r = reference.clamp(0, n.saturating_sub(1)); - let coded = if (r << 1) <= n { - recenter(r, v) - } else { - recenter(n - 1 - r, n - 1 - v) - }; - write_subexp(enc, n, k, coded); - } + /// The write side these roundtrips exercise now lives beside the + /// readers (`write_ns`/`write_subexp`/`write_unsigned_subexp_with_ref`, + /// used by the encoder's per-unit LR syntax) instead of being a + /// test-only transcription of it -- one implementation, pinned here. /// `decode_subexp_msac`/`ns_msac` roundtrip every value in a handful of /// `(num_syms, k)` alphabets -- the shapes LR's tap ranges (`k` 1..=4, @@ -1489,4 +1569,34 @@ mod tests { } } } + + /// [`write_wiener_filter`] against [`read_wiener_filter`], including the + /// running per-tile reference both sides advance: three units in a row, + /// luma (7-tap) and chroma (5-tap, tap 0 forced to zero). + #[test] + fn wiener_filter_roundtrips() { + for chroma in [false, true] { + let units = [ + wiener_from_taps([0, 0, 8], [0, 0, 8]), + wiener_from_taps([0, 4, 12], [0, 0, -8]), + wiener_from_taps([0, 0, 0], [0, 0, 0]), + ]; + let units: Vec = if chroma { + units.iter().copied().collect() + } else { + units.to_vec() + }; + let mut enc = SymbolEncoder::new(); + let mut wref = WienerInfo::default(); + for u in &units { + write_wiener_filter(&mut enc, chroma, &mut wref, u); + } + let payload = enc.finish(); + let mut dec = SymbolDecoder::new(&payload); + let mut rref = WienerInfo::default(); + for u in &units { + assert_eq!(read_wiener_filter(&mut dec, chroma, &mut rref), *u, "chroma={chroma}"); + } + } + } } diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index b3ab969a..da25c40c 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -28,7 +28,7 @@ use crate::decode::{ q_ctx_of, }; #[cfg(test)] -use crate::decode::decode_key_frame_tile; +use crate::decode::decode_key_frame_tile_lr; use crate::encode::Picture; /// lane-midcut r1: `EC_AV1_NO_GRAIN=1` skips film grain synthesis at output, so a @@ -2986,7 +2986,7 @@ mod tests { for &(width, height) in &[(64usize, 64usize), (216, 96)] { let picture = test_card(width, height); let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); - let via_tile = decode_key_frame_tile( + let via_tile = decode_key_frame_tile_lr( &encoded.tile, encoded.mi_cols, encoded.mi_rows, @@ -3000,7 +3000,8 @@ mod tests { // Our own encoder always writes `reduced_tx_set: true`. true, false, - false, fctx, + false, + &encoded.loop_restoration, fctx, ) .unwrap(); let via_stream = decode_stream(&encoded.stream).unwrap(); diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index 0b222923..4fa74075 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -31,6 +31,90 @@ use crate::mvstack::{MiGrid, MiInfo, NO_REF1, find_mv_stack, mv16, single_ref_ct // ([`CdefIdxGuard`] clears it on every exit path, error included), so a frame // that arms nothing writes no literals. +// --------------------------------------------------------------------------- +// lane-av1lr: per-restoration-unit loop restoration syntax (spec 5.11.57, +// `read_lr`), armed by the encoder's restoration search the same way +// [`arm_cdef_idx`] arms the CDEF indices. LUMA ONLY and Wiener only: the +// frame header this encoder writes sets `FrameRestorationType[0] = WIENER` +// and leaves both chroma planes at `RESTORE_NONE`, so a unit codes one +// `restore_wiener` symbol and, when it takes the filter, its two directions +// against the running per-tile reference (`crate::restoration:: +// write_wiener_filter`, the exact inverse of the reader's own +// `read_wiener_filter`). + +/// One frame's per-unit restoration plan (see [`arm_lr`]). +struct LrPlan { + /// `LoopRestorationSize[0]`, in luma samples. + unit_size: u32, + /// `horz_units`/`vert_units` for the luma plane. + horz_units: u32, + vert_units: u32, + /// One entry per unit, `rcol + rrow * horz_units`: the filter it takes, + /// or `None` for `RESTORE_NONE`. + units: Vec>, + /// `ref_wiener_info`: the running reference the taps are coded against, + /// reset to the midpoint filter at the start of each tile (this writer + /// codes one tile per frame). + reference: crate::restoration::WienerInfo, +} + +thread_local! { + static LR_PLAN: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + +/// Arms the next tile write with one Wiener decision per luma restoration +/// unit. An empty `units` disarms (the frame codes no restoration at all). +pub(crate) fn arm_lr( + unit_size: u32, + horz_units: u32, + vert_units: u32, + units: Vec>, +) { + LR_PLAN.with(|c| { + *c.borrow_mut() = (!units.is_empty()).then(|| LrPlan { + unit_size, + horz_units, + vert_units, + units, + reference: crate::restoration::WienerInfo::default(), + }); + }); +} + +/// `read_lr`'s write side, called once at the top of every superblock, +/// before its partition symbol: writes the units this superblock's own +/// mi span covers (`av1_loop_restoration_corners_in_sb`; no superres, so the +/// column scaling is the plain mi one). +fn write_lr(enc: &mut SymbolEncoder, cdfs: &mut Cdfs, mi_row: u32, mi_col: u32) { + LR_PLAN.with(|c| { + let mut plan = c.borrow_mut(); + let Some(plan) = plan.as_mut() else { return }; + let unit = plan.unit_size; + let rcol0 = (mi_col * 4).div_ceil(unit); + let rcol1 = ((mi_col + SB_MI_W) * 4).div_ceil(unit).min(plan.horz_units); + let rrow0 = (mi_row * 4).div_ceil(unit); + let rrow1 = ((mi_row + SB_MI_W) * 4).div_ceil(unit).min(plan.vert_units); + for rrow in rrow0..rrow1 { + for rcol in rcol0..rcol1 { + let info = plan.units[(rcol + rrow * plan.horz_units) as usize]; + enc.symbol(usize::from(info.is_some()), &mut cdfs.restore_wiener); + if let Some(info) = info { + crate::restoration::write_wiener_filter( + enc, + false, + &mut plan.reference, + &info, + ); + } + } + } + }); +} + +/// A 64x64 superblock's width in 4x4 mode-info units (`SB_MI` in +/// `crate::decode`), the span [`write_lr`] resolves its units over. +const SB_MI_W: u32 = 16; + /// One frame's per-superblock `cdef_idx` plan (see [`arm_cdef_idx`]). struct CdefIdxPlan { /// The header's `cdef_bits`; never 0 while armed. @@ -65,6 +149,7 @@ struct CdefIdxGuard; impl Drop for CdefIdxGuard { fn drop(&mut self) { CDEF_IDX.with(|c| *c.borrow_mut() = None); + LR_PLAN.with(|c| *c.borrow_mut() = None); } } @@ -1177,6 +1262,7 @@ pub fn sb_coeff_key_frame_tile_tx( for sb_r in 0..sb_rows { neighbours.start_row(); for sb_c in 0..sb_cols { + write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W); let at = (sb_r as usize * 4, sb_c as usize * 4); let ctx = neighbours.partition_ctx(at, SB); ec_rng_trace(|| { @@ -2836,6 +2922,7 @@ pub fn sb_coeff_inter_frame_tile_tx( for sb_r in 0..sb_rows { neighbours.start_row(); for sb_c in 0..sb_cols { + write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W); let sb_at = (sb_r as usize * 4, sb_c as usize * 4); let sb_ctx = neighbours.partition_ctx(sb_at, SB); // spec `decode_partition`'s hasRows/hasCols (5.11.4): a superblock