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};
4040 ///
4141 /// `Cell`/`RefCell` make this `!Sync` on purpose: a `FrameCtx` belongs to
4242 /// 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+
4362 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>>,
4471 pub(crate) sb128_flag: std::cell::Cell<bool>,
4572 pub(crate) cdef_bits: std::cell::Cell<u8>,
4673 pub(crate) bit_depth: std::cell::Cell<u8>,
@@ -130,6 +157,8 @@ impl FrameCtx {
130157 superres: std::cell::Cell::new((0, 8)),
131158 cdef_transmitted: std::cell::Cell::new(false),
132159 cdef_sb_cols: std::cell::Cell::new(0),
160+ capture_stages: std::cell::Cell::new(false),
161+ stages: std::cell::RefCell::new(None),
133162 cdef_idx_grid: std::cell::RefCell::new(Vec::new()),
134163 delta_q_present: std::cell::Cell::new(false),
135164 delta_q_res: std::cell::Cell::new(1),
@@ -20431,6 +20460,37 @@ fn apply_cdef(
2043120460 scratch_return(src_v);
2043220461 }
2043320462
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+
2043420494 /// Spec 7.17: loop restoration, run after [`apply_cdef`] (a sibling lane's
2043520495 /// ordering note: libaom also runs `superres_post_decode` between the two,
2043620496 /// but this decoder never implements super-resolution, so there is nothing
@@ -20546,6 +20606,34 @@ pub(crate) fn decode_key_frame_tile(
2054620606 reduced_tx_set: bool,
2054720607 allow_screen_content_tools: bool,
2054820608 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,
2054920637 ) -> Result<Picture> {
2055020638 let delta = DeltaParams::default();
2055120639 let single_tile = TileInfo {
@@ -20566,7 +20654,7 @@ pub(crate) fn decode_key_frame_tile(
2056620654 false,
2056720655 cdef,
2056820656 loop_filter,
20569- &LoopRestorationParams::default(),
20657+ lr,
2057020658 None,
2057120659 tx_select,
2057220660 reduced_tx_set,
@@ -22883,6 +22971,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
2288322971 );
2288422972 dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v);
2288522973 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);
2288622975 // spec 7.16 (libaom `superres_post_decode`, decodeframe.c: called
2288722976 // between `av1_cdef_frame` and `av1_loop_restoration_filter_frame`):
2288822977 // the horizontal upscale runs HERE -- after CDEF, before loop
@@ -32639,6 +32728,36 @@ pub(crate) fn decode_inter_frame_tile(
3263932728 // stale header, second instance).
3264032729 tx_select: bool,
3264132730 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,
3264232761 ) -> Result<Picture> {
3264332762 let single_tile = TileInfo {
3264432763 mi_col_starts: vec![0, mi_cols],
@@ -32657,7 +32776,7 @@ pub(crate) fn decode_inter_frame_tile(
3265732776 refpix,
3265832777 cdef,
3265932778 loop_filter,
32660- &LoopRestorationParams::default(),
32779+ lr,
3266132780 None,
3266232781 allow_high_precision_mv,
3266332782 force_integer_mv,
@@ -35498,6 +35617,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3549835617 }
3549935618 dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v);
3550035619 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);
3550135621 // spec 7.16 (libaom `superres_post_decode`, decodeframe.c: called
3550235622 // between `av1_cdef_frame` and `av1_loop_restoration_filter_frame`):
3550335623 // the horizontal upscale runs HERE -- after CDEF, before loop
@@ -36625,9 +36745,10 @@ mod tests {
3662536745 tx_select,
3662636746 loop_filter,
3662736747 cdef,
36748+ loop_restoration,
3662836749 ..
3662936750 }: 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(
3663136752 &tile,
3663236753 mi_cols,
3663336754 mi_rows,
@@ -36640,7 +36761,8 @@ mod tests {
3664036761 tx_select,
3664136762 true,
3664236763 false,
36643- false, fctx,
36764+ false,
36765+ &loop_restoration, fctx,
3664436766 )
3664536767 .unwrap();
3664636768 assert_eq!(decoded.width, w, "{w}x{h}: decoded width");
@@ -36994,7 +37116,7 @@ mod tests {
3699437116 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
3699537117 let (coded_w, coded_h) = ffprobe_size(&encoded.stream);
3699637118 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(
3699837120 &encoded.tile,
3699937121 encoded.mi_cols,
3700037122 encoded.mi_rows,
@@ -37007,7 +37129,8 @@ mod tests {
3700737129 encoded.tx_select,
3700837130 true,
3700937131 false,
37010- false, fctx,
37132+ false,
37133+ &encoded.loop_restoration, fctx,
3701137134 )
3701237135 .unwrap();
3701337136 assert_eq!(ours.y, ffmpeg_decoded.y, "{width}x{height}: luma vs ffmpeg");
@@ -37037,7 +37160,7 @@ mod tests {
3703737160 gate's premise moved, not the decoder"
3703837161 );
3703937162 let decode = |tx_select: bool| {
37040- decode_key_frame_tile(
37163+ decode_key_frame_tile_lr(
3704137164 &encoded.tile,
3704237165 encoded.mi_cols,
3704337166 encoded.mi_rows,
@@ -37051,6 +37174,7 @@ mod tests {
3705137174 true,
3705237175 false,
3705337176 false,
37177+ &encoded.loop_restoration,
3705437178 fctx,
3705537179 )
3705637180 };
@@ -37121,7 +37245,7 @@ mod tests {
3712137245 assert_eq!(encoded.frames.len(), 4);
3712237246
3712337247 let key = &encoded.frames[0];
37124- let mut reference = decode_key_frame_tile(
37248+ let mut reference = decode_key_frame_tile_lr(
3712537249 &key.tile,
3712637250 key.mi_cols,
3712737251 key.mi_rows,
@@ -37134,7 +37258,8 @@ mod tests {
3713437258 key.tx_select,
3713537259 true,
3713637260 false,
37137- false, fctx,
37261+ false,
37262+ &key.loop_restoration, fctx,
3713837263 )
3713937264 .unwrap();
3714037265 assert_eq!(
@@ -37151,7 +37276,7 @@ mod tests {
3715137276 );
3715237277
3715337278 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(
3715537280 &frame.tile,
3715637281 frame.mi_cols,
3715737282 frame.mi_rows,
@@ -37167,6 +37292,7 @@ mod tests {
3716737292 false,
3716837293 false,
3716937294 frame.tx_select,
37295+ &frame.loop_restoration,
3717037296 fctx,
3717137297 )
3717237298 .unwrap();
@@ -37443,7 +37569,7 @@ mod tests {
3744337569 ffmpeg_decode_sequence(&encoded.stream, coded_w as usize, coded_h as usize, 3);
3744437570
3744537571 let key = &encoded.frames[0];
37446- let mut reference = decode_key_frame_tile(
37572+ let mut reference = decode_key_frame_tile_lr(
3744737573 &key.tile,
3744837574 key.mi_cols,
3744937575 key.mi_rows,
@@ -37456,13 +37582,14 @@ mod tests {
3745637582 key.tx_select,
3745737583 true,
3745837584 false,
37459- false, fctx,
37585+ false,
37586+ &key.loop_restoration, fctx,
3746037587 )
3746137588 .unwrap();
3746237589 assert_eq!(reference.y, ffmpeg_frames[0].y, "frame 0 luma vs ffmpeg");
3746337590
3746437591 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(
3746637593 &frame.tile,
3746737594 frame.mi_cols,
3746837595 frame.mi_rows,
@@ -37478,6 +37605,7 @@ mod tests {
3747837605 false,
3747937606 false,
3748037607 frame.tx_select,
37608+ &frame.loop_restoration,
3748137609 fctx,
3748237610 )
3748337611 .unwrap();
crates/ec-av1/src/encode.rsmodified+119 -17
@@ -19,8 +19,8 @@
1919 use crate::decode::WithRef;
2020 use ec_av1_syntax::sequence::{ColorConfig, OperatingPoint, SequenceHeader};
2121 use ec_av1_syntax::{
22- CdefParams, ChromaSamplePosition, FrameHeader, FrameType, LoopFilterParams, PRIMARY_REF_NONE,
23- QuantizationParams, TileInfo, TxMode,
22+ CdefParams, ChromaSamplePosition, FrameHeader, FrameType, LoopFilterParams,
23+ LoopRestorationParams, PRIMARY_REF_NONE, QuantizationParams, TileInfo, TxMode,
2424 };
2525 use ec_core::{Error, Result};
2626
@@ -190,6 +190,20 @@ fn split_inter_blocks() -> bool {
190190 }
191191 }
192192
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+
193207 /// libaom's `partition_search_breakout` shape: how many non-zero luma
194208 /// coefficients per 256 luma samples a block may code and still be judged
195209 /// 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
478492 base_q_idx: encoded.base_q_idx,
479493 tx_select: encoded.tx_select,
480494 loop_filter: encoded.loop_filter,
495+ loop_restoration: encoded.loop_restoration,
481496 cdef: encoded.cdef,
482497 }
483498 }
@@ -524,6 +539,11 @@ pub struct Encoded {
524539 /// This frame header's chosen CDEF parameters, threaded for the same
525540 /// reason as `loop_filter`.
526541 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,
527547 }
528548
529549 /// 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(
608628 // `cdef_idx` literal is coded in the tile and a frame that wants no
609629 // CDEF simply carries zero strengths.
610630 enable_cdef: true,
611- enable_restoration: false,
631+ enable_restoration: true,
612632 seq_force_screen_content_tools: 0,
613633 seq_force_integer_mv: 0,
614634 color_config,
@@ -3037,6 +3057,12 @@ pub(crate) fn encode_key_frame_inner(
30373057 // `crate::filter_search`), and keep the filtered picture that wins as
30383058 // the reconstruction -- what a decoder outputs, and what the next
30393059 // 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;
30403066 pick_and_apply_filters(
30413067 &mut header,
30423068 &mut luma,
@@ -3045,8 +3071,10 @@ pub(crate) fn encode_key_frame_inner(
30453071 true,
30463072 &mut tile,
30473073 search.lambda,
3048- |bits, sb_cols, grid| {
3074+ fctx,
3075+ |bits, sb_cols, grid, units| {
30493076 crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());
3077+ crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());
30503078 crate::tile::sb_coeff_key_frame_tile_tx(
30513079 mi_cols,
30523080 mi_rows,
@@ -3055,8 +3083,8 @@ pub(crate) fn encode_key_frame_inner(
30553083 tx_select,
30563084 )
30573085 },
3058- |lf, cdef, h, tile| {
3059- crate::decode::decode_key_frame_tile(
3086+ |lf, cdef, h, tile, lr| {
3087+ crate::decode::decode_key_frame_tile_lr(
30603088 tile,
30613089 h.mi_cols,
30623090 h.mi_rows,
@@ -3070,6 +3098,7 @@ pub(crate) fn encode_key_frame_inner(
30703098 h.reduced_tx_set,
30713099 h.allow_screen_content_tools,
30723100 h.allow_intrabc,
3101+ lr,
30733102 fctx,
30743103 )
30753104 },
@@ -3097,6 +3126,7 @@ pub(crate) fn encode_key_frame_inner(
30973126 tx_select,
30983127 loop_filter: header.loop_filter,
30993128 cdef: header.cdef,
3129+ loop_restoration: header.loop_restoration,
31003130 })
31013131 }
31023132
@@ -3126,8 +3156,15 @@ fn pick_and_apply_filters(
31263156 // winner re-decoded from it.
31273157 tile: &mut Vec<u8>,
31283158 lambda: f64,
3129- recode: impl Fn(u8, usize, &[u8]) -> Result<Vec<u8>>,
3130- decode: impl Fn(&LoopFilterParams, &CdefParams, &FrameHeader, &[u8]) -> Result<Picture>,
3159+ fctx: &crate::decode::FrameCtx,
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>,
31313168 ) -> Result<()> {
31323169 if !search {
31333170 return Ok(());
@@ -3139,8 +3176,9 @@ fn pick_and_apply_filters(
31393176 let damping = 3 + (header.quantization.base_q_idx >> 6);
31403177 let (cols32, rows32) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
31413178 let (sb_cols, sb_rows) = (cols32.div_ceil(2) as usize, rows32.div_ceil(2) as usize);
3179+ let none_lr = LoopRestorationParams::default();
31423180 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),
31443182 source,
31453183 luma.width,
31463184 (fw, fh),
@@ -3150,14 +3188,61 @@ fn pick_and_apply_filters(
31503188 )?;
31513189 header.loop_filter = lf;
31523190 header.cdef = cdef;
3153- let filtered = if idx_grid.is_empty() {
3154- picture
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]
31553206 } else {
3156- let coded = recode(cdef.bits, sb_cols, &idx_grid)?;
3157- let picture = decode(&lf, &cdef, &hdr, &coded)?;
3158- *tile = coded;
3207+ 0
3208+ };
3209+ let filtered = if idx_grid.is_empty() && n_units == 0 {
31593210 picture
3211+ } else {
3212+ let probe = recode(cdef.bits, sb_cols, &idx_grid, &vec![None; n_units])?;
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)?;
3231+ *tile = coded;
3232+ 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+ }
31603244 };
3245+ header.loop_restoration = lr;
31613246 let dec_cw = filtered.width.div_ceil(2);
31623247 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));
31633248 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(
42574342 let mut refs: [Option<&Picture>; 8] = [None; 8];
42584343 refs[1] = Some(&trial_ref);
42594344 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;
42604351 pick_and_apply_filters(
42614352 &mut header,
42624353 &mut luma,
@@ -4269,8 +4360,10 @@ pub(crate) fn encode_inter_frame(
42694360 true,
42704361 &mut tile,
42714362 search.lambda,
4272- |bits, sb_cols, grid| {
4363+ fctx,
4364+ |bits, sb_cols, grid, units| {
42734365 crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());
4366+ crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());
42744367 crate::tile::sb_coeff_inter_frame_tile_tx(
42754368 mi_cols,
42764369 mi_rows,
@@ -4279,8 +4372,8 @@ pub(crate) fn encode_inter_frame(
42794372 tx_select,
42804373 )
42814374 },
4282- |lf, cdef, h, tile| {
4283- crate::decode::decode_inter_frame_tile(
4375+ |lf, cdef, h, tile, lr| {
4376+ crate::decode::decode_inter_frame_tile_lr(
42844377 tile,
42854378 h.mi_cols,
42864379 h.mi_rows,
@@ -4296,6 +4389,7 @@ pub(crate) fn encode_inter_frame(
42964389 seq.enable_dual_filter,
42974390 h.reference_select,
42984391 tx_select,
4392+ lr,
42994393 fctx,
43004394 )
43014395 },
@@ -4322,6 +4416,7 @@ pub(crate) fn encode_inter_frame(
43224416 tx_select,
43234417 loop_filter: header.loop_filter,
43244418 cdef: header.cdef,
4419+ loop_restoration: header.loop_restoration,
43254420 })
43264421 }
43274422
@@ -7287,6 +7382,13 @@ mod tests {
72877382 units,
72887383 100.0 * on_extra as f64 / units.max(1) as f64
72897384 );
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+ );
72907392 // Which chroma modes the search actually wins with, against the
72917393 // unconditional DC_PRED that was the only outcome before
72927394 // (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:
344344 }
345345 }
346346 }
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
8080 decode_unsigned_subexp_with_ref_msac(dec, n, k, r) as i32 + low
8181 }
8282
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+
83216 #[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
84217 const WIENER_HALFWIN: usize = 3;
85218 #[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
@@ -291,7 +424,7 @@ impl RestorationGrid {
291424 }
292425 }
293426
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) {
295428 let idx = rcol + rrow * self.horz_units[plane];
296429 self.units[plane][idx] = filter;
297430 }
@@ -303,7 +436,7 @@ impl RestorationGrid {
303436 }
304437
305438 /// `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 {
307440 (((plane_size + (unit_size >> 1)) / unit_size).max(1)) as usize
308441 }
309442
@@ -1366,63 +1499,10 @@ mod tests {
13661499 use super::*;
13671500 use crate::msac::{SymbolDecoder, SymbolEncoder};
13681501
1369- /// `write_primitive_quniform`, the exact inverse of [`ns_msac`] -- used
1370- /// only to build roundtrip fixtures for the decode-only helpers above
1371- /// (this decoder never writes loop restoration itself).
1372- fn write_ns(enc: &mut SymbolEncoder, n: u32, v: u32) {
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- }
1502+ /// The write side these roundtrips exercise now lives beside the
1503+ /// readers (`write_ns`/`write_subexp`/`write_unsigned_subexp_with_ref`,
1504+ /// used by the encoder's per-unit LR syntax) instead of being a
1505+ /// test-only transcription of it -- one implementation, pinned here.
14261506
14271507 /// `decode_subexp_msac`/`ns_msac` roundtrip every value in a handful of
14281508 /// `(num_syms, k)` alphabets -- the shapes LR's tap ranges (`k` 1..=4,
@@ -1489,4 +1569,34 @@ mod tests {
14891569 }
14901570 }
14911571 }
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+ }
14921602 }
crates/ec-av1/src/stream.rsmodified+4 -3
@@ -28,7 +28,7 @@ use crate::decode::{
2828 q_ctx_of,
2929 };
3030 #[cfg(test)]
31-use crate::decode::decode_key_frame_tile;
31+use crate::decode::decode_key_frame_tile_lr;
3232 use crate::encode::Picture;
3333
3434 /// lane-midcut r1: `EC_AV1_NO_GRAIN=1` skips film grain synthesis at output, so a
@@ -2986,7 +2986,7 @@ mod tests {
29862986 for &(width, height) in &[(64usize, 64usize), (216, 96)] {
29872987 let picture = test_card(width, height);
29882988 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(
29902990 &encoded.tile,
29912991 encoded.mi_cols,
29922992 encoded.mi_rows,
@@ -3000,7 +3000,8 @@ mod tests {
30003000 // Our own encoder always writes `reduced_tx_set: true`.
30013001 true,
30023002 false,
3003- false, fctx,
3003+ false,
3004+ &encoded.loop_restoration, fctx,
30043005 )
30053006 .unwrap();
30063007 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
3131 // ([`CdefIdxGuard`] clears it on every exit path, error included), so a frame
3232 // that arms nothing writes no literals.
3333
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+
34118 /// One frame's per-superblock `cdef_idx` plan (see [`arm_cdef_idx`]).
35119 struct CdefIdxPlan {
36120 /// The header's `cdef_bits`; never 0 while armed.
@@ -65,6 +149,7 @@ struct CdefIdxGuard;
65149 impl Drop for CdefIdxGuard {
66150 fn drop(&mut self) {
67151 CDEF_IDX.with(|c| *c.borrow_mut() = None);
152+ LR_PLAN.with(|c| *c.borrow_mut() = None);
68153 }
69154 }
70155
@@ -1177,6 +1262,7 @@ pub fn sb_coeff_key_frame_tile_tx(
11771262 for sb_r in 0..sb_rows {
11781263 neighbours.start_row();
11791264 for sb_c in 0..sb_cols {
1265+ write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W);
11801266 let at = (sb_r as usize * 4, sb_c as usize * 4);
11811267 let ctx = neighbours.partition_ctx(at, SB);
11821268 ec_rng_trace(|| {
@@ -2836,6 +2922,7 @@ pub fn sb_coeff_inter_frame_tile_tx(
28362922 for sb_r in 0..sb_rows {
28372923 neighbours.start_row();
28382924 for sb_c in 0..sb_cols {
2925+ write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W);
28392926 let sb_at = (sb_r as usize * 4, sb_c as usize * 4);
28402927 let sb_ctx = neighbours.partition_ctx(sb_at, SB);
28412928 // spec `decode_partition`'s hasRows/hasCols (5.11.4): a superblock