forge
Explore
Log in

Don't you dare go Hollow

wip(av1): loop restoration unit syntax + search, snapshot at the agent cap (may not compile)

Browse files at this commit

c3b0776ed9bb682ff6674d485d91afc426e8cf4eAhmet Kaan GümüşParent: 93429cb
crates/ec-av1/src/decode.rsmodified+141 -13
@@ -40,7 +40,34 @@ use ec_core::{Error, Result};
40 ///40 ///
41 /// `Cell`/`RefCell` make this `!Sync` on purpose: a `FrameCtx` belongs to41 /// `Cell`/`RefCell` make this `!Sync` on purpose: a `FrameCtx` belongs to
42 /// exactly one thread's decode, and is never shared between workers.42 /// exactly one thread's decode, and is never shared between workers.
43+/// One frame's in-loop filter intermediates, as [`FrameCtx::capture_stages`]
44+/// asks for them: each plane's post-deblock (pre-CDEF) and post-CDEF
45+/// (pre-restoration) samples, at the decoder's own plane stride.
46+pub(crate) struct FilterStages {
47+ /// Post-deblock, pre-CDEF planes (Y, U, V).
48+ pub(crate) deblocked: [Vec<u16>; 3],
49+ /// Post-CDEF, pre-restoration planes (Y, U, V).
50+ pub(crate) cdefed: [Vec<u16>; 3],
51+ /// Each plane's stride (and so its width in the buffers above).
52+ pub(crate) stride: [usize; 3],
53+}
54+
55+/// Takes whatever the last capturing decode left (see
56+/// [`FrameCtx::capture_stages`]).
57+#[allow(dead_code)] // read from the encoder's loop restoration search
58+pub(crate) fn take_filter_stages(fctx: &FrameCtx) -> Option<FilterStages> {
59+ fctx.stages.borrow_mut().take()
60+}
61+
43 pub(crate) struct FrameCtx {62 pub(crate) struct FrameCtx {
63+ /// lane-av1lr: when set, the frame filter chain leaves its post-deblock
64+ /// and post-CDEF planes in [`FrameCtx::stages`] for the ENCODER's loop
65+ /// restoration search (spec 7.17 reads both: the stripe interior from
66+ /// the post-CDEF plane, its 3-row border from the post-deblock one).
67+ /// Off for every decode but that search, and off it costs one bool read
68+ /// per frame and not a single copy.
69+ pub(crate) capture_stages: std::cell::Cell<bool>,
70+ pub(crate) stages: std::cell::RefCell<Option<FilterStages>>,
44 pub(crate) sb128_flag: std::cell::Cell<bool>,71 pub(crate) sb128_flag: std::cell::Cell<bool>,
45 pub(crate) cdef_bits: std::cell::Cell<u8>,72 pub(crate) cdef_bits: std::cell::Cell<u8>,
46 pub(crate) bit_depth: std::cell::Cell<u8>,73 pub(crate) bit_depth: std::cell::Cell<u8>,
@@ -130,6 +157,8 @@ impl FrameCtx {
130 superres: std::cell::Cell::new((0, 8)),157 superres: std::cell::Cell::new((0, 8)),
131 cdef_transmitted: std::cell::Cell::new(false),158 cdef_transmitted: std::cell::Cell::new(false),
132 cdef_sb_cols: std::cell::Cell::new(0),159 cdef_sb_cols: std::cell::Cell::new(0),
160+ capture_stages: std::cell::Cell::new(false),
161+ stages: std::cell::RefCell::new(None),
133 cdef_idx_grid: std::cell::RefCell::new(Vec::new()),162 cdef_idx_grid: std::cell::RefCell::new(Vec::new()),
134 delta_q_present: std::cell::Cell::new(false),163 delta_q_present: std::cell::Cell::new(false),
135 delta_q_res: std::cell::Cell::new(1),164 delta_q_res: std::cell::Cell::new(1),
@@ -20431,6 +20460,37 @@ fn apply_cdef(
20431 scratch_return(src_v);20460 scratch_return(src_v);
20432 }20461 }
20433 20462
20463+/// [`FrameCtx::capture_stages`]'s write side, called between CDEF and loop
20464+/// restoration on both tile paths: hands the encoder's restoration search the
20465+/// two pictures spec 7.17 filters from. `deblocked` is the decoder's own
20466+/// stripe-boundary snapshot ([`plane_snapshot`], only the rows LR reads), so
20467+/// a capture is worth three plane copies and nothing else -- and when the
20468+/// capture flag is off (every decode but that search) it is worth a bool.
20469+fn capture_stages(
20470+ y: &PlaneBuf<'_>,
20471+ u: &PlaneBuf<'_>,
20472+ v: &PlaneBuf<'_>,
20473+ deblocked: Option<&(PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>,
20474+ fctx: &FrameCtx,
20475+) {
20476+ if !fctx.capture_stages.get() {
20477+ return;
20478+ }
20479+ // Without an active restoration type the decoder took no pre-CDEF
20480+ // snapshot; the post-CDEF plane then stands in for it, which is exact
20481+ // everywhere but LR's own 3-row stripe borders (the encoder's search
20482+ // always asks with a type set, so this is the defensive arm).
20483+ let db = |i: usize, p: &PlaneBuf<'_>| match deblocked {
20484+ Some((a, b, c)) => [a, b, c][i].data.to_vec(),
20485+ None => p.data.to_vec(),
20486+ };
20487+ *fctx.stages.borrow_mut() = Some(FilterStages {
20488+ deblocked: [db(0, y), db(1, u), db(2, v)],
20489+ cdefed: [y.data.to_vec(), u.data.to_vec(), v.data.to_vec()],
20490+ stride: [y.width, u.width, v.width],
20491+ });
20492+}
20493+
20434 /// Spec 7.17: loop restoration, run after [`apply_cdef`] (a sibling lane's20494 /// Spec 7.17: loop restoration, run after [`apply_cdef`] (a sibling lane's
20435 /// ordering note: libaom also runs `superres_post_decode` between the two,20495 /// ordering note: libaom also runs `superres_post_decode` between the two,
20436 /// but this decoder never implements super-resolution, so there is nothing20496 /// but this decoder never implements super-resolution, so there is nothing
@@ -20546,6 +20606,34 @@ pub(crate) fn decode_key_frame_tile(
20546 reduced_tx_set: bool,20606 reduced_tx_set: bool,
20547 allow_screen_content_tools: bool,20607 allow_screen_content_tools: bool,
20548 allow_intrabc: bool, fctx: &crate::decode::FrameCtx,20608 allow_intrabc: bool, fctx: &crate::decode::FrameCtx,
20609+) -> Result<Picture> {
20610+ decode_key_frame_tile_lr(
20611+ data, mi_cols, mi_rows, base_q_idx, frame_width, frame_height, enable_filter_intra,
20612+ cdef, loop_filter, tx_select, reduced_tx_set, allow_screen_content_tools, allow_intrabc,
20613+ &LoopRestorationParams::default(), fctx,
20614+ )
20615+}
20616+
20617+/// [`decode_key_frame_tile`] with this frame header's own `lr_params` (spec
20618+/// 5.9.20) instead of the no-restoration default -- the per-unit filters
20619+/// themselves live in the tile payload, so the header is all this needs.
20620+#[allow(clippy::too_many_arguments)]
20621+pub(crate) fn decode_key_frame_tile_lr(
20622+ data: &[u8],
20623+ mi_cols: u32,
20624+ mi_rows: u32,
20625+ base_q_idx: u8,
20626+ frame_width: u32,
20627+ frame_height: u32,
20628+ enable_filter_intra: bool,
20629+ cdef: &CdefParams,
20630+ loop_filter: &LoopFilterParams,
20631+ tx_select: bool,
20632+ reduced_tx_set: bool,
20633+ allow_screen_content_tools: bool,
20634+ allow_intrabc: bool,
20635+ lr: &LoopRestorationParams,
20636+ fctx: &crate::decode::FrameCtx,
20549 ) -> Result<Picture> {20637 ) -> Result<Picture> {
20550 let delta = DeltaParams::default();20638 let delta = DeltaParams::default();
20551 let single_tile = TileInfo {20639 let single_tile = TileInfo {
@@ -20566,7 +20654,7 @@ pub(crate) fn decode_key_frame_tile(
20566 false,20654 false,
20567 cdef,20655 cdef,
20568 loop_filter,20656 loop_filter,
20569- &LoopRestorationParams::default(),20657+ lr,
20570 None,20658 None,
20571 tx_select,20659 tx_select,
20572 reduced_tx_set,20660 reduced_tx_set,
@@ -22883,6 +22971,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
22883 );22971 );
22884 dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v);22972 dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v);
22885 dump_stage16("EC_AV1_POSTCDEF_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize);22973 dump_stage16("EC_AV1_POSTCDEF_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize);
22974+ capture_stages(&y, &u, &v, deblocked.as_ref(), fctx);
22886 // spec 7.16 (libaom `superres_post_decode`, decodeframe.c: called22975 // spec 7.16 (libaom `superres_post_decode`, decodeframe.c: called
22887 // between `av1_cdef_frame` and `av1_loop_restoration_filter_frame`):22976 // between `av1_cdef_frame` and `av1_loop_restoration_filter_frame`):
22888 // the horizontal upscale runs HERE -- after CDEF, before loop22977 // the horizontal upscale runs HERE -- after CDEF, before loop
@@ -32639,6 +32728,36 @@ pub(crate) fn decode_inter_frame_tile(
32639 // stale header, second instance).32728 // stale header, second instance).
32640 tx_select: bool,32729 tx_select: bool,
32641 fctx: &crate::decode::FrameCtx,32730 fctx: &crate::decode::FrameCtx,
32731+) -> Result<Picture> {
32732+ decode_inter_frame_tile_lr(
32733+ data, mi_cols, mi_rows, base_q_idx, frame_width, frame_height, refpix, cdef,
32734+ loop_filter, allow_high_precision_mv, force_integer_mv, interp_fixed,
32735+ enable_dual_filter, reference_select, tx_select,
32736+ &LoopRestorationParams::default(), fctx,
32737+ )
32738+}
32739+
32740+/// [`decode_inter_frame_tile`] with this frame header's own `lr_params`, the
32741+/// inter sibling of [`decode_key_frame_tile_lr`].
32742+#[allow(clippy::too_many_arguments)]
32743+pub(crate) fn decode_inter_frame_tile_lr(
32744+ data: &[u8],
32745+ mi_cols: u32,
32746+ mi_rows: u32,
32747+ base_q_idx: u8,
32748+ frame_width: u32,
32749+ frame_height: u32,
32750+ refpix: &RefPix<'_>,
32751+ cdef: &CdefParams,
32752+ loop_filter: &LoopFilterParams,
32753+ allow_high_precision_mv: bool,
32754+ force_integer_mv: bool,
32755+ interp_fixed: Option<mc::InterpFilterKind>,
32756+ enable_dual_filter: bool,
32757+ reference_select: bool,
32758+ tx_select: bool,
32759+ lr: &LoopRestorationParams,
32760+ fctx: &crate::decode::FrameCtx,
32642 ) -> Result<Picture> {32761 ) -> Result<Picture> {
32643 let single_tile = TileInfo {32762 let single_tile = TileInfo {
32644 mi_col_starts: vec![0, mi_cols],32763 mi_col_starts: vec![0, mi_cols],
@@ -32657,7 +32776,7 @@ pub(crate) fn decode_inter_frame_tile(
32657 refpix,32776 refpix,
32658 cdef,32777 cdef,
32659 loop_filter,32778 loop_filter,
32660- &LoopRestorationParams::default(),32779+ lr,
32661 None,32780 None,
32662 allow_high_precision_mv,32781 allow_high_precision_mv,
32663 force_integer_mv,32782 force_integer_mv,
@@ -35498,6 +35617,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
35498 }35617 }
35499 dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v);35618 dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v);
35500 dump_stage16("EC_AV1_POSTCDEF_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize);35619 dump_stage16("EC_AV1_POSTCDEF_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize);
35620+ capture_stages(&y, &u, &v, deblocked.as_ref(), fctx);
35501 // spec 7.16 (libaom `superres_post_decode`, decodeframe.c: called35621 // spec 7.16 (libaom `superres_post_decode`, decodeframe.c: called
35502 // between `av1_cdef_frame` and `av1_loop_restoration_filter_frame`):35622 // between `av1_cdef_frame` and `av1_loop_restoration_filter_frame`):
35503 // the horizontal upscale runs HERE -- after CDEF, before loop35623 // the horizontal upscale runs HERE -- after CDEF, before loop
@@ -36625,9 +36745,10 @@ mod tests {
36625 tx_select,36745 tx_select,
36626 loop_filter,36746 loop_filter,
36627 cdef,36747 cdef,
36748+ loop_restoration,
36628 ..36749 ..
36629 }: Encoded = crate::encode::encode_key_frame_with_modes_with_ctx(&picture, 40, 0.0, modes, fctx).unwrap();36750 }: Encoded = crate::encode::encode_key_frame_with_modes_with_ctx(&picture, 40, 0.0, modes, fctx).unwrap();
36630- let decoded = decode_key_frame_tile(36751+ let decoded = decode_key_frame_tile_lr(
36631 &tile,36752 &tile,
36632 mi_cols,36753 mi_cols,
36633 mi_rows,36754 mi_rows,
@@ -36640,7 +36761,8 @@ mod tests {
36640 tx_select,36761 tx_select,
36641 true,36762 true,
36642 false,36763 false,
36643- false, fctx,36764+ false,
36765+ &loop_restoration, fctx,
36644 )36766 )
36645 .unwrap();36767 .unwrap();
36646 assert_eq!(decoded.width, w, "{w}x{h}: decoded width");36768 assert_eq!(decoded.width, w, "{w}x{h}: decoded width");
@@ -36994,7 +37116,7 @@ mod tests {
36994 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();37116 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
36995 let (coded_w, coded_h) = ffprobe_size(&encoded.stream);37117 let (coded_w, coded_h) = ffprobe_size(&encoded.stream);
36996 let ffmpeg_decoded = ffmpeg_decode(&encoded.stream, coded_w as usize, coded_h as usize);37118 let ffmpeg_decoded = ffmpeg_decode(&encoded.stream, coded_w as usize, coded_h as usize);
36997- let ours = decode_key_frame_tile(37119+ let ours = decode_key_frame_tile_lr(
36998 &encoded.tile,37120 &encoded.tile,
36999 encoded.mi_cols,37121 encoded.mi_cols,
37000 encoded.mi_rows,37122 encoded.mi_rows,
@@ -37007,7 +37129,8 @@ mod tests {
37007 encoded.tx_select,37129 encoded.tx_select,
37008 true,37130 true,
37009 false,37131 false,
37010- false, fctx,37132+ false,
37133+ &encoded.loop_restoration, fctx,
37011 )37134 )
37012 .unwrap();37135 .unwrap();
37013 assert_eq!(ours.y, ffmpeg_decoded.y, "{width}x{height}: luma vs ffmpeg");37136 assert_eq!(ours.y, ffmpeg_decoded.y, "{width}x{height}: luma vs ffmpeg");
@@ -37037,7 +37160,7 @@ mod tests {
37037 gate's premise moved, not the decoder"37160 gate's premise moved, not the decoder"
37038 );37161 );
37039 let decode = |tx_select: bool| {37162 let decode = |tx_select: bool| {
37040- decode_key_frame_tile(37163+ decode_key_frame_tile_lr(
37041 &encoded.tile,37164 &encoded.tile,
37042 encoded.mi_cols,37165 encoded.mi_cols,
37043 encoded.mi_rows,37166 encoded.mi_rows,
@@ -37051,6 +37174,7 @@ mod tests {
37051 true,37174 true,
37052 false,37175 false,
37053 false,37176 false,
37177+ &encoded.loop_restoration,
37054 fctx,37178 fctx,
37055 )37179 )
37056 };37180 };
@@ -37121,7 +37245,7 @@ mod tests {
37121 assert_eq!(encoded.frames.len(), 4);37245 assert_eq!(encoded.frames.len(), 4);
37122 37246
37123 let key = &encoded.frames[0];37247 let key = &encoded.frames[0];
37124- let mut reference = decode_key_frame_tile(37248+ let mut reference = decode_key_frame_tile_lr(
37125 &key.tile,37249 &key.tile,
37126 key.mi_cols,37250 key.mi_cols,
37127 key.mi_rows,37251 key.mi_rows,
@@ -37134,7 +37258,8 @@ mod tests {
37134 key.tx_select,37258 key.tx_select,
37135 true,37259 true,
37136 false,37260 false,
37137- false, fctx,37261+ false,
37262+ &key.loop_restoration, fctx,
37138 )37263 )
37139 .unwrap();37264 .unwrap();
37140 assert_eq!(37265 assert_eq!(
@@ -37151,7 +37276,7 @@ mod tests {
37151 );37276 );
37152 37277
37153 for (i, frame) in encoded.frames.iter().enumerate().skip(1) {37278 for (i, frame) in encoded.frames.iter().enumerate().skip(1) {
37154- let decoded = decode_inter_frame_tile(37279+ let decoded = decode_inter_frame_tile_lr(
37155 &frame.tile,37280 &frame.tile,
37156 frame.mi_cols,37281 frame.mi_cols,
37157 frame.mi_rows,37282 frame.mi_rows,
@@ -37167,6 +37292,7 @@ mod tests {
37167 false,37292 false,
37168 false,37293 false,
37169 frame.tx_select,37294 frame.tx_select,
37295+ &frame.loop_restoration,
37170 fctx,37296 fctx,
37171 )37297 )
37172 .unwrap();37298 .unwrap();
@@ -37443,7 +37569,7 @@ mod tests {
37443 ffmpeg_decode_sequence(&encoded.stream, coded_w as usize, coded_h as usize, 3);37569 ffmpeg_decode_sequence(&encoded.stream, coded_w as usize, coded_h as usize, 3);
37444 37570
37445 let key = &encoded.frames[0];37571 let key = &encoded.frames[0];
37446- let mut reference = decode_key_frame_tile(37572+ let mut reference = decode_key_frame_tile_lr(
37447 &key.tile,37573 &key.tile,
37448 key.mi_cols,37574 key.mi_cols,
37449 key.mi_rows,37575 key.mi_rows,
@@ -37456,13 +37582,14 @@ mod tests {
37456 key.tx_select,37582 key.tx_select,
37457 true,37583 true,
37458 false,37584 false,
37459- false, fctx,37585+ false,
37586+ &key.loop_restoration, fctx,
37460 )37587 )
37461 .unwrap();37588 .unwrap();
37462 assert_eq!(reference.y, ffmpeg_frames[0].y, "frame 0 luma vs ffmpeg");37589 assert_eq!(reference.y, ffmpeg_frames[0].y, "frame 0 luma vs ffmpeg");
37463 37590
37464 for (i, frame) in encoded.frames.iter().enumerate().skip(1) {37591 for (i, frame) in encoded.frames.iter().enumerate().skip(1) {
37465- let decoded = decode_inter_frame_tile(37592+ let decoded = decode_inter_frame_tile_lr(
37466 &frame.tile,37593 &frame.tile,
37467 frame.mi_cols,37594 frame.mi_cols,
37468 frame.mi_rows,37595 frame.mi_rows,
@@ -37478,6 +37605,7 @@ mod tests {
37478 false,37605 false,
37479 false,37606 false,
37480 frame.tx_select,37607 frame.tx_select,
37608+ &frame.loop_restoration,
37481 fctx,37609 fctx,
37482 )37610 )
37483 .unwrap();37611 .unwrap();
crates/ec-av1/src/encode.rsmodified+117 -15
@@ -19,8 +19,8 @@
19 use crate::decode::WithRef;19 use crate::decode::WithRef;
20 use ec_av1_syntax::sequence::{ColorConfig, OperatingPoint, SequenceHeader};20 use ec_av1_syntax::sequence::{ColorConfig, OperatingPoint, SequenceHeader};
21 use ec_av1_syntax::{21 use ec_av1_syntax::{
22- CdefParams, ChromaSamplePosition, FrameHeader, FrameType, LoopFilterParams, PRIMARY_REF_NONE,22+ CdefParams, ChromaSamplePosition, FrameHeader, FrameType, LoopFilterParams,
23- QuantizationParams, TileInfo, TxMode,23+ LoopRestorationParams, PRIMARY_REF_NONE, QuantizationParams, TileInfo, TxMode,
24 };24 };
25 use ec_core::{Error, Result};25 use ec_core::{Error, Result};
26 26
@@ -190,6 +190,20 @@ fn split_inter_blocks() -> bool {
190 }190 }
191 }191 }
192 192
193+/// Whether the encoder searches loop restoration at all (spec 7.17): one
194+/// Wiener filter per 64x64 luma restoration unit, picked from
195+/// [`crate::filter_search::WIENER_CANDIDATES`]. Swept by `EC_AV1_LR` in a
196+/// test build, like [`lambda_scale`].
197+const RESTORATION: bool = true;
198+
199+/// [`RESTORATION`], or what `EC_AV1_LR` names in a test build.
200+fn restoration_enabled() -> bool {
201+ match std::env::var("EC_AV1_LR").ok() {
202+ Some(v) if cfg!(test) => v != "0",
203+ _ => RESTORATION,
204+ }
205+}
206+
193 /// libaom's `partition_search_breakout` shape: how many non-zero luma207 /// libaom's `partition_search_breakout` shape: how many non-zero luma
194 /// coefficients per 256 luma samples a block may code and still be judged208 /// coefficients per 256 luma samples a block may code and still be judged
195 /// well enough predicted that the split below it is not worth trying. `0`209 /// 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
478 base_q_idx: encoded.base_q_idx,492 base_q_idx: encoded.base_q_idx,
479 tx_select: encoded.tx_select,493 tx_select: encoded.tx_select,
480 loop_filter: encoded.loop_filter,494 loop_filter: encoded.loop_filter,
495+ loop_restoration: encoded.loop_restoration,
481 cdef: encoded.cdef,496 cdef: encoded.cdef,
482 }497 }
483 }498 }
@@ -524,6 +539,11 @@ pub struct Encoded {
524 /// This frame header's chosen CDEF parameters, threaded for the same539 /// This frame header's chosen CDEF parameters, threaded for the same
525 /// reason as `loop_filter`.540 /// reason as `loop_filter`.
526 pub(crate) cdef: CdefParams,541 pub(crate) cdef: CdefParams,
542+ /// This frame header's chosen loop restoration parameters, threaded for
543+ /// the same reason as `loop_filter` -- and doubly so: the per-unit
544+ /// filters themselves are coded in `tile`, so a decode of it under a
545+ /// stale `RESTORE_NONE` header desyncs at the first superblock.
546+ pub(crate) loop_restoration: LoopRestorationParams,
527 }547 }
528 548
529 /// The sequence and frame headers a picture of this size is coded under: one549 /// 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(
608 // `cdef_idx` literal is coded in the tile and a frame that wants no628 // `cdef_idx` literal is coded in the tile and a frame that wants no
609 // CDEF simply carries zero strengths.629 // CDEF simply carries zero strengths.
610 enable_cdef: true,630 enable_cdef: true,
611- enable_restoration: false,631+ enable_restoration: true,
612 seq_force_screen_content_tools: 0,632 seq_force_screen_content_tools: 0,
613 seq_force_integer_mv: 0,633 seq_force_integer_mv: 0,
614 color_config,634 color_config,
@@ -3037,6 +3057,12 @@ pub(crate) fn encode_key_frame_inner(
3037 // `crate::filter_search`), and keep the filtered picture that wins as3057 // `crate::filter_search`), and keep the filtered picture that wins as
3038 // the reconstruction -- what a decoder outputs, and what the next3058 // the reconstruction -- what a decoder outputs, and what the next
3039 // frame predicts from.3059 // frame predicts from.
3060+ // The luma restoration-unit grid this frame's `lr_params` implies
3061+ // (`av1_lr_count_units` rounds to nearest, so a short last unit is
3062+ // swallowed by the one before it), for the tile writer's own per-unit
3063+ // walk.
3064+ let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32;
3065+ let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32;
3040 pick_and_apply_filters(3066 pick_and_apply_filters(
3041 &mut header,3067 &mut header,
3042 &mut luma,3068 &mut luma,
@@ -3045,8 +3071,10 @@ pub(crate) fn encode_key_frame_inner(
3045 true,3071 true,
3046 &mut tile,3072 &mut tile,
3047 search.lambda,3073 search.lambda,
3048- |bits, sb_cols, grid| {3074+ fctx,
3075+ |bits, sb_cols, grid, units| {
3049 crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());3076 crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());
3077+ crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());
3050 crate::tile::sb_coeff_key_frame_tile_tx(3078 crate::tile::sb_coeff_key_frame_tile_tx(
3051 mi_cols,3079 mi_cols,
3052 mi_rows,3080 mi_rows,
@@ -3055,8 +3083,8 @@ pub(crate) fn encode_key_frame_inner(
3055 tx_select,3083 tx_select,
3056 )3084 )
3057 },3085 },
3058- |lf, cdef, h, tile| {3086+ |lf, cdef, h, tile, lr| {
3059- crate::decode::decode_key_frame_tile(3087+ crate::decode::decode_key_frame_tile_lr(
3060 tile,3088 tile,
3061 h.mi_cols,3089 h.mi_cols,
3062 h.mi_rows,3090 h.mi_rows,
@@ -3070,6 +3098,7 @@ pub(crate) fn encode_key_frame_inner(
3070 h.reduced_tx_set,3098 h.reduced_tx_set,
3071 h.allow_screen_content_tools,3099 h.allow_screen_content_tools,
3072 h.allow_intrabc,3100 h.allow_intrabc,
3101+ lr,
3073 fctx,3102 fctx,
3074 )3103 )
3075 },3104 },
@@ -3097,6 +3126,7 @@ pub(crate) fn encode_key_frame_inner(
3097 tx_select,3126 tx_select,
3098 loop_filter: header.loop_filter,3127 loop_filter: header.loop_filter,
3099 cdef: header.cdef,3128 cdef: header.cdef,
3129+ loop_restoration: header.loop_restoration,
3100 })3130 })
3101 }3131 }
3102 3132
@@ -3126,8 +3156,15 @@ fn pick_and_apply_filters(
3126 // winner re-decoded from it.3156 // winner re-decoded from it.
3127 tile: &mut Vec<u8>,3157 tile: &mut Vec<u8>,
3128 lambda: f64,3158 lambda: f64,
3129- recode: impl Fn(u8, usize, &[u8]) -> Result<Vec<u8>>,3159+ fctx: &crate::decode::FrameCtx,
3130- decode: impl Fn(&LoopFilterParams, &CdefParams, &FrameHeader, &[u8]) -> Result<Picture>,3160+ recode: impl Fn(u8, usize, &[u8], &[Option<crate::restoration::WienerInfo>]) -> Result<Vec<u8>>,
3161+ decode: impl Fn(
3162+ &LoopFilterParams,
3163+ &CdefParams,
3164+ &FrameHeader,
3165+ &[u8],
3166+ &LoopRestorationParams,
3167+ ) -> Result<Picture>,
3131 ) -> Result<()> {3168 ) -> Result<()> {
3132 if !search {3169 if !search {
3133 return Ok(());3170 return Ok(());
@@ -3139,8 +3176,9 @@ fn pick_and_apply_filters(
3139 let damping = 3 + (header.quantization.base_q_idx >> 6);3176 let damping = 3 + (header.quantization.base_q_idx >> 6);
3140 let (cols32, rows32) = crate::tile::block_grid(header.mi_cols, header.mi_rows);3177 let (cols32, rows32) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
3141 let (sb_cols, sb_rows) = (cols32.div_ceil(2) as usize, rows32.div_ceil(2) as usize);3178 let (sb_cols, sb_rows) = (cols32.div_ceil(2) as usize, rows32.div_ceil(2) as usize);
3179+ let none_lr = LoopRestorationParams::default();
3142 let (lf, cdef, idx_grid, picture) = crate::filter_search::pick_filters(3180 let (lf, cdef, idx_grid, picture) = crate::filter_search::pick_filters(
3143- |lf, cdef| decode(lf, cdef, &hdr, tile),3181+ |lf, cdef| decode(lf, cdef, &hdr, tile, &none_lr),
3144 source,3182 source,
3145 luma.width,3183 luma.width,
3146 (fw, fh),3184 (fw, fh),
@@ -3150,14 +3188,61 @@ fn pick_and_apply_filters(
3150 )?;3188 )?;
3151 header.loop_filter = lf;3189 header.loop_filter = lf;
3152 header.cdef = cdef;3190 header.cdef = cdef;
3153- let filtered = if idx_grid.is_empty() {3191+ // spec 7.17: loop restoration. Its per-unit filters live in the TILE, so
3192+ // this stage codes the tile a second time no matter what -- first with
3193+ // every unit at `RESTORE_NONE`, which is the shape whose decode hands
3194+ // back the post-deblock and post-CDEF pictures the search needs (and
3195+ // whose output IS the post-CDEF picture), then again with the filters it
3196+ // picked.
3197+ let mut lr = LoopRestorationParams::default();
3198+ if restoration_enabled() {
3199+ lr.frame_restoration_type[0] = ec_av1_syntax::RestorationType::Wiener;
3200+ lr.loop_restoration_size = [64, 64, 64];
3201+ lr.uses_lr = true;
3202+ }
3203+ let grid_dims = crate::restoration::RestorationGrid::new(&lr, fw as u32, fh as u32);
3204+ let n_units = if lr.uses_lr {
3205+ grid_dims.horz_units[0] * grid_dims.vert_units[0]
3206+ } else {
3207+ 0
3208+ };
3209+ let filtered = if idx_grid.is_empty() && n_units == 0 {
3154 picture3210 picture
3155 } else {3211 } else {
3156- let coded = recode(cdef.bits, sb_cols, &idx_grid)?;3212+ let probe = recode(cdef.bits, sb_cols, &idx_grid, &vec![None; n_units])?;
3157- let picture = decode(&lf, &cdef, &hdr, &coded)?;3213+ fctx.capture_stages.set(n_units > 0);
3214+ let probe_picture = decode(&lf, &cdef, &hdr, &probe, &lr)?;
3215+ fctx.capture_stages.set(false);
3216+ let units = match crate::decode::take_filter_stages(fctx) {
3217+ Some(stages) => crate::filter_search::pick_restoration(
3218+ &stages,
3219+ source[0],
3220+ luma.width,
3221+ (fw, fh),
3222+ &lr,
3223+ lambda,
3224+ fctx,
3225+ ),
3226+ None => Vec::new(),
3227+ };
3228+ if units.iter().any(Option::is_some) {
3229+ let coded = recode(cdef.bits, sb_cols, &idx_grid, &units)?;
3230+ let picture = decode(&lf, &cdef, &hdr, &coded, &lr)?;
3158 *tile = coded;3231 *tile = coded;
3159 picture3232 picture
3233+ } else {
3234+ // Nothing to restore: code the frame with `RESTORE_NONE` on every
3235+ // plane instead of a tile full of `restore_wiener = 0` symbols
3236+ // (worth ~1 bit per 64x64, which the BD gate saw on a clip whose
3237+ // units never take a filter). The probe's picture already IS the
3238+ // unrestored one -- a grid of `RESTORE_NONE` units restores
3239+ // nothing -- so this costs one tile write and no decode.
3240+ lr = LoopRestorationParams::default();
3241+ *tile = recode(cdef.bits, sb_cols, &idx_grid, &[])?;
3242+ probe_picture
3243+ }
3160 };3244 };
3245+ header.loop_restoration = lr;
3161 let dec_cw = filtered.width.div_ceil(2);3246 let dec_cw = filtered.width.div_ceil(2);
3162 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));3247 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));
3163 crate::filter_search::splice(&mut luma.reconstruction, luma.width, &filtered.y, filtered.width, fw, fh);3248 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(
4257 let mut refs: [Option<&Picture>; 8] = [None; 8];4342 let mut refs: [Option<&Picture>; 8] = [None; 8];
4258 refs[1] = Some(&trial_ref);4343 refs[1] = Some(&trial_ref);
4259 let refpix = crate::decode::RefPix::ready(refs);4344 let refpix = crate::decode::RefPix::ready(refs);
4345+ // The luma restoration-unit grid this frame's `lr_params` implies
4346+ // (`av1_lr_count_units` rounds to nearest, so a short last unit is
4347+ // swallowed by the one before it), for the tile writer's own per-unit
4348+ // walk.
4349+ let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32;
4350+ let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32;
4260 pick_and_apply_filters(4351 pick_and_apply_filters(
4261 &mut header,4352 &mut header,
4262 &mut luma,4353 &mut luma,
@@ -4269,8 +4360,10 @@ pub(crate) fn encode_inter_frame(
4269 true,4360 true,
4270 &mut tile,4361 &mut tile,
4271 search.lambda,4362 search.lambda,
4272- |bits, sb_cols, grid| {4363+ fctx,
4364+ |bits, sb_cols, grid, units| {
4273 crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());4365 crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());
4366+ crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());
4274 crate::tile::sb_coeff_inter_frame_tile_tx(4367 crate::tile::sb_coeff_inter_frame_tile_tx(
4275 mi_cols,4368 mi_cols,
4276 mi_rows,4369 mi_rows,
@@ -4279,8 +4372,8 @@ pub(crate) fn encode_inter_frame(
4279 tx_select,4372 tx_select,
4280 )4373 )
4281 },4374 },
4282- |lf, cdef, h, tile| {4375+ |lf, cdef, h, tile, lr| {
4283- crate::decode::decode_inter_frame_tile(4376+ crate::decode::decode_inter_frame_tile_lr(
4284 tile,4377 tile,
4285 h.mi_cols,4378 h.mi_cols,
4286 h.mi_rows,4379 h.mi_rows,
@@ -4296,6 +4389,7 @@ pub(crate) fn encode_inter_frame(
4296 seq.enable_dual_filter,4389 seq.enable_dual_filter,
4297 h.reference_select,4390 h.reference_select,
4298 tx_select,4391 tx_select,
4392+ lr,
4299 fctx,4393 fctx,
4300 )4394 )
4301 },4395 },
@@ -4322,6 +4416,7 @@ pub(crate) fn encode_inter_frame(
4322 tx_select,4416 tx_select,
4323 loop_filter: header.loop_filter,4417 loop_filter: header.loop_filter,
4324 cdef: header.cdef,4418 cdef: header.cdef,
4419+ loop_restoration: header.loop_restoration,
4325 })4420 })
4326 }4421 }
4327 4422
@@ -7287,6 +7382,13 @@ mod tests {
7287 units,7382 units,
7288 100.0 * on_extra as f64 / units.max(1) as f647383 100.0 * on_extra as f64 / units.max(1) as f64
7289 );7384 );
7385+ // How the 64x64 luma restoration units split between
7386+ // RESTORE_NONE and Wiener (lane-av1lr).
7387+ let (lr_none, lr_wiener) = crate::filter_search::take_lr_histogram();
7388+ eprintln!(
7389+ "{name}: lr units none={lr_none} wiener={lr_wiener} ({:.1}% restored)",
7390+ 100.0 * lr_wiener as f64 / (lr_none + lr_wiener).max(1) as f64
7391+ );
7290 // Which chroma modes the search actually wins with, against the7392 // Which chroma modes the search actually wins with, against the
7291 // unconditional DC_PRED that was the only outcome before7393 // unconditional DC_PRED that was the only outcome before
7292 // (gate-blind-to-feature).7394 // (gate-blind-to-feature).
crates/ec-av1/src/filter_search.rsmodified+136 -0
@@ -344,3 +344,139 @@ pub(crate) fn splice(dst: &mut [u8], dst_w: usize, src: &[u16], src_w: usize, w:
344 }344 }
345 }345 }
346 }346 }
347+
348+// ---------------------------------------------------------------------------
349+// lane-av1lr: loop restoration (spec 7.17). Unlike deblocking and CDEF, whose
350+// parameters live in the frame header, a restoration unit's filter is coded
351+// in the TILE payload, so a whole-frame re-decode cannot search it: the
352+// search runs here, on the two pictures the decoder captured between its own
353+// filter stages (`crate::decode::FrameCtx::capture_stages`), through the
354+// decoder's OWN Wiener kernel (`crate::restoration::
355+// apply_loop_restoration_plane`) -- never a second implementation.
356+
357+/// The Wiener filters offered per unit, as the three free taps of a
358+/// direction (the centre tap is derived). Both directions take the same
359+/// candidate, so a unit picks one of four separable filters: two strengths
360+/// of low pass, one wider low pass, and one sharpener.
361+///
362+/// corner-cut: libaom's `av1_pick_filter_restoration` SOLVES for each unit's
363+/// taps (the Wiener-Hopf normal equations over that unit's autocorrelation)
364+/// instead of picking from a ladder, and also offers self-guided restoration.
365+/// The ceiling is whatever a four-point ladder leaves on the table; the
366+/// upgrade path is a per-unit solve feeding the same `write_wiener_filter`
367+/// syntax this already writes, plus `RestorationType::Switchable` for the
368+/// SGR arm.
369+const WIENER_CANDIDATES: [[i32; 3]; 4] = [[0, 0, 8], [0, 0, 16], [0, 4, 12], [0, 0, -8]];
370+
371+/// What a unit spends on its own syntax, for the RD choice below: one
372+/// `restore_wiener` symbol for `RESTORE_NONE`, and roughly the two
373+/// directions' three subexp-coded taps when it takes a filter.
374+const LR_NONE_BITS: f64 = 1.0;
375+const LR_WIENER_BITS: f64 = 25.0;
376+
377+/// Picks each luma restoration unit's filter, on the frame the decoder
378+/// captured after CDEF (with its post-deblock stripe borders), against the
379+/// source it was coded from. Returns one entry per unit in `rcol + rrow *
380+/// horz_units` order -- what `crate::tile::arm_lr` writes.
381+pub(crate) fn pick_restoration(
382+ stages: &crate::decode::FilterStages,
383+ source: &[u8],
384+ src_w: usize,
385+ (fw, fh): (usize, usize),
386+ lr: &ec_av1_syntax::LoopRestorationParams,
387+ lambda: f64,
388+ fctx: &crate::decode::FrameCtx,
389+) -> Vec<Option<crate::restoration::WienerInfo>> {
390+ let grid_dims = crate::restoration::RestorationGrid::new(lr, fw as u32, fh as u32);
391+ let (horz, vert) = (grid_dims.horz_units[0], grid_dims.vert_units[0]);
392+ let unit = lr.loop_restoration_size[0] as usize;
393+ let stride = stages.stride[0];
394+ let rows = crate::restoration::lr_unit_rows(fh, unit as u32, 0, lr.frame_restoration_type[0]);
395+ if rows.len() != vert {
396+ return Vec::new();
397+ }
398+ // Each unit's own sample span: the row walk's (a short last row is
399+ // swallowed by the one above it), and the column mirror of it.
400+ let span = |rrow: usize, rcol: usize| -> (usize, usize, usize, usize) {
401+ let (r0, r1) = rows[rrow];
402+ let c0 = rcol * unit;
403+ let c1 = if rcol + 1 == horz { fw } else { (rcol + 1) * unit };
404+ (r0 as usize, r1 as usize, c0, c1)
405+ };
406+ let unit_sse = |plane: &[u16], rrow: usize, rcol: usize| -> u64 {
407+ let (r0, r1, c0, c1) = span(rrow, rcol);
408+ let mut sse = 0u64;
409+ for row in r0..r1 {
410+ for col in c0..c1 {
411+ let diff = i64::from(plane[row * stride + col]) - i64::from(source[row * src_w + col]);
412+ sse += (diff * diff) as u64;
413+ }
414+ }
415+ sse
416+ };
417+ // Cost of leaving every unit alone, then one whole-plane pass per
418+ // candidate to price taking it.
419+ let mut best: Vec<(f64, Option<crate::restoration::WienerInfo>)> = (0..horz * vert)
420+ .map(|i| {
421+ let sse = unit_sse(&stages.cdefed[0], i / horz, i % horz) as f64;
422+ (sse + lambda * LR_NONE_BITS, None)
423+ })
424+ .collect();
425+ let mut out = Vec::new();
426+ for taps in WIENER_CANDIDATES {
427+ let info = crate::restoration::wiener_from_taps(taps, taps);
428+ let mut grid = crate::restoration::RestorationGrid::new(lr, fw as u32, fh as u32);
429+ for rrow in 0..vert {
430+ for rcol in 0..horz {
431+ grid.set(0, rrow, rcol, crate::restoration::UnitFilter::Wiener(info));
432+ }
433+ }
434+ crate::restoration::apply_loop_restoration_plane(
435+ &stages.cdefed[0],
436+ &stages.deblocked[0],
437+ stride,
438+ fw,
439+ fh,
440+ 0,
441+ lr.frame_restoration_type[0],
442+ lr.loop_restoration_size[0],
443+ &grid,
444+ 0,
445+ &mut out,
446+ None,
447+ fctx,
448+ );
449+ for rrow in 0..vert {
450+ for rcol in 0..horz {
451+ let cost = unit_sse(&out, rrow, rcol) as f64 + lambda * LR_WIENER_BITS;
452+ let slot = &mut best[rcol + rrow * horz];
453+ if cost < slot.0 {
454+ *slot = (cost, Some(info));
455+ }
456+ }
457+ }
458+ }
459+ let chosen: Vec<Option<crate::restoration::WienerInfo>> =
460+ best.into_iter().map(|(_, f)| f).collect();
461+ LR_CHOSEN.with(|c| {
462+ let mut hist = c.borrow_mut();
463+ for f in &chosen {
464+ hist.0 += usize::from(f.is_none());
465+ hist.1 += usize::from(f.is_some());
466+ }
467+ });
468+ chosen
469+}
470+
471+thread_local! {
472+ /// `(RESTORE_NONE units, Wiener units)` over every frame since the last
473+ /// [`take_lr_histogram`] -- the BD gate's own proof the feature fires.
474+ static LR_CHOSEN: std::cell::RefCell<(usize, usize)> =
475+ const { std::cell::RefCell::new((0, 0)) };
476+}
477+
478+/// Takes and clears [`LR_CHOSEN`].
479+#[allow(dead_code)] // read from the `#[cfg(test)]` BD gate
480+pub(crate) fn take_lr_histogram() -> (usize, usize) {
481+ LR_CHOSEN.with(|c| std::mem::take(&mut *c.borrow_mut()))
482+}
crates/ec-av1/src/restoration.rsmodified+169 -59
@@ -80,6 +80,139 @@ fn decode_signed_subexp_with_ref_msac(dec: &mut SymbolDecoder, low: i32, high: i
80 decode_unsigned_subexp_with_ref_msac(dec, n, k, r) as i32 + low80 decode_unsigned_subexp_with_ref_msac(dec, n, k, r) as i32 + low
81 }81 }
82 82
83+// ---------------------------------------------------------------------------
84+// lane-av1lr: the WRITE side of the three primitives above, for the encoder's
85+// per-restoration-unit syntax (`crate::tile`). Each is libaom's own writer
86+// (`aom_dsp/bitwriter.h`'s `write_primitive_*`) and the exact inverse of the
87+// reader it sits under; `wiener_filter_roundtrips` below pins the pair.
88+
89+/// `aom_write_primitive_quniform`, the inverse of [`ns_msac`].
90+fn write_ns(enc: &mut crate::msac::SymbolEncoder, n: u32, v: u32) {
91+ if n <= 1 {
92+ return;
93+ }
94+ let w = floor_log2(n) + 1;
95+ let m = (1u32 << w) - n;
96+ if v < m {
97+ enc.literal(v, w - 1);
98+ } else {
99+ enc.literal(m + ((v - m) >> 1), w - 1);
100+ enc.literal((v - m) & 1, 1);
101+ }
102+}
103+
104+/// `aom_write_primitive_subexpfin`, the inverse of [`decode_subexp_msac`].
105+fn write_subexp(enc: &mut crate::msac::SymbolEncoder, num_syms: u32, k: u32, v: u32) {
106+ let mut i = 0u32;
107+ let mut mk = 0u32;
108+ loop {
109+ let b = if i > 0 { k + i - 1 } else { k };
110+ let a = 1u32 << b;
111+ if num_syms <= mk + 3 * a {
112+ write_ns(enc, num_syms - mk, v - mk);
113+ return;
114+ }
115+ if v < mk + a {
116+ enc.literal(0, 1);
117+ enc.literal(v - mk, b);
118+ return;
119+ }
120+ enc.literal(1, 1);
121+ i += 1;
122+ mk += a;
123+ }
124+}
125+
126+/// `recenter_nonneg`, the inverse of [`inverse_recenter`].
127+fn recenter(r: u32, v: u32) -> u32 {
128+ if v > 2 * r {
129+ v
130+ } else if v >= r {
131+ (v - r) << 1
132+ } else {
133+ ((r - v) << 1) - 1
134+ }
135+}
136+
137+/// Inverse of [`decode_unsigned_subexp_with_ref_msac`].
138+fn write_unsigned_subexp_with_ref(
139+ enc: &mut crate::msac::SymbolEncoder,
140+ n: u32,
141+ k: u32,
142+ reference: u32,
143+ v: u32,
144+) {
145+ let recentred = if (reference << 1) <= n {
146+ recenter(reference, v)
147+ } else {
148+ recenter(n - 1 - reference, n - 1 - v)
149+ };
150+ write_subexp(enc, n, k, recentred);
151+}
152+
153+/// Inverse of [`decode_signed_subexp_with_ref_msac`].
154+fn write_signed_subexp_with_ref(
155+ enc: &mut crate::msac::SymbolEncoder,
156+ low: i32,
157+ high: i32,
158+ k: u32,
159+ reference: i32,
160+ v: i32,
161+) {
162+ let n = (high - low) as u32;
163+ let r = (reference - low).clamp(0, n as i32) as u32;
164+ write_unsigned_subexp_with_ref(enc, n, k, r, (v - low).clamp(0, n as i32 - 1) as u32);
165+}
166+
167+/// Inverse of [`read_wiener_filter`]: writes one unit's two directions and
168+/// advances the caller's running per-plane reference, exactly as the reader
169+/// advances its own.
170+pub(crate) fn write_wiener_filter(
171+ enc: &mut crate::msac::SymbolEncoder,
172+ chroma: bool,
173+ reference: &mut WienerInfo,
174+ info: &WienerInfo,
175+) {
176+ write_wiener_direction(enc, chroma, &reference.vfilter, &info.vfilter);
177+ write_wiener_direction(enc, chroma, &reference.hfilter, &info.hfilter);
178+ *reference = *info;
179+}
180+
181+/// Inverse of [`read_wiener_direction`].
182+fn write_wiener_direction(
183+ enc: &mut crate::msac::SymbolEncoder,
184+ chroma: bool,
185+ reference: &[i32; 7],
186+ taps: &[i32; 7],
187+) {
188+ for i in 0..3 {
189+ if i == 0 && chroma {
190+ continue;
191+ }
192+ write_signed_subexp_with_ref(
193+ enc,
194+ WIENER_TAP_MINV[i],
195+ WIENER_TAP_MAXV[i] + 1,
196+ WIENER_TAP_K[i],
197+ reference[i],
198+ taps[i],
199+ );
200+ }
201+}
202+
203+/// A Wiener unit's three free taps per direction, as [`WienerInfo`] (the
204+/// centre tap is derived, spec 7.17.4).
205+pub(crate) fn wiener_from_taps(v: [i32; 3], h: [i32; 3]) -> WienerInfo {
206+ let fill = |t: [i32; 3]| {
207+ let centre = 128 - 2 * (t[0] + t[1] + t[2]);
208+ [t[0], t[1], t[2], centre, t[2], t[1], t[0]]
209+ };
210+ WienerInfo {
211+ vfilter: fill(v),
212+ hfilter: fill(h),
213+ }
214+}
215+
83 #[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live216 #[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
84 const WIENER_HALFWIN: usize = 3;217 const WIENER_HALFWIN: usize = 3;
85 #[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live218 #[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
@@ -291,7 +424,7 @@ impl RestorationGrid {
291 }424 }
292 }425 }
293 426
294- fn set(&mut self, plane: usize, rrow: usize, rcol: usize, filter: UnitFilter) {427+ pub(crate) fn set(&mut self, plane: usize, rrow: usize, rcol: usize, filter: UnitFilter) {
295 let idx = rcol + rrow * self.horz_units[plane];428 let idx = rcol + rrow * self.horz_units[plane];
296 self.units[plane][idx] = filter;429 self.units[plane][idx] = filter;
297 }430 }
@@ -303,7 +436,7 @@ impl RestorationGrid {
303 }436 }
304 437
305 /// `av1_lr_count_units` (restoration.c:63): round, not ceil, to nearest.438 /// `av1_lr_count_units` (restoration.c:63): round, not ceil, to nearest.
306-fn count_units(plane_size: u32, unit_size: u32) -> usize {439+pub(crate) fn count_units(plane_size: u32, unit_size: u32) -> usize {
307 (((plane_size + (unit_size >> 1)) / unit_size).max(1)) as usize440 (((plane_size + (unit_size >> 1)) / unit_size).max(1)) as usize
308 }441 }
309 442
@@ -1366,63 +1499,10 @@ mod tests {
1366 use super::*;1499 use super::*;
1367 use crate::msac::{SymbolDecoder, SymbolEncoder};1500 use crate::msac::{SymbolDecoder, SymbolEncoder};
1368 1501
1369- /// `write_primitive_quniform`, the exact inverse of [`ns_msac`] -- used1502+ /// The write side these roundtrips exercise now lives beside the
1370- /// only to build roundtrip fixtures for the decode-only helpers above1503+ /// readers (`write_ns`/`write_subexp`/`write_unsigned_subexp_with_ref`,
1371- /// (this decoder never writes loop restoration itself).1504+ /// used by the encoder's per-unit LR syntax) instead of being a
1372- fn write_ns(enc: &mut SymbolEncoder, n: u32, v: u32) {1505+ /// test-only transcription of it -- one implementation, pinned here.
1373- if n <= 1 {
1374- return;
1375- }
1376- let w = floor_log2(n) + 1;
1377- let m = (1u32 << w) - n;
1378- if v < m {
1379- enc.literal(v, w - 1);
1380- } else {
1381- enc.literal((v + m) >> 1, w - 1);
1382- enc.literal((v + m) & 1, 1);
1383- }
1384- }
1385-
1386- fn write_subexp(enc: &mut SymbolEncoder, num_syms: u32, k: u32, v: u32) {
1387- let mut i = 0u32;
1388- let mut mk = 0u32;
1389- loop {
1390- let b = if i > 0 { k + i - 1 } else { k };
1391- let a = 1u32 << b;
1392- if num_syms <= mk + 3 * a {
1393- write_ns(enc, num_syms - mk, v - mk);
1394- return;
1395- }
1396- if v < mk + a {
1397- enc.literal(0, 1);
1398- enc.literal(v - mk, b);
1399- return;
1400- }
1401- enc.literal(1, 1);
1402- i += 1;
1403- mk += a;
1404- }
1405- }
1406-
1407- fn recenter(r: u32, v: u32) -> u32 {
1408- if v > 2 * r {
1409- v
1410- } else if v >= r {
1411- (v - r) << 1
1412- } else {
1413- ((r - v) << 1) - 1
1414- }
1415- }
1416-
1417- fn write_unsigned_subexp_with_ref(enc: &mut SymbolEncoder, n: u32, k: u32, reference: u32, v: u32) {
1418- let r = reference.clamp(0, n.saturating_sub(1));
1419- let coded = if (r << 1) <= n {
1420- recenter(r, v)
1421- } else {
1422- recenter(n - 1 - r, n - 1 - v)
1423- };
1424- write_subexp(enc, n, k, coded);
1425- }
1426 1506
1427 /// `decode_subexp_msac`/`ns_msac` roundtrip every value in a handful of1507 /// `decode_subexp_msac`/`ns_msac` roundtrip every value in a handful of
1428 /// `(num_syms, k)` alphabets -- the shapes LR's tap ranges (`k` 1..=4,1508 /// `(num_syms, k)` alphabets -- the shapes LR's tap ranges (`k` 1..=4,
@@ -1489,4 +1569,34 @@ mod tests {
1489 }1569 }
1490 }1570 }
1491 }1571 }
1572+
1573+ /// [`write_wiener_filter`] against [`read_wiener_filter`], including the
1574+ /// running per-tile reference both sides advance: three units in a row,
1575+ /// luma (7-tap) and chroma (5-tap, tap 0 forced to zero).
1576+ #[test]
1577+ fn wiener_filter_roundtrips() {
1578+ for chroma in [false, true] {
1579+ let units = [
1580+ wiener_from_taps([0, 0, 8], [0, 0, 8]),
1581+ wiener_from_taps([0, 4, 12], [0, 0, -8]),
1582+ wiener_from_taps([0, 0, 0], [0, 0, 0]),
1583+ ];
1584+ let units: Vec<WienerInfo> = if chroma {
1585+ units.iter().copied().collect()
1586+ } else {
1587+ units.to_vec()
1588+ };
1589+ let mut enc = SymbolEncoder::new();
1590+ let mut wref = WienerInfo::default();
1591+ for u in &units {
1592+ write_wiener_filter(&mut enc, chroma, &mut wref, u);
1593+ }
1594+ let payload = enc.finish();
1595+ let mut dec = SymbolDecoder::new(&payload);
1596+ let mut rref = WienerInfo::default();
1597+ for u in &units {
1598+ assert_eq!(read_wiener_filter(&mut dec, chroma, &mut rref), *u, "chroma={chroma}");
1599+ }
1600+ }
1601+ }
1492 }1602 }
crates/ec-av1/src/stream.rsmodified+4 -3
@@ -28,7 +28,7 @@ use crate::decode::{
28 q_ctx_of,28 q_ctx_of,
29 };29 };
30 #[cfg(test)]30 #[cfg(test)]
31-use crate::decode::decode_key_frame_tile;31+use crate::decode::decode_key_frame_tile_lr;
32 use crate::encode::Picture;32 use crate::encode::Picture;
33 33
34 /// lane-midcut r1: `EC_AV1_NO_GRAIN=1` skips film grain synthesis at output, so a34 /// lane-midcut r1: `EC_AV1_NO_GRAIN=1` skips film grain synthesis at output, so a
@@ -2986,7 +2986,7 @@ mod tests {
2986 for &(width, height) in &[(64usize, 64usize), (216, 96)] {2986 for &(width, height) in &[(64usize, 64usize), (216, 96)] {
2987 let picture = test_card(width, height);2987 let picture = test_card(width, height);
2988 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();2988 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
2989- let via_tile = decode_key_frame_tile(2989+ let via_tile = decode_key_frame_tile_lr(
2990 &encoded.tile,2990 &encoded.tile,
2991 encoded.mi_cols,2991 encoded.mi_cols,
2992 encoded.mi_rows,2992 encoded.mi_rows,
@@ -3000,7 +3000,8 @@ mod tests {
3000 // Our own encoder always writes `reduced_tx_set: true`.3000 // Our own encoder always writes `reduced_tx_set: true`.
3001 true,3001 true,
3002 false,3002 false,
3003- false, fctx,3003+ false,
3004+ &encoded.loop_restoration, fctx,
3004 )3005 )
3005 .unwrap();3006 .unwrap();
3006 let via_stream = decode_stream(&encoded.stream).unwrap();3007 let via_stream = decode_stream(&encoded.stream).unwrap();
crates/ec-av1/src/tile.rsmodified+87 -0
@@ -31,6 +31,90 @@ use crate::mvstack::{MiGrid, MiInfo, NO_REF1, find_mv_stack, mv16, single_ref_ct
31 // ([`CdefIdxGuard`] clears it on every exit path, error included), so a frame31 // ([`CdefIdxGuard`] clears it on every exit path, error included), so a frame
32 // that arms nothing writes no literals.32 // that arms nothing writes no literals.
33 33
34+// ---------------------------------------------------------------------------
35+// lane-av1lr: per-restoration-unit loop restoration syntax (spec 5.11.57,
36+// `read_lr`), armed by the encoder's restoration search the same way
37+// [`arm_cdef_idx`] arms the CDEF indices. LUMA ONLY and Wiener only: the
38+// frame header this encoder writes sets `FrameRestorationType[0] = WIENER`
39+// and leaves both chroma planes at `RESTORE_NONE`, so a unit codes one
40+// `restore_wiener` symbol and, when it takes the filter, its two directions
41+// against the running per-tile reference (`crate::restoration::
42+// write_wiener_filter`, the exact inverse of the reader's own
43+// `read_wiener_filter`).
44+
45+/// One frame's per-unit restoration plan (see [`arm_lr`]).
46+struct LrPlan {
47+ /// `LoopRestorationSize[0]`, in luma samples.
48+ unit_size: u32,
49+ /// `horz_units`/`vert_units` for the luma plane.
50+ horz_units: u32,
51+ vert_units: u32,
52+ /// One entry per unit, `rcol + rrow * horz_units`: the filter it takes,
53+ /// or `None` for `RESTORE_NONE`.
54+ units: Vec<Option<crate::restoration::WienerInfo>>,
55+ /// `ref_wiener_info`: the running reference the taps are coded against,
56+ /// reset to the midpoint filter at the start of each tile (this writer
57+ /// codes one tile per frame).
58+ reference: crate::restoration::WienerInfo,
59+}
60+
61+thread_local! {
62+ static LR_PLAN: std::cell::RefCell<Option<LrPlan>> = const { std::cell::RefCell::new(None) };
63+}
64+
65+/// Arms the next tile write with one Wiener decision per luma restoration
66+/// unit. An empty `units` disarms (the frame codes no restoration at all).
67+pub(crate) fn arm_lr(
68+ unit_size: u32,
69+ horz_units: u32,
70+ vert_units: u32,
71+ units: Vec<Option<crate::restoration::WienerInfo>>,
72+) {
73+ LR_PLAN.with(|c| {
74+ *c.borrow_mut() = (!units.is_empty()).then(|| LrPlan {
75+ unit_size,
76+ horz_units,
77+ vert_units,
78+ units,
79+ reference: crate::restoration::WienerInfo::default(),
80+ });
81+ });
82+}
83+
84+/// `read_lr`'s write side, called once at the top of every superblock,
85+/// before its partition symbol: writes the units this superblock's own
86+/// mi span covers (`av1_loop_restoration_corners_in_sb`; no superres, so the
87+/// column scaling is the plain mi one).
88+fn write_lr(enc: &mut SymbolEncoder, cdfs: &mut Cdfs, mi_row: u32, mi_col: u32) {
89+ LR_PLAN.with(|c| {
90+ let mut plan = c.borrow_mut();
91+ let Some(plan) = plan.as_mut() else { return };
92+ let unit = plan.unit_size;
93+ let rcol0 = (mi_col * 4).div_ceil(unit);
94+ let rcol1 = ((mi_col + SB_MI_W) * 4).div_ceil(unit).min(plan.horz_units);
95+ let rrow0 = (mi_row * 4).div_ceil(unit);
96+ let rrow1 = ((mi_row + SB_MI_W) * 4).div_ceil(unit).min(plan.vert_units);
97+ for rrow in rrow0..rrow1 {
98+ for rcol in rcol0..rcol1 {
99+ let info = plan.units[(rcol + rrow * plan.horz_units) as usize];
100+ enc.symbol(usize::from(info.is_some()), &mut cdfs.restore_wiener);
101+ if let Some(info) = info {
102+ crate::restoration::write_wiener_filter(
103+ enc,
104+ false,
105+ &mut plan.reference,
106+ &info,
107+ );
108+ }
109+ }
110+ }
111+ });
112+}
113+
114+/// A 64x64 superblock's width in 4x4 mode-info units (`SB_MI` in
115+/// `crate::decode`), the span [`write_lr`] resolves its units over.
116+const SB_MI_W: u32 = 16;
117+
34 /// One frame's per-superblock `cdef_idx` plan (see [`arm_cdef_idx`]).118 /// One frame's per-superblock `cdef_idx` plan (see [`arm_cdef_idx`]).
35 struct CdefIdxPlan {119 struct CdefIdxPlan {
36 /// The header's `cdef_bits`; never 0 while armed.120 /// The header's `cdef_bits`; never 0 while armed.
@@ -65,6 +149,7 @@ struct CdefIdxGuard;
65 impl Drop for CdefIdxGuard {149 impl Drop for CdefIdxGuard {
66 fn drop(&mut self) {150 fn drop(&mut self) {
67 CDEF_IDX.with(|c| *c.borrow_mut() = None);151 CDEF_IDX.with(|c| *c.borrow_mut() = None);
152+ LR_PLAN.with(|c| *c.borrow_mut() = None);
68 }153 }
69 }154 }
70 155
@@ -1177,6 +1262,7 @@ pub fn sb_coeff_key_frame_tile_tx(
1177 for sb_r in 0..sb_rows {1262 for sb_r in 0..sb_rows {
1178 neighbours.start_row();1263 neighbours.start_row();
1179 for sb_c in 0..sb_cols {1264 for sb_c in 0..sb_cols {
1265+ write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W);
1180 let at = (sb_r as usize * 4, sb_c as usize * 4);1266 let at = (sb_r as usize * 4, sb_c as usize * 4);
1181 let ctx = neighbours.partition_ctx(at, SB);1267 let ctx = neighbours.partition_ctx(at, SB);
1182 ec_rng_trace(|| {1268 ec_rng_trace(|| {
@@ -2836,6 +2922,7 @@ pub fn sb_coeff_inter_frame_tile_tx(
2836 for sb_r in 0..sb_rows {2922 for sb_r in 0..sb_rows {
2837 neighbours.start_row();2923 neighbours.start_row();
2838 for sb_c in 0..sb_cols {2924 for sb_c in 0..sb_cols {
2925+ write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W);
2839 let sb_at = (sb_r as usize * 4, sb_c as usize * 4);2926 let sb_at = (sb_r as usize * 4, sb_c as usize * 4);
2840 let sb_ctx = neighbours.partition_ctx(sb_at, SB);2927 let sb_ctx = neighbours.partition_ctx(sb_at, SB);
2841 // spec `decode_partition`'s hasRows/hasCols (5.11.4): a superblock2928 // spec `decode_partition`'s hasRows/hasCols (5.11.4): a superblock