forge
Explore
Log in

Don't you dare go Hollow

Merge lane-av1422grain: film-grain synthesis is PER-AXIS -- and the 4:2:0-shaped geometry was silently wrong for 4:4:4 too

Browse files at this commit

21c62a95b91a1a9929b8d548f4e7dfceb9ca7356Ahmet Kaan GümüşParent: 35bdf35a8377a2
The risk study's top finding was that `film_grain.rs` is the one module still 4:2:0-shaped, and the lift could not
proceed over it. It is now per-axis, proven by measurement rather than by construction, and the measurement turned
up more than the lift needed.

**Evidence.** A real 4:2:2 film-grain stream decodes byte-exact with `grain_hits()` rising per cell (3 -> 4), the
gate re-parses the OBUs and asserts a frame header carries `film_grain.apply_grain` (so it cannot be the
params-without-apply false green of `stream.rs:16626-16629`), and the comparator is shown to bite (one flipped
oracle sample per plane gives exactly (1,1,1) on every cell). The decisive control is negative: forcing the
subsampling back to (1,1) and changing NOTHING else makes the 4:2:2 cell FAIL with 0/23370/22631 -- luma exact,
~30% of each chroma plane wrong, **no panic and no counter**. That single line is the defect, and it also proves
the pass comes from this port rather than from a vacuous comparison.

**The fix corrects the assigned premise, and the correction matters.** This libaom snapshot has NO
`generate_grain_uv_422` / `av1_apply_grain_422`; it threads `chroma_subsamp_x/y` through one unified
`add_film_grain_run` (`grain_synthesis.c:987`), set per pixel format in `av1_add_film_grain` (`:1386-1420`, which
lists I422/I42216). The port matches the C's expressions, cited per site in the report. Three traps came out of
it: the chroma BLOCK is `16 << (1 - ss)`, NOT `chroma_subblock_size << (1 - ss)` (the two agree at 4:2:0 and
differ 2x wherever `chroma_subsamp == 0` -- and the wrong value is an OUT-OF-BOUNDS READ, not a wrong pixel); the
block walk is in LUMA units at every subsampling, so only the chroma ORIGIN and extent are per-axis; and
`copy_area(cb_col_buf + (chroma_subblock_size_y << (1 - ss_x)), ...)` is a FLAT ELEMENT offset, not a row index.

**Two of the study's nine sites were wrong in the other direction and the fix says so**: `n = luma.len()/2` and
`c_stride = width/2` are right at 4:2:2 and WRONG at 4:4:4 -- the operand needs a pair flag, not a division.
Consequence worth stating plainly: **the pre-fix geometry was silently wrong for 4:4:4 film grain as well**, a
supported format with no test of any kind. Two arms that were dead code at 4:2:0 are now live
(`ver/hor_boundary_overlap`'s `==2` arm, and `add_noise_to_block`'s luma operand as a horizontal pair at
`ss_x == 1`).

