forge
Explore
Log in

Don't you dare go Hollow

lane-av1422grain: film grain synthesis is per-axis, not 4:2:0-shaped

Browse files at this commit

55a71875bcc403be8d7b00095f39acf2883dff9bAhmet Kaan GümüşParent: f3a29d1
MEASUREMENT first: aomenc really does emit 4:2:2 film grain, so this is a
live arm, not a latent one. `aomenc --profile=2 --film-grain-test=5` over a
`yuv422p` source produces a frame header carrying `subsampling_x = 1,
subsampling_y = 0` with a full point set (read back with `ffprobe
-export_side_data +film_grain`: seed, ar_coeff_lag 3, scaling_shift 11). The
same is true at 4:4:4 under profile 1. Before this change the module grained
the TOP HALF of a 4:2:2 chroma plane with a 4:2:0 row map and a 2x2 avgLuma
quad -- no panic, no counter, no refusal, just a different picture.

Every chroma-side constant and extent is now the C's expression, per-axis
(`grain_synthesis.c`): the subblock and grain-block template
(`:1018-1035`), the `avgLuma` tap, which is the
`(chroma_subsamp_y + 1) x (chroma_subsamp_x + 1)` luma sample set -- a 2x2
quad at 4:2:0, a horizontal PAIR at 4:2:2, the sample itself at 4:4:4
(`:554-565`); the block placement offsets (`:1091-1094`); the chroma origin
and the `half_h << (1 - ss_y)` by `half_w << (1 - ss_x)` block (`:680-681`,
`:1129-1132`); the chroma stride (`:1461`); the line and column buffers
(`:392-414`); and all four chroma `copy_area`/`hor_boundary_overlap` extents.

Two traps the port walks into, both recorded at the site:

* The block size is `16 << (1 - ss)`, NOT `chroma_subblock_size << (1 - ss)`.
  They agree at 4:2:0 and diverge wherever `chroma_subsamp == 0`, because the
  half extents `add_noise_to_block` is handed are LUMA ones (`:1254-1255`).
* `copy_area(cb_col_buf + (chroma_subblock_size_y << (1 - ss_x)), ...)` is a
  FLAT element offset in the C, not a row index. Passing it as a row index
  multiplies it by the stride a second time and reads past the buffer.

The `chroma_noise_row_scalar` reference grew a `pair` argument because
`add_noise_to_block`'s luma operand differs by axis too: a horizontal pair at
`ss_x == 1` (4:2:0 and 4:2:2 alike -- only the row step changes) and the bare
luma sample at `ss_x == 0` (`:683-691`).

CONTROLS UNCHANGED. The existing 4:2:0 coverage is untouched and still
byte-exact against ffmpeg: `a_real_aomenc_stream_with_film_grain_decodes_pixel_exact`
(8-bit), `a_real_aomenc_10bit_film_grain_stream_decodes_pixel_exact`,
`a_real_aomenc_12bit_film_grain_stream_decodes_pixel_exact`,
`real_aomenc_film_grain_streams_decode_pixel_exact`, plus both SIMD-vs-scalar
pins. `untouched_planes_and_ragged_tail_come_back_clean` and
`simd_matches_scalar_*` are unaffected.

