forge
Explore
Log in

Don't you dare go Hollow

wip(av1): lane-lr r4 Wiener work at the 75-turn cap (orchestrator commit, unverified)

Browse files at this commit

10cbc50e46ac60a3f9b2511586d5085049d44d5aAhmet Kaan GümüşParent: 65d1211
crates/ec-av1/src/decode.rsmodified+61 -0
@@ -2609,6 +2609,7 @@ fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 {
2609 /// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly2609 /// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly
2610 /// (own-edge and reach clamps both), passing what it gathers straight to2610 /// (own-edge and reach clamps both), passing what it gathers straight to
2611 /// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone.2611 /// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone.
2612+#[derive(Clone)]
2612 struct PlaneBuf {2613 struct PlaneBuf {
2613 data: Vec<u8>,2614 data: Vec<u8>,
2614 width: usize,2615 width: usize,
@@ -4414,6 +4415,62 @@ fn apply_cdef(
4414 }4415 }
4415 }4416 }
4416 4417
4418+/// Spec 7.17: loop restoration, run after [`apply_cdef`] (a sibling lane's
4419+/// ordering note: libaom also runs `superres_post_decode` between the two,
4420+/// but this decoder never implements super-resolution, so there is nothing
4421+/// to interleave). `deblocked_*` is each plane's post-deblock, pre-CDEF
4422+/// buffer (the caller clones it before calling [`apply_cdef`]) -- loop
4423+/// restoration's stripe-boundary rows read from it instead of the
4424+/// CDEF-filtered plane, per `restoration.rs`'s own `lr_sample` doc comment.
4425+#[allow(clippy::too_many_arguments)]
4426+fn apply_loop_restoration(
4427+ y: &mut PlaneBuf,
4428+ u: &mut PlaneBuf,
4429+ v: &mut PlaneBuf,
4430+ deblocked_y: &PlaneBuf,
4431+ deblocked_u: &PlaneBuf,
4432+ deblocked_v: &PlaneBuf,
4433+ lr: &LoopRestorationParams,
4434+ grid: &crate::restoration::RestorationGrid,
4435+) {
4436+ y.data = crate::restoration::apply_loop_restoration_plane(
4437+ &y.data,
4438+ &deblocked_y.data,
4439+ y.width,
4440+ y.true_width,
4441+ y.true_height,
4442+ 0,
4443+ lr.frame_restoration_type[0],
4444+ lr.loop_restoration_size[0],
4445+ grid,
4446+ 0,
4447+ );
4448+ u.data = crate::restoration::apply_loop_restoration_plane(
4449+ &u.data,
4450+ &deblocked_u.data,
4451+ u.width,
4452+ u.true_width,
4453+ u.true_height,
4454+ 1,
4455+ lr.frame_restoration_type[1],
4456+ lr.loop_restoration_size[1],
4457+ grid,
4458+ 1,
4459+ );
4460+ v.data = crate::restoration::apply_loop_restoration_plane(
4461+ &v.data,
4462+ &deblocked_v.data,
4463+ v.width,
4464+ v.true_width,
4465+ v.true_height,
4466+ 1,
4467+ lr.frame_restoration_type[2],
4468+ lr.loop_restoration_size[2],
4469+ grid,
4470+ 2,
4471+ );
4472+}
4473+
4417 /// Decodes the payload [`crate::tile::sb_coeff_key_frame_tile`] writes,4474 /// Decodes the payload [`crate::tile::sb_coeff_key_frame_tile`] writes,
4418 /// returning the picture it reconstructs to.4475 /// returning the picture it reconstructs to.
4419 ///4476 ///
@@ -4980,7 +5037,9 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
4980 PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);5037 PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
4981 }5038 }
4982 apply_deblock(&mut y, &mut u, &mut v, loop_filter, &neighbours);5039 apply_deblock(&mut y, &mut u, &mut v, loop_filter, &neighbours);
5040+ let (deblocked_y, deblocked_u, deblocked_v) = (y.clone(), u.clone(), v.clone());
4983 apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours);5041 apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours);
5042+ apply_loop_restoration(&mut y, &mut u, &mut v, &deblocked_y, &deblocked_u, &deblocked_v, lr, &lr_grid);
4984 5043
4985 let (fw, fh) = (frame_width as usize, frame_height as usize);5044 let (fw, fh) = (frame_width as usize, frame_height as usize);
4986 if fw == width && fh == height {5045 if fw == width && fh == height {
@@ -10499,7 +10558,9 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
10499 PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);10558 PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
10500 }10559 }
10501 apply_deblock(&mut y, &mut u, &mut v, loop_filter, &neighbours);10560 apply_deblock(&mut y, &mut u, &mut v, loop_filter, &neighbours);
10561+ let (deblocked_y, deblocked_u, deblocked_v) = (y.clone(), u.clone(), v.clone());
10502 apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours);10562 apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours);
10563+ apply_loop_restoration(&mut y, &mut u, &mut v, &deblocked_y, &deblocked_u, &deblocked_v, lr, &lr_grid);
10503 10564
10504 let motion_field = build_motion_field(10565 let motion_field = build_motion_field(
10505 &grid,10566 &grid,
crates/ec-av1/src/restoration.rsmodified+448 -0
@@ -425,6 +425,454 @@ fn read_lr_unit(
425 }425 }
426 }426 }
427 427
428+// ---------------------------------------------------------------------
429+// Spec 7.17: the two pixel filters (Wiener, self-guided) plus the
430+// restoration-unit/stripe walk that drives them.
431+// ---------------------------------------------------------------------
432+
433+/// `Round2` (spec 4.7): halves round up, arithmetic shift for negative sums
434+/// -- same primitive as `mc.rs`/`warp.rs`'s own `round2`, here at `i64`
435+/// since the self-guided filter's intermediate products don't fit `i32`.
436+fn round2(value: i64, shift: u32) -> i64 {
437+ if shift == 0 {
438+ value
439+ } else {
440+ (value + (1i64 << (shift - 1))) >> shift
441+ }
442+}
443+
444+/// One plane's sample fetch for the pixel filters (spec 7.17.2's stripe
445+/// boundary substitution, libaom `setup_processing_stripe_boundary`/
446+/// `get_stripe_boundary_info`): within the stripe `[stripe_v_start,
447+/// stripe_v_end)` currently being filtered, read the post-CDEF plane;
448+/// outside it (the 3-row border both filters' kernels reach into), read the
449+/// post-deblock, pre-CDEF plane instead -- UNLESS the stripe is the very
450+/// first/last stripe in the whole plane, where the frame's own top/bottom
451+/// edge replicates (`av1_extend_frame`) rather than crossing into deblocked
452+/// data. Columns always clamp to the plane's own true width -- restoration
453+/// unit COLUMN boundaries have no such substitution, only stripe (row)
454+/// boundaries do.
455+#[allow(clippy::too_many_arguments)]
456+fn lr_sample(
457+ cdef: &[u8],
458+ deblocked: &[u8],
459+ stride: usize,
460+ plane_w: usize,
461+ plane_h: usize,
462+ stripe_v_start: usize,
463+ stripe_v_end: usize,
464+ row: i64,
465+ col: i64,
466+) -> i32 {
467+ let col_c = col.clamp(0, plane_w as i64 - 1) as usize;
468+ if row >= stripe_v_start as i64 && row < stripe_v_end as i64 {
469+ i32::from(cdef[row as usize * stride + col_c])
470+ } else if row < stripe_v_start as i64 {
471+ if stripe_v_start == 0 {
472+ i32::from(cdef[col_c])
473+ } else {
474+ // libaom saves 2 deblocked context lines and duplicates the
475+ // outer one to fill a 3-row border (`RESTORATION_BORDER`):
476+ // row `stripe_v_start-1` reads deblocked row `stripe_v_start-1`,
477+ // rows `stripe_v_start-2`/`-3` both read deblocked row
478+ // `stripe_v_start-2`.
479+ let dist = stripe_v_start as i64 - 1 - row;
480+ let src_row = if dist == 0 {
481+ stripe_v_start - 1
482+ } else {
483+ stripe_v_start.saturating_sub(2)
484+ };
485+ i32::from(deblocked[src_row * stride + col_c])
486+ }
487+ } else if stripe_v_end == plane_h {
488+ i32::from(cdef[(plane_h - 1) * stride + col_c])
489+ } else {
490+ // Mirror image of the above: rows `stripe_v_end`/`stripe_v_end+1`
491+ // read their own deblocked row, row `stripe_v_end+2` duplicates
492+ // `stripe_v_end+1`.
493+ let dist = (row - stripe_v_end as i64).min(1) as usize;
494+ let src_row = (stripe_v_end + dist).min(plane_h - 1);
495+ i32::from(deblocked[src_row * stride + col_c])
496+ }
497+}
498+
499+/// Wiener pixel filter (spec 7.17.4, libaom `wiener_filter_stripe` ->
500+/// `av1_wiener_convolve_add_src_c`), one stripe-height chunk of one
501+/// restoration unit: a separable 7-tap horizontal pass (rounded by
502+/// `WIENER_ROUND0_BITS==3`, clipped to spec's intermediate range) feeding a
503+/// 7-tap vertical pass (rounded by `2*FILTER_BITS-3==11`) -- the same
504+/// `INTER_ROUND_0`/`INTER_ROUND_1` shifts `mc.rs`'s motion compensation
505+/// uses, since AV1 reuses that same separable-filter machinery here with a
506+/// custom 7-tap kernel instead of the fixed subpel tables. libaom's C
507+/// folds an extra `+/- (1 << ...)` bias into each pass to compensate for a
508+/// pointer-alignment trick that borrows the interpolation filter's 8-tap
509+/// convolution loop for a 7-tap kernel; that bias cancels algebraically
510+/// against `WienerInfo`'s own derived centre tap (`128 - 2*sum(taps)`), so
511+/// plugging the real taps straight into `sum(tap * sample)` (no bias term)
512+/// reproduces the same output byte-for-byte.
513+#[allow(clippy::too_many_arguments)]
514+fn apply_wiener_stripe(
515+ out: &mut [u8],
516+ cdef: &[u8],
517+ deblocked: &[u8],
518+ stride: usize,
519+ plane_w: usize,
520+ plane_h: usize,
521+ h_start: usize,
522+ h_end: usize,
523+ v_start: usize,
524+ v_end: usize,
525+ info: &WienerInfo,
526+) {
527+ let w = h_end - h_start;
528+ let h = v_end - v_start;
529+ if w == 0 || h == 0 {
530+ return;
531+ }
532+ let rows = h + 6;
533+ let mut inter = vec![0i32; rows * w];
534+ for r in 0..rows {
535+ let row = v_start as i64 - 3 + r as i64;
536+ for c in 0..w {
537+ let col = h_start as i64 + c as i64;
538+ let mut sum = 0i64;
539+ for (t, &tap) in info.hfilter.iter().enumerate() {
540+ let x = col - 3 + t as i64;
541+ sum += tap as i64
542+ * lr_sample(cdef, deblocked, stride, plane_w, plane_h, v_start, v_end, row, x) as i64;
543+ }
544+ // `WIENER_CLAMP_LIMIT(round0=3, bd=8) - 1`.
545+ inter[r * w + c] = round2(sum, 3).clamp(0, 8191) as i32;
546+ }
547+ }
548+ for r in 0..h {
549+ for c in 0..w {
550+ let mut sum = 0i64;
551+ for (t, &tap) in info.vfilter.iter().enumerate() {
552+ sum += tap as i64 * inter[(r + t) * w + c] as i64;
553+ }
554+ out[(v_start + r) * stride + h_start + c] = round2(sum, 11).clamp(0, 255) as u8;
555+ }
556+ }
557+}
558+
559+/// `av1_x_by_xplus1` (`restoration.c`): `round(256*z/(z+1))` for `z` in
560+/// `[0,255]`, saturating the `z==0` case to `1` instead of `0` (see the
561+/// libaom source comment this ports -- keeps `256-A[k]` inside a `u8` and
562+/// avoids a later overflow, without visibly affecting a near-flat block).
563+const SGR_X_BY_XPLUS1: [i32; 256] = [
564+ 1, 128, 171, 192, 205, 213, 219, 224, 228, 230, 233, 235, 236, 238, 239, 240, 241, 242, 243, 243, 244, 244, 245,
565+ 245, 246, 246, 247, 247, 247, 247, 248, 248, 248, 248, 249, 249, 249, 249, 249, 250, 250, 250, 250, 250, 250,
566+ 250, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252,
567+ 252, 252, 252, 252, 252, 252, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253,
568+ 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254,
569+ 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254,
570+ 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254,
571+ 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
572+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
573+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
574+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
575+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 256,
576+];
577+
578+/// `av1_one_by_x` (`restoration.c`): `round(4096/n)` for `n` in `1..=25`
579+/// (`MAX_NELEM`, `(2*MAX_RADIUS+1)^2`), indexed `[n-1]`.
580+const SGR_ONE_BY_X: [i32; 25] = [
581+ 4096, 2048, 1365, 1024, 819, 683, 585, 512, 455, 410, 372, 341, 315, 293, 273, 256, 241, 228, 216, 205, 195, 186,
582+ 178, 171, 164,
583+];
584+
585+const SGRPROJ_MTABLE_BITS: u32 = 20;
586+const SGRPROJ_RECIP_BITS: u32 = 12;
587+const SGRPROJ_SGR_BITS: u32 = 8;
588+const SGRPROJ_RST_BITS: u32 = 4;
589+
590+/// `calculate_intermediate_result` (`restoration.c`): the blend-factor pair
591+/// `(A[k], B[k])` at every position in `-1..=h` x `-1..=w` relative to a
592+/// restoration unit (a 1-pixel border around the unit, spec 7.17.3's
593+/// `BoxFilter`), for one of the two SGR radii. `r`/`s` are `SGR_PARAMS[ep]`'s
594+/// `(r0,s0)` or `(r1,s1)`; libaom computes this only at odd rows for the
595+/// `r==2` ("fast") radius as a running-sum speed optimisation -- the box
596+/// sum itself is identical at every row regardless, so computing it
597+/// everywhere (this function does, via a plain windowed sum through
598+/// [`lr_sample`] rather than libaom's O(1)-per-step sliding sum) and only
599+/// *reading* the odd rows back in [`apply_sgrproj_stripe`]'s fast branch
600+/// reproduces the same values without porting the sliding-window trick.
601+#[allow(clippy::too_many_arguments)]
602+fn compute_ab(
603+ cdef: &[u8],
604+ deblocked: &[u8],
605+ stride: usize,
606+ plane_w: usize,
607+ plane_h: usize,
608+ h_start: usize,
609+ v_start: usize,
610+ v_end: usize,
611+ w: usize,
612+ h: usize,
613+ r: i32,
614+ s: i32,
615+) -> Vec<(i32, i64)> {
616+ let gw = w + 2;
617+ let gh = h + 2;
618+ let mut ab = vec![(0i32, 0i64); gw * gh];
619+ let n = ((2 * r + 1) * (2 * r + 1)) as i64;
620+ for gi in 0..gh {
621+ let i = gi as i64 - 1;
622+ for gj in 0..gw {
623+ let j = gj as i64 - 1;
624+ let mut a = 0i64;
625+ let mut b = 0i64;
626+ for dr in -r..=r {
627+ let row = v_start as i64 + i + dr as i64;
628+ for dc in -r..=r {
629+ let col = h_start as i64 + j + dc as i64;
630+ let px =
631+ lr_sample(cdef, deblocked, stride, plane_w, plane_h, v_start, v_end, row, col) as i64;
632+ a += px * px;
633+ b += px;
634+ }
635+ }
636+ let p = if a * n < b * b { 0 } else { a * n - b * b };
637+ let z = round2(p * s as i64, SGRPROJ_MTABLE_BITS).clamp(0, 255) as usize;
638+ let a_val = SGR_X_BY_XPLUS1[z];
639+ let b_val = round2(
640+ (256 - a_val) as i64 * b * SGR_ONE_BY_X[(n - 1) as usize] as i64,
641+ SGRPROJ_RECIP_BITS,
642+ );
643+ ab[gi * gw + gj] = (a_val, b_val);
644+ }
645+ }
646+ ab
647+}
648+
649+/// Self-guided pixel filter (spec 7.17.3, libaom `sgrproj_filter_stripe` ->
650+/// `av1_apply_selfguided_restoration_c`), one stripe-height chunk of one
651+/// restoration unit: up to two box-filtered blends (`SGR_PARAMS[ep]`'s `r0`
652+/// "fast"/even-odd-row and `r1` dense radii, either may be `0` and skipped)
653+/// combined with the decoded `xqd` weights via `av1_decode_xq`.
654+#[allow(clippy::too_many_arguments)]
655+fn apply_sgrproj_stripe(
656+ out: &mut [u8],
657+ cdef: &[u8],
658+ deblocked: &[u8],
659+ stride: usize,
660+ plane_w: usize,
661+ plane_h: usize,
662+ h_start: usize,
663+ h_end: usize,
664+ v_start: usize,
665+ v_end: usize,
666+ info: &SgrprojInfo,
667+) {
668+ let w = h_end - h_start;
669+ let h = v_end - v_start;
670+ if w == 0 || h == 0 {
671+ return;
672+ }
673+ let (r0, r1, s0, s1) = SGR_PARAMS[info.ep];
674+ let gw = w + 2;
675+ let idx = |gi: i64, gj: i64| -> usize { (gi + 1) as usize * gw + (gj + 1) as usize };
676+
677+ let ab0 = (r0 > 0).then(|| compute_ab(cdef, deblocked, stride, plane_w, plane_h, h_start, v_start, v_end, w, h, r0, s0));
678+ let ab1 = (r1 > 0).then(|| compute_ab(cdef, deblocked, stride, plane_w, plane_h, h_start, v_start, v_end, w, h, r1, s1));
679+
680+ let mut xq = [0i32; 2];
681+ if r0 == 0 {
682+ xq[0] = 0;
683+ xq[1] = (1 << SGRPROJ_PRJ_BITS) - info.xqd[1];
684+ } else if r1 == 0 {
685+ xq[0] = info.xqd[0];
686+ xq[1] = 0;
687+ } else {
688+ xq[0] = info.xqd[0];
689+ xq[1] = (1 << SGRPROJ_PRJ_BITS) - xq[0] - info.xqd[1];
690+ }
691+
692+ for i in 0..h as i64 {
693+ for j in 0..w as i64 {
694+ let dgd = lr_sample(
695+ cdef,
696+ deblocked,
697+ stride,
698+ plane_w,
699+ plane_h,
700+ v_start,
701+ v_end,
702+ v_start as i64 + i,
703+ h_start as i64 + j,
704+ ) as i64;
705+ let u = dgd << SGRPROJ_RST_BITS;
706+ let mut v = u << SGRPROJ_PRJ_BITS;
707+ if let Some(ab) = &ab0 {
708+ // "Fast" radius (`r0==2`): A/B were only ever meaningfully
709+ // computed at odd rows (see `compute_ab`'s doc comment) --
710+ // an even output row blends its two odd neighbour rows
711+ // (weight 6/5, `nb=5`), an odd output row reuses its own
712+ // row's A/B plus column neighbours (weight 6/5, `nb=4`).
713+ let (a, b, nb) = if i & 1 == 0 {
714+ let (a_um1, b_um1) = ab[idx(i - 1, j)];
715+ let (a_up1, b_up1) = ab[idx(i + 1, j)];
716+ let (a_uml, b_uml) = ab[idx(i - 1, j - 1)];
717+ let (a_umr, b_umr) = ab[idx(i - 1, j + 1)];
718+ let (a_upl, b_upl) = ab[idx(i + 1, j - 1)];
719+ let (a_upr, b_upr) = ab[idx(i + 1, j + 1)];
720+ let a = (a_um1 + a_up1) as i64 * 6 + (a_uml + a_umr + a_upl + a_upr) as i64 * 5;
721+ let b = (b_um1 + b_up1) * 6 + (b_uml + b_umr + b_upl + b_upr) * 5;
722+ (a, b, 5u32)
723+ } else {
724+ let (a_c, b_c) = ab[idx(i, j)];
725+ let (a_l, b_l) = ab[idx(i, j - 1)];
726+ let (a_r, b_r) = ab[idx(i, j + 1)];
727+ let a = a_c as i64 * 6 + (a_l + a_r) as i64 * 5;
728+ let b = b_c * 6 + (b_l + b_r) * 5;
729+ (a, b, 4u32)
730+ };
731+ let flt0 = round2(a * dgd + b, SGRPROJ_SGR_BITS + nb - SGRPROJ_RST_BITS);
732+ v += xq[0] as i64 * (flt0 - u);
733+ }
734+ if let Some(ab) = &ab1 {
735+ // Dense radius (`r1==1`): every row was computed, so the
736+ // combine is the full 3x3 neighbourhood (weight 4/3).
737+ let (a_c, b_c) = ab[idx(i, j)];
738+ let (a_u, b_u) = ab[idx(i - 1, j)];
739+ let (a_d, b_d) = ab[idx(i + 1, j)];
740+ let (a_l, b_l) = ab[idx(i, j - 1)];
741+ let (a_r, b_r) = ab[idx(i, j + 1)];
742+ let (a_ul, b_ul) = ab[idx(i - 1, j - 1)];
743+ let (a_ur, b_ur) = ab[idx(i - 1, j + 1)];
744+ let (a_dl, b_dl) = ab[idx(i + 1, j - 1)];
745+ let (a_dr, b_dr) = ab[idx(i + 1, j + 1)];
746+ let a = (a_c + a_u + a_d + a_l + a_r) as i64 * 4 + (a_ul + a_ur + a_dl + a_dr) as i64 * 3;
747+ let b = (b_c + b_u + b_d + b_l + b_r) * 4 + (b_ul + b_ur + b_dl + b_dr) * 3;
748+ let flt1 = round2(a * dgd + b, SGRPROJ_SGR_BITS + 5 - SGRPROJ_RST_BITS);
749+ v += xq[1] as i64 * (flt1 - u);
750+ }
751+ let out_v = round2(v, SGRPROJ_PRJ_BITS as u32 + SGRPROJ_RST_BITS).clamp(0, 255) as u8;
752+ out[(v_start as i64 + i) as usize * stride + (h_start as i64 + j) as usize] = out_v;
753+ }
754+ }
755+}
756+
757+/// Chunks one restoration unit's `[v_start, v_end)` extent into 64-row
758+/// (56 for the plane's very first stripe -- `RESTORATION_UNIT_OFFSET==8`)
759+/// processing stripes and filters each (libaom
760+/// `av1_loop_restoration_filter_unit`'s own `while (i < unit_h)` loop) --
761+/// a restoration unit can be up to `256*1.5` px tall, spanning several
762+/// stripes, each of which needs its own boundary-source decision from
763+/// [`lr_sample`].
764+#[allow(clippy::too_many_arguments)]
765+fn filter_restoration_unit(
766+ out: &mut [u8],
767+ cdef: &[u8],
768+ deblocked: &[u8],
769+ stride: usize,
770+ plane_w: usize,
771+ plane_h: usize,
772+ h_start: usize,
773+ h_end: usize,
774+ v_start: usize,
775+ v_end: usize,
776+ ss_y: u32,
777+ filter: UnitFilter,
778+) {
779+ let full_stripe_height = 64usize >> ss_y;
780+ let runit_offset = 8usize >> ss_y;
781+ let unit_h = v_end - v_start;
782+ let mut i = 0usize;
783+ while i < unit_h {
784+ let stripe_v_start = v_start + i;
785+ let frame_stripe = (stripe_v_start + runit_offset) / full_stripe_height;
786+ let nominal_h = full_stripe_height - if frame_stripe == 0 { runit_offset } else { 0 };
787+ let h = nominal_h.min(unit_h - i);
788+ let stripe_v_end = stripe_v_start + h;
789+ match filter {
790+ UnitFilter::Wiener(info) => apply_wiener_stripe(
791+ out, cdef, deblocked, stride, plane_w, plane_h, h_start, h_end, stripe_v_start, stripe_v_end, &info,
792+ ),
793+ UnitFilter::Sgrproj(info) => apply_sgrproj_stripe(
794+ out, cdef, deblocked, stride, plane_w, plane_h, h_start, h_end, stripe_v_start, stripe_v_end, &info,
795+ ),
796+ UnitFilter::None => {}
797+ }
798+ i += h;
799+ }
800+}
801+
802+/// Applies loop restoration to one whole plane's post-CDEF samples (spec
803+/// 7.17). Walks restoration units exactly as libaom's
804+/// `foreach_rest_unit_in_plane` (`unit_size` steps, the tail folded into
805+/// the previous unit when the remainder is under `1.5*unit_size` -- the
806+/// same round-to-nearest [`count_units`] already used to size
807+/// [`RestorationGrid`]), then re-offsets internal row boundaries by
808+/// `RESTORATION_UNIT_OFFSET==8` (the first/last row of the plane keeps its
809+/// full extent). Returns a fresh copy of `cdef` with only this plane's
810+/// restoration-unit pixels replaced -- a restoration unit must never read
811+/// another, already-filtered unit's output (spec keeps a separate
812+/// destination buffer for exactly this reason), so this never filters in
813+/// place.
814+#[allow(clippy::too_many_arguments)]
815+pub(crate) fn apply_loop_restoration_plane(
816+ cdef: &[u8],
817+ deblocked: &[u8],
818+ stride: usize,
819+ plane_w: usize,
820+ plane_h: usize,
821+ ss_y: u32,
822+ ftype: RestorationType,
823+ unit_size: u32,
824+ grid: &RestorationGrid,
825+ plane: usize,
826+) -> Vec<u8> {
827+ let mut out = cdef.to_vec();
828+ if ftype == RestorationType::None || unit_size == 0 {
829+ return out;
830+ }
831+ let voffset = 8u32 >> ss_y;
832+ let ext_size = (unit_size * 3) / 2;
833+ let mut y0 = 0u32;
834+ let mut rrow = 0usize;
835+ while y0 < plane_h as u32 {
836+ let remaining_h = plane_h as u32 - y0;
837+ let uh = if remaining_h < ext_size { remaining_h } else { unit_size };
838+ let v_start = (y0 as i64 - voffset as i64).max(0) as u32;
839+ let mut v_end = y0 + uh;
840+ if v_end < plane_h as u32 {
841+ v_end -= voffset;
842+ }
843+
844+ let mut x0 = 0u32;
845+ let mut rcol = 0usize;
846+ while x0 < plane_w as u32 {
847+ let remaining_w = plane_w as u32 - x0;
848+ let uw = if remaining_w < ext_size { remaining_w } else { unit_size };
849+ let filter = grid.get(plane, rrow, rcol);
850+ if filter != UnitFilter::None {
851+ filter_restoration_unit(
852+ &mut out,
853+ cdef,
854+ deblocked,
855+ stride,
856+ plane_w,
857+ plane_h,
858+ x0 as usize,
859+ (x0 + uw) as usize,
860+ v_start as usize,
861+ v_end as usize,
862+ ss_y,
863+ filter,
864+ );
865+ }
866+ x0 += uw;
867+ rcol += 1;
868+ }
869+ y0 += uh;
870+ rrow += 1;
871+ }
872+ debug_assert_eq!(rrow, grid.vert_units[plane], "RU row walk must match RestorationGrid::new's count_units");
873+ out
874+}
875+
428 #[cfg(test)]876 #[cfg(test)]
429 mod tests {877 mod tests {
430 use super::*;878 use super::*;
crates/ec-av1/src/stream.rsmodified+22 -27
@@ -461,15 +461,9 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
461 header.allow_screen_content_tools,461 header.allow_screen_content_tools,
462 )?462 )?
463 };463 };
464- // lane-lr r3: the tile decode above just ran `read_lr` for real (see464+ // lane-lr r4: the Wiener/self-guided pixel filters are wired
465- // this refusal's own doc comment further up) -- refuse now, after a465+ // (`decode.rs::apply_loop_restoration`) -- no more refusal here,
466- // successful structural decode, rather than before it.466+ // `uses_lr` frames now decode all the way to pixels.
467- if header.loop_restoration.uses_lr {
468- return Err(Error::unsupported(
469- "AV1 decode_stream",
470- "a frame with loop restoration enabled (the per-unit lr symbols are read but the Wiener/self-guided filters are not yet applied to pixels)",
471- ));
472- }
473 // Spec 7.20: `disable_frame_end_update_cdf` stores the frame's467 // Spec 7.20: `disable_frame_end_update_cdf` stores the frame's
474 // *initial* table into the slots it refreshes, not the adapted468 // *initial* table into the slots it refreshes, not the adapted
475 // end-of-tile one.469 // end-of-tile one.
@@ -4782,33 +4776,34 @@ mod tests {
4782 );4776 );
4783 let stream = out.stdout;4777 let stream = out.stdout;
4784 match decode_stream(&stream) {4778 match decode_stream(&stream) {
4785- Ok(_) => {4779+ Ok(pics) => {
4786- // aomenc's own RD chose `RESTORE_NONE` on every plane this4780+ // r4: the pixel filters are wired -- every `uses_lr`
4787- // attempt -- a legitimately LR-free frame, not a gate4781+ // frame must now decode Ok AND match an independent
4788- // failure (see the cq-level comment above: not every4782+ // decoder pixel-exact, not just refuse cleanly.
4789- // attempt lands `uses_lr=true`).4783+ let reference = ffmpeg_decode_sequence(&stream, width, height, pics.len());
4790- continue;4784+ for (i, (pic, refpic)) in pics.iter().zip(reference.iter()).enumerate() {
4785+ assert_eq!(pic.y, refpic.y, "{NAME}: luma mismatch (seed {seed} frame {i})");
4786+ assert_eq!(pic.u, refpic.u, "{NAME}: U mismatch (seed {seed} frame {i})");
4787+ assert_eq!(pic.v, refpic.v, "{NAME}: V mismatch (seed {seed} frame {i})");
4788+ }
4789+ lr_refusals += 1; // reused below as "attempts that actually exercised LR pixels"
4791 }4790 }
4792 Err(e) => {4791 Err(e) => {
4793 let msg = e.to_string();4792 let msg = e.to_string();
4794- assert!(4793+ other_refusals.push(format!("seed {seed}: {msg}"));
4795- msg.contains("unsupported"),
4796- "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
4797- );
4798- if msg.contains("loop restoration enabled") {
4799- lr_refusals += 1;
4800- } else {
4801- other_refusals.push(format!("seed {seed}: {msg}"));
4802- }
4803 }4794 }
4804 }4795 }
4805 }4796 }
4806 assert!(4797 assert!(
4807- lr_refusals > 0,4798+ other_refusals.is_empty(),
4808- "{NAME}: the LR refusal never fired ({} attempts, other refusals:\n{})",4799+ "{NAME}: {} attempts failed outright instead of decoding:\n{}",
4809- n_attempts,4800+ other_refusals.len(),
4810 other_refusals.join("\n")4801 other_refusals.join("\n")
4811 );4802 );
4803+ assert!(
4804+ lr_refusals > 0,
4805+ "{NAME}: no attempt ever decoded pixel-exact ({n_attempts} attempts)"
4806+ );
4812 // Any real (non-`RESTORE_NONE`) filter kind is acceptable proof --4807 // Any real (non-`RESTORE_NONE`) filter kind is acceptable proof --
4813 // aomenc's RD picks the frame-level `restoration_type` itself (not4808 // aomenc's RD picks the frame-level `restoration_type` itself (not
4814 // always `Switchable`; observed `Sgrproj` live at cq-level=15 for4809 // always `Switchable`; observed `Sgrproj` live at cq-level=15 for