diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 9137495f..45db5e06 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), @@ -20545,6 +20574,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 @@ -20660,6 +20720,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 { @@ -20680,7 +20768,7 @@ pub(crate) fn decode_key_frame_tile( false, cdef, loop_filter, - &LoopRestorationParams::default(), + lr, None, tx_select, reduced_tx_set, @@ -23019,6 +23107,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 @@ -32780,6 +32869,37 @@ pub(crate) fn decode_inter_frame_tile( // class as `tx_select` above, third instance. initial_cdfs: Option, 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(), initial_cdfs, 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, + initial_cdfs: Option, + fctx: &crate::decode::FrameCtx, ) -> Result { let single_tile = TileInfo { mi_col_starts: vec![0, mi_cols], @@ -32798,7 +32918,7 @@ pub(crate) fn decode_inter_frame_tile( refpix, cdef, loop_filter, - &LoopRestorationParams::default(), + lr, initial_cdfs, allow_high_precision_mv, force_integer_mv, @@ -35660,6 +35780,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 @@ -36803,9 +36924,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, @@ -36818,7 +36940,8 @@ mod tests { tx_select, true, false, - false, fctx, + false, + &loop_restoration, fctx, ) .unwrap(); assert_eq!(decoded.width, w, "{w}x{h}: decoded width"); @@ -37173,7 +37296,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, @@ -37186,7 +37309,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"); @@ -37216,7 +37340,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, @@ -37230,6 +37354,7 @@ mod tests { true, false, false, + &encoded.loop_restoration, fctx, ) }; @@ -37300,7 +37425,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, @@ -37313,7 +37438,8 @@ mod tests { key.tx_select, true, false, - false, fctx, + false, + &key.loop_restoration, fctx, ) .unwrap(); assert_eq!( @@ -37330,7 +37456,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, @@ -37350,6 +37476,7 @@ mod tests { false, false, frame.tx_select, + &frame.loop_restoration, Some(frame.start_cdfs.0.clone()), fctx, ) @@ -37627,7 +37754,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, @@ -37640,13 +37767,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, @@ -37666,6 +37794,7 @@ mod tests { false, false, frame.tx_select, + &frame.loop_restoration, Some(frame.start_cdfs.0.clone()), fctx, ) diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index c617077f..921bdd0f 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` @@ -480,6 +494,7 @@ pub(crate) fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> En start_cdfs: encoded.start_cdfs.clone(), next_cdfs: encoded.next_cdfs.clone(), loop_filter: encoded.loop_filter, + loop_restoration: encoded.loop_restoration, cdef: encoded.cdef, } } @@ -549,6 +564,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 @@ -633,7 +653,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, @@ -3096,11 +3116,12 @@ pub(crate) fn encode_key_frame_inner( // set, so what it stores into the slots it refreshes is exactly those // defaults again (spec 7.20's `started_from` arm) -- the first inter // frame after it therefore starts from the defaults too. + let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows); let mut cdfs = crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx)); let start_cdfs = CdfSnapshot(cdfs.clone()); - let tile = crate::tile::sb_coeff_key_frame_tile_cdfs( - header.mi_cols, - header.mi_rows, + let mut tile = crate::tile::sb_coeff_key_frame_tile_cdfs( + mi_cols, + mi_rows, base_q_idx, &superblocks, tx_select, @@ -3111,16 +3132,41 @@ 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, &mut chroma, [&picture_y8, &picture_u8, &picture_v8], true, + &mut tile, + search.lambda, fctx, - |lf, cdef, h| { - crate::decode::decode_key_frame_tile( - &tile, + // Every re-code starts from this frame's OWN starting tables, never + // from where the first write left them: the second tile is the same + // symbol sequence plus new ones, so it must adapt from the same + // point the decoder will. + |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()); + let mut cdfs = start_cdfs.0.clone(); + crate::tile::sb_coeff_key_frame_tile_cdfs( + mi_cols, + mi_rows, + base_q_idx, + &superblocks, + tx_select, + &mut cdfs, + ) + }, + |lf, cdef, h, tile, lr| { + crate::decode::decode_key_frame_tile_lr( + tile, h.mi_cols, h.mi_rows, base_q_idx, @@ -3133,6 +3179,7 @@ pub(crate) fn encode_key_frame_inner( h.reduced_tx_set, h.allow_screen_content_tools, h.allow_intrabc, + lr, fctx, ) }, @@ -3162,6 +3209,7 @@ pub(crate) fn encode_key_frame_inner( start_cdfs, loop_filter: header.loop_filter, cdef: header.cdef, + loop_restoration: header.loop_restoration, }) } @@ -3185,8 +3233,21 @@ fn pick_and_apply_filters( chroma: &mut [Plane<'_>; 2], source: [&[u8]; 3], search: bool, + // The coded tile, replaced in place when the search chooses a per-64x64 + // `cdef_idx` list (`cdef_bits > 0`): those literals live in the tile + // payload, so the tile is written a second time under `recode` and the + // winner re-decoded from it. + tile: &mut Vec, + lambda: f64, fctx: &crate::decode::FrameCtx, - decode: impl Fn(&LoopFilterParams, &CdefParams, &FrameHeader) -> Result, + recode: impl Fn(u8, usize, &[u8], &[Option]) -> Result>, + decode: impl Fn( + &LoopFilterParams, + &CdefParams, + &FrameHeader, + &[u8], + &LoopRestorationParams, + ) -> Result, ) -> Result<()> { if !search { return Ok(()); @@ -3196,9 +3257,14 @@ fn pick_and_apply_filters( // libaom `av1_pick_filter_level`'s sibling `av1_cdef_search`: // `cdef_damping = 3 + (base_qindex >> 6)`, never searched. let damping = 3 + (header.quantization.base_q_idx >> 6); + let (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(); // Every candidate scores the same coded tile: decode it once and re-run // the filters alone for the rest (`crate::decode::FilterReplay`, 24% of - // the encoder's profile before this). + // the encoder's profile before this). The per-64x64 error the CDEF + // preset search reads comes off the REPLAYED picture, which is the same + // picture a decode produces -- that is what the replay is pinned on. crate::decode::clear_filter_replay(); let search_result = crate::filter_search::pick_filters( |lf, cdef| { @@ -3206,17 +3272,80 @@ fn pick_and_apply_filters( return Ok(picture); } crate::decode::arm_filter_replay(); - decode(lf, cdef, &hdr) + decode(lf, cdef, &hdr, tile, &none_lr) }, source, luma.width, (fw, fh), damping, + (sb_cols, sb_rows), + lambda, ); crate::decode::clear_filter_replay(); - let (lf, cdef, filtered) = search_result?; + let (lf, cdef, idx_grid, picture) = search_result?; header.loop_filter = lf; header.cdef = cdef; + // spec 7.17: loop restoration. Its per-unit filters live in the TILE, not + // in the frame header, so a re-decode under candidate parameters cannot + // search them the way deblocking and CDEF are searched above. What the + // decoder hands back instead is its own filter chain's intermediates + // (`crate::decode::FrameCtx::capture_stages`), and the search runs on + // those, through the decoder's own Wiener kernel. + // + // The capture rides the decode this stage was already going to do: the + // re-decode of the `cdef_idx` tile when there is one, and otherwise one + // decode of the tile as it stands. That decode's header still says + // `RESTORE_NONE`, so the decoder takes no pre-CDEF snapshot and the + // post-CDEF picture stands in for it at LR's 3-row stripe borders -- + // an approximation inside the SEARCH only; the reconstruction this + // function ends up splicing is always a real decode of the real tile. + let lr_on = restoration_enabled(); + fctx.capture_stages.set(lr_on); + let mut filtered = if idx_grid.is_empty() { + if lr_on { + decode(&lf, &cdef, &hdr, tile, &none_lr)? + } else { + picture + } + } else { + let coded = recode(cdef.bits, sb_cols, &idx_grid, &[])?; + let picture = decode(&lf, &cdef, &hdr, &coded, &none_lr)?; + *tile = coded; + picture + }; + fctx.capture_stages.set(false); + let mut lr = LoopRestorationParams::default(); + if lr_on { + let mut want = LoopRestorationParams { + loop_restoration_size: [64, 64, 64], + uses_lr: true, + ..LoopRestorationParams::default() + }; + want.frame_restoration_type[0] = ec_av1_syntax::RestorationType::Wiener; + let units = match crate::decode::take_filter_stages(fctx) { + Some(stages) => crate::filter_search::pick_restoration( + &stages, + source[0], + luma.width, + (fw, fh), + &want, + lambda, + fctx, + ), + None => Vec::new(), + }; + // A frame no unit restores keeps `RESTORE_NONE` on every plane + // rather than paying ~1 bit per 64x64 for a tile full of + // `restore_wiener = 0` symbols (the BD gate saw exactly that on the + // clip whose units never take a filter). + if units.iter().any(Option::is_some) { + let coded = recode(cdef.bits, sb_cols, &idx_grid, &units)?; + filtered = decode(&lf, &cdef, &hdr, &coded, &want)?; + *tile = coded; + lr = want; + } + } + 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); @@ -4388,13 +4517,14 @@ pub(crate) fn encode_inter_frame( // stores its end-of-tile tables with the counts reset (spec 7.20) and the // next frame's writer starts from them -- exactly what // `crate::stream::stored_cdfs_for` hands the decoder. + let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows); let mut cdfs = start_cdfs .cloned() .unwrap_or_else(|| crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx))); let start_cdfs = CdfSnapshot(cdfs.clone()); - let tile = crate::tile::sb_coeff_inter_frame_tile_cdfs( - header.mi_cols, - header.mi_rows, + let mut tile = crate::tile::sb_coeff_inter_frame_tile_cdfs( + mi_cols, + mi_rows, base_q_idx, &blocks, tx_select, @@ -4408,6 +4538,7 @@ pub(crate) fn encode_inter_frame( // reference whose height is not the header's own `frame_height` (spec // 7.9's compatible-size rule), and the chained-decode round trips prove // the two predict identically. + let end_cdfs = std::cell::RefCell::new(cdfs); let (fw, fh) = (header.frame_width as usize, header.frame_height as usize); let trial_ref = if (reference.width, reference.height) == (fw, fh) { reference.clone() @@ -4454,6 +4585,12 @@ pub(crate) fn encode_inter_frame( refs[4] = trial_golden.as_ref(); refs[7] = trial_altref.as_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, @@ -4464,10 +4601,33 @@ pub(crate) fn encode_inter_frame( // `TxMode::Select` too (it used to skip and leave every inter frame // unfiltered once Select became the default). true, + &mut tile, + search.lambda, fctx, - |lf, cdef, h| { - crate::decode::decode_inter_frame_tile( - &tile, + // As in `encode_key_frame_inner`, but this frame's end-of-tile tables + // are what the NEXT frame writes from, so the winning re-code + // publishes its own into `end_cdfs` -- the first write's are stale + // the moment a second tile is coded. + |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()); + let mut cdfs = start_cdfs.0.clone(); + let coded = crate::tile::sb_coeff_inter_frame_tile_cdfs( + mi_cols, + mi_rows, + base_q_idx, + &blocks, + tx_select, + &mut cdfs, + ); + if coded.is_ok() { + *end_cdfs.borrow_mut() = cdfs; + } + coded + }, + |lf, cdef, h, tile, lr| { + crate::decode::decode_inter_frame_tile_lr( + tile, h.mi_cols, h.mi_rows, base_q_idx, @@ -4482,6 +4642,7 @@ pub(crate) fn encode_inter_frame( seq.enable_dual_filter, h.reference_select, tx_select, + lr, // The trial decode re-reads the tile the writer just wrote, // so it starts from the same tables the writer did (this // frame's `start_cdfs`), not from the defaults. @@ -4490,6 +4651,7 @@ pub(crate) fn encode_inter_frame( ) }, )?; + let mut cdfs = end_cdfs.into_inner(); cdfs.reset_counts(); let next_cdfs = CdfSnapshot(cdfs); let mut stream = temporal_delimiter(); @@ -4516,6 +4678,7 @@ pub(crate) fn encode_inter_frame( next_cdfs, loop_filter: header.loop_filter, cdef: header.cdef, + loop_restoration: header.loop_restoration, }) } @@ -7319,9 +7482,18 @@ mod tests { /// /// The BD gate above measures quality, which a speed lane can move by a /// hair without failing anything; this pins the streams themselves. - /// Every number below was measured 2026-09-06 (lane-av1fwd) and is - /// identical at `a6649c4e`, the merge before that lane's three exact - /// speed steps. + /// Re-measured on the lane-av1lr merge with main d5fc99e0: the per-64x64 + /// `cdef_idx` literals and the per-unit loop restoration syntax are new + /// bits in the tile, so the streams move (q=150 7416 -> 7458 bytes, + /// q=60 27927 -> 27807 -- the low-rate frame pays for the syntax, the + /// high-rate one more than earns it back). + /// + /// Every number below was measured 2026-09-06: first on lane-av1fwd + /// (whose three speed steps left them identical to `a6649c4e`'s), then + /// re-measured on the lane-av1lr merge, which legitimately moves them -- + /// per-64x64 `cdef_idx` literals and the per-unit loop restoration + /// syntax are new bits in the tile, and both streams came out SMALLER + /// (7823 -> 7796, 28189 -> 28182 bytes) for it. #[test] fn the_encoders_own_streams_are_byte_identical_to_their_pins() { if !have_ffmpeg() { @@ -7343,7 +7515,7 @@ mod tests { }) }; let pins: [(u8, usize, u64); 2] = - [(150, 7416, 0x75632db72a63d5f1), (60, 27927, 0xb63a984f521b7341)]; + [(150, 7458, 0x7eb2_33c6_bd96_3baf), (60, 27807, 0xeee0_f1e5_e099_46bd)]; for (q, bytes, hash) in pins { let encoded = encode_sequence(&source, q, 0.5).unwrap(); assert_eq!( @@ -7558,6 +7730,37 @@ mod tests { mean(|l| l.2.0), mean(|l| l.2.1), ); + // How many strength presets each frame's CDEF list carried and + // how the 64x64 units spread over them (lane-av1lr): `bits 0` + // everywhere would mean the per-unit choice never fires. + let presets = crate::filter_search::take_cdef_presets(); + let mut by_bits = [0usize; 4]; + for (b, _) in &presets { + by_bits[usize::from(*b)] += 1; + } + let units: usize = presets.iter().flat_map(|(_, c)| c).sum(); + let on_extra: usize = presets + .iter() + .flat_map(|(_, c)| c.iter().skip(1)) + .sum(); + eprintln!( + "{name}: cdef_bits frames {}/{}/{}/{} (0/1/2/3); {} of {} 64x64 units \ + on a non-default preset ({:.1}%)", + by_bits[0], + by_bits[1], + by_bits[2], + by_bits[3], + on_extra, + 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 7a40e1b9..3c20d7b7 100644 --- a/crates/ec-av1/src/filter_search.rs +++ b/crates/ec-av1/src/filter_search.rs @@ -40,6 +40,20 @@ pub(crate) fn take_chosen_levels() -> Vec<((u8, u8), (u8, u8), (u8, u8))> { }) } +thread_local! { + /// Per frame, in coding order: the `cdef_bits` chosen and how many 64x64 + /// superblocks ended up on each strength preset -- the BD gate prints the + /// distribution once per clip (gate-blind-to-feature). + static PRESET_COUNTS: std::cell::RefCell)>> = + const { std::cell::RefCell::new(Vec::new()) }; +} + +/// Takes and clears [`PRESET_COUNTS`]. +#[allow(dead_code)] // read from the `#[cfg(test)]` BD gate +pub(crate) fn take_cdef_presets() -> Vec<(u8, Vec)> { + PRESET_COUNTS.with(|c| std::mem::take(&mut *c.borrow_mut())) +} + /// Squared error between a decoded plane and the source it was coded from, /// over the frame's own cropped `w x h` (the two planes have different /// strides: the source is the encoder's padded coding surface). @@ -55,6 +69,31 @@ fn plane_sse(dec: &[u16], dec_w: usize, src: &[u8], src_w: usize, w: usize, h: u sse } +/// [`plane_sse`], accumulated per CDEF unit instead of over the frame: `out` +/// is one entry per 64x64 SUPERBLOCK (stride `sb_cols`) and `unit` is the +/// unit side in this plane's own samples (64 for luma, 32 for 4:2:0 chroma), +/// which is what makes the luma and chroma sums land in the same slot. +fn unit_sse( + dec: &[u16], + dec_w: usize, + src: &[u8], + src_w: usize, + w: usize, + h: usize, + unit: usize, + sb_cols: usize, + out: &mut [u64], +) { + for row in 0..h { + let base = (row / unit) * sb_cols; + let (d, s) = (&dec[row * dec_w..][..w], &src[row * src_w..][..w]); + for (col, (&a, &b)) in d.iter().zip(s).enumerate() { + let diff = i64::from(a) - i64::from(b); + out[base + col / unit] += (diff * diff) as u64; + } + } +} + /// CDEF primary strengths tried (libaom's own range is 0..15 for 8-bit /// content) and the secondary ladder, whose only legal values are 0, 1, 2 /// and 4 -- 3 is not codeable (spec 5.9.19 codes a secondary strength of 4 @@ -82,6 +121,10 @@ struct Trial { picture: Picture, sse_y: u64, sse_uv: u64, + /// Luma + chroma error per 64x64 CDEF unit, in the tile writer's own + /// superblock raster order -- what the per-unit `cdef_idx` choice below + /// is made on. + sse64: Vec, } /// Picks this frame's deblocking levels and CDEF strengths and hands back @@ -111,8 +154,11 @@ pub(crate) fn pick_filters( src_w: usize, (fw, fh): (usize, usize), damping: u8, -) -> Result<(LoopFilterParams, CdefParams, Picture)> { + (sb_cols, sb_rows): (usize, usize), + lambda: f64, +) -> Result<(LoopFilterParams, CdefParams, Vec, Picture)> { let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2)); + let nsb = sb_cols * sb_rows; let mut trials: Vec = Vec::new(); let eval = |cand: Cand, trials: &mut Vec| -> Result { if let Some(i) = trials.iter().position(|t| t.cand == cand) { @@ -123,7 +169,11 @@ pub(crate) fn pick_filters( let sse_y = plane_sse(&picture.y, picture.width, source[0], src_w, fw, fh); let sse_uv = plane_sse(&picture.u, dec_cw, source[1], src_w / 2, cw, ch) + plane_sse(&picture.v, dec_cw, source[2], src_w / 2, cw, ch); - trials.push(Trial { cand, picture, sse_y, sse_uv }); + let mut sse64 = vec![0u64; nsb]; + unit_sse(&picture.y, picture.width, source[0], src_w, fw, fh, 64, sb_cols, &mut sse64); + unit_sse(&picture.u, dec_cw, source[1], src_w / 2, cw, ch, 32, sb_cols, &mut sse64); + unit_sse(&picture.v, dec_cw, source[2], src_w / 2, cw, ch, 32, sb_cols, &mut sse64); + trials.push(Trial { cand, picture, sse_y, sse_uv, sse64 }); Ok(trials.len() - 1) }; // One stage of the coordinate search: try `values` in the slot `set` @@ -168,11 +218,100 @@ pub(crate) fn pick_filters( stage(&mut best, &CDEF_SEC, |c, v| c.uv.1 = v, |t| t.sse_uv, &mut trials)?; CHOSEN.with(|c| c.borrow_mut().push(best)); + + // libaom `av1_cdef_search`'s shape, on the candidates this coordinate + // search already decoded: every trial that ran under the WINNING + // deblocking levels is a legal strength pair for this frame, and each + // one already carries its own per-64x64 error. Pick up to eight of them + // as the header's strength list and give every superblock the one that + // costs it least -- the `cdef_idx` literal the tile writer then codes + // (`crate::tile::arm_cdef_idx`). + let mut presets: Vec = vec![best]; + let pool: Vec = trials + .iter() + .map(|t| t.cand) + .filter(|c| c.lf == best.lf && *c != best) + .collect(); + // How often each pool candidate would win a superblock outright, which + // is the order the list is grown in (libaom picks its presets by the + // same per-unit histogram, not by frame-level error). + let sse_of = |c: &Cand| -> &Vec { + &trials + .iter() + .find(|t| t.cand == *c) + .expect("every pool candidate was evaluated") + .sse64 + }; + let mut counts = vec![0usize; pool.len()]; + let best_sse = sse_of(&best).clone(); + for sb in 0..nsb { + let mut winner = (best_sse[sb], usize::MAX); + for (i, c) in pool.iter().enumerate() { + if sse_of(c)[sb] < winner.0 { + winner = (sse_of(c)[sb], i); + } + } + if winner.1 != usize::MAX { + counts[winner.1] += 1; + } + } + let mut order: Vec = (0..pool.len()).collect(); + order.sort_by_key(|&i| std::cmp::Reverse(counts[i])); + presets.extend(order.iter().take(7).map(|&i| pool[i])); + // The cheapest list length: `bits` costs one literal per superblock plus + // twelve header bits per extra pair, and buys whatever per-unit error the + // wider choice removes. + let unit_min = |n: usize, sb: usize| -> u64 { + presets[..n].iter().map(|c| sse_of(c)[sb]).min().unwrap_or(0) + }; + let mut bits = 0u8; + let mut cost = best_sse.iter().sum::() as f64; + for b in 1..=3u8 { + let n = 1usize << b; + if n > presets.len() { + break; + } + let sse: u64 = (0..nsb).map(|sb| unit_min(n, sb)).sum(); + let c = sse as f64 + lambda * ((b as usize * nsb) as f64 + 12.0 * (n - 1) as f64); + if c < cost { + cost = c; + bits = b; + } + } + let grid: Vec = if bits == 0 { + Vec::new() + } else { + let n = 1usize << bits; + (0..nsb) + .map(|sb| { + (0..n) + .min_by_key(|&i| sse_of(&presets[i])[sb]) + .expect("at least one preset") as u8 + }) + .collect() + }; + let mut params = cdef(best, damping); + params.bits = bits; + for (i, c) in presets.iter().take(1usize << bits).enumerate() { + params.y_pri_strength[i] = c.y.0; + params.y_sec_strength[i] = c.y.1; + params.uv_pri_strength[i] = c.uv.0; + params.uv_sec_strength[i] = c.uv.1; + } + let mut counts_used = vec![0usize; 1usize << bits]; + for &g in &grid { + counts_used[usize::from(g)] += 1; + } + if grid.is_empty() { + counts_used = vec![nsb]; + } + PRESET_COUNTS.with(|c| c.borrow_mut().push((bits, counts_used))); + let win = trials .into_iter() .find(|t| t.cand == best) .expect("the winning candidate was evaluated"); - Ok((loop_filter(best), cdef(best, damping), win.picture)) + Ok((loop_filter(best), params, grid, win.picture)) } /// The header's `loop_filter_params` for one candidate. @@ -205,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 675cb1a2..381638d7 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 5b55e7d4..2f5eebf9 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -20,6 +20,163 @@ use crate::decode::{TXFM_CTX_INIT, txfm_partition_ctx_rect}; use crate::msac::SymbolEncoder; use crate::mvstack::{MiGrid, MiInfo, NO_REF1, find_mv_stack, mv16}; +// --------------------------------------------------------------------------- +// lane-av1lr: per-64x64 `cdef_idx` (spec 5.11.56, `read_cdef`). The decoder +// reads ONE `cdef_idx` literal per 64x64 superblock, at that superblock's +// first non-skip block, and only when the frame header's `cdef_bits > 0` +// (`crate::decode::maybe_read_cdef_idx`). The writers below mirror that from +// a plan the filter search hands over, kept in a thread-local rather than +// threaded through every `write_*` signature -- the same shape the decoder's +// own `FrameCtx::cdef_transmitted` uses, and the encoder codes one tile at a +// time on one thread. The plan is CONSUMED by the tile writer that runs next +// ([`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. + bits: u8, + /// Superblocks per row, the stride of `grid`. + sb_cols: usize, + /// One index per 64x64 superblock, in raster order. + grid: Vec, + /// The superblock whose literal was already written -- the decoder's + /// `cdef_transmitted`, which resets at every superblock and which coding + /// order (each superblock's blocks are contiguous) makes a single slot. + last: Option, +} + +thread_local! { + static CDEF_IDX: std::cell::RefCell> = + const { std::cell::RefCell::new(None) }; +} + +/// Arms the next tile write with one `cdef_idx` per 64x64 superblock. +/// `bits == 0` disarms (the header codes a single strength pair, so the tile +/// carries no literal at all). +pub(crate) fn arm_cdef_idx(bits: u8, sb_cols: usize, grid: Vec) { + CDEF_IDX.with(|c| { + *c.borrow_mut() = (bits > 0).then(|| CdefIdxPlan { bits, sb_cols, grid, last: None }); + }); +} + +/// Clears the armed plan when the tile writer that consumed it returns. +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); + } +} + +/// `read_cdef`'s write side, called right after every block's `skip` symbol: +/// writes this superblock's `cdef_idx` literal the first time a non-skip +/// block of it is coded. `mi` is the block's own position in 4x4 mode-info +/// units. +fn write_cdef_idx(enc: &mut SymbolEncoder, mi: (usize, usize), skip: bool) { + if skip { + return; + } + CDEF_IDX.with(|c| { + let mut plan = c.borrow_mut(); + let Some(plan) = plan.as_mut() else { return }; + let sb = (mi.0 / 16) * plan.sb_cols + (mi.1 / 16); + if plan.last == Some(sb) { + return; + } + plan.last = Some(sb); + enc.literal( + u32::from(plan.grid.get(sb).copied().unwrap_or(0)), + u32::from(plan.bits), + ); + }); +} + /// round-4 av1-truesize debugging aid: prints `msg()` to stderr when the /// `EC_RNG` environment variable is set, mirroring the `EC_PART`/`EC_TOK` /// trace `/tmp/libaom-src`'s debug `aomdec` build already emits under the @@ -1085,6 +1242,8 @@ pub(crate) fn sb_coeff_key_frame_tile_cdfs( tx_select: bool, cdfs: &mut Cdfs, ) -> Result> { + // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path. + let _cdef_idx = CdefIdxGuard; check_blocks(mi_cols, mi_rows)?; let (cols, rows) = block_grid(mi_cols, mi_rows); let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2)); @@ -1148,6 +1307,7 @@ pub(crate) fn sb_coeff_key_frame_tile_cdfs( 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(|| { @@ -1535,9 +1695,13 @@ fn write_intra_mode( above_mode: usize, left_mode: usize, cfl: bool, + // This block's own position in 4x4 mode-info units, for the `cdef_idx` + // literal that follows the `skip` symbol (see [`write_cdef_idx`]). + mi: (usize, usize), ) -> usize { let mode = usize::from(block.mode); enc.symbol(0, &mut cdfs.skip[0]); + write_cdef_idx(enc, mi, false); enc.symbol( mode, &mut cdfs.kf_y_mode[INTRA_MODE_CTX[above_mode]][INTRA_MODE_CTX[left_mode]], @@ -1585,6 +1749,7 @@ fn write_block( all_scans: &[Vec; 4], ) -> Result<()> { let (r, c) = at; + let at_mi = (r * (SUB / MI), c * (SUB / MI)); let mode = write_intra_mode( enc, cdfs, @@ -1592,8 +1757,8 @@ fn write_block( neighbours.above_mode[c], neighbours.left_mode[r], cfl, + at_mi, ); - let at_mi = (r * (SUB / MI), c * (SUB / MI)); let split = if tx_select { let tx = write_luma_select( enc, @@ -1667,7 +1832,7 @@ fn write_leaf8( // true first divergence (a differently-sized alphabet under the same // DC_PRED decision desyncs the coder even though the decoded mode is // unchanged). - let mode = write_intra_mode(enc, cdfs, block, above_mode, left_mode, true); + let mode = write_intra_mode(enc, cdfs, block, above_mode, left_mode, true, leaf_mi); let planes = [TxbSet::Luma8, TxbSet::Chroma4, TxbSet::Chroma4]; let split = if tx_select { let tx = write_luma_select( @@ -3004,6 +3169,8 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( tx_select: bool, cdfs: &mut Cdfs, ) -> Result> { + // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path. + let _cdef_idx = CdefIdxGuard; check_blocks(mi_cols, mi_rows)?; // `block_grid`'s ceiling, not a plain division: a true frame size that is // not a whole number of 32x32 blocks (or of 64x64 superblocks) still has @@ -3071,6 +3238,7 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( 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 @@ -3318,6 +3486,7 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( let skip_ctx = usize::from(neighbours.above_skip[mi_c]) + usize::from(neighbours.left_skip[mi_r]); enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]); + write_cdef_idx(&mut enc, (mi_r, mi_c), block.skip); let is_inter = block.inter.is_some(); let (above_inter, left_inter) = @@ -3522,6 +3691,7 @@ fn write_inter_frame_leaf( let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI)); let skip_ctx = usize::from(neighbours.above_skip[mi_c]) + usize::from(neighbours.left_skip[mi_r]); enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]); + write_cdef_idx(enc, (mi_r, mi_c), block.skip); let (has_above, has_left) = (r > 0, c > 0); let (above_inter, left_inter) = (neighbours.above_inter[mi_c], neighbours.left_inter[mi_r]); @@ -3715,6 +3885,7 @@ fn write_inter_frame_leaf8( let left_inter = neighbours.left_inter[leaf_mi.0]; let skip_ctx = usize::from(above_skip) + usize::from(left_skip); enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]); + write_cdef_idx(enc, leaf_mi, block.skip); let (has_above, has_left) = (leaf_mi.0 > 0, leaf_mi.1 > 0); let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);