`ragged_overlap_tail_matches_spec_reference` was a 4:2:0-only transcription and
is now driven over all three formats, so 4:2:2 and 4:4:4 have coverage for
the first time. It also gained the assertion the old geometry could not make:
the LAST chroma row must come back grained -- at 4:2:2 the plane is `height`
rows tall and the old `nrows = height / 2` walk left the bottom half raw.
crates/ec-av1/src/film_grain.rsmodified+784 -261
@@ -1,9 +1,18 @@
11 //! AV1 film grain synthesis (spec 7.18.3), ported bit-exact from libaom's
22 //! `av1/decoder/grain_synthesis.c` (`add_film_grain_run` and its helpers),
3-//! specialized to this crate's only picture shape: 4:2:0 planar
4-//! (`chroma_subsamp_x = chroma_subsamp_y = 1` throughout, which is why every
5-//! `<< (1 - subsamp)` in the reference collapses to a no-op and every
6-//! `>> subsamp` collapses to `>> 1` below).
3+//! lane-av1422grain: this module USED to be specialised to 4:2:0 -- the
4+//! chroma subblock, the chroma grain-block template, the chroma row map, the
5+//! `avgLuma` tap, the line/column buffers and the chroma stride were all
6+//! written for `subsampling_x == subsampling_y == 1`. It is now per-axis,
7+//! matching the C, which threads `chroma_subsamp_y`/`chroma_subsamp_x`
8+//! through every one of those sites (`grain_synthesis.c:1018-1035`,
9+//! `:1069-1078`, `:1091-1094`, `:1129-1132`, `:554-565`, `:680-691`).
10+//!
11+//! The MEASUREMENT that makes this a live arm rather than a latent one:
12+//! `aomenc` really does emit 4:2:2 film grain (and 4:4:4, profile 1).
13+//! `aomenc --profile=2 --film-grain-test=5` over a `yuv422p` source produces
14+//! a frame header carrying `subsampling_x = 1, subsampling_y = 0` and a full
15+//! point set (read back with `ffprobe -export_side_data +film_grain`).
716 //!
817 //! Grain is synthesized only into the picture handed back to the caller for
918 //! *output* -- the picture stored as a reference for later inter prediction
@@ -36,19 +45,66 @@ const BOTTOM_PAD: i32 = 0;
3645 const AR_PADDING: i32 = 3;
3746
3847 const LUMA_SUBBLOCK: i32 = 32;
39-const CHROMA_SUBBLOCK: i32 = 16; // LUMA_SUBBLOCK >> subsampling (always 1 here)
4048
41-// 73 x 82, and 38 x 44 for chroma -- the sizes the mission's own recon named.
49+/// lane-av1422grain: the frame's `chroma_subsamp_x`/`chroma_subsamp_y`
50+/// (spec 5.5.2, parsed by `ec-av1-syntax`, published into `FrameCtx` by
51+/// `decode::set_subsampling`), as libaom's `add_film_grain_run` takes them.
52+/// Every chroma-side constant and extent in this module is one of the
53+/// methods below, which are the C's expressions verbatim.
54+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
55+pub(crate) struct Ss {
56+ pub x: i32,
57+ pub y: i32,
58+}
59+
60+impl Ss {
61+ /// The sequence header's pair, read out of `FrameCtx`.
62+ pub(crate) fn read(fctx: &crate::decode::FrameCtx) -> Ss {
63+ Ss {
64+ x: crate::decode::ss_x(fctx) as i32,
65+ y: crate::decode::ss_y(fctx) as i32,
66+ }
67+ }
68+
69+ /// libaom's `2 >> chroma_subsamp_x` / `2 >> chroma_subsamp_y`.
70+ #[inline]
71+ fn two_x(self) -> i32 {
72+ 2 >> self.x
73+ }
74+ #[inline]
75+ fn two_y(self) -> i32 {
76+ 2 >> self.y
77+ }
78+ /// `chroma_subblock_size_x` (`grain_synthesis.c:1019`).
79+ #[inline]
80+ fn csub_x(self) -> i32 {
81+ LUMA_SUBBLOCK >> self.x
82+ }
83+ /// `chroma_subblock_size_y` (`grain_synthesis.c:1018`).
84+ #[inline]
85+ fn csub_y(self) -> i32 {
86+ LUMA_SUBBLOCK >> self.y
87+ }
88+ /// `chroma_block_size_x` (`grain_synthesis.c:1033-1035`).
89+ fn cblock_w(self) -> i32 {
90+ LEFT_PAD
91+ + self.two_x() * AR_PADDING
92+ + self.csub_x() * 2
93+ + self.two_x() * AR_PADDING
94+ + RIGHT_PAD
95+ }
96+ /// `chroma_block_size_y` (`grain_synthesis.c:1031-1032`).
97+ fn cblock_h(self) -> i32 {
98+ TOP_PAD + self.two_y() * AR_PADDING + self.csub_y() * 2 + BOTTOM_PAD
99+ }
100+}
101+
102+// 73 x 82 for luma (`grain_synthesis.c:1027-1030`); the chroma template is
103+// per-axis and lives in `Ss::cblock_h`/`Ss::cblock_w` (38 x 44 at 4:2:0,
104+// 73 x 44 at 4:2:2, 73 x 82 at 4:4:4).
42105 const LUMA_BLOCK_H: i32 = TOP_PAD + 2 * AR_PADDING + LUMA_SUBBLOCK * 2 + BOTTOM_PAD;
43106 const LUMA_BLOCK_W: i32 =
44107 LEFT_PAD + 2 * AR_PADDING + LUMA_SUBBLOCK * 2 + 2 * AR_PADDING + RIGHT_PAD;
45-const CHROMA_BLOCK_H: i32 = TOP_PAD + AR_PADDING + CHROMA_SUBBLOCK * 2 + BOTTOM_PAD;
46-const CHROMA_BLOCK_W: i32 = LEFT_PAD + AR_PADDING + CHROMA_SUBBLOCK * 2 + AR_PADDING + RIGHT_PAD;
47-
48- /// `params->bit_depth` of the picture currently being grained. libaom
49- /// keeps `grain_min`/`grain_max` as file statics set once per
50- /// `av1_add_film_grain_run` (`grain_synthesis.c:1041-1045`); this mirrors
51- /// that rather than threading a parameter through every helper.
52108
53109 /// `params->bit_depth` for the [`apply_grain`] call in progress.
54110 fn grain_bit_depth(fctx: &crate::decode::FrameCtx) -> u32 {
@@ -134,7 +190,8 @@ fn build_pred_pos(lag: i32, has_luma_avg: bool) -> Vec<(i32, i32, i32)> {
134190 fn generate_luma_grain_block(
135191 fg: &FilmGrainParams,
136192 pred_pos: &[(i32, i32, i32)],
137- rng: &mut Rng, fctx: &crate::decode::FrameCtx,
193+ rng: &mut Rng,
194+ fctx: &crate::decode::FrameCtx,
138195 ) -> Vec<i32> {
139196 let (grain_min, grain_max) = grain_range(fctx);
140197 let mut block = vec![0i32; (LUMA_BLOCK_H * LUMA_BLOCK_W) as usize];
@@ -166,16 +223,27 @@ fn generate_luma_grain_block(
166223 block
167224 }
168225
169-/// `generate_chroma_grain_blocks` (spec 7.18.3.3), returning `(cb, cr)`.
226+/// `generate_chroma_grain_blocks` (spec 7.18.3.3), returning
227+/// `(cb, cr, chroma_grain_stride)`.
228+/// lane-av1422grain: the template's own size and its `avgLuma` tap are
229+/// per-axis, as the C (`grain_synthesis.c:496-589`): the block is
230+/// `chroma_block_size_y x chroma_block_size_x` and the luma average covers
231+/// the `(chroma_subsamp_y + 1) x (chroma_subsamp_x + 1)` luma samples that
232+/// map onto the chroma sample -- a 2x2 quad at 4:2:0, a horizontal PAIR at
233+/// 4:2:2, the single sample itself at 4:4:4.
170234 fn generate_chroma_grain_blocks(
171235 fg: &FilmGrainParams,
172236 pred_pos: &[(i32, i32, i32)],
173237 luma_block: &[i32],
174- seed: u16, fctx: &crate::decode::FrameCtx,
175-) -> (Vec<i32>, Vec<i32>) {
238+ seed: u16,
239+ ss: Ss,
240+ fctx: &crate::decode::FrameCtx,
241+) -> (Vec<i32>, Vec<i32>, i32) {
176242 let (grain_min, grain_max) = grain_range(fctx);
177- let mut cb = vec![0i32; (CHROMA_BLOCK_H * CHROMA_BLOCK_W) as usize];
178- let mut cr = vec![0i32; (CHROMA_BLOCK_H * CHROMA_BLOCK_W) as usize];
243+ let cbh = ss.cblock_h();
244+ let cbw = ss.cblock_w();
245+ let mut cb = vec![0i32; (cbh * cbw) as usize];
246+ let mut cr = vec![0i32; (cbh * cbw) as usize];
179247 let gauss_sec_shift = 12 - grain_bit_depth(fctx) as i32 + fg.grain_scale_shift as i32;
180248 let ar_coeff_shift = fg.ar_coeff_shift_minus_6 as i32 + 6;
181249 let rounding_offset = 1i32 << (ar_coeff_shift - 1);
@@ -185,12 +253,12 @@ fn generate_chroma_grain_blocks(
185253
186254 if apply_cb {
187255 let mut rng = Rng::line(7 << 5, seed);
188- for i in 0..CHROMA_BLOCK_H {
189- for j in 0..CHROMA_BLOCK_W {
256+ for i in 0..cbh {
257+ for j in 0..cbw {
190258 let g = GAUSSIAN_SEQUENCE[rng.get(GAUSS_BITS) as usize];
191259 set_at(
192260 &mut cb,
193- CHROMA_BLOCK_W,
261+ cbw,
194262 i,
195263 j,
196264 (g + ((1 << gauss_sec_shift) >> 1)) >> gauss_sec_shift,
@@ -200,12 +268,12 @@ fn generate_chroma_grain_blocks(
200268 }
201269 if apply_cr {
202270 let mut rng = Rng::line(11 << 5, seed);
203- for i in 0..CHROMA_BLOCK_H {
204- for j in 0..CHROMA_BLOCK_W {
271+ for i in 0..cbh {
272+ for j in 0..cbw {
205273 let g = GAUSSIAN_SEQUENCE[rng.get(GAUSS_BITS) as usize];
206274 set_at(
207275 &mut cr,
208- CHROMA_BLOCK_W,
276+ cbw,
209277 i,
210278 j,
211279 (g + ((1 << gauss_sec_shift) >> 1)) >> gauss_sec_shift,
@@ -214,47 +282,47 @@ fn generate_chroma_grain_blocks(
214282 }
215283 }
216284
217- for i in TOP_PAD..CHROMA_BLOCK_H - BOTTOM_PAD {
218- for j in LEFT_PAD..CHROMA_BLOCK_W - RIGHT_PAD {
285+ for i in TOP_PAD..cbh - BOTTOM_PAD {
286+ for j in LEFT_PAD..cbw - RIGHT_PAD {
219287 let mut wsum_cb = 0i32;
220288 let mut wsum_cr = 0i32;
221289 for (idx, &(dy, dx, kind)) in pred_pos.iter().enumerate() {
222290 if kind == 0 {
223- wsum_cb +=
224- fg.ar_coeffs_cb[idx] as i32 * at(&cb, CHROMA_BLOCK_W, i + dy, j + dx);
225- wsum_cr +=
226- fg.ar_coeffs_cr[idx] as i32 * at(&cr, CHROMA_BLOCK_W, i + dy, j + dx);
291+ wsum_cb += fg.ar_coeffs_cb[idx] as i32 * at(&cb, cbw, i + dy, j + dx);
292+ wsum_cr += fg.ar_coeffs_cr[idx] as i32 * at(&cr, cbw, i + dy, j + dx);
227293 } else {
228- // `avgLuma` (spec 7.18.3.3): subsampling_x = subsampling_y = 1
229- // always here, so the 2x2 luma quad is exactly one 4:2:0 cell.
230- let luma_y = ((i - TOP_PAD) << 1) + TOP_PAD;
231- let luma_x = ((j - LEFT_PAD) << 1) + LEFT_PAD;
294+ // `avgLuma` (spec 7.18.3.3; `grain_synthesis.c:554-565`):
295+ // the luma origin is the chroma origin scaled back by each
296+ // axis' subsampling, and the average divides by the
297+ // per-axis sample count with the C's rounding term
298+ // `((1 << (ss_y + ss_x)) >> 1)`.
299+ let luma_y = ((i - TOP_PAD) << ss.y) + TOP_PAD;
300+ let luma_x = ((j - LEFT_PAD) << ss.x) + LEFT_PAD;
232301 let mut av = 0i32;
233- for k in luma_y..luma_y + 2 {
234- for l in luma_x..luma_x + 2 {
302+ for k in luma_y..luma_y + ss.y + 1 {
303+ for l in luma_x..luma_x + ss.x + 1 {
235304 av += at(luma_block, LUMA_BLOCK_W, k, l);
236305 }
237306 }
238- av = (av + 2) >> 2;
307+ let shift = ss.y + ss.x;
308+ av = (av + ((1 << shift) >> 1)) >> shift;
239309 wsum_cb += fg.ar_coeffs_cb[idx] as i32 * av;
240310 wsum_cr += fg.ar_coeffs_cr[idx] as i32 * av;
241311 }
242312 }
243313 if apply_cb {
244- let v = (at(&cb, CHROMA_BLOCK_W, i, j)
245- + ((wsum_cb + rounding_offset) >> ar_coeff_shift))
314+ let v = (at(&cb, cbw, i, j) + ((wsum_cb + rounding_offset) >> ar_coeff_shift))
246315 .clamp(grain_min, grain_max);
247- set_at(&mut cb, CHROMA_BLOCK_W, i, j, v);
316+ set_at(&mut cb, cbw, i, j, v);
248317 }
249318 if apply_cr {
250- let v = (at(&cr, CHROMA_BLOCK_W, i, j)
251- + ((wsum_cr + rounding_offset) >> ar_coeff_shift))
319+ let v = (at(&cr, cbw, i, j) + ((wsum_cr + rounding_offset) >> ar_coeff_shift))
252320 .clamp(grain_min, grain_max);
253- set_at(&mut cr, CHROMA_BLOCK_W, i, j, v);
321+ set_at(&mut cr, cbw, i, j, v);
254322 }
255323 }
256324 }
257- (cb, cr)
325+ (cb, cr, cbw)
258326 }
259327
260328 /// `init_scaling_function` (spec 7.18.3.2, piecewise-linear scaling LUT).
@@ -291,8 +359,8 @@ fn scale_lut(lut: &[i32; 256], index: i32, bit_depth: u32) -> i32 {
291359 if shift == 0 || x == 255 {
292360 lut[x]
293361 } else {
294- lut[x] + (((lut[x + 1] - lut[x]) * (index & ((1 << shift) - 1)) + (1 << (shift - 1)))
295- >> shift)
362+ lut[x]
363+ + (((lut[x + 1] - lut[x]) * (index & ((1 << shift) - 1)) + (1 << (shift - 1))) >> shift)
296364 }
297365 }
298366
@@ -310,15 +378,21 @@ fn expand_scaling_lut(lut: &[i32; 256], bit_depth: u32) -> Vec<i32> {
310378 .collect()
311379 }
312380
313-/// `add_noise_to_block` (spec 7.18.3.5), 4:2:0 only. `(py0, px0)` is
314-/// the luma-plane pixel origin; the matching chroma origin is `(py0/2,
315-/// px0/2)`. Grain is read from `(grain, stride, row0, col0)` triples so the
316-/// same function serves both the raw 82x73/44x38 templates and the small
317-/// blended col/line buffers below.
381+/// `add_noise_to_block` (spec 7.18.3.5). `(py0, px0)` is the luma-plane
382+/// pixel origin; the matching chroma origin is `(py0 >> ss_y, px0 >>
383+/// ss_x)` -- `(py0/2, px0/2)` only at 4:2:0. Grain is read from
384+/// `(grain, stride, row0, col0)` triples so the same function serves both
385+/// the raw luma/chroma templates and the small blended col/line buffers
386+/// below.
387+///
388+/// lane-av1422grain: the chroma half-extents are per-axis, as the C: the
389+/// chroma loops run `half_h << (1 - ss_y)` rows by `half_w << (1 - ss_x)`
390+/// columns (`grain_synthesis.c:680-681`).
318391 #[allow(clippy::too_many_arguments)]
319392 fn add_noise_to_block(
320393 fg: &FilmGrainParams,
321394 mc_identity: bool,
395+ ss: Ss,
322396 scaling_y: &[i32],
323397 scaling_cb: &[i32],
324398 scaling_cr: &[i32],
@@ -335,7 +409,8 @@ fn add_noise_to_block(
335409 cg_row0: i32,
336410 cg_col0: i32,
337411 half_h: i32,
338- half_w: i32, fctx: &crate::decode::FrameCtx,
412+ half_w: i32,
413+ fctx: &crate::decode::FrameCtx,
339414 ) {
340415 // spec 7.18.3.5 runs the block's noise loops `for i in 0..h`/`for j in
341416 // 0..w`, so a block with no rows (or no columns) writes nothing. The
@@ -348,7 +423,7 @@ fn add_noise_to_block(
348423 return;
349424 }
350425 let y_stride = picture.width as i32;
351- let c_stride = (picture.width / 2) as i32;
426+ let c_stride = (picture.width >> ss.x) as i32;
352427 let scaling_shift = fg.grain_scaling_minus_8 as i32 + 8;
353428 let bit_depth = grain_bit_depth(fctx);
354429 let bd_shift = bit_depth - 8;
@@ -394,24 +469,51 @@ fn add_noise_to_block(
394469 (0, index_max, 0, index_max)
395470 };
396471
397- let cy0 = py0 / 2;
398- let cx0 = px0 / 2;
472+ // `cb + ((y + i) << (1 - chroma_subsamp_y)) * chroma_stride + ((x + j) <<
473+ // (1 - chroma_subsamp_x))` (`grain_synthesis.c:1129-1130`), with
474+ // `py0 == (y + i) << 1`: per-axis, and equal to `/ 2` only at 4:2:0.
475+ let cy0 = py0 >> ss.y;
476+ let cx0 = px0 >> ss.x;
399477 if apply_cb || apply_cr {
400- // lane-perf4: one row of each operand at a time. The 4:2:0 luma
401- // average (spec 7.18.3.5) reads a horizontally adjacent PAIR of the
402- // block's own luma row, so `chunks_exact(2)` walks exactly the pairs
403- // the per-sample `(ly * y_stride + lx)` form used to re-derive, and
404- // the U/V/grain rows advance in lockstep with it -- same integers,
405- // same rounding, no per-sample index arithmetic or bounds check.
406- let cw = half_w as usize;
478+ // lane-perf4: one row of each operand at a time. The luma average
479+ // (spec 7.18.3.5) reads a horizontally adjacent PAIR of the block's
480+ // own luma row at `ss_x == 1` (4:2:0 and 4:2:2 alike), so
481+ // `chunks_exact(2)` walks exactly the pairs the per-sample
482+ // `(ly * y_stride + lx)` form used to re-derive, and the U/V/grain rows
483+ // advance in lockstep with it -- same integers, same rounding, no
484+ // per-sample index arithmetic or bounds check. At `ss_x == 0` (4:4:4)
485+ // the C reads the luma sample itself and the kernel takes its scalar
486+ // `pair == false` arm.
487+ //
488+ // The chroma block is `half_h << (1 - ss_y)` rows by
489+ // `half_w << (1 - ss_x)` columns, and the luma row a chroma row
490+ // averages is `1 << ss_y` luma rows down.
491+ let pair = ss.x == 1;
492+ let cw = (half_w << (1 - ss.x)) as usize;
493+ let ch = (half_h << (1 - ss.y)) as usize;
494+ // The luma ROW a chroma row averages is `i << ss_y`
495+ // (`grain_synthesis.c:684`), so consecutive chroma rows step
496+ // `1 << ss_y` luma rows -- 2 at 4:2:0 and 4:2:2, 1 at 4:4:4.
497+ let lrow_step = 1usize << ss.y;
407498 // U and V are distinct fields, so a disjoint borrow of each is
408499 // needed alongside the immutable read of Y.
409- let Picture { y: ref luma_plane, u: ref mut u_plane, v: ref mut v_plane, .. } = *picture;
500+ let Picture {
501+ y: ref luma_plane,
502+ u: ref mut u_plane,
503+ v: ref mut v_plane,
504+ ..
505+ } = *picture;
410506 let lrow0 = (py0 * y_stride + px0) as usize;
411507 let crow0 = (cy0 * c_stride + cx0) as usize;
412508 let grow0 = (cg_row0 * cg_stride + cg_col0) as usize;
413509 let luma = &luma_plane[lrow0..];
414- let params = ChromaNoise { index_max, rounding_offset, scaling_shift, min_chroma, max_chroma };
510+ let params = ChromaNoise {
511+ index_max,
512+ rounding_offset,
513+ scaling_shift,
514+ min_chroma,
515+ max_chroma,
516+ };
415517 // lane-grain: the whole block in one call, so the kernel's AVX2
416518 // prologue is paid once per block instead of once per 15-sample row.
417519 if apply_cb {
@@ -419,16 +521,17 @@ fn add_noise_to_block(
419521 &mut u_plane[crow0..],
420522 c_stride as usize,
421523 luma,
422- 2 * y_stride as usize,
524+ lrow_step * y_stride as usize,
423525 &cb_grain[grow0..],
424526 cg_stride as usize,
425- half_h as usize,
527+ ch,
426528 cw,
427529 scaling_cb,
428530 cb_luma_mult,
429531 cb_mult,
430532 cb_offset,
431533 params,
534+ pair,
432535 );
433536 }
434537 if apply_cr {
@@ -436,16 +539,17 @@ fn add_noise_to_block(
436539 &mut v_plane[crow0..],
437540 c_stride as usize,
438541 luma,
439- 2 * y_stride as usize,
542+ lrow_step * y_stride as usize,
440543 &cr_grain[grow0..],
441544 cg_stride as usize,
442- half_h as usize,
545+ ch,
443546 cw,
444547 scaling_cr,
445548 cr_luma_mult,
446549 cr_mult,
447550 cr_offset,
448551 params,
552+ pair,
449553 );
450554 }
451555 }
@@ -489,7 +593,17 @@ fn luma_noise_row(
489593 ) {
490594 let n = pixels.len().min(grain.len());
491595 luma_noise_rows(
492- pixels, n, grain, n, 1, n, scaling, rounding_offset, scaling_shift, min_luma, max_luma,
596+ pixels,
597+ n,
598+ grain,
599+ n,
600+ 1,
601+ n,
602+ scaling,
603+ rounding_offset,
604+ scaling_shift,
605+ min_luma,
606+ max_luma,
493607 );
494608 }
495609
@@ -524,8 +638,17 @@ fn luma_noise_rows(
524638 // sliced, and gathers only in-range LUT entries.
525639 unsafe {
526640 simd::luma_noise_rows_avx2(
527- pixels, p_stride, grain, g_stride, rows, n, scaling, rounding_offset,
528- scaling_shift, min_luma, max_luma,
641+ pixels,
642+ p_stride,
643+ grain,
644+ g_stride,
645+ rows,
646+ n,
647+ scaling,
648+ rounding_offset,
649+ scaling_shift,
650+ min_luma,
651+ max_luma,
529652 )
530653 };
531654 return;
@@ -554,9 +677,21 @@ struct ChromaNoise {
554677 max_chroma: i32,
555678 }
556679
557-/// One chroma row of spec 7.18.3.5's `add_noise_to_block`: `luma` is the
558-/// block's own luma row pair-averaged 4:2:0 (`luma.len() == 2 *
559-/// chroma.len()`), `grain` and `scaling` are the plane's own.
680+/// One chroma row of spec 7.18.3.5's `add_noise_to_block`.
681+///
682+/// lane-av1422grain: the luma operand is per-axis, as the C
683+/// (`grain_synthesis.c:680-691`). The chroma loop runs
684+/// `half_luma_height << (1 - ss_y)` rows by `half_luma_width << (1 - ss_x)`
685+/// columns, and the luma sample a chroma sample averages is:
686+///
687+/// * `ss_x == 1` -- a horizontal PAIR at luma row `i << ss_y`, columns
688+/// `(j << ss_x)` and `(j << ss_x) + 1`, rounded `(a + b + 1) >> 1`. True at
689+/// BOTH 4:2:0 and 4:2:2; only the row step differs, and that is `l_stride`.
690+/// * `ss_x == 0` (4:4:4) -- the single luma sample itself, no pair and no
691+/// `+ 1`. `luma.len() == chroma.len()` and `l_stride` is one luma row per
692+/// chroma row.
693+///
694+/// `pair` selects which; it is `ss_x == 1`.
560695 ///
561696 /// lane-perf9: AVX2 does 8 chroma samples at a time, the luma pair sum being
562697 /// one `vpmaddwd` against ones; every other CPU runs the scalar loop, which
@@ -574,14 +709,31 @@ fn chroma_noise_row(
574709 offset: i32,
575710 p: ChromaNoise,
576711 ) {
577- let n = chroma.len().min(grain.len()).min(luma.len() / 2);
712+ // The 4:2:0/4:2:2 shape the existing SIMD kernel is written for: one
713+ // horizontal luma pair per chroma sample, one luma row per chroma row.
714+ let per = 2usize;
715+ let n = chroma.len().min(grain.len()).min(luma.len() / per);
578716 chroma_noise_rows(
579- chroma, n, luma, 2 * n, grain, n, 1, n, scaling, luma_mult, mult, offset, p,
717+ chroma,
718+ n,
719+ luma,
720+ 2 * n,
721+ grain,
722+ n,
723+ 1,
724+ n,
725+ scaling,
726+ luma_mult,
727+ mult,
728+ offset,
729+ p,
730+ true,
580731 );
581732 }
582733
583734 /// [`chroma_noise_row`] over `rows` consecutive chroma rows of a block; see
584735 /// [`luma_noise_rows`] for why the row loop lives inside the kernel.
736+/// `pair` is `ss_x == 1`; see [`chroma_noise_row`] for the two luma shapes.
585737 #[allow(unsafe_code)]
586738 #[allow(clippy::too_many_arguments)]
587739 fn chroma_noise_rows(
@@ -598,9 +750,10 @@ fn chroma_noise_rows(
598750 mult: i32,
599751 offset: i32,
600752 p: ChromaNoise,
753+ pair: bool,
601754 ) {
602755 #[cfg(target_arch = "x86_64")]
603- if n >= 4 && crate::mc::simd_level() == crate::mc::SimdLevel::Avx2 {
756+ if pair && n >= 4 && crate::mc::simd_level() == crate::mc::SimdLevel::Avx2 {
604757 // SAFETY: reached only when the CPU reports avx2; the kernel reads
605758 // `luma`/`grain`/`chroma` only inside the window the caller sliced,
606759 // and gathers only in-range LUT entries.
@@ -612,16 +765,18 @@ fn chroma_noise_rows(
612765 };
613766 return;
614767 }
768+ let lrow = if pair { 2 * n } else { n };
615769 for r in 0..rows {
616770 chroma_noise_row_scalar(
617771 &mut chroma[r * c_stride..r * c_stride + n],
618- &luma[r * l_stride..r * l_stride + 2 * n],
772+ &luma[r * l_stride..r * l_stride + lrow],
619773 &grain[r * g_stride..r * g_stride + n],
620774 scaling,
621775 luma_mult,
622776 mult,
623777 offset,
624778 p,
779+ pair,
625780 );
626781 }
627782 }
@@ -637,13 +792,26 @@ fn chroma_noise_row_scalar(
637792 mult: i32,
638793 offset: i32,
639794 p: ChromaNoise,
795+ pair: bool,
640796 ) {
641- for ((c, lpair), &g) in chroma.iter_mut().zip(luma.chunks_exact(2)).zip(grain) {
642- let average_luma = (lpair[0] as i32 + lpair[1] as i32 + 1) >> 1;
643- let scaled =
644- (((average_luma * luma_mult + mult * *c as i32) >> 6) + offset).clamp(0, p.index_max);
645- let delta = (scaling[scaled as usize] * g + p.rounding_offset) >> p.scaling_shift;
646- *c = ((*c as i32 + delta).clamp(p.min_chroma, p.max_chroma)) as u16;
797+ if pair {
798+ for ((c, lpair), &g) in chroma.iter_mut().zip(luma.chunks_exact(2)).zip(grain) {
799+ let average_luma = (lpair[0] as i32 + lpair[1] as i32 + 1) >> 1;
800+ let scaled = (((average_luma * luma_mult + mult * *c as i32) >> 6) + offset)
801+ .clamp(0, p.index_max);
802+ let delta = (scaling[scaled as usize] * g + p.rounding_offset) >> p.scaling_shift;
803+ *c = ((*c as i32 + delta).clamp(p.min_chroma, p.max_chroma)) as u16;
804+ }
805+ } else {
806+ // 4:4:4: `average_luma = luma[(i << ss_y) * luma_stride + j]` -- the
807+ // luma sample itself (`grain_synthesis.c:691`).
808+ for ((c, &l), &g) in chroma.iter_mut().zip(luma).zip(grain) {
809+ let average_luma = l as i32;
810+ let scaled = (((average_luma * luma_mult + mult * *c as i32) >> 6) + offset)
811+ .clamp(0, p.index_max);
812+ let delta = (scaling[scaled as usize] * g + p.rounding_offset) >> p.scaling_shift;
813+ *c = ((*c as i32 + delta).clamp(p.min_chroma, p.max_chroma)) as u16;
814+ }
647815 }
648816 }
649817
@@ -695,7 +863,17 @@ mod simd {
695863 ) {
696864 let n = pixels.len().min(grain.len());
697865 luma_noise_rows_avx2(
698- pixels, n, grain, n, 1, n, scaling, rounding_offset, scaling_shift, min_luma, max_luma,
866+ pixels,
867+ n,
868+ grain,
869+ n,
870+ 1,
871+ n,
872+ scaling,
873+ rounding_offset,
874+ scaling_shift,
875+ min_luma,
876+ max_luma,
699877 );
700878 }
701879
@@ -800,7 +978,19 @@ mod simd {
800978 ) {
801979 let n = chroma.len().min(grain.len()).min(luma.len() / 2);
802980 chroma_noise_rows_avx2(
803- chroma, n, luma, 2 * n, grain, n, 1, n, scaling, luma_mult, mult, offset, p,
981+ chroma,
982+ n,
983+ luma,
984+ 2 * n,
985+ grain,
986+ n,
987+ 1,
988+ n,
989+ scaling,
990+ luma_mult,
991+ mult,
992+ offset,
993+ p,
804994 );
805995 }
806996
@@ -886,8 +1076,10 @@ mod simd {
8861076 let avg = _mm_srai_epi32(_mm_add_epi32(pair_sum, one4), 1);
8871077 let c16 = _mm_loadl_epi64(cp.add(c).cast());
8881078 let c32 = _mm_cvtepu16_epi32(c16);
889- let mixed =
890- _mm_add_epi32(_mm_mullo_epi32(avg, vluma_mult4), _mm_mullo_epi32(c32, vmult4));
1079+ let mixed = _mm_add_epi32(
1080+ _mm_mullo_epi32(avg, vluma_mult4),
1081+ _mm_mullo_epi32(c32, vmult4),
1082+ );
8911083 let scaled = _mm_add_epi32(_mm_srai_epi32(mixed, 6), voffset4);
8921084 let clamped = _mm_max_epi32(_mm_min_epi32(scaled, vindex_max4), zero4);
8931085 let idx = _mm_min_epi32(clamped, last4);
@@ -910,6 +1102,7 @@ mod simd {
9101102 mult,
9111103 offset,
9121104 p,
1105+ true,
9131106 );
9141107 }
9151108 }
@@ -929,7 +1122,8 @@ fn ver_overlap_inplace(
9291122 right_row0: i32,
9301123 right_col0: i32,
9311124 width: i32,
932- height: i32, fctx: &crate::decode::FrameCtx,
1125+ height: i32,
1126+ fctx: &crate::decode::FrameCtx,
9331127 ) {
9341128 let (grain_min, grain_max) = grain_range(fctx);
9351129 for h in 0..height {
@@ -979,7 +1173,8 @@ fn hor_overlap_inplace(
9791173 bot_row0: i32,
9801174 bot_col0: i32,
9811175 width: i32,
982- height: i32, fctx: &crate::decode::FrameCtx,
1176+ height: i32,
1177+ fctx: &crate::decode::FrameCtx,
9831178 ) {
9841179 let (grain_min, grain_max) = grain_range(fctx);
9851180 if height == 1 {
@@ -1029,7 +1224,8 @@ fn copy_area(
10291224 src_row0: i32,
10301225 src_col0: i32,
10311226 width: i32,
1032- height: i32, fctx: &crate::decode::FrameCtx,
1227+ height: i32,
1228+ fctx: &crate::decode::FrameCtx,
10331229 ) {
10341230 let (_grain_min, _grain_max) = grain_range(fctx);
10351231 for h in 0..height {
@@ -1138,17 +1334,33 @@ pub(crate) fn apply_grain(
11381334 picture: &Picture,
11391335 fg: &FilmGrainParams,
11401336 mc_identity: bool,
1141- bit_depth: u32, fctx: &crate::decode::FrameCtx,
1337+ bit_depth: u32,
1338+ fctx: &crate::decode::FrameCtx,
11421339 ) -> Picture {
11431340 if !fg.apply_grain {
11441341 return picture.clone();
11451342 }
11461343 fctx.grain_bit_depth.with(|c| c.set(bit_depth));
11471344 hit!(GRAIN_HITS);
1345+ // lane-av1422grain: the chroma geometry is per-axis. `FrameCtx` already
1346+ // carries the sequence header's pair (`decode::set_subsampling`), and
1347+ // `apply_grain` runs inside the same frame context, so the chroma
1348+ // subblock, template, row map and stride all follow the header rather
1349+ // than a hardcoded 4:2:0.
1350+ let ss = Ss::read(fctx);
11481351 let width = picture.width as i32;
11491352 let height = picture.height as i32;
11501353 let y_stride = width;
1151- let c_stride = width / 2;
1354+ // `width >> chroma_subsamp_x`: `chroma_stride` is the U/V plane's own
1355+ // row length (`grain_synthesis.c:1461`).
1356+ let c_stride = width >> ss.x;
1357+ let csub_x = ss.csub_x();
1358+ let csub_y = ss.csub_y();
1359+ // The chroma plane is `c_stride x (height >> ss_y)` rows tall, so the
1360+ // number of block ROWS is unchanged by `ss_y` only if the walk is
1361+ // expressed in luma rows -- which is what the C does: `for (y = 0; y <
1362+ // height / 2; y += luma_subblock_size_y >> 1)` (`grain_synthesis.c:1069`).
1363+ // Each such block row covers `csub_y << (1 - ss_y)` chroma rows.
11521364
11531365 let lag = fg.ar_coeff_lag as i32;
11541366 let pred_luma = build_pred_pos(lag, false);
@@ -1156,8 +1368,8 @@ pub(crate) fn apply_grain(
11561368
11571369 let mut rng = Rng::raw(fg.grain_seed);
11581370 let luma_template = generate_luma_grain_block(fg, &pred_luma, &mut rng, fctx);
1159- let (cb_template, cr_template) =
1160- generate_chroma_grain_blocks(fg, &pred_chroma, &luma_template, fg.grain_seed, fctx);
1371+ let (cb_template, cr_template, cg_stride) =
1372+ generate_chroma_grain_blocks(fg, &pred_chroma, &luma_template, fg.grain_seed, ss, fctx);
11611373
11621374 let scaling_y = build_scaling_lut(
11631375 &fg.point_y_value,
@@ -1194,7 +1406,7 @@ pub(crate) fn apply_grain(
11941406 // lane-filt1: 32-pixel block ROWS are the parallel axis. A row's noise
11951407 // offsets come from `Rng::line(y * 2, grain_seed)` -- a function of the
11961408 // row and the frame seed alone -- and a row writes only luma rows
1197- // `y*2 .. y*2+31` (chroma `y .. y+15`), so rows are write-disjoint. The
1409+ // `y*2 >> ss_y .. +csub_y << (1 - ss_y)`), so rows are write-disjoint. The
11981410 // one carry ACROSS rows is `*_line_buf` (the row above's bottom lines,
11991411 // blended into this row's top lines when `overlap_flag`), and its final
12001412 // content is written by that row's own blocks out of the grain templates
@@ -1203,6 +1415,11 @@ pub(crate) fn apply_grain(
12031415 // to rebuild the line buffers, then codes its own rows exactly as the
12041416 // single-threaded walk does.
12051417 let row_step = LUMA_SUBBLOCK >> 1;
1418+ // lane-av1422grain: one luma block row spans `csub_y << (1 - ss_y)` chroma
1419+ // rows (16 at 4:2:0, 32 at 4:2:2 and at 4:4:4), and the chroma row a block
1420+ // row `y` starts at is `y * 2 >> ss_y`. At 4:2:0 both collapse to the old
1421+ // `row_step` / `y` this walk used.
1422+ let chroma_row = |y: usize| (2 * y) >> ss.y;
12061423 let nrows = ((height / 2).max(0) as usize).div_ceil(row_step as usize);
12071424 let gbands = crate::par::bands(nrows, crate::par::filter_threads());
12081425 // lane-grain2: the clean picture used to be cloned here, on the frame
@@ -1211,8 +1428,16 @@ pub(crate) fn apply_grain(
12111428 // walk. The bands own a partition of the plane rows, so each band copies
12121429 // its OWN rows out of the clean source and adds noise to them: the copy
12131430 // moves onto the filter pool and the destination never needs zeroing.
1214- let y_rows = if y_stride > 0 { picture.y.len() / y_stride as usize } else { 0 };
1215- let c_rows = if c_stride > 0 { picture.u.len() / c_stride as usize } else { 0 };
1431+ let y_rows = if y_stride > 0 {
1432+ picture.y.len() / y_stride as usize
1433+ } else {
1434+ 0
1435+ };
1436+ let c_rows = if c_stride > 0 {
1437+ picture.u.len() / c_stride as usize
1438+ } else {
1439+ 0
1440+ };
12161441 let banded = !gbands.is_empty() && y_stride > 0 && c_stride > 0;
12171442 let mut out = if banded {
12181443 Picture {
@@ -1240,23 +1465,44 @@ pub(crate) fn apply_grain(
12401465 // the rows the kernels then read back are still in this core's cache.
12411466 let ys = y_stride as usize;
12421467 let cs = c_stride as usize;
1243- let c_end = if b_hi == nrows { c_rows } else { (b_hi * row_step as usize).min(c_rows) };
1244- let l_end =
1245- if b_hi == nrows { y_rows } else { (2 * b_hi * row_step as usize).min(y_rows) };
1246- let mut ccur = (b_lo * row_step as usize).min(c_rows);
1468+ let c_end = if b_hi == nrows {
1469+ c_rows
1470+ } else {
1471+ chroma_row(b_hi * row_step as usize).min(c_rows)
1472+ };
1473+ let l_end = if b_hi == nrows {
1474+ y_rows
1475+ } else {
1476+ (2 * b_hi * row_step as usize).min(y_rows)
1477+ };
1478+ let mut ccur = chroma_row(b_lo * row_step as usize).min(c_rows);
12471479 let mut lcur = (2 * b_lo * row_step as usize).min(y_rows);
12481480 let y_lo = (b_lo * row_step as usize) as i32;
12491481 let y_hi = ((b_hi * row_step as usize) as i32).min(height / 2);
12501482 let y_first = if b_lo > 0 { y_lo - row_step } else { y_lo };
12511483 let mut y_line_buf = vec![0i32; (y_stride * 2).max(1) as usize];
1252- let mut cb_line_buf = vec![0i32; c_stride.max(1) as usize];
1253- let mut cr_line_buf = vec![0i32; c_stride.max(1) as usize];
1484+ // lane-av1422grain: the line and column buffers are per-axis, as the C's
1485+ // `init_arrays` (`grain_synthesis.c:392-414`): the chroma line buffer
1486+ // is `chroma_stride * (2 >> ss_y)` samples and the chroma column
1487+ // buffer is `(chroma_subblock_size_y + (2 >> ss_y)) * (2 >> ss_x)`.
1488+ let mut cb_line_buf = vec![0i32; (c_stride * ss.two_y()).max(1) as usize];
1489+ let mut cr_line_buf = vec![0i32; (c_stride * ss.two_y()).max(1) as usize];
12541490 let mut y_col_buf = vec![0i32; ((LUMA_SUBBLOCK + 2) * 2) as usize];
1255- let mut cb_col_buf = vec![0i32; (CHROMA_SUBBLOCK + 1) as usize];
1256- let mut cr_col_buf = vec![0i32; (CHROMA_SUBBLOCK + 1) as usize];
1491+ let cb_col_len = ((csub_y + ss.two_y()) * ss.two_x()).max(1) as usize;
1492+ let mut cb_col_buf = vec![0i32; cb_col_len];
1493+ let mut cr_col_buf = vec![0i32; cb_col_len];
1494+ // The assembled chroma block is `half_luma_height << (1 - ss_y)` rows
1495+ // by `half_luma_width << (1 - ss_x)` columns -- the block the C's
1496+ // `add_noise_to_block` walks (`grain_synthesis.c:680-681`). Note the
1497+ // half extents it is given are LUMA ones (`AOMMIN(32 >> 1, ...)`,
1498+ // `:1254-1255`), so the block size is `16 << (1 - ss)`, NOT
1499+ // `chroma_subblock_size << (1 - ss)`: the two differ wherever
1500+ // `chroma_subsamp == 0` (4:2:2 rows, 4:4:4 both axes).
1501+ let cblk_stride = ((LUMA_SUBBLOCK >> 1) << (1 - ss.x)) as usize;
1502+ let cblk_rows = ((LUMA_SUBBLOCK >> 1) << (1 - ss.y)) as usize;
12571503 let mut y_blk = vec![0i32; (LUMA_SUBBLOCK * LUMA_SUBBLOCK) as usize];
1258- let mut cb_blk = vec![0i32; (CHROMA_SUBBLOCK * CHROMA_SUBBLOCK) as usize];
1259- let mut cr_blk = vec![0i32; (CHROMA_SUBBLOCK * CHROMA_SUBBLOCK) as usize];
1504+ let mut cb_blk = vec![0i32; cblk_stride * cblk_rows];
1505+ let mut cr_blk = vec![0i32; cblk_stride * cblk_rows];
12601506
12611507 let mut y = y_first;
12621508 while y < y_hi {
@@ -1269,9 +1515,13 @@ pub(crate) fn apply_grain(
12691515 &mut lcur,
12701516 &mut ccur,
12711517 (2 * (y as usize + row_step as usize)).min(l_end),
1272- (y as usize + row_step as usize).min(c_end),
1518+ chroma_row(y as usize + row_step as usize).min(c_end),
12731519 );
12741520 let mut row_rng = Rng::line(y * 2, fg.grain_seed);
1521+ // `for (x = 0; x < width / 2; x += luma_subblock_size_x >> 1)`
1522+ // (`grain_synthesis.c:1075`): the COLUMN walk is in luma units at
1523+ // every subsampling, so `width / 2` is right as written and the
1524+ // chroma column follows from it per-axis.
12751525 let mut x = 0;
12761526 while x < width / 2 {
12771527 let raw = row_rng.get(8);
@@ -1280,8 +1530,11 @@ pub(crate) fn apply_grain(
12801530
12811531 let luma_off_y = LEFT_PAD + 2 * AR_PADDING + (offset_y << 1);
12821532 let luma_off_x = TOP_PAD + 2 * AR_PADDING + (offset_x << 1);
1283- let chroma_off_y = TOP_PAD + AR_PADDING + offset_y;
1284- let chroma_off_x = LEFT_PAD + AR_PADDING + offset_x;
1533+ // `chroma_offset_y = top_pad + (2 >> chroma_subsamp_y) *
1534+ // ar_padding + offset_y * (2 >> chroma_subsamp_y)`
1535+ // (`grain_synthesis.c:1091-1094`).
1536+ let chroma_off_y = TOP_PAD + ss.two_y() * AR_PADDING + offset_y * ss.two_y();
1537+ let chroma_off_x = LEFT_PAD + ss.two_x() * AR_PADDING + offset_x * ss.two_x();
12851538
12861539 if overlap && x != 0 {
12871540 let h_count = (LUMA_SUBBLOCK + 2).min(height - (y << 1));
@@ -1295,34 +1548,40 @@ pub(crate) fn apply_grain(
12951548 luma_off_y,
12961549 luma_off_x,
12971550 2,
1298- h_count, fctx,
1551+ h_count,
1552+ fctx,
12991553 );
1300- let hc_count = (CHROMA_SUBBLOCK + 1).min((height - (y << 1)) >> 1);
1554+ // `ver_boundary_overlap(cb_col_buf, 2 >> chroma_subsamp_x,
1555+ // ..., 2 >> chroma_subsamp_x, AOMMIN(chroma_subblock_size_y
1556+ // + (2 >> chroma_subsamp_y), (height - (y << 1)) >>
1557+ // chroma_subsamp_y))` (`grain_synthesis.c:1102-1112`).
1558+ let hc_count = (csub_y + ss.two_y()).min((height - (y << 1)) >> ss.y);
13011559 ver_overlap_inplace(
13021560 &mut cb_col_buf,
1303- 1,
1561+ ss.two_x(),
13041562 0,
13051563 0,
13061564 &cb_template,
1307- CHROMA_BLOCK_W,
1565+ cg_stride,
13081566 chroma_off_y,
13091567 chroma_off_x,
1310- 1,
1311- hc_count, fctx,
1568+ ss.two_x(),
1569+ hc_count,
1570+ fctx,
13121571 );
13131572 ver_overlap_inplace(
13141573 &mut cr_col_buf,
1315- 1,
1574+ ss.two_x(),
13161575 0,
13171576 0,
13181577 &cr_template,
1319- CHROMA_BLOCK_W,
1578+ cg_stride,
13201579 chroma_off_y,
13211580 chroma_off_x,
1322- 1,
1323- hc_count, fctx,
1581+ ss.two_x(),
1582+ hc_count,
1583+ fctx,
13241584 );
1325-
13261585 }
13271586
13281587 if overlap && y != 0 {
@@ -1337,35 +1596,43 @@ pub(crate) fn apply_grain(
13371596 0,
13381597 0,
13391598 2,
1340- 2, fctx,
1599+ 2,
1600+ fctx,
13411601 );
1602+ // `hor_boundary_overlap(cb_line_buf + (x << (1 -
1603+ // chroma_subsamp_x)), chroma_stride, cb_col_buf, 2 >>
1604+ // chroma_subsamp_x, ..., 2 >> chroma_subsamp_x, 2 >>
1605+ // chroma_subsamp_y)` (`grain_synthesis.c:1157-1168`).
1606+ let ccol_x = x << (1 - ss.x);
13421607 hor_overlap_inplace(
13431608 &mut cb_line_buf,
13441609 c_stride,
13451610 0,
1346- x,
1611+ ccol_x,
13471612 &cb_col_buf,
1348- 1,
1613+ ss.two_x(),
13491614 0,
13501615 0,
1351- 1,
1352- 1, fctx,
1616+ ss.two_x(),
1617+ ss.two_y(),
1618+ fctx,
13531619 );
13541620 hor_overlap_inplace(
13551621 &mut cr_line_buf,
13561622 c_stride,
13571623 0,
1358- x,
1624+ ccol_x,
13591625 &cr_col_buf,
1360- 1,
1626+ ss.two_x(),
13611627 0,
13621628 0,
1363- 1,
1364- 1, fctx,
1629+ ss.two_x(),
1630+ ss.two_y(),
1631+ fctx,
13651632 );
13661633 }
13671634 let lcol0 = if x != 0 { (x + 1) << 1 } else { 0 };
1368- let ccol0 = if x != 0 { x + 1 } else { 0 };
1635+ let ccol0 = if x != 0 { (x + 1) << (1 - ss.x) } else { 0 };
13691636 let lw = (LUMA_SUBBLOCK - (if x != 0 { 2 } else { 0 })).min(width - lcol0);
13701637 hor_overlap_inplace(
13711638 &mut y_line_buf,
@@ -1377,20 +1644,31 @@ pub(crate) fn apply_grain(
13771644 luma_off_y,
13781645 luma_off_x + if x != 0 { 2 } else { 0 },
13791646 lw,
1380- 2, fctx,
1647+ 2,
1648+ fctx,
13811649 );
1382- let cw = (CHROMA_SUBBLOCK - (if x != 0 { 1 } else { 0 })).min((width - lcol0) >> 1);
1650+ // `hor_boundary_overlap(cb_line_buf + ((x ? x + 1 : 0) << (1
1651+ // - chroma_subsamp_x)), chroma_stride, cb_grain_block +
1652+ // chroma_offset_y * stride + chroma_offset_x + ((x ? 1 : 0)
1653+ // << (1 - chroma_subsamp_x)), chroma_grain_stride, ...,
1654+ // AOMMIN(chroma_subblock_size_x - ((x ? 1 : 0) << (1 -
1655+ // chroma_subsamp_x)), (width - ((x ? x + 1 : 0) << 1)) >>
1656+ // chroma_subsamp_x), 2 >> chroma_subsamp_y)`
1657+ // (`grain_synthesis.c:1189-1200`).
1658+ let cskip = if x != 0 { ss.two_x() } else { 0 };
1659+ let cw = (csub_x - cskip).min((width - lcol0) >> ss.x);
13831660 hor_overlap_inplace(
13841661 &mut cb_line_buf,
13851662 c_stride,
13861663 0,
13871664 ccol0,
13881665 &cb_template,
1389- CHROMA_BLOCK_W,
1666+ cg_stride,
13901667 chroma_off_y,
1391- chroma_off_x + if x != 0 { 1 } else { 0 },
1668+ chroma_off_x + cskip,
13921669 cw,
1393- 1, fctx,
1670+ ss.two_y(),
1671+ fctx,
13941672 );
13951673 hor_overlap_inplace(
13961674 &mut cr_line_buf,
@@ -1398,13 +1676,13 @@ pub(crate) fn apply_grain(
13981676 0,
13991677 ccol0,
14001678 &cr_template,
1401- CHROMA_BLOCK_W,
1679+ cg_stride,
14021680 chroma_off_y,
1403- chroma_off_x + if x != 0 { 1 } else { 0 },
1681+ chroma_off_x + cskip,
14041682 cw,
1405- 1, fctx,
1683+ ss.two_y(),
1684+ fctx,
14061685 );
1407-
14081686 }
14091687
14101688 let i = if overlap && y != 0 { 1 } else { 0 };
@@ -1416,6 +1694,7 @@ pub(crate) fn apply_grain(
14161694 add_noise_to_block(
14171695 fg,
14181696 mc_identity,
1697+ ss,
14191698 &scaling_y,
14201699 &scaling_cb,
14211700 &scaling_cr,
@@ -1428,11 +1707,12 @@ pub(crate) fn apply_grain(
14281707 luma_off_x,
14291708 &cb_template,
14301709 &cr_template,
1431- CHROMA_BLOCK_W,
1710+ cg_stride,
14321711 chroma_off_y,
14331712 chroma_off_x,
14341713 bh,
1435- bw, fctx,
1714+ bw,
1715+ fctx,
14361716 );
14371717 } else {
14381718 // lane-grainrow: the overlap line and the overlap
@@ -1442,11 +1722,23 @@ pub(crate) fn apply_grain(
14421722 // AVX2 kernel handed the 3-sample tail of every row
14431723 // back to the scalar loop. A 4K cut spent 2.19e9 calls
14441724 // on 4.4e9 such samples. Assembling the three noise
1445- // sources into one 32x32 block (16x16 chroma) first
1446- // makes it one kernel call per block over a width that
1447- // is a multiple of 8, with no scalar remainder. Every
1448- // sample keeps the value its own source gave it, so the
1449- // picture is bit-identical.
1725+ // sources into one block first makes it one kernel call
1726+ // per block over a width that is a multiple of 8, with
1727+ // no scalar remainder. Every sample keeps the value its
1728+ // own source gave it, so the picture is bit-identical.
1729+ //
1730+ // lane-av1422grain: the assembled CHROMA block is
1731+ // `bh << (1 - ss_y)` rows by `bw << (1 - ss_x)` columns
1732+ // -- the very block `add_noise_to_block` walks
1733+ // (`grain_synthesis.c:680-681`) -- with `i << (1 - ss_y)`
1734+ // overlap rows and `j << (1 - ss_x)` overlap columns
1735+ // taken from the line and column buffers. At 4:2:0 both
1736+ // shifts are `<< 0`, so this is the 16x16 it always was.
1737+ let cch = (bh << (1 - ss.y)) as usize;
1738+ let ccw = (bw << (1 - ss.x)) as usize;
1739+ let ctop = (i << (1 - ss.y)) as usize;
1740+ let cwide = (j << (1 - ss.x)) as usize;
1741+ let ccol_x = (x << (1 - ss.x)) as usize;
14501742 if apply_y {
14511743 assemble_block_noise(
14521744 &mut y_blk,
@@ -1468,17 +1760,17 @@ pub(crate) fn apply_grain(
14681760 if apply_cb {
14691761 assemble_block_noise(
14701762 &mut cb_blk,
1471- CHROMA_SUBBLOCK as usize,
1472- bh as usize,
1473- bw as usize,
1763+ cblk_stride,
1764+ cch,
1765+ ccw,
14741766 &cb_line_buf,
14751767 c_stride as usize,
1476- x as usize,
1477- i as usize,
1768+ ccol_x,
1769+ ctop,
14781770 &cb_col_buf,
1479- j as usize,
1771+ cwide,
14801772 &cb_template,
1481- CHROMA_BLOCK_W as usize,
1773+ cg_stride as usize,
14821774 chroma_off_y as usize,
14831775 chroma_off_x as usize,
14841776 );
@@ -1486,17 +1778,17 @@ pub(crate) fn apply_grain(
14861778 if apply_cr {
14871779 assemble_block_noise(
14881780 &mut cr_blk,
1489- CHROMA_SUBBLOCK as usize,
1490- bh as usize,
1491- bw as usize,
1781+ cblk_stride,
1782+ cch,
1783+ ccw,
14921784 &cr_line_buf,
14931785 c_stride as usize,
1494- x as usize,
1495- i as usize,
1786+ ccol_x,
1787+ ctop,
14961788 &cr_col_buf,
1497- j as usize,
1789+ cwide,
14981790 &cr_template,
1499- CHROMA_BLOCK_W as usize,
1791+ cg_stride as usize,
15001792 chroma_off_y as usize,
15011793 chroma_off_x as usize,
15021794 );
@@ -1504,6 +1796,7 @@ pub(crate) fn apply_grain(
15041796 add_noise_to_block(
15051797 fg,
15061798 mc_identity,
1799+ ss,
15071800 &scaling_y,
15081801 &scaling_cb,
15091802 &scaling_cr,
@@ -1516,11 +1809,12 @@ pub(crate) fn apply_grain(
15161809 0,
15171810 &cb_blk,
15181811 &cr_blk,
1519- CHROMA_SUBBLOCK,
1812+ cblk_stride as i32,
15201813 0,
15211814 0,
15221815 bh,
1523- bw, fctx,
1816+ bw,
1817+ fctx,
15241818 );
15251819 }
15261820 }
@@ -1537,37 +1831,56 @@ pub(crate) fn apply_grain(
15371831 LUMA_SUBBLOCK,
15381832 0,
15391833 2,
1540- 2, fctx,
1834+ 2,
1835+ fctx,
15411836 );
1837+ // `copy_area(cb_col_buf + (chroma_subblock_size_y << (1
1838+ // - chroma_subsamp_x)), 2 >> chroma_subsamp_x,
1839+ // cb_line_buf + (x << (1 - chroma_subsamp_x)),
1840+ // chroma_stride, 2 >> chroma_subsamp_x, 2 >>
1841+ // chroma_subsamp_y)` (`grain_synthesis.c:1289-1296`).
1842+ //
1843+ // The C's source base is a FLAT element offset into
1844+ // `cb_col_buf`, and `copy_area` here addresses
1845+ // `src_row0 * src_stride + src_col0`. Since
1846+ // `src_stride == 2 >> ss_x` and the flat offset is
1847+ // `chroma_subblock_size_y << (1 - ss_x)`, the two agree
1848+ // for every `ss_x` -- but only because the flat offset
1849+ // was folded back into a ROW index here. Passing the
1850+ // flat value as the row index (the obvious reading)
1851+ // multiplies it by the stride a second time and reads
1852+ // past the buffer.
15421853 copy_area(
15431854 &mut cb_line_buf,
15441855 c_stride,
15451856 0,
1546- x,
1857+ x << (1 - ss.x),
15471858 &cb_col_buf,
1548- 1,
1549- CHROMA_SUBBLOCK,
1859+ ss.two_x(),
1860+ csub_y,
15501861 0,
1551- 1,
1552- 1, fctx,
1862+ ss.two_x(),
1863+ ss.two_y(),
1864+ fctx,
15531865 );
15541866 copy_area(
15551867 &mut cr_line_buf,
15561868 c_stride,
15571869 0,
1558- x,
1870+ x << (1 - ss.x),
15591871 &cr_col_buf,
1560- 1,
1561- CHROMA_SUBBLOCK,
1872+ ss.two_x(),
1873+ csub_y,
15621874 0,
1563- 1,
1564- 1, fctx,
1875+ ss.two_x(),
1876+ ss.two_y(),
1877+ fctx,
15651878 );
15661879 }
15671880 let lcol0 = if x != 0 { (x + 1) << 1 } else { 0 };
1568- let ccol0 = if x != 0 { x + 1 } else { 0 };
1881+ let ccol0 = if x != 0 { (x + 1) << (1 - ss.x) } else { 0 };
15691882 let lcut = if x != 0 { 2 } else { 0 };
1570- let ccut = if x != 0 { 1 } else { 0 };
1883+ let ccut = if x != 0 { ss.two_x() } else { 0 };
15711884 copy_area(
15721885 &mut y_line_buf,
15731886 y_stride,
@@ -1578,19 +1891,30 @@ pub(crate) fn apply_grain(
15781891 luma_off_y + LUMA_SUBBLOCK,
15791892 luma_off_x + lcut,
15801893 LUMA_SUBBLOCK.min(width - (x << 1)) - lcut,
1581- 2, fctx,
1894+ 2,
1895+ fctx,
15821896 );
1897+ // `copy_area(cb_grain_block + (chroma_offset_y +
1898+ // chroma_subblock_size_y) * chroma_grain_stride +
1899+ // chroma_offset_x + (x ? 2 >> chroma_subsamp_x : 0), ...,
1900+ // cb_line_buf + ((x ? x + 1 : 0) << (1 -
1901+ // chroma_subsamp_x)), chroma_stride, AOMMIN(
1902+ // chroma_subblock_size_x, ((width - (x << 1)) >>
1903+ // chroma_subsamp_x)) - (x ? 2 >> chroma_subsamp_x : 0), 2
1904+ // >> chroma_subsamp_y)` (`grain_synthesis.c:1309-1320`).
1905+ let cgw = csub_x.min((width - (x << 1)) >> ss.x) - ccut;
15831906 copy_area(
15841907 &mut cb_line_buf,
15851908 c_stride,
15861909 0,
15871910 ccol0,
15881911 &cb_template,
1589- CHROMA_BLOCK_W,
1590- chroma_off_y + CHROMA_SUBBLOCK,
1912+ cg_stride,
1913+ chroma_off_y + csub_y,
15911914 chroma_off_x + ccut,
1592- CHROMA_SUBBLOCK.min((width - (x << 1)) >> 1) - ccut,
1593- 1, fctx,
1915+ cgw,
1916+ ss.two_y(),
1917+ fctx,
15941918 );
15951919 copy_area(
15961920 &mut cr_line_buf,
@@ -1598,14 +1922,20 @@ pub(crate) fn apply_grain(
15981922 0,
15991923 ccol0,
16001924 &cr_template,
1601- CHROMA_BLOCK_W,
1602- chroma_off_y + CHROMA_SUBBLOCK,
1925+ cg_stride,
1926+ chroma_off_y + csub_y,
16031927 chroma_off_x + ccut,
1604- CHROMA_SUBBLOCK.min((width - (x << 1)) >> 1) - ccut,
1605- 1, fctx,
1928+ cgw,
1929+ ss.two_y(),
1930+ fctx,
16061931 );
16071932
16081933 let h_count = (LUMA_SUBBLOCK + 2).min(height - (y << 1));
1934+ // The chroma column buffer's row count, per-axis as the C
1935+ // (`grain_synthesis.c:1349-1350`): the same
1936+ // `AOMMIN(chroma_subblock_size_y + (2 >> ss_y), (height -
1937+ // (y << 1)) >> ss_y)` the vertical overlap above used.
1938+ let hc_count = (csub_y + ss.two_y()).min((height - (y << 1)) >> ss.y);
16091939 copy_area(
16101940 &mut y_col_buf,
16111941 2,
@@ -1616,32 +1946,41 @@ pub(crate) fn apply_grain(
16161946 luma_off_y,
16171947 luma_off_x + LUMA_SUBBLOCK,
16181948 2,
1619- h_count, fctx,
1949+ h_count,
1950+ fctx,
16201951 );
1621- let hc_count = (CHROMA_SUBBLOCK + 1).min((height - (y << 1)) >> 1);
1952+ // `copy_area(cb_grain_block + chroma_offset_y *
1953+ // chroma_grain_stride + chroma_offset_x +
1954+ // chroma_subblock_size_x, chroma_grain_stride, cb_col_buf,
1955+ // 2 >> chroma_subsamp_x, 2 >> chroma_subsamp_x, AOMMIN(
1956+ // chroma_subblock_size_y + (2 >> chroma_subsamp_y),
1957+ // (height - (y << 1)) >> chroma_subsamp_y))`
1958+ // (`grain_synthesis.c:1345-1352`).
16221959 copy_area(
16231960 &mut cb_col_buf,
1624- 1,
1961+ ss.two_x(),
16251962 0,
16261963 0,
16271964 &cb_template,
1628- CHROMA_BLOCK_W,
1965+ cg_stride,
16291966 chroma_off_y,
1630- chroma_off_x + CHROMA_SUBBLOCK,
1631- 1,
1632- hc_count, fctx,
1967+ chroma_off_x + csub_x,
1968+ ss.two_x(),
1969+ hc_count,
1970+ fctx,
16331971 );
16341972 copy_area(
16351973 &mut cr_col_buf,
1636- 1,
1974+ ss.two_x(),
16371975 0,
16381976 0,
16391977 &cr_template,
1640- CHROMA_BLOCK_W,
1978+ cg_stride,
16411979 chroma_off_y,
1642- chroma_off_x + CHROMA_SUBBLOCK,
1643- 1,
1644- hc_count, fctx,
1980+ chroma_off_x + csub_x,
1981+ ss.two_x(),
1982+ hc_count,
1983+ fctx,
16451984 );
16461985 }
16471986
@@ -1681,17 +2020,30 @@ mod perf5_tests {
16812020 let rounding_offset = 1i32 << (scaling_shift - 1);
16822021 for &(lo, hi) in &[(0i32, sample_max as i32), (16 << bd_shift, 235 << bd_shift)] {
16832022 for len in [1usize, 4, 7, 8, 9, 16, 31, 32, 64, 128] {
1684- let pixels: Vec<u16> =
1685- (0..len).map(|_| (rng() % (u64::from(sample_max) + 1)) as u16).collect();
2023+ let pixels: Vec<u16> = (0..len)
2024+ .map(|_| (rng() % (u64::from(sample_max) + 1)) as u16)
2025+ .collect();
16862026 let grain: Vec<i32> =
16872027 (0..len).map(|_| (rng() % 513) as i32 - 256).collect();
16882028 let mut want = pixels.clone();
16892029 super::luma_noise_row_scalar(
1690- &mut want, &grain, &scaling, rounding_offset, scaling_shift, lo, hi,
2030+ &mut want,
2031+ &grain,
2032+ &scaling,
2033+ rounding_offset,
2034+ scaling_shift,
2035+ lo,
2036+ hi,
16912037 );
16922038 let mut got = pixels.clone();
16932039 super::luma_noise_row(
1694- &mut got, &grain, &scaling, rounding_offset, scaling_shift, lo, hi,
2040+ &mut got,
2041+ &grain,
2042+ &scaling,
2043+ rounding_offset,
2044+ scaling_shift,
2045+ lo,
2046+ hi,
16952047 );
16962048 assert_eq!(got, want, "dispatch len={len} shift={scaling_shift}");
16972049 #[cfg(target_arch = "x86_64")]
@@ -1700,8 +2052,13 @@ mod perf5_tests {
17002052 #[allow(unsafe_code)]
17012053 unsafe {
17022054 super::simd::luma_noise_row_avx2(
1703- &mut avx, &grain, &scaling, rounding_offset, scaling_shift,
1704- lo, hi,
2055+ &mut avx,
2056+ &grain,
2057+ &scaling,
2058+ rounding_offset,
2059+ scaling_shift,
2060+ lo,
2061+ hi,
17052062 )
17062063 };
17072064 assert_eq!(avx, want, "avx2 len={len} shift={scaling_shift}");
@@ -1740,9 +2097,7 @@ mod perf5_tests {
17402097 (-128, 127, -(1 << (8 + bd_shift))),
17412098 (17, -64, 42),
17422099 ] {
1743- for &(lo, hi) in
1744- &[(0i32, index_max), (16 << bd_shift, 240 << bd_shift)]
1745- {
2100+ for &(lo, hi) in &[(0i32, index_max), (16 << bd_shift, 240 << bd_shift)] {
17462101 for len in [1usize, 5, 8, 9, 16, 17, 32] {
17472102 let p = super::ChromaNoise {
17482103 index_max,
@@ -1762,6 +2117,7 @@ mod perf5_tests {
17622117 let mut want = chroma.clone();
17632118 super::chroma_noise_row_scalar(
17642119 &mut want, &luma, &grain, &scaling, luma_mult, mult, offset, p,
2120+ true,
17652121 );
17662122 let mut got = chroma.clone();
17672123 super::chroma_noise_row(
@@ -1774,8 +2130,8 @@ mod perf5_tests {
17742130 #[allow(unsafe_code)]
17752131 unsafe {
17762132 super::simd::chroma_noise_row_avx2(
1777- &mut avx, &luma, &grain, &scaling, luma_mult, mult,
1778- offset, p,
2133+ &mut avx, &luma, &grain, &scaling, luma_mult, mult, offset,
2134+ p,
17792135 )
17802136 };
17812137 assert_eq!(avx, want, "avx2 len={len} mult={mult}");
@@ -1807,8 +2163,12 @@ mod grain2_tests {
18072163 width: w,
18082164 height: h,
18092165 y: (0..w * h).map(|i| ((i * 7 + 3) % 256) as u16).collect(),
1810- u: (0..w * h / 4).map(|i| ((i * 11 + 5) % 256) as u16).collect(),
1811- v: (0..w * h / 4).map(|i| ((i * 13 + 9) % 256) as u16).collect(),
2166+ u: (0..w * h / 4)
2167+ .map(|i| ((i * 11 + 5) % 256) as u16)
2168+ .collect(),
2169+ v: (0..w * h / 4)
2170+ .map(|i| ((i * 13 + 9) % 256) as u16)
2171+ .collect(),
18122172 };
18132173 let mut fg = FilmGrainParams {
18142174 apply_grain: true,
@@ -1827,7 +2187,10 @@ mod grain2_tests {
18272187 fg.point_cb_scaling[..2].copy_from_slice(&[40, 60]);
18282188 let fctx = crate::decode::FrameCtx::new();
18292189 let out = apply_grain(&src, &fg, false, 8, &fctx);
1830- assert_eq!(out.y, src.y, "no luma points: the luma plane is the clean copy");
2190+ assert_eq!(
2191+ out.y, src.y,
2192+ "no luma points: the luma plane is the clean copy"
2193+ );
18312194 assert_eq!(out.v, src.v, "no cr points: the V plane is the clean copy");
18322195 assert_ne!(out.u, src.u, "cb grain landed on the U plane");
18332196
@@ -1837,7 +2200,10 @@ mod grain2_tests {
18372200 fg2.point_y_scaling[..2].copy_from_slice(&[50, 70]);
18382201 let out2 = apply_grain(&src, &fg2, false, 8, &fctx);
18392202 assert_ne!(out2.y, src.y, "luma grain landed");
1840- assert_eq!(out2.v, src.v, "no cr points: the V plane is still the clean copy");
2203+ assert_eq!(
2204+ out2.v, src.v,
2205+ "no cr points: the V plane is still the clean copy"
2206+ );
18412207 assert_eq!(out2.y.len(), w * h, "the ragged tail row is present");
18422208 }
18432209 }
@@ -1850,25 +2216,45 @@ mod ragged_grain_tests {
18502216 (x + (1 << (n - 1))) >> n
18512217 }
18522218
1853- /// One 17-row chroma stripe block of spec 7.18.3.4's `add_noise_stripe`.
2219+ /// One chroma stripe block of spec 7.18.3.4's `add_noise_stripe`, per-axis.
2220+ ///
2221+ /// `rows`/`cols` are the block's own extent plus the `2 >> ss` overlap
2222+ /// rows/columns the NEXT block blends against, and `x` is the block's first
2223+ /// chroma column. The column blend is `ver_boundary_overlap`
2224+ /// (`grain_synthesis.c:912-939`), whose two widths are DIFFERENT formulas:
2225+ /// `width == 1` (`2 >> ss_x == 1`, so 4:2:0 and 4:2:2) is 23/22, while
2226+ /// `width == 2` (4:4:4) is 27/17 on the first column and 17/27 on the
2227+ /// second.
2228+ #[allow(clippy::too_many_arguments)]
18542229 fn chroma_stripe_block(
18552230 st: &mut [i32],
18562231 tpl: &[i32],
2232+ tp_stride: i32,
18572233 coy: i32,
18582234 cox: i32,
18592235 x: i32,
18602236 cw: i32,
2237+ rows: i32,
2238+ cols: i32,
2239+ skip: i32,
18612240 overlap: bool,
18622241 gmin: i32,
18632242 gmax: i32,
18642243 ) {
1865- for i in 0..17 {
1866- for j in 0..17 {
2244+ for i in 0..rows {
2245+ for j in 0..cols {
18672246 let col = x + j;
1868- let mut g = tpl[((coy + i) * CHROMA_BLOCK_W + cox + j) as usize];
1869- if overlap && x > 0 && j < 1 {
2247+ let mut g = tpl[((coy + i) * tp_stride + cox + j) as usize];
2248+ if overlap && x > 0 && j < skip {
18702249 let old = st[(i * cw + col) as usize];
1871- g = round2(old * 23 + g * 22, 5).clamp(gmin, gmax);
2250+ g = if skip == 1 {
2251+ round2(old * 23 + g * 22, 5)
2252+ } else if j == 0 {
2253+ round2(old * 27 + g * 17, 5)
2254+ } else {
2255+ round2(old * 17 + g * 27, 5)
2256+ }
2257+ .clamp(gmin, gmax);
18722258 }
18732259 if col < cw {
18742260 st[(i * cw + col) as usize] = g;
@@ -1884,10 +2270,22 @@ mod ragged_grain_tests {
18842270 /// pixel kernels (which are not what this test exercises). 8-bit, 4:2:0,
18852271 /// `clip_to_restricted_range == false`.
18862272 fn reference(src: &Picture, fg: &FilmGrainParams, fctx: &crate::decode::FrameCtx) -> Picture {
2273+ let ss = Ss::read(fctx);
18872274 let w = src.width as i32;
18882275 let h = src.height as i32;
1889- let cw = w / 2;
1890- let ch = h / 2;
2276+ // lane-av1422grain: the reference walks LUMA units exactly as the C's
2277+ // `add_film_grain_run` does (`grain_synthesis.c:1069-1078`) and derives
2278+ // every chroma extent per-axis, so one transcription serves 4:2:0,
2279+ // 4:2:2 and 4:4:4.
2280+ let cw = w >> ss.x;
2281+ let ch = h >> ss.y;
2282+ // The chroma block a luma block covers, per-axis. As in the C the
2283+ // half extents are LUMA ones (`AOMMIN(32 >> 1, ...)`,
2284+ // `grain_synthesis.c:1254-1255`) scaled by each axis, so this is
2285+ // `16 << (1 - ss)` -- 16x16 at 4:2:0, 32x16 at 4:2:2, 32x32 at 4:4:4.
2286+ let cblk_rows = (LUMA_SUBBLOCK >> 1) << (1 - ss.y);
2287+ let cblk_cols = (LUMA_SUBBLOCK >> 1) << (1 - ss.x);
2288+ let chroma_row = |y: i32| (y * 2) >> ss.y;
18912289 let (gmin, gmax) = grain_range(fctx);
18922290 let overlap = fg.overlap_flag;
18932291
@@ -1895,32 +2293,48 @@ mod ragged_grain_tests {
18952293 let pl = build_pred_pos(fg.ar_coeff_lag as i32, false);
18962294 let pc = build_pred_pos(fg.ar_coeff_lag as i32, fg.num_y_points > 0);
18972295 let lt = generate_luma_grain_block(fg, &pl, &mut rng, fctx);
1898- let (cbt, crt) = generate_chroma_grain_blocks(fg, &pc, &lt, fg.grain_seed, fctx);
2296+ let (cbt, crt, cg_stride) =
2297+ generate_chroma_grain_blocks(fg, &pc, &lt, fg.grain_seed, ss, fctx);
18992298
19002299 let mut nl = vec![0i32; (w * h) as usize];
19012300 let mut ncb = vec![0i32; (cw * ch) as usize];
19022301 let mut ncr = vec![0i32; (cw * ch) as usize];
19032302 let mut prev: Option<(Vec<i32>, Vec<i32>, Vec<i32>)> = None;
19042303 let mut y = 0;
1905- while y < ch {
2304+ while y < h / 2 {
19062305 let mut row_rng = Rng::line(y * 2, fg.grain_seed);
2306+ // 34 luma rows (32 + 2 overlap) and, per chroma plane, a stripe of
2307+ // `cblk_rows + (2 >> ss_y)` rows by `cblk_cols + (2 >> ss_x)`
2308+ // columns (17 x 17 at 4:2:0, 34 x 17 at 4:2:2, 34 x 34 at 4:4:4).
2309+ let crows = cblk_rows + (2 >> ss.y);
2310+ let ccols = cblk_cols + (2 >> ss.x);
19072311 let mut sl = vec![0i32; (34 * w) as usize];
1908- let mut scb = vec![0i32; (17 * cw) as usize];
1909- let mut scr = vec![0i32; (17 * cw) as usize];
2312+ let mut scb = vec![0i32; (crows * cw) as usize];
2313+ let mut scr = vec![0i32; (crows * cw) as usize];
19102314 let mut x = 0;
1911- while x < cw {
2315+ while x < w / 2 {
19122316 let raw = row_rng.get(8);
19132317 let ox = (raw >> 4) & 15;
19142318 let oy = raw & 15;
1915- let (loy, lox) = (9 + 2 * oy, 9 + 2 * ox);
1916- let (coy, cox) = (6 + oy, 6 + ox);
2319+ let (loy, lox) = (
2320+ LEFT_PAD + 2 * AR_PADDING + (oy << 1),
2321+ TOP_PAD + 2 * AR_PADDING + (ox << 1),
2322+ );
2323+ let (coy, cox) = (
2324+ TOP_PAD + ss.two_y() * AR_PADDING + oy * ss.two_y(),
2325+ LEFT_PAD + ss.two_x() * AR_PADDING + ox * ss.two_x(),
2326+ );
19172327 for i in 0..34 {
19182328 for j in 0..34 {
19192329 let col = x * 2 + j;
19202330 let mut g = lt[((loy + i) * LUMA_BLOCK_W + lox + j) as usize];
19212331 if overlap && x > 0 && j < 2 {
19222332 let old = sl[(i * w + col) as usize];
1923- g = if j == 0 { old * 27 + g * 17 } else { old * 17 + g * 27 };
2333+ g = if j == 0 {
2334+ old * 27 + g * 17
2335+ } else {
2336+ old * 17 + g * 27
2337+ };
19242338 g = round2(g, 5).clamp(gmin, gmax);
19252339 }
19262340 if col < w {
@@ -1928,11 +2342,44 @@ mod ragged_grain_tests {
19282342 }
19292343 }
19302344 }
1931- chroma_stripe_block(&mut scb, &cbt, coy, cox, x, cw, overlap, gmin, gmax);
1932- chroma_stripe_block(&mut scr, &crt, coy, cox, x, cw, overlap, gmin, gmax);
1933- x += 16;
2345+ // The stripe block spans `cblk_rows + (2 >> ss_y)` rows -- the
2346+ // trailing `2 >> ss_y` are the rows the NEXT block row's
2347+ // vertical overlap reads back out of `prev` -- and starts at
2348+ // chroma column `x << (1 - ss_x)`. At 4:2:0 that is the 17x17
2349+ // the transcription always used.
2350+ chroma_stripe_block(
2351+ &mut scb,
2352+ &cbt,
2353+ cg_stride,
2354+ coy,
2355+ cox,
2356+ x << (1 - ss.x),
2357+ cw,
2358+ crows,
2359+ ccols,
2360+ 2 >> ss.x,
2361+ overlap,
2362+ gmin,
2363+ gmax,
2364+ );
2365+ chroma_stripe_block(
2366+ &mut scr,
2367+ &crt,
2368+ cg_stride,
2369+ coy,
2370+ cox,
2371+ x << (1 - ss.x),
2372+ cw,
2373+ crows,
2374+ ccols,
2375+ 2 >> ss.x,
2376+ overlap,
2377+ gmin,
2378+ gmax,
2379+ );
2380+ x += LUMA_SUBBLOCK >> 1;
19342381 }
1935- for i in 0..32 {
2382+ for i in 0..(LUMA_SUBBLOCK >> 1) * 2 {
19362383 let row = y * 2 + i;
19372384 if row >= h {
19382385 break;
@@ -1942,31 +2389,56 @@ mod ragged_grain_tests {
19422389 if overlap && i < 2 {
19432390 if let Some((p, _, _)) = &prev {
19442391 let old = p[((i + 32) * w + col) as usize];
1945- g = if i == 0 { old * 27 + g * 17 } else { old * 17 + g * 27 };
2392+ g = if i == 0 {
2393+ old * 27 + g * 17
2394+ } else {
2395+ old * 17 + g * 27
2396+ };
19462397 g = round2(g, 5).clamp(gmin, gmax);
19472398 }
19482399 }
19492400 nl[(row * w + col) as usize] = g;
19502401 }
19512402 }
1952- for i in 0..16 {
1953- let row = y + i;
2403+ let cy0 = chroma_row(y);
2404+ for i in 0..cblk_rows {
2405+ let row = cy0 + i;
19542406 if row >= ch {
19552407 break;
19562408 }
19572409 for col in 0..cw {
19582410 for (st, img) in [(&scb, &mut ncb), (&scr, &mut ncr)] {
19592411 let mut g = st[(i * cw + col) as usize];
1960- if overlap && i < 1 {
2412+ if overlap && i < (2 >> ss.y) {
19612413 let old = match &prev {
19622414 Some((_, pb, pr)) => {
1963- let p = if std::ptr::eq(st.as_ptr(), scb.as_ptr()) { pb } else { pr };
1964- Some(p[((i + 16) * cw + col) as usize])
2415+ let p = if std::ptr::eq(st.as_ptr(), scb.as_ptr()) {
2416+ pb
2417+ } else {
2418+ pr
2419+ };
2420+ Some(p[((i + cblk_rows) * cw + col) as usize])
19652421 }
19662422 None => None,
19672423 };
19682424 if let Some(old) = old {
1969- g = round2(old * 23 + g * 22, 5).clamp(gmin, gmax);
2425+ // `hor_boundary_overlap`'s two heights are
2426+ // DIFFERENT formulas: `height == 1` blends
2427+ // 23/22 (`grain_synthesis.c:941-956`),
2428+ // `height == 2` blends 27/17 on the first row
2429+ // and 17/27 on the second (`:957-970`). At
2430+ // 4:2:0 `2 >> ss_y == 1` and only the first
2431+ // applies; at 4:2:2 and 4:4:4 it is 2 and the
2432+ // second row's 17/27 blend is a DIFFERENT
2433+ // value.
2434+ g = if (2 >> ss.y) == 1 {
2435+ round2(old * 23 + g * 22, 5)
2436+ } else if i == 0 {
2437+ round2(old * 27 + g * 17, 5)
2438+ } else {
2439+ round2(old * 17 + g * 27, 5)
2440+ }
2441+ .clamp(gmin, gmax);
19702442 }
19712443 }
19722444 img[(row * cw + col) as usize] = g;
@@ -1974,20 +2446,32 @@ mod ragged_grain_tests {
19742446 }
19752447 }
19762448 prev = Some((sl, scb, scr));
1977- y += 16;
2449+ y += LUMA_SUBBLOCK >> 1;
19782450 }
19792451
19802452 let mut out = src.clone();
19812453 let sy = expand_scaling_lut(
1982- &build_scaling_lut(&fg.point_y_value, &fg.point_y_scaling, fg.num_y_points as usize),
2454+ &build_scaling_lut(
2455+ &fg.point_y_value,
2456+ &fg.point_y_scaling,
2457+ fg.num_y_points as usize,
2458+ ),
19832459 8,
19842460 );
19852461 let s_cb = expand_scaling_lut(
1986- &build_scaling_lut(&fg.point_cb_value, &fg.point_cb_scaling, fg.num_cb_points as usize),
2462+ &build_scaling_lut(
2463+ &fg.point_cb_value,
2464+ &fg.point_cb_scaling,
2465+ fg.num_cb_points as usize,
2466+ ),
19872467 8,
19882468 );
19892469 let s_cr = expand_scaling_lut(
1990- &build_scaling_lut(&fg.point_cr_value, &fg.point_cr_scaling, fg.num_cr_points as usize),
2470+ &build_scaling_lut(
2471+ &fg.point_cr_value,
2472+ &fg.point_cr_scaling,
2473+ fg.num_cr_points as usize,
2474+ ),
19912475 8,
19922476 );
19932477 let scaling_shift = fg.grain_scaling_minus_8 as i32 + 8;
@@ -2002,9 +2486,18 @@ mod ragged_grain_tests {
20022486 // Chroma first, and out of the CLEAN luma: `add_noise_to_block` adds
20032487 // the block's chroma noise before its luma noise, so no chroma
20042488 // sample ever sees a noised luma neighbour.
2489+ // lane-av1422grain: chroma row `r` averages luma row `r << ss_y`, and
2490+ // the luma operand is a horizontal pair at `ss_x == 1` and the sample
2491+ // itself at `ss_x == 0` -- `grain_synthesis.c:683-691`.
2492+ let pair = ss.x == 1;
20052493 for r in 0..ch {
20062494 let (cs, ce) = ((r * cw) as usize, ((r + 1) * cw) as usize);
2007- let (ls, le) = ((2 * r * w) as usize, (2 * r * w + w) as usize);
2495+ let lrow = (r << ss.y) as usize;
2496+ let lper = if pair { 2 } else { 1 };
2497+ let (ls, le) = (
2498+ lrow * w as usize,
2499+ lrow * w as usize + cw as usize * lper as usize,
2500+ );
20082501 if fg.num_cb_points > 0 {
20092502 chroma_noise_row_scalar(
20102503 &mut out.u[cs..ce],
@@ -2015,6 +2508,7 @@ mod ragged_grain_tests {
20152508 fg.cb_mult as i32 - 128,
20162509 fg.cb_offset as i32 - 256,
20172510 p,
2511+ pair,
20182512 );
20192513 }
20202514 if fg.num_cr_points > 0 {
@@ -2027,13 +2521,22 @@ mod ragged_grain_tests {
20272521 fg.cr_mult as i32 - 128,
20282522 fg.cr_offset as i32 - 256,
20292523 p,
2524+ pair,
20302525 );
20312526 }
20322527 }
20332528 if fg.num_y_points > 0 {
20342529 for r in 0..h {
20352530 let (ls, le) = ((r * w) as usize, (r * w + w) as usize);
2036- luma_noise_row_scalar(&mut out.y[ls..le], &nl[ls..le], &sy, ro, scaling_shift, 0, 255);
2531+ luma_noise_row_scalar(
2532+ &mut out.y[ls..le],
2533+ &nl[ls..le],
2534+ &sy,
2535+ ro,
2536+ scaling_shift,
2537+ 0,
2538+ 255,
2539+ );
20372540 }
20382541 }
20392542 out
@@ -2078,20 +2581,40 @@ mod ragged_grain_tests {
20782581 let fctx = crate::decode::FrameCtx::new();
20792582 fctx.grain_bit_depth.with(|c| c.set(8));
20802583 let fg = params();
2081- for &(w, h) in &[(64usize, 66usize), (66, 64), (64, 98), (48, 100)] {
2082- let src = Picture {
2083- width: w,
2084- height: h,
2085- y: (0..w * h).map(|i| ((i * 7 + 3) % 256) as u16).collect(),
2086- u: (0..w / 2 * (h / 2)).map(|i| ((i * 11 + 5) % 256) as u16).collect(),
2087- v: (0..w / 2 * (h / 2)).map(|i| ((i * 13 + 9) % 256) as u16).collect(),
2088- };
2089- let got = apply_grain(&src, &fg, false, 8, &fctx);
2090- let want = reference(&src, &fg, &fctx);
2091- assert_eq!(got.y, want.y, "{w}x{h} luma");
2092- assert_eq!(got.u, want.u, "{w}x{h} cb");
2093- assert_eq!(got.v, want.v, "{w}x{h} cr");
2094- assert_ne!(got.y, src.y, "{w}x{h} grain actually landed");
2584+ // lane-av1422grain: the same transcription, driven over every chroma
2585+ // format the module admits. Before this lane the geometry was 4:2:0
2586+ // only, so 4:2:2 and 4:4:4 had NO coverage here at all -- and the
2587+ // defect was silent (a wrong picture, never a panic), which is exactly
2588+ // why the reference had to become per-axis rather than gain a second
2589+ // 4:2:0-shaped copy.
2590+ for (ss_x, ss_y, name) in [(1i32, 1i32, "420"), (1, 0, "422"), (0, 0, "444")] {
2591+ crate::decode::set_subsampling(ss_x as u8, ss_y as u8, &fctx);
2592+ for &(w, h) in &[(64usize, 66usize), (66, 64), (64, 98), (48, 100)] {
2593+ let (cw, ch) = (w >> ss_x as usize, h >> ss_y as usize);
2594+ let src = Picture {
2595+ width: w,
2596+ height: h,
2597+ y: (0..w * h).map(|i| ((i * 7 + 3) % 256) as u16).collect(),
2598+ u: (0..cw * ch).map(|i| ((i * 11 + 5) % 256) as u16).collect(),
2599+ v: (0..cw * ch).map(|i| ((i * 13 + 9) % 256) as u16).collect(),
2600+ };
2601+ let got = apply_grain(&src, &fg, false, 8, &fctx);
2602+ let want = reference(&src, &fg, &fctx);
2603+ let tag = format!("{name} {w}x{h}");
2604+ assert_eq!(got.y, want.y, "{tag} luma");
2605+ assert_eq!(got.u, want.u, "{tag} cb");
2606+ assert_eq!(got.v, want.v, "{tag} cr");
2607+ assert_ne!(got.y, src.y, "{tag} grain actually landed");
2608+ // The whole chroma plane must be grained, not just the top
2609+ // half. This is THE assertion the 4:2:0-shaped geometry
2610+ // could not make: at 4:2:2 the plane is `height` rows tall and
2611+ // the old `nrows = height / 2` walk left the bottom half raw.
2612+ assert_ne!(
2613+ &got.u[ch.saturating_sub(1) * cw..],
2614+ &src.u[ch.saturating_sub(1) * cw..],
2615+ "{tag}: the LAST chroma row came back clean -- the walk did not reach it"
2616+ );
2617+ }
20952618 }
20962619 }
20972620 }