forge
Explore
Log in

Don't you dare go Hollow

Bit-depth-generic film grain synthesis and superres upscale

Browse files at this commit

a67e457d59ae381b02a0a1bb5aadf17725718a5cAhmet Kaan GümüşParent: d21774e
  • feat
    • bit-depth-generic film grain synthesis and superres upscale
Show full message
feat(av1): bit-depth-generic film grain synthesis and superres upscale

Lifts the last two `bit_depth != 8` refusals. Film grain (spec 7.18.3 /
libaom grain_synthesis.c): grain_center = 128 << (bd-8), gauss_sec_shift =
12 - bd + grain_scale_shift, scale_LUT interpolation over the 256-entry LUT,
cb/cr offsets and clip_to_restricted_range ranges shifted by (bd-8).
Superres (spec 7.16): planes stay u16 end to end, output clamp is
(1 << bd) - 1; the filter/Round2/edge-margin path is unchanged and its three
libaom pins still hold at 8-bit.

Gated by two real-aomenc 10-bit gates (--film-grain-test=1 and
--superres-mode=1 --superres-denominator=12), both pixel-exact vs ffmpeg's
own 10-bit decode and both hard-asserting bit_depth==10 plus a firing
counter (grain_hits / superres_hits). Forcing bit_depth=8 back into either
call site fails its gate, so neither is vacuous.

