From 769ba672ceba09f4b03a19e965af507b5fb47f7b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 2 Sep 2026 08:54:18 +0300 Subject: [PATCH] fix(av1): palette colours were read at 8 bits on every stream -- the raw literal widths, the delta range and the clamp are all sized by the sequence bit_depth read_palette_colors_y/_uv (decodemv.c:478/:509) size every raw literal by bit_depth: the first colour is bit_depth bits, min_bits is bit_depth-3 (Y/U) and bit_depth-4 (V), range starts at 1< 31364 -> renormalised 62728), so a cross-decoder RANGE ladder stays bit-identical straight through the miscount and only the VALUE moves (compare-range-not-tell's blind spot). Pinned on a 256x192 10-bit cq59 stream whose first block is a 32x16 palette: aomdec's EC_PAL ladder and ours agreed on every range and disagreed on the first colour index, 0 vs 1. After the fix all 1024 EC_PAL lines of that block match aomdec line for line and the block grid matches aomdec's for the rest of the frame. Gate: a_real_aomenc_palette_stream_decodes_pixel_exact_at_8_and_10_bit -- the existing 8-bit palette recipe with the depth as the only variable, both arms hard-asserting palette_hits() moved and comparing all three planes against ffmpeg. Reverting the fix to a literal 8 makes the 10-bit arm fail on luma; the 8-bit arm is unaffected. --- crates/ec-av1/src/decode.rs | 45 ++++++++---- crates/ec-av1/src/stream.rs | 141 ++++++++++++++++++++++++++++++++++++ 2 files changed, 170 insertions(+), 16 deletions(-) diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 901f8b91..da177b90 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -5220,7 +5220,15 @@ fn merge_colors(transmitted: &[u16], cached: &[u16]) -> Vec { out } -/// `read_palette_colors_y` (decodemv.c:478), bit_depth fixed at 8 (this +/// `read_palette_colors_y` (decodemv.c:478), at the sequence's real +/// `bit_depth` -- lane-kf900 r3: every raw literal here (the first colour, +/// each delta's width, the `range` bound and the clamp) is sized by +/// `bit_depth`, and hardcoding 8 read 2 bits too few per colour on every +/// 10-bit palette block. Raw literals are EQUIPROBABLE, and at the ranges +/// this stream reaches (e.g. 62728) an equiprobable read is a FIXED POINT of +/// the msac range, so a cross-decoder range ladder stays bit-identical +/// through the whole miscount -- only the decoded VALUE differs (class +/// `compare-range-not-tell`'s blind spot). (this /// decoder is 8-bit only): accepts up to `n` colours straight from `cache` /// (one flag bit each, in cache order), then delta-codes the remainder /// (first value raw, each following delta `>= 1` off a shrinking bit width), @@ -5235,20 +5243,22 @@ fn read_palette_colors_y(dec: &mut SymbolDecoder, n: usize, cache: &[u16]) -> [u cached.push(c); } } + let bd = u32::from(bit_depth()); + let max_val = (1i32 << bd) - 1; let mut colors = [0u16; 8]; let n_cached = cached.len(); if n_cached < n { let mut transmitted = Vec::with_capacity(n - n_cached); - let first = dec.literal(8) as u16; + let first = dec.literal(bd) as u16; transmitted.push(first); if n_cached + 1 < n { - let min_bits = 8u32 - 3; + let min_bits = bd - 3; let mut bits = min_bits + dec.literal(2); - let mut range = 255i32 - i32::from(first) - 1; + let mut range = (1i32 << bd) - i32::from(first) - 1; for _ in (n_cached + 1)..n { let delta = dec.literal(bits) as i32 + 1; let prev = *transmitted.last().unwrap(); - let val = (i32::from(prev) + delta).clamp(0, 255) as u16; + let val = (i32::from(prev) + delta).clamp(0, max_val) as u16; range -= i32::from(val) - i32::from(prev); bits = bits.min(ceil_log2(range.max(0) as u32)); transmitted.push(val); @@ -5262,7 +5272,8 @@ fn read_palette_colors_y(dec: &mut SymbolDecoder, n: usize, cache: &[u16]) -> [u colors } -/// `read_palette_colors_uv` (decodemv.c:509), bit_depth fixed at 8: U reads +/// `read_palette_colors_uv` (decodemv.c:509), at the sequence's real +/// `bit_depth` (see [`read_palette_colors_y`]): U reads /// exactly [`read_palette_colors_y`]'s cache/delta scheme (against the U-only /// cache, `range` starting at `255 - prev` with no `-1`, and each raw `delta` /// unbiased by `+1` -- both differences from Y's own reader, matching the C @@ -5279,20 +5290,22 @@ fn read_palette_colors_uv(dec: &mut SymbolDecoder, n: usize, cache: &[u16]) -> ( cached.push(c); } } + let bd = u32::from(bit_depth()); + let max_val = 1i32 << bd; let mut u_colors = [0u16; 8]; let n_cached = cached.len(); if n_cached < n { let mut transmitted = Vec::with_capacity(n - n_cached); - let first = dec.literal(8) as u16; + let first = dec.literal(bd) as u16; transmitted.push(first); if n_cached + 1 < n { - let min_bits = 8u32 - 3; + let min_bits = bd - 3; let mut bits = min_bits + dec.literal(2); - let mut range = 255i32 - i32::from(first); + let mut range = max_val - i32::from(first); for _ in (n_cached + 1)..n { let delta = dec.literal(bits) as i32; let prev = *transmitted.last().unwrap(); - let val = (i32::from(prev) + delta).clamp(0, 255) as u16; + let val = (i32::from(prev) + delta).clamp(0, max_val - 1) as u16; range -= i32::from(val) - i32::from(prev); bits = bits.min(ceil_log2(range.max(0) as u32)); transmitted.push(val); @@ -5305,9 +5318,9 @@ fn read_palette_colors_uv(dec: &mut SymbolDecoder, n: usize, cache: &[u16]) -> ( } let mut v_colors = [0u16; 8]; if dec.literal(1) == 1 { - let min_bits_v = 8u32 - 4; + let min_bits_v = bd - 4; let bits = min_bits_v + dec.literal(2); - v_colors[0] = dec.literal(8) as u16; + v_colors[0] = dec.literal(bd) as u16; for i in 1..n { let mut delta = dec.literal(bits) as i32; if delta != 0 && dec.literal(1) == 1 { @@ -5315,16 +5328,16 @@ fn read_palette_colors_uv(dec: &mut SymbolDecoder, n: usize, cache: &[u16]) -> ( } let mut val = i32::from(v_colors[i - 1]) + delta; if val < 0 { - val += 256; + val += max_val; } - if val >= 256 { - val -= 256; + if val >= max_val { + val -= max_val; } v_colors[i] = val as u16; } } else { for i in 0..n { - v_colors[i] = dec.literal(8) as u16; + v_colors[i] = dec.literal(bd) as u16; } } (u_colors, v_colors) diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index f6d442b5..8d98156b 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -2572,6 +2572,147 @@ mod tests { assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg"); } + /// lane-kf900 r3: the palette colour reader at BOTH bit depths. + /// + /// `read_palette_colors_y`/`_uv` (decode.rs, mirroring `decodemv.c:478` + /// and `:509`) size every raw literal they read by the sequence's + /// `bit_depth`: the first colour is `bit_depth` bits, `min_bits` is + /// `bit_depth - 3` (Y/U) or `bit_depth - 4` (V), `range` starts at + /// `1 << bit_depth`, and the clamp/wrap bound is `(1 << bit_depth) - 1`. + /// Ours hardcoded 8, so every 10-bit palette block read TWO BITS TOO FEW + /// per transmitted colour and silently decoded the rest of the tile from + /// the wrong bit position. + /// + /// It was silent because raw literals are EQUIPROBABLE: at the ranges + /// this content reaches an equiprobable read maps the msac range onto + /// itself (62728 -> 31364 -> renormalised 62728), so a cross-decoder + /// RANGE ladder stays bit-identical straight through the miscount and + /// only the decoded VALUE moves. Pinned on a 256x192 10-bit + /// `--cq-level=59` stream whose first block is a 32x16 palette: aomdec's + /// `EC_PAL` ladder and ours agreed on every range and disagreed on the + /// very first colour index (0 vs 1); after the fix all 1024 `EC_PAL` + /// lines of that block match aomdec line for line. + /// + /// The recipe is the 8-bit `..._with_palette_y_...` gate's, with the + /// depth as the only variable, so a failure here is the depth and + /// nothing else. HARD-asserts [`decode::palette_hits`] moved on each arm + /// (a stream with no real palette block would prove nothing) and + /// compares all three planes against ffmpeg's decode of the same bytes. + #[test] + fn a_real_aomenc_palette_stream_decodes_pixel_exact_at_8_and_10_bit() { + const NAME: &str = "a_real_aomenc_palette_stream_decodes_pixel_exact_at_8_and_10_bit"; + 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); + for depth in [8usize, 10] { + let pix_fmt = if depth == 10 { "yuv420p10le" } else { "yuv420p" }; + let render = || { + Command::new("ffmpeg") + .args([ + "-v", "error", + "-f", "lavfi", + "-i", "smptebars=size=64x64:rate=25", + "-vf", "hue=s=0", + "-pix_fmt", pix_fmt, + "-strict", "-1", + "-t", "0.04", + "-f", "yuv4mpegpipe", + "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run") + .stdout + }; + let y4m_a = render(); + let y4m_b = render(); + assert_eq!( + y4m_a, y4m_b, + "{NAME}: smptebars must render byte-identical across two runs at {depth}-bit" + ); + let y4m = y4m_a; + let depth_arg = format!("--bit-depth={depth}"); + let input_depth_arg = format!("--input-bit-depth={depth}"); + 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", + "--tune-content=screen", + "--enable-palette=1", + "--enable-intrabc=0", + "--enable-rect-partitions=0", + "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", + "--min-partition-size=32", + "--max-partition-size=32", + "--enable-filter-intra=0", + "--enable-smooth-intra=0", + "--enable-paeth-intra=0", + "--enable-directional-intra=0", + "--enable-angle-delta=0", + "--enable-cfl-intra=0", + "--enable-cdef=0", + "--enable-restoration=0", + "--enable-tx-size-search=0", + "--loopfilter-control=0", + "--limit=1", + ]) + // Per-arm overrides go AFTER the base recipe: aomenc keeps the + // LAST occurrence of a repeated flag. + .args([&depth_arg, &input_depth_arg]) + .args(["--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) + .expect("writing y4m to aomenc"); + let out = child.wait_with_output().expect("aomenc failed to run"); + assert!( + out.status.success(), + "{NAME}: aomenc refused the {depth}-bit fixture: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + let before = decode::palette_hits(); + let frames = match decode_stream(&stream) { + Ok(frames) => frames, + Err(e) => panic!("{NAME}: decode_stream refused the {depth}-bit stream: {e}"), + }; + assert!( + decode::palette_hits() > before, + "{NAME}: no real palette block at {depth}-bit -- gate is vacuous" + ); + let ffmpeg_frames = if depth == 10 { + ffmpeg_decode_sequence_10bit(&stream, width, height, 1) + } else { + ffmpeg_decode_sequence(&stream, width, height, 1) + }; + assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma at {depth}-bit"); + assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U at {depth}-bit"); + assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V at {depth}-bit"); + } + } + /// 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