forge
Explore
Log in

Don't you dare go Hollow

merge main (lane-av1lr) into lane-av1mv: pins re-measured with the extra-reference NEWMV in

Browse files at this commit

97b0f0880a178dab653d61dc7b36be23ad178593Ahmet Kaan GümüşParent: 242c43156a796a
crates/ec-av1/src/decode.rsmodified+142 -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),
@@ -20545,6 +20574,37 @@ fn apply_cdef(
2054520574 scratch_return(src_v);
2054620575 }
2054720576
20577+/// [`FrameCtx::capture_stages`]'s write side, called between CDEF and loop
20578+/// restoration on both tile paths: hands the encoder's restoration search the
20579+/// two pictures spec 7.17 filters from. `deblocked` is the decoder's own
20580+/// stripe-boundary snapshot ([`plane_snapshot`], only the rows LR reads), so
20581+/// a capture is worth three plane copies and nothing else -- and when the
20582+/// capture flag is off (every decode but that search) it is worth a bool.
20583+fn capture_stages(
20584+ y: &PlaneBuf<'_>,
20585+ u: &PlaneBuf<'_>,
20586+ v: &PlaneBuf<'_>,
20587+ deblocked: Option<&(PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>,
20588+ fctx: &FrameCtx,
20589+) {
20590+ if !fctx.capture_stages.get() {
20591+ return;
20592+ }
20593+ // Without an active restoration type the decoder took no pre-CDEF
20594+ // snapshot; the post-CDEF plane then stands in for it, which is exact
20595+ // everywhere but LR's own 3-row stripe borders (the encoder's search
20596+ // always asks with a type set, so this is the defensive arm).
20597+ let db = |i: usize, p: &PlaneBuf<'_>| match deblocked {
20598+ Some((a, b, c)) => [a, b, c][i].data.to_vec(),
20599+ None => p.data.to_vec(),
20600+ };
20601+ *fctx.stages.borrow_mut() = Some(FilterStages {
20602+ deblocked: [db(0, y), db(1, u), db(2, v)],
20603+ cdefed: [y.data.to_vec(), u.data.to_vec(), v.data.to_vec()],
20604+ stride: [y.width, u.width, v.width],
20605+ });
20606+}
20607+
2054820608 /// Spec 7.17: loop restoration, run after [`apply_cdef`] (a sibling lane's
2054920609 /// ordering note: libaom also runs `superres_post_decode` between the two,
2055020610 /// but this decoder never implements super-resolution, so there is nothing
@@ -20660,6 +20720,34 @@ pub(crate) fn decode_key_frame_tile(
2066020720 reduced_tx_set: bool,
2066120721 allow_screen_content_tools: bool,
2066220722 allow_intrabc: bool, fctx: &crate::decode::FrameCtx,
20723+) -> Result<Picture> {
20724+ decode_key_frame_tile_lr(
20725+ data, mi_cols, mi_rows, base_q_idx, frame_width, frame_height, enable_filter_intra,
20726+ cdef, loop_filter, tx_select, reduced_tx_set, allow_screen_content_tools, allow_intrabc,
20727+ &LoopRestorationParams::default(), fctx,
20728+ )
20729+}
20730+
20731+/// [`decode_key_frame_tile`] with this frame header's own `lr_params` (spec
20732+/// 5.9.20) instead of the no-restoration default -- the per-unit filters
20733+/// themselves live in the tile payload, so the header is all this needs.
20734+#[allow(clippy::too_many_arguments)]
20735+pub(crate) fn decode_key_frame_tile_lr(
20736+ data: &[u8],
20737+ mi_cols: u32,
20738+ mi_rows: u32,
20739+ base_q_idx: u8,
20740+ frame_width: u32,
20741+ frame_height: u32,
20742+ enable_filter_intra: bool,
20743+ cdef: &CdefParams,
20744+ loop_filter: &LoopFilterParams,
20745+ tx_select: bool,
20746+ reduced_tx_set: bool,
20747+ allow_screen_content_tools: bool,
20748+ allow_intrabc: bool,
20749+ lr: &LoopRestorationParams,
20750+ fctx: &crate::decode::FrameCtx,
2066320751 ) -> Result<Picture> {
2066420752 let delta = DeltaParams::default();
2066520753 let single_tile = TileInfo {
@@ -20680,7 +20768,7 @@ pub(crate) fn decode_key_frame_tile(
2068020768 false,
2068120769 cdef,
2068220770 loop_filter,
20683- &LoopRestorationParams::default(),
20771+ lr,
2068420772 None,
2068520773 tx_select,
2068620774 reduced_tx_set,
@@ -23019,6 +23107,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
2301923107 );
2302023108 dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v);
2302123109 dump_stage16("EC_AV1_POSTCDEF_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize);
23110+ capture_stages(&y, &u, &v, deblocked.as_ref(), fctx);
2302223111 // spec 7.16 (libaom `superres_post_decode`, decodeframe.c: called
2302323112 // between `av1_cdef_frame` and `av1_loop_restoration_filter_frame`):
2302423113 // the horizontal upscale runs HERE -- after CDEF, before loop
@@ -32780,6 +32869,37 @@ pub(crate) fn decode_inter_frame_tile(
3278032869 // class as `tx_select` above, third instance.
3278132870 initial_cdfs: Option<Cdfs>,
3278232871 fctx: &crate::decode::FrameCtx,
32872+) -> Result<Picture> {
32873+ decode_inter_frame_tile_lr(
32874+ data, mi_cols, mi_rows, base_q_idx, frame_width, frame_height, refpix, cdef,
32875+ loop_filter, allow_high_precision_mv, force_integer_mv, interp_fixed,
32876+ enable_dual_filter, reference_select, tx_select,
32877+ &LoopRestorationParams::default(), initial_cdfs, fctx,
32878+ )
32879+}
32880+
32881+/// [`decode_inter_frame_tile`] with this frame header's own `lr_params`, the
32882+/// inter sibling of [`decode_key_frame_tile_lr`].
32883+#[allow(clippy::too_many_arguments)]
32884+pub(crate) fn decode_inter_frame_tile_lr(
32885+ data: &[u8],
32886+ mi_cols: u32,
32887+ mi_rows: u32,
32888+ base_q_idx: u8,
32889+ frame_width: u32,
32890+ frame_height: u32,
32891+ refpix: &RefPix<'_>,
32892+ cdef: &CdefParams,
32893+ loop_filter: &LoopFilterParams,
32894+ allow_high_precision_mv: bool,
32895+ force_integer_mv: bool,
32896+ interp_fixed: Option<mc::InterpFilterKind>,
32897+ enable_dual_filter: bool,
32898+ reference_select: bool,
32899+ tx_select: bool,
32900+ lr: &LoopRestorationParams,
32901+ initial_cdfs: Option<Cdfs>,
32902+ fctx: &crate::decode::FrameCtx,
3278332903 ) -> Result<Picture> {
3278432904 let single_tile = TileInfo {
3278532905 mi_col_starts: vec![0, mi_cols],
@@ -32798,7 +32918,7 @@ pub(crate) fn decode_inter_frame_tile(
3279832918 refpix,
3279932919 cdef,
3280032920 loop_filter,
32801- &LoopRestorationParams::default(),
32921+ lr,
3280232922 initial_cdfs,
3280332923 allow_high_precision_mv,
3280432924 force_integer_mv,
@@ -35660,6 +35780,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3566035780 }
3566135781 dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v);
3566235782 dump_stage16("EC_AV1_POSTCDEF_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize);
35783+ capture_stages(&y, &u, &v, deblocked.as_ref(), fctx);
3566335784 // spec 7.16 (libaom `superres_post_decode`, decodeframe.c: called
3566435785 // between `av1_cdef_frame` and `av1_loop_restoration_filter_frame`):
3566535786 // the horizontal upscale runs HERE -- after CDEF, before loop
@@ -36803,9 +36924,10 @@ mod tests {
3680336924 tx_select,
3680436925 loop_filter,
3680536926 cdef,
36927+ loop_restoration,
3680636928 ..
3680736929 }: Encoded = crate::encode::encode_key_frame_with_modes_with_ctx(&picture, 40, 0.0, modes, fctx).unwrap();
36808- let decoded = decode_key_frame_tile(
36930+ let decoded = decode_key_frame_tile_lr(
3680936931 &tile,
3681036932 mi_cols,
3681136933 mi_rows,
@@ -36818,7 +36940,8 @@ mod tests {
3681836940 tx_select,
3681936941 true,
3682036942 false,
36821- false, fctx,
36943+ false,
36944+ &loop_restoration, fctx,
3682236945 )
3682336946 .unwrap();
3682436947 assert_eq!(decoded.width, w, "{w}x{h}: decoded width");
@@ -37173,7 +37296,7 @@ mod tests {
3717337296 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
3717437297 let (coded_w, coded_h) = ffprobe_size(&encoded.stream);
3717537298 let ffmpeg_decoded = ffmpeg_decode(&encoded.stream, coded_w as usize, coded_h as usize);
37176- let ours = decode_key_frame_tile(
37299+ let ours = decode_key_frame_tile_lr(
3717737300 &encoded.tile,
3717837301 encoded.mi_cols,
3717937302 encoded.mi_rows,
@@ -37186,7 +37309,8 @@ mod tests {
3718637309 encoded.tx_select,
3718737310 true,
3718837311 false,
37189- false, fctx,
37312+ false,
37313+ &encoded.loop_restoration, fctx,
3719037314 )
3719137315 .unwrap();
3719237316 assert_eq!(ours.y, ffmpeg_decoded.y, "{width}x{height}: luma vs ffmpeg");
@@ -37216,7 +37340,7 @@ mod tests {
3721637340 gate's premise moved, not the decoder"
3721737341 );
3721837342 let decode = |tx_select: bool| {
37219- decode_key_frame_tile(
37343+ decode_key_frame_tile_lr(
3722037344 &encoded.tile,
3722137345 encoded.mi_cols,
3722237346 encoded.mi_rows,
@@ -37230,6 +37354,7 @@ mod tests {
3723037354 true,
3723137355 false,
3723237356 false,
37357+ &encoded.loop_restoration,
3723337358 fctx,
3723437359 )
3723537360 };
@@ -37300,7 +37425,7 @@ mod tests {
3730037425 assert_eq!(encoded.frames.len(), 4);
3730137426
3730237427 let key = &encoded.frames[0];
37303- let mut reference = decode_key_frame_tile(
37428+ let mut reference = decode_key_frame_tile_lr(
3730437429 &key.tile,
3730537430 key.mi_cols,
3730637431 key.mi_rows,
@@ -37313,7 +37438,8 @@ mod tests {
3731337438 key.tx_select,
3731437439 true,
3731537440 false,
37316- false, fctx,
37441+ false,
37442+ &key.loop_restoration, fctx,
3731737443 )
3731837444 .unwrap();
3731937445 assert_eq!(
@@ -37330,7 +37456,7 @@ mod tests {
3733037456 );
3733137457
3733237458 for (i, frame) in encoded.frames.iter().enumerate().skip(1) {
37333- let decoded = decode_inter_frame_tile(
37459+ let decoded = decode_inter_frame_tile_lr(
3733437460 &frame.tile,
3733537461 frame.mi_cols,
3733637462 frame.mi_rows,
@@ -37350,6 +37476,7 @@ mod tests {
3735037476 false,
3735137477 false,
3735237478 frame.tx_select,
37479+ &frame.loop_restoration,
3735337480 Some(frame.start_cdfs.0.clone()),
3735437481 fctx,
3735537482 )
@@ -37627,7 +37754,7 @@ mod tests {
3762737754 ffmpeg_decode_sequence(&encoded.stream, coded_w as usize, coded_h as usize, 3);
3762837755
3762937756 let key = &encoded.frames[0];
37630- let mut reference = decode_key_frame_tile(
37757+ let mut reference = decode_key_frame_tile_lr(
3763137758 &key.tile,
3763237759 key.mi_cols,
3763337760 key.mi_rows,
@@ -37640,13 +37767,14 @@ mod tests {
3764037767 key.tx_select,
3764137768 true,
3764237769 false,
37643- false, fctx,
37770+ false,
37771+ &key.loop_restoration, fctx,
3764437772 )
3764537773 .unwrap();
3764637774 assert_eq!(reference.y, ffmpeg_frames[0].y, "frame 0 luma vs ffmpeg");
3764737775
3764837776 for (i, frame) in encoded.frames.iter().enumerate().skip(1) {
37649- let decoded = decode_inter_frame_tile(
37777+ let decoded = decode_inter_frame_tile_lr(
3765037778 &frame.tile,
3765137779 frame.mi_cols,
3765237780 frame.mi_rows,
@@ -37666,6 +37794,7 @@ mod tests {
3766637794 false,
3766737795 false,
3766837796 frame.tx_select,
37797+ &frame.loop_restoration,
3766937798 Some(frame.start_cdfs.0.clone()),
3767037799 fctx,
3767137800 )
crates/ec-av1/src/encode.rsmodified+240 -30
@@ -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
@@ -215,6 +215,20 @@ fn split_inter_blocks() -> bool {
215215 }
216216 }
217217
218+/// Whether the encoder searches loop restoration at all (spec 7.17): one
219+/// Wiener filter per 64x64 luma restoration unit, picked from
220+/// [`crate::filter_search::WIENER_CANDIDATES`]. Swept by `EC_AV1_LR` in a
221+/// test build, like [`lambda_scale`].
222+const RESTORATION: bool = true;
223+
224+/// [`RESTORATION`], or what `EC_AV1_LR` names in a test build.
225+fn restoration_enabled() -> bool {
226+ match std::env::var("EC_AV1_LR").ok() {
227+ Some(v) if cfg!(test) => v != "0",
228+ _ => RESTORATION,
229+ }
230+}
231+
218232 /// libaom's `partition_search_breakout` shape: how many non-zero luma
219233 /// coefficients per 256 luma samples a block may code and still be judged
220234 /// well enough predicted that the split below it is not worth trying. `0`
@@ -505,6 +519,7 @@ pub(crate) fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> En
505519 start_cdfs: encoded.start_cdfs.clone(),
506520 next_cdfs: encoded.next_cdfs.clone(),
507521 loop_filter: encoded.loop_filter,
522+ loop_restoration: encoded.loop_restoration,
508523 cdef: encoded.cdef,
509524 }
510525 }
@@ -574,6 +589,11 @@ pub struct Encoded {
574589 /// This frame header's chosen CDEF parameters, threaded for the same
575590 /// reason as `loop_filter`.
576591 pub(crate) cdef: CdefParams,
592+ /// This frame header's chosen loop restoration parameters, threaded for
593+ /// the same reason as `loop_filter` -- and doubly so: the per-unit
594+ /// filters themselves are coded in `tile`, so a decode of it under a
595+ /// stale `RESTORE_NONE` header desyncs at the first superblock.
596+ pub(crate) loop_restoration: LoopRestorationParams,
577597 }
578598
579599 /// The sequence and frame headers a picture of this size is coded under: one
@@ -658,7 +678,7 @@ pub(crate) fn key_frame_headers_colour(
658678 // `cdef_idx` literal is coded in the tile and a frame that wants no
659679 // CDEF simply carries zero strengths.
660680 enable_cdef: true,
661- enable_restoration: false,
681+ enable_restoration: true,
662682 seq_force_screen_content_tools: 0,
663683 seq_force_integer_mv: 0,
664684 color_config,
@@ -3123,11 +3143,12 @@ pub(crate) fn encode_key_frame_inner(
31233143 // set, so what it stores into the slots it refreshes is exactly those
31243144 // defaults again (spec 7.20's `started_from` arm) -- the first inter
31253145 // frame after it therefore starts from the defaults too.
3146+ let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
31263147 let mut cdfs = crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx));
31273148 let start_cdfs = CdfSnapshot(cdfs.clone());
3128- let tile = crate::tile::sb_coeff_key_frame_tile_cdfs(
3129- header.mi_cols,
3130- header.mi_rows,
3149+ let mut tile = crate::tile::sb_coeff_key_frame_tile_cdfs(
3150+ mi_cols,
3151+ mi_rows,
31313152 base_q_idx,
31323153 &superblocks,
31333154 tx_select,
@@ -3138,16 +3159,41 @@ pub(crate) fn encode_key_frame_inner(
31383159 // `crate::filter_search`), and keep the filtered picture that wins as
31393160 // the reconstruction -- what a decoder outputs, and what the next
31403161 // frame predicts from.
3162+ // The luma restoration-unit grid this frame's `lr_params` implies
3163+ // (`av1_lr_count_units` rounds to nearest, so a short last unit is
3164+ // swallowed by the one before it), for the tile writer's own per-unit
3165+ // walk.
3166+ let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32;
3167+ let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32;
31413168 pick_and_apply_filters(
31423169 &mut header,
31433170 &mut luma,
31443171 &mut chroma,
31453172 [&picture_y8, &picture_u8, &picture_v8],
31463173 true,
3174+ &mut tile,
3175+ search.lambda,
31473176 fctx,
3148- |lf, cdef, h| {
3149- crate::decode::decode_key_frame_tile(
3150- &tile,
3177+ // Every re-code starts from this frame's OWN starting tables, never
3178+ // from where the first write left them: the second tile is the same
3179+ // symbol sequence plus new ones, so it must adapt from the same
3180+ // point the decoder will.
3181+ |bits, sb_cols, grid, units| {
3182+ crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());
3183+ crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());
3184+ let mut cdfs = start_cdfs.0.clone();
3185+ crate::tile::sb_coeff_key_frame_tile_cdfs(
3186+ mi_cols,
3187+ mi_rows,
3188+ base_q_idx,
3189+ &superblocks,
3190+ tx_select,
3191+ &mut cdfs,
3192+ )
3193+ },
3194+ |lf, cdef, h, tile, lr| {
3195+ crate::decode::decode_key_frame_tile_lr(
3196+ tile,
31513197 h.mi_cols,
31523198 h.mi_rows,
31533199 base_q_idx,
@@ -3160,6 +3206,7 @@ pub(crate) fn encode_key_frame_inner(
31603206 h.reduced_tx_set,
31613207 h.allow_screen_content_tools,
31623208 h.allow_intrabc,
3209+ lr,
31633210 fctx,
31643211 )
31653212 },
@@ -3189,6 +3236,7 @@ pub(crate) fn encode_key_frame_inner(
31893236 start_cdfs,
31903237 loop_filter: header.loop_filter,
31913238 cdef: header.cdef,
3239+ loop_restoration: header.loop_restoration,
31923240 })
31933241 }
31943242
@@ -3212,8 +3260,21 @@ fn pick_and_apply_filters(
32123260 chroma: &mut [Plane<'_>; 2],
32133261 source: [&[u8]; 3],
32143262 search: bool,
3263+ // The coded tile, replaced in place when the search chooses a per-64x64
3264+ // `cdef_idx` list (`cdef_bits > 0`): those literals live in the tile
3265+ // payload, so the tile is written a second time under `recode` and the
3266+ // winner re-decoded from it.
3267+ tile: &mut Vec<u8>,
3268+ lambda: f64,
32153269 fctx: &crate::decode::FrameCtx,
3216- decode: impl Fn(&LoopFilterParams, &CdefParams, &FrameHeader) -> Result<Picture>,
3270+ recode: impl Fn(u8, usize, &[u8], &[Option<crate::restoration::WienerInfo>]) -> Result<Vec<u8>>,
3271+ decode: impl Fn(
3272+ &LoopFilterParams,
3273+ &CdefParams,
3274+ &FrameHeader,
3275+ &[u8],
3276+ &LoopRestorationParams,
3277+ ) -> Result<Picture>,
32173278 ) -> Result<()> {
32183279 if !search {
32193280 return Ok(());
@@ -3223,9 +3284,14 @@ fn pick_and_apply_filters(
32233284 // libaom `av1_pick_filter_level`'s sibling `av1_cdef_search`:
32243285 // `cdef_damping = 3 + (base_qindex >> 6)`, never searched.
32253286 let damping = 3 + (header.quantization.base_q_idx >> 6);
3287+ let (cols32, rows32) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
3288+ let (sb_cols, sb_rows) = (cols32.div_ceil(2) as usize, rows32.div_ceil(2) as usize);
3289+ let none_lr = LoopRestorationParams::default();
32263290 // Every candidate scores the same coded tile: decode it once and re-run
32273291 // the filters alone for the rest (`crate::decode::FilterReplay`, 24% of
3228- // the encoder's profile before this).
3292+ // the encoder's profile before this). The per-64x64 error the CDEF
3293+ // preset search reads comes off the REPLAYED picture, which is the same
3294+ // picture a decode produces -- that is what the replay is pinned on.
32293295 crate::decode::clear_filter_replay();
32303296 let search_result = crate::filter_search::pick_filters(
32313297 |lf, cdef| {
@@ -3233,17 +3299,80 @@ fn pick_and_apply_filters(
32333299 return Ok(picture);
32343300 }
32353301 crate::decode::arm_filter_replay();
3236- decode(lf, cdef, &hdr)
3302+ decode(lf, cdef, &hdr, tile, &none_lr)
32373303 },
32383304 source,
32393305 luma.width,
32403306 (fw, fh),
32413307 damping,
3308+ (sb_cols, sb_rows),
3309+ lambda,
32423310 );
32433311 crate::decode::clear_filter_replay();
3244- let (lf, cdef, filtered) = search_result?;
3312+ let (lf, cdef, idx_grid, picture) = search_result?;
32453313 header.loop_filter = lf;
32463314 header.cdef = cdef;
3315+ // spec 7.17: loop restoration. Its per-unit filters live in the TILE, not
3316+ // in the frame header, so a re-decode under candidate parameters cannot
3317+ // search them the way deblocking and CDEF are searched above. What the
3318+ // decoder hands back instead is its own filter chain's intermediates
3319+ // (`crate::decode::FrameCtx::capture_stages`), and the search runs on
3320+ // those, through the decoder's own Wiener kernel.
3321+ //
3322+ // The capture rides the decode this stage was already going to do: the
3323+ // re-decode of the `cdef_idx` tile when there is one, and otherwise one
3324+ // decode of the tile as it stands. That decode's header still says
3325+ // `RESTORE_NONE`, so the decoder takes no pre-CDEF snapshot and the
3326+ // post-CDEF picture stands in for it at LR's 3-row stripe borders --
3327+ // an approximation inside the SEARCH only; the reconstruction this
3328+ // function ends up splicing is always a real decode of the real tile.
3329+ let lr_on = restoration_enabled();
3330+ fctx.capture_stages.set(lr_on);
3331+ let mut filtered = if idx_grid.is_empty() {
3332+ if lr_on {
3333+ decode(&lf, &cdef, &hdr, tile, &none_lr)?
3334+ } else {
3335+ picture
3336+ }
3337+ } else {
3338+ let coded = recode(cdef.bits, sb_cols, &idx_grid, &[])?;
3339+ let picture = decode(&lf, &cdef, &hdr, &coded, &none_lr)?;
3340+ *tile = coded;
3341+ picture
3342+ };
3343+ fctx.capture_stages.set(false);
3344+ let mut lr = LoopRestorationParams::default();
3345+ if lr_on {
3346+ let mut want = LoopRestorationParams {
3347+ loop_restoration_size: [64, 64, 64],
3348+ uses_lr: true,
3349+ ..LoopRestorationParams::default()
3350+ };
3351+ want.frame_restoration_type[0] = ec_av1_syntax::RestorationType::Wiener;
3352+ let units = match crate::decode::take_filter_stages(fctx) {
3353+ Some(stages) => crate::filter_search::pick_restoration(
3354+ &stages,
3355+ source[0],
3356+ luma.width,
3357+ (fw, fh),
3358+ &want,
3359+ lambda,
3360+ fctx,
3361+ ),
3362+ None => Vec::new(),
3363+ };
3364+ // A frame no unit restores keeps `RESTORE_NONE` on every plane
3365+ // rather than paying ~1 bit per 64x64 for a tile full of
3366+ // `restore_wiener = 0` symbols (the BD gate saw exactly that on the
3367+ // clip whose units never take a filter).
3368+ if units.iter().any(Option::is_some) {
3369+ let coded = recode(cdef.bits, sb_cols, &idx_grid, &units)?;
3370+ filtered = decode(&lf, &cdef, &hdr, &coded, &want)?;
3371+ *tile = coded;
3372+ lr = want;
3373+ }
3374+ }
3375+ header.loop_restoration = lr;
32473376 let dec_cw = filtered.width.div_ceil(2);
32483377 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));
32493378 crate::filter_search::splice(&mut luma.reconstruction, luma.width, &filtered.y, filtered.width, fw, fh);
@@ -4515,13 +4644,14 @@ pub(crate) fn encode_inter_frame(
45154644 // stores its end-of-tile tables with the counts reset (spec 7.20) and the
45164645 // next frame's writer starts from them -- exactly what
45174646 // `crate::stream::stored_cdfs_for` hands the decoder.
4647+ let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
45184648 let mut cdfs = start_cdfs
45194649 .cloned()
45204650 .unwrap_or_else(|| crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx)));
45214651 let start_cdfs = CdfSnapshot(cdfs.clone());
4522- let tile = crate::tile::sb_coeff_inter_frame_tile_cdfs(
4523- header.mi_cols,
4524- header.mi_rows,
4652+ let mut tile = crate::tile::sb_coeff_inter_frame_tile_cdfs(
4653+ mi_cols,
4654+ mi_rows,
45254655 base_q_idx,
45264656 &blocks,
45274657 tx_select,
@@ -4535,6 +4665,7 @@ pub(crate) fn encode_inter_frame(
45354665 // reference whose height is not the header's own `frame_height` (spec
45364666 // 7.9's compatible-size rule), and the chained-decode round trips prove
45374667 // the two predict identically.
4668+ let end_cdfs = std::cell::RefCell::new(cdfs);
45384669 let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);
45394670 let trial_ref = if (reference.width, reference.height) == (fw, fh) {
45404671 reference.clone()
@@ -4581,6 +4712,12 @@ pub(crate) fn encode_inter_frame(
45814712 refs[4] = trial_golden.as_ref();
45824713 refs[7] = trial_altref.as_ref();
45834714 let refpix = crate::decode::RefPix::ready(refs);
4715+ // The luma restoration-unit grid this frame's `lr_params` implies
4716+ // (`av1_lr_count_units` rounds to nearest, so a short last unit is
4717+ // swallowed by the one before it), for the tile writer's own per-unit
4718+ // walk.
4719+ let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32;
4720+ let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32;
45844721 pick_and_apply_filters(
45854722 &mut header,
45864723 &mut luma,
@@ -4591,10 +4728,33 @@ pub(crate) fn encode_inter_frame(
45914728 // `TxMode::Select` too (it used to skip and leave every inter frame
45924729 // unfiltered once Select became the default).
45934730 true,
4731+ &mut tile,
4732+ search.lambda,
45944733 fctx,
4595- |lf, cdef, h| {
4596- crate::decode::decode_inter_frame_tile(
4597- &tile,
4734+ // As in `encode_key_frame_inner`, but this frame's end-of-tile tables
4735+ // are what the NEXT frame writes from, so the winning re-code
4736+ // publishes its own into `end_cdfs` -- the first write's are stale
4737+ // the moment a second tile is coded.
4738+ |bits, sb_cols, grid, units| {
4739+ crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());
4740+ crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());
4741+ let mut cdfs = start_cdfs.0.clone();
4742+ let coded = crate::tile::sb_coeff_inter_frame_tile_cdfs(
4743+ mi_cols,
4744+ mi_rows,
4745+ base_q_idx,
4746+ &blocks,
4747+ tx_select,
4748+ &mut cdfs,
4749+ );
4750+ if coded.is_ok() {
4751+ *end_cdfs.borrow_mut() = cdfs;
4752+ }
4753+ coded
4754+ },
4755+ |lf, cdef, h, tile, lr| {
4756+ crate::decode::decode_inter_frame_tile_lr(
4757+ tile,
45984758 h.mi_cols,
45994759 h.mi_rows,
46004760 base_q_idx,
@@ -4609,6 +4769,7 @@ pub(crate) fn encode_inter_frame(
46094769 seq.enable_dual_filter,
46104770 h.reference_select,
46114771 tx_select,
4772+ lr,
46124773 // The trial decode re-reads the tile the writer just wrote,
46134774 // so it starts from the same tables the writer did (this
46144775 // frame's `start_cdfs`), not from the defaults.
@@ -4617,6 +4778,7 @@ pub(crate) fn encode_inter_frame(
46174778 )
46184779 },
46194780 )?;
4781+ let mut cdfs = end_cdfs.into_inner();
46204782 cdfs.reset_counts();
46214783 let next_cdfs = CdfSnapshot(cdfs);
46224784 let mut stream = temporal_delimiter();
@@ -4643,6 +4805,7 @@ pub(crate) fn encode_inter_frame(
46434805 next_cdfs,
46444806 loop_filter: header.loop_filter,
46454807 cdef: header.cdef,
4808+ loop_restoration: header.loop_restoration,
46464809 })
46474810 }
46484811
@@ -6665,11 +6828,18 @@ mod tests {
66656828 assert_eq!(predicted.len(), encoded.frames.len());
66666829
66676830 eprintln!("frame predicted bits written bits drift");
6668- let mut worst: f64 = 0.0;
6831+ // Split by sign: a NEGATIVE drift is the search OVER-pricing (the
6832+ // defect this gate exists to catch), a positive one is the written
6833+ // side carrying syntax the coefficient sum leaves out -- and since
6834+ // lane-av1mv an extra reference's `NEWMV` puts a whole MV residual
6835+ // on that side, so the two directions no longer share a bound.
6836+ let mut worst_over: f64 = 0.0;
6837+ let mut worst_under: f64 = 0.0;
66696838 for (i, (frame, &bits)) in encoded.frames.iter().zip(&predicted).enumerate() {
66706839 let written = frame.tile.len() as f64 * 8.0;
66716840 let drift = (written - bits) / written;
6672- worst = worst.max(drift.abs());
6841+ worst_over = worst_over.max(-drift);
6842+ worst_under = worst_under.max(drift);
66736843 eprintln!("{i:5} {bits:14.0} {written:12.0} {:+6.2}%", drift * 100.0);
66746844 }
66756845 // Measured 2026-09-06 on this sequence: -13.5% at the key frame,
@@ -6681,9 +6851,18 @@ mod tests {
66816851 // set just above the worst measured point -- a widening drift is the
66826852 // thing this gate exists to catch.
66836853 assert!(
6684- worst <= 0.16,
6685- "the search's rate term drifted {:.2}% from the bits the writer spent",
6686- worst * 100.0
6854+ worst_over <= 0.16,
6855+ "the search's rate term OVER-priced by {:.2}% against the bits the writer spent",
6856+ worst_over * 100.0
6857+ );
6858+ // Measured 2026-09-06 with the extra-reference `NEWMV` in: +18.9% at
6859+ // the worst inter frame, where nearly every block now codes an MV
6860+ // residual and a reference the coefficient sum never counts.
6861+ assert!(
6862+ worst_under <= 0.22,
6863+ "the writer spent {:.2}% more than the search priced -- more than \
6864+ the mode/mv syntax outside the coefficient sum explains",
6865+ worst_under * 100.0
66876866 );
66886867 }
66896868
@@ -7446,11 +7625,11 @@ mod tests {
74467625 ///
74477626 /// The BD gate above measures quality, which a speed lane can move by a
74487627 /// hair without failing anything; this pins the streams themselves.
7449- /// Every number below was measured 2026-09-06 (lane-av1fwd) and is
7450- /// identical at `a6649c4e`, the merge before that lane's three exact
7451- /// speed steps; the q=150 pin moved with lane-av1mv's extra-reference
7452- /// `NEWMV` (a coded-bits change, not a speed step -- the BD gate is what
7453- /// judged it).
7628+ /// Re-measured on the lane-av1lr merge with main d5fc99e0 (per-64x64
7629+ /// `cdef_idx` literals and per-unit loop restoration syntax are new bits
7630+ /// in the tile) and again on lane-av1mv's merge of it: an extra
7631+ /// reference's `NEWMV` is a coded-bits change too, judged by the BD gate
7632+ /// above, not by this pin.
74547633 #[test]
74557634 fn the_encoders_own_streams_are_byte_identical_to_their_pins() {
74567635 if !have_ffmpeg() {
@@ -7472,7 +7651,7 @@ mod tests {
74727651 })
74737652 };
74747653 let pins: [(u8, usize, u64); 2] =
7475- [(150, 7397, 0xca56a6962842df67), (60, 27780, 0x584a5034ed4c3b27)];
7654+ [(150, 7444, 0x76eb980832d719f1), (60, 27692, 0x8c88f7e73455d439)];
74767655 for (q, bytes, hash) in pins {
74777656 let encoded = encode_sequence(&source, q, 0.5).unwrap();
74787657 assert_eq!(
@@ -7704,6 +7883,37 @@ mod tests {
77047883 mean(|l| l.2.0),
77057884 mean(|l| l.2.1),
77067885 );
7886+ // How many strength presets each frame's CDEF list carried and
7887+ // how the 64x64 units spread over them (lane-av1lr): `bits 0`
7888+ // everywhere would mean the per-unit choice never fires.
7889+ let presets = crate::filter_search::take_cdef_presets();
7890+ let mut by_bits = [0usize; 4];
7891+ for (b, _) in &presets {
7892+ by_bits[usize::from(*b)] += 1;
7893+ }
7894+ let units: usize = presets.iter().flat_map(|(_, c)| c).sum();
7895+ let on_extra: usize = presets
7896+ .iter()
7897+ .flat_map(|(_, c)| c.iter().skip(1))
7898+ .sum();
7899+ eprintln!(
7900+ "{name}: cdef_bits frames {}/{}/{}/{} (0/1/2/3); {} of {} 64x64 units \
7901+ on a non-default preset ({:.1}%)",
7902+ by_bits[0],
7903+ by_bits[1],
7904+ by_bits[2],
7905+ by_bits[3],
7906+ on_extra,
7907+ units,
7908+ 100.0 * on_extra as f64 / units.max(1) as f64
7909+ );
7910+ // How the 64x64 luma restoration units split between
7911+ // RESTORE_NONE and Wiener (lane-av1lr).
7912+ let (lr_none, lr_wiener) = crate::filter_search::take_lr_histogram();
7913+ eprintln!(
7914+ "{name}: lr units none={lr_none} wiener={lr_wiener} ({:.1}% restored)",
7915+ 100.0 * lr_wiener as f64 / (lr_none + lr_wiener).max(1) as f64
7916+ );
77077917 // Which chroma modes the search actually wins with, against the
77087918 // unconditional DC_PRED that was the only outcome before
77097919 // (gate-blind-to-feature).
crates/ec-av1/src/filter_search.rsmodified+278 -3
@@ -40,6 +40,20 @@ pub(crate) fn take_chosen_levels() -> Vec<((u8, u8), (u8, u8), (u8, u8))> {
4040 })
4141 }
4242
43+thread_local! {
44+ /// Per frame, in coding order: the `cdef_bits` chosen and how many 64x64
45+ /// superblocks ended up on each strength preset -- the BD gate prints the
46+ /// distribution once per clip (gate-blind-to-feature).
47+ static PRESET_COUNTS: std::cell::RefCell<Vec<(u8, Vec<usize>)>> =
48+ const { std::cell::RefCell::new(Vec::new()) };
49+}
50+
51+/// Takes and clears [`PRESET_COUNTS`].
52+#[allow(dead_code)] // read from the `#[cfg(test)]` BD gate
53+pub(crate) fn take_cdef_presets() -> Vec<(u8, Vec<usize>)> {
54+ PRESET_COUNTS.with(|c| std::mem::take(&mut *c.borrow_mut()))
55+}
56+
4357 /// Squared error between a decoded plane and the source it was coded from,
4458 /// over the frame's own cropped `w x h` (the two planes have different
4559 /// strides: the source is the encoder's padded coding surface).
@@ -55,6 +69,31 @@ fn plane_sse(dec: &[u16], dec_w: usize, src: &[u8], src_w: usize, w: usize, h: u
5569 sse
5670 }
5771
72+/// [`plane_sse`], accumulated per CDEF unit instead of over the frame: `out`
73+/// is one entry per 64x64 SUPERBLOCK (stride `sb_cols`) and `unit` is the
74+/// unit side in this plane's own samples (64 for luma, 32 for 4:2:0 chroma),
75+/// which is what makes the luma and chroma sums land in the same slot.
76+fn unit_sse(
77+ dec: &[u16],
78+ dec_w: usize,
79+ src: &[u8],
80+ src_w: usize,
81+ w: usize,
82+ h: usize,
83+ unit: usize,
84+ sb_cols: usize,
85+ out: &mut [u64],
86+) {
87+ for row in 0..h {
88+ let base = (row / unit) * sb_cols;
89+ let (d, s) = (&dec[row * dec_w..][..w], &src[row * src_w..][..w]);
90+ for (col, (&a, &b)) in d.iter().zip(s).enumerate() {
91+ let diff = i64::from(a) - i64::from(b);
92+ out[base + col / unit] += (diff * diff) as u64;
93+ }
94+ }
95+}
96+
5897 /// CDEF primary strengths tried (libaom's own range is 0..15 for 8-bit
5998 /// content) and the secondary ladder, whose only legal values are 0, 1, 2
6099 /// and 4 -- 3 is not codeable (spec 5.9.19 codes a secondary strength of 4
@@ -82,6 +121,10 @@ struct Trial {
82121 picture: Picture,
83122 sse_y: u64,
84123 sse_uv: u64,
124+ /// Luma + chroma error per 64x64 CDEF unit, in the tile writer's own
125+ /// superblock raster order -- what the per-unit `cdef_idx` choice below
126+ /// is made on.
127+ sse64: Vec<u64>,
85128 }
86129
87130 /// Picks this frame's deblocking levels and CDEF strengths and hands back
@@ -111,8 +154,11 @@ pub(crate) fn pick_filters(
111154 src_w: usize,
112155 (fw, fh): (usize, usize),
113156 damping: u8,
114-) -> Result<(LoopFilterParams, CdefParams, Picture)> {
157+ (sb_cols, sb_rows): (usize, usize),
158+ lambda: f64,
159+) -> Result<(LoopFilterParams, CdefParams, Vec<u8>, Picture)> {
115160 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));
161+ let nsb = sb_cols * sb_rows;
116162 let mut trials: Vec<Trial> = Vec::new();
117163 let eval = |cand: Cand, trials: &mut Vec<Trial>| -> Result<usize> {
118164 if let Some(i) = trials.iter().position(|t| t.cand == cand) {
@@ -123,7 +169,11 @@ pub(crate) fn pick_filters(
123169 let sse_y = plane_sse(&picture.y, picture.width, source[0], src_w, fw, fh);
124170 let sse_uv = plane_sse(&picture.u, dec_cw, source[1], src_w / 2, cw, ch)
125171 + plane_sse(&picture.v, dec_cw, source[2], src_w / 2, cw, ch);
126- trials.push(Trial { cand, picture, sse_y, sse_uv });
172+ let mut sse64 = vec![0u64; nsb];
173+ unit_sse(&picture.y, picture.width, source[0], src_w, fw, fh, 64, sb_cols, &mut sse64);
174+ unit_sse(&picture.u, dec_cw, source[1], src_w / 2, cw, ch, 32, sb_cols, &mut sse64);
175+ unit_sse(&picture.v, dec_cw, source[2], src_w / 2, cw, ch, 32, sb_cols, &mut sse64);
176+ trials.push(Trial { cand, picture, sse_y, sse_uv, sse64 });
127177 Ok(trials.len() - 1)
128178 };
129179 // One stage of the coordinate search: try `values` in the slot `set`
@@ -168,11 +218,100 @@ pub(crate) fn pick_filters(
168218 stage(&mut best, &CDEF_SEC, |c, v| c.uv.1 = v, |t| t.sse_uv, &mut trials)?;
169219
170220 CHOSEN.with(|c| c.borrow_mut().push(best));
221+
222+ // libaom `av1_cdef_search`'s shape, on the candidates this coordinate
223+ // search already decoded: every trial that ran under the WINNING
224+ // deblocking levels is a legal strength pair for this frame, and each
225+ // one already carries its own per-64x64 error. Pick up to eight of them
226+ // as the header's strength list and give every superblock the one that
227+ // costs it least -- the `cdef_idx` literal the tile writer then codes
228+ // (`crate::tile::arm_cdef_idx`).
229+ let mut presets: Vec<Cand> = vec![best];
230+ let pool: Vec<Cand> = trials
231+ .iter()
232+ .map(|t| t.cand)
233+ .filter(|c| c.lf == best.lf && *c != best)
234+ .collect();
235+ // How often each pool candidate would win a superblock outright, which
236+ // is the order the list is grown in (libaom picks its presets by the
237+ // same per-unit histogram, not by frame-level error).
238+ let sse_of = |c: &Cand| -> &Vec<u64> {
239+ &trials
240+ .iter()
241+ .find(|t| t.cand == *c)
242+ .expect("every pool candidate was evaluated")
243+ .sse64
244+ };
245+ let mut counts = vec![0usize; pool.len()];
246+ let best_sse = sse_of(&best).clone();
247+ for sb in 0..nsb {
248+ let mut winner = (best_sse[sb], usize::MAX);
249+ for (i, c) in pool.iter().enumerate() {
250+ if sse_of(c)[sb] < winner.0 {
251+ winner = (sse_of(c)[sb], i);
252+ }
253+ }
254+ if winner.1 != usize::MAX {
255+ counts[winner.1] += 1;
256+ }
257+ }
258+ let mut order: Vec<usize> = (0..pool.len()).collect();
259+ order.sort_by_key(|&i| std::cmp::Reverse(counts[i]));
260+ presets.extend(order.iter().take(7).map(|&i| pool[i]));
261+ // The cheapest list length: `bits` costs one literal per superblock plus
262+ // twelve header bits per extra pair, and buys whatever per-unit error the
263+ // wider choice removes.
264+ let unit_min = |n: usize, sb: usize| -> u64 {
265+ presets[..n].iter().map(|c| sse_of(c)[sb]).min().unwrap_or(0)
266+ };
267+ let mut bits = 0u8;
268+ let mut cost = best_sse.iter().sum::<u64>() as f64;
269+ for b in 1..=3u8 {
270+ let n = 1usize << b;
271+ if n > presets.len() {
272+ break;
273+ }
274+ let sse: u64 = (0..nsb).map(|sb| unit_min(n, sb)).sum();
275+ let c = sse as f64 + lambda * ((b as usize * nsb) as f64 + 12.0 * (n - 1) as f64);
276+ if c < cost {
277+ cost = c;
278+ bits = b;
279+ }
280+ }
281+ let grid: Vec<u8> = if bits == 0 {
282+ Vec::new()
283+ } else {
284+ let n = 1usize << bits;
285+ (0..nsb)
286+ .map(|sb| {
287+ (0..n)
288+ .min_by_key(|&i| sse_of(&presets[i])[sb])
289+ .expect("at least one preset") as u8
290+ })
291+ .collect()
292+ };
293+ let mut params = cdef(best, damping);
294+ params.bits = bits;
295+ for (i, c) in presets.iter().take(1usize << bits).enumerate() {
296+ params.y_pri_strength[i] = c.y.0;
297+ params.y_sec_strength[i] = c.y.1;
298+ params.uv_pri_strength[i] = c.uv.0;
299+ params.uv_sec_strength[i] = c.uv.1;
300+ }
301+ let mut counts_used = vec![0usize; 1usize << bits];
302+ for &g in &grid {
303+ counts_used[usize::from(g)] += 1;
304+ }
305+ if grid.is_empty() {
306+ counts_used = vec![nsb];
307+ }
308+ PRESET_COUNTS.with(|c| c.borrow_mut().push((bits, counts_used)));
309+
171310 let win = trials
172311 .into_iter()
173312 .find(|t| t.cand == best)
174313 .expect("the winning candidate was evaluated");
175- Ok((loop_filter(best), cdef(best, damping), win.picture))
314+ Ok((loop_filter(best), params, grid, win.picture))
176315 }
177316
178317 /// The header's `loop_filter_params` for one candidate.
@@ -205,3 +344,139 @@ pub(crate) fn splice(dst: &mut [u8], dst_w: usize, src: &[u16], src_w: usize, w:
205344 }
206345 }
207346 }
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+173 -2
@@ -20,6 +20,163 @@ use crate::decode::{TXFM_CTX_INIT, txfm_partition_ctx_rect};
2020 use crate::msac::SymbolEncoder;
2121 use crate::mvstack::{MiGrid, MiInfo, NO_REF1, find_mv_stack, mv16};
2222
23+// ---------------------------------------------------------------------------
24+// lane-av1lr: per-64x64 `cdef_idx` (spec 5.11.56, `read_cdef`). The decoder
25+// reads ONE `cdef_idx` literal per 64x64 superblock, at that superblock's
26+// first non-skip block, and only when the frame header's `cdef_bits > 0`
27+// (`crate::decode::maybe_read_cdef_idx`). The writers below mirror that from
28+// a plan the filter search hands over, kept in a thread-local rather than
29+// threaded through every `write_*` signature -- the same shape the decoder's
30+// own `FrameCtx::cdef_transmitted` uses, and the encoder codes one tile at a
31+// time on one thread. The plan is CONSUMED by the tile writer that runs next
32+// ([`CdefIdxGuard`] clears it on every exit path, error included), so a frame
33+// that arms nothing writes no literals.
34+
35+// ---------------------------------------------------------------------------
36+// lane-av1lr: per-restoration-unit loop restoration syntax (spec 5.11.57,
37+// `read_lr`), armed by the encoder's restoration search the same way
38+// [`arm_cdef_idx`] arms the CDEF indices. LUMA ONLY and Wiener only: the
39+// frame header this encoder writes sets `FrameRestorationType[0] = WIENER`
40+// and leaves both chroma planes at `RESTORE_NONE`, so a unit codes one
41+// `restore_wiener` symbol and, when it takes the filter, its two directions
42+// against the running per-tile reference (`crate::restoration::
43+// write_wiener_filter`, the exact inverse of the reader's own
44+// `read_wiener_filter`).
45+
46+/// One frame's per-unit restoration plan (see [`arm_lr`]).
47+struct LrPlan {
48+ /// `LoopRestorationSize[0]`, in luma samples.
49+ unit_size: u32,
50+ /// `horz_units`/`vert_units` for the luma plane.
51+ horz_units: u32,
52+ vert_units: u32,
53+ /// One entry per unit, `rcol + rrow * horz_units`: the filter it takes,
54+ /// or `None` for `RESTORE_NONE`.
55+ units: Vec<Option<crate::restoration::WienerInfo>>,
56+ /// `ref_wiener_info`: the running reference the taps are coded against,
57+ /// reset to the midpoint filter at the start of each tile (this writer
58+ /// codes one tile per frame).
59+ reference: crate::restoration::WienerInfo,
60+}
61+
62+thread_local! {
63+ static LR_PLAN: std::cell::RefCell<Option<LrPlan>> = const { std::cell::RefCell::new(None) };
64+}
65+
66+/// Arms the next tile write with one Wiener decision per luma restoration
67+/// unit. An empty `units` disarms (the frame codes no restoration at all).
68+pub(crate) fn arm_lr(
69+ unit_size: u32,
70+ horz_units: u32,
71+ vert_units: u32,
72+ units: Vec<Option<crate::restoration::WienerInfo>>,
73+) {
74+ LR_PLAN.with(|c| {
75+ *c.borrow_mut() = (!units.is_empty()).then(|| LrPlan {
76+ unit_size,
77+ horz_units,
78+ vert_units,
79+ units,
80+ reference: crate::restoration::WienerInfo::default(),
81+ });
82+ });
83+}
84+
85+/// `read_lr`'s write side, called once at the top of every superblock,
86+/// before its partition symbol: writes the units this superblock's own
87+/// mi span covers (`av1_loop_restoration_corners_in_sb`; no superres, so the
88+/// column scaling is the plain mi one).
89+fn write_lr(enc: &mut SymbolEncoder, cdfs: &mut Cdfs, mi_row: u32, mi_col: u32) {
90+ LR_PLAN.with(|c| {
91+ let mut plan = c.borrow_mut();
92+ let Some(plan) = plan.as_mut() else { return };
93+ let unit = plan.unit_size;
94+ let rcol0 = (mi_col * 4).div_ceil(unit);
95+ let rcol1 = ((mi_col + SB_MI_W) * 4).div_ceil(unit).min(plan.horz_units);
96+ let rrow0 = (mi_row * 4).div_ceil(unit);
97+ let rrow1 = ((mi_row + SB_MI_W) * 4).div_ceil(unit).min(plan.vert_units);
98+ for rrow in rrow0..rrow1 {
99+ for rcol in rcol0..rcol1 {
100+ let info = plan.units[(rcol + rrow * plan.horz_units) as usize];
101+ enc.symbol(usize::from(info.is_some()), &mut cdfs.restore_wiener);
102+ if let Some(info) = info {
103+ crate::restoration::write_wiener_filter(
104+ enc,
105+ false,
106+ &mut plan.reference,
107+ &info,
108+ );
109+ }
110+ }
111+ }
112+ });
113+}
114+
115+/// A 64x64 superblock's width in 4x4 mode-info units (`SB_MI` in
116+/// `crate::decode`), the span [`write_lr`] resolves its units over.
117+const SB_MI_W: u32 = 16;
118+
119+/// One frame's per-superblock `cdef_idx` plan (see [`arm_cdef_idx`]).
120+struct CdefIdxPlan {
121+ /// The header's `cdef_bits`; never 0 while armed.
122+ bits: u8,
123+ /// Superblocks per row, the stride of `grid`.
124+ sb_cols: usize,
125+ /// One index per 64x64 superblock, in raster order.
126+ grid: Vec<u8>,
127+ /// The superblock whose literal was already written -- the decoder's
128+ /// `cdef_transmitted`, which resets at every superblock and which coding
129+ /// order (each superblock's blocks are contiguous) makes a single slot.
130+ last: Option<usize>,
131+}
132+
133+thread_local! {
134+ static CDEF_IDX: std::cell::RefCell<Option<CdefIdxPlan>> =
135+ const { std::cell::RefCell::new(None) };
136+}
137+
138+/// Arms the next tile write with one `cdef_idx` per 64x64 superblock.
139+/// `bits == 0` disarms (the header codes a single strength pair, so the tile
140+/// carries no literal at all).
141+pub(crate) fn arm_cdef_idx(bits: u8, sb_cols: usize, grid: Vec<u8>) {
142+ CDEF_IDX.with(|c| {
143+ *c.borrow_mut() = (bits > 0).then(|| CdefIdxPlan { bits, sb_cols, grid, last: None });
144+ });
145+}
146+
147+/// Clears the armed plan when the tile writer that consumed it returns.
148+struct CdefIdxGuard;
149+
150+impl Drop for CdefIdxGuard {
151+ fn drop(&mut self) {
152+ CDEF_IDX.with(|c| *c.borrow_mut() = None);
153+ LR_PLAN.with(|c| *c.borrow_mut() = None);
154+ }
155+}
156+
157+/// `read_cdef`'s write side, called right after every block's `skip` symbol:
158+/// writes this superblock's `cdef_idx` literal the first time a non-skip
159+/// block of it is coded. `mi` is the block's own position in 4x4 mode-info
160+/// units.
161+fn write_cdef_idx(enc: &mut SymbolEncoder, mi: (usize, usize), skip: bool) {
162+ if skip {
163+ return;
164+ }
165+ CDEF_IDX.with(|c| {
166+ let mut plan = c.borrow_mut();
167+ let Some(plan) = plan.as_mut() else { return };
168+ let sb = (mi.0 / 16) * plan.sb_cols + (mi.1 / 16);
169+ if plan.last == Some(sb) {
170+ return;
171+ }
172+ plan.last = Some(sb);
173+ enc.literal(
174+ u32::from(plan.grid.get(sb).copied().unwrap_or(0)),
175+ u32::from(plan.bits),
176+ );
177+ });
178+}
179+
23180 /// round-4 av1-truesize debugging aid: prints `msg()` to stderr when the
24181 /// `EC_RNG` environment variable is set, mirroring the `EC_PART`/`EC_TOK`
25182 /// trace `/tmp/libaom-src`'s debug `aomdec` build already emits under the
@@ -1085,6 +1242,8 @@ pub(crate) fn sb_coeff_key_frame_tile_cdfs(
10851242 tx_select: bool,
10861243 cdfs: &mut Cdfs,
10871244 ) -> Result<Vec<u8>> {
1245+ // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path.
1246+ let _cdef_idx = CdefIdxGuard;
10881247 check_blocks(mi_cols, mi_rows)?;
10891248 let (cols, rows) = block_grid(mi_cols, mi_rows);
10901249 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
@@ -1148,6 +1307,7 @@ pub(crate) fn sb_coeff_key_frame_tile_cdfs(
11481307 for sb_r in 0..sb_rows {
11491308 neighbours.start_row();
11501309 for sb_c in 0..sb_cols {
1310+ write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W);
11511311 let at = (sb_r as usize * 4, sb_c as usize * 4);
11521312 let ctx = neighbours.partition_ctx(at, SB);
11531313 ec_rng_trace(|| {
@@ -1535,9 +1695,13 @@ fn write_intra_mode(
15351695 above_mode: usize,
15361696 left_mode: usize,
15371697 cfl: bool,
1698+ // This block's own position in 4x4 mode-info units, for the `cdef_idx`
1699+ // literal that follows the `skip` symbol (see [`write_cdef_idx`]).
1700+ mi: (usize, usize),
15381701 ) -> usize {
15391702 let mode = usize::from(block.mode);
15401703 enc.symbol(0, &mut cdfs.skip[0]);
1704+ write_cdef_idx(enc, mi, false);
15411705 enc.symbol(
15421706 mode,
15431707 &mut cdfs.kf_y_mode[INTRA_MODE_CTX[above_mode]][INTRA_MODE_CTX[left_mode]],
@@ -1585,6 +1749,7 @@ fn write_block(
15851749 all_scans: &[Vec<u16>; 4],
15861750 ) -> Result<()> {
15871751 let (r, c) = at;
1752+ let at_mi = (r * (SUB / MI), c * (SUB / MI));
15881753 let mode = write_intra_mode(
15891754 enc,
15901755 cdfs,
@@ -1592,8 +1757,8 @@ fn write_block(
15921757 neighbours.above_mode[c],
15931758 neighbours.left_mode[r],
15941759 cfl,
1760+ at_mi,
15951761 );
1596- let at_mi = (r * (SUB / MI), c * (SUB / MI));
15971762 let split = if tx_select {
15981763 let tx = write_luma_select(
15991764 enc,
@@ -1667,7 +1832,7 @@ fn write_leaf8(
16671832 // true first divergence (a differently-sized alphabet under the same
16681833 // DC_PRED decision desyncs the coder even though the decoded mode is
16691834 // unchanged).
1670- let mode = write_intra_mode(enc, cdfs, block, above_mode, left_mode, true);
1835+ let mode = write_intra_mode(enc, cdfs, block, above_mode, left_mode, true, leaf_mi);
16711836 let planes = [TxbSet::Luma8, TxbSet::Chroma4, TxbSet::Chroma4];
16721837 let split = if tx_select {
16731838 let tx = write_luma_select(
@@ -2979,6 +3144,8 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
29793144 tx_select: bool,
29803145 cdfs: &mut Cdfs,
29813146 ) -> Result<Vec<u8>> {
3147+ // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path.
3148+ let _cdef_idx = CdefIdxGuard;
29823149 check_blocks(mi_cols, mi_rows)?;
29833150 // `block_grid`'s ceiling, not a plain division: a true frame size that is
29843151 // not a whole number of 32x32 blocks (or of 64x64 superblocks) still has
@@ -3046,6 +3213,7 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
30463213 for sb_r in 0..sb_rows {
30473214 neighbours.start_row();
30483215 for sb_c in 0..sb_cols {
3216+ write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W);
30493217 let sb_at = (sb_r as usize * 4, sb_c as usize * 4);
30503218 let sb_ctx = neighbours.partition_ctx(sb_at, SB);
30513219 // spec `decode_partition`'s hasRows/hasCols (5.11.4): a superblock
@@ -3293,6 +3461,7 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
32933461 let skip_ctx = usize::from(neighbours.above_skip[mi_c])
32943462 + usize::from(neighbours.left_skip[mi_r]);
32953463 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
3464+ write_cdef_idx(&mut enc, (mi_r, mi_c), block.skip);
32963465
32973466 let is_inter = block.inter.is_some();
32983467 let (above_inter, left_inter) =
@@ -3497,6 +3666,7 @@ fn write_inter_frame_leaf(
34973666 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
34983667 let skip_ctx = usize::from(neighbours.above_skip[mi_c]) + usize::from(neighbours.left_skip[mi_r]);
34993668 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
3669+ write_cdef_idx(enc, (mi_r, mi_c), block.skip);
35003670
35013671 let (has_above, has_left) = (r > 0, c > 0);
35023672 let (above_inter, left_inter) = (neighbours.above_inter[mi_c], neighbours.left_inter[mi_r]);
@@ -3690,6 +3860,7 @@ fn write_inter_frame_leaf8(
36903860 let left_inter = neighbours.left_inter[leaf_mi.0];
36913861 let skip_ctx = usize::from(above_skip) + usize::from(left_skip);
36923862 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
3863+ write_cdef_idx(enc, leaf_mi, block.skip);
36933864
36943865 let (has_above, has_left) = (leaf_mi.0 > 0, leaf_mi.1 > 0);
36953866 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);