Measured on his library: ReelB sets apply_grain on 25 of its first 50
frames with a real luma scaling LUT at 10 bit; neither film uses superres
(enable_superres=false in both sequence headers).
crates/ec-av1/src/film_grain.rsmodified+93 -33
@@ -1,6 +1,6 @@
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: 8-bit, 4:2:0 planar3+//! specialized to this crate's only picture shape: 4:2:0 planar
4 //! (`chroma_subsamp_x = chroma_subsamp_y = 1` throughout, which is why every4 //! (`chroma_subsamp_x = chroma_subsamp_y = 1` throughout, which is why every
5 //! `<< (1 - subsamp)` in the reference collapses to a no-op and every5 //! `<< (1 - subsamp)` in the reference collapses to a no-op and every
6 //! `>> subsamp` collapses to `>> 1` below).6 //! `>> subsamp` collapses to `>> 1` below).
@@ -43,9 +43,25 @@ const LUMA_BLOCK_W: i32 =
43 const CHROMA_BLOCK_H: i32 = TOP_PAD + AR_PADDING + CHROMA_SUBBLOCK * 2 + BOTTOM_PAD;43 const CHROMA_BLOCK_H: i32 = TOP_PAD + AR_PADDING + CHROMA_SUBBLOCK * 2 + BOTTOM_PAD;
44 const CHROMA_BLOCK_W: i32 = LEFT_PAD + AR_PADDING + CHROMA_SUBBLOCK * 2 + AR_PADDING + RIGHT_PAD;44 const CHROMA_BLOCK_W: i32 = LEFT_PAD + AR_PADDING + CHROMA_SUBBLOCK * 2 + AR_PADDING + RIGHT_PAD;
45 45
46-// bit_depth is always 8 in this crate: grain_center = 128 << (8 - 8) = 128.46+thread_local! {
47-const GRAIN_MIN: i32 = -128;47+ /// `params->bit_depth` of the picture currently being grained. libaom
48-const GRAIN_MAX: i32 = 127;48+ /// keeps `grain_min`/`grain_max` as file statics set once per
49+ /// `av1_add_film_grain_run` (`grain_synthesis.c:1041-1045`); this mirrors
50+ /// that rather than threading a parameter through every helper.
51+ static GRAIN_BIT_DEPTH: std::cell::Cell<u32> = const { std::cell::Cell::new(8) };
52+}
53+
54+/// `params->bit_depth` for the [`apply_grain`] call in progress.
55+fn grain_bit_depth() -> u32 {
56+ GRAIN_BIT_DEPTH.with(|c| c.get())
57+}
58+
59+/// `grain_min`/`grain_max` (`grain_synthesis.c:1043-1045`):
60+/// `grain_center = 128 << (bit_depth - 8)`.
61+fn grain_range() -> (i32, i32) {
62+ let center = 128i32 << (grain_bit_depth() - 8);
63+ (-center, center - 1)
64+}
49 65
50 const MIN_LUMA_LEGAL: i32 = 16;66 const MIN_LUMA_LEGAL: i32 = 16;
51 const MAX_LUMA_LEGAL: i32 = 235;67 const MAX_LUMA_LEGAL: i32 = 235;
@@ -121,11 +137,12 @@ fn generate_luma_grain_block(
121 pred_pos: &[(i32, i32, i32)],137 pred_pos: &[(i32, i32, i32)],
122 rng: &mut Rng,138 rng: &mut Rng,
123 ) -> Vec<i32> {139 ) -> Vec<i32> {
140+ let (grain_min, grain_max) = grain_range();
124 let mut block = vec![0i32; (LUMA_BLOCK_H * LUMA_BLOCK_W) as usize];141 let mut block = vec![0i32; (LUMA_BLOCK_H * LUMA_BLOCK_W) as usize];
125 if fg.num_y_points == 0 {142 if fg.num_y_points == 0 {
126 return block;143 return block;
127 }144 }
128- let gauss_sec_shift = 4 + fg.grain_scale_shift as i32; // 12 - 8 + grain_scale_shift145+ let gauss_sec_shift = 12 - grain_bit_depth() as i32 + fg.grain_scale_shift as i32;
129 let ar_coeff_shift = fg.ar_coeff_shift_minus_6 as i32 + 6;146 let ar_coeff_shift = fg.ar_coeff_shift_minus_6 as i32 + 6;
130 let rounding_offset = 1i32 << (ar_coeff_shift - 1);147 let rounding_offset = 1i32 << (ar_coeff_shift - 1);
131 148
@@ -143,7 +160,7 @@ fn generate_luma_grain_block(
143 wsum += fg.ar_coeffs_y[idx] as i32 * at(&block, LUMA_BLOCK_W, i + dy, j + dx);160 wsum += fg.ar_coeffs_y[idx] as i32 * at(&block, LUMA_BLOCK_W, i + dy, j + dx);
144 }161 }
145 let v = (at(&block, LUMA_BLOCK_W, i, j) + ((wsum + rounding_offset) >> ar_coeff_shift))162 let v = (at(&block, LUMA_BLOCK_W, i, j) + ((wsum + rounding_offset) >> ar_coeff_shift))
146- .clamp(GRAIN_MIN, GRAIN_MAX);163+ .clamp(grain_min, grain_max);
147 set_at(&mut block, LUMA_BLOCK_W, i, j, v);164 set_at(&mut block, LUMA_BLOCK_W, i, j, v);
148 }165 }
149 }166 }
@@ -157,9 +174,10 @@ fn generate_chroma_grain_blocks(
157 luma_block: &[i32],174 luma_block: &[i32],
158 seed: u16,175 seed: u16,
159 ) -> (Vec<i32>, Vec<i32>) {176 ) -> (Vec<i32>, Vec<i32>) {
177+ let (grain_min, grain_max) = grain_range();
160 let mut cb = vec![0i32; (CHROMA_BLOCK_H * CHROMA_BLOCK_W) as usize];178 let mut cb = vec![0i32; (CHROMA_BLOCK_H * CHROMA_BLOCK_W) as usize];
161 let mut cr = vec![0i32; (CHROMA_BLOCK_H * CHROMA_BLOCK_W) as usize];179 let mut cr = vec![0i32; (CHROMA_BLOCK_H * CHROMA_BLOCK_W) as usize];
162- let gauss_sec_shift = 4 + fg.grain_scale_shift as i32;180+ let gauss_sec_shift = 12 - grain_bit_depth() as i32 + fg.grain_scale_shift as i32;
163 let ar_coeff_shift = fg.ar_coeff_shift_minus_6 as i32 + 6;181 let ar_coeff_shift = fg.ar_coeff_shift_minus_6 as i32 + 6;
164 let rounding_offset = 1i32 << (ar_coeff_shift - 1);182 let rounding_offset = 1i32 << (ar_coeff_shift - 1);
165 183
@@ -226,13 +244,13 @@ fn generate_chroma_grain_blocks(
226 if apply_cb {244 if apply_cb {
227 let v = (at(&cb, CHROMA_BLOCK_W, i, j)245 let v = (at(&cb, CHROMA_BLOCK_W, i, j)
228 + ((wsum_cb + rounding_offset) >> ar_coeff_shift))246 + ((wsum_cb + rounding_offset) >> ar_coeff_shift))
229- .clamp(GRAIN_MIN, GRAIN_MAX);247+ .clamp(grain_min, grain_max);
230 set_at(&mut cb, CHROMA_BLOCK_W, i, j, v);248 set_at(&mut cb, CHROMA_BLOCK_W, i, j, v);
231 }249 }
232 if apply_cr {250 if apply_cr {
233 let v = (at(&cr, CHROMA_BLOCK_W, i, j)251 let v = (at(&cr, CHROMA_BLOCK_W, i, j)
234 + ((wsum_cr + rounding_offset) >> ar_coeff_shift))252 + ((wsum_cr + rounding_offset) >> ar_coeff_shift))
235- .clamp(GRAIN_MIN, GRAIN_MAX);253+ .clamp(grain_min, grain_max);
236 set_at(&mut cr, CHROMA_BLOCK_W, i, j, v);254 set_at(&mut cr, CHROMA_BLOCK_W, i, j, v);
237 }255 }
238 }256 }
@@ -265,7 +283,21 @@ fn build_scaling_lut(values: &[u8], scaling: &[u8], num_points: usize) -> [i32;
265 lut283 lut
266 }284 }
267 285
268-/// `add_noise_to_block` (spec 7.18.3.5), 8-bit / 4:2:0 only. `(py0, px0)` is286+/// `scale_LUT` (`grain_synthesis.c:616`): the scaling LUT has 256 entries
287+/// regardless of bit depth, so at 10/12 bit the index is shifted down and the
288+/// two neighbouring entries are interpolated with the dropped low bits.
289+fn scale_lut(lut: &[i32; 256], index: i32, bit_depth: u32) -> i32 {
290+ let shift = bit_depth - 8;
291+ let x = (index >> shift) as usize;
292+ if shift == 0 || x == 255 {
293+ lut[x]
294+ } else {
295+ lut[x] + (((lut[x + 1] - lut[x]) * (index & ((1 << shift) - 1)) + (1 << (shift - 1)))
296+ >> shift)
297+ }
298+}
299+
300+/// `add_noise_to_block` (spec 7.18.3.5), 4:2:0 only. `(py0, px0)` is
269 /// the luma-plane pixel origin; the matching chroma origin is `(py0/2,301 /// the luma-plane pixel origin; the matching chroma origin is `(py0/2,
270 /// px0/2)`. Grain is read from `(grain, stride, row0, col0)` triples so the302 /// px0/2)`. Grain is read from `(grain, stride, row0, col0)` triples so the
271 /// same function serves both the raw 82x73/44x38 templates and the small303 /// same function serves both the raw 82x73/44x38 templates and the small
@@ -295,13 +327,17 @@ fn add_noise_to_block(
295 let y_stride = picture.width as i32;327 let y_stride = picture.width as i32;
296 let c_stride = (picture.width / 2) as i32;328 let c_stride = (picture.width / 2) as i32;
297 let scaling_shift = fg.grain_scaling_minus_8 as i32 + 8;329 let scaling_shift = fg.grain_scaling_minus_8 as i32 + 8;
330+ let bit_depth = grain_bit_depth();
331+ let bd_shift = bit_depth - 8;
332+ // `(256 << (bit_depth - 8)) - 1`, the scaling-LUT index clamp.
333+ let index_max = (256i32 << bd_shift) - 1;
298 334
299 let mut cb_mult = fg.cb_mult as i32 - 128;335 let mut cb_mult = fg.cb_mult as i32 - 128;
300 let mut cb_luma_mult = fg.cb_luma_mult as i32 - 128;336 let mut cb_luma_mult = fg.cb_luma_mult as i32 - 128;
301- let mut cb_offset = fg.cb_offset as i32 - 256;337+ let mut cb_offset = ((fg.cb_offset as i32) << bd_shift) - (1 << bit_depth);
302 let mut cr_mult = fg.cr_mult as i32 - 128;338 let mut cr_mult = fg.cr_mult as i32 - 128;
303 let mut cr_luma_mult = fg.cr_luma_mult as i32 - 128;339 let mut cr_luma_mult = fg.cr_luma_mult as i32 - 128;
304- let mut cr_offset = fg.cr_offset as i32 - 256;340+ let mut cr_offset = ((fg.cr_offset as i32) << bd_shift) - (1 << bit_depth);
305 if fg.chroma_scaling_from_luma {341 if fg.chroma_scaling_from_luma {
306 cb_mult = 0;342 cb_mult = 0;
307 cb_luma_mult = 64;343 cb_luma_mult = 64;
@@ -318,21 +354,21 @@ fn add_noise_to_block(
318 let (min_luma, max_luma, min_chroma, max_chroma) = if fg.clip_to_restricted_range {354 let (min_luma, max_luma, min_chroma, max_chroma) = if fg.clip_to_restricted_range {
319 if mc_identity {355 if mc_identity {
320 (356 (
321- MIN_LUMA_LEGAL,357+ MIN_LUMA_LEGAL << bd_shift,
322- MAX_LUMA_LEGAL,358+ MAX_LUMA_LEGAL << bd_shift,
323- MIN_LUMA_LEGAL,359+ MIN_LUMA_LEGAL << bd_shift,
324- MAX_LUMA_LEGAL,360+ MAX_LUMA_LEGAL << bd_shift,
325 )361 )
326 } else {362 } else {
327 (363 (
328- MIN_LUMA_LEGAL,364+ MIN_LUMA_LEGAL << bd_shift,
329- MAX_LUMA_LEGAL,365+ MAX_LUMA_LEGAL << bd_shift,
330- MIN_CHROMA_LEGAL,366+ MIN_CHROMA_LEGAL << bd_shift,
331- MAX_CHROMA_LEGAL,367+ MAX_CHROMA_LEGAL << bd_shift,
332 )368 )
333 }369 }
334 } else {370 } else {
335- (0, 255, 0, 255)371+ (0, index_max, 0, index_max)
336 };372 };
337 373
338 let cy0 = py0 / 2;374 let cy0 = py0 / 2;
@@ -349,8 +385,9 @@ fn add_noise_to_block(
349 let scaled = (((average_luma * cb_luma_mult + cb_mult * picture.u[cidx] as i32)385 let scaled = (((average_luma * cb_luma_mult + cb_mult * picture.u[cidx] as i32)
350 >> 6)386 >> 6)
351 + cb_offset)387 + cb_offset)
352- .clamp(0, 255);388+ .clamp(0, index_max);
353- let delta = (scaling_cb[scaled as usize] * cb_grain[gidx] + rounding_offset)389+ let delta = (scale_lut(scaling_cb, scaled, bit_depth) * cb_grain[gidx]
390+ + rounding_offset)
354 >> scaling_shift;391 >> scaling_shift;
355 picture.u[cidx] =392 picture.u[cidx] =
356 ((picture.u[cidx] as i32 + delta).clamp(min_chroma, max_chroma)) as u16;393 ((picture.u[cidx] as i32 + delta).clamp(min_chroma, max_chroma)) as u16;
@@ -359,8 +396,9 @@ fn add_noise_to_block(
359 let scaled = (((average_luma * cr_luma_mult + cr_mult * picture.v[cidx] as i32)396 let scaled = (((average_luma * cr_luma_mult + cr_mult * picture.v[cidx] as i32)
360 >> 6)397 >> 6)
361 + cr_offset)398 + cr_offset)
362- .clamp(0, 255);399+ .clamp(0, index_max);
363- let delta = (scaling_cr[scaled as usize] * cr_grain[gidx] + rounding_offset)400+ let delta = (scale_lut(scaling_cr, scaled, bit_depth) * cr_grain[gidx]
401+ + rounding_offset)
364 >> scaling_shift;402 >> scaling_shift;
365 picture.v[cidx] =403 picture.v[cidx] =
366 ((picture.v[cidx] as i32 + delta).clamp(min_chroma, max_chroma)) as u16;404 ((picture.v[cidx] as i32 + delta).clamp(min_chroma, max_chroma)) as u16;
@@ -372,7 +410,8 @@ fn add_noise_to_block(
372 for j in 0..half_w * 2 {410 for j in 0..half_w * 2 {
373 let pidx = ((py0 + i) * y_stride + (px0 + j)) as usize;411 let pidx = ((py0 + i) * y_stride + (px0 + j)) as usize;
374 let gidx = ((lg_row0 + i) * lg_stride + (lg_col0 + j)) as usize;412 let gidx = ((lg_row0 + i) * lg_stride + (lg_col0 + j)) as usize;
375- let delta = (scaling_y[picture.y[pidx] as usize] * luma_grain[gidx]413+ let delta = (scale_lut(scaling_y, picture.y[pidx] as i32, bit_depth)
414+ * luma_grain[gidx]
376 + rounding_offset)415 + rounding_offset)
377 >> scaling_shift;416 >> scaling_shift;
378 picture.y[pidx] =417 picture.y[pidx] =
@@ -398,6 +437,7 @@ fn ver_overlap_inplace(
398 width: i32,437 width: i32,
399 height: i32,438 height: i32,
400 ) {439 ) {
440+ let (grain_min, grain_max) = grain_range();
401 for h in 0..height {441 for h in 0..height {
402 if width == 1 {442 if width == 1 {
403 let l = at(dst, dst_stride, dst_row0 + h, dst_col0);443 let l = at(dst, dst_stride, dst_row0 + h, dst_col0);
@@ -407,7 +447,7 @@ fn ver_overlap_inplace(
407 dst_stride,447 dst_stride,
408 dst_row0 + h,448 dst_row0 + h,
409 dst_col0,449 dst_col0,
410- ((l * 23 + r * 22 + 16) >> 5).clamp(GRAIN_MIN, GRAIN_MAX),450+ ((l * 23 + r * 22 + 16) >> 5).clamp(grain_min, grain_max),
411 );451 );
412 } else {452 } else {
413 let l0 = at(dst, dst_stride, dst_row0 + h, dst_col0);453 let l0 = at(dst, dst_stride, dst_row0 + h, dst_col0);
@@ -419,14 +459,14 @@ fn ver_overlap_inplace(
419 dst_stride,459 dst_stride,
420 dst_row0 + h,460 dst_row0 + h,
421 dst_col0,461 dst_col0,
422- ((27 * l0 + 17 * r0 + 16) >> 5).clamp(GRAIN_MIN, GRAIN_MAX),462+ ((27 * l0 + 17 * r0 + 16) >> 5).clamp(grain_min, grain_max),
423 );463 );
424 set_at(464 set_at(
425 dst,465 dst,
426 dst_stride,466 dst_stride,
427 dst_row0 + h,467 dst_row0 + h,
428 dst_col0 + 1,468 dst_col0 + 1,
429- ((17 * l1 + 27 * r1 + 16) >> 5).clamp(GRAIN_MIN, GRAIN_MAX),469+ ((17 * l1 + 27 * r1 + 16) >> 5).clamp(grain_min, grain_max),
430 );470 );
431 }471 }
432 }472 }
@@ -447,6 +487,7 @@ fn hor_overlap_inplace(
447 width: i32,487 width: i32,
448 height: i32,488 height: i32,
449 ) {489 ) {
490+ let (grain_min, grain_max) = grain_range();
450 if height == 1 {491 if height == 1 {
451 for w in 0..width {492 for w in 0..width {
452 let t = at(dst, dst_stride, dst_row0, dst_col0 + w);493 let t = at(dst, dst_stride, dst_row0, dst_col0 + w);
@@ -456,7 +497,7 @@ fn hor_overlap_inplace(
456 dst_stride,497 dst_stride,
457 dst_row0,498 dst_row0,
458 dst_col0 + w,499 dst_col0 + w,
459- ((t * 23 + b * 22 + 16) >> 5).clamp(GRAIN_MIN, GRAIN_MAX),500+ ((t * 23 + b * 22 + 16) >> 5).clamp(grain_min, grain_max),
460 );501 );
461 }502 }
462 } else {503 } else {
@@ -470,14 +511,14 @@ fn hor_overlap_inplace(
470 dst_stride,511 dst_stride,
471 dst_row0,512 dst_row0,
472 dst_col0 + w,513 dst_col0 + w,
473- ((27 * t0 + 17 * b0 + 16) >> 5).clamp(GRAIN_MIN, GRAIN_MAX),514+ ((27 * t0 + 17 * b0 + 16) >> 5).clamp(grain_min, grain_max),
474 );515 );
475 set_at(516 set_at(
476 dst,517 dst,
477 dst_stride,518 dst_stride,
478 dst_row0 + 1,519 dst_row0 + 1,
479 dst_col0 + w,520 dst_col0 + w,
480- ((17 * t1 + 27 * b1 + 16) >> 5).clamp(GRAIN_MIN, GRAIN_MAX),521+ ((17 * t1 + 27 * b1 + 16) >> 5).clamp(grain_min, grain_max),
481 );522 );
482 }523 }
483 }524 }
@@ -496,6 +537,7 @@ fn copy_area(
496 width: i32,537 width: i32,
497 height: i32,538 height: i32,
498 ) {539 ) {
540+ let (grain_min, grain_max) = grain_range();
499 for h in 0..height {541 for h in 0..height {
500 for w in 0..width {542 for w in 0..width {
501 let v = at(src, src_stride, src_row0 + h, src_col0 + w);543 let v = at(src, src_stride, src_row0 + h, src_col0 + w);
@@ -504,15 +546,33 @@ fn copy_area(
504 }546 }
505 }547 }
506 548
549+thread_local! {
550+ /// Firing count for the film-grain gates (class `gate-blind-to-feature`):
551+ /// how many pictures actually ran through grain synthesis.
552+ static GRAIN_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
553+}
554+
555+/// Current value of [`GRAIN_HITS`].
556+pub(crate) fn grain_hits() -> usize {
557+ GRAIN_HITS.with(|c| c.get())
558+}
559+
507 /// `av1_add_film_grain`/`add_film_grain_run` (spec 7.18.3.5): synthesize and560 /// `av1_add_film_grain`/`add_film_grain_run` (spec 7.18.3.5): synthesize and
508 /// apply film grain to `picture`, returning a new grained picture. `picture`561 /// apply film grain to `picture`, returning a new grained picture. `picture`
509 /// itself is unchanged -- it stays the clean reference-frame-bank copy.562 /// itself is unchanged -- it stays the clean reference-frame-bank copy.
510 /// Returns `picture.clone()` untouched when `apply_grain` is unset.563 /// Returns `picture.clone()` untouched when `apply_grain` is unset.
511-pub(crate) fn apply_grain(picture: &Picture, fg: &FilmGrainParams, mc_identity: bool) -> Picture {564+pub(crate) fn apply_grain(
565+ picture: &Picture,
566+ fg: &FilmGrainParams,
567+ mc_identity: bool,
568+ bit_depth: u32,
569+) -> Picture {
512 let mut out = picture.clone();570 let mut out = picture.clone();
513 if !fg.apply_grain {571 if !fg.apply_grain {
514 return out;572 return out;
515 }573 }
574+ GRAIN_BIT_DEPTH.with(|c| c.set(bit_depth));
575+ GRAIN_HITS.with(|c| c.set(c.get() + 1));
516 let width = out.width as i32;576 let width = out.width as i32;
517 let height = out.height as i32;577 let height = out.height as i32;
518 let y_stride = width;578 let y_stride = width;
crates/ec-av1/src/refusal_inventory.rsmodified+0 -2
@@ -42,8 +42,6 @@ const REFUSALS: &[&str] = &[
42 "a 16x16 inter block whose true edge cuts through both axes needs a rectangular transform this decoder does not code yet",42 "a 16x16 inter block whose true edge cuts through both axes needs a rectangular transform this decoder does not code yet",
43 "a 32x32 partition type this decoder does not code (value={part32})",43 "a 32x32 partition type this decoder does not code (value={part32})",
44 "a Golomb tail longer than this decoder reads",44 "a Golomb tail longer than this decoder reads",
45- "a bit depth other than 8 with film grain applied (film_grain.rs's LUT and blend are hardcoded 8-bit)",
46- "a bit depth other than 8 with use_superres set (superres.rs's upscale_row is hardcoded 8-bit)",
47 "a superblock-level HORZ/VERT strip with a split transform (per-unit rect prediction is not ported)",45 "a superblock-level HORZ/VERT strip with a split transform (per-unit rect prediction is not ported)",
48 "a tx_type symbol outside its CDF's own set: {t}",46 "a tx_type symbol outside its CDF's own set: {t}",
49 "an INTER 32x32 partition type this decoder does not code (value={part32})",47 "an INTER 32x32 partition type this decoder does not code (value={part32})",
crates/ec-av1/src/stream.rsmodified+247 -29
@@ -128,23 +128,20 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
128 }128 }
129 }129 }
130 let output = if header.film_grain.apply_grain {130 let output = if header.film_grain.apply_grain {
131- // lane-hbd r5: `film_grain.rs`'s grain LUT and blend are131+ // lane-hbd10 r1: grain synthesis is bit-depth generic
132- // hardcoded 8-bit (`[i32; 256]`, clamps at 255) -- narrowed132+ // (`film_grain.rs`'s `grain_range`/`scale_lut`, spec 7.18.3).
133- // from the old blanket bit-depth refusal to only the case
134- // that actually reaches unported code.
135 let bit_depth = parser133 let bit_depth = parser
136 .sequence_header()134 .sequence_header()
137 .map_or(8, |seq| seq.color_config.bit_depth);135 .map_or(8, |seq| seq.color_config.bit_depth);
138- if bit_depth != 8 {
139- return Err(Error::unsupported(
140- "AV1 decode_stream",
141- "a bit depth other than 8 with film grain applied (film_grain.rs's LUT and blend are hardcoded 8-bit)",
142- ));
143- }
144 let mc_identity = parser136 let mc_identity = parser
145 .sequence_header()137 .sequence_header()
146 .is_some_and(|seq| seq.color_config.matrix_coefficients == 0);138 .is_some_and(|seq| seq.color_config.matrix_coefficients == 0);
147- crate::film_grain::apply_grain(&picture, &header.film_grain, mc_identity)139+ crate::film_grain::apply_grain(
140+ &picture,
141+ &header.film_grain,
142+ mc_identity,
143+ bit_depth as u32,
144+ )
148 } else {145 } else {
149 picture146 picture
150 };147 };
@@ -509,20 +506,12 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
509 // call above, right before anything else can overwrite it) --506 // call above, right before anything else can overwrite it) --
510 // see `decode::take_last_frame_wide_margin`'s doc.507 // see `decode::take_last_frame_wide_margin`'s doc.
511 let wide_margin = crate::decode::take_last_frame_wide_margin();508 let wide_margin = crate::decode::take_last_frame_wide_margin();
512- // lane-hbd r5: `upscale_row` (superres.rs) is `&[u8]`, clamping at
513- // 255 -- narrowed from the old blanket bit-depth refusal to only
514- // the case that actually reaches unported code.
515- if header.use_superres && bit_depth != 8 {
516- return Err(Error::unsupported(
517- "AV1 decode_stream",
518- "a bit depth other than 8 with use_superres set (superres.rs's upscale_row is hardcoded 8-bit)",
519- ));
520- }
521 let picture = if header.use_superres {509 let picture = if header.use_superres {
522 crate::superres::upscale_picture(510 crate::superres::upscale_picture(
523 &picture,511 &picture,
524 header.upscaled_width as usize,512 header.upscaled_width as usize,
525 wide_margin.as_ref(),513 wide_margin.as_ref(),
514+ bit_depth as u32,
526 )515 )
527 } else {516 } else {
528 picture517 picture
@@ -634,6 +623,7 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
634 &picture,623 &picture,
635 header.upscaled_width as usize,624 header.upscaled_width as usize,
636 wide_margin.as_ref(),625 wide_margin.as_ref(),
626+ bit_depth as u32,
637 )627 )
638 } else {628 } else {
639 picture629 picture
@@ -710,18 +700,15 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
710 }700 }
711 if header.show_frame {701 if header.show_frame {
712 let output = if header.film_grain.apply_grain {702 let output = if header.film_grain.apply_grain {
713- // lane-hbd r5: same 8-bit-only LUT/blend as the
714- // show_existing_frame arm above.
715- if bit_depth != 8 {
716- return Err(Error::unsupported(
717- "AV1 decode_stream",
718- "a bit depth other than 8 with film grain applied (film_grain.rs's LUT and blend are hardcoded 8-bit)",
719- ));
720- }
721 let mc_identity = parser703 let mc_identity = parser
722 .sequence_header()704 .sequence_header()
723 .is_some_and(|seq| seq.color_config.matrix_coefficients == 0);705 .is_some_and(|seq| seq.color_config.matrix_coefficients == 0);
724- crate::film_grain::apply_grain(&picture, &header.film_grain, mc_identity)706+ crate::film_grain::apply_grain(
707+ &picture,
708+ &header.film_grain,
709+ mc_identity,
710+ bit_depth as u32,
711+ )
725 } else {712 } else {
726 picture713 picture
727 };714 };
@@ -1942,6 +1929,237 @@ mod tests {
1942 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (10-bit)");1929 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (10-bit)");
1943 }1930 }
1944 1931
1932+ /// lane-hbd10 r1: a real `aomenc --bit-depth=10 --film-grain-test=1`
1933+ /// stream, decoded pixel-exact against ffmpeg's own 10-bit decode of the
1934+ /// identical bytes (ffmpeg synthesizes grain by default -- no
1935+ /// grain-disable flag is passed anywhere in this file). Proves the
1936+ /// bit-depth-generic grain path (`film_grain.rs`'s `grain_range`,
1937+ /// `scale_lut`, the `<< (bit_depth - 8)` offsets/legal ranges) rather
1938+ /// than the old `bit_depth != 8` refusal. HARD-asserts both the parsed
1939+ /// `bit_depth == 10` and `film_grain::grain_hits() > 0`, so neither a
1940+ /// silent 8-bit fallback nor a stream aomenc emitted without
1941+ /// `apply_grain` can make it pass vacuously.
1942+ #[test]
1943+ fn a_real_aomenc_10bit_film_grain_stream_decodes_pixel_exact() {
1944+ const NAME: &str = "a_real_aomenc_10bit_film_grain_stream_decodes_pixel_exact";
1945+ if !have_ffmpeg() {
1946+ eprintln!("SKIP {NAME}: no ffmpeg");
1947+ return;
1948+ }
1949+ if !have_aomenc() {
1950+ eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
1951+ return;
1952+ }
1953+ let (width, height) = (64usize, 64usize);
1954+ let stream = encode_10bit_gradients(
1955+ NAME,
1956+ width,
1957+ height,
1958+ 1,
1959+ &["--film-grain-test=1", "--limit=1"],
1960+ );
1961+ assert_eq!(
1962+ parsed_bit_depth(&stream),
1963+ 10,
1964+ "{NAME}: aomenc did not actually write a 10-bit sequence header"
1965+ );
1966+ let mut probe = Av1Parser::new();
1967+ let mut pos = 0usize;
1968+ let mut saw_grain = false;
1969+ while pos < stream.len() {
1970+ let obu = probe.parse_obu(&stream[pos..]).unwrap();
1971+ pos += obu.total_size;
1972+ if let ObuKind::Frame(header, _) = obu.kind
1973+ && header.film_grain.apply_grain
1974+ {
1975+ // A grain block whose scaling LUT is empty would blend a
1976+ // zero delta into every pixel and let this gate pass without
1977+ // the bit-depth math mattering at all.
1978+ assert!(
1979+ header.film_grain.num_y_points > 0,
1980+ "{NAME}: apply_grain with no luma scaling points -- grain would be a no-op"
1981+ );
1982+ saw_grain = true;
1983+ }
1984+ }
1985+ assert!(saw_grain, "{NAME}: aomenc did not turn on apply_grain");
1986+ let before = crate::film_grain::grain_hits();
1987+ let frames = match decode_stream(&stream) {
1988+ Ok(frames) => frames,
1989+ Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
1990+ };
1991+ assert!(
1992+ crate::film_grain::grain_hits() > before,
1993+ "{NAME}: matched but zero grain_hits -- grain synthesis never ran"
1994+ );
1995+ let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
1996+ assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
1997+ assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
1998+ assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
1999+ eprintln!("{NAME}: pixel-exact, grain_hits={}", crate::film_grain::grain_hits());
2000+ }
2001+
2002+ /// lane-hbd10 r1: a real `aomenc --bit-depth=10 --superres-mode=1
2003+ /// --superres-denominator=12` key frame, decoded pixel-exact against
2004+ /// ffmpeg's own 10-bit decode. Proves `superres::upscale_row`'s
2005+ /// `clip_pixel_highbd` clamp (`(1 << bit_depth) - 1`) on real 10-bit
2006+ /// planes rather than the old `bit_depth != 8` refusal. HARD-asserts
2007+ /// `bit_depth == 10` and `superres_hits > 0`.
2008+ #[test]
2009+ fn a_real_aomenc_10bit_superres_stream_decodes_pixel_exact() {
2010+ const NAME: &str = "a_real_aomenc_10bit_superres_stream_decodes_pixel_exact";
2011+ if !have_ffmpeg() {
2012+ eprintln!("SKIP {NAME}: no ffmpeg");
2013+ return;
2014+ }
2015+ if !have_aomenc() {
2016+ eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
2017+ return;
2018+ }
2019+ let (width, height) = (64usize, 64usize);
2020+ let stream = encode_10bit_gradients(
2021+ NAME,
2022+ width,
2023+ height,
2024+ 1,
2025+ &[
2026+ "--limit=1",
2027+ "--kf-max-dist=0",
2028+ "--superres-mode=1",
2029+ "--superres-denominator=12",
2030+ "--superres-kf-denominator=12",
2031+ "--enable-rect-partitions=0",
2032+ "--enable-ab-partitions=0",
2033+ "--enable-1to4-partitions=0",
2034+ "--enable-filter-intra=0",
2035+ "--enable-smooth-intra=0",
2036+ "--enable-paeth-intra=0",
2037+ "--enable-directional-intra=0",
2038+ "--enable-angle-delta=0",
2039+ "--enable-tx-size-search=0",
2040+ "--enable-cdef=0",
2041+ "--enable-restoration=0",
2042+ "--max-partition-size=32",
2043+ "--min-partition-size=32",
2044+ "--enable-palette=0",
2045+ "--enable-intrabc=0",
2046+ "--enable-cfl-intra=0",
2047+ ],
2048+ );
2049+ assert_eq!(
2050+ parsed_bit_depth(&stream),
2051+ 10,
2052+ "{NAME}: aomenc did not actually write a 10-bit sequence header"
2053+ );
2054+ let before = crate::superres::superres_hits();
2055+ let frames = match decode_stream(&stream) {
2056+ Ok(frames) => frames,
2057+ Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
2058+ };
2059+ assert!(
2060+ crate::superres::superres_hits() > before,
2061+ "{NAME}: matched but zero superres_hits -- the upscaler never ran"
2062+ );
2063+ let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
2064+ assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
2065+ assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
2066+ assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
2067+ eprintln!(
2068+ "{NAME}: pixel-exact, superres_hits={}",
2069+ crate::superres::superres_hits()
2070+ );
2071+ }
2072+
2073+ /// `bit_depth` of the first sequence header in `stream`.
2074+ fn parsed_bit_depth(stream: &[u8]) -> u8 {
2075+ let mut probe = Av1Parser::new();
2076+ let mut pos = 0usize;
2077+ while pos < stream.len() && probe.sequence_header().is_none() {
2078+ let obu = probe.parse_obu(&stream[pos..]).unwrap();
2079+ pos += obu.total_size;
2080+ }
2081+ probe
2082+ .sequence_header()
2083+ .expect("stream has a sequence header OBU")
2084+ .color_config
2085+ .bit_depth
2086+ }
2087+
2088+ /// Render `frames` of the shared `gradients_source` as `yuv420p10le` and
2089+ /// encode it with a real 10-bit `aomenc`, returning the OBU stream.
2090+ /// `extra` carries the tool flags under test.
2091+ fn encode_10bit_gradients(
2092+ name: &str,
2093+ width: usize,
2094+ height: usize,
2095+ frames: usize,
2096+ extra: &[&str],
2097+ ) -> Vec<u8> {
2098+ let duration = frames as f64 / 25.0;
2099+ let y4m = Command::new("ffmpeg")
2100+ .args([
2101+ "-v",
2102+ "error",
2103+ "-f",
2104+ "lavfi",
2105+ "-i",
2106+ &gradients_source(42, width, height, &format!("duration={duration}:rate=25")),
2107+ "-pix_fmt",
2108+ "yuv420p10le",
2109+ "-strict",
2110+ "-1",
2111+ "-t",
2112+ &format!("{duration}"),
2113+ "-f",
2114+ "yuv4mpegpipe",
2115+ "-",
2116+ ])
2117+ .stdin(Stdio::null())
2118+ .stdout(Stdio::piped())
2119+ .stderr(Stdio::piped())
2120+ .output()
2121+ .expect("ffmpeg failed to run");
2122+ assert!(
2123+ y4m.status.success(),
2124+ "{name}: ffmpeg failed to render the 10-bit fixture: {}",
2125+ String::from_utf8_lossy(&y4m.stderr)
2126+ );
2127+ let mut args: Vec<&str> = vec![
2128+ "--codec=av1",
2129+ "--passes=1",
2130+ "--end-usage=q",
2131+ "--cq-level=30",
2132+ "--cpu-used=0",
2133+ "--threads=1",
2134+ "--row-mt=0",
2135+ "--sb-size=64",
2136+ "--input-bit-depth=10",
2137+ "--bit-depth=10",
2138+ ];
2139+ args.extend_from_slice(extra);
2140+ args.extend_from_slice(&["--obu", "-o", "-", "-"]);
2141+ let mut child = Command::new(aomenc_path())
2142+ .args(&args)
2143+ .stdin(Stdio::piped())
2144+ .stdout(Stdio::piped())
2145+ .stderr(Stdio::piped())
2146+ .spawn()
2147+ .expect("aomenc failed to start");
2148+ child
2149+ .stdin
2150+ .take()
2151+ .expect("aomenc stdin")
2152+ .write_all(&y4m.stdout)
2153+ .expect("writing y4m to aomenc");
2154+ let out = child.wait_with_output().expect("aomenc failed to run");
2155+ assert!(
2156+ out.status.success(),
2157+ "{name}: aomenc refused the 10-bit fixture: {}",
2158+ String::from_utf8_lossy(&out.stderr)
2159+ );
2160+ out.stdout
2161+ }
2162+
1945 /// A real `aomenc` palette-**UV** fixture (lane-palette2 r2): `testsrc2`2163 /// A real `aomenc` palette-**UV** fixture (lane-palette2 r2): `testsrc2`
1946 /// (the multicoloured AV1 test pattern -- flat, few-colour, repetitive2164 /// (the multicoloured AV1 test pattern -- flat, few-colour, repetitive
1947 /// per-region colour *and* chroma, unlike `smptebars=hue=s=0` above,2165 /// per-region colour *and* chroma, unlike `smptebars=hue=s=0` above,
crates/ec-av1/src/superres.rsmodified+48 -49
@@ -89,7 +89,16 @@ fn round_power_of_two(sum: i32, bits: u32) -> i32 {
89 /// true, replicating the row's own edge pixels rather than sampling a89 /// true, replicating the row's own edge pixels rather than sampling a
90 /// neighbour tile). `in_width` and `out_width` must both be positive;90 /// neighbour tile). `in_width` and `out_width` must both be positive;
91 /// `row.len() == in_width` and `out.len() == out_width`.91 /// `row.len() == in_width` and `out.len() == out_width`.
92-pub(crate) fn upscale_row(row: &[u8], real_right_margin: &[u8], out_width: usize, out: &mut [u8]) {92+/// `bit_depth` only picks the output clamp (`clip_pixel`/`clip_pixel_highbd`
93+/// in libaom's `av1_convolve_horiz_rs_c`); the filter, its `Round2` and the
94+/// edge padding are bit-depth independent (spec 7.16).
95+pub(crate) fn upscale_row(
96+ row: &[u16],
97+ real_right_margin: &[u16],
98+ out_width: usize,
99+ out: &mut [u16],
100+ bit_depth: u32,
101+) {
93 let in_width = row.len();102 let in_width = row.len();
94 debug_assert!(in_width > 0 && out_width > 0);103 debug_assert!(in_width > 0 && out_width > 0);
95 debug_assert_eq!(out.len(), out_width);104 debug_assert_eq!(out.len(), out_width);
@@ -109,7 +118,7 @@ pub(crate) fn upscale_row(row: &[u8], real_right_margin: &[u8], out_width: usize
109 // column-by-column against real libaom via `scripts/superres-pin-118 // column-by-column against real libaom via `scripts/superres-pin-
110 // harness.c`'s `row6-realedgeval` case (r3).119 // harness.c`'s `row6-realedgeval` case (r3).
111 let pad = UPSCALE_NORMATIVE_TAPS + 2;120 let pad = UPSCALE_NORMATIVE_TAPS + 2;
112- let mut padded = vec![0u8; in_width + 2 * pad];121+ let mut padded = vec![0u16; in_width + 2 * pad];
113 padded[..pad].fill(row[0]);122 padded[..pad].fill(row[0]);
114 padded[pad..pad + in_width].copy_from_slice(row);123 padded[pad..pad + in_width].copy_from_slice(row);
115 let real_n = real_right_margin.len().min(pad);124 let real_n = real_right_margin.len().min(pad);
@@ -131,7 +140,7 @@ pub(crate) fn upscale_row(row: &[u8], real_right_margin: &[u8], out_width: usize
131 let idx = base + int_pel + k as i64;140 let idx = base + int_pel + k as i64;
132 sum += padded[idx as usize] as i32 * c as i32;141 sum += padded[idx as usize] as i32 * c as i32;
133 }142 }
134- *out_x = round_power_of_two(sum, FILTER_BITS).clamp(0, 255) as u8;143+ *out_x = round_power_of_two(sum, FILTER_BITS).clamp(0, (1 << bit_depth) - 1) as u16;
135 x_qn += x_step_qn;144 x_qn += x_step_qn;
136 }145 }
137 }146 }
@@ -141,14 +150,15 @@ pub(crate) fn upscale_row(row: &[u8], real_right_margin: &[u8], out_width: usize
141 /// spec only widens columns). `rows` is the plane's row-major byte buffer150 /// spec only widens columns). `rows` is the plane's row-major byte buffer
142 /// at `in_width`; returns a new buffer at `out_width`.151 /// at `in_width`; returns a new buffer at `out_width`.
143 pub(crate) fn upscale_plane(152 pub(crate) fn upscale_plane(
144- rows: &[u8],153+ rows: &[u16],
145 height: usize,154 height: usize,
146 in_width: usize,155 in_width: usize,
147 out_width: usize,156 out_width: usize,
148- margin: Option<(&[u8], usize)>,157+ margin: Option<(&[u16], usize)>,
149-) -> Vec<u8> {158+ bit_depth: u32,
159+) -> Vec<u16> {
150 debug_assert_eq!(rows.len(), height * in_width);160 debug_assert_eq!(rows.len(), height * in_width);
151- let mut out = vec![0u8; height * out_width];161+ let mut out = vec![0u16; height * out_width];
152 for r in 0..height {162 for r in 0..height {
153 let src = &rows[r * in_width..(r + 1) * in_width];163 let src = &rows[r * in_width..(r + 1) * in_width];
154 let dst = &mut out[r * out_width..(r + 1) * out_width];164 let dst = &mut out[r * out_width..(r + 1) * out_width];
@@ -158,7 +168,7 @@ pub(crate) fn upscale_plane(
158 }168 }
159 _ => &[],169 _ => &[],
160 };170 };
161- upscale_row(src, real_right, out_width, dst);171+ upscale_row(src, real_right, out_width, dst, bit_depth);
162 }172 }
163 out173 out
164 }174 }
@@ -185,51 +195,40 @@ pub(crate) fn upscale_picture(
185 picture: &crate::encode::Picture,195 picture: &crate::encode::Picture,
186 upscaled_width: usize,196 upscaled_width: usize,
187 margin: Option<&crate::encode::Picture>,197 margin: Option<&crate::encode::Picture>,
198+ bit_depth: u32,
188 ) -> crate::encode::Picture {199 ) -> crate::encode::Picture {
189 SUPERRES_HITS.with(|c| c.set(c.get() + 1));200 SUPERRES_HITS.with(|c| c.set(c.get() + 1));
190 let height = picture.height;201 let height = picture.height;
191 let chroma_in_w = picture.width.div_ceil(2);202 let chroma_in_w = picture.width.div_ceil(2);
192 let chroma_out_w = upscaled_width.div_ceil(2);203 let chroma_out_w = upscaled_width.div_ceil(2);
193 let chroma_h = height.div_ceil(2);204 let chroma_h = height.div_ceil(2);
194- // lane-hbd r4: superres is 8-bit by construction (`upscale_row` clamps
195- // to 255) -- narrow at this boundary; callers refuse `bit_depth != 8`
196- // before ever reaching here (see `stream.rs`).
197- let narrow = |v: &[u16]| -> Vec<u8> { v.iter().map(|&s| s as u8).collect() };
198- let picture_y8 = narrow(&picture.y);
199- let picture_u8 = narrow(&picture.u);
200- let picture_v8 = narrow(&picture.v);
201- let margin_y8 = margin.map(|m| narrow(&m.y));
202- let margin_u8 = margin.map(|m| narrow(&m.u));
203- let margin_v8 = margin.map(|m| narrow(&m.v));
204- let widen = |v: Vec<u8>| -> Vec<u16> { v.into_iter().map(u16::from).collect() };
205 crate::encode::Picture {205 crate::encode::Picture {
206 width: upscaled_width,206 width: upscaled_width,
207 height,207 height,
208- y: widen(upscale_plane(208+ y: upscale_plane(
209- &picture_y8,209+ &picture.y,
210 height,210 height,
211 picture.width,211 picture.width,
212 upscaled_width,212 upscaled_width,
213- margin_y8.as_deref().map(|m| (m, margin.unwrap().width)),213+ margin.map(|m| (m.y.as_slice(), m.width)),
214- )),214+ bit_depth,
215- u: widen(upscale_plane(215+ ),
216- &picture_u8,216+ u: upscale_plane(
217+ &picture.u,
217 chroma_h,218 chroma_h,
218 chroma_in_w,219 chroma_in_w,
219 chroma_out_w,220 chroma_out_w,
220- margin_u8221+ margin.map(|m| (m.u.as_slice(), m.width.div_ceil(2))),
221- .as_deref()222+ bit_depth,
222- .map(|m| (m, margin.unwrap().width.div_ceil(2))),223+ ),
223- )),224+ v: upscale_plane(
224- v: widen(upscale_plane(225+ &picture.v,
225- &picture_v8,
226 chroma_h,226 chroma_h,
227 chroma_in_w,227 chroma_in_w,
228 chroma_out_w,228 chroma_out_w,
229- margin_v8229+ margin.map(|m| (m.v.as_slice(), m.width.div_ceil(2))),
230- .as_deref()230+ bit_depth,
231- .map(|m| (m, margin.unwrap().width.div_ceil(2))),231+ ),
232- )),
233 }232 }
234 }233 }
235 234
@@ -249,17 +248,17 @@ mod tests {
249 /// here independently of this module's own logic.248 /// here independently of this module's own logic.
250 #[test]249 #[test]
251 fn upscale_row_matches_libaom_in8_out12() {250 fn upscale_row_matches_libaom_in8_out12() {
252- let row = [10u8, 20, 30, 40, 50, 60, 70, 80];251+ let row = [10u16, 20, 30, 40, 50, 60, 70, 80];
253- let mut out = [0u8; 12];252+ let mut out = [0u16; 12];
254- upscale_row(&row, &[], 12, &mut out);253+ upscale_row(&row, &[], 12, &mut out, 8);
255 assert_eq!(out, [9, 14, 22, 29, 35, 42, 48, 55, 61, 68, 76, 81]);254 assert_eq!(out, [9, 14, 22, 29, 35, 42, 48, 55, 61, 68, 76, 81]);
256 }255 }
257 256
258 #[test]257 #[test]
259 fn upscale_row_matches_libaom_in8_out16() {258 fn upscale_row_matches_libaom_in8_out16() {
260- let row = [10u8, 20, 30, 40, 50, 60, 70, 80];259+ let row = [10u16, 20, 30, 40, 50, 60, 70, 80];
261- let mut out = [0u8; 16];260+ let mut out = [0u16; 16];
262- upscale_row(&row, &[], 16, &mut out);261+ upscale_row(&row, &[], 16, &mut out, 8);
263 assert_eq!(262 assert_eq!(
264 out,263 out,
265 [9, 12, 17, 23, 28, 32, 37, 43, 48, 53, 58, 62, 67, 73, 78, 81]264 [9, 12, 17, 23, 28, 32, 37, 43, 48, 53, 58, 62, 67, 73, 78, 81]
@@ -273,10 +272,10 @@ mod tests {
273 /// captured-row pins above.272 /// captured-row pins above.
274 #[test]273 #[test]
275 fn upscale_row_of_a_flat_input_is_flat() {274 fn upscale_row_of_a_flat_input_is_flat() {
276- let row = [200u8; 8];275+ let row = [200u16; 8];
277- let mut out = [0u8; 12];276+ let mut out = [0u16; 12];
278- upscale_row(&row, &[], 12, &mut out);277+ upscale_row(&row, &[], 12, &mut out, 8);
279- assert_eq!(out, [200u8; 12]);278+ assert_eq!(out, [200u16; 12]);
280 }279 }
281 280
282 /// r3: the real 43->64 failing case, pinned against real libaom281 /// r3: the real 43->64 failing case, pinned against real libaom
@@ -287,14 +286,14 @@ mod tests {
287 /// margin fix.286 /// margin fix.
288 #[test]287 #[test]
289 fn upscale_row_with_real_margin_matches_libaom_in43_out64() {288 fn upscale_row_with_real_margin_matches_libaom_in43_out64() {
290- let row: [u8; 43] = [289+ let row: [u16; 43] = [
291 102, 102, 103, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116,290 102, 102, 103, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116,
292 117, 118, 119, 120, 121, 122, 123, 125, 126, 127, 127, 128, 129, 130, 130, 131, 131,291 117, 118, 119, 120, 121, 122, 123, 125, 126, 127, 127, 128, 129, 130, 130, 131, 131,
293 133, 134, 136, 137, 138, 139, 140, 140, 141,292 133, 134, 136, 137, 138, 139, 140, 140, 141,
294 ];293 ];
295- let real_margin = [140u8];294+ let real_margin = [140u16];
296- let mut out = [0u8; 64];295+ let mut out = [0u16; 64];
297- upscale_row(&row, &real_margin, 64, &mut out);296+ upscale_row(&row, &real_margin, 64, &mut out, 8);
298 assert_eq!(out[62], 141, "column 62 must match libaom, not the old replicate-padded 140");297 assert_eq!(out[62], 141, "column 62 must match libaom, not the old replicate-padded 140");
299 }298 }
300 }299 }
lanes/hbd10-r1.report.mdadded+123 -0
@@ -0,0 +1,123 @@
1+# lane-hbd10 round 1 report
2+
3+Branch `lane-hbd10`, worktree `edith_codecs-hbd10`, off main `3808cf8` (no rebase
4+needed -- branch was already at main's HEAD, `git log --oneline -1 main` = 3808cf8).
5+
6+## Refusals lifted (2)
7+
8+Both removed from `crates/ec-av1/src/refusal_inventory.rs` and from their
9+`stream.rs` guard sites, each with a real-aomenc 10-bit gate in the same commit:
10+
11+- `"a bit depth other than 8 with film grain applied (film_grain.rs's LUT and blend are hardcoded 8-bit)"`
12+- `"a bit depth other than 8 with use_superres set (superres.rs's upscale_row is hardcoded 8-bit)"`
13+
14+## What changed
15+
16+- `crates/ec-av1/src/film_grain.rs:180` -- `GRAIN_MIN`/`GRAIN_MAX` consts replaced by
17+ `GRAIN_BIT_DEPTH` (thread-local, set once per `apply_grain`) + `grain_range()`:
18+ `grain_center = 128 << (bit_depth - 8)`, mirroring libaom's file statics
19+ (`grain_synthesis.c:1043-1045`). All 10 clamp sites (luma/chroma AR filter,
20+ ver/hor overlap blending) now read the runtime range.
21+- `crates/ec-av1/src/film_grain.rs:230,265` -- `gauss_sec_shift` was hardcoded
22+ `4 + grain_scale_shift` (i.e. `12 - 8 + ...`); now `12 - bit_depth + grain_scale_shift`
23+ (`grain_synthesis.c:468,503`).
24+- `crates/ec-av1/src/film_grain.rs:~296` -- new `scale_lut()`, a verbatim port of
25+ `scale_LUT` (`grain_synthesis.c:616-626`): the scaling LUT stays 256 entries at
26+ every bit depth, so the index is `>> (bit_depth-8)` and the two neighbouring
27+ entries are interpolated with the dropped low bits (`x == 255` short-circuits).
28+ Used at all three blend sites (Y, Cb, Cr) in `add_noise_to_block`.
29+- `crates/ec-av1/src/film_grain.rs` `add_noise_to_block` -- `cb_offset`/`cr_offset`
30+ now `(offset << (bd-8)) - (1 << bit_depth)` (was `- 256`); the scaling-index clamp
31+ is `(256 << (bd-8)) - 1` (was `255`); `clip_to_restricted_range` legal ranges and
32+ the unrestricted max are `<< (bd-8)` (`grain_synthesis.c:752-795`).
33+- `crates/ec-av1/src/film_grain.rs:551` -- new `GRAIN_HITS` counter + `grain_hits()`
34+ (class `gate-blind-to-feature`), incremented once per grained picture.
35+- `crates/ec-av1/src/superres.rs` -- `upscale_row`/`upscale_plane`/`upscale_picture`
36+ take `&[u16]`/`bit_depth` instead of narrowing the (already `u16`) `Picture` planes
37+ to `u8` and back; the only bit-depth-dependent step in spec 7.16 is the output
38+ clamp, now `clamp(0, (1 << bit_depth) - 1)` (`clip_pixel_highbd`). Filter table,
39+ `Round2`, step/x0 and the real-margin edge padding are unchanged. The three
40+ libaom-pinned unit tests were retyped to `u16` and pass `bit_depth = 8`, so the
41+ 8-bit pins still hold byte-for-byte.
42+- `crates/ec-av1/src/stream.rs` -- both `bit_depth != 8` refusal blocks deleted;
43+ `apply_grain` (2 call sites) and `upscale_picture` (2 call sites) now receive the
44+ sequence header's real `bit_depth`.
45+- `crates/ec-av1/src/gate_coverage.rs` -- unchanged, deliberately: it derives its set
46+ from `--enable-*` flags only, and neither new gate enables or disables a tool that
47+ was not already covered. `every_gate_disabling_a_tool_is_a_listed_coverage_hole`
48+ stays green with the two new gates in the derived gate set.
49+
50+## Gates added (both hard-asserting, neither can SKIP on a mismatch)
51+
52+`crates/ec-av1/src/stream.rs`:
53+
54+1. `a_real_aomenc_10bit_film_grain_stream_decodes_pixel_exact` --
55+ `aomenc --bit-depth=10 --input-bit-depth=10 --film-grain-test=1` over a
56+ `yuv420p10le` lavfi gradients source, pixel-exact vs `ffmpeg_decode_sequence_10bit`
57+ (ffmpeg synthesizes grain by default; no grain-disable flag exists anywhere in
58+ this file). Hard-asserts the parsed `bit_depth == 10`, `apply_grain == true`,
59+ `num_y_points > 0` (an empty scaling LUT would blend a zero delta and make the
60+ gate vacuous), and `grain_hits()` moved.
61+2. `a_real_aomenc_10bit_superres_stream_decodes_pixel_exact` --
62+ `aomenc --bit-depth=10 --superres-mode=1 --superres-denominator=12
63+ --superres-kf-denominator=12`, same tool-disable envelope as the existing 8-bit
64+ superres gate. Hard-asserts `bit_depth == 10` and `superres_hits()` moved.
65+
66+Shared helpers `encode_10bit_gradients` / `parsed_bit_depth` factored out next to them.
67+
68+EVIDENCE: /tmp/claude-1000/.../tasks (test stdout) | `EC_AV1_REQUIRE_AOMENC=1 cargo test -j3 -p ec-av1 --lib 10bit_ -- --nocapture` | `test result: ok. 3 passed; 0 failed` -- `grain_hits=1`, `superres_hits=1`, all three planes exact
69+
70+### Sensitivity check (the gates are not vacuous)
71+
72+Temporarily passed a literal `8u32` instead of the real `bit_depth` at both call
73+sites (mutation reverted before commit):
74+- film-grain gate: panics in `film_grain.rs` `scale_lut` (a 10-bit sample indexes
75+ past the 256-entry LUT) -- proves the grain path really runs over 10-bit samples.
76+- superres gate: `assertion left == right failed: luma vs ffmpeg`, ours saturated at
77+ `255` where ffmpeg has 10-bit values -- proves the clamp is the thing under test.
78+
79+EVIDENCE: /home/user/.claude/projects/-home-user-Documents-Code-Rust-edith-codecs/b6d8a07f-96a4-4bbb-b378-af9ae25cf7c9/tool-results/b1odbi79e.txt | forced `bit_depth = 8` at both call sites, ran the two gates | both FAILED (LUT overrun / luma saturated at 255), both pass again with the mutation reverted
80+
81+## His films: does either actually use grain or superres?
82+
83+Extracted 2s (`-t 2 -c:v copy -an -f obu`, bounded) of each and counted header
84+flags with a throwaway `examples/hbd10_headers.rs` (deleted after the run; the
85+0.4s extract the charter names is only 1.8 KB / a handful of OBUs at 2160p, too
86+short to be representative, so the window was widened to 2s).
87+
88+| film | seq bit_depth | film_grain_params_present | enable_superres | frames | apply_grain | num_y_points>0 | use_superres |
89+|---|---|---|---|---|---|---|---|
90+| ReelB (Ballad, 2160p HDR10) | 10 | true | **false** | 50 | **25** | 25 | 0 |
91+| ReelC (Director's Cut, 1080p) | 10 | true | false | 49 | 0 | 0 | 0 |
92+
93+**ReelB really does carry film grain**: half its frames in the first 2s set
94+`apply_grain` with a non-empty luma scaling LUT, at 10 bit. That refusal was a real
95+blocker-in-waiting for his library, and it is gone. **Neither film uses superres**
96+(`enable_superres = false` in both sequence headers, `use_superres = 0` on every
97+frame) -- the superres refusal is lifted and gated, but it is not on his films' path.
98+
99+`decode_probe` on those extracts (this branch): both films still stop earlier than
100+grain/superres, at partition coverage -- unchanged by this lane, as expected:
101+- ReelB: `REFUSED: unsupported: AV1 tile (a partition below 8x8 (this decoder codes no leaf smaller than 8x8))`
102+- ReelC: `REFUSED: unsupported: AV1 tile (a 32x32 partition type this decoder does not code (value=4))`
103+
104+EVIDENCE: scratchpad reelb2.obu / reelc2.obu | `ffmpeg -t 2 -c:v copy -f obu` then `cargo run -p ec-av1 --example decode_probe` | ReelB apply_grain 25/50 frames, use_superres 0/50; both films' first refusal is the pre-existing partition gap
105+
106+## Test totals
107+
108+`EC_AV1_REQUIRE_AOMENC=1 nice -n 10 cargo test -j3 -p ec-av1 --lib`
109+-> **269 passed, 0 failed, 23 ignored, 0 filtered out, 334.60s.**
110+
111+EVIDENCE: /tmp/claude-1000/-home-user-Documents-Code-Rust-edith-codecs/b6d8a07f-96a4-4bbb-b378-af9ae25cf7c9/tasks/bsumuvd86.output | `EC_AV1_REQUIRE_AOMENC=1 cargo test -j3 -p ec-av1 --lib` | test result: ok. 269 passed; 0 failed; 23 ignored; 334.60s
112+
113+## Residue
114+
115+- accepted: 12-bit is code-generic (every formula is `bit_depth`-parameterised, not
116+ `10`-specialised) but ungated -- no 12-bit gate was written and none of his files
117+ is 12-bit. A 12-bit stream would decode, not refuse; that is a claim no test backs.
118+- accepted: grain at 4:2:2/4:4:4 stays out of scope -- `film_grain.rs` is 4:2:0 by
119+ construction (documented at the top of the module), unchanged by this lane.
120+- deferred: chroma-only grain params (`num_y_points == 0`, `chroma_scaling_from_luma`)
121+ at 10 bit are exercised by neither gate -- `--film-grain-test=1` sets luma points --
122+ what unblocks it: a `--film-grain-table` fixture that pins a chroma-only parameter
123+ set.