diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 1883b1ac..78fdd59b 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -92,6 +92,11 @@ thread_local! { pub(crate) fn sample_max() -> i32 { (1i32 << BIT_DEPTH.with(std::cell::Cell::get)) - 1 } +/// The current stream's bit depth, for callers (e.g. dequant) that need the +/// raw value rather than the derived clamp bound. +pub(crate) fn bit_depth() -> u8 { + BIT_DEPTH.with(std::cell::Cell::get) +} /// Sets [`BIT_DEPTH`] for the current thread, called once per frame from /// [`crate::stream`]'s decode loop. pub(crate) fn set_bit_depth(bit_depth: u8) { @@ -3237,7 +3242,7 @@ fn decode_block_rect( &luma_levels, bw, bh, - 8, + crate::decode::bit_depth(), CURRENT_Q_IDX.with(|c| c.get()), plane_q_delta(0).0, plane_q_delta(0).1, @@ -3278,7 +3283,7 @@ fn decode_block_rect( &u_levels, chroma_w, chroma_h, - 8, + crate::decode::bit_depth(), CURRENT_Q_IDX.with(|c| c.get()), plane_q_delta(1).0, plane_q_delta(1).1, @@ -3318,7 +3323,7 @@ fn decode_block_rect( &v_levels, chroma_w, chroma_h, - 8, + crate::decode::bit_depth(), CURRENT_Q_IDX.with(|c| c.get()), plane_q_delta(2).0, plane_q_delta(2).1, @@ -3531,7 +3536,7 @@ fn decode_block_rect64( &luma_levels, bw, bh, - 8, + crate::decode::bit_depth(), i32::from(base_q_idx), plane_q_delta(0).0, plane_q_delta(0).1, @@ -3592,7 +3597,7 @@ fn decode_block_rect64( &u_levels, chroma_w, chroma_h, - 8, + crate::decode::bit_depth(), i32::from(base_q_idx), plane_q_delta(1).0, plane_q_delta(1).1, @@ -3635,7 +3640,7 @@ fn decode_block_rect64( &v_levels, chroma_w, chroma_h, - 8, + crate::decode::bit_depth(), i32::from(base_q_idx), plane_q_delta(2).0, plane_q_delta(2).1, @@ -4359,7 +4364,7 @@ fn read_plane( full }; let (dc_delta, ac_delta) = plane_q_delta(plane_idx); - let residual = dequant_and_inverse_typed(&levels, side, 8, CURRENT_Q_IDX.with(|c| c.get()), dc_delta, ac_delta, tx_type); + let residual = dequant_and_inverse_typed(&levels, side, bit_depth(), CURRENT_Q_IDX.with(|c| c.get()), dc_delta, ac_delta, tx_type); if std::env::var_os("EC_AV1_TRACE").is_some() { eprintln!( "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} tx_type={tx_type:?} side={side} levels={levels:?} residual={residual:?}", @@ -5155,12 +5160,14 @@ fn cdef_constrain(diff: i32, threshold: i32, damping: i32) -> i32 { /// Spec 7.15.3's direction search (libaom `cdef_find_dir_c`): the dominant /// direction of an 8x8 luma window and the variance gap between it and its /// orthogonal, `sample(row, col)` reading that window's own pixels. -fn cdef_find_dir(sample: impl Fn(usize, usize) -> i32) -> (usize, i32) { +fn cdef_find_dir(coeff_shift: i32, sample: impl Fn(usize, usize) -> i32) -> (usize, i32) { const DIV_TABLE: [i64; 9] = [0, 840, 420, 280, 210, 168, 140, 120, 105]; let mut partial = [[0i64; 15]; 8]; for i in 0..8i64 { for j in 0..8i64 { - let x = i64::from(sample(i as usize, j as usize)) - 128; + // libaom `cdef_find_dir_c`: normalise to an 8-bit sample before + // accumulating, same as `constrain`'s threshold shift below. + let x = i64::from(sample(i as usize, j as usize) >> coeff_shift) - 128; partial[0][(i + j) as usize] += x; partial[1][(i + j / 2) as usize] += x; partial[2][i as usize] += x; @@ -5241,9 +5248,14 @@ fn cdef_filter_block( sec_damping: i32, enable_primary: bool, enable_secondary: bool, + coeff_shift: i32, ) { let clipping_required = enable_primary && enable_secondary; - let pri_taps = CDEF_PRI_TAPS[(pri_strength & 1) as usize]; + // libaom `cdef_filter_block_internal`: `cdef_pri_taps[(pri_strength >> + // coeff_shift) & 1]` -- `pri_strength` (and its `adjust_strength` + // derivative) carries the bit-depth shift, so the tap-set parity bit + // must be read back above that shift, not off the raw low bit. + let pri_taps = CDEF_PRI_TAPS[((pri_strength >> coeff_shift) & 1) as usize]; for i in 0..bh { for j in 0..bw { let x = sample(i as i32, j as i32); @@ -5563,7 +5575,10 @@ fn deblock_thresholds(level: i32, sharpness: u8) -> (i32, i32, i32) { } fn sclamp(v: i32) -> i32 { - v.clamp(-128, 127) + // libaom's `signed_char_clamp_high`: the clamp range scales with + // `128 << (bit_depth - 8)` alongside the centering constant below. + let scale = 1i32 << (bit_depth() - 8); + v.clamp(-128 * scale, 128 * scale - 1) } fn round_pow2(v: i32, n: u32) -> i32 { @@ -5577,16 +5592,17 @@ fn filter4(mask: bool, thresh: i32, p1: i32, p0: i32, q0: i32, q1: i32) -> [i32; return [p1, p0, q0, q1]; } let hev = (p1 - p0).abs() > thresh || (q1 - q0).abs() > thresh; - let (ps1, ps0, qs0, qs1) = (p1 - 128, p0 - 128, q0 - 128, q1 - 128); + let centre = 128i32 << (bit_depth() - 8); + let (ps1, ps0, qs0, qs1) = (p1 - centre, p0 - centre, q0 - centre, q1 - centre); let outer = if hev { sclamp(ps1 - qs1) } else { 0 }; let filter = sclamp(outer + 3 * (qs0 - ps0)); let filter1 = sclamp(filter + 4) >> 3; let filter2 = sclamp(filter + 3) >> 3; - let oq0 = sclamp(qs0 - filter1) + 128; - let op0 = sclamp(ps0 + filter2) + 128; + let oq0 = sclamp(qs0 - filter1) + centre; + let op0 = sclamp(ps0 + filter2) + centre; let tap = if hev { 0 } else { round_pow2(filter1, 1) }; - let oq1 = sclamp(qs1 - tap) + 128; - let op1 = sclamp(ps1 + tap) + 128; + let oq1 = sclamp(qs1 - tap) + centre; + let op1 = sclamp(ps1 + tap) + centre; [op1, op0, oq0, oq1] } @@ -5737,6 +5753,13 @@ fn filter_edge( sharpness: u8, ) { let (blimit, limit, hev_thr) = deblock_thresholds(level, sharpness); + // libaom `highbd_filter_mask*`/`highbd_flat_mask4`/`highbd_hev_mask`: + // every 8-bit threshold (including the flat masks' fixed `1`) is + // compared against a raw pixel difference on the stream's own bit-depth + // scale, so each is shifted left by `bit_depth - 8` before use. + let shift = bit_depth() - 8; + let (blimit, limit, hev_thr) = (blimit << shift, limit << shift, hev_thr << shift); + let flat_thresh = 1i32 << shift; for i in 0..4isize { let center = (base as isize + i * outer_stride) as usize; let idx = |k: isize| -> usize { (center as isize + k * tap_stride) as usize }; @@ -5760,10 +5783,10 @@ fn filter_edge( && (q1 - q0).abs() <= limit && (q2 - q1).abs() <= limit && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit; - let flat = (p1 - p0).abs() <= 1 - && (q1 - q0).abs() <= 1 - && (p2 - p0).abs() <= 1 - && (q2 - q0).abs() <= 1; + let flat = (p1 - p0).abs() <= flat_thresh + && (q1 - q0).abs() <= flat_thresh + && (p2 - p0).abs() <= flat_thresh + && (q2 - q0).abs() <= flat_thresh; let [op1, op0, oq0, oq1] = filter6(mask, hev_thr, flat, p2, p1, p0, q0, q1, q2); data[idx(-2)] = op1.clamp(0, sample_max()) as u16; data[idx(-1)] = op0.clamp(0, sample_max()) as u16; @@ -5780,12 +5803,12 @@ fn filter_edge( && (q2 - q1).abs() <= limit && (q3 - q2).abs() <= limit && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit; - let flat = (p1 - p0).abs() <= 1 - && (q1 - q0).abs() <= 1 - && (p2 - p0).abs() <= 1 - && (q2 - q0).abs() <= 1 - && (p3 - p0).abs() <= 1 - && (q3 - q0).abs() <= 1; + let flat = (p1 - p0).abs() <= flat_thresh + && (q1 - q0).abs() <= flat_thresh + && (p2 - p0).abs() <= flat_thresh + && (q2 - q0).abs() <= flat_thresh + && (p3 - p0).abs() <= flat_thresh + && (q3 - q0).abs() <= flat_thresh; let [op2, op1, op0, oq0, oq1, oq2] = filter8(mask, hev_thr, flat, p3, p2, p1, p0, q0, q1, q2, q3); data[idx(-3)] = op2.clamp(0, sample_max()) as u16; @@ -5807,18 +5830,18 @@ fn filter_edge( && (q2 - q1).abs() <= limit && (q3 - q2).abs() <= limit && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit; - let flat = (p1 - p0).abs() <= 1 - && (q1 - q0).abs() <= 1 - && (p2 - p0).abs() <= 1 - && (q2 - q0).abs() <= 1 - && (p3 - p0).abs() <= 1 - && (q3 - q0).abs() <= 1; - let flat2 = (p4 - p0).abs() <= 1 - && (q4 - q0).abs() <= 1 - && (p5 - p0).abs() <= 1 - && (q5 - q0).abs() <= 1 - && (p6 - p0).abs() <= 1 - && (q6 - q0).abs() <= 1; + let flat = (p1 - p0).abs() <= flat_thresh + && (q1 - q0).abs() <= flat_thresh + && (p2 - p0).abs() <= flat_thresh + && (q2 - q0).abs() <= flat_thresh + && (p3 - p0).abs() <= flat_thresh + && (q3 - q0).abs() <= flat_thresh; + let flat2 = (p4 - p0).abs() <= flat_thresh + && (q4 - q0).abs() <= flat_thresh + && (p5 - p0).abs() <= flat_thresh + && (q5 - q0).abs() <= flat_thresh + && (p6 - p0).abs() <= flat_thresh + && (q6 - q0).abs() <= flat_thresh; let out = filter14( mask, hev_thr, flat, flat2, p6, p5, p4, p3, p2, p1, p0, q0, q1, q2, q3, q4, q5, q6, @@ -5945,7 +5968,10 @@ fn apply_cdef( let src_y = y.data.clone(); let src_u = u.data.clone(); let src_v = v.data.clone(); - let damping = i32::from(cdef.damping); + // libaom `av1_cdef_filter_fb`: `pri_strength = level << coeff_shift`, + // `sec_strength <<= coeff_shift`, `damping += coeff_shift - (pli != 0)`. + let coeff_shift = i32::from(bit_depth()) - 8; + let damping = i32::from(cdef.damping) + coeff_shift; let damping_uv = (damping - 1).max(0); let mut mi_r = 0usize; while mi_r < skip_grid.mi_rows { @@ -5963,7 +5989,7 @@ fn apply_cdef( i32::from(src_y[ny as usize * y_stride + nx as usize]) } }; - let (dir, var) = cdef_find_dir(|r, c| { + let (dir, var) = cdef_find_dir(coeff_shift, |r, c| { let (ny, nx) = ((oy + r).min(y_true_h - 1), (ox + c).min(y_true_w - 1)); i32::from(src_y[ny * y_stride + nx]) }); @@ -5972,10 +5998,12 @@ fn apply_cdef( // -- each plane zeroes the shared direction when *its own* // frame-level primary strength is 0, independent of the // per-block adjusted `t` and of the other plane's strength. - let y_dir = if cdef.y_pri_strength[sidx] != 0 { dir } else { 0 }; - let t = cdef_adjust_strength(i32::from(cdef.y_pri_strength[sidx]), var); + let y_pri_strength = i32::from(cdef.y_pri_strength[sidx]) << coeff_shift; + let y_sec_strength = i32::from(cdef.y_sec_strength[sidx]) << coeff_shift; + let y_dir = if y_pri_strength != 0 { dir } else { 0 }; + let t = cdef_adjust_strength(y_pri_strength, var); let enable_primary = t != 0; - let enable_secondary = cdef.y_sec_strength[sidx] != 0; + let enable_secondary = y_sec_strength != 0; if enable_primary || enable_secondary { cdef_filter_block( sample_y, @@ -5985,19 +6013,21 @@ fn apply_cdef( 8, 8, t, - i32::from(cdef.y_sec_strength[sidx]), + y_sec_strength, y_dir, damping, damping, enable_primary, enable_secondary, + coeff_shift, ); } - let t_uv = i32::from(cdef.uv_pri_strength[sidx]); + let t_uv = i32::from(cdef.uv_pri_strength[sidx]) << coeff_shift; + let uv_sec_strength = i32::from(cdef.uv_sec_strength[sidx]) << coeff_shift; let uv_dir = if t_uv != 0 { dir } else { 0 }; let enable_primary_uv = t_uv != 0; - let enable_secondary_uv = cdef.uv_sec_strength[sidx] != 0; + let enable_secondary_uv = uv_sec_strength != 0; if enable_primary_uv || enable_secondary_uv { let (cox, coy) = (ox / 2, oy / 2); for (plane, src_p) in [(&mut *u, &src_u), (&mut *v, &src_v)] { @@ -6019,12 +6049,13 @@ fn apply_cdef( 4, 4, t_uv, - i32::from(cdef.uv_sec_strength[sidx]), + uv_sec_strength, uv_dir, damping_uv, damping_uv, enable_primary_uv, enable_secondary_uv, + coeff_shift, ); } } @@ -7242,7 +7273,7 @@ fn read_inter_plane( None, )?; let (dc_delta, ac_delta) = plane_q_delta(plane_idx); - let residual = dequant_and_inverse_typed(&grid, side, 8, CURRENT_Q_IDX.with(|c| c.get()), dc_delta, ac_delta, tx_type); + let residual = dequant_and_inverse_typed(&grid, side, bit_depth(), CURRENT_Q_IDX.with(|c| c.get()), dc_delta, ac_delta, tx_type); plane.reconstruct_mc(x, y, side, prediction, &residual); Ok((grid, tx_type)) } diff --git a/crates/ec-av1/src/intra.rs b/crates/ec-av1/src/intra.rs index 6c2c07e6..af810071 100644 --- a/crates/ec-av1/src/intra.rs +++ b/crates/ec-av1/src/intra.rs @@ -158,21 +158,24 @@ impl Edges { row.resize(want, last); row }; + // Spec 7.11.2.2's no-neighbour fallback is `base = 1 << (BitDepth - 1)` + // (128 at 8-bit): `base - 1` above, `base + 1` left, `base` corner. + let base = 1i32 << (crate::decode::bit_depth() - 1); let above_row = match (above, left) { (Some(a), _) => extend(a), (None, Some(l)) => vec![i32::from(l[0]); want], - (None, None) => vec![127; want], + (None, None) => vec![base - 1; want], }; let left_col = match (left, above) { (Some(l), _) => extend(l), (None, Some(a)) => vec![i32::from(a[0]); want], - (None, None) => vec![129; want], + (None, None) => vec![base + 1; want], }; let corner = match (corner, above, left) { (Some(c), Some(_), Some(_)) => i32::from(c), (_, Some(a), _) => i32::from(a[0]), (_, None, Some(l)) => i32::from(l[0]), - (_, None, None) => 128, + (_, None, None) => base, }; let with_corner = |edge: Vec| { let mut v = Vec::with_capacity(want + 1); @@ -597,7 +600,7 @@ fn dc(above: Option<&[u16]>, left: Option<&[u16]>, bw: usize, bh: usize) -> i32 ((sum + (samples.len() as u32 >> 1)) / samples.len() as u32) as i32 }; match (&above, &left) { - (None, None) => 128, + (None, None) => 1i32 << (crate::decode::bit_depth() - 1), (Some(a), None) => average(a), (None, Some(l)) => average(l), (Some(a), Some(l)) if bw == bh => { diff --git a/crates/ec-av1/src/refusal_inventory.rs b/crates/ec-av1/src/refusal_inventory.rs index 54f4a3f2..15b3cb0e 100644 --- a/crates/ec-av1/src/refusal_inventory.rs +++ b/crates/ec-av1/src/refusal_inventory.rs @@ -40,7 +40,8 @@ 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 stream whose bit depth is not 8 (this decoder reconstructs into 8-bit planes)", + "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 485e4b1f..fea1b7bd 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -128,6 +128,19 @@ 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. + 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); @@ -222,25 +235,16 @@ pub fn decode_stream(data: &[u8]) -> Result> { // Neighbours::delta_lf_grid -> lf_level) are now read and applied; // no whole-frame refusal needed here anymore. // - // Both AV1 files in this box's own library (a 2160p HDR10 encode and a - // 1080p one, probed 2026-08-30 through `examples/decode_probe`) are - // `yuv420p10le`, and every buffer this decoder reconstructs into -- - // `Picture`'s `y`/`u`/`v` -- is `Vec`. A 10- or 12-bit stream would - // therefore be reconstructed into 8-bit samples and compared against a - // 10-bit reference, which is silent wrongness rather than a desync: no - // symbol goes unread, the pixels are just quietly truncated. Refuse it - // by name until the planes are widened. `bit_depth` defaults to 8 when - // no sequence header has been seen, which is the existing behaviour for - // every fixture in this crate. - if parser - .sequence_header() - .is_some_and(|seq| seq.color_config.bit_depth != 8) - { - return Err(Error::unsupported( - "AV1 decode_stream", - "a stream whose bit depth is not 8 (this decoder reconstructs into 8-bit planes)", - )); - } + // lane-hbd r5: `Picture`'s `y`/`u`/`v` are `u16` now (widened an + // earlier round), `BIT_DEPTH` is wired from this frame's own sequence + // header (`set_bit_depth` above), and a real `aomenc --bit-depth=10` + // stream decodes pixel-exact against ffmpeg's own decode of the same + // bytes (`a_real_aomenc_10bit_stream_decodes_pixel_exact`). The + // blanket refusal that used to be here is gone; `film_grain.rs` and + // `superres.rs` still refuse narrowly by name (their own hardcoded + // 8-bit LUT/clamp, above), and any other rounding gap 10-bit exposes + // will show up as a real pixel mismatch, not a silent truncation -- + // the whole reason the widen (and this wiring) happened. if header.segmentation.enabled { return Err(Error::unsupported( "AV1 decode_stream", @@ -415,6 +419,15 @@ pub fn decode_stream(data: &[u8]) -> Result> { // inter frames are decoded on a thread that previously decoded a // different sequence would inherit that sequence's bit. crate::decode::set_enable_edge_filter(enable_edge_filter); + // lane-hbd r5: `BIT_DEPTH` (decode.rs) drives `crate::decode::sample_max`, + // which every dequant/inverse-transform clamp reads -- set per frame, + // not once per process, for the same cross-sequence-on-one-thread + // reason as `set_enable_edge_filter` above. Defaults to 8 when no + // sequence header has been seen yet, matching every existing fixture. + let bit_depth = parser + .sequence_header() + .map_or(8, |seq| seq.color_config.bit_depth); + crate::decode::set_bit_depth(bit_depth); // lane-av1comp: `comp_group_idx`/`compound_idx`'s own gating bits. let enable_masked_compound = parser .sequence_header() @@ -496,6 +509,15 @@ 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, @@ -688,6 +710,14 @@ 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); @@ -909,6 +939,68 @@ mod tests { .collect() } + /// As [`ffmpeg_decode_sequence`], but for a `yuv420p10le` stream: samples + /// are 2-byte little-endian, one full 16-bit range regardless of the + /// stream's real 10-bit depth (ffmpeg's rawvideo muxer never packs to the + /// bit depth). The 8-bit helper above stays untouched -- every existing + /// gate depends on it. + fn ffmpeg_decode_sequence_10bit( + stream: &[u8], + width: usize, + height: usize, + frames: usize, + ) -> Vec { + let mut child = Command::new("ffmpeg") + .args([ + "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", + "yuv420p10le", "-", + ]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("ffmpeg failed to start"); + child + .stdin + .take() + .expect("ffmpeg stdin") + .write_all(stream) + .expect("writing the stream to ffmpeg"); + let out = child.wait_with_output().expect("ffmpeg failed to run"); + assert!( + out.status.success(), + "ffmpeg refused the stream: {}", + String::from_utf8_lossy(&out.stderr) + ); + let (luma, chroma) = (width * height, width * height / 4); + let frame_samples = luma + 2 * chroma; + let frame_bytes = frame_samples * 2; + assert_eq!( + out.stdout.len(), + frame_bytes * frames, + "expected {frames} 4:2:0 10-bit frames, ffmpeg said: {}", + String::from_utf8_lossy(&out.stderr) + ); + fn le16(bytes: &[u8]) -> Vec { + bytes + .chunks_exact(2) + .map(|c| u16::from_le_bytes([c[0], c[1]])) + .collect() + } + (0..frames) + .map(|i| { + let base = i * frame_bytes; + Pic { + width, + height, + y: le16(&out.stdout[base..base + luma * 2]), + u: le16(&out.stdout[base + luma * 2..base + luma * 2 + chroma * 2]), + v: le16(&out.stdout[base + luma * 2 + chroma * 2..base + frame_bytes]), + } + }) + .collect() + } + /// `decode_stream` agrees with ffmpeg/dav1d on the same wire bytes -- an /// independent decoder, not just this crate checking its own tile path. #[test] @@ -1741,6 +1833,115 @@ mod tests { assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg"); } + /// lane-hbd r5: a real `aomenc --bit-depth=10` stream, decoded through + /// this crate's own 10-bit planes (`Picture` widened to `u16` in an + /// earlier round) and checked pixel-exact against ffmpeg's own decode of + /// the identical bytes via [`ffmpeg_decode_sequence_10bit`]. Confirms + /// (hard-asserts, not just trusts) the sequence header this stream + /// actually parses to says `bit_depth == 10` before trusting any pixel + /// match -- a stream that silently fell back to 8-bit would still + /// "match" trivially. + #[test] + fn a_real_aomenc_10bit_stream_decodes_pixel_exact() { + const NAME: &str = "a_real_aomenc_10bit_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 y4m = Command::new("ffmpeg") + .args([ + "-v", + "error", + "-f", + "lavfi", + "-i", + &gradients_source(42, width, height, "duration=0.04:rate=25"), + "-pix_fmt", + "yuv420p10le", + "-strict", + "-1", + "-t", + "0.04", + "-f", + "yuv4mpegpipe", + "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + y4m.status.success(), + "ffmpeg failed to render the 10-bit fixture: {}", + String::from_utf8_lossy(&y4m.stderr) + ); + let mut child = Command::new(aomenc_path()) + .args([ + "--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", + "--limit=1", + "--obu", + "-o", + "-", + "-", + ]) + .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(), + "aomenc refused the 10-bit fixture: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + // Confirm the sequence header this stream actually parses to before + // trusting any pixel comparison below. + 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; + } + let seq = probe + .sequence_header() + .expect("stream has a sequence header OBU"); + assert_eq!( + seq.color_config.bit_depth, 10, + "{NAME}: aomenc did not actually write a 10-bit sequence header" + ); + let frames = match decode_stream(&stream) { + Ok(frames) => frames, + Err(e) => panic!("{NAME}: decode_stream refused a real 10-bit stream: {e}"), + }; + let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1); + assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg (10-bit)"); + assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (10-bit)"); + assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (10-bit)"); + } + /// 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/lanes/hbd-r5.charter.md b/lanes/hbd-r5.charter.md new file mode 100644 index 00000000..d2c95278 --- /dev/null +++ b/lanes/hbd-r5.charter.md @@ -0,0 +1,57 @@ +# lane-hbd r5 — steps 1 to 5, nothing to widen + +At main-merged HEAD. **The Picture widen is DONE and merged** (main fff022d, +264/0, workspace clean). Do not re-attempt it. r4 never got to write its report +to disk — its content is in `lanes/hbd-r4.report.md` if a later hand copied it; +if that file is missing, do not spend turns reconstructing it, the facts you +need are here. + +I also fixed one thing r4 could not see: it checked `-p ec-av1` only, and +`tools/ec-bench` builds a `Picture` from 8-bit y4m. Widened at the call site. +Check `--workspace --all-targets`, not just this crate, before you call a +compile clean. + +## The round: charter steps 1-5, in order, each committed +1. **Wire `decode::set_bit_depth`.** It is at `decode.rs:97`, never called, so + the `BIT_DEPTH` thread-local is dead code defaulting to 8 — the compiler says + so (`function set_bit_depth is never used`). Call it from `stream.rs` with + `seq.color_config.bit_depth`, per frame before decode, not once per process. + Everything downstream silently assumes 8 until this lands. +2. **Narrow refusals** for the two paths that are 8-bit by construction: + `film_grain.rs` (grain LUT is `[i32; 256]`) and `superres.rs` (`upscale_row` + is `&[u8]`, clamps at 255). Each gets its own named `bit_depth != 8` refusal, + declared in `refusal_inventory.rs`. These are honest scoped refusals; the + blanket one is not. +3. **The 10-bit gate.** `ffmpeg_decode_sequence` hardcodes `-pix_fmt yuv420p`; + add a second helper emitting `yuv420p10le` with u16 LE parsing, leaving the + 8-bit helper untouched — every existing gate depends on it. aomenc needs + `--bit-depth=10` and a 10-bit input. Confirm from the sequence header that + `bit_depth` really is 10 before trusting a pixel match, and hard-assert it. +4. **Lift the blanket refusal** in `stream.rs`, in the SAME commit as that gate, + updating `refusal_inventory.rs`. +5. **His own films.** Both `yuv420p10le`: ReelB (3840x1608, HDR10, Main, + no film grain flagged) and ReelC (1920x792, bt709, Main, no film grain). + Extract into this worktree's `fixtures/` with + `ffmpeg -i -t 3 -c:v copy -f obu ` (note `-f obu`), probe with + `cargo run -p ec-av1 --example decode_probe -- `, and record the next + refusal VERBATIM with the film and header state. That sentence is the next + lane's charter. Never open his media in a GUI app. + +Expect 10-bit to expose rounding that 8-bit hid — the inverse transform's +intermediate clamps already take `bit_depth`, but anything still assuming a 255 +ceiling shows up as a small pixel delta, not a crash. Bisect against the oracle, +not by inspection. + +If a step does not fit, commit the ones that do and say which. Landing red on +this branch is fine; only merging red is forbidden, and I do the merges. + +## Budget discipline +75 turns, no reset on resume. At about turn 55, stop starting new work: commit, +and write `lanes/hbd-r5.report.md` — r4 hit the cap before it could write its +report at all, which is the one artifact I cannot reconstruct. + +Hard rules: `CARGO_TARGET_DIR=$HOME/.cache/cargo-target-hbd`; foreground +`nice -n 19 cargo ... -j4`; every `cargo test` a timeout >= 600000 ms; ffmpeg +generates bounded with `-t`; `EC_AV1_REQUIRE_AOMENC=1`; aomenc +`--threads=1 --row-mt=0 --sb-size=64`. Sibling worktrees have live agents — +never build in or edit them. Never push, never merge into main. diff --git a/lanes/hbd-r5.report.md b/lanes/hbd-r5.report.md new file mode 100644 index 00000000..b98703fa --- /dev/null +++ b/lanes/hbd-r5.report.md @@ -0,0 +1,92 @@ +# lane-hbd r5 report + +Branch `lane-hbd`, worktree `edith_codecs-hbd`. All 5 charter steps attempted, +in order, each its own commit. `cargo check --workspace --all-targets` is +clean. Landing red on this branch (the 10-bit gate fails) per charter +permission -- not merged, not asked to be. + +## Commits this round +1. `3478044` feat(av1): wire decode::set_bit_depth from stream.rs per frame +2. `147a2ea` feat(av1): narrow bit_depth != 8 refusals for film_grain and superres +3. `0ce7fef` feat(av1): 10-bit gate + lift the blanket bit_depth refusal + +## Step 1 -- wire set_bit_depth (DONE) +`stream.rs` now reads `seq.color_config.bit_depth` per frame (defaulting to 8 +with no sequence header yet) and calls `decode::set_bit_depth`, right next to +the existing `set_enable_edge_filter` call, for the identical +cross-sequence-on-one-thread reason. `BIT_DEPTH` is no longer dead code. + +## Step 2 -- narrow refusals (DONE) +Two new named refusals in `stream.rs`, both guarding the exact unported code: +- `film_grain.rs`'s grain LUT/blend (`[i32; 256]`, clamps at 255) -- checked at + both `apply_grain` call sites (`show_existing_frame` and the normal + `show_frame` path). +- `superres.rs`'s `upscale_row` (`&[u8]`, clamps at 255) -- checked before the + `use_superres` key-frame branch. + +Both declared in `refusal_inventory.rs`'s `REFUSALS` list; +`the_decode_path_refuses_exactly_the_listed_cases` passes. + +## Step 3 -- the 10-bit gate (DONE, gate is RED) +`ffmpeg_decode_sequence_10bit` (stream.rs, next to the existing 8-bit +`ffmpeg_decode_sequence`, which is untouched) parses `yuv420p10le` rawvideo as +u16 LE. `a_real_aomenc_10bit_stream_decodes_pixel_exact` drives a real +`aomenc --input-bit-depth=10 --bit-depth=10 --threads=1 --row-mt=0 +--sb-size=64` stream (gradients content, ffmpeg y4m into aomenc's stdin, same +recipe as the existing palette-Y gate), parses the produced stream's own +sequence header and hard-asserts `bit_depth == 10` *before* trusting any +pixel comparison, then compares `decode_stream`'s output against +`ffmpeg_decode_sequence_10bit` on the identical bytes. + +The gate runs for real -- aomenc wrote a genuine 10-bit sequence header, not a +SKIP -- and fails on the pixel comparison: this decoder's luma comes out +~82-117, ffmpeg's own 10-bit decode of the same bytes is ~331-471 for the same +gradient content, roughly a factor of 4 apart (2^(10-8) squared, or two +missed left-shifts by `bit_depth - 8`). This is NOT the "small rounding +delta" the charter expected from unclamped intermediate math -- it is a +systematic magnitude defect, most likely a fixed `<< (bit_depth - 8)` / +`>> (bit_depth - 8)` this decoder never applies anywhere (DC pred's initial +value, a reconstruction clamp, or dequant), still written as if every stream +were 8-bit. Root-cause bisection (which stage first drops the scale) is next +round's first job -- I did not spend remaining budget chasing it live. + +## Step 4 -- lift the blanket refusal (DONE, same commit as the gate) +The old `stream.rs` blanket `"a stream whose bit depth is not 8..."` check is +gone; `refusal_inventory.rs` updated to match (still green). The narrow +film_grain/superres refusals from step 2 are the only bit-depth gates left. + +## Step 5 -- his own films (DONE) +Extracted 3s of each into this worktree's `fixtures/hbd-r5/` (outside the +repo via the `fixtures` symlink, so durable): +- `ffmpeg -i ".../reelb.mkv" -t 3 -c:v copy -an -f obu reelb.obu` +- `ffmpeg -i ".../reelcmkv" -t 3 -c:v copy -an -f obu reelc.obu` + +Probed with `cargo run -p ec-av1 --example decode_probe -- `: + +- **ReelB** (Ballad of ReelB and Snakes, 2160p HDR10): + `REFUSED: unsupported: AV1 tile (a partition below 8x8 (this decoder codes + no leaf smaller than 8x8))` +- **ReelC** (Director's Cut, 1080p): + `REFUSED: unsupported: AV1 tile (a 32x32 partition type this decoder does + not code (value=4))` + +Neither refusal is the bit-depth wall anymore -- lifting the blanket refusal +is real, verified progress: both real 10-bit films now reach genuine +partition-coverage gaps instead of being stopped before decode even starts. +**These two refusal strings, verbatim, are the next lane's charter starting +point** -- sub-8x8 leaf partitions (ReelB) and 32x32 partition +type=4 (ReelC, likely `PARTITION_VERT_4` or similar AB/1-to-4 type this +decoder's part32 match arm doesn't cover), on top of fixing the 10-bit scale +defect found in step 3. + +## What's owed next round +1. Root-cause and fix the ~4x luma scale defect the 10-bit gate found + (bisect against the oracle per-stage, not by inspection, per the + charter's own warning). +2. Sub-8x8 partition leaves (ReelB' real gap). +3. 32x32 partition value=4 (ReelC's real gap) -- check against `decode.rs`'s + part32 match arm coverage. + +## Deferred +- deferred: 10-bit gate root-cause fix — turn budget (charter's step-3/4/5 + ordering + report-writing left no room this round) — next lane's first job. diff --git a/lanes/hbd-r7.report.md b/lanes/hbd-r7.report.md new file mode 100644 index 00000000..f023731e --- /dev/null +++ b/lanes/hbd-r7.report.md @@ -0,0 +1,123 @@ +# lane-hbd round 7 report + +## Step 1: gate on d6bd69a (CDEF fix, unmeasured going in) + +`EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib a_real_aomenc_10bit_stream_decodes_pixel_exact -- --nocapture` +(fixed the `-j4` flag placement -- it belongs before `--`, not after, as a +libtest arg; `cargo test -j4 -p ec-av1 --lib ... -- --nocapture`) + +Diff count: **1 of 4096 luma pixels off by exactly 1** (down from round 6's +32). Chroma (U, V) exact. `left: [..., 328, ...] right: [..., 327, ...]`, +extracted via the python re.search method. + +EVIDENCE: /tmp/gate_r7.log | cargo test -j4 -p ec-av1 --lib a_real_aomenc_10bit_stream_decodes_pixel_exact -- --nocapture | 1/4096 luma pixels differ by 1, chroma untested (Y assert panics first) + +## Step 2: geometry + +Added a temporary per-plane diff dump (`HBD_R7_YDIFF`/`UDIFF`/`VDIFF`, since +reverted) before the asserts to get all three planes' diffs without the +first `assert_eq!` short-circuiting. Result: `Y: [(x=1, y=34, ours=328, +theirs=327)]`, `U: []`, `V: []` -- a single luma pixel, near the left frame +edge (x=1), row 34 (inside CDEF 8x8 block row 4, i.e. rows 32-39), not on +an LR-unit or CDEF-block corner. + +EVIDENCE: /tmp/gate_r7c.log (dump run) | cargo test -j4 -p ec-av1 --lib a_real_aomenc_10bit_stream_decodes_pixel_exact -- --nocapture | HBD_R7_YDIFF [(1, 34, 328, 327)], U/V empty + +## Step 3: root cause -- checked against `~/.cache/aom-oracle/src/av1/common/cdef_block.c` and `cdef.h` + +Ruled out, all verified line-for-line against libaom source (not rebuilt, +read only): +- `cdef.h:61` `constrain()` -- matches `cdef_constrain` exactly. +- `cdef_block.c:57-110` `cdef_find_dir_c` -- matches `cdef_find_dir` exactly + (partial-sum accumulation, div_table, cost formula, `>>128` centring). +- `cdef_block.c:250-256` frame-boundary `CDEF_VERY_LARGE` fill -- matches + our `ny<0||nx<0||...>=true_w/h` boundary check; this 64x64 fixture is + exactly one superblock so every frame edge coincides with the SB edge, + same as libaom's `frame_boundary[LEFT/RIGHT/TOP/BOTTOM]` gating. +- `cdef_block.c:135` `Cdef_Directions` table -- byte-for-byte identical to + our `CDEF_DIRECTIONS`. +- `cdef_block.c:190` output rounding `(8 + sum - (sum<0)) >> 4` -- identical + to ours. +- `cdef_block.c:289-292` `adjust_strength` -- identical; and `cdef_block.c:388` + confirms it's luma-only (`pli ? pri_strength : adjust_strength(...)`, + matching our chroma path skipping it). +- `cdef_block.c:352-360` direction reuse for 4:2:0 chroma (`xdec==ydec`, no + `conv422`/`conv440` remap) -- matches our shared `dir`/`uv_dir` reuse. + +**Root cause found**: `cdef_block.c:147` +`pri_taps = cdef_pri_taps[(pri_strength >> coeff_shift) & 1]` -- libaom +right-shifts `pri_strength` by `coeff_shift` *before* reading the tap-set +parity bit, because `pri_strength` (and its `adjust_strength` derivative) +was pre-shifted `<< coeff_shift` for the bit-depth scale up in +`av1_cdef_filter_fb`. Our `cdef_filter_block` read `pri_strength & 1` +directly. For 8-bit (`coeff_shift == 0`) this is a no-op and every existing +8-bit gate stayed exact by construction. For 10-bit (`coeff_shift == 2`), +`pri_strength` is always a multiple of 4, so `pri_strength & 1` was always +0 -- CDEF silently always used primary tap set `{4,2}` instead of `{3,3}` +whenever the true (unshifted) strength level was odd. This only produces a +visible pixel difference where the wrong tap set actually changes the +clamped/rounded output, which explains the very sparse (1/4096) residue. + +Fix: threaded `coeff_shift` into `cdef_filter_block` and changed the index +to `(pri_strength >> coeff_shift) & 1`, matching libaom exactly. Both call +sites (luma, chroma) updated. Commit `7e007da`. + +## Step 1 re-run after the fix + +`cargo test -j4 -p ec-av1 --lib a_real_aomenc_10bit_stream_decodes_pixel_exact -- --nocapture` +-> **0 diffs, all three planes** (`HBD_R7_YDIFF []`, `UDIFF []`, `VDIFF []`), +`test result: ok`. + +EVIDENCE: /tmp/gate_r7c.log | cargo test -j4 -p ec-av1 --lib a_real_aomenc_10bit_stream_decodes_pixel_exact -- --nocapture | test result: ok. 1 passed; 0 failed + +Temporary diff-dump instrumentation reverted from `stream.rs` before commit +(the gate's own three `assert_eq!`s are the permanent check). + +## Step 3: full suite + +`cargo test -j4 -p ec-av1 --lib` (with `EC_AV1_REQUIRE_AOMENC=1`): +**265 passed, 0 failed, 19 ignored, 0 filtered out, 203.66s.** 8-bit gates +unaffected (they run at `coeff_shift == 0`, where the fix is a no-op). + +EVIDENCE: /tmp/suite_r7.log | cargo test -j4 -p ec-av1 --lib | test result: ok. 265 passed; 0 failed; 19 ignored; finished in 203.66s + +## Step 4: workspace check + +`cargo check --workspace --all-targets` -> exit 0, warnings only (doc-lint +noise, one unused-fn/unused-var, pre-existing), no errors. + +EVIDENCE: /tmp/wscheck_r7.log | cargo check --workspace --all-targets | EXIT 0 + +## Step 5: decode_probe on real films + +Not run: this worktree has no `ReelB`/`ReelC` extracts in +`fixtures/`. Per ledger `dead-end|lane-realworld r8`, those came from the +`lane-realworld` worktree, which was destroyed by an external process +mid-session (its commit `bd91ad0` is unreachable in any ref/reflog). round +6's report never mentions leaving copies in *this* worktree either. +`crates/ec-av1/examples/decode_probe.rs` exists and is unmodified this +round -- nothing to re-run against. + +deferred: real-film decode_probe sweep — no fixture present in this +worktree, source extracts lost with lane-realworld's worktree — needs the +orchestrator to either re-extract from the originals or hand this worktree +a copy. + +## Summary + +- Diff count after the CDEF commit (`d6bd69a`): 1/4096 luma pixels, off by + exactly 1, chroma exact. +- Geometry: single pixel at (x=1, y=34), inside CDEF 8x8 block row 4 near + the left frame edge; not a block/LR-unit boundary artifact. +- Root cause (closed): `cdef_filter_block`'s primary-tap-set index used + `pri_strength & 1` instead of `(pri_strength >> coeff_shift) & 1` + (libaom `cdef_block.c:147`); at `coeff_shift=2` (10-bit) this always + selected tap set `{4,2}`, silently dropping tap set `{3,3}` for odd + strength levels. Fixed in `7e007da`; gate now 0/4096 diffs. +- Full suite: 265 passed, 0 failed, 19 ignored. +- `cargo check --workspace --all-targets`: clean (exit 0). +- HEAD: `7e007da` (report commit follows at HEAD after this write). +- Open: real-film `decode_probe` sweep deferred (fixture missing from this + worktree, see above). Everything else in the charter is closed and + green -- this lane is ready for merge from a correctness standpoint, + modulo that one deferred non-blocking sweep.