forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-av1lr' (12055f9c): per-64x64 CDEF strengths and luma Wiener loop restoration in the encoder

Browse files at this commit

56a796a9983d1bd6a7db49756c99b4b472be5451Ahmet Kaan GümüşParent: 0f156688e2799a
Both searched with the decoder's own kernels on decoder-exposed post-deblock /
post-CDEF planes (FrameCtx::capture_stages, one bool read when off). BD vs
libaom +122.7/+147.3/+79.4, vs rav1e +73.4/+98.5/+17.2 (all six down from
d5fc99e0); wall +0.6 s 2160p / +0.8 s screen for the tile re-code.
crates/ec-av1/src/decode.rsmodified+142 -13
@@ -40,7 +40,34 @@ use ec_core::{Error, Result};
40 ///40 ///
41 /// `Cell`/`RefCell` make this `!Sync` on purpose: a `FrameCtx` belongs to41 /// `Cell`/`RefCell` make this `!Sync` on purpose: a `FrameCtx` belongs to
42 /// exactly one thread's decode, and is never shared between workers.42 /// exactly one thread's decode, and is never shared between workers.
43+/// One frame's in-loop filter intermediates, as [`FrameCtx::capture_stages`]
44+/// asks for them: each plane's post-deblock (pre-CDEF) and post-CDEF
45+/// (pre-restoration) samples, at the decoder's own plane stride.
46+pub(crate) struct FilterStages {
47+ /// Post-deblock, pre-CDEF planes (Y, U, V).
48+ pub(crate) deblocked: [Vec<u16>; 3],
49+ /// Post-CDEF, pre-restoration planes (Y, U, V).
50+ pub(crate) cdefed: [Vec<u16>; 3],
51+ /// Each plane's stride (and so its width in the buffers above).
52+ pub(crate) stride: [usize; 3],
53+}
54+
55+/// Takes whatever the last capturing decode left (see
56+/// [`FrameCtx::capture_stages`]).
57+#[allow(dead_code)] // read from the encoder's loop restoration search
58+pub(crate) fn take_filter_stages(fctx: &FrameCtx) -> Option<FilterStages> {
59+ fctx.stages.borrow_mut().take()
60+}
61+
43 pub(crate) struct FrameCtx {62 pub(crate) struct FrameCtx {
63+ /// lane-av1lr: when set, the frame filter chain leaves its post-deblock
64+ /// and post-CDEF planes in [`FrameCtx::stages`] for the ENCODER's loop
65+ /// restoration search (spec 7.17 reads both: the stripe interior from
66+ /// the post-CDEF plane, its 3-row border from the post-deblock one).
67+ /// Off for every decode but that search, and off it costs one bool read
68+ /// per frame and not a single copy.
69+ pub(crate) capture_stages: std::cell::Cell<bool>,
70+ pub(crate) stages: std::cell::RefCell<Option<FilterStages>>,
44 pub(crate) sb128_flag: std::cell::Cell<bool>,71 pub(crate) sb128_flag: std::cell::Cell<bool>,
45 pub(crate) cdef_bits: std::cell::Cell<u8>,72 pub(crate) cdef_bits: std::cell::Cell<u8>,
46 pub(crate) bit_depth: std::cell::Cell<u8>,73 pub(crate) bit_depth: std::cell::Cell<u8>,
@@ -130,6 +157,8 @@ impl FrameCtx {
130 superres: std::cell::Cell::new((0, 8)),157 superres: std::cell::Cell::new((0, 8)),
131 cdef_transmitted: std::cell::Cell::new(false),158 cdef_transmitted: std::cell::Cell::new(false),
132 cdef_sb_cols: std::cell::Cell::new(0),159 cdef_sb_cols: std::cell::Cell::new(0),
160+ capture_stages: std::cell::Cell::new(false),
161+ stages: std::cell::RefCell::new(None),
133 cdef_idx_grid: std::cell::RefCell::new(Vec::new()),162 cdef_idx_grid: std::cell::RefCell::new(Vec::new()),
134 delta_q_present: std::cell::Cell::new(false),163 delta_q_present: std::cell::Cell::new(false),
135 delta_q_res: std::cell::Cell::new(1),164 delta_q_res: std::cell::Cell::new(1),
@@ -20545,6 +20574,37 @@ fn apply_cdef(
20545 scratch_return(src_v);20574 scratch_return(src_v);
20546 }20575 }
20547 20576
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+
20548 /// Spec 7.17: loop restoration, run after [`apply_cdef`] (a sibling lane's20608 /// Spec 7.17: loop restoration, run after [`apply_cdef`] (a sibling lane's
20549 /// ordering note: libaom also runs `superres_post_decode` between the two,20609 /// ordering note: libaom also runs `superres_post_decode` between the two,
20550 /// but this decoder never implements super-resolution, so there is nothing20610 /// but this decoder never implements super-resolution, so there is nothing
@@ -20660,6 +20720,34 @@ pub(crate) fn decode_key_frame_tile(
20660 reduced_tx_set: bool,20720 reduced_tx_set: bool,
20661 allow_screen_content_tools: bool,20721 allow_screen_content_tools: bool,
20662 allow_intrabc: bool, fctx: &crate::decode::FrameCtx,20722 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,
20663 ) -> Result<Picture> {20751 ) -> Result<Picture> {
20664 let delta = DeltaParams::default();20752 let delta = DeltaParams::default();
20665 let single_tile = TileInfo {20753 let single_tile = TileInfo {
@@ -20680,7 +20768,7 @@ pub(crate) fn decode_key_frame_tile(
20680 false,20768 false,
20681 cdef,20769 cdef,
20682 loop_filter,20770 loop_filter,
20683- &LoopRestorationParams::default(),20771+ lr,
20684 None,20772 None,
20685 tx_select,20773 tx_select,
20686 reduced_tx_set,20774 reduced_tx_set,
@@ -23019,6 +23107,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
23019 );23107 );
23020 dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v);23108 dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v);
23021 dump_stage16("EC_AV1_POSTCDEF_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize);23109 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);
23022 // spec 7.16 (libaom `superres_post_decode`, decodeframe.c: called23111 // spec 7.16 (libaom `superres_post_decode`, decodeframe.c: called
23023 // between `av1_cdef_frame` and `av1_loop_restoration_filter_frame`):23112 // between `av1_cdef_frame` and `av1_loop_restoration_filter_frame`):
23024 // the horizontal upscale runs HERE -- after CDEF, before loop23113 // the horizontal upscale runs HERE -- after CDEF, before loop
@@ -32780,6 +32869,37 @@ pub(crate) fn decode_inter_frame_tile(
32780 // class as `tx_select` above, third instance.32869 // class as `tx_select` above, third instance.
32781 initial_cdfs: Option<Cdfs>,32870 initial_cdfs: Option<Cdfs>,
32782 fctx: &crate::decode::FrameCtx,32871 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,
32783 ) -> Result<Picture> {32903 ) -> Result<Picture> {
32784 let single_tile = TileInfo {32904 let single_tile = TileInfo {
32785 mi_col_starts: vec![0, mi_cols],32905 mi_col_starts: vec![0, mi_cols],
@@ -32798,7 +32918,7 @@ pub(crate) fn decode_inter_frame_tile(
32798 refpix,32918 refpix,
32799 cdef,32919 cdef,
32800 loop_filter,32920 loop_filter,
32801- &LoopRestorationParams::default(),32921+ lr,
32802 initial_cdfs,32922 initial_cdfs,
32803 allow_high_precision_mv,32923 allow_high_precision_mv,
32804 force_integer_mv,32924 force_integer_mv,
@@ -35660,6 +35780,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
35660 }35780 }
35661 dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v);35781 dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v);
35662 dump_stage16("EC_AV1_POSTCDEF_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize);35782 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);
35663 // spec 7.16 (libaom `superres_post_decode`, decodeframe.c: called35784 // spec 7.16 (libaom `superres_post_decode`, decodeframe.c: called
35664 // between `av1_cdef_frame` and `av1_loop_restoration_filter_frame`):35785 // between `av1_cdef_frame` and `av1_loop_restoration_filter_frame`):
35665 // the horizontal upscale runs HERE -- after CDEF, before loop35786 // the horizontal upscale runs HERE -- after CDEF, before loop
@@ -36803,9 +36924,10 @@ mod tests {
36803 tx_select,36924 tx_select,
36804 loop_filter,36925 loop_filter,
36805 cdef,36926 cdef,
36927+ loop_restoration,
36806 ..36928 ..
36807 }: Encoded = crate::encode::encode_key_frame_with_modes_with_ctx(&picture, 40, 0.0, modes, fctx).unwrap();36929 }: 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(
36809 &tile,36931 &tile,
36810 mi_cols,36932 mi_cols,
36811 mi_rows,36933 mi_rows,
@@ -36818,7 +36940,8 @@ mod tests {
36818 tx_select,36940 tx_select,
36819 true,36941 true,
36820 false,36942 false,
36821- false, fctx,36943+ false,
36944+ &loop_restoration, fctx,
36822 )36945 )
36823 .unwrap();36946 .unwrap();
36824 assert_eq!(decoded.width, w, "{w}x{h}: decoded width");36947 assert_eq!(decoded.width, w, "{w}x{h}: decoded width");
@@ -37173,7 +37296,7 @@ mod tests {
37173 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();37296 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
37174 let (coded_w, coded_h) = ffprobe_size(&encoded.stream);37297 let (coded_w, coded_h) = ffprobe_size(&encoded.stream);
37175 let ffmpeg_decoded = ffmpeg_decode(&encoded.stream, coded_w as usize, coded_h as usize);37298 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(
37177 &encoded.tile,37300 &encoded.tile,
37178 encoded.mi_cols,37301 encoded.mi_cols,
37179 encoded.mi_rows,37302 encoded.mi_rows,
@@ -37186,7 +37309,8 @@ mod tests {
37186 encoded.tx_select,37309 encoded.tx_select,
37187 true,37310 true,
37188 false,37311 false,
37189- false, fctx,37312+ false,
37313+ &encoded.loop_restoration, fctx,
37190 )37314 )
37191 .unwrap();37315 .unwrap();
37192 assert_eq!(ours.y, ffmpeg_decoded.y, "{width}x{height}: luma vs ffmpeg");37316 assert_eq!(ours.y, ffmpeg_decoded.y, "{width}x{height}: luma vs ffmpeg");
@@ -37216,7 +37340,7 @@ mod tests {
37216 gate's premise moved, not the decoder"37340 gate's premise moved, not the decoder"
37217 );37341 );
37218 let decode = |tx_select: bool| {37342 let decode = |tx_select: bool| {
37219- decode_key_frame_tile(37343+ decode_key_frame_tile_lr(
37220 &encoded.tile,37344 &encoded.tile,
37221 encoded.mi_cols,37345 encoded.mi_cols,
37222 encoded.mi_rows,37346 encoded.mi_rows,
@@ -37230,6 +37354,7 @@ mod tests {
37230 true,37354 true,
37231 false,37355 false,
37232 false,37356 false,
37357+ &encoded.loop_restoration,
37233 fctx,37358 fctx,
37234 )37359 )
37235 };37360 };
@@ -37300,7 +37425,7 @@ mod tests {
37300 assert_eq!(encoded.frames.len(), 4);37425 assert_eq!(encoded.frames.len(), 4);
37301 37426
37302 let key = &encoded.frames[0];37427 let key = &encoded.frames[0];
37303- let mut reference = decode_key_frame_tile(37428+ let mut reference = decode_key_frame_tile_lr(
37304 &key.tile,37429 &key.tile,
37305 key.mi_cols,37430 key.mi_cols,
37306 key.mi_rows,37431 key.mi_rows,
@@ -37313,7 +37438,8 @@ mod tests {
37313 key.tx_select,37438 key.tx_select,
37314 true,37439 true,
37315 false,37440 false,
37316- false, fctx,37441+ false,
37442+ &key.loop_restoration, fctx,
37317 )37443 )
37318 .unwrap();37444 .unwrap();
37319 assert_eq!(37445 assert_eq!(
@@ -37330,7 +37456,7 @@ mod tests {
37330 );37456 );
37331 37457
37332 for (i, frame) in encoded.frames.iter().enumerate().skip(1) {37458 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(
37334 &frame.tile,37460 &frame.tile,
37335 frame.mi_cols,37461 frame.mi_cols,
37336 frame.mi_rows,37462 frame.mi_rows,
@@ -37350,6 +37476,7 @@ mod tests {
37350 false,37476 false,
37351 false,37477 false,
37352 frame.tx_select,37478 frame.tx_select,
37479+ &frame.loop_restoration,
37353 Some(frame.start_cdfs.0.clone()),37480 Some(frame.start_cdfs.0.clone()),
37354 fctx,37481 fctx,
37355 )37482 )
@@ -37627,7 +37754,7 @@ mod tests {
37627 ffmpeg_decode_sequence(&encoded.stream, coded_w as usize, coded_h as usize, 3);37754 ffmpeg_decode_sequence(&encoded.stream, coded_w as usize, coded_h as usize, 3);
37628 37755
37629 let key = &encoded.frames[0];37756 let key = &encoded.frames[0];
37630- let mut reference = decode_key_frame_tile(37757+ let mut reference = decode_key_frame_tile_lr(
37631 &key.tile,37758 &key.tile,
37632 key.mi_cols,37759 key.mi_cols,
37633 key.mi_rows,37760 key.mi_rows,
@@ -37640,13 +37767,14 @@ mod tests {
37640 key.tx_select,37767 key.tx_select,
37641 true,37768 true,
37642 false,37769 false,
37643- false, fctx,37770+ false,
37771+ &key.loop_restoration, fctx,
37644 )37772 )
37645 .unwrap();37773 .unwrap();
37646 assert_eq!(reference.y, ffmpeg_frames[0].y, "frame 0 luma vs ffmpeg");37774 assert_eq!(reference.y, ffmpeg_frames[0].y, "frame 0 luma vs ffmpeg");
37647 37775
37648 for (i, frame) in encoded.frames.iter().enumerate().skip(1) {37776 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(
37650 &frame.tile,37778 &frame.tile,
37651 frame.mi_cols,37779 frame.mi_cols,
37652 frame.mi_rows,37780 frame.mi_rows,
@@ -37666,6 +37794,7 @@ mod tests {
37666 false,37794 false,
37667 false,37795 false,
37668 frame.tx_select,37796 frame.tx_select,
37797+ &frame.loop_restoration,
37669 Some(frame.start_cdfs.0.clone()),37798 Some(frame.start_cdfs.0.clone()),
37670 fctx,37799 fctx,
37671 )37800 )
crates/ec-av1/src/encode.rsmodified+226 -23
@@ -19,8 +19,8 @@
19 use crate::decode::WithRef;19 use crate::decode::WithRef;
20 use ec_av1_syntax::sequence::{ColorConfig, OperatingPoint, SequenceHeader};20 use ec_av1_syntax::sequence::{ColorConfig, OperatingPoint, SequenceHeader};
21 use ec_av1_syntax::{21 use ec_av1_syntax::{
22- CdefParams, ChromaSamplePosition, FrameHeader, FrameType, LoopFilterParams, PRIMARY_REF_NONE,22+ CdefParams, ChromaSamplePosition, FrameHeader, FrameType, LoopFilterParams,
23- QuantizationParams, TileInfo, TxMode,23+ LoopRestorationParams, PRIMARY_REF_NONE, QuantizationParams, TileInfo, TxMode,
24 };24 };
25 use ec_core::{Error, Result};25 use ec_core::{Error, Result};
26 26
@@ -190,6 +190,20 @@ fn split_inter_blocks() -> bool {
190 }190 }
191 }191 }
192 192
193+/// Whether the encoder searches loop restoration at all (spec 7.17): one
194+/// Wiener filter per 64x64 luma restoration unit, picked from
195+/// [`crate::filter_search::WIENER_CANDIDATES`]. Swept by `EC_AV1_LR` in a
196+/// test build, like [`lambda_scale`].
197+const RESTORATION: bool = true;
198+
199+/// [`RESTORATION`], or what `EC_AV1_LR` names in a test build.
200+fn restoration_enabled() -> bool {
201+ match std::env::var("EC_AV1_LR").ok() {
202+ Some(v) if cfg!(test) => v != "0",
203+ _ => RESTORATION,
204+ }
205+}
206+
193 /// libaom's `partition_search_breakout` shape: how many non-zero luma207 /// libaom's `partition_search_breakout` shape: how many non-zero luma
194 /// coefficients per 256 luma samples a block may code and still be judged208 /// coefficients per 256 luma samples a block may code and still be judged
195 /// well enough predicted that the split below it is not worth trying. `0`209 /// well enough predicted that the split below it is not worth trying. `0`
@@ -480,6 +494,7 @@ pub(crate) fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> En
480 start_cdfs: encoded.start_cdfs.clone(),494 start_cdfs: encoded.start_cdfs.clone(),
481 next_cdfs: encoded.next_cdfs.clone(),495 next_cdfs: encoded.next_cdfs.clone(),
482 loop_filter: encoded.loop_filter,496 loop_filter: encoded.loop_filter,
497+ loop_restoration: encoded.loop_restoration,
483 cdef: encoded.cdef,498 cdef: encoded.cdef,
484 }499 }
485 }500 }
@@ -549,6 +564,11 @@ pub struct Encoded {
549 /// This frame header's chosen CDEF parameters, threaded for the same564 /// This frame header's chosen CDEF parameters, threaded for the same
550 /// reason as `loop_filter`.565 /// reason as `loop_filter`.
551 pub(crate) cdef: CdefParams,566 pub(crate) cdef: CdefParams,
567+ /// This frame header's chosen loop restoration parameters, threaded for
568+ /// the same reason as `loop_filter` -- and doubly so: the per-unit
569+ /// filters themselves are coded in `tile`, so a decode of it under a
570+ /// stale `RESTORE_NONE` header desyncs at the first superblock.
571+ pub(crate) loop_restoration: LoopRestorationParams,
552 }572 }
553 573
554 /// The sequence and frame headers a picture of this size is coded under: one574 /// The sequence and frame headers a picture of this size is coded under: one
@@ -633,7 +653,7 @@ pub(crate) fn key_frame_headers_colour(
633 // `cdef_idx` literal is coded in the tile and a frame that wants no653 // `cdef_idx` literal is coded in the tile and a frame that wants no
634 // CDEF simply carries zero strengths.654 // CDEF simply carries zero strengths.
635 enable_cdef: true,655 enable_cdef: true,
636- enable_restoration: false,656+ enable_restoration: true,
637 seq_force_screen_content_tools: 0,657 seq_force_screen_content_tools: 0,
638 seq_force_integer_mv: 0,658 seq_force_integer_mv: 0,
639 color_config,659 color_config,
@@ -3096,11 +3116,12 @@ pub(crate) fn encode_key_frame_inner(
3096 // set, so what it stores into the slots it refreshes is exactly those3116 // set, so what it stores into the slots it refreshes is exactly those
3097 // defaults again (spec 7.20's `started_from` arm) -- the first inter3117 // defaults again (spec 7.20's `started_from` arm) -- the first inter
3098 // frame after it therefore starts from the defaults too.3118 // frame after it therefore starts from the defaults too.
3119+ let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
3099 let mut cdfs = crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx));3120 let mut cdfs = crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx));
3100 let start_cdfs = CdfSnapshot(cdfs.clone());3121 let start_cdfs = CdfSnapshot(cdfs.clone());
3101- let tile = crate::tile::sb_coeff_key_frame_tile_cdfs(3122+ let mut tile = crate::tile::sb_coeff_key_frame_tile_cdfs(
3102- header.mi_cols,3123+ mi_cols,
3103- header.mi_rows,3124+ mi_rows,
3104 base_q_idx,3125 base_q_idx,
3105 &superblocks,3126 &superblocks,
3106 tx_select,3127 tx_select,
@@ -3111,16 +3132,41 @@ pub(crate) fn encode_key_frame_inner(
3111 // `crate::filter_search`), and keep the filtered picture that wins as3132 // `crate::filter_search`), and keep the filtered picture that wins as
3112 // the reconstruction -- what a decoder outputs, and what the next3133 // the reconstruction -- what a decoder outputs, and what the next
3113 // frame predicts from.3134 // frame predicts from.
3135+ // The luma restoration-unit grid this frame's `lr_params` implies
3136+ // (`av1_lr_count_units` rounds to nearest, so a short last unit is
3137+ // swallowed by the one before it), for the tile writer's own per-unit
3138+ // walk.
3139+ let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32;
3140+ let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32;
3114 pick_and_apply_filters(3141 pick_and_apply_filters(
3115 &mut header,3142 &mut header,
3116 &mut luma,3143 &mut luma,
3117 &mut chroma,3144 &mut chroma,
3118 [&picture_y8, &picture_u8, &picture_v8],3145 [&picture_y8, &picture_u8, &picture_v8],
3119 true,3146 true,
3147+ &mut tile,
3148+ search.lambda,
3120 fctx,3149 fctx,
3121- |lf, cdef, h| {3150+ // Every re-code starts from this frame's OWN starting tables, never
3122- crate::decode::decode_key_frame_tile(3151+ // from where the first write left them: the second tile is the same
3123- &tile,3152+ // symbol sequence plus new ones, so it must adapt from the same
3153+ // point the decoder will.
3154+ |bits, sb_cols, grid, units| {
3155+ crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());
3156+ crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());
3157+ let mut cdfs = start_cdfs.0.clone();
3158+ crate::tile::sb_coeff_key_frame_tile_cdfs(
3159+ mi_cols,
3160+ mi_rows,
3161+ base_q_idx,
3162+ &superblocks,
3163+ tx_select,
3164+ &mut cdfs,
3165+ )
3166+ },
3167+ |lf, cdef, h, tile, lr| {
3168+ crate::decode::decode_key_frame_tile_lr(
3169+ tile,
3124 h.mi_cols,3170 h.mi_cols,
3125 h.mi_rows,3171 h.mi_rows,
3126 base_q_idx,3172 base_q_idx,
@@ -3133,6 +3179,7 @@ pub(crate) fn encode_key_frame_inner(
3133 h.reduced_tx_set,3179 h.reduced_tx_set,
3134 h.allow_screen_content_tools,3180 h.allow_screen_content_tools,
3135 h.allow_intrabc,3181 h.allow_intrabc,
3182+ lr,
3136 fctx,3183 fctx,
3137 )3184 )
3138 },3185 },
@@ -3162,6 +3209,7 @@ pub(crate) fn encode_key_frame_inner(
3162 start_cdfs,3209 start_cdfs,
3163 loop_filter: header.loop_filter,3210 loop_filter: header.loop_filter,
3164 cdef: header.cdef,3211 cdef: header.cdef,
3212+ loop_restoration: header.loop_restoration,
3165 })3213 })
3166 }3214 }
3167 3215
@@ -3185,8 +3233,21 @@ fn pick_and_apply_filters(
3185 chroma: &mut [Plane<'_>; 2],3233 chroma: &mut [Plane<'_>; 2],
3186 source: [&[u8]; 3],3234 source: [&[u8]; 3],
3187 search: bool,3235 search: bool,
3236+ // The coded tile, replaced in place when the search chooses a per-64x64
3237+ // `cdef_idx` list (`cdef_bits > 0`): those literals live in the tile
3238+ // payload, so the tile is written a second time under `recode` and the
3239+ // winner re-decoded from it.
3240+ tile: &mut Vec<u8>,
3241+ lambda: f64,
3188 fctx: &crate::decode::FrameCtx,3242 fctx: &crate::decode::FrameCtx,
3189- decode: impl Fn(&LoopFilterParams, &CdefParams, &FrameHeader) -> Result<Picture>,3243+ recode: impl Fn(u8, usize, &[u8], &[Option<crate::restoration::WienerInfo>]) -> Result<Vec<u8>>,
3244+ decode: impl Fn(
3245+ &LoopFilterParams,
3246+ &CdefParams,
3247+ &FrameHeader,
3248+ &[u8],
3249+ &LoopRestorationParams,
3250+ ) -> Result<Picture>,
3190 ) -> Result<()> {3251 ) -> Result<()> {
3191 if !search {3252 if !search {
3192 return Ok(());3253 return Ok(());
@@ -3196,9 +3257,14 @@ fn pick_and_apply_filters(
3196 // libaom `av1_pick_filter_level`'s sibling `av1_cdef_search`:3257 // libaom `av1_pick_filter_level`'s sibling `av1_cdef_search`:
3197 // `cdef_damping = 3 + (base_qindex >> 6)`, never searched.3258 // `cdef_damping = 3 + (base_qindex >> 6)`, never searched.
3198 let damping = 3 + (header.quantization.base_q_idx >> 6);3259 let damping = 3 + (header.quantization.base_q_idx >> 6);
3260+ let (cols32, rows32) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
3261+ let (sb_cols, sb_rows) = (cols32.div_ceil(2) as usize, rows32.div_ceil(2) as usize);
3262+ let none_lr = LoopRestorationParams::default();
3199 // Every candidate scores the same coded tile: decode it once and re-run3263 // Every candidate scores the same coded tile: decode it once and re-run
3200 // the filters alone for the rest (`crate::decode::FilterReplay`, 24% of3264 // the filters alone for the rest (`crate::decode::FilterReplay`, 24% of
3201- // the encoder's profile before this).3265+ // the encoder's profile before this). The per-64x64 error the CDEF
3266+ // preset search reads comes off the REPLAYED picture, which is the same
3267+ // picture a decode produces -- that is what the replay is pinned on.
3202 crate::decode::clear_filter_replay();3268 crate::decode::clear_filter_replay();
3203 let search_result = crate::filter_search::pick_filters(3269 let search_result = crate::filter_search::pick_filters(
3204 |lf, cdef| {3270 |lf, cdef| {
@@ -3206,17 +3272,80 @@ fn pick_and_apply_filters(
3206 return Ok(picture);3272 return Ok(picture);
3207 }3273 }
3208 crate::decode::arm_filter_replay();3274 crate::decode::arm_filter_replay();
3209- decode(lf, cdef, &hdr)3275+ decode(lf, cdef, &hdr, tile, &none_lr)
3210 },3276 },
3211 source,3277 source,
3212 luma.width,3278 luma.width,
3213 (fw, fh),3279 (fw, fh),
3214 damping,3280 damping,
3281+ (sb_cols, sb_rows),
3282+ lambda,
3215 );3283 );
3216 crate::decode::clear_filter_replay();3284 crate::decode::clear_filter_replay();
3217- let (lf, cdef, filtered) = search_result?;3285+ let (lf, cdef, idx_grid, picture) = search_result?;
3218 header.loop_filter = lf;3286 header.loop_filter = lf;
3219 header.cdef = cdef;3287 header.cdef = cdef;
3288+ // spec 7.17: loop restoration. Its per-unit filters live in the TILE, not
3289+ // in the frame header, so a re-decode under candidate parameters cannot
3290+ // search them the way deblocking and CDEF are searched above. What the
3291+ // decoder hands back instead is its own filter chain's intermediates
3292+ // (`crate::decode::FrameCtx::capture_stages`), and the search runs on
3293+ // those, through the decoder's own Wiener kernel.
3294+ //
3295+ // The capture rides the decode this stage was already going to do: the
3296+ // re-decode of the `cdef_idx` tile when there is one, and otherwise one
3297+ // decode of the tile as it stands. That decode's header still says
3298+ // `RESTORE_NONE`, so the decoder takes no pre-CDEF snapshot and the
3299+ // post-CDEF picture stands in for it at LR's 3-row stripe borders --
3300+ // an approximation inside the SEARCH only; the reconstruction this
3301+ // function ends up splicing is always a real decode of the real tile.
3302+ let lr_on = restoration_enabled();
3303+ fctx.capture_stages.set(lr_on);
3304+ let mut filtered = if idx_grid.is_empty() {
3305+ if lr_on {
3306+ decode(&lf, &cdef, &hdr, tile, &none_lr)?
3307+ } else {
3308+ picture
3309+ }
3310+ } else {
3311+ let coded = recode(cdef.bits, sb_cols, &idx_grid, &[])?;
3312+ let picture = decode(&lf, &cdef, &hdr, &coded, &none_lr)?;
3313+ *tile = coded;
3314+ picture
3315+ };
3316+ fctx.capture_stages.set(false);
3317+ let mut lr = LoopRestorationParams::default();
3318+ if lr_on {
3319+ let mut want = LoopRestorationParams {
3320+ loop_restoration_size: [64, 64, 64],
3321+ uses_lr: true,
3322+ ..LoopRestorationParams::default()
3323+ };
3324+ want.frame_restoration_type[0] = ec_av1_syntax::RestorationType::Wiener;
3325+ let units = match crate::decode::take_filter_stages(fctx) {
3326+ Some(stages) => crate::filter_search::pick_restoration(
3327+ &stages,
3328+ source[0],
3329+ luma.width,
3330+ (fw, fh),
3331+ &want,
3332+ lambda,
3333+ fctx,
3334+ ),
3335+ None => Vec::new(),
3336+ };
3337+ // A frame no unit restores keeps `RESTORE_NONE` on every plane
3338+ // rather than paying ~1 bit per 64x64 for a tile full of
3339+ // `restore_wiener = 0` symbols (the BD gate saw exactly that on the
3340+ // clip whose units never take a filter).
3341+ if units.iter().any(Option::is_some) {
3342+ let coded = recode(cdef.bits, sb_cols, &idx_grid, &units)?;
3343+ filtered = decode(&lf, &cdef, &hdr, &coded, &want)?;
3344+ *tile = coded;
3345+ lr = want;
3346+ }
3347+ }
3348+ header.loop_restoration = lr;
3220 let dec_cw = filtered.width.div_ceil(2);3349 let dec_cw = filtered.width.div_ceil(2);
3221 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));3350 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));
3222 crate::filter_search::splice(&mut luma.reconstruction, luma.width, &filtered.y, filtered.width, fw, fh);3351 crate::filter_search::splice(&mut luma.reconstruction, luma.width, &filtered.y, filtered.width, fw, fh);
@@ -4388,13 +4517,14 @@ pub(crate) fn encode_inter_frame(
4388 // stores its end-of-tile tables with the counts reset (spec 7.20) and the4517 // stores its end-of-tile tables with the counts reset (spec 7.20) and the
4389 // next frame's writer starts from them -- exactly what4518 // next frame's writer starts from them -- exactly what
4390 // `crate::stream::stored_cdfs_for` hands the decoder.4519 // `crate::stream::stored_cdfs_for` hands the decoder.
4520+ let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
4391 let mut cdfs = start_cdfs4521 let mut cdfs = start_cdfs
4392 .cloned()4522 .cloned()
4393 .unwrap_or_else(|| crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx)));4523 .unwrap_or_else(|| crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx)));
4394 let start_cdfs = CdfSnapshot(cdfs.clone());4524 let start_cdfs = CdfSnapshot(cdfs.clone());
4395- let tile = crate::tile::sb_coeff_inter_frame_tile_cdfs(4525+ let mut tile = crate::tile::sb_coeff_inter_frame_tile_cdfs(
4396- header.mi_cols,4526+ mi_cols,
4397- header.mi_rows,4527+ mi_rows,
4398 base_q_idx,4528 base_q_idx,
4399 &blocks,4529 &blocks,
4400 tx_select,4530 tx_select,
@@ -4408,6 +4538,7 @@ pub(crate) fn encode_inter_frame(
4408 // reference whose height is not the header's own `frame_height` (spec4538 // reference whose height is not the header's own `frame_height` (spec
4409 // 7.9's compatible-size rule), and the chained-decode round trips prove4539 // 7.9's compatible-size rule), and the chained-decode round trips prove
4410 // the two predict identically.4540 // the two predict identically.
4541+ let end_cdfs = std::cell::RefCell::new(cdfs);
4411 let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);4542 let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);
4412 let trial_ref = if (reference.width, reference.height) == (fw, fh) {4543 let trial_ref = if (reference.width, reference.height) == (fw, fh) {
4413 reference.clone()4544 reference.clone()
@@ -4454,6 +4585,12 @@ pub(crate) fn encode_inter_frame(
4454 refs[4] = trial_golden.as_ref();4585 refs[4] = trial_golden.as_ref();
4455 refs[7] = trial_altref.as_ref();4586 refs[7] = trial_altref.as_ref();
4456 let refpix = crate::decode::RefPix::ready(refs);4587 let refpix = crate::decode::RefPix::ready(refs);
4588+ // The luma restoration-unit grid this frame's `lr_params` implies
4589+ // (`av1_lr_count_units` rounds to nearest, so a short last unit is
4590+ // swallowed by the one before it), for the tile writer's own per-unit
4591+ // walk.
4592+ let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32;
4593+ let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32;
4457 pick_and_apply_filters(4594 pick_and_apply_filters(
4458 &mut header,4595 &mut header,
4459 &mut luma,4596 &mut luma,
@@ -4464,10 +4601,33 @@ pub(crate) fn encode_inter_frame(
4464 // `TxMode::Select` too (it used to skip and leave every inter frame4601 // `TxMode::Select` too (it used to skip and leave every inter frame
4465 // unfiltered once Select became the default).4602 // unfiltered once Select became the default).
4466 true,4603 true,
4604+ &mut tile,
4605+ search.lambda,
4467 fctx,4606 fctx,
4468- |lf, cdef, h| {4607+ // As in `encode_key_frame_inner`, but this frame's end-of-tile tables
4469- crate::decode::decode_inter_frame_tile(4608+ // are what the NEXT frame writes from, so the winning re-code
4470- &tile,4609+ // publishes its own into `end_cdfs` -- the first write's are stale
4610+ // the moment a second tile is coded.
4611+ |bits, sb_cols, grid, units| {
4612+ crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());
4613+ crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());
4614+ let mut cdfs = start_cdfs.0.clone();
4615+ let coded = crate::tile::sb_coeff_inter_frame_tile_cdfs(
4616+ mi_cols,
4617+ mi_rows,
4618+ base_q_idx,
4619+ &blocks,
4620+ tx_select,
4621+ &mut cdfs,
4622+ );
4623+ if coded.is_ok() {
4624+ *end_cdfs.borrow_mut() = cdfs;
4625+ }
4626+ coded
4627+ },
4628+ |lf, cdef, h, tile, lr| {
4629+ crate::decode::decode_inter_frame_tile_lr(
4630+ tile,
4471 h.mi_cols,4631 h.mi_cols,
4472 h.mi_rows,4632 h.mi_rows,
4473 base_q_idx,4633 base_q_idx,
@@ -4482,6 +4642,7 @@ pub(crate) fn encode_inter_frame(
4482 seq.enable_dual_filter,4642 seq.enable_dual_filter,
4483 h.reference_select,4643 h.reference_select,
4484 tx_select,4644 tx_select,
4645+ lr,
4485 // The trial decode re-reads the tile the writer just wrote,4646 // The trial decode re-reads the tile the writer just wrote,
4486 // so it starts from the same tables the writer did (this4647 // so it starts from the same tables the writer did (this
4487 // frame's `start_cdfs`), not from the defaults.4648 // frame's `start_cdfs`), not from the defaults.
@@ -4490,6 +4651,7 @@ pub(crate) fn encode_inter_frame(
4490 )4651 )
4491 },4652 },
4492 )?;4653 )?;
4654+ let mut cdfs = end_cdfs.into_inner();
4493 cdfs.reset_counts();4655 cdfs.reset_counts();
4494 let next_cdfs = CdfSnapshot(cdfs);4656 let next_cdfs = CdfSnapshot(cdfs);
4495 let mut stream = temporal_delimiter();4657 let mut stream = temporal_delimiter();
@@ -4516,6 +4678,7 @@ pub(crate) fn encode_inter_frame(
4516 next_cdfs,4678 next_cdfs,
4517 loop_filter: header.loop_filter,4679 loop_filter: header.loop_filter,
4518 cdef: header.cdef,4680 cdef: header.cdef,
4681+ loop_restoration: header.loop_restoration,
4519 })4682 })
4520 }4683 }
4521 4684
@@ -7319,9 +7482,18 @@ mod tests {
7319 ///7482 ///
7320 /// The BD gate above measures quality, which a speed lane can move by a7483 /// The BD gate above measures quality, which a speed lane can move by a
7321 /// hair without failing anything; this pins the streams themselves.7484 /// hair without failing anything; this pins the streams themselves.
7322- /// Every number below was measured 2026-09-06 (lane-av1fwd) and is7485+ /// Re-measured on the lane-av1lr merge with main d5fc99e0: the per-64x64
7323- /// identical at `a6649c4e`, the merge before that lane's three exact7486+ /// `cdef_idx` literals and the per-unit loop restoration syntax are new
7324- /// speed steps.7487+ /// bits in the tile, so the streams move (q=150 7416 -> 7458 bytes,
7488+ /// q=60 27927 -> 27807 -- the low-rate frame pays for the syntax, the
7489+ /// high-rate one more than earns it back).
7490+ ///
7491+ /// Every number below was measured 2026-09-06: first on lane-av1fwd
7492+ /// (whose three speed steps left them identical to `a6649c4e`'s), then
7493+ /// re-measured on the lane-av1lr merge, which legitimately moves them --
7494+ /// per-64x64 `cdef_idx` literals and the per-unit loop restoration
7495+ /// syntax are new bits in the tile, and both streams came out SMALLER
7496+ /// (7823 -> 7796, 28189 -> 28182 bytes) for it.
7325 #[test]7497 #[test]
7326 fn the_encoders_own_streams_are_byte_identical_to_their_pins() {7498 fn the_encoders_own_streams_are_byte_identical_to_their_pins() {
7327 if !have_ffmpeg() {7499 if !have_ffmpeg() {
@@ -7343,7 +7515,7 @@ mod tests {
7343 })7515 })
7344 };7516 };
7345 let pins: [(u8, usize, u64); 2] =7517 let pins: [(u8, usize, u64); 2] =
7346- [(150, 7416, 0x75632db72a63d5f1), (60, 27927, 0xb63a984f521b7341)];7518+ [(150, 7458, 0x7eb2_33c6_bd96_3baf), (60, 27807, 0xeee0_f1e5_e099_46bd)];
7347 for (q, bytes, hash) in pins {7519 for (q, bytes, hash) in pins {
7348 let encoded = encode_sequence(&source, q, 0.5).unwrap();7520 let encoded = encode_sequence(&source, q, 0.5).unwrap();
7349 assert_eq!(7521 assert_eq!(
@@ -7558,6 +7730,37 @@ mod tests {
7558 mean(|l| l.2.0),7730 mean(|l| l.2.0),
7559 mean(|l| l.2.1),7731 mean(|l| l.2.1),
7560 );7732 );
7733+ // How many strength presets each frame's CDEF list carried and
7734+ // how the 64x64 units spread over them (lane-av1lr): `bits 0`
7735+ // everywhere would mean the per-unit choice never fires.
7736+ let presets = crate::filter_search::take_cdef_presets();
7737+ let mut by_bits = [0usize; 4];
7738+ for (b, _) in &presets {
7739+ by_bits[usize::from(*b)] += 1;
7740+ }
7741+ let units: usize = presets.iter().flat_map(|(_, c)| c).sum();
7742+ let on_extra: usize = presets
7743+ .iter()
7744+ .flat_map(|(_, c)| c.iter().skip(1))
7745+ .sum();
7746+ eprintln!(
7747+ "{name}: cdef_bits frames {}/{}/{}/{} (0/1/2/3); {} of {} 64x64 units \
7748+ on a non-default preset ({:.1}%)",
7749+ by_bits[0],
7750+ by_bits[1],
7751+ by_bits[2],
7752+ by_bits[3],
7753+ on_extra,
7754+ units,
7755+ 100.0 * on_extra as f64 / units.max(1) as f64
7756+ );
7757+ // How the 64x64 luma restoration units split between
7758+ // RESTORE_NONE and Wiener (lane-av1lr).
7759+ let (lr_none, lr_wiener) = crate::filter_search::take_lr_histogram();
7760+ eprintln!(
7761+ "{name}: lr units none={lr_none} wiener={lr_wiener} ({:.1}% restored)",
7762+ 100.0 * lr_wiener as f64 / (lr_none + lr_wiener).max(1) as f64
7763+ );
7561 // Which chroma modes the search actually wins with, against the7764 // Which chroma modes the search actually wins with, against the
7562 // unconditional DC_PRED that was the only outcome before7765 // unconditional DC_PRED that was the only outcome before
7563 // (gate-blind-to-feature).7766 // (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))> {
40 })40 })
41 }41 }
42 42
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+
43 /// Squared error between a decoded plane and the source it was coded from,57 /// Squared error between a decoded plane and the source it was coded from,
44 /// over the frame's own cropped `w x h` (the two planes have different58 /// over the frame's own cropped `w x h` (the two planes have different
45 /// strides: the source is the encoder's padded coding surface).59 /// 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
55 sse69 sse
56 }70 }
57 71
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+
58 /// CDEF primary strengths tried (libaom's own range is 0..15 for 8-bit97 /// CDEF primary strengths tried (libaom's own range is 0..15 for 8-bit
59 /// content) and the secondary ladder, whose only legal values are 0, 1, 298 /// content) and the secondary ladder, whose only legal values are 0, 1, 2
60 /// and 4 -- 3 is not codeable (spec 5.9.19 codes a secondary strength of 499 /// and 4 -- 3 is not codeable (spec 5.9.19 codes a secondary strength of 4
@@ -82,6 +121,10 @@ struct Trial {
82 picture: Picture,121 picture: Picture,
83 sse_y: u64,122 sse_y: u64,
84 sse_uv: u64,123 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>,
85 }128 }
86 129
87 /// Picks this frame's deblocking levels and CDEF strengths and hands back130 /// Picks this frame's deblocking levels and CDEF strengths and hands back
@@ -111,8 +154,11 @@ pub(crate) fn pick_filters(
111 src_w: usize,154 src_w: usize,
112 (fw, fh): (usize, usize),155 (fw, fh): (usize, usize),
113 damping: u8,156 damping: u8,
114-) -> Result<(LoopFilterParams, CdefParams, Picture)> {157+ (sb_cols, sb_rows): (usize, usize),
158+ lambda: f64,
159+) -> Result<(LoopFilterParams, CdefParams, Vec<u8>, Picture)> {
115 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));160 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));
161+ let nsb = sb_cols * sb_rows;
116 let mut trials: Vec<Trial> = Vec::new();162 let mut trials: Vec<Trial> = Vec::new();
117 let eval = |cand: Cand, trials: &mut Vec<Trial>| -> Result<usize> {163 let eval = |cand: Cand, trials: &mut Vec<Trial>| -> Result<usize> {
118 if let Some(i) = trials.iter().position(|t| t.cand == cand) {164 if let Some(i) = trials.iter().position(|t| t.cand == cand) {
@@ -123,7 +169,11 @@ pub(crate) fn pick_filters(
123 let sse_y = plane_sse(&picture.y, picture.width, source[0], src_w, fw, fh);169 let sse_y = plane_sse(&picture.y, picture.width, source[0], src_w, fw, fh);
124 let sse_uv = plane_sse(&picture.u, dec_cw, source[1], src_w / 2, cw, ch)170 let sse_uv = plane_sse(&picture.u, dec_cw, source[1], src_w / 2, cw, ch)
125 + plane_sse(&picture.v, dec_cw, source[2], src_w / 2, cw, ch);171 + 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 });
127 Ok(trials.len() - 1)177 Ok(trials.len() - 1)
128 };178 };
129 // One stage of the coordinate search: try `values` in the slot `set`179 // One stage of the coordinate search: try `values` in the slot `set`
@@ -168,11 +218,100 @@ pub(crate) fn pick_filters(
168 stage(&mut best, &CDEF_SEC, |c, v| c.uv.1 = v, |t| t.sse_uv, &mut trials)?;218 stage(&mut best, &CDEF_SEC, |c, v| c.uv.1 = v, |t| t.sse_uv, &mut trials)?;
169 219
170 CHOSEN.with(|c| c.borrow_mut().push(best));220 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+
171 let win = trials310 let win = trials
172 .into_iter()311 .into_iter()
173 .find(|t| t.cand == best)312 .find(|t| t.cand == best)
174 .expect("the winning candidate was evaluated");313 .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))
176 }315 }
177 316
178 /// The header's `loop_filter_params` for one candidate.317 /// 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:
205 }344 }
206 }345 }
207 }346 }
347+
348+// ---------------------------------------------------------------------------
349+// lane-av1lr: loop restoration (spec 7.17). Unlike deblocking and CDEF, whose
350+// parameters live in the frame header, a restoration unit's filter is coded
351+// in the TILE payload, so a whole-frame re-decode cannot search it: the
352+// search runs here, on the two pictures the decoder captured between its own
353+// filter stages (`crate::decode::FrameCtx::capture_stages`), through the
354+// decoder's OWN Wiener kernel (`crate::restoration::
355+// apply_loop_restoration_plane`) -- never a second implementation.
356+
357+/// The Wiener filters offered per unit, as the three free taps of a
358+/// direction (the centre tap is derived). Both directions take the same
359+/// candidate, so a unit picks one of four separable filters: two strengths
360+/// of low pass, one wider low pass, and one sharpener.
361+///
362+/// corner-cut: libaom's `av1_pick_filter_restoration` SOLVES for each unit's
363+/// taps (the Wiener-Hopf normal equations over that unit's autocorrelation)
364+/// instead of picking from a ladder, and also offers self-guided restoration.
365+/// The ceiling is whatever a four-point ladder leaves on the table; the
366+/// upgrade path is a per-unit solve feeding the same `write_wiener_filter`
367+/// syntax this already writes, plus `RestorationType::Switchable` for the
368+/// SGR arm.
369+const WIENER_CANDIDATES: [[i32; 3]; 4] = [[0, 0, 8], [0, 0, 16], [0, 4, 12], [0, 0, -8]];
370+
371+/// What a unit spends on its own syntax, for the RD choice below: one
372+/// `restore_wiener` symbol for `RESTORE_NONE`, and roughly the two
373+/// directions' three subexp-coded taps when it takes a filter.
374+const LR_NONE_BITS: f64 = 1.0;
375+const LR_WIENER_BITS: f64 = 25.0;
376+
377+/// Picks each luma restoration unit's filter, on the frame the decoder
378+/// captured after CDEF (with its post-deblock stripe borders), against the
379+/// source it was coded from. Returns one entry per unit in `rcol + rrow *
380+/// horz_units` order -- what `crate::tile::arm_lr` writes.
381+pub(crate) fn pick_restoration(
382+ stages: &crate::decode::FilterStages,
383+ source: &[u8],
384+ src_w: usize,
385+ (fw, fh): (usize, usize),
386+ lr: &ec_av1_syntax::LoopRestorationParams,
387+ lambda: f64,
388+ fctx: &crate::decode::FrameCtx,
389+) -> Vec<Option<crate::restoration::WienerInfo>> {
390+ let grid_dims = crate::restoration::RestorationGrid::new(lr, fw as u32, fh as u32);
391+ let (horz, vert) = (grid_dims.horz_units[0], grid_dims.vert_units[0]);
392+ let unit = lr.loop_restoration_size[0] as usize;
393+ let stride = stages.stride[0];
394+ let rows = crate::restoration::lr_unit_rows(fh, unit as u32, 0, lr.frame_restoration_type[0]);
395+ if rows.len() != vert {
396+ return Vec::new();
397+ }
398+ // Each unit's own sample span: the row walk's (a short last row is
399+ // swallowed by the one above it), and the column mirror of it.
400+ let span = |rrow: usize, rcol: usize| -> (usize, usize, usize, usize) {
401+ let (r0, r1) = rows[rrow];
402+ let c0 = rcol * unit;
403+ let c1 = if rcol + 1 == horz { fw } else { (rcol + 1) * unit };
404+ (r0 as usize, r1 as usize, c0, c1)
405+ };
406+ let unit_sse = |plane: &[u16], rrow: usize, rcol: usize| -> u64 {
407+ let (r0, r1, c0, c1) = span(rrow, rcol);
408+ let mut sse = 0u64;
409+ for row in r0..r1 {
410+ for col in c0..c1 {
411+ let diff = i64::from(plane[row * stride + col]) - i64::from(source[row * src_w + col]);
412+ sse += (diff * diff) as u64;
413+ }
414+ }
415+ sse
416+ };
417+ // Cost of leaving every unit alone, then one whole-plane pass per
418+ // candidate to price taking it.
419+ let mut best: Vec<(f64, Option<crate::restoration::WienerInfo>)> = (0..horz * vert)
420+ .map(|i| {
421+ let sse = unit_sse(&stages.cdefed[0], i / horz, i % horz) as f64;
422+ (sse + lambda * LR_NONE_BITS, None)
423+ })
424+ .collect();
425+ let mut out = Vec::new();
426+ for taps in WIENER_CANDIDATES {
427+ let info = crate::restoration::wiener_from_taps(taps, taps);
428+ let mut grid = crate::restoration::RestorationGrid::new(lr, fw as u32, fh as u32);
429+ for rrow in 0..vert {
430+ for rcol in 0..horz {
431+ grid.set(0, rrow, rcol, crate::restoration::UnitFilter::Wiener(info));
432+ }
433+ }
434+ crate::restoration::apply_loop_restoration_plane(
435+ &stages.cdefed[0],
436+ &stages.deblocked[0],
437+ stride,
438+ fw,
439+ fh,
440+ 0,
441+ lr.frame_restoration_type[0],
442+ lr.loop_restoration_size[0],
443+ &grid,
444+ 0,
445+ &mut out,
446+ None,
447+ fctx,
448+ );
449+ for rrow in 0..vert {
450+ for rcol in 0..horz {
451+ let cost = unit_sse(&out, rrow, rcol) as f64 + lambda * LR_WIENER_BITS;
452+ let slot = &mut best[rcol + rrow * horz];
453+ if cost < slot.0 {
454+ *slot = (cost, Some(info));
455+ }
456+ }
457+ }
458+ }
459+ let chosen: Vec<Option<crate::restoration::WienerInfo>> =
460+ best.into_iter().map(|(_, f)| f).collect();
461+ LR_CHOSEN.with(|c| {
462+ let mut hist = c.borrow_mut();
463+ for f in &chosen {
464+ hist.0 += usize::from(f.is_none());
465+ hist.1 += usize::from(f.is_some());
466+ }
467+ });
468+ chosen
469+}
470+
471+thread_local! {
472+ /// `(RESTORE_NONE units, Wiener units)` over every frame since the last
473+ /// [`take_lr_histogram`] -- the BD gate's own proof the feature fires.
474+ static LR_CHOSEN: std::cell::RefCell<(usize, usize)> =
475+ const { std::cell::RefCell::new((0, 0)) };
476+}
477+
478+/// Takes and clears [`LR_CHOSEN`].
479+#[allow(dead_code)] // read from the `#[cfg(test)]` BD gate
480+pub(crate) fn take_lr_histogram() -> (usize, usize) {
481+ LR_CHOSEN.with(|c| std::mem::take(&mut *c.borrow_mut()))
482+}
crates/ec-av1/src/restoration.rsmodified+169 -59
@@ -80,6 +80,139 @@ fn decode_signed_subexp_with_ref_msac(dec: &mut SymbolDecoder, low: i32, high: i
80 decode_unsigned_subexp_with_ref_msac(dec, n, k, r) as i32 + low80 decode_unsigned_subexp_with_ref_msac(dec, n, k, r) as i32 + low
81 }81 }
82 82
83+// ---------------------------------------------------------------------------
84+// lane-av1lr: the WRITE side of the three primitives above, for the encoder's
85+// per-restoration-unit syntax (`crate::tile`). Each is libaom's own writer
86+// (`aom_dsp/bitwriter.h`'s `write_primitive_*`) and the exact inverse of the
87+// reader it sits under; `wiener_filter_roundtrips` below pins the pair.
88+
89+/// `aom_write_primitive_quniform`, the inverse of [`ns_msac`].
90+fn write_ns(enc: &mut crate::msac::SymbolEncoder, n: u32, v: u32) {
91+ if n <= 1 {
92+ return;
93+ }
94+ let w = floor_log2(n) + 1;
95+ let m = (1u32 << w) - n;
96+ if v < m {
97+ enc.literal(v, w - 1);
98+ } else {
99+ enc.literal(m + ((v - m) >> 1), w - 1);
100+ enc.literal((v - m) & 1, 1);
101+ }
102+}
103+
104+/// `aom_write_primitive_subexpfin`, the inverse of [`decode_subexp_msac`].
105+fn write_subexp(enc: &mut crate::msac::SymbolEncoder, num_syms: u32, k: u32, v: u32) {
106+ let mut i = 0u32;
107+ let mut mk = 0u32;
108+ loop {
109+ let b = if i > 0 { k + i - 1 } else { k };
110+ let a = 1u32 << b;
111+ if num_syms <= mk + 3 * a {
112+ write_ns(enc, num_syms - mk, v - mk);
113+ return;
114+ }
115+ if v < mk + a {
116+ enc.literal(0, 1);
117+ enc.literal(v - mk, b);
118+ return;
119+ }
120+ enc.literal(1, 1);
121+ i += 1;
122+ mk += a;
123+ }
124+}
125+
126+/// `recenter_nonneg`, the inverse of [`inverse_recenter`].
127+fn recenter(r: u32, v: u32) -> u32 {
128+ if v > 2 * r {
129+ v
130+ } else if v >= r {
131+ (v - r) << 1
132+ } else {
133+ ((r - v) << 1) - 1
134+ }
135+}
136+
137+/// Inverse of [`decode_unsigned_subexp_with_ref_msac`].
138+fn write_unsigned_subexp_with_ref(
139+ enc: &mut crate::msac::SymbolEncoder,
140+ n: u32,
141+ k: u32,
142+ reference: u32,
143+ v: u32,
144+) {
145+ let recentred = if (reference << 1) <= n {
146+ recenter(reference, v)
147+ } else {
148+ recenter(n - 1 - reference, n - 1 - v)
149+ };
150+ write_subexp(enc, n, k, recentred);
151+}
152+
153+/// Inverse of [`decode_signed_subexp_with_ref_msac`].
154+fn write_signed_subexp_with_ref(
155+ enc: &mut crate::msac::SymbolEncoder,
156+ low: i32,
157+ high: i32,
158+ k: u32,
159+ reference: i32,
160+ v: i32,
161+) {
162+ let n = (high - low) as u32;
163+ let r = (reference - low).clamp(0, n as i32) as u32;
164+ write_unsigned_subexp_with_ref(enc, n, k, r, (v - low).clamp(0, n as i32 - 1) as u32);
165+}
166+
167+/// Inverse of [`read_wiener_filter`]: writes one unit's two directions and
168+/// advances the caller's running per-plane reference, exactly as the reader
169+/// advances its own.
170+pub(crate) fn write_wiener_filter(
171+ enc: &mut crate::msac::SymbolEncoder,
172+ chroma: bool,
173+ reference: &mut WienerInfo,
174+ info: &WienerInfo,
175+) {
176+ write_wiener_direction(enc, chroma, &reference.vfilter, &info.vfilter);
177+ write_wiener_direction(enc, chroma, &reference.hfilter, &info.hfilter);
178+ *reference = *info;
179+}
180+
181+/// Inverse of [`read_wiener_direction`].
182+fn write_wiener_direction(
183+ enc: &mut crate::msac::SymbolEncoder,
184+ chroma: bool,
185+ reference: &[i32; 7],
186+ taps: &[i32; 7],
187+) {
188+ for i in 0..3 {
189+ if i == 0 && chroma {
190+ continue;
191+ }
192+ write_signed_subexp_with_ref(
193+ enc,
194+ WIENER_TAP_MINV[i],
195+ WIENER_TAP_MAXV[i] + 1,
196+ WIENER_TAP_K[i],
197+ reference[i],
198+ taps[i],
199+ );
200+ }
201+}
202+
203+/// A Wiener unit's three free taps per direction, as [`WienerInfo`] (the
204+/// centre tap is derived, spec 7.17.4).
205+pub(crate) fn wiener_from_taps(v: [i32; 3], h: [i32; 3]) -> WienerInfo {
206+ let fill = |t: [i32; 3]| {
207+ let centre = 128 - 2 * (t[0] + t[1] + t[2]);
208+ [t[0], t[1], t[2], centre, t[2], t[1], t[0]]
209+ };
210+ WienerInfo {
211+ vfilter: fill(v),
212+ hfilter: fill(h),
213+ }
214+}
215+
83 #[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live216 #[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
84 const WIENER_HALFWIN: usize = 3;217 const WIENER_HALFWIN: usize = 3;
85 #[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live218 #[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
@@ -291,7 +424,7 @@ impl RestorationGrid {
291 }424 }
292 }425 }
293 426
294- fn set(&mut self, plane: usize, rrow: usize, rcol: usize, filter: UnitFilter) {427+ pub(crate) fn set(&mut self, plane: usize, rrow: usize, rcol: usize, filter: UnitFilter) {
295 let idx = rcol + rrow * self.horz_units[plane];428 let idx = rcol + rrow * self.horz_units[plane];
296 self.units[plane][idx] = filter;429 self.units[plane][idx] = filter;
297 }430 }
@@ -303,7 +436,7 @@ impl RestorationGrid {
303 }436 }
304 437
305 /// `av1_lr_count_units` (restoration.c:63): round, not ceil, to nearest.438 /// `av1_lr_count_units` (restoration.c:63): round, not ceil, to nearest.
306-fn count_units(plane_size: u32, unit_size: u32) -> usize {439+pub(crate) fn count_units(plane_size: u32, unit_size: u32) -> usize {
307 (((plane_size + (unit_size >> 1)) / unit_size).max(1)) as usize440 (((plane_size + (unit_size >> 1)) / unit_size).max(1)) as usize
308 }441 }
309 442
@@ -1366,63 +1499,10 @@ mod tests {
1366 use super::*;1499 use super::*;
1367 use crate::msac::{SymbolDecoder, SymbolEncoder};1500 use crate::msac::{SymbolDecoder, SymbolEncoder};
1368 1501
1369- /// `write_primitive_quniform`, the exact inverse of [`ns_msac`] -- used1502+ /// The write side these roundtrips exercise now lives beside the
1370- /// only to build roundtrip fixtures for the decode-only helpers above1503+ /// readers (`write_ns`/`write_subexp`/`write_unsigned_subexp_with_ref`,
1371- /// (this decoder never writes loop restoration itself).1504+ /// used by the encoder's per-unit LR syntax) instead of being a
1372- fn write_ns(enc: &mut SymbolEncoder, n: u32, v: u32) {1505+ /// test-only transcription of it -- one implementation, pinned here.
1373- if n <= 1 {
1374- return;
1375- }
1376- let w = floor_log2(n) + 1;
1377- let m = (1u32 << w) - n;
1378- if v < m {
1379- enc.literal(v, w - 1);
1380- } else {
1381- enc.literal((v + m) >> 1, w - 1);
1382- enc.literal((v + m) & 1, 1);
1383- }
1384- }
1385-
1386- fn write_subexp(enc: &mut SymbolEncoder, num_syms: u32, k: u32, v: u32) {
1387- let mut i = 0u32;
1388- let mut mk = 0u32;
1389- loop {
1390- let b = if i > 0 { k + i - 1 } else { k };
1391- let a = 1u32 << b;
1392- if num_syms <= mk + 3 * a {
1393- write_ns(enc, num_syms - mk, v - mk);
1394- return;
1395- }
1396- if v < mk + a {
1397- enc.literal(0, 1);
1398- enc.literal(v - mk, b);
1399- return;
1400- }
1401- enc.literal(1, 1);
1402- i += 1;
1403- mk += a;
1404- }
1405- }
1406-
1407- fn recenter(r: u32, v: u32) -> u32 {
1408- if v > 2 * r {
1409- v
1410- } else if v >= r {
1411- (v - r) << 1
1412- } else {
1413- ((r - v) << 1) - 1
1414- }
1415- }
1416-
1417- fn write_unsigned_subexp_with_ref(enc: &mut SymbolEncoder, n: u32, k: u32, reference: u32, v: u32) {
1418- let r = reference.clamp(0, n.saturating_sub(1));
1419- let coded = if (r << 1) <= n {
1420- recenter(r, v)
1421- } else {
1422- recenter(n - 1 - r, n - 1 - v)
1423- };
1424- write_subexp(enc, n, k, coded);
1425- }
1426 1506
1427 /// `decode_subexp_msac`/`ns_msac` roundtrip every value in a handful of1507 /// `decode_subexp_msac`/`ns_msac` roundtrip every value in a handful of
1428 /// `(num_syms, k)` alphabets -- the shapes LR's tap ranges (`k` 1..=4,1508 /// `(num_syms, k)` alphabets -- the shapes LR's tap ranges (`k` 1..=4,
@@ -1489,4 +1569,34 @@ mod tests {
1489 }1569 }
1490 }1570 }
1491 }1571 }
1572+
1573+ /// [`write_wiener_filter`] against [`read_wiener_filter`], including the
1574+ /// running per-tile reference both sides advance: three units in a row,
1575+ /// luma (7-tap) and chroma (5-tap, tap 0 forced to zero).
1576+ #[test]
1577+ fn wiener_filter_roundtrips() {
1578+ for chroma in [false, true] {
1579+ let units = [
1580+ wiener_from_taps([0, 0, 8], [0, 0, 8]),
1581+ wiener_from_taps([0, 4, 12], [0, 0, -8]),
1582+ wiener_from_taps([0, 0, 0], [0, 0, 0]),
1583+ ];
1584+ let units: Vec<WienerInfo> = if chroma {
1585+ units.iter().copied().collect()
1586+ } else {
1587+ units.to_vec()
1588+ };
1589+ let mut enc = SymbolEncoder::new();
1590+ let mut wref = WienerInfo::default();
1591+ for u in &units {
1592+ write_wiener_filter(&mut enc, chroma, &mut wref, u);
1593+ }
1594+ let payload = enc.finish();
1595+ let mut dec = SymbolDecoder::new(&payload);
1596+ let mut rref = WienerInfo::default();
1597+ for u in &units {
1598+ assert_eq!(read_wiener_filter(&mut dec, chroma, &mut rref), *u, "chroma={chroma}");
1599+ }
1600+ }
1601+ }
1492 }1602 }
crates/ec-av1/src/stream.rsmodified+4 -3
@@ -28,7 +28,7 @@ use crate::decode::{
28 q_ctx_of,28 q_ctx_of,
29 };29 };
30 #[cfg(test)]30 #[cfg(test)]
31-use crate::decode::decode_key_frame_tile;31+use crate::decode::decode_key_frame_tile_lr;
32 use crate::encode::Picture;32 use crate::encode::Picture;
33 33
34 /// lane-midcut r1: `EC_AV1_NO_GRAIN=1` skips film grain synthesis at output, so a34 /// lane-midcut r1: `EC_AV1_NO_GRAIN=1` skips film grain synthesis at output, so a
@@ -2986,7 +2986,7 @@ mod tests {
2986 for &(width, height) in &[(64usize, 64usize), (216, 96)] {2986 for &(width, height) in &[(64usize, 64usize), (216, 96)] {
2987 let picture = test_card(width, height);2987 let picture = test_card(width, height);
2988 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();2988 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
2989- let via_tile = decode_key_frame_tile(2989+ let via_tile = decode_key_frame_tile_lr(
2990 &encoded.tile,2990 &encoded.tile,
2991 encoded.mi_cols,2991 encoded.mi_cols,
2992 encoded.mi_rows,2992 encoded.mi_rows,
@@ -3000,7 +3000,8 @@ mod tests {
3000 // Our own encoder always writes `reduced_tx_set: true`.3000 // Our own encoder always writes `reduced_tx_set: true`.
3001 true,3001 true,
3002 false,3002 false,
3003- false, fctx,3003+ false,
3004+ &encoded.loop_restoration, fctx,
3004 )3005 )
3005 .unwrap();3006 .unwrap();
3006 let via_stream = decode_stream(&encoded.stream).unwrap();3007 let via_stream = decode_stream(&encoded.stream).unwrap();
crates/ec-av1/src/tile.rsmodified+173 -2
@@ -20,6 +20,163 @@ use crate::decode::{TXFM_CTX_INIT, txfm_partition_ctx_rect};
20 use crate::msac::SymbolEncoder;20 use crate::msac::SymbolEncoder;
21 use crate::mvstack::{MiGrid, MiInfo, NO_REF1, find_mv_stack, mv16};21 use crate::mvstack::{MiGrid, MiInfo, NO_REF1, find_mv_stack, mv16};
22 22
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+
23 /// round-4 av1-truesize debugging aid: prints `msg()` to stderr when the180 /// round-4 av1-truesize debugging aid: prints `msg()` to stderr when the
24 /// `EC_RNG` environment variable is set, mirroring the `EC_PART`/`EC_TOK`181 /// `EC_RNG` environment variable is set, mirroring the `EC_PART`/`EC_TOK`
25 /// trace `/tmp/libaom-src`'s debug `aomdec` build already emits under the182 /// 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(
1085 tx_select: bool,1242 tx_select: bool,
1086 cdfs: &mut Cdfs,1243 cdfs: &mut Cdfs,
1087 ) -> Result<Vec<u8>> {1244 ) -> Result<Vec<u8>> {
1245+ // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path.
1246+ let _cdef_idx = CdefIdxGuard;
1088 check_blocks(mi_cols, mi_rows)?;1247 check_blocks(mi_cols, mi_rows)?;
1089 let (cols, rows) = block_grid(mi_cols, mi_rows);1248 let (cols, rows) = block_grid(mi_cols, mi_rows);
1090 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));1249 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(
1148 for sb_r in 0..sb_rows {1307 for sb_r in 0..sb_rows {
1149 neighbours.start_row();1308 neighbours.start_row();
1150 for sb_c in 0..sb_cols {1309 for sb_c in 0..sb_cols {
1310+ write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W);
1151 let at = (sb_r as usize * 4, sb_c as usize * 4);1311 let at = (sb_r as usize * 4, sb_c as usize * 4);
1152 let ctx = neighbours.partition_ctx(at, SB);1312 let ctx = neighbours.partition_ctx(at, SB);
1153 ec_rng_trace(|| {1313 ec_rng_trace(|| {
@@ -1535,9 +1695,13 @@ fn write_intra_mode(
1535 above_mode: usize,1695 above_mode: usize,
1536 left_mode: usize,1696 left_mode: usize,
1537 cfl: bool,1697 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),
1538 ) -> usize {1701 ) -> usize {
1539 let mode = usize::from(block.mode);1702 let mode = usize::from(block.mode);
1540 enc.symbol(0, &mut cdfs.skip[0]);1703 enc.symbol(0, &mut cdfs.skip[0]);
1704+ write_cdef_idx(enc, mi, false);
1541 enc.symbol(1705 enc.symbol(
1542 mode,1706 mode,
1543 &mut cdfs.kf_y_mode[INTRA_MODE_CTX[above_mode]][INTRA_MODE_CTX[left_mode]],1707 &mut cdfs.kf_y_mode[INTRA_MODE_CTX[above_mode]][INTRA_MODE_CTX[left_mode]],
@@ -1585,6 +1749,7 @@ fn write_block(
1585 all_scans: &[Vec<u16>; 4],1749 all_scans: &[Vec<u16>; 4],
1586 ) -> Result<()> {1750 ) -> Result<()> {
1587 let (r, c) = at;1751 let (r, c) = at;
1752+ let at_mi = (r * (SUB / MI), c * (SUB / MI));
1588 let mode = write_intra_mode(1753 let mode = write_intra_mode(
1589 enc,1754 enc,
1590 cdfs,1755 cdfs,
@@ -1592,8 +1757,8 @@ fn write_block(
1592 neighbours.above_mode[c],1757 neighbours.above_mode[c],
1593 neighbours.left_mode[r],1758 neighbours.left_mode[r],
1594 cfl,1759 cfl,
1760+ at_mi,
1595 );1761 );
1596- let at_mi = (r * (SUB / MI), c * (SUB / MI));
1597 let split = if tx_select {1762 let split = if tx_select {
1598 let tx = write_luma_select(1763 let tx = write_luma_select(
1599 enc,1764 enc,
@@ -1667,7 +1832,7 @@ fn write_leaf8(
1667 // true first divergence (a differently-sized alphabet under the same1832 // true first divergence (a differently-sized alphabet under the same
1668 // DC_PRED decision desyncs the coder even though the decoded mode is1833 // DC_PRED decision desyncs the coder even though the decoded mode is
1669 // unchanged).1834 // 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);
1671 let planes = [TxbSet::Luma8, TxbSet::Chroma4, TxbSet::Chroma4];1836 let planes = [TxbSet::Luma8, TxbSet::Chroma4, TxbSet::Chroma4];
1672 let split = if tx_select {1837 let split = if tx_select {
1673 let tx = write_luma_select(1838 let tx = write_luma_select(
@@ -2979,6 +3144,8 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
2979 tx_select: bool,3144 tx_select: bool,
2980 cdfs: &mut Cdfs,3145 cdfs: &mut Cdfs,
2981 ) -> Result<Vec<u8>> {3146 ) -> Result<Vec<u8>> {
3147+ // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path.
3148+ let _cdef_idx = CdefIdxGuard;
2982 check_blocks(mi_cols, mi_rows)?;3149 check_blocks(mi_cols, mi_rows)?;
2983 // `block_grid`'s ceiling, not a plain division: a true frame size that is3150 // `block_grid`'s ceiling, not a plain division: a true frame size that is
2984 // not a whole number of 32x32 blocks (or of 64x64 superblocks) still has3151 // 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(
3046 for sb_r in 0..sb_rows {3213 for sb_r in 0..sb_rows {
3047 neighbours.start_row();3214 neighbours.start_row();
3048 for sb_c in 0..sb_cols {3215 for sb_c in 0..sb_cols {
3216+ write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W);
3049 let sb_at = (sb_r as usize * 4, sb_c as usize * 4);3217 let sb_at = (sb_r as usize * 4, sb_c as usize * 4);
3050 let sb_ctx = neighbours.partition_ctx(sb_at, SB);3218 let sb_ctx = neighbours.partition_ctx(sb_at, SB);
3051 // spec `decode_partition`'s hasRows/hasCols (5.11.4): a superblock3219 // spec `decode_partition`'s hasRows/hasCols (5.11.4): a superblock
@@ -3293,6 +3461,7 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
3293 let skip_ctx = usize::from(neighbours.above_skip[mi_c])3461 let skip_ctx = usize::from(neighbours.above_skip[mi_c])
3294 + usize::from(neighbours.left_skip[mi_r]);3462 + usize::from(neighbours.left_skip[mi_r]);
3295 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);3463 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
3464+ write_cdef_idx(&mut enc, (mi_r, mi_c), block.skip);
3296 3465
3297 let is_inter = block.inter.is_some();3466 let is_inter = block.inter.is_some();
3298 let (above_inter, left_inter) =3467 let (above_inter, left_inter) =
@@ -3497,6 +3666,7 @@ fn write_inter_frame_leaf(
3497 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));3666 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
3498 let skip_ctx = usize::from(neighbours.above_skip[mi_c]) + usize::from(neighbours.left_skip[mi_r]);3667 let skip_ctx = usize::from(neighbours.above_skip[mi_c]) + usize::from(neighbours.left_skip[mi_r]);
3499 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);3668 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
3669+ write_cdef_idx(enc, (mi_r, mi_c), block.skip);
3500 3670
3501 let (has_above, has_left) = (r > 0, c > 0);3671 let (has_above, has_left) = (r > 0, c > 0);
3502 let (above_inter, left_inter) = (neighbours.above_inter[mi_c], neighbours.left_inter[mi_r]);3672 let (above_inter, left_inter) = (neighbours.above_inter[mi_c], neighbours.left_inter[mi_r]);
@@ -3690,6 +3860,7 @@ fn write_inter_frame_leaf8(
3690 let left_inter = neighbours.left_inter[leaf_mi.0];3860 let left_inter = neighbours.left_inter[leaf_mi.0];
3691 let skip_ctx = usize::from(above_skip) + usize::from(left_skip);3861 let skip_ctx = usize::from(above_skip) + usize::from(left_skip);
3692 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);3862 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
3863+ write_cdef_idx(enc, leaf_mi, block.skip);
3693 3864
3694 let (has_above, has_left) = (leaf_mi.0 > 0, leaf_mi.1 > 0);3865 let (has_above, has_left) = (leaf_mi.0 > 0, leaf_mi.1 > 0);
3695 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);3866 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);