diff --git a/crates/ec-av1/src/film_grain.rs b/crates/ec-av1/src/film_grain.rs index a7472358..4ebaad44 100644 --- a/crates/ec-av1/src/film_grain.rs +++ b/crates/ec-av1/src/film_grain.rs @@ -1,6 +1,6 @@ //! AV1 film grain synthesis (spec 7.18.3), ported bit-exact from libaom's //! `av1/decoder/grain_synthesis.c` (`add_film_grain_run` and its helpers), -//! specialized to this crate's only picture shape: 8-bit, 4:2:0 planar +//! specialized to this crate's only picture shape: 4:2:0 planar //! (`chroma_subsamp_x = chroma_subsamp_y = 1` throughout, which is why every //! `<< (1 - subsamp)` in the reference collapses to a no-op and every //! `>> subsamp` collapses to `>> 1` below). @@ -43,9 +43,25 @@ const LUMA_BLOCK_W: i32 = const CHROMA_BLOCK_H: i32 = TOP_PAD + AR_PADDING + CHROMA_SUBBLOCK * 2 + BOTTOM_PAD; const CHROMA_BLOCK_W: i32 = LEFT_PAD + AR_PADDING + CHROMA_SUBBLOCK * 2 + AR_PADDING + RIGHT_PAD; -// bit_depth is always 8 in this crate: grain_center = 128 << (8 - 8) = 128. -const GRAIN_MIN: i32 = -128; -const GRAIN_MAX: i32 = 127; +thread_local! { + /// `params->bit_depth` of the picture currently being grained. libaom + /// keeps `grain_min`/`grain_max` as file statics set once per + /// `av1_add_film_grain_run` (`grain_synthesis.c:1041-1045`); this mirrors + /// that rather than threading a parameter through every helper. + static GRAIN_BIT_DEPTH: std::cell::Cell = const { std::cell::Cell::new(8) }; +} + +/// `params->bit_depth` for the [`apply_grain`] call in progress. +fn grain_bit_depth() -> u32 { + GRAIN_BIT_DEPTH.with(|c| c.get()) +} + +/// `grain_min`/`grain_max` (`grain_synthesis.c:1043-1045`): +/// `grain_center = 128 << (bit_depth - 8)`. +fn grain_range() -> (i32, i32) { + let center = 128i32 << (grain_bit_depth() - 8); + (-center, center - 1) +} const MIN_LUMA_LEGAL: i32 = 16; const MAX_LUMA_LEGAL: i32 = 235; @@ -121,11 +137,12 @@ fn generate_luma_grain_block( pred_pos: &[(i32, i32, i32)], rng: &mut Rng, ) -> Vec { + let (grain_min, grain_max) = grain_range(); let mut block = vec![0i32; (LUMA_BLOCK_H * LUMA_BLOCK_W) as usize]; if fg.num_y_points == 0 { return block; } - let gauss_sec_shift = 4 + fg.grain_scale_shift as i32; // 12 - 8 + grain_scale_shift + let gauss_sec_shift = 12 - grain_bit_depth() as i32 + fg.grain_scale_shift as i32; let ar_coeff_shift = fg.ar_coeff_shift_minus_6 as i32 + 6; let rounding_offset = 1i32 << (ar_coeff_shift - 1); @@ -143,7 +160,7 @@ fn generate_luma_grain_block( wsum += fg.ar_coeffs_y[idx] as i32 * at(&block, LUMA_BLOCK_W, i + dy, j + dx); } let v = (at(&block, LUMA_BLOCK_W, i, j) + ((wsum + rounding_offset) >> ar_coeff_shift)) - .clamp(GRAIN_MIN, GRAIN_MAX); + .clamp(grain_min, grain_max); set_at(&mut block, LUMA_BLOCK_W, i, j, v); } } @@ -157,9 +174,10 @@ fn generate_chroma_grain_blocks( luma_block: &[i32], seed: u16, ) -> (Vec, Vec) { + let (grain_min, grain_max) = grain_range(); let mut cb = vec![0i32; (CHROMA_BLOCK_H * CHROMA_BLOCK_W) as usize]; let mut cr = vec![0i32; (CHROMA_BLOCK_H * CHROMA_BLOCK_W) as usize]; - let gauss_sec_shift = 4 + fg.grain_scale_shift as i32; + let gauss_sec_shift = 12 - grain_bit_depth() as i32 + fg.grain_scale_shift as i32; let ar_coeff_shift = fg.ar_coeff_shift_minus_6 as i32 + 6; let rounding_offset = 1i32 << (ar_coeff_shift - 1); @@ -226,13 +244,13 @@ fn generate_chroma_grain_blocks( if apply_cb { let v = (at(&cb, CHROMA_BLOCK_W, i, j) + ((wsum_cb + rounding_offset) >> ar_coeff_shift)) - .clamp(GRAIN_MIN, GRAIN_MAX); + .clamp(grain_min, grain_max); set_at(&mut cb, CHROMA_BLOCK_W, i, j, v); } if apply_cr { let v = (at(&cr, CHROMA_BLOCK_W, i, j) + ((wsum_cr + rounding_offset) >> ar_coeff_shift)) - .clamp(GRAIN_MIN, GRAIN_MAX); + .clamp(grain_min, grain_max); set_at(&mut cr, CHROMA_BLOCK_W, i, j, v); } } @@ -265,7 +283,21 @@ fn build_scaling_lut(values: &[u8], scaling: &[u8], num_points: usize) -> [i32; lut } -/// `add_noise_to_block` (spec 7.18.3.5), 8-bit / 4:2:0 only. `(py0, px0)` is +/// `scale_LUT` (`grain_synthesis.c:616`): the scaling LUT has 256 entries +/// regardless of bit depth, so at 10/12 bit the index is shifted down and the +/// two neighbouring entries are interpolated with the dropped low bits. +fn scale_lut(lut: &[i32; 256], index: i32, bit_depth: u32) -> i32 { + let shift = bit_depth - 8; + let x = (index >> shift) as usize; + if shift == 0 || x == 255 { + lut[x] + } else { + lut[x] + (((lut[x + 1] - lut[x]) * (index & ((1 << shift) - 1)) + (1 << (shift - 1))) + >> shift) + } +} + +/// `add_noise_to_block` (spec 7.18.3.5), 4:2:0 only. `(py0, px0)` is /// the luma-plane pixel origin; the matching chroma origin is `(py0/2, /// px0/2)`. Grain is read from `(grain, stride, row0, col0)` triples so the /// same function serves both the raw 82x73/44x38 templates and the small @@ -295,13 +327,17 @@ fn add_noise_to_block( let y_stride = picture.width as i32; let c_stride = (picture.width / 2) as i32; let scaling_shift = fg.grain_scaling_minus_8 as i32 + 8; + let bit_depth = grain_bit_depth(); + let bd_shift = bit_depth - 8; + // `(256 << (bit_depth - 8)) - 1`, the scaling-LUT index clamp. + let index_max = (256i32 << bd_shift) - 1; let mut cb_mult = fg.cb_mult as i32 - 128; let mut cb_luma_mult = fg.cb_luma_mult as i32 - 128; - let mut cb_offset = fg.cb_offset as i32 - 256; + let mut cb_offset = ((fg.cb_offset as i32) << bd_shift) - (1 << bit_depth); let mut cr_mult = fg.cr_mult as i32 - 128; let mut cr_luma_mult = fg.cr_luma_mult as i32 - 128; - let mut cr_offset = fg.cr_offset as i32 - 256; + let mut cr_offset = ((fg.cr_offset as i32) << bd_shift) - (1 << bit_depth); if fg.chroma_scaling_from_luma { cb_mult = 0; cb_luma_mult = 64; @@ -318,21 +354,21 @@ fn add_noise_to_block( let (min_luma, max_luma, min_chroma, max_chroma) = if fg.clip_to_restricted_range { if mc_identity { ( - MIN_LUMA_LEGAL, - MAX_LUMA_LEGAL, - MIN_LUMA_LEGAL, - MAX_LUMA_LEGAL, + MIN_LUMA_LEGAL << bd_shift, + MAX_LUMA_LEGAL << bd_shift, + MIN_LUMA_LEGAL << bd_shift, + MAX_LUMA_LEGAL << bd_shift, ) } else { ( - MIN_LUMA_LEGAL, - MAX_LUMA_LEGAL, - MIN_CHROMA_LEGAL, - MAX_CHROMA_LEGAL, + MIN_LUMA_LEGAL << bd_shift, + MAX_LUMA_LEGAL << bd_shift, + MIN_CHROMA_LEGAL << bd_shift, + MAX_CHROMA_LEGAL << bd_shift, ) } } else { - (0, 255, 0, 255) + (0, index_max, 0, index_max) }; let cy0 = py0 / 2; @@ -349,8 +385,9 @@ fn add_noise_to_block( let scaled = (((average_luma * cb_luma_mult + cb_mult * picture.u[cidx] as i32) >> 6) + cb_offset) - .clamp(0, 255); - let delta = (scaling_cb[scaled as usize] * cb_grain[gidx] + rounding_offset) + .clamp(0, index_max); + let delta = (scale_lut(scaling_cb, scaled, bit_depth) * cb_grain[gidx] + + rounding_offset) >> scaling_shift; picture.u[cidx] = ((picture.u[cidx] as i32 + delta).clamp(min_chroma, max_chroma)) as u16; @@ -359,8 +396,9 @@ fn add_noise_to_block( let scaled = (((average_luma * cr_luma_mult + cr_mult * picture.v[cidx] as i32) >> 6) + cr_offset) - .clamp(0, 255); - let delta = (scaling_cr[scaled as usize] * cr_grain[gidx] + rounding_offset) + .clamp(0, index_max); + let delta = (scale_lut(scaling_cr, scaled, bit_depth) * cr_grain[gidx] + + rounding_offset) >> scaling_shift; picture.v[cidx] = ((picture.v[cidx] as i32 + delta).clamp(min_chroma, max_chroma)) as u16; @@ -372,7 +410,8 @@ fn add_noise_to_block( for j in 0..half_w * 2 { let pidx = ((py0 + i) * y_stride + (px0 + j)) as usize; let gidx = ((lg_row0 + i) * lg_stride + (lg_col0 + j)) as usize; - let delta = (scaling_y[picture.y[pidx] as usize] * luma_grain[gidx] + let delta = (scale_lut(scaling_y, picture.y[pidx] as i32, bit_depth) + * luma_grain[gidx] + rounding_offset) >> scaling_shift; picture.y[pidx] = @@ -398,6 +437,7 @@ fn ver_overlap_inplace( width: i32, height: i32, ) { + let (grain_min, grain_max) = grain_range(); for h in 0..height { if width == 1 { let l = at(dst, dst_stride, dst_row0 + h, dst_col0); @@ -407,7 +447,7 @@ fn ver_overlap_inplace( dst_stride, dst_row0 + h, dst_col0, - ((l * 23 + r * 22 + 16) >> 5).clamp(GRAIN_MIN, GRAIN_MAX), + ((l * 23 + r * 22 + 16) >> 5).clamp(grain_min, grain_max), ); } else { let l0 = at(dst, dst_stride, dst_row0 + h, dst_col0); @@ -419,14 +459,14 @@ fn ver_overlap_inplace( dst_stride, dst_row0 + h, dst_col0, - ((27 * l0 + 17 * r0 + 16) >> 5).clamp(GRAIN_MIN, GRAIN_MAX), + ((27 * l0 + 17 * r0 + 16) >> 5).clamp(grain_min, grain_max), ); set_at( dst, dst_stride, dst_row0 + h, dst_col0 + 1, - ((17 * l1 + 27 * r1 + 16) >> 5).clamp(GRAIN_MIN, GRAIN_MAX), + ((17 * l1 + 27 * r1 + 16) >> 5).clamp(grain_min, grain_max), ); } } @@ -447,6 +487,7 @@ fn hor_overlap_inplace( width: i32, height: i32, ) { + let (grain_min, grain_max) = grain_range(); if height == 1 { for w in 0..width { let t = at(dst, dst_stride, dst_row0, dst_col0 + w); @@ -456,7 +497,7 @@ fn hor_overlap_inplace( dst_stride, dst_row0, dst_col0 + w, - ((t * 23 + b * 22 + 16) >> 5).clamp(GRAIN_MIN, GRAIN_MAX), + ((t * 23 + b * 22 + 16) >> 5).clamp(grain_min, grain_max), ); } } else { @@ -470,14 +511,14 @@ fn hor_overlap_inplace( dst_stride, dst_row0, dst_col0 + w, - ((27 * t0 + 17 * b0 + 16) >> 5).clamp(GRAIN_MIN, GRAIN_MAX), + ((27 * t0 + 17 * b0 + 16) >> 5).clamp(grain_min, grain_max), ); set_at( dst, dst_stride, dst_row0 + 1, dst_col0 + w, - ((17 * t1 + 27 * b1 + 16) >> 5).clamp(GRAIN_MIN, GRAIN_MAX), + ((17 * t1 + 27 * b1 + 16) >> 5).clamp(grain_min, grain_max), ); } } @@ -496,6 +537,7 @@ fn copy_area( width: i32, height: i32, ) { + let (grain_min, grain_max) = grain_range(); for h in 0..height { for w in 0..width { let v = at(src, src_stride, src_row0 + h, src_col0 + w); @@ -504,15 +546,33 @@ fn copy_area( } } +thread_local! { + /// Firing count for the film-grain gates (class `gate-blind-to-feature`): + /// how many pictures actually ran through grain synthesis. + static GRAIN_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Current value of [`GRAIN_HITS`]. +pub(crate) fn grain_hits() -> usize { + GRAIN_HITS.with(|c| c.get()) +} + /// `av1_add_film_grain`/`add_film_grain_run` (spec 7.18.3.5): synthesize and /// apply film grain to `picture`, returning a new grained picture. `picture` /// itself is unchanged -- it stays the clean reference-frame-bank copy. /// Returns `picture.clone()` untouched when `apply_grain` is unset. -pub(crate) fn apply_grain(picture: &Picture, fg: &FilmGrainParams, mc_identity: bool) -> Picture { +pub(crate) fn apply_grain( + picture: &Picture, + fg: &FilmGrainParams, + mc_identity: bool, + bit_depth: u32, +) -> Picture { let mut out = picture.clone(); if !fg.apply_grain { return out; } + GRAIN_BIT_DEPTH.with(|c| c.set(bit_depth)); + GRAIN_HITS.with(|c| c.set(c.get() + 1)); let width = out.width as i32; let height = out.height as i32; let y_stride = width; diff --git a/crates/ec-av1/src/refusal_inventory.rs b/crates/ec-av1/src/refusal_inventory.rs index fb771602..9c2e1416 100644 --- a/crates/ec-av1/src/refusal_inventory.rs +++ b/crates/ec-av1/src/refusal_inventory.rs @@ -42,8 +42,6 @@ const REFUSALS: &[&str] = &[ "a 16x16 inter block whose true edge cuts through both axes needs a rectangular transform this decoder does not code yet", "a 32x32 partition type this decoder does not code (value={part32})", "a Golomb tail longer than this decoder reads", - "a bit depth other than 8 with film grain applied (film_grain.rs's LUT and blend are hardcoded 8-bit)", - "a bit depth other than 8 with use_superres set (superres.rs's upscale_row is hardcoded 8-bit)", "a superblock-level HORZ/VERT strip with a split transform (per-unit rect prediction is not ported)", "a tx_type symbol outside its CDF's own set: {t}", "an INTER 32x32 partition type this decoder does not code (value={part32})", diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index aaa96889..20dbbc98 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -128,23 +128,20 @@ pub fn decode_stream(data: &[u8]) -> Result> { } } let output = if header.film_grain.apply_grain { - // lane-hbd r5: `film_grain.rs`'s grain LUT and blend are - // hardcoded 8-bit (`[i32; 256]`, clamps at 255) -- narrowed - // from the old blanket bit-depth refusal to only the case - // that actually reaches unported code. + // lane-hbd10 r1: grain synthesis is bit-depth generic + // (`film_grain.rs`'s `grain_range`/`scale_lut`, spec 7.18.3). let bit_depth = parser .sequence_header() .map_or(8, |seq| seq.color_config.bit_depth); - if bit_depth != 8 { - return Err(Error::unsupported( - "AV1 decode_stream", - "a bit depth other than 8 with film grain applied (film_grain.rs's LUT and blend are hardcoded 8-bit)", - )); - } let mc_identity = parser .sequence_header() .is_some_and(|seq| seq.color_config.matrix_coefficients == 0); - crate::film_grain::apply_grain(&picture, &header.film_grain, mc_identity) + crate::film_grain::apply_grain( + &picture, + &header.film_grain, + mc_identity, + bit_depth as u32, + ) } else { picture }; @@ -509,20 +506,12 @@ pub fn decode_stream(data: &[u8]) -> Result> { // call above, right before anything else can overwrite it) -- // see `decode::take_last_frame_wide_margin`'s doc. let wide_margin = crate::decode::take_last_frame_wide_margin(); - // lane-hbd r5: `upscale_row` (superres.rs) is `&[u8]`, clamping at - // 255 -- narrowed from the old blanket bit-depth refusal to only - // the case that actually reaches unported code. - if header.use_superres && bit_depth != 8 { - return Err(Error::unsupported( - "AV1 decode_stream", - "a bit depth other than 8 with use_superres set (superres.rs's upscale_row is hardcoded 8-bit)", - )); - } let picture = if header.use_superres { crate::superres::upscale_picture( &picture, header.upscaled_width as usize, wide_margin.as_ref(), + bit_depth as u32, ) } else { picture @@ -634,6 +623,7 @@ pub fn decode_stream(data: &[u8]) -> Result> { &picture, header.upscaled_width as usize, wide_margin.as_ref(), + bit_depth as u32, ) } else { picture @@ -710,18 +700,15 @@ pub fn decode_stream(data: &[u8]) -> Result> { } if header.show_frame { let output = if header.film_grain.apply_grain { - // lane-hbd r5: same 8-bit-only LUT/blend as the - // show_existing_frame arm above. - if bit_depth != 8 { - return Err(Error::unsupported( - "AV1 decode_stream", - "a bit depth other than 8 with film grain applied (film_grain.rs's LUT and blend are hardcoded 8-bit)", - )); - } let mc_identity = parser .sequence_header() .is_some_and(|seq| seq.color_config.matrix_coefficients == 0); - crate::film_grain::apply_grain(&picture, &header.film_grain, mc_identity) + crate::film_grain::apply_grain( + &picture, + &header.film_grain, + mc_identity, + bit_depth as u32, + ) } else { picture }; @@ -1942,6 +1929,237 @@ mod tests { assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (10-bit)"); } + /// lane-hbd10 r1: a real `aomenc --bit-depth=10 --film-grain-test=1` + /// stream, decoded pixel-exact against ffmpeg's own 10-bit decode of the + /// identical bytes (ffmpeg synthesizes grain by default -- no + /// grain-disable flag is passed anywhere in this file). Proves the + /// bit-depth-generic grain path (`film_grain.rs`'s `grain_range`, + /// `scale_lut`, the `<< (bit_depth - 8)` offsets/legal ranges) rather + /// than the old `bit_depth != 8` refusal. HARD-asserts both the parsed + /// `bit_depth == 10` and `film_grain::grain_hits() > 0`, so neither a + /// silent 8-bit fallback nor a stream aomenc emitted without + /// `apply_grain` can make it pass vacuously. + #[test] + fn a_real_aomenc_10bit_film_grain_stream_decodes_pixel_exact() { + const NAME: &str = "a_real_aomenc_10bit_film_grain_stream_decodes_pixel_exact"; + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + if !have_aomenc() { + eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); + return; + } + let (width, height) = (64usize, 64usize); + let stream = encode_10bit_gradients( + NAME, + width, + height, + 1, + &["--film-grain-test=1", "--limit=1"], + ); + assert_eq!( + parsed_bit_depth(&stream), + 10, + "{NAME}: aomenc did not actually write a 10-bit sequence header" + ); + let mut probe = Av1Parser::new(); + let mut pos = 0usize; + let mut saw_grain = false; + while pos < stream.len() { + let obu = probe.parse_obu(&stream[pos..]).unwrap(); + pos += obu.total_size; + if let ObuKind::Frame(header, _) = obu.kind + && header.film_grain.apply_grain + { + // A grain block whose scaling LUT is empty would blend a + // zero delta into every pixel and let this gate pass without + // the bit-depth math mattering at all. + assert!( + header.film_grain.num_y_points > 0, + "{NAME}: apply_grain with no luma scaling points -- grain would be a no-op" + ); + saw_grain = true; + } + } + assert!(saw_grain, "{NAME}: aomenc did not turn on apply_grain"); + let before = crate::film_grain::grain_hits(); + let frames = match decode_stream(&stream) { + Ok(frames) => frames, + Err(e) => panic!("{NAME}: decode_stream refused: {e}"), + }; + assert!( + crate::film_grain::grain_hits() > before, + "{NAME}: matched but zero grain_hits -- grain synthesis never ran" + ); + let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1); + assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg"); + assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg"); + assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg"); + eprintln!("{NAME}: pixel-exact, grain_hits={}", crate::film_grain::grain_hits()); + } + + /// lane-hbd10 r1: a real `aomenc --bit-depth=10 --superres-mode=1 + /// --superres-denominator=12` key frame, decoded pixel-exact against + /// ffmpeg's own 10-bit decode. Proves `superres::upscale_row`'s + /// `clip_pixel_highbd` clamp (`(1 << bit_depth) - 1`) on real 10-bit + /// planes rather than the old `bit_depth != 8` refusal. HARD-asserts + /// `bit_depth == 10` and `superres_hits > 0`. + #[test] + fn a_real_aomenc_10bit_superres_stream_decodes_pixel_exact() { + const NAME: &str = "a_real_aomenc_10bit_superres_stream_decodes_pixel_exact"; + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + if !have_aomenc() { + eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); + return; + } + let (width, height) = (64usize, 64usize); + let stream = encode_10bit_gradients( + NAME, + width, + height, + 1, + &[ + "--limit=1", + "--kf-max-dist=0", + "--superres-mode=1", + "--superres-denominator=12", + "--superres-kf-denominator=12", + "--enable-rect-partitions=0", + "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", + "--enable-filter-intra=0", + "--enable-smooth-intra=0", + "--enable-paeth-intra=0", + "--enable-directional-intra=0", + "--enable-angle-delta=0", + "--enable-tx-size-search=0", + "--enable-cdef=0", + "--enable-restoration=0", + "--max-partition-size=32", + "--min-partition-size=32", + "--enable-palette=0", + "--enable-intrabc=0", + "--enable-cfl-intra=0", + ], + ); + assert_eq!( + parsed_bit_depth(&stream), + 10, + "{NAME}: aomenc did not actually write a 10-bit sequence header" + ); + let before = crate::superres::superres_hits(); + let frames = match decode_stream(&stream) { + Ok(frames) => frames, + Err(e) => panic!("{NAME}: decode_stream refused: {e}"), + }; + assert!( + crate::superres::superres_hits() > before, + "{NAME}: matched but zero superres_hits -- the upscaler never ran" + ); + let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1); + assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg"); + assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg"); + assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg"); + eprintln!( + "{NAME}: pixel-exact, superres_hits={}", + crate::superres::superres_hits() + ); + } + + /// `bit_depth` of the first sequence header in `stream`. + fn parsed_bit_depth(stream: &[u8]) -> u8 { + let mut probe = Av1Parser::new(); + let mut pos = 0usize; + while pos < stream.len() && probe.sequence_header().is_none() { + let obu = probe.parse_obu(&stream[pos..]).unwrap(); + pos += obu.total_size; + } + probe + .sequence_header() + .expect("stream has a sequence header OBU") + .color_config + .bit_depth + } + + /// Render `frames` of the shared `gradients_source` as `yuv420p10le` and + /// encode it with a real 10-bit `aomenc`, returning the OBU stream. + /// `extra` carries the tool flags under test. + fn encode_10bit_gradients( + name: &str, + width: usize, + height: usize, + frames: usize, + extra: &[&str], + ) -> Vec { + let duration = frames as f64 / 25.0; + let y4m = Command::new("ffmpeg") + .args([ + "-v", + "error", + "-f", + "lavfi", + "-i", + &gradients_source(42, width, height, &format!("duration={duration}:rate=25")), + "-pix_fmt", + "yuv420p10le", + "-strict", + "-1", + "-t", + &format!("{duration}"), + "-f", + "yuv4mpegpipe", + "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + y4m.status.success(), + "{name}: ffmpeg failed to render the 10-bit fixture: {}", + String::from_utf8_lossy(&y4m.stderr) + ); + let mut args: Vec<&str> = vec![ + "--codec=av1", + "--passes=1", + "--end-usage=q", + "--cq-level=30", + "--cpu-used=0", + "--threads=1", + "--row-mt=0", + "--sb-size=64", + "--input-bit-depth=10", + "--bit-depth=10", + ]; + args.extend_from_slice(extra); + args.extend_from_slice(&["--obu", "-o", "-", "-"]); + let mut child = Command::new(aomenc_path()) + .args(&args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("aomenc failed to start"); + child + .stdin + .take() + .expect("aomenc stdin") + .write_all(&y4m.stdout) + .expect("writing y4m to aomenc"); + let out = child.wait_with_output().expect("aomenc failed to run"); + assert!( + out.status.success(), + "{name}: aomenc refused the 10-bit fixture: {}", + String::from_utf8_lossy(&out.stderr) + ); + out.stdout + } + /// A real `aomenc` palette-**UV** fixture (lane-palette2 r2): `testsrc2` /// (the multicoloured AV1 test pattern -- flat, few-colour, repetitive /// per-region colour *and* chroma, unlike `smptebars=hue=s=0` above, diff --git a/crates/ec-av1/src/superres.rs b/crates/ec-av1/src/superres.rs index 6affd094..d49f2196 100644 --- a/crates/ec-av1/src/superres.rs +++ b/crates/ec-av1/src/superres.rs @@ -89,7 +89,16 @@ fn round_power_of_two(sum: i32, bits: u32) -> i32 { /// true, replicating the row's own edge pixels rather than sampling a /// neighbour tile). `in_width` and `out_width` must both be positive; /// `row.len() == in_width` and `out.len() == out_width`. -pub(crate) fn upscale_row(row: &[u8], real_right_margin: &[u8], out_width: usize, out: &mut [u8]) { +/// `bit_depth` only picks the output clamp (`clip_pixel`/`clip_pixel_highbd` +/// in libaom's `av1_convolve_horiz_rs_c`); the filter, its `Round2` and the +/// edge padding are bit-depth independent (spec 7.16). +pub(crate) fn upscale_row( + row: &[u16], + real_right_margin: &[u16], + out_width: usize, + out: &mut [u16], + bit_depth: u32, +) { let in_width = row.len(); debug_assert!(in_width > 0 && out_width > 0); 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 // column-by-column against real libaom via `scripts/superres-pin- // harness.c`'s `row6-realedgeval` case (r3). let pad = UPSCALE_NORMATIVE_TAPS + 2; - let mut padded = vec![0u8; in_width + 2 * pad]; + let mut padded = vec![0u16; in_width + 2 * pad]; padded[..pad].fill(row[0]); padded[pad..pad + in_width].copy_from_slice(row); 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 let idx = base + int_pel + k as i64; sum += padded[idx as usize] as i32 * c as i32; } - *out_x = round_power_of_two(sum, FILTER_BITS).clamp(0, 255) as u8; + *out_x = round_power_of_two(sum, FILTER_BITS).clamp(0, (1 << bit_depth) - 1) as u16; x_qn += x_step_qn; } } @@ -141,14 +150,15 @@ pub(crate) fn upscale_row(row: &[u8], real_right_margin: &[u8], out_width: usize /// spec only widens columns). `rows` is the plane's row-major byte buffer /// at `in_width`; returns a new buffer at `out_width`. pub(crate) fn upscale_plane( - rows: &[u8], + rows: &[u16], height: usize, in_width: usize, out_width: usize, - margin: Option<(&[u8], usize)>, -) -> Vec { + margin: Option<(&[u16], usize)>, + bit_depth: u32, +) -> Vec { debug_assert_eq!(rows.len(), height * in_width); - let mut out = vec![0u8; height * out_width]; + let mut out = vec![0u16; height * out_width]; for r in 0..height { let src = &rows[r * in_width..(r + 1) * in_width]; let dst = &mut out[r * out_width..(r + 1) * out_width]; @@ -158,7 +168,7 @@ pub(crate) fn upscale_plane( } _ => &[], }; - upscale_row(src, real_right, out_width, dst); + upscale_row(src, real_right, out_width, dst, bit_depth); } out } @@ -185,51 +195,40 @@ pub(crate) fn upscale_picture( picture: &crate::encode::Picture, upscaled_width: usize, margin: Option<&crate::encode::Picture>, + bit_depth: u32, ) -> crate::encode::Picture { SUPERRES_HITS.with(|c| c.set(c.get() + 1)); let height = picture.height; let chroma_in_w = picture.width.div_ceil(2); let chroma_out_w = upscaled_width.div_ceil(2); let chroma_h = height.div_ceil(2); - // lane-hbd r4: superres is 8-bit by construction (`upscale_row` clamps - // to 255) -- narrow at this boundary; callers refuse `bit_depth != 8` - // before ever reaching here (see `stream.rs`). - let narrow = |v: &[u16]| -> Vec { v.iter().map(|&s| s as u8).collect() }; - let picture_y8 = narrow(&picture.y); - let picture_u8 = narrow(&picture.u); - let picture_v8 = narrow(&picture.v); - let margin_y8 = margin.map(|m| narrow(&m.y)); - let margin_u8 = margin.map(|m| narrow(&m.u)); - let margin_v8 = margin.map(|m| narrow(&m.v)); - let widen = |v: Vec| -> Vec { v.into_iter().map(u16::from).collect() }; crate::encode::Picture { width: upscaled_width, height, - y: widen(upscale_plane( - &picture_y8, + y: upscale_plane( + &picture.y, height, picture.width, upscaled_width, - margin_y8.as_deref().map(|m| (m, margin.unwrap().width)), - )), - u: widen(upscale_plane( - &picture_u8, + margin.map(|m| (m.y.as_slice(), m.width)), + bit_depth, + ), + u: upscale_plane( + &picture.u, chroma_h, chroma_in_w, chroma_out_w, - margin_u8 - .as_deref() - .map(|m| (m, margin.unwrap().width.div_ceil(2))), - )), - v: widen(upscale_plane( - &picture_v8, + margin.map(|m| (m.u.as_slice(), m.width.div_ceil(2))), + bit_depth, + ), + v: upscale_plane( + &picture.v, chroma_h, chroma_in_w, chroma_out_w, - margin_v8 - .as_deref() - .map(|m| (m, margin.unwrap().width.div_ceil(2))), - )), + margin.map(|m| (m.v.as_slice(), m.width.div_ceil(2))), + bit_depth, + ), } } @@ -249,17 +248,17 @@ mod tests { /// here independently of this module's own logic. #[test] fn upscale_row_matches_libaom_in8_out12() { - let row = [10u8, 20, 30, 40, 50, 60, 70, 80]; - let mut out = [0u8; 12]; - upscale_row(&row, &[], 12, &mut out); + let row = [10u16, 20, 30, 40, 50, 60, 70, 80]; + let mut out = [0u16; 12]; + upscale_row(&row, &[], 12, &mut out, 8); assert_eq!(out, [9, 14, 22, 29, 35, 42, 48, 55, 61, 68, 76, 81]); } #[test] fn upscale_row_matches_libaom_in8_out16() { - let row = [10u8, 20, 30, 40, 50, 60, 70, 80]; - let mut out = [0u8; 16]; - upscale_row(&row, &[], 16, &mut out); + let row = [10u16, 20, 30, 40, 50, 60, 70, 80]; + let mut out = [0u16; 16]; + upscale_row(&row, &[], 16, &mut out, 8); assert_eq!( out, [9, 12, 17, 23, 28, 32, 37, 43, 48, 53, 58, 62, 67, 73, 78, 81] @@ -273,10 +272,10 @@ mod tests { /// captured-row pins above. #[test] fn upscale_row_of_a_flat_input_is_flat() { - let row = [200u8; 8]; - let mut out = [0u8; 12]; - upscale_row(&row, &[], 12, &mut out); - assert_eq!(out, [200u8; 12]); + let row = [200u16; 8]; + let mut out = [0u16; 12]; + upscale_row(&row, &[], 12, &mut out, 8); + assert_eq!(out, [200u16; 12]); } /// r3: the real 43->64 failing case, pinned against real libaom @@ -287,14 +286,14 @@ mod tests { /// margin fix. #[test] fn upscale_row_with_real_margin_matches_libaom_in43_out64() { - let row: [u8; 43] = [ + let row: [u16; 43] = [ 102, 102, 103, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 125, 126, 127, 127, 128, 129, 130, 130, 131, 131, 133, 134, 136, 137, 138, 139, 140, 140, 141, ]; - let real_margin = [140u8]; - let mut out = [0u8; 64]; - upscale_row(&row, &real_margin, 64, &mut out); + let real_margin = [140u16]; + let mut out = [0u16; 64]; + upscale_row(&row, &real_margin, 64, &mut out, 8); assert_eq!(out[62], 141, "column 62 must match libaom, not the old replicate-padded 140"); } } diff --git a/lanes/hbd10-r1.report.md b/lanes/hbd10-r1.report.md new file mode 100644 index 00000000..3f46f67f --- /dev/null +++ b/lanes/hbd10-r1.report.md @@ -0,0 +1,123 @@ +# lane-hbd10 round 1 report + +Branch `lane-hbd10`, worktree `edith_codecs-hbd10`, off main `3808cf8` (no rebase +needed -- branch was already at main's HEAD, `git log --oneline -1 main` = 3808cf8). + +## Refusals lifted (2) + +Both removed from `crates/ec-av1/src/refusal_inventory.rs` and from their +`stream.rs` guard sites, each with a real-aomenc 10-bit gate in the same commit: + +- `"a bit depth other than 8 with film grain applied (film_grain.rs's LUT and blend are hardcoded 8-bit)"` +- `"a bit depth other than 8 with use_superres set (superres.rs's upscale_row is hardcoded 8-bit)"` + +## What changed + +- `crates/ec-av1/src/film_grain.rs:180` -- `GRAIN_MIN`/`GRAIN_MAX` consts replaced by + `GRAIN_BIT_DEPTH` (thread-local, set once per `apply_grain`) + `grain_range()`: + `grain_center = 128 << (bit_depth - 8)`, mirroring libaom's file statics + (`grain_synthesis.c:1043-1045`). All 10 clamp sites (luma/chroma AR filter, + ver/hor overlap blending) now read the runtime range. +- `crates/ec-av1/src/film_grain.rs:230,265` -- `gauss_sec_shift` was hardcoded + `4 + grain_scale_shift` (i.e. `12 - 8 + ...`); now `12 - bit_depth + grain_scale_shift` + (`grain_synthesis.c:468,503`). +- `crates/ec-av1/src/film_grain.rs:~296` -- new `scale_lut()`, a verbatim port of + `scale_LUT` (`grain_synthesis.c:616-626`): the scaling LUT stays 256 entries at + every bit depth, so the index is `>> (bit_depth-8)` and the two neighbouring + entries are interpolated with the dropped low bits (`x == 255` short-circuits). + Used at all three blend sites (Y, Cb, Cr) in `add_noise_to_block`. +- `crates/ec-av1/src/film_grain.rs` `add_noise_to_block` -- `cb_offset`/`cr_offset` + now `(offset << (bd-8)) - (1 << bit_depth)` (was `- 256`); the scaling-index clamp + is `(256 << (bd-8)) - 1` (was `255`); `clip_to_restricted_range` legal ranges and + the unrestricted max are `<< (bd-8)` (`grain_synthesis.c:752-795`). +- `crates/ec-av1/src/film_grain.rs:551` -- new `GRAIN_HITS` counter + `grain_hits()` + (class `gate-blind-to-feature`), incremented once per grained picture. +- `crates/ec-av1/src/superres.rs` -- `upscale_row`/`upscale_plane`/`upscale_picture` + take `&[u16]`/`bit_depth` instead of narrowing the (already `u16`) `Picture` planes + to `u8` and back; the only bit-depth-dependent step in spec 7.16 is the output + clamp, now `clamp(0, (1 << bit_depth) - 1)` (`clip_pixel_highbd`). Filter table, + `Round2`, step/x0 and the real-margin edge padding are unchanged. The three + libaom-pinned unit tests were retyped to `u16` and pass `bit_depth = 8`, so the + 8-bit pins still hold byte-for-byte. +- `crates/ec-av1/src/stream.rs` -- both `bit_depth != 8` refusal blocks deleted; + `apply_grain` (2 call sites) and `upscale_picture` (2 call sites) now receive the + sequence header's real `bit_depth`. +- `crates/ec-av1/src/gate_coverage.rs` -- unchanged, deliberately: it derives its set + from `--enable-*` flags only, and neither new gate enables or disables a tool that + was not already covered. `every_gate_disabling_a_tool_is_a_listed_coverage_hole` + stays green with the two new gates in the derived gate set. + +## Gates added (both hard-asserting, neither can SKIP on a mismatch) + +`crates/ec-av1/src/stream.rs`: + +1. `a_real_aomenc_10bit_film_grain_stream_decodes_pixel_exact` -- + `aomenc --bit-depth=10 --input-bit-depth=10 --film-grain-test=1` over a + `yuv420p10le` lavfi gradients source, pixel-exact vs `ffmpeg_decode_sequence_10bit` + (ffmpeg synthesizes grain by default; no grain-disable flag exists anywhere in + this file). Hard-asserts the parsed `bit_depth == 10`, `apply_grain == true`, + `num_y_points > 0` (an empty scaling LUT would blend a zero delta and make the + gate vacuous), and `grain_hits()` moved. +2. `a_real_aomenc_10bit_superres_stream_decodes_pixel_exact` -- + `aomenc --bit-depth=10 --superres-mode=1 --superres-denominator=12 + --superres-kf-denominator=12`, same tool-disable envelope as the existing 8-bit + superres gate. Hard-asserts `bit_depth == 10` and `superres_hits()` moved. + +Shared helpers `encode_10bit_gradients` / `parsed_bit_depth` factored out next to them. + +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 + +### Sensitivity check (the gates are not vacuous) + +Temporarily passed a literal `8u32` instead of the real `bit_depth` at both call +sites (mutation reverted before commit): +- film-grain gate: panics in `film_grain.rs` `scale_lut` (a 10-bit sample indexes + past the 256-entry LUT) -- proves the grain path really runs over 10-bit samples. +- superres gate: `assertion left == right failed: luma vs ffmpeg`, ours saturated at + `255` where ffmpeg has 10-bit values -- proves the clamp is the thing under test. + +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 + +## His films: does either actually use grain or superres? + +Extracted 2s (`-t 2 -c:v copy -an -f obu`, bounded) of each and counted header +flags with a throwaway `examples/hbd10_headers.rs` (deleted after the run; the +0.4s extract the charter names is only 1.8 KB / a handful of OBUs at 2160p, too +short to be representative, so the window was widened to 2s). + +| film | seq bit_depth | film_grain_params_present | enable_superres | frames | apply_grain | num_y_points>0 | use_superres | +|---|---|---|---|---|---|---|---| +| ReelB (Ballad, 2160p HDR10) | 10 | true | **false** | 50 | **25** | 25 | 0 | +| ReelC (Director's Cut, 1080p) | 10 | true | false | 49 | 0 | 0 | 0 | + +**ReelB really does carry film grain**: half its frames in the first 2s set +`apply_grain` with a non-empty luma scaling LUT, at 10 bit. That refusal was a real +blocker-in-waiting for his library, and it is gone. **Neither film uses superres** +(`enable_superres = false` in both sequence headers, `use_superres = 0` on every +frame) -- the superres refusal is lifted and gated, but it is not on his films' path. + +`decode_probe` on those extracts (this branch): both films still stop earlier than +grain/superres, at partition coverage -- unchanged by this lane, as expected: +- ReelB: `REFUSED: unsupported: AV1 tile (a partition below 8x8 (this decoder codes no leaf smaller than 8x8))` +- ReelC: `REFUSED: unsupported: AV1 tile (a 32x32 partition type this decoder does not code (value=4))` + +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 + +## Test totals + +`EC_AV1_REQUIRE_AOMENC=1 nice -n 10 cargo test -j3 -p ec-av1 --lib` +-> **269 passed, 0 failed, 23 ignored, 0 filtered out, 334.60s.** + +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 + +## Residue + +- accepted: 12-bit is code-generic (every formula is `bit_depth`-parameterised, not + `10`-specialised) but ungated -- no 12-bit gate was written and none of his files + is 12-bit. A 12-bit stream would decode, not refuse; that is a claim no test backs. +- accepted: grain at 4:2:2/4:4:4 stays out of scope -- `film_grain.rs` is 4:2:0 by + construction (documented at the top of the module), unchanged by this lane. +- deferred: chroma-only grain params (`num_y_points == 0`, `chroma_scaling_from_luma`) + at 10 bit are exercised by neither gate -- `--film-grain-test=1` sets luma points -- + what unblocks it: a `--film-grain-table` fixture that pins a chroma-only parameter + set.