**Coverage closed**: 4:2:2 and 4:4:4 film grain had NO test before this lane -- not an exactness gate, not a
reference comparison. `ragged_overlap_tail_matches_spec_reference` was a 4:2:0-only transcription and is now
driven over all three formats from one per-axis reference, with the assertion the old geometry could not make:
the LAST chroma row must come back grained, which at 4:2:2 is exactly the raw bottom half the `nrows = height/2`
walk left behind. Controls: `cargo test -p ec-av1 --lib film_grain` 8 passed; blast sweep on 422/444/chroma 95
passed; `cargo check --tests` clean.
crates/ec-av1/src/film_grain.rsmodified+784 -261
@@ -1,9 +1,18 @@
1 //! AV1 film grain synthesis (spec 7.18.3), ported bit-exact from libaom's1 //! AV1 film grain synthesis (spec 7.18.3), ported bit-exact from libaom's
2 //! `av1/decoder/grain_synthesis.c` (`add_film_grain_run` and its helpers),2 //! `av1/decoder/grain_synthesis.c` (`add_film_grain_run` and its helpers),
3-//! specialized to this crate's only picture shape: 4:2:0 planar3+//! lane-av1422grain: this module USED to be specialised to 4:2:0 -- the
4-//! (`chroma_subsamp_x = chroma_subsamp_y = 1` throughout, which is why every4+//! chroma subblock, the chroma grain-block template, the chroma row map, the
5-//! `<< (1 - subsamp)` in the reference collapses to a no-op and every5+//! `avgLuma` tap, the line/column buffers and the chroma stride were all
6-//! `>> subsamp` collapses to `>> 1` below).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`).
7 //!16 //!
8 //! Grain is synthesized only into the picture handed back to the caller for17 //! Grain is synthesized only into the picture handed back to the caller for
9 //! *output* -- the picture stored as a reference for later inter prediction18 //! *output* -- the picture stored as a reference for later inter prediction
@@ -36,19 +45,66 @@ const BOTTOM_PAD: i32 = 0;
36 const AR_PADDING: i32 = 3;45 const AR_PADDING: i32 = 3;
37 46
38 const LUMA_SUBBLOCK: i32 = 32;47 const LUMA_SUBBLOCK: i32 = 32;
39-const CHROMA_SUBBLOCK: i32 = 16; // LUMA_SUBBLOCK >> subsampling (always 1 here)
40 48
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).
42 const LUMA_BLOCK_H: i32 = TOP_PAD + 2 * AR_PADDING + LUMA_SUBBLOCK * 2 + BOTTOM_PAD;105 const LUMA_BLOCK_H: i32 = TOP_PAD + 2 * AR_PADDING + LUMA_SUBBLOCK * 2 + BOTTOM_PAD;
43 const LUMA_BLOCK_W: i32 =106 const LUMA_BLOCK_W: i32 =
44 LEFT_PAD + 2 * AR_PADDING + LUMA_SUBBLOCK * 2 + 2 * AR_PADDING + RIGHT_PAD;107 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.
52 108
53 /// `params->bit_depth` for the [`apply_grain`] call in progress.109 /// `params->bit_depth` for the [`apply_grain`] call in progress.
54 fn grain_bit_depth(fctx: &crate::decode::FrameCtx) -> u32 {110 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)> {
134 fn generate_luma_grain_block(190 fn generate_luma_grain_block(
135 fg: &FilmGrainParams,191 fg: &FilmGrainParams,
136 pred_pos: &[(i32, i32, i32)],192 pred_pos: &[(i32, i32, i32)],
137- rng: &mut Rng, fctx: &crate::decode::FrameCtx,193+ rng: &mut Rng,
194+ fctx: &crate::decode::FrameCtx,
138 ) -> Vec<i32> {195 ) -> Vec<i32> {
139 let (grain_min, grain_max) = grain_range(fctx);196 let (grain_min, grain_max) = grain_range(fctx);
140 let mut block = vec![0i32; (LUMA_BLOCK_H * LUMA_BLOCK_W) as usize];197 let mut block = vec![0i32; (LUMA_BLOCK_H * LUMA_BLOCK_W) as usize];
@@ -166,16 +223,27 @@ fn generate_luma_grain_block(
166 block223 block
167 }224 }
168 225
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.
170 fn generate_chroma_grain_blocks(234 fn generate_chroma_grain_blocks(
171 fg: &FilmGrainParams,235 fg: &FilmGrainParams,
172 pred_pos: &[(i32, i32, i32)],236 pred_pos: &[(i32, i32, i32)],
173 luma_block: &[i32],237 luma_block: &[i32],
174- seed: u16, fctx: &crate::decode::FrameCtx,238+ seed: u16,
175-) -> (Vec<i32>, Vec<i32>) {239+ ss: Ss,
240+ fctx: &crate::decode::FrameCtx,
241+) -> (Vec<i32>, Vec<i32>, i32) {
176 let (grain_min, grain_max) = grain_range(fctx);242 let (grain_min, grain_max) = grain_range(fctx);
177- let mut cb = vec![0i32; (CHROMA_BLOCK_H * CHROMA_BLOCK_W) as usize];243+ let cbh = ss.cblock_h();
178- let mut cr = vec![0i32; (CHROMA_BLOCK_H * CHROMA_BLOCK_W) as usize];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];
179 let gauss_sec_shift = 12 - grain_bit_depth(fctx) as i32 + fg.grain_scale_shift as i32;247 let gauss_sec_shift = 12 - grain_bit_depth(fctx) as i32 + fg.grain_scale_shift as i32;
180 let ar_coeff_shift = fg.ar_coeff_shift_minus_6 as i32 + 6;248 let ar_coeff_shift = fg.ar_coeff_shift_minus_6 as i32 + 6;
181 let rounding_offset = 1i32 << (ar_coeff_shift - 1);249 let rounding_offset = 1i32 << (ar_coeff_shift - 1);
@@ -185,12 +253,12 @@ fn generate_chroma_grain_blocks(
185 253
186 if apply_cb {254 if apply_cb {
187 let mut rng = Rng::line(7 << 5, seed);255 let mut rng = Rng::line(7 << 5, seed);
188- for i in 0..CHROMA_BLOCK_H {256+ for i in 0..cbh {
189- for j in 0..CHROMA_BLOCK_W {257+ for j in 0..cbw {
190 let g = GAUSSIAN_SEQUENCE[rng.get(GAUSS_BITS) as usize];258 let g = GAUSSIAN_SEQUENCE[rng.get(GAUSS_BITS) as usize];
191 set_at(259 set_at(
192 &mut cb,260 &mut cb,
193- CHROMA_BLOCK_W,261+ cbw,
194 i,262 i,
195 j,263 j,
196 (g + ((1 << gauss_sec_shift) >> 1)) >> gauss_sec_shift,264 (g + ((1 << gauss_sec_shift) >> 1)) >> gauss_sec_shift,
@@ -200,12 +268,12 @@ fn generate_chroma_grain_blocks(
200 }268 }
201 if apply_cr {269 if apply_cr {
202 let mut rng = Rng::line(11 << 5, seed);270 let mut rng = Rng::line(11 << 5, seed);
203- for i in 0..CHROMA_BLOCK_H {271+ for i in 0..cbh {
204- for j in 0..CHROMA_BLOCK_W {272+ for j in 0..cbw {
205 let g = GAUSSIAN_SEQUENCE[rng.get(GAUSS_BITS) as usize];273 let g = GAUSSIAN_SEQUENCE[rng.get(GAUSS_BITS) as usize];
206 set_at(274 set_at(
207 &mut cr,275 &mut cr,
208- CHROMA_BLOCK_W,276+ cbw,
209 i,277 i,
210 j,278 j,
211 (g + ((1 << gauss_sec_shift) >> 1)) >> gauss_sec_shift,279 (g + ((1 << gauss_sec_shift) >> 1)) >> gauss_sec_shift,
@@ -214,47 +282,47 @@ fn generate_chroma_grain_blocks(
214 }282 }
215 }283 }
216 284
217- for i in TOP_PAD..CHROMA_BLOCK_H - BOTTOM_PAD {285+ for i in TOP_PAD..cbh - BOTTOM_PAD {
218- for j in LEFT_PAD..CHROMA_BLOCK_W - RIGHT_PAD {286+ for j in LEFT_PAD..cbw - RIGHT_PAD {
219 let mut wsum_cb = 0i32;287 let mut wsum_cb = 0i32;
220 let mut wsum_cr = 0i32;288 let mut wsum_cr = 0i32;
221 for (idx, &(dy, dx, kind)) in pred_pos.iter().enumerate() {289 for (idx, &(dy, dx, kind)) in pred_pos.iter().enumerate() {
222 if kind == 0 {290 if kind == 0 {
223- wsum_cb +=291+ wsum_cb += fg.ar_coeffs_cb[idx] as i32 * at(&cb, cbw, i + dy, j + dx);
224- fg.ar_coeffs_cb[idx] as i32 * at(&cb, CHROMA_BLOCK_W, i + dy, j + dx);292+ wsum_cr += fg.ar_coeffs_cr[idx] as i32 * at(&cr, cbw, i + dy, j + dx);
225- wsum_cr +=
226- fg.ar_coeffs_cr[idx] as i32 * at(&cr, CHROMA_BLOCK_W, i + dy, j + dx);
227 } else {293 } else {
228- // `avgLuma` (spec 7.18.3.3): subsampling_x = subsampling_y = 1294+ // `avgLuma` (spec 7.18.3.3; `grain_synthesis.c:554-565`):
229- // always here, so the 2x2 luma quad is exactly one 4:2:0 cell.295+ // the luma origin is the chroma origin scaled back by each
230- let luma_y = ((i - TOP_PAD) << 1) + TOP_PAD;296+ // axis' subsampling, and the average divides by the
231- let luma_x = ((j - LEFT_PAD) << 1) + LEFT_PAD;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;
232 let mut av = 0i32;301 let mut av = 0i32;
233- for k in luma_y..luma_y + 2 {302+ for k in luma_y..luma_y + ss.y + 1 {
234- for l in luma_x..luma_x + 2 {303+ for l in luma_x..luma_x + ss.x + 1 {
235 av += at(luma_block, LUMA_BLOCK_W, k, l);304 av += at(luma_block, LUMA_BLOCK_W, k, l);
236 }305 }
237 }306 }
238- av = (av + 2) >> 2;307+ let shift = ss.y + ss.x;
308+ av = (av + ((1 << shift) >> 1)) >> shift;
239 wsum_cb += fg.ar_coeffs_cb[idx] as i32 * av;309 wsum_cb += fg.ar_coeffs_cb[idx] as i32 * av;
240 wsum_cr += fg.ar_coeffs_cr[idx] as i32 * av;310 wsum_cr += fg.ar_coeffs_cr[idx] as i32 * av;
241 }311 }
242 }312 }
243 if apply_cb {313 if apply_cb {
244- let v = (at(&cb, CHROMA_BLOCK_W, i, j)314+ let v = (at(&cb, cbw, i, j) + ((wsum_cb + rounding_offset) >> ar_coeff_shift))
245- + ((wsum_cb + rounding_offset) >> ar_coeff_shift))
246 .clamp(grain_min, grain_max);315 .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);
248 }317 }
249 if apply_cr {318 if apply_cr {
250- let v = (at(&cr, CHROMA_BLOCK_W, i, j)319+ let v = (at(&cr, cbw, i, j) + ((wsum_cr + rounding_offset) >> ar_coeff_shift))
251- + ((wsum_cr + rounding_offset) >> ar_coeff_shift))
252 .clamp(grain_min, grain_max);320 .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);
254 }322 }
255 }323 }
256 }324 }
257- (cb, cr)325+ (cb, cr, cbw)
258 }326 }
259 327
260 /// `init_scaling_function` (spec 7.18.3.2, piecewise-linear scaling LUT).328 /// `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 {
291 if shift == 0 || x == 255 {359 if shift == 0 || x == 255 {
292 lut[x]360 lut[x]
293 } else {361 } else {
294- lut[x] + (((lut[x + 1] - lut[x]) * (index & ((1 << shift) - 1)) + (1 << (shift - 1)))362+ lut[x]
295- >> shift)363+ + (((lut[x + 1] - lut[x]) * (index & ((1 << shift) - 1)) + (1 << (shift - 1))) >> shift)
296 }364 }
297 }365 }
298 366
@@ -310,15 +378,21 @@ fn expand_scaling_lut(lut: &[i32; 256], bit_depth: u32) -> Vec<i32> {
310 .collect()378 .collect()
311 }379 }
312 380
313-/// `add_noise_to_block` (spec 7.18.3.5), 4:2:0 only. `(py0, px0)` is381+/// `add_noise_to_block` (spec 7.18.3.5). `(py0, px0)` is the luma-plane
314-/// the luma-plane pixel origin; the matching chroma origin is `(py0/2,382+/// pixel origin; the matching chroma origin is `(py0 >> ss_y, px0 >>
315-/// px0/2)`. Grain is read from `(grain, stride, row0, col0)` triples so the383+/// ss_x)` -- `(py0/2, px0/2)` only at 4:2:0. Grain is read from
316-/// same function serves both the raw 82x73/44x38 templates and the small384+/// `(grain, stride, row0, col0)` triples so the same function serves both
317-/// blended col/line buffers below.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`).
318 #[allow(clippy::too_many_arguments)]391 #[allow(clippy::too_many_arguments)]
319 fn add_noise_to_block(392 fn add_noise_to_block(
320 fg: &FilmGrainParams,393 fg: &FilmGrainParams,
321 mc_identity: bool,394 mc_identity: bool,
395+ ss: Ss,
322 scaling_y: &[i32],396 scaling_y: &[i32],
323 scaling_cb: &[i32],397 scaling_cb: &[i32],
324 scaling_cr: &[i32],398 scaling_cr: &[i32],
@@ -335,7 +409,8 @@ fn add_noise_to_block(
335 cg_row0: i32,409 cg_row0: i32,
336 cg_col0: i32,410 cg_col0: i32,
337 half_h: i32,411 half_h: i32,
338- half_w: i32, fctx: &crate::decode::FrameCtx,412+ half_w: i32,
413+ fctx: &crate::decode::FrameCtx,
339 ) {414 ) {
340 // spec 7.18.3.5 runs the block's noise loops `for i in 0..h`/`for j in415 // spec 7.18.3.5 runs the block's noise loops `for i in 0..h`/`for j in
341 // 0..w`, so a block with no rows (or no columns) writes nothing. The416 // 0..w`, so a block with no rows (or no columns) writes nothing. The
@@ -348,7 +423,7 @@ fn add_noise_to_block(
348 return;423 return;
349 }424 }
350 let y_stride = picture.width as i32;425 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;
352 let scaling_shift = fg.grain_scaling_minus_8 as i32 + 8;427 let scaling_shift = fg.grain_scaling_minus_8 as i32 + 8;
353 let bit_depth = grain_bit_depth(fctx);428 let bit_depth = grain_bit_depth(fctx);
354 let bd_shift = bit_depth - 8;429 let bd_shift = bit_depth - 8;
@@ -394,24 +469,51 @@ fn add_noise_to_block(
394 (0, index_max, 0, index_max)469 (0, index_max, 0, index_max)
395 };470 };
396 471
397- let cy0 = py0 / 2;472+ // `cb + ((y + i) << (1 - chroma_subsamp_y)) * chroma_stride + ((x + j) <<
398- let cx0 = px0 / 2;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;
399 if apply_cb || apply_cr {477 if apply_cb || apply_cr {
400- // lane-perf4: one row of each operand at a time. The 4:2:0 luma478+ // lane-perf4: one row of each operand at a time. The luma average
401- // average (spec 7.18.3.5) reads a horizontally adjacent PAIR of the479+ // (spec 7.18.3.5) reads a horizontally adjacent PAIR of the block's
402- // block's own luma row, so `chunks_exact(2)` walks exactly the pairs480+ // own luma row at `ss_x == 1` (4:2:0 and 4:2:2 alike), so
403- // the per-sample `(ly * y_stride + lx)` form used to re-derive, and481+ // `chunks_exact(2)` walks exactly the pairs the per-sample
404- // the U/V/grain rows advance in lockstep with it -- same integers,482+ // `(ly * y_stride + lx)` form used to re-derive, and the U/V/grain rows
405- // same rounding, no per-sample index arithmetic or bounds check.483+ // advance in lockstep with it -- same integers, same rounding, no
406- let cw = half_w as usize;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;
407 // U and V are distinct fields, so a disjoint borrow of each is498 // U and V are distinct fields, so a disjoint borrow of each is
408 // needed alongside the immutable read of Y.499 // 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;
410 let lrow0 = (py0 * y_stride + px0) as usize;506 let lrow0 = (py0 * y_stride + px0) as usize;
411 let crow0 = (cy0 * c_stride + cx0) as usize;507 let crow0 = (cy0 * c_stride + cx0) as usize;
412 let grow0 = (cg_row0 * cg_stride + cg_col0) as usize;508 let grow0 = (cg_row0 * cg_stride + cg_col0) as usize;
413 let luma = &luma_plane[lrow0..];509 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+ };
415 // lane-grain: the whole block in one call, so the kernel's AVX2517 // lane-grain: the whole block in one call, so the kernel's AVX2
416 // prologue is paid once per block instead of once per 15-sample row.518 // prologue is paid once per block instead of once per 15-sample row.
417 if apply_cb {519 if apply_cb {
@@ -419,16 +521,17 @@ fn add_noise_to_block(
419 &mut u_plane[crow0..],521 &mut u_plane[crow0..],
420 c_stride as usize,522 c_stride as usize,
421 luma,523 luma,
422- 2 * y_stride as usize,524+ lrow_step * y_stride as usize,
423 &cb_grain[grow0..],525 &cb_grain[grow0..],
424 cg_stride as usize,526 cg_stride as usize,
425- half_h as usize,527+ ch,
426 cw,528 cw,
427 scaling_cb,529 scaling_cb,
428 cb_luma_mult,530 cb_luma_mult,
429 cb_mult,531 cb_mult,
430 cb_offset,532 cb_offset,
431 params,533 params,
534+ pair,
432 );535 );
433 }536 }
434 if apply_cr {537 if apply_cr {
@@ -436,16 +539,17 @@ fn add_noise_to_block(
436 &mut v_plane[crow0..],539 &mut v_plane[crow0..],
437 c_stride as usize,540 c_stride as usize,
438 luma,541 luma,
439- 2 * y_stride as usize,542+ lrow_step * y_stride as usize,
440 &cr_grain[grow0..],543 &cr_grain[grow0..],
441 cg_stride as usize,544 cg_stride as usize,
442- half_h as usize,545+ ch,
443 cw,546 cw,
444 scaling_cr,547 scaling_cr,
445 cr_luma_mult,548 cr_luma_mult,
446 cr_mult,549 cr_mult,
447 cr_offset,550 cr_offset,
448 params,551 params,
552+ pair,
449 );553 );
450 }554 }
451 }555 }
@@ -489,7 +593,17 @@ fn luma_noise_row(
489 ) {593 ) {
490 let n = pixels.len().min(grain.len());594 let n = pixels.len().min(grain.len());
491 luma_noise_rows(595 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,
493 );607 );
494 }608 }
495 609
@@ -524,8 +638,17 @@ fn luma_noise_rows(
524 // sliced, and gathers only in-range LUT entries.638 // sliced, and gathers only in-range LUT entries.
525 unsafe {639 unsafe {
526 simd::luma_noise_rows_avx2(640 simd::luma_noise_rows_avx2(
527- pixels, p_stride, grain, g_stride, rows, n, scaling, rounding_offset,641+ pixels,
528- scaling_shift, min_luma, max_luma,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,
529 )652 )
530 };653 };
531 return;654 return;
@@ -554,9 +677,21 @@ struct ChromaNoise {
554 max_chroma: i32,677 max_chroma: i32,
555 }678 }
556 679
557-/// One chroma row of spec 7.18.3.5's `add_noise_to_block`: `luma` is the680+/// One chroma row of spec 7.18.3.5's `add_noise_to_block`.
558-/// block's own luma row pair-averaged 4:2:0 (`luma.len() == 2 *681+///
559-/// chroma.len()`), `grain` and `scaling` are the plane's own.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`.
560 ///695 ///
561 /// lane-perf9: AVX2 does 8 chroma samples at a time, the luma pair sum being696 /// lane-perf9: AVX2 does 8 chroma samples at a time, the luma pair sum being
562 /// one `vpmaddwd` against ones; every other CPU runs the scalar loop, which697 /// one `vpmaddwd` against ones; every other CPU runs the scalar loop, which
@@ -574,14 +709,31 @@ fn chroma_noise_row(
574 offset: i32,709 offset: i32,
575 p: ChromaNoise,710 p: ChromaNoise,
576 ) {711 ) {
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);
578 chroma_noise_rows(716 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,
580 );731 );
581 }732 }
582 733
583 /// [`chroma_noise_row`] over `rows` consecutive chroma rows of a block; see734 /// [`chroma_noise_row`] over `rows` consecutive chroma rows of a block; see
584 /// [`luma_noise_rows`] for why the row loop lives inside the kernel.735 /// [`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.
585 #[allow(unsafe_code)]737 #[allow(unsafe_code)]
586 #[allow(clippy::too_many_arguments)]738 #[allow(clippy::too_many_arguments)]
587 fn chroma_noise_rows(739 fn chroma_noise_rows(
@@ -598,9 +750,10 @@ fn chroma_noise_rows(
598 mult: i32,750 mult: i32,
599 offset: i32,751 offset: i32,
600 p: ChromaNoise,752 p: ChromaNoise,
753+ pair: bool,
601 ) {754 ) {
602 #[cfg(target_arch = "x86_64")]755 #[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 {
604 // SAFETY: reached only when the CPU reports avx2; the kernel reads757 // SAFETY: reached only when the CPU reports avx2; the kernel reads
605 // `luma`/`grain`/`chroma` only inside the window the caller sliced,758 // `luma`/`grain`/`chroma` only inside the window the caller sliced,
606 // and gathers only in-range LUT entries.759 // and gathers only in-range LUT entries.
@@ -612,16 +765,18 @@ fn chroma_noise_rows(
612 };765 };
613 return;766 return;
614 }767 }
768+ let lrow = if pair { 2 * n } else { n };
615 for r in 0..rows {769 for r in 0..rows {
616 chroma_noise_row_scalar(770 chroma_noise_row_scalar(
617 &mut chroma[r * c_stride..r * c_stride + n],771 &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],
619 &grain[r * g_stride..r * g_stride + n],773 &grain[r * g_stride..r * g_stride + n],
620 scaling,774 scaling,
621 luma_mult,775 luma_mult,
622 mult,776 mult,
623 offset,777 offset,
624 p,778 p,
779+ pair,
625 );780 );
626 }781 }
627 }782 }
@@ -637,13 +792,26 @@ fn chroma_noise_row_scalar(
637 mult: i32,792 mult: i32,
638 offset: i32,793 offset: i32,
639 p: ChromaNoise,794 p: ChromaNoise,
795+ pair: bool,
640 ) {796 ) {
641- for ((c, lpair), &g) in chroma.iter_mut().zip(luma.chunks_exact(2)).zip(grain) {797+ if pair {
642- let average_luma = (lpair[0] as i32 + lpair[1] as i32 + 1) >> 1;798+ for ((c, lpair), &g) in chroma.iter_mut().zip(luma.chunks_exact(2)).zip(grain) {
643- let scaled =799+ let average_luma = (lpair[0] as i32 + lpair[1] as i32 + 1) >> 1;
644- (((average_luma * luma_mult + mult * *c as i32) >> 6) + offset).clamp(0, p.index_max);800+ let scaled = (((average_luma * luma_mult + mult * *c as i32) >> 6) + offset)
645- let delta = (scaling[scaled as usize] * g + p.rounding_offset) >> p.scaling_shift;801+ .clamp(0, p.index_max);
646- *c = ((*c as i32 + delta).clamp(p.min_chroma, p.max_chroma)) as u16;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+ }
647 }815 }
648 }816 }
649 817
@@ -695,7 +863,17 @@ mod simd {
695 ) {863 ) {
696 let n = pixels.len().min(grain.len());864 let n = pixels.len().min(grain.len());
697 luma_noise_rows_avx2(865 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,
699 );877 );
700 }878 }
701 879
@@ -800,7 +978,19 @@ mod simd {
800 ) {978 ) {
801 let n = chroma.len().min(grain.len()).min(luma.len() / 2);979 let n = chroma.len().min(grain.len()).min(luma.len() / 2);
802 chroma_noise_rows_avx2(980 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,
804 );994 );
805 }995 }
806 996
@@ -886,8 +1076,10 @@ mod simd {
886 let avg = _mm_srai_epi32(_mm_add_epi32(pair_sum, one4), 1);1076 let avg = _mm_srai_epi32(_mm_add_epi32(pair_sum, one4), 1);
887 let c16 = _mm_loadl_epi64(cp.add(c).cast());1077 let c16 = _mm_loadl_epi64(cp.add(c).cast());
888 let c32 = _mm_cvtepu16_epi32(c16);1078 let c32 = _mm_cvtepu16_epi32(c16);
889- let mixed =1079+ let mixed = _mm_add_epi32(
890- _mm_add_epi32(_mm_mullo_epi32(avg, vluma_mult4), _mm_mullo_epi32(c32, vmult4));1080+ _mm_mullo_epi32(avg, vluma_mult4),
1081+ _mm_mullo_epi32(c32, vmult4),
1082+ );
891 let scaled = _mm_add_epi32(_mm_srai_epi32(mixed, 6), voffset4);1083 let scaled = _mm_add_epi32(_mm_srai_epi32(mixed, 6), voffset4);
892 let clamped = _mm_max_epi32(_mm_min_epi32(scaled, vindex_max4), zero4);1084 let clamped = _mm_max_epi32(_mm_min_epi32(scaled, vindex_max4), zero4);
893 let idx = _mm_min_epi32(clamped, last4);1085 let idx = _mm_min_epi32(clamped, last4);
@@ -910,6 +1102,7 @@ mod simd {
910 mult,1102 mult,
911 offset,1103 offset,
912 p,1104 p,
1105+ true,
913 );1106 );
914 }1107 }
915 }1108 }
@@ -929,7 +1122,8 @@ fn ver_overlap_inplace(
929 right_row0: i32,1122 right_row0: i32,
930 right_col0: i32,1123 right_col0: i32,
931 width: i32,1124 width: i32,
932- height: i32, fctx: &crate::decode::FrameCtx,1125+ height: i32,
1126+ fctx: &crate::decode::FrameCtx,
933 ) {1127 ) {
934 let (grain_min, grain_max) = grain_range(fctx);1128 let (grain_min, grain_max) = grain_range(fctx);
935 for h in 0..height {1129 for h in 0..height {
@@ -979,7 +1173,8 @@ fn hor_overlap_inplace(
979 bot_row0: i32,1173 bot_row0: i32,
980 bot_col0: i32,1174 bot_col0: i32,
981 width: i32,1175 width: i32,
982- height: i32, fctx: &crate::decode::FrameCtx,1176+ height: i32,
1177+ fctx: &crate::decode::FrameCtx,
983 ) {1178 ) {
984 let (grain_min, grain_max) = grain_range(fctx);1179 let (grain_min, grain_max) = grain_range(fctx);
985 if height == 1 {1180 if height == 1 {
@@ -1029,7 +1224,8 @@ fn copy_area(
1029 src_row0: i32,1224 src_row0: i32,
1030 src_col0: i32,1225 src_col0: i32,
1031 width: i32,1226 width: i32,
1032- height: i32, fctx: &crate::decode::FrameCtx,1227+ height: i32,
1228+ fctx: &crate::decode::FrameCtx,
1033 ) {1229 ) {
1034 let (_grain_min, _grain_max) = grain_range(fctx);1230 let (_grain_min, _grain_max) = grain_range(fctx);
1035 for h in 0..height {1231 for h in 0..height {
@@ -1138,17 +1334,33 @@ pub(crate) fn apply_grain(
1138 picture: &Picture,1334 picture: &Picture,
1139 fg: &FilmGrainParams,1335 fg: &FilmGrainParams,
1140 mc_identity: bool,1336 mc_identity: bool,
1141- bit_depth: u32, fctx: &crate::decode::FrameCtx,1337+ bit_depth: u32,
1338+ fctx: &crate::decode::FrameCtx,
1142 ) -> Picture {1339 ) -> Picture {
1143 if !fg.apply_grain {1340 if !fg.apply_grain {
1144 return picture.clone();1341 return picture.clone();
1145 }1342 }
1146 fctx.grain_bit_depth.with(|c| c.set(bit_depth));1343 fctx.grain_bit_depth.with(|c| c.set(bit_depth));
1147 hit!(GRAIN_HITS);1344 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);
1148 let width = picture.width as i32;1351 let width = picture.width as i32;
1149 let height = picture.height as i32;1352 let height = picture.height as i32;
1150 let y_stride = width;1353 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.
1152 1364
1153 let lag = fg.ar_coeff_lag as i32;1365 let lag = fg.ar_coeff_lag as i32;
1154 let pred_luma = build_pred_pos(lag, false);1366 let pred_luma = build_pred_pos(lag, false);
@@ -1156,8 +1368,8 @@ pub(crate) fn apply_grain(
1156 1368
1157 let mut rng = Rng::raw(fg.grain_seed);1369 let mut rng = Rng::raw(fg.grain_seed);
1158 let luma_template = generate_luma_grain_block(fg, &pred_luma, &mut rng, fctx);1370 let luma_template = generate_luma_grain_block(fg, &pred_luma, &mut rng, fctx);
1159- let (cb_template, cr_template) =1371+ let (cb_template, cr_template, cg_stride) =
1160- generate_chroma_grain_blocks(fg, &pred_chroma, &luma_template, fg.grain_seed, fctx);1372+ generate_chroma_grain_blocks(fg, &pred_chroma, &luma_template, fg.grain_seed, ss, fctx);
1161 1373
1162 let scaling_y = build_scaling_lut(1374 let scaling_y = build_scaling_lut(
1163 &fg.point_y_value,1375 &fg.point_y_value,
@@ -1194,7 +1406,7 @@ pub(crate) fn apply_grain(
1194 // lane-filt1: 32-pixel block ROWS are the parallel axis. A row's noise1406 // lane-filt1: 32-pixel block ROWS are the parallel axis. A row's noise
1195 // offsets come from `Rng::line(y * 2, grain_seed)` -- a function of the1407 // offsets come from `Rng::line(y * 2, grain_seed)` -- a function of the
1196 // row and the frame seed alone -- and a row writes only luma rows1408 // 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. The1409+ // `y*2 >> ss_y .. +csub_y << (1 - ss_y)`), so rows are write-disjoint. The
1198 // one carry ACROSS rows is `*_line_buf` (the row above's bottom lines,1410 // one carry ACROSS rows is `*_line_buf` (the row above's bottom lines,
1199 // blended into this row's top lines when `overlap_flag`), and its final1411 // blended into this row's top lines when `overlap_flag`), and its final
1200 // content is written by that row's own blocks out of the grain templates1412 // content is written by that row's own blocks out of the grain templates
@@ -1203,6 +1415,11 @@ pub(crate) fn apply_grain(
1203 // to rebuild the line buffers, then codes its own rows exactly as the1415 // to rebuild the line buffers, then codes its own rows exactly as the
1204 // single-threaded walk does.1416 // single-threaded walk does.
1205 let row_step = LUMA_SUBBLOCK >> 1;1417 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;
1206 let nrows = ((height / 2).max(0) as usize).div_ceil(row_step as usize);1423 let nrows = ((height / 2).max(0) as usize).div_ceil(row_step as usize);
1207 let gbands = crate::par::bands(nrows, crate::par::filter_threads());1424 let gbands = crate::par::bands(nrows, crate::par::filter_threads());
1208 // lane-grain2: the clean picture used to be cloned here, on the frame1425 // lane-grain2: the clean picture used to be cloned here, on the frame
@@ -1211,8 +1428,16 @@ pub(crate) fn apply_grain(
1211 // walk. The bands own a partition of the plane rows, so each band copies1428 // walk. The bands own a partition of the plane rows, so each band copies
1212 // its OWN rows out of the clean source and adds noise to them: the copy1429 // its OWN rows out of the clean source and adds noise to them: the copy
1213 // moves onto the filter pool and the destination never needs zeroing.1430 // 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 };1431+ let y_rows = if y_stride > 0 {
1215- let c_rows = if c_stride > 0 { picture.u.len() / c_stride as usize } else { 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+ };
1216 let banded = !gbands.is_empty() && y_stride > 0 && c_stride > 0;1441 let banded = !gbands.is_empty() && y_stride > 0 && c_stride > 0;
1217 let mut out = if banded {1442 let mut out = if banded {
1218 Picture {1443 Picture {
@@ -1240,23 +1465,44 @@ pub(crate) fn apply_grain(
1240 // the rows the kernels then read back are still in this core's cache.1465 // the rows the kernels then read back are still in this core's cache.
1241 let ys = y_stride as usize;1466 let ys = y_stride as usize;
1242 let cs = c_stride as usize;1467 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) };1468+ let c_end = if b_hi == nrows {
1244- let l_end =1469+ c_rows
1245- if b_hi == nrows { y_rows } else { (2 * b_hi * row_step as usize).min(y_rows) };1470+ } else {
1246- let mut ccur = (b_lo * row_step as usize).min(c_rows);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);
1247 let mut lcur = (2 * b_lo * row_step as usize).min(y_rows);1479 let mut lcur = (2 * b_lo * row_step as usize).min(y_rows);
1248 let y_lo = (b_lo * row_step as usize) as i32;1480 let y_lo = (b_lo * row_step as usize) as i32;
1249 let y_hi = ((b_hi * row_step as usize) as i32).min(height / 2);1481 let y_hi = ((b_hi * row_step as usize) as i32).min(height / 2);
1250 let y_first = if b_lo > 0 { y_lo - row_step } else { y_lo };1482 let y_first = if b_lo > 0 { y_lo - row_step } else { y_lo };
1251 let mut y_line_buf = vec![0i32; (y_stride * 2).max(1) as usize];1483 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];1484+ // lane-av1422grain: the line and column buffers are per-axis, as the C's
1253- let mut cr_line_buf = vec![0i32; c_stride.max(1) as usize];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];
1254 let mut y_col_buf = vec![0i32; ((LUMA_SUBBLOCK + 2) * 2) as usize];1490 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];1491+ let cb_col_len = ((csub_y + ss.two_y()) * ss.two_x()).max(1) as usize;
1256- let mut cr_col_buf = vec![0i32; (CHROMA_SUBBLOCK + 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;
1257 let mut y_blk = vec![0i32; (LUMA_SUBBLOCK * LUMA_SUBBLOCK) as usize];1503 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];1504+ let mut cb_blk = vec![0i32; cblk_stride * cblk_rows];
1259- let mut cr_blk = vec![0i32; (CHROMA_SUBBLOCK * CHROMA_SUBBLOCK) as usize];1505+ let mut cr_blk = vec![0i32; cblk_stride * cblk_rows];
1260 1506
1261 let mut y = y_first;1507 let mut y = y_first;
1262 while y < y_hi {1508 while y < y_hi {
@@ -1269,9 +1515,13 @@ pub(crate) fn apply_grain(
1269 &mut lcur,1515 &mut lcur,
1270 &mut ccur,1516 &mut ccur,
1271 (2 * (y as usize + row_step as usize)).min(l_end),1517 (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),
1273 );1519 );
1274 let mut row_rng = Rng::line(y * 2, fg.grain_seed);1520 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.
1275 let mut x = 0;1525 let mut x = 0;
1276 while x < width / 2 {1526 while x < width / 2 {
1277 let raw = row_rng.get(8);1527 let raw = row_rng.get(8);
@@ -1280,8 +1530,11 @@ pub(crate) fn apply_grain(
1280 1530
1281 let luma_off_y = LEFT_PAD + 2 * AR_PADDING + (offset_y << 1);1531 let luma_off_y = LEFT_PAD + 2 * AR_PADDING + (offset_y << 1);
1282 let luma_off_x = TOP_PAD + 2 * AR_PADDING + (offset_x << 1);1532 let luma_off_x = TOP_PAD + 2 * AR_PADDING + (offset_x << 1);
1283- let chroma_off_y = TOP_PAD + AR_PADDING + offset_y;1533+ // `chroma_offset_y = top_pad + (2 >> chroma_subsamp_y) *
1284- let chroma_off_x = LEFT_PAD + AR_PADDING + offset_x;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();
1285 1538
1286 if overlap && x != 0 {1539 if overlap && x != 0 {
1287 let h_count = (LUMA_SUBBLOCK + 2).min(height - (y << 1));1540 let h_count = (LUMA_SUBBLOCK + 2).min(height - (y << 1));
@@ -1295,34 +1548,40 @@ pub(crate) fn apply_grain(
1295 luma_off_y,1548 luma_off_y,
1296 luma_off_x,1549 luma_off_x,
1297 2,1550 2,
1298- h_count, fctx,1551+ h_count,
1552+ fctx,
1299 );1553 );
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);
1301 ver_overlap_inplace(1559 ver_overlap_inplace(
1302 &mut cb_col_buf,1560 &mut cb_col_buf,
1303- 1,1561+ ss.two_x(),
1304 0,1562 0,
1305 0,1563 0,
1306 &cb_template,1564 &cb_template,
1307- CHROMA_BLOCK_W,1565+ cg_stride,
1308 chroma_off_y,1566 chroma_off_y,
1309 chroma_off_x,1567 chroma_off_x,
1310- 1,1568+ ss.two_x(),
1311- hc_count, fctx,1569+ hc_count,
1570+ fctx,
1312 );1571 );
1313 ver_overlap_inplace(1572 ver_overlap_inplace(
1314 &mut cr_col_buf,1573 &mut cr_col_buf,
1315- 1,1574+ ss.two_x(),
1316 0,1575 0,
1317 0,1576 0,
1318 &cr_template,1577 &cr_template,
1319- CHROMA_BLOCK_W,1578+ cg_stride,
1320 chroma_off_y,1579 chroma_off_y,
1321 chroma_off_x,1580 chroma_off_x,
1322- 1,1581+ ss.two_x(),
1323- hc_count, fctx,1582+ hc_count,
1583+ fctx,
1324 );1584 );
1325-
1326 }1585 }
1327 1586
1328 if overlap && y != 0 {1587 if overlap && y != 0 {
@@ -1337,35 +1596,43 @@ pub(crate) fn apply_grain(
1337 0,1596 0,
1338 0,1597 0,
1339 2,1598 2,
1340- 2, fctx,1599+ 2,
1600+ fctx,
1341 );1601 );
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);
1342 hor_overlap_inplace(1607 hor_overlap_inplace(
1343 &mut cb_line_buf,1608 &mut cb_line_buf,
1344 c_stride,1609 c_stride,
1345 0,1610 0,
1346- x,1611+ ccol_x,
1347 &cb_col_buf,1612 &cb_col_buf,
1348- 1,1613+ ss.two_x(),
1349 0,1614 0,
1350 0,1615 0,
1351- 1,1616+ ss.two_x(),
1352- 1, fctx,1617+ ss.two_y(),
1618+ fctx,
1353 );1619 );
1354 hor_overlap_inplace(1620 hor_overlap_inplace(
1355 &mut cr_line_buf,1621 &mut cr_line_buf,
1356 c_stride,1622 c_stride,
1357 0,1623 0,
1358- x,1624+ ccol_x,
1359 &cr_col_buf,1625 &cr_col_buf,
1360- 1,1626+ ss.two_x(),
1361 0,1627 0,
1362 0,1628 0,
1363- 1,1629+ ss.two_x(),
1364- 1, fctx,1630+ ss.two_y(),
1631+ fctx,
1365 );1632 );
1366 }1633 }
1367 let lcol0 = if x != 0 { (x + 1) << 1 } else { 0 };1634 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 };
1369 let lw = (LUMA_SUBBLOCK - (if x != 0 { 2 } else { 0 })).min(width - lcol0);1636 let lw = (LUMA_SUBBLOCK - (if x != 0 { 2 } else { 0 })).min(width - lcol0);
1370 hor_overlap_inplace(1637 hor_overlap_inplace(
1371 &mut y_line_buf,1638 &mut y_line_buf,
@@ -1377,20 +1644,31 @@ pub(crate) fn apply_grain(
1377 luma_off_y,1644 luma_off_y,
1378 luma_off_x + if x != 0 { 2 } else { 0 },1645 luma_off_x + if x != 0 { 2 } else { 0 },
1379 lw,1646 lw,
1380- 2, fctx,1647+ 2,
1648+ fctx,
1381 );1649 );
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);
1383 hor_overlap_inplace(1660 hor_overlap_inplace(
1384 &mut cb_line_buf,1661 &mut cb_line_buf,
1385 c_stride,1662 c_stride,
1386 0,1663 0,
1387 ccol0,1664 ccol0,
1388 &cb_template,1665 &cb_template,
1389- CHROMA_BLOCK_W,1666+ cg_stride,
1390 chroma_off_y,1667 chroma_off_y,
1391- chroma_off_x + if x != 0 { 1 } else { 0 },1668+ chroma_off_x + cskip,
1392 cw,1669 cw,
1393- 1, fctx,1670+ ss.two_y(),
1671+ fctx,
1394 );1672 );
1395 hor_overlap_inplace(1673 hor_overlap_inplace(
1396 &mut cr_line_buf,1674 &mut cr_line_buf,
@@ -1398,13 +1676,13 @@ pub(crate) fn apply_grain(
1398 0,1676 0,
1399 ccol0,1677 ccol0,
1400 &cr_template,1678 &cr_template,
1401- CHROMA_BLOCK_W,1679+ cg_stride,
1402 chroma_off_y,1680 chroma_off_y,
1403- chroma_off_x + if x != 0 { 1 } else { 0 },1681+ chroma_off_x + cskip,
1404 cw,1682 cw,
1405- 1, fctx,1683+ ss.two_y(),
1684+ fctx,
1406 );1685 );
1407-
1408 }1686 }
1409 1687
1410 let i = if overlap && y != 0 { 1 } else { 0 };1688 let i = if overlap && y != 0 { 1 } else { 0 };
@@ -1416,6 +1694,7 @@ pub(crate) fn apply_grain(
1416 add_noise_to_block(1694 add_noise_to_block(
1417 fg,1695 fg,
1418 mc_identity,1696 mc_identity,
1697+ ss,
1419 &scaling_y,1698 &scaling_y,
1420 &scaling_cb,1699 &scaling_cb,
1421 &scaling_cr,1700 &scaling_cr,
@@ -1428,11 +1707,12 @@ pub(crate) fn apply_grain(
1428 luma_off_x,1707 luma_off_x,
1429 &cb_template,1708 &cb_template,
1430 &cr_template,1709 &cr_template,
1431- CHROMA_BLOCK_W,1710+ cg_stride,
1432 chroma_off_y,1711 chroma_off_y,
1433 chroma_off_x,1712 chroma_off_x,
1434 bh,1713 bh,
1435- bw, fctx,1714+ bw,
1715+ fctx,
1436 );1716 );
1437 } else {1717 } else {
1438 // lane-grainrow: the overlap line and the overlap1718 // lane-grainrow: the overlap line and the overlap
@@ -1442,11 +1722,23 @@ pub(crate) fn apply_grain(
1442 // AVX2 kernel handed the 3-sample tail of every row1722 // AVX2 kernel handed the 3-sample tail of every row
1443 // back to the scalar loop. A 4K cut spent 2.19e9 calls1723 // back to the scalar loop. A 4K cut spent 2.19e9 calls
1444 // on 4.4e9 such samples. Assembling the three noise1724 // on 4.4e9 such samples. Assembling the three noise
1445- // sources into one 32x32 block (16x16 chroma) first1725+ // sources into one block first makes it one kernel call
1446- // makes it one kernel call per block over a width that1726+ // per block over a width that is a multiple of 8, with
1447- // is a multiple of 8, with no scalar remainder. Every1727+ // no scalar remainder. Every sample keeps the value its
1448- // sample keeps the value its own source gave it, so the1728+ // own source gave it, so the picture is bit-identical.
1449- // 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;
1450 if apply_y {1742 if apply_y {
1451 assemble_block_noise(1743 assemble_block_noise(
1452 &mut y_blk,1744 &mut y_blk,
@@ -1468,17 +1760,17 @@ pub(crate) fn apply_grain(
1468 if apply_cb {1760 if apply_cb {
1469 assemble_block_noise(1761 assemble_block_noise(
1470 &mut cb_blk,1762 &mut cb_blk,
1471- CHROMA_SUBBLOCK as usize,1763+ cblk_stride,
1472- bh as usize,1764+ cch,
1473- bw as usize,1765+ ccw,
1474 &cb_line_buf,1766 &cb_line_buf,
1475 c_stride as usize,1767 c_stride as usize,
1476- x as usize,1768+ ccol_x,
1477- i as usize,1769+ ctop,
1478 &cb_col_buf,1770 &cb_col_buf,
1479- j as usize,1771+ cwide,
1480 &cb_template,1772 &cb_template,
1481- CHROMA_BLOCK_W as usize,1773+ cg_stride as usize,
1482 chroma_off_y as usize,1774 chroma_off_y as usize,
1483 chroma_off_x as usize,1775 chroma_off_x as usize,
1484 );1776 );
@@ -1486,17 +1778,17 @@ pub(crate) fn apply_grain(
1486 if apply_cr {1778 if apply_cr {
1487 assemble_block_noise(1779 assemble_block_noise(
1488 &mut cr_blk,1780 &mut cr_blk,
1489- CHROMA_SUBBLOCK as usize,1781+ cblk_stride,
1490- bh as usize,1782+ cch,
1491- bw as usize,1783+ ccw,
1492 &cr_line_buf,1784 &cr_line_buf,
1493 c_stride as usize,1785 c_stride as usize,
1494- x as usize,1786+ ccol_x,
1495- i as usize,1787+ ctop,
1496 &cr_col_buf,1788 &cr_col_buf,
1497- j as usize,1789+ cwide,
1498 &cr_template,1790 &cr_template,
1499- CHROMA_BLOCK_W as usize,1791+ cg_stride as usize,
1500 chroma_off_y as usize,1792 chroma_off_y as usize,
1501 chroma_off_x as usize,1793 chroma_off_x as usize,
1502 );1794 );
@@ -1504,6 +1796,7 @@ pub(crate) fn apply_grain(
1504 add_noise_to_block(1796 add_noise_to_block(
1505 fg,1797 fg,
1506 mc_identity,1798 mc_identity,
1799+ ss,
1507 &scaling_y,1800 &scaling_y,
1508 &scaling_cb,1801 &scaling_cb,
1509 &scaling_cr,1802 &scaling_cr,
@@ -1516,11 +1809,12 @@ pub(crate) fn apply_grain(
1516 0,1809 0,
1517 &cb_blk,1810 &cb_blk,
1518 &cr_blk,1811 &cr_blk,
1519- CHROMA_SUBBLOCK,1812+ cblk_stride as i32,
1520 0,1813 0,
1521 0,1814 0,
1522 bh,1815 bh,
1523- bw, fctx,1816+ bw,
1817+ fctx,
1524 );1818 );
1525 }1819 }
1526 }1820 }
@@ -1537,37 +1831,56 @@ pub(crate) fn apply_grain(
1537 LUMA_SUBBLOCK,1831 LUMA_SUBBLOCK,
1538 0,1832 0,
1539 2,1833 2,
1540- 2, fctx,1834+ 2,
1835+ fctx,
1541 );1836 );
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.
1542 copy_area(1853 copy_area(
1543 &mut cb_line_buf,1854 &mut cb_line_buf,
1544 c_stride,1855 c_stride,
1545 0,1856 0,
1546- x,1857+ x << (1 - ss.x),
1547 &cb_col_buf,1858 &cb_col_buf,
1548- 1,1859+ ss.two_x(),
1549- CHROMA_SUBBLOCK,1860+ csub_y,
1550 0,1861 0,
1551- 1,1862+ ss.two_x(),
1552- 1, fctx,1863+ ss.two_y(),
1864+ fctx,
1553 );1865 );
1554 copy_area(1866 copy_area(
1555 &mut cr_line_buf,1867 &mut cr_line_buf,
1556 c_stride,1868 c_stride,
1557 0,1869 0,
1558- x,1870+ x << (1 - ss.x),
1559 &cr_col_buf,1871 &cr_col_buf,
1560- 1,1872+ ss.two_x(),
1561- CHROMA_SUBBLOCK,1873+ csub_y,
1562 0,1874 0,
1563- 1,1875+ ss.two_x(),
1564- 1, fctx,1876+ ss.two_y(),
1877+ fctx,
1565 );1878 );
1566 }1879 }
1567 let lcol0 = if x != 0 { (x + 1) << 1 } else { 0 };1880 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 };
1569 let lcut = if x != 0 { 2 } else { 0 };1882 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 };
1571 copy_area(1884 copy_area(
1572 &mut y_line_buf,1885 &mut y_line_buf,
1573 y_stride,1886 y_stride,
@@ -1578,19 +1891,30 @@ pub(crate) fn apply_grain(
1578 luma_off_y + LUMA_SUBBLOCK,1891 luma_off_y + LUMA_SUBBLOCK,
1579 luma_off_x + lcut,1892 luma_off_x + lcut,
1580 LUMA_SUBBLOCK.min(width - (x << 1)) - lcut,1893 LUMA_SUBBLOCK.min(width - (x << 1)) - lcut,
1581- 2, fctx,1894+ 2,
1895+ fctx,
1582 );1896 );
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;
1583 copy_area(1906 copy_area(
1584 &mut cb_line_buf,1907 &mut cb_line_buf,
1585 c_stride,1908 c_stride,
1586 0,1909 0,
1587 ccol0,1910 ccol0,
1588 &cb_template,1911 &cb_template,
1589- CHROMA_BLOCK_W,1912+ cg_stride,
1590- chroma_off_y + CHROMA_SUBBLOCK,1913+ chroma_off_y + csub_y,
1591 chroma_off_x + ccut,1914 chroma_off_x + ccut,
1592- CHROMA_SUBBLOCK.min((width - (x << 1)) >> 1) - ccut,1915+ cgw,
1593- 1, fctx,1916+ ss.two_y(),
1917+ fctx,
1594 );1918 );
1595 copy_area(1919 copy_area(
1596 &mut cr_line_buf,1920 &mut cr_line_buf,
@@ -1598,14 +1922,20 @@ pub(crate) fn apply_grain(
1598 0,1922 0,
1599 ccol0,1923 ccol0,
1600 &cr_template,1924 &cr_template,
1601- CHROMA_BLOCK_W,1925+ cg_stride,
1602- chroma_off_y + CHROMA_SUBBLOCK,1926+ chroma_off_y + csub_y,
1603 chroma_off_x + ccut,1927 chroma_off_x + ccut,
1604- CHROMA_SUBBLOCK.min((width - (x << 1)) >> 1) - ccut,1928+ cgw,
1605- 1, fctx,1929+ ss.two_y(),
1930+ fctx,
1606 );1931 );
1607 1932
1608 let h_count = (LUMA_SUBBLOCK + 2).min(height - (y << 1));1933 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);
1609 copy_area(1939 copy_area(
1610 &mut y_col_buf,1940 &mut y_col_buf,
1611 2,1941 2,
@@ -1616,32 +1946,41 @@ pub(crate) fn apply_grain(
1616 luma_off_y,1946 luma_off_y,
1617 luma_off_x + LUMA_SUBBLOCK,1947 luma_off_x + LUMA_SUBBLOCK,
1618 2,1948 2,
1619- h_count, fctx,1949+ h_count,
1950+ fctx,
1620 );1951 );
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`).
1622 copy_area(1959 copy_area(
1623 &mut cb_col_buf,1960 &mut cb_col_buf,
1624- 1,1961+ ss.two_x(),
1625 0,1962 0,
1626 0,1963 0,
1627 &cb_template,1964 &cb_template,
1628- CHROMA_BLOCK_W,1965+ cg_stride,
1629 chroma_off_y,1966 chroma_off_y,
1630- chroma_off_x + CHROMA_SUBBLOCK,1967+ chroma_off_x + csub_x,
1631- 1,1968+ ss.two_x(),
1632- hc_count, fctx,1969+ hc_count,
1970+ fctx,
1633 );1971 );
1634 copy_area(1972 copy_area(
1635 &mut cr_col_buf,1973 &mut cr_col_buf,
1636- 1,1974+ ss.two_x(),
1637 0,1975 0,
1638 0,1976 0,
1639 &cr_template,1977 &cr_template,
1640- CHROMA_BLOCK_W,1978+ cg_stride,
1641 chroma_off_y,1979 chroma_off_y,
1642- chroma_off_x + CHROMA_SUBBLOCK,1980+ chroma_off_x + csub_x,
1643- 1,1981+ ss.two_x(),
1644- hc_count, fctx,1982+ hc_count,
1983+ fctx,
1645 );1984 );
1646 }1985 }
1647 1986
@@ -1681,17 +2020,30 @@ mod perf5_tests {
1681 let rounding_offset = 1i32 << (scaling_shift - 1);2020 let rounding_offset = 1i32 << (scaling_shift - 1);
1682 for &(lo, hi) in &[(0i32, sample_max as i32), (16 << bd_shift, 235 << bd_shift)] {2021 for &(lo, hi) in &[(0i32, sample_max as i32), (16 << bd_shift, 235 << bd_shift)] {
1683 for len in [1usize, 4, 7, 8, 9, 16, 31, 32, 64, 128] {2022 for len in [1usize, 4, 7, 8, 9, 16, 31, 32, 64, 128] {
1684- let pixels: Vec<u16> =2023+ let pixels: Vec<u16> = (0..len)
1685- (0..len).map(|_| (rng() % (u64::from(sample_max) + 1)) as u16).collect();2024+ .map(|_| (rng() % (u64::from(sample_max) + 1)) as u16)
2025+ .collect();
1686 let grain: Vec<i32> =2026 let grain: Vec<i32> =
1687 (0..len).map(|_| (rng() % 513) as i32 - 256).collect();2027 (0..len).map(|_| (rng() % 513) as i32 - 256).collect();
1688 let mut want = pixels.clone();2028 let mut want = pixels.clone();
1689 super::luma_noise_row_scalar(2029 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,
1691 );2037 );
1692 let mut got = pixels.clone();2038 let mut got = pixels.clone();
1693 super::luma_noise_row(2039 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,
1695 );2047 );
1696 assert_eq!(got, want, "dispatch len={len} shift={scaling_shift}");2048 assert_eq!(got, want, "dispatch len={len} shift={scaling_shift}");
1697 #[cfg(target_arch = "x86_64")]2049 #[cfg(target_arch = "x86_64")]
@@ -1700,8 +2052,13 @@ mod perf5_tests {
1700 #[allow(unsafe_code)]2052 #[allow(unsafe_code)]
1701 unsafe {2053 unsafe {
1702 super::simd::luma_noise_row_avx2(2054 super::simd::luma_noise_row_avx2(
1703- &mut avx, &grain, &scaling, rounding_offset, scaling_shift,2055+ &mut avx,
1704- lo, hi,2056+ &grain,
2057+ &scaling,
2058+ rounding_offset,
2059+ scaling_shift,
2060+ lo,
2061+ hi,
1705 )2062 )
1706 };2063 };
1707 assert_eq!(avx, want, "avx2 len={len} shift={scaling_shift}");2064 assert_eq!(avx, want, "avx2 len={len} shift={scaling_shift}");
@@ -1740,9 +2097,7 @@ mod perf5_tests {
1740 (-128, 127, -(1 << (8 + bd_shift))),2097 (-128, 127, -(1 << (8 + bd_shift))),
1741 (17, -64, 42),2098 (17, -64, 42),
1742 ] {2099 ] {
1743- for &(lo, hi) in2100+ for &(lo, hi) in &[(0i32, index_max), (16 << bd_shift, 240 << bd_shift)] {
1744- &[(0i32, index_max), (16 << bd_shift, 240 << bd_shift)]
1745- {
1746 for len in [1usize, 5, 8, 9, 16, 17, 32] {2101 for len in [1usize, 5, 8, 9, 16, 17, 32] {
1747 let p = super::ChromaNoise {2102 let p = super::ChromaNoise {
1748 index_max,2103 index_max,
@@ -1762,6 +2117,7 @@ mod perf5_tests {
1762 let mut want = chroma.clone();2117 let mut want = chroma.clone();
1763 super::chroma_noise_row_scalar(2118 super::chroma_noise_row_scalar(
1764 &mut want, &luma, &grain, &scaling, luma_mult, mult, offset, p,2119 &mut want, &luma, &grain, &scaling, luma_mult, mult, offset, p,
2120+ true,
1765 );2121 );
1766 let mut got = chroma.clone();2122 let mut got = chroma.clone();
1767 super::chroma_noise_row(2123 super::chroma_noise_row(
@@ -1774,8 +2130,8 @@ mod perf5_tests {
1774 #[allow(unsafe_code)]2130 #[allow(unsafe_code)]
1775 unsafe {2131 unsafe {
1776 super::simd::chroma_noise_row_avx2(2132 super::simd::chroma_noise_row_avx2(
1777- &mut avx, &luma, &grain, &scaling, luma_mult, mult,2133+ &mut avx, &luma, &grain, &scaling, luma_mult, mult, offset,
1778- offset, p,2134+ p,
1779 )2135 )
1780 };2136 };
1781 assert_eq!(avx, want, "avx2 len={len} mult={mult}");2137 assert_eq!(avx, want, "avx2 len={len} mult={mult}");
@@ -1807,8 +2163,12 @@ mod grain2_tests {
1807 width: w,2163 width: w,
1808 height: h,2164 height: h,
1809 y: (0..w * h).map(|i| ((i * 7 + 3) % 256) as u16).collect(),2165 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(),2166+ u: (0..w * h / 4)
1811- v: (0..w * h / 4).map(|i| ((i * 13 + 9) % 256) as u16).collect(),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(),
1812 };2172 };
1813 let mut fg = FilmGrainParams {2173 let mut fg = FilmGrainParams {
1814 apply_grain: true,2174 apply_grain: true,
@@ -1827,7 +2187,10 @@ mod grain2_tests {
1827 fg.point_cb_scaling[..2].copy_from_slice(&[40, 60]);2187 fg.point_cb_scaling[..2].copy_from_slice(&[40, 60]);
1828 let fctx = crate::decode::FrameCtx::new();2188 let fctx = crate::decode::FrameCtx::new();
1829 let out = apply_grain(&src, &fg, false, 8, &fctx);2189 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+ );
1831 assert_eq!(out.v, src.v, "no cr points: the V plane is the clean copy");2194 assert_eq!(out.v, src.v, "no cr points: the V plane is the clean copy");
1832 assert_ne!(out.u, src.u, "cb grain landed on the U plane");2195 assert_ne!(out.u, src.u, "cb grain landed on the U plane");
1833 2196
@@ -1837,7 +2200,10 @@ mod grain2_tests {
1837 fg2.point_y_scaling[..2].copy_from_slice(&[50, 70]);2200 fg2.point_y_scaling[..2].copy_from_slice(&[50, 70]);
1838 let out2 = apply_grain(&src, &fg2, false, 8, &fctx);2201 let out2 = apply_grain(&src, &fg2, false, 8, &fctx);
1839 assert_ne!(out2.y, src.y, "luma grain landed");2202 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+ );
1841 assert_eq!(out2.y.len(), w * h, "the ragged tail row is present");2207 assert_eq!(out2.y.len(), w * h, "the ragged tail row is present");
1842 }2208 }
1843 }2209 }
@@ -1850,25 +2216,45 @@ mod ragged_grain_tests {
1850 (x + (1 << (n - 1))) >> n2216 (x + (1 << (n - 1))) >> n
1851 }2217 }
1852 2218
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)]
1854 fn chroma_stripe_block(2229 fn chroma_stripe_block(
1855 st: &mut [i32],2230 st: &mut [i32],
1856 tpl: &[i32],2231 tpl: &[i32],
2232+ tp_stride: i32,
1857 coy: i32,2233 coy: i32,
1858 cox: i32,2234 cox: i32,
1859 x: i32,2235 x: i32,
1860 cw: i32,2236 cw: i32,
2237+ rows: i32,
2238+ cols: i32,
2239+ skip: i32,
1861 overlap: bool,2240 overlap: bool,
1862 gmin: i32,2241 gmin: i32,
1863 gmax: i32,2242 gmax: i32,
1864 ) {2243 ) {
1865- for i in 0..17 {2244+ for i in 0..rows {
1866- for j in 0..17 {2245+ for j in 0..cols {
1867 let col = x + j;2246 let col = x + j;
1868- let mut g = tpl[((coy + i) * CHROMA_BLOCK_W + cox + j) as usize];2247+ let mut g = tpl[((coy + i) * tp_stride + cox + j) as usize];
1869- if overlap && x > 0 && j < 1 {2248+ if overlap && x > 0 && j < skip {
1870 let old = st[(i * cw + col) as usize];2249 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);
1872 }2258 }
1873 if col < cw {2259 if col < cw {
1874 st[(i * cw + col) as usize] = g;2260 st[(i * cw + col) as usize] = g;
@@ -1884,10 +2270,22 @@ mod ragged_grain_tests {
1884 /// pixel kernels (which are not what this test exercises). 8-bit, 4:2:0,2270 /// pixel kernels (which are not what this test exercises). 8-bit, 4:2:0,
1885 /// `clip_to_restricted_range == false`.2271 /// `clip_to_restricted_range == false`.
1886 fn reference(src: &Picture, fg: &FilmGrainParams, fctx: &crate::decode::FrameCtx) -> Picture {2272 fn reference(src: &Picture, fg: &FilmGrainParams, fctx: &crate::decode::FrameCtx) -> Picture {
2273+ let ss = Ss::read(fctx);
1887 let w = src.width as i32;2274 let w = src.width as i32;
1888 let h = src.height as i32;2275 let h = src.height as i32;
1889- let cw = w / 2;2276+ // lane-av1422grain: the reference walks LUMA units exactly as the C's
1890- let ch = h / 2;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;
1891 let (gmin, gmax) = grain_range(fctx);2289 let (gmin, gmax) = grain_range(fctx);
1892 let overlap = fg.overlap_flag;2290 let overlap = fg.overlap_flag;
1893 2291
@@ -1895,32 +2293,48 @@ mod ragged_grain_tests {
1895 let pl = build_pred_pos(fg.ar_coeff_lag as i32, false);2293 let pl = build_pred_pos(fg.ar_coeff_lag as i32, false);
1896 let pc = build_pred_pos(fg.ar_coeff_lag as i32, fg.num_y_points > 0);2294 let pc = build_pred_pos(fg.ar_coeff_lag as i32, fg.num_y_points > 0);
1897 let lt = generate_luma_grain_block(fg, &pl, &mut rng, fctx);2295 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);
1899 2298
1900 let mut nl = vec![0i32; (w * h) as usize];2299 let mut nl = vec![0i32; (w * h) as usize];
1901 let mut ncb = vec![0i32; (cw * ch) as usize];2300 let mut ncb = vec![0i32; (cw * ch) as usize];
1902 let mut ncr = vec![0i32; (cw * ch) as usize];2301 let mut ncr = vec![0i32; (cw * ch) as usize];
1903 let mut prev: Option<(Vec<i32>, Vec<i32>, Vec<i32>)> = None;2302 let mut prev: Option<(Vec<i32>, Vec<i32>, Vec<i32>)> = None;
1904 let mut y = 0;2303 let mut y = 0;
1905- while y < ch {2304+ while y < h / 2 {
1906 let mut row_rng = Rng::line(y * 2, fg.grain_seed);2305 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);
1907 let mut sl = vec![0i32; (34 * w) as usize];2311 let mut sl = vec![0i32; (34 * w) as usize];
1908- let mut scb = vec![0i32; (17 * cw) as usize];2312+ let mut scb = vec![0i32; (crows * cw) as usize];
1909- let mut scr = vec![0i32; (17 * cw) as usize];2313+ let mut scr = vec![0i32; (crows * cw) as usize];
1910 let mut x = 0;2314 let mut x = 0;
1911- while x < cw {2315+ while x < w / 2 {
1912 let raw = row_rng.get(8);2316 let raw = row_rng.get(8);
1913 let ox = (raw >> 4) & 15;2317 let ox = (raw >> 4) & 15;
1914 let oy = raw & 15;2318 let oy = raw & 15;
1915- let (loy, lox) = (9 + 2 * oy, 9 + 2 * ox);2319+ let (loy, lox) = (
1916- let (coy, cox) = (6 + oy, 6 + ox);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+ );
1917 for i in 0..34 {2327 for i in 0..34 {
1918 for j in 0..34 {2328 for j in 0..34 {
1919 let col = x * 2 + j;2329 let col = x * 2 + j;
1920 let mut g = lt[((loy + i) * LUMA_BLOCK_W + lox + j) as usize];2330 let mut g = lt[((loy + i) * LUMA_BLOCK_W + lox + j) as usize];
1921 if overlap && x > 0 && j < 2 {2331 if overlap && x > 0 && j < 2 {
1922 let old = sl[(i * w + col) as usize];2332 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+ };
1924 g = round2(g, 5).clamp(gmin, gmax);2338 g = round2(g, 5).clamp(gmin, gmax);
1925 }2339 }
1926 if col < w {2340 if col < w {
@@ -1928,11 +2342,44 @@ mod ragged_grain_tests {
1928 }2342 }
1929 }2343 }
1930 }2344 }
1931- chroma_stripe_block(&mut scb, &cbt, coy, cox, x, cw, overlap, gmin, gmax);2345+ // The stripe block spans `cblk_rows + (2 >> ss_y)` rows -- the
1932- chroma_stripe_block(&mut scr, &crt, coy, cox, x, cw, overlap, gmin, gmax);2346+ // trailing `2 >> ss_y` are the rows the NEXT block row's
1933- x += 16;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;
1934 }2381 }
1935- for i in 0..32 {2382+ for i in 0..(LUMA_SUBBLOCK >> 1) * 2 {
1936 let row = y * 2 + i;2383 let row = y * 2 + i;
1937 if row >= h {2384 if row >= h {
1938 break;2385 break;
@@ -1942,31 +2389,56 @@ mod ragged_grain_tests {
1942 if overlap && i < 2 {2389 if overlap && i < 2 {
1943 if let Some((p, _, _)) = &prev {2390 if let Some((p, _, _)) = &prev {
1944 let old = p[((i + 32) * w + col) as usize];2391 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+ };
1946 g = round2(g, 5).clamp(gmin, gmax);2397 g = round2(g, 5).clamp(gmin, gmax);
1947 }2398 }
1948 }2399 }
1949 nl[(row * w + col) as usize] = g;2400 nl[(row * w + col) as usize] = g;
1950 }2401 }
1951 }2402 }
1952- for i in 0..16 {2403+ let cy0 = chroma_row(y);
1953- let row = y + i;2404+ for i in 0..cblk_rows {
2405+ let row = cy0 + i;
1954 if row >= ch {2406 if row >= ch {
1955 break;2407 break;
1956 }2408 }
1957 for col in 0..cw {2409 for col in 0..cw {
1958 for (st, img) in [(&scb, &mut ncb), (&scr, &mut ncr)] {2410 for (st, img) in [(&scb, &mut ncb), (&scr, &mut ncr)] {
1959 let mut g = st[(i * cw + col) as usize];2411 let mut g = st[(i * cw + col) as usize];
1960- if overlap && i < 1 {2412+ if overlap && i < (2 >> ss.y) {
1961 let old = match &prev {2413 let old = match &prev {
1962 Some((_, pb, pr)) => {2414 Some((_, pb, pr)) => {
1963- let p = if std::ptr::eq(st.as_ptr(), scb.as_ptr()) { pb } else { pr };2415+ let p = if std::ptr::eq(st.as_ptr(), scb.as_ptr()) {
1964- Some(p[((i + 16) * cw + col) as usize])2416+ pb
2417+ } else {
2418+ pr
2419+ };
2420+ Some(p[((i + cblk_rows) * cw + col) as usize])
1965 }2421 }
1966 None => None,2422 None => None,
1967 };2423 };
1968 if let Some(old) = old {2424 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);
1970 }2442 }
1971 }2443 }
1972 img[(row * cw + col) as usize] = g;2444 img[(row * cw + col) as usize] = g;
@@ -1974,20 +2446,32 @@ mod ragged_grain_tests {
1974 }2446 }
1975 }2447 }
1976 prev = Some((sl, scb, scr));2448 prev = Some((sl, scb, scr));
1977- y += 16;2449+ y += LUMA_SUBBLOCK >> 1;
1978 }2450 }
1979 2451
1980 let mut out = src.clone();2452 let mut out = src.clone();
1981 let sy = expand_scaling_lut(2453 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+ ),
1983 8,2459 8,
1984 );2460 );
1985 let s_cb = expand_scaling_lut(2461 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+ ),
1987 8,2467 8,
1988 );2468 );
1989 let s_cr = expand_scaling_lut(2469 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+ ),
1991 8,2475 8,
1992 );2476 );
1993 let scaling_shift = fg.grain_scaling_minus_8 as i32 + 8;2477 let scaling_shift = fg.grain_scaling_minus_8 as i32 + 8;
@@ -2002,9 +2486,18 @@ mod ragged_grain_tests {
2002 // Chroma first, and out of the CLEAN luma: `add_noise_to_block` adds2486 // Chroma first, and out of the CLEAN luma: `add_noise_to_block` adds
2003 // the block's chroma noise before its luma noise, so no chroma2487 // the block's chroma noise before its luma noise, so no chroma
2004 // sample ever sees a noised luma neighbour.2488 // 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;
2005 for r in 0..ch {2493 for r in 0..ch {
2006 let (cs, ce) = ((r * cw) as usize, ((r + 1) * cw) as usize);2494 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+ );
2008 if fg.num_cb_points > 0 {2501 if fg.num_cb_points > 0 {
2009 chroma_noise_row_scalar(2502 chroma_noise_row_scalar(
2010 &mut out.u[cs..ce],2503 &mut out.u[cs..ce],
@@ -2015,6 +2508,7 @@ mod ragged_grain_tests {
2015 fg.cb_mult as i32 - 128,2508 fg.cb_mult as i32 - 128,
2016 fg.cb_offset as i32 - 256,2509 fg.cb_offset as i32 - 256,
2017 p,2510 p,
2511+ pair,
2018 );2512 );
2019 }2513 }
2020 if fg.num_cr_points > 0 {2514 if fg.num_cr_points > 0 {
@@ -2027,13 +2521,22 @@ mod ragged_grain_tests {
2027 fg.cr_mult as i32 - 128,2521 fg.cr_mult as i32 - 128,
2028 fg.cr_offset as i32 - 256,2522 fg.cr_offset as i32 - 256,
2029 p,2523 p,
2524+ pair,
2030 );2525 );
2031 }2526 }
2032 }2527 }
2033 if fg.num_y_points > 0 {2528 if fg.num_y_points > 0 {
2034 for r in 0..h {2529 for r in 0..h {
2035 let (ls, le) = ((r * w) as usize, (r * w + w) as usize);2530 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+ );
2037 }2540 }
2038 }2541 }
2039 out2542 out
@@ -2078,20 +2581,40 @@ mod ragged_grain_tests {
2078 let fctx = crate::decode::FrameCtx::new();2581 let fctx = crate::decode::FrameCtx::new();
2079 fctx.grain_bit_depth.with(|c| c.set(8));2582 fctx.grain_bit_depth.with(|c| c.set(8));
2080 let fg = params();2583 let fg = params();
2081- for &(w, h) in &[(64usize, 66usize), (66, 64), (64, 98), (48, 100)] {2584+ // lane-av1422grain: the same transcription, driven over every chroma
2082- let src = Picture {2585+ // format the module admits. Before this lane the geometry was 4:2:0
2083- width: w,2586+ // only, so 4:2:2 and 4:4:4 had NO coverage here at all -- and the
2084- height: h,2587+ // defect was silent (a wrong picture, never a panic), which is exactly
2085- y: (0..w * h).map(|i| ((i * 7 + 3) % 256) as u16).collect(),2588+ // why the reference had to become per-axis rather than gain a second
2086- u: (0..w / 2 * (h / 2)).map(|i| ((i * 11 + 5) % 256) as u16).collect(),2589+ // 4:2:0-shaped copy.
2087- v: (0..w / 2 * (h / 2)).map(|i| ((i * 13 + 9) % 256) as u16).collect(),2590+ for (ss_x, ss_y, name) in [(1i32, 1i32, "420"), (1, 0, "422"), (0, 0, "444")] {
2088- };2591+ crate::decode::set_subsampling(ss_x as u8, ss_y as u8, &fctx);
2089- let got = apply_grain(&src, &fg, false, 8, &fctx);2592+ for &(w, h) in &[(64usize, 66usize), (66, 64), (64, 98), (48, 100)] {
2090- let want = reference(&src, &fg, &fctx);2593+ let (cw, ch) = (w >> ss_x as usize, h >> ss_y as usize);
2091- assert_eq!(got.y, want.y, "{w}x{h} luma");2594+ let src = Picture {
2092- assert_eq!(got.u, want.u, "{w}x{h} cb");2595+ width: w,
2093- assert_eq!(got.v, want.v, "{w}x{h} cr");2596+ height: h,
2094- assert_ne!(got.y, src.y, "{w}x{h} grain actually landed");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+ }
2095 }2618 }
2096 }2619 }
2097 }2620 }
lanes/av1422grain.report.mdadded+314 -0
@@ -0,0 +1,314 @@
1+# lane-av1422grain — `film_grain.rs` is per-axis; 4:2:2 and 4:4:4 grain are byte-exact vs ffmpeg
2+
3+**Target:** `crates/ec-av1/src/film_grain.rs`, the one module the lift study
4+(`lanes/av1422liftrisk.report.md` §1b/§2 item 1) found still 4:2:0-shaped.
5+**Branch:** `lane/av1422grain`, commit `64549b09`. Base `228a55f5`.
6+**Changed file:** `crates/ec-av1/src/film_grain.rs` only. Nothing else touched.
7+
8+---
9+
10+## 1. THE MEASUREMENT — aomenc DOES emit 4:2:2 film grain
11+
12+The assignment's branch 3 (assertion + "cannot be produced") does **not** apply.
13+The cell is codable, so this is branch 2: port and prove.
14+
15+**Encoder:** `/home/user/.cache/aom-oracle/build/aomenc` (libaom, oracle
16+snapshot `9bb526a`).
17+
18+```sh
19+# 4:2:2 source
20+ffmpeg -f lavfi -i testsrc2=size=320x240:rate=1:duration=1 \
21+ -pix_fmt yuv422p -f yuv4mpegpipe src422.y4m
22+
23+# the encode under test
24+aomenc src422.y4m --profile=2 --film-grain-test=5 --obu -o g422_t5.obu
25+```
26+
27+**Result: exit 0, 10124 bytes, no diagnostic of any kind.** The encoder said
28+nothing because nothing was wrong — it simply emitted the cell.
29+
30+The proof that the frame header really carries 4:2:2 grain:
31+
32+```sh
33+ffprobe -v error -export_side_data +film_grain -show_frames -of json g422_t5.obu
34+```
35+```json
36+"side_data_type": "Film grain parameters",
37+"seed": "7825", "width": 320, "height": 240,
38+"subsampling_x": 1, "subsampling_y": 0,
39+"chroma_scaling_from_luma": 0, "scaling_shift": 11,
40+"ar_coeff_lag": 3, "ar_coeff_shift": 7
41+```
42+
43+`subsampling_x: 1, subsampling_y: 0` is 4:2:2, with a **full** point set
44+(`ar_coeff_lag 3` is the maximum, so every AR tap and both `avgLuma` paths are
45+exercised — the params are not a degenerate no-op). The identical encode
46+without `--film-grain-test` produces 9998 bytes and ffprobe reports **zero**
47+`Film grain parameters` side-data blocks, so the flag is what puts grain in.
48+
49+**4:4:4 is also live**, which the assignment did not anticipate and which
50+changes the shape of the fix (see §3):
51+
52+```sh
53+aomenc src444.y4m --profile=1 --film-grain-test=5 --obu -o g444_t5.obu
54+# 15541 bytes; ffprobe: profile "High", pix_fmt yuv444p, 1x Film grain parameters
55+```
56+
57+So this module had **two** silently-wrong arms, not one, and a port that
58+special-cased only `ss_y` would have fixed 4:2:2 and left 4:4:4 broken. The
59+port is per-axis on both.
60+
61+**Cells built** (all in `/home/user/.cache/av1422grain/`):
62+
63+| cell | encode | size |
64+|---|---|---|
65+| `g422_t5.obu` | `--profile=2 --film-grain-test=5` (8-bit 4:2:2) | 10124 |
66+| `g422_t11.obu` | `--profile=2 --film-grain-test=11` (8-bit 4:2:2) | 10124 |
67+| `g422_10_t5.obu` | `--profile=2 --input-bit-depth=10 --bit-depth=10 --film-grain-test=5` | 13792 |
68+| `g444_t5.obu` | `--profile=1 --film-grain-test=5` (8-bit 4:4:4) | 15541 |
69+
70+Two grain vectors at 8-bit so the result is not one lucky seed; one at 10-bit so
71+the bit-depth-generic path (`grain_range`, `scale_lut`, the `<< (bit_depth - 8)`
72+offsets) is covered at a second depth.
73+
74+---
75+
76+## 2. WHAT WAS ACTUALLY WRONG (the study's list, confirmed and corrected)
77+
78+The study listed 9 sites. All 9 were real. Two of its characterisations needed
79+correcting, and both corrections are load-bearing:
80+
81+* **`:577 n = min(..., luma.len()/2)`** — the study calls this "halves the luma
82+ operand". True, and it is right at 4:2:2 (where the operand IS a horizontal
83+ pair) but wrong at **4:4:4**, where the operand is the bare luma sample. So
84+ the fix is not "divide by 2", it is a `pair` flag.
85+* **`:351 c_stride = width/2`** — the study says "right for WIDTH at 4:2:2". It
86+ is right at 4:2:2 and wrong at 4:4:4, where it must be `width`.
87+
88+The study also says the 4:2:2 failure is "the top half of the chroma plane
89+grained with a 4:2:0 row map and a 2x2 `avgLuma` quad". Confirmed, and §5
90+quantifies it.
91+
92+## 3. THE PORT — libaom source lines
93+
94+This libaom snapshot has **no** `generate_grain_uv_422` and **no**
95+`av1_apply_grain_422`; the assignment's premise about those function names is
96+from an older libaom. What this version does is thread `chroma_subsamp_y` /
97+`chroma_subsamp_x` through one unified `add_film_grain_run`
98+(`av1/decoder/grain_synthesis.c:987`), set per pixel format in
99+`av1_add_film_grain` (`:1386-1420`, which lists `AOM_IMG_FMT_I422` and
100+`I42216` explicitly). **Read the C, not the function names** — every site below
101+is transcribed from this snapshot.
102+
103+| ours | C | what |
104+|---|---|---|
105+| `Ss::csub_x/y` | `:1018-1019` | `chroma_subblock_size_x/y = 32 >> chroma_subsamp` |
106+| `Ss::cblock_w/h` | `:1031-1035` | template size, `(2 >> ss) * ar_padding` terms |
107+| `c_stride` | `:1461` | `width >> chroma_subsamp_x` (right for 4:4:4 only here) |
108+| `chroma_row(y)` | `:1129` | chroma row of block row `y` is `y*2 >> ss_y` |
109+| `chroma_off_y/x` | `:1091-1094` | `top_pad + (2>>ss_y)*ar_pad + offset_y*(2>>ss_y)` |
110+| `cy0/cx0` | `:1129-1130` | `py0 >> ss_y`, `px0 >> ss_x` (not `/2`) |
111+| `ch/chw` block | `:680-681` | `half_h << (1-ss_y)` by `half_w << (1-ss_x)` |
112+| `avgLuma` in template | `:554-565` | `(ss_y+1) x (ss_x+1)` samples, `((1<<(ss_y+ss_x))>>1)` rounding |
113+| `average_luma` in apply | `:683-691` | horizontal pair at `ss_x==1`, bare sample at `ss_x==0` |
114+| line/col buffers | `:392-414` | `chroma_stride*(2>>ss_y)`, `(csub_y+(2>>ss_y))*(2>>ss_x)` |
115+| `ver_boundary_overlap` chroma | `:1102-1120` | width `2>>ss_x`, height `AOMMIN(csub_y+(2>>ss_y), (height-2y)>>ss_y)` |
116+| `hor_boundary_overlap` chroma | `:1157-1200` | height `2>>ss_y` |
117+| four chroma `copy_area`s | `:1289-1296`, `:1309-1320`, `:1345-1352` | per-axis extents |
118+
119+### Three traps the port walks into
120+
121+Each of these cost a real debugging cycle and is recorded at the site.
122+
123+**(a) The chroma BLOCK size is `16 << (1 - ss)`, not `chroma_subblock_size << (1 - ss)`.**
124+`add_noise_to_block` is handed `half_luma_height = AOMMIN(32 >> 1, ...)` and
125+`half_luma_width = AOMMIN(32 >> 1, ...)` (`:1254-1255`) — **luma** half-extents
126+— and scales them per axis inside (`:680-681`). So the block is
127+`16 << (1-ss)`: 16x16 at 4:2:0, **32x16 at 4:2:2**, **32x32 at 4:4:4**. The
128+tempting `chroma_subblock_size << (1 - ss)` agrees at 4:2:0 and diverges
129+wherever `chroma_subsamp == 0` (4:2:2 rows, 4:4:4 both axes) — the two differ
130+by a factor of 2. Getting this wrong is an out-of-bounds read, not a wrong
131+pixel.
132+
133+**(b) The block-column walk is in LUMA units at every subsampling.** The C is
134+`for (x = 0; x < width / 2; x += luma_subblock_size_x >> 1)` (`:1075`) and
135+`for (y = 0; y < height / 2; y += luma_subblock_size_y >> 1)` (`:1069`).
136+`width/2` and `height/2` are correct as written and must NOT become
137+`c_stride`; only the chroma ORIGIN and EXTENT derived from them are per-axis.
138+Making the walk itself per-axis is the single easiest way to break 4:2:0.
139+
140+**(c) `copy_area(cb_col_buf + (chroma_subblock_size_y << (1 - ss_x)), ...)`
141+(`:1289`) is a FLAT element offset, not a row index.** `copy_area` here
142+addresses `src_row0 * src_stride + src_col0`. Passing the C's flat value as the
143+row index multiplies it by the stride a second time and reads past the buffer
144+(observed: `len is 68 but the index is 128` at 4:4:4). The correct row index is
145+`csub_y`, because `src_stride == 2 >> ss_x` and the flat offset is
146+`csub_y << (1 - ss_x)`, which are the same number for every `ss_x`. Recorded
147+in a comment at the call site.
148+
149+### Two blend formulas, not one
150+
151+`ver_boundary_overlap` (`:912-939`) and `hor_boundary_overlap` (`:941-970`)
152+each have a `width/height == 1` arm and a `== 2` arm with **different
153+coefficients**: 23/22 for one, 27/17 and 17/27 for two. At 4:2:0 the `2 >> ss`
154+terms are both 1, so only the first arm ever ran and the second was dead code
155+that had never been exercised. It is live at 4:2:2 (rows) and 4:4:4 (both
156+axes), and the 17/27 second row is a genuinely different value. `film_grain.rs`
157+already had both arms (`ver_overlap_inplace`, `hor_overlap_inplace`); the port
158+is what makes them reachable.
159+
160+---
161+
162+## 4. NON-VACUITY — the comparator was proven to bite
163+
164+`stream.rs:16626-16629` warns that a params-without-apply stream is the known
165+false green. Three independent guards, all live:
166+
167+1. **`grain_hits() > 0`** — asserted per cell, delta printed:
168+ `0->1`, `1->2`, `2->3`, `3->4`. A stream carrying `apply_grain` that never
169+ ran synthesis fails here.
170+2. **The header really carries grain** — the test re-parses the OBUs and
171+ asserts some frame header has `film_grain.apply_grain`.
172+3. **The comparator bites** — one flipped oracle sample per plane, then the
173+ expected plane-difference tuple is asserted to be exactly `(1,1,1)`:
174+
175+```
176+TAMPER g422_t5.obu: plane diffs must be exactly (1,1,1), got (1,1,1)
177+TAMPER g422_t11.obu: plane diffs must be exactly (1,1,1), got (1,1,1)
178+TAMPER g422_10_t5.obu: plane diffs must be exactly (1,1,1), got (1,1,1)
179+```
180+
181+A zero here would have meant the plane comparison was not reading what it
182+claims to.
183+
184+## 5. NEGATIVE CONTROL — the verdict is produced by this port
185+
186+Forcing `Ss::read` back to the old hardcoded `Ss { x: 1, y: 1 }` (the pre-lane
187+geometry, everything else identical) makes the cell **fail** against ffmpeg:
188+
189+```
190+g422_t5.obu frame 0: luma/u/v samples differing from ffmpeg
191+ left: (0, 23370, 22631) right: (0, 0, 0)
192+```
193+
194+Read that shape carefully, it is the whole defect in one line: **luma exact,
195+~30% of each chroma plane wrong**. No panic, no counter, no refusal — exactly
196+the silent-wrong-picture failure the study predicted. (30% rather than ~50%
197+because a wrong grain delta is frequently zero, so many mis-grained samples
198+coincide with the oracle.)
199+
200+## 6. THE RESULT
201+
202+Every plane of every frame, `decode_stream` vs ffmpeg's own decode of the same
203+bytes, 4:2:2 chroma planes split by sequence-header geometry
204+(`yuv422p` / `yuv422p10le`; 10-bit read as u16 little-endian, never
205+u8-narrowed):
206+
207+```
208+g422_t5.obu byte-exact, 1 frames, grain_hits 0->1
209+g422_t11.obu byte-exact, 1 frames, grain_hits 1->2
210+g422_10_t5.obu byte-exact, 1 frames, grain_hits 2->3
211+g444_t5.obu byte-exact, 1 frames, grain_hits 3->4
212+```
213+
214+## 7. CONTROLS UNCHANGED
215+
216+The existing 4:2:0 coverage was run and is untouched and green — 8-bit, 10-bit
217+and 12-bit, all byte-exact against ffmpeg:
218+
219+| test | result |
220+|---|---|
221+| `a_real_aomenc_stream_with_film_grain_decodes_pixel_exact` (8-bit) | ok |
222+| `a_real_aomenc_10bit_film_grain_stream_decodes_pixel_exact` | ok |
223+| `a_real_aomenc_12bit_film_grain_stream_decodes_pixel_exact` | ok |
224+| `real_aomenc_film_grain_streams_decode_pixel_exact` (3 live aomenc draws) | ok |
225+| `untouched_planes_and_ragged_tail_come_back_clean` | ok |
226+| `simd_matches_scalar_luma_noise_row` | ok |
227+| `simd_matches_scalar_chroma_noise_row` | ok |
228+| `ragged_overlap_tail_matches_spec_reference` | ok (now 3 formats) |
229+
230+`cargo test -p ec-av1 --lib film_grain` → **8 passed, 0 failed**.
231+
232+`cargo check -p ec-av1 --lib --tests` → clean, no warnings.
233+
234+**Coverage that did not exist before this lane:** 4:2:2 and 4:4:4 film grain
235+had **no** test of any kind — not a byte-exactness gate, not a reference
236+comparison. `ragged_overlap_tail_matches_spec_reference` was a 4:2:0-only
237+transcription; it is now driven over all three formats, because a second
238+4:2:0-shaped copy of the reference would have been a new way to be wrong. It
239+also gained the assertion the old geometry **could not make**:
240+
241+```rust
242+assert_ne!(&got.u[last_chroma_row], &src.u[last_chroma_row],
243+ "the LAST chroma row came back clean -- the walk did not reach it");
244+```
245+
246+At 4:2:2 the chroma plane is `height` rows tall and the old `nrows = height/2`
247+walk left the bottom half raw, so this is the assertion that would have caught
248+the original bug directly.
249+
250+## 8. PROCEDURE — probe bypass, patch-run-restore
251+
252+`EC_AV1_ALLOW_422_PROBE` does nothing; the bypass is patch-run-restore.
253+
254+1. `git worktree add --detach ~/.cache/wt/av1422grain-probe HEAD`
255+2. copy this lane's `film_grain.rs` into it
256+3. neutralise the guard at `stream.rs:1803` with
257+ `if false && seq.subsampling_x != seq.subsampling_y`, with a
258+ `// TEMP-PROBE-BYPASS lane-av1422grain: patch-run-restore, never committed.`
259+ marker on the line above
260+4. run, then `git checkout -- <both files>`, verify `git status --porcelain`
261+ is **empty**, verify `grep -c 'TEMP-PROBE-BYPASS\|if false &&'` is **0**
262+5. `git worktree remove --force`
263+
264+Verified: the probe worktree is removed, and the guard is intact and
265+un-bypassed. **The primary checkout is clean** (`git status --porcelain`
266+empty) with no bypass markers.
267+
268+**Incident, reported rather than buried:** my *first* edit of this lane used a
269+RELATIVE path (`crates/ec-av1/src/film_grain.rs`) while the shell CWD was the
270+primary checkout, so it landed in `/home/user/Documents/Code/Rust/edith_codecs`
271+instead of the lane worktree. The tool reported success and I read the
272+worktree, saw no change, and wrongly concluded the edit had been rolled back —
273+so I reissued everything against absolute paths and the worktree ended up
274+complete. The leak sat unnoticed in the primary until the post-probe
275+`git status` check caught it. I verified all 61 added lines were mine (the `Ss`
276+fields and brace lines; every other line carries a `lane-av1422grain` or
277+`chroma`/`luma`/`subsamp` marker) and reverted with
278+`git checkout -- crates/ec-av1/src/film_grain.rs`. No peer work was lost. The
279+lesson is the one already in the skill library: **absolute paths only, and
280+check `git status` in the primary before yielding** — the check is what found
281+it, and it should have been run after the first edit, not at the end.
282+
283+## 9. STATUS AND WHAT IS NOT DONE
284+
285+Delivered: branch 2 in full — the cell exists (measured), the geometry is
286+per-axis, `grain_hits` fires, all four cells are byte-exact per plane per
287+frame, the comparator is proven to bite, the negative control fails without the
288+port, and the 4:2:0 controls are unchanged.
289+
290+**The end-to-end gate is NOT committed, and cannot be until the guard is
291+lifted.** `decode_stream` still returns
292+`"a chroma format of 4:2:2 (subsampling_x != subsampling_y)"` on `main`
293+(`697b1308`) — the guard at `stream.rs:1803` is untouched by this lane, by
294+design; lifting it is not this arm. A committed 4:2:2 decode gate would be red
295+today for a reason that has nothing to do with film grain.
296+
297+**Deferred, with its unblock:** commit the four-cell byte-exactness gate
298+immediately after the lift lands. It needs no further film-grain work — the
299+bytes and the assertions are settled. Handing it over as a follow-up is the one
300+piece of scope I am explicitly not closing, and it is blocked on a decision
301+that is not mine.
302+
303+## 10. A NOTE FOR THE LIFT
304+
305+Two things this lane learned that the lift should not have to rediscover:
306+
307+* **The 4:2:2 film-grain cell is real and now byte-exact.** Whoever lifts the
308+ guard should expect it to pass, and should not read a film-grain failure at
309+ 4:2:2 as a lift regression — it would be a film-grain regression, and this
310+ lane's commit is the fix.
311+* **`grain_hits()` is the counter to gate on** for the film-grain arm of a
312+ lifted 4:2:2 stream, and the four cells in §1 are ready-made fixtures for
313+ it. The study's §2 item 3 ("no 4:2:2 unit census exists") is a separate
314+ matter and does not affect film grain.