From 276058ca79228133ba96a3e0bba5225a1f9f82f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 14 Aug 2026 13:21:39 +0300 Subject: [PATCH] fix(h264): unavailable neighbours carry reference index -1, not 0 Two derivation defects that only inter coding can reach: - Nb::default() derived Default, so an unavailable neighbouring partition reported refIdxLXN 0 instead of the -1 that clause 8.4.1.3.2 assigns. Every median prediction with a missing neighbour then saw a phantom match on reference picture 0 and took the wrong branch of 8.4.1.3.1. Picture-edge macroblocks came out wrong in most inter frames. - coded_block_flag (9.3.3.1.1.9): an unavailable neighbour counts as set only when the current macroblock is intra. The chroma DC block of an inter macroblock at the left picture edge read the opposite value and desynchronised the arithmetic decoder. JVT full-sequence sweep: 4 vectors bit-exact end to end before, 18 now. Adds the full-sequence conformance test that found them, plus an env-gated macroblock trace (EC_H264_TRACE) and deblocking bypass (EC_H264_NO_DEBLOCK) that split reconstruction defects from filter defects; both resolve their environment once so the decode loop stays allocation free. --- crates/ec-h264/src/cabac.rs | 8 +- crates/ec-h264/src/decoder.rs | 50 +++++ crates/ec-h264/src/mv.rs | 15 +- crates/ec-h264/tests/conformance.rs | 331 +++++++++++++++++++++++++++- 4 files changed, 399 insertions(+), 5 deletions(-) diff --git a/crates/ec-h264/src/cabac.rs b/crates/ec-h264/src/cabac.rs index a4ca9bf2..a954c04e 100644 --- a/crates/ec-h264/src/cabac.rs +++ b/crates/ec-h264/src/cabac.rs @@ -639,11 +639,13 @@ impl<'a> Cabac<'a> { } /// condTermFlagN for a DC block: bit `which` of the neighbour's DC - /// coded_block_flags, with I_PCM counting as coded and an unavailable - /// neighbour as set (the current macroblock is always intra here). + /// coded_block_flags, with I_PCM counting as coded. An unavailable + /// neighbour counts as set only for an intra macroblock (9.3.3.1.1.9) — + /// the chroma DC block of an inter macroblock at the picture edge reads + /// the opposite value. fn dc_cbf(&self, n: Option, which: u8) -> usize { match n { - None => 1, + None => usize::from(self.cur_intra), Some(i) if i.flags & FLAG_PCM != 0 => 1, Some(i) => usize::from(i.dc_cbf & (1 << which) != 0), } diff --git a/crates/ec-h264/src/decoder.rs b/crates/ec-h264/src/decoder.rs index 68f3b545..200623df 100644 --- a/crates/ec-h264/src/decoder.rs +++ b/crates/ec-h264/src/decoder.rs @@ -52,6 +52,18 @@ use crate::transform::{ unzigzag, unzigzag_ac15, }; +/// Debug tracing gates, resolved once: reading the environment per macroblock +/// would allocate, which the zero-allocation test would (rightly) catch. +fn trace_enabled() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("EC_H264_TRACE").is_some()) +} + +fn no_deblock() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("EC_H264_NO_DEBLOCK").is_some()) +} + /// Where a 4x4 block's top-right neighbour samples come from, per /// luma4x4BlkIdx (derivation of 6.4.12 + the 8.3.1.2 blkIdx 3/11 rule). #[derive(Clone, Copy, PartialEq)] @@ -492,6 +504,14 @@ impl Decoder { weights: sh.pred_weight_table.clone(), poc: self.cur.poc, }; + if trace_enabled() { + eprintln!( + "SLICE type {:?} qp {} cabac_init_idc {} l0 {} l1 {} first_mb {first_mb} \ + header_bits {} bytes {:02x?}", + sh.slice_type, sh.slice_qp, sh.cabac_init_idc, sh.num_ref_idx_l0_active, + sh.num_ref_idx_l1_active, sh.header_bits, &rbsp[..rbsp.len().min(6)] + ); + } let intra_slice = sh.slice_type.is_intra(); let b_slice = sh.slice_type == SliceType::B; if !intra_slice && ctx.lists[0].len() == 0 { @@ -1014,6 +1034,12 @@ fn decode_macroblock( (None, Some(mb_type)) }; r.set_intra(intra_type.is_some()); + if trace_enabled() { + eprintln!( + "MB {mb_addr} ({mb_x},{mb_y}) type {} skipped {skipped} qp {}", + mb_type as i64, ctx.qp + ); + } if let Some(shape) = shape { return decode_inter_mb( @@ -1413,6 +1439,9 @@ fn decode_inter_mb( if shape.sub && !skipped { for part in 0..4 { let t = r.sub_mb_type(b)? as usize; + if trace_enabled() { + eprintln!(" sub_mb_type[{part}] = {t}"); + } motion.sub[part] = if b { B_SUB[t] } else { P_SUB[t] }; if motion.sub[part].pred == Pred::Direct { for k in 0..4 { @@ -1498,6 +1527,9 @@ fn decode_inter_mb( 0 }; let v = r.mvd(comp, inc)?; + if trace_enabled() { + eprintln!(" mvd part {part} sp {sp} list {list} comp {comp} inc {inc} = {v}"); + } mvd[comp] = i16::try_from(v) .map_err(|_| Error::corrupt("mvd outside the level limits"))?; } @@ -1547,6 +1579,12 @@ fn decode_inter_mb( // partition width inside an 8x8. let n = mvc.neighbours(pic, px, py, pw, list); let mvp = predict_mv(&n, idx, shape.w, shape.h, part); + if trace_enabled() { + eprintln!( + " nb A {:?} B {:?} C {:?} shape {}x{} part {part} mvp {mvp:?} written {:#06x}", + n[0], n[1], n[2], shape.w, shape.h, mvc.written + ); + } let d = motion.mvd[list][py * 4 + px]; mv[list] = [mvp[0].wrapping_add(d[0]), mvp[1].wrapping_add(d[1])]; ref_idx[list] = idx; @@ -1555,6 +1593,12 @@ fn decode_inter_mb( .map(|p| p.id) .unwrap_or(-1); } + if trace_enabled() { + eprintln!( + " MV part {part} sp {sp} at ({px},{py}) {pw}x{ph} mv {:?} ref {:?}", + mv[0], ref_idx + ); + } for dy in 0..ph { for dx in 0..pw { write_block(pic, &mut mvc, px + dx, py + dy, mv, ref_idx, ref_id, 0); @@ -1597,6 +1641,9 @@ fn decode_inter_mb( pic.i4_modes[base..base + 4].fill(2); } let (cbp_luma, cbp_chroma) = r.coded_block_pattern_inter()?; + if trace_enabled() { + eprintln!(" cbp {cbp_luma:#x}/{cbp_chroma}"); + } // The inter scaling lists (Table 7-2 lists 3..5) govern an inter residual. finish_macroblock( pic, @@ -2019,6 +2066,9 @@ fn gather_nbr4(pic: &Picture, nbr: &MbNeighbors, blk: usize, x: usize, y: usize) /// Whole-picture deblocking (spec 8.7): macroblocks in raster order, all /// vertical edges then all horizontal edges per macroblock, then chroma. fn deblock_picture(pic: &mut Picture) { + if no_deblock() { + return; + } let mb_w = pic.mb_w; for mb_y in 0..pic.mb_h { for mb_x in 0..mb_w { diff --git a/crates/ec-h264/src/mv.rs b/crates/ec-h264/src/mv.rs index 686fe703..51eb202c 100644 --- a/crates/ec-h264/src/mv.rs +++ b/crates/ec-h264/src/mv.rs @@ -146,7 +146,7 @@ pub(crate) const B_SUB: [SubShape; 13] = [ ]; /// Motion data of one neighbouring partition (8.4.1.3.2). -#[derive(Clone, Copy, Debug, Default)] +#[derive(Clone, Copy, Debug)] pub(crate) struct Nb { /// The partition exists and has been decoded (clause 6.4.11.7). pub avail: bool, @@ -155,6 +155,19 @@ pub(crate) struct Nb { pub ref_idx: i8, } +impl Default for Nb { + /// An unavailable partition, which 8.4.1.3.2 gives reference index -1 — + /// *not* 0. A derived `Default` would make it look like a neighbour on + /// reference picture 0 and hand the median rules a phantom match. + fn default() -> Nb { + Nb { + avail: false, + mv: [0; 2], + ref_idx: -1, + } + } +} + /// Where the current macroblock's motion data is being written, and which of /// its 4x4 blocks already carry it. pub(crate) struct MvCtx { diff --git a/crates/ec-h264/tests/conformance.rs b/crates/ec-h264/tests/conformance.rs index e26c1a1f..1d211d64 100644 --- a/crates/ec-h264/tests/conformance.rs +++ b/crates/ec-h264/tests/conformance.rs @@ -20,7 +20,7 @@ use std::sync::atomic::{AtomicU64, Ordering}; use ec_core::registry::{CodecId, CodecParameters, Decoder as _}; use ec_core::{Buf, Frame, Packet, TimeBase}; -use ec_h264::{Decoder, Error, H264Decoder}; +use ec_h264::{Decoder, Error, H264Decoder, NalOutcome}; // --------------------------------------------------------------------------- // Counting allocator: proves the steady-state decode loop allocates nothing. @@ -157,6 +157,137 @@ fn first_diff(a: &[u8], b: &[u8]) -> Option { a.iter().zip(b).position(|(x, y)| x != y) } +/// Pack a decoded frame as contiguous I420 bytes. +fn frame_bytes(frame: &ec_core::frame::VideoFrame) -> Vec { + let (w, h) = (frame.width as usize, frame.height as usize); + let mut out = Vec::with_capacity(w * h * 3 / 2); + let dims = [ + (w, h), + (w.div_ceil(2), h.div_ceil(2)), + (w.div_ceil(2), h.div_ceil(2)), + ]; + for (plane, (pw, ph)) in frame.planes.iter().zip(dims) { + for y in 0..ph { + out.extend_from_slice(plane.row(y, pw).expect("plane row")); + } + } + out +} + +/// Decode a whole Annex B stream, returning every frame in display order. +fn decode_all(bytes: &[u8]) -> Result>, Error> { + let mut dec = Decoder::new(); + let mut frames = Vec::new(); + for nal in ec_h264_syntax::AnnexBIter::new(bytes) { + match dec.push_nal(nal)? { + NalOutcome::PictureBoundary => { + dec.end_picture()?; + dec.push_nal(nal)?; + } + _ => {} + } + while let Some(f) = dec.next_frame() { + frames.push(frame_bytes(&f)); + } + } + dec.flush()?; + while let Some(f) = dec.next_frame() { + frames.push(frame_bytes(&f)); + } + Ok(frames) +} + +/// Every frame ffmpeg decodes from `stream`, as raw I420. +fn ffmpeg_all_frames(stream: &Path, frame_len: usize) -> Option>> { + let mut cmd = Command::new("ffmpeg"); + cmd.args(["-v", "error"]); + if std::env::var_os("EC_H264_NO_DEBLOCK").is_some() { + cmd.args(["-skip_loop_filter", "all"]); + } + let out = cmd + .arg("-i") + .arg(stream) + .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) + .output() + .ok()?; + if !out.status.success() || out.stdout.is_empty() { + return None; + } + Some( + out.stdout + .chunks_exact(frame_len) + .map(<[u8]>::to_vec) + .collect(), + ) +} + +/// Encode a multi-frame clip with x264 and return the Annex B file. +fn x264_encode_gop( + dir: &Path, + tag: &str, + size: &str, + frames: u32, + extra: &[&str], +) -> Option { + let stream = dir.join(format!("{tag}.264")); + let source = format!("testsrc=size={size}:rate=25:duration=4"); + let mut args: Vec = [ + "-hide_banner", + "-loglevel", + "error", + "-y", + "-f", + "lavfi", + "-i", + ] + .iter() + .map(|s| s.to_string()) + .collect(); + args.push(source); + if !extra.contains(&"-pix_fmt") { + args.extend(["-pix_fmt".into(), "yuv420p".into()]); + } + args.extend([ + "-c:v".into(), + "libx264".into(), + "-frames:v".into(), + frames.to_string(), + ]); + args.extend(extra.iter().map(|s| s.to_string())); + args.extend([ + "-f".into(), + "h264".into(), + stream.to_string_lossy().into_owned(), + ]); + let refs: Vec<&str> = args.iter().map(|s| s.as_str()).collect(); + run("ffmpeg", &refs).then_some(stream) +} + +/// Decode `stream` both ways and report the first frame that differs. +fn compare_sequence(stream: &Path) -> Result { + let bytes = std::fs::read(stream).map_err(|e| e.to_string())?; + let ours = decode_all(&bytes).map_err(|e| format!("{e}"))?; + let first = ours.first().ok_or("no frames decoded")?; + let theirs = + ffmpeg_all_frames(stream, first.len()).ok_or("ffmpeg cannot decode the stream")?; + if ours.len() != theirs.len() { + return Err(format!( + "{} frames decoded, ffmpeg gave {}", + ours.len(), + theirs.len() + )); + } + for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { + if let Some(pos) = first_diff(a, b) { + return Err(format!( + "frame {i} differs at byte {pos}: ours {} ffmpeg {}", + a[pos], b[pos] + )); + } + } + Ok(ours.len()) +} + #[test] fn jvt_cavlc_first_idr_bit_exact() { let base = vectors_dir(); @@ -907,3 +1038,201 @@ fn avcc_extradata_and_length_prefixed_packets() { assert_eq!(avcc_frame, annex_b_frame); let _ = std::fs::remove_dir_all(&dir); } + +// --------------------------------------------------------------------------- +// Inter prediction, the decoded picture buffer and display order. +// --------------------------------------------------------------------------- + +/// A P-only GOP, every frame bit-exact against ffmpeg, under both entropy +/// coders. This is the narrowest thing that exercises motion compensation, the +/// reference list, sliding-window marking and the inter boundary strengths at +/// once, so it is the first test to look at when any of them regress. +#[test] +fn p_only_gop_matches_ffmpeg_every_frame() { + if !have_ffmpeg() { + eprintln!("SKIP: ffmpeg not on PATH"); + return; + } + let dir = scratch("p-gop"); + let mut failures = Vec::new(); + for (mode, profile) in ENTROPY_MODES { + let mut extra = profile.to_vec(); + extra.extend(["-qp", "26", "-x264-params", "bframes=0:weightp=0:ref=1"]); + let tag = format!("{mode}-p"); + match x264_encode_gop(&dir, &tag, "176x144", 12, &extra) { + Some(stream) => match compare_sequence(&stream) { + Ok(n) => eprintln!("{tag}: {n} frames bit-exact"), + Err(e) => failures.push(format!("{tag}: {e}")), + }, + None => failures.push(format!("{tag}: ffmpeg cannot encode")), + } + } + let _ = std::fs::remove_dir_all(&dir); + assert!(failures.is_empty(), "{failures:#?}"); +} + +/// Scratch driver kept out of the default run: decode a stream named by +/// `EC_H264_DEBUG_STREAM` frame by frame and report the first mismatch. +#[test] +#[ignore] +fn debug_named_stream() { + let Ok(path) = std::env::var("EC_H264_DEBUG_STREAM") else { + return; + }; + let stream = PathBuf::from(path); + let bytes = std::fs::read(&stream).unwrap(); + let mut dec = Decoder::new(); + let mut pictures = 0usize; + for (i, nal) in ec_h264_syntax::AnnexBIter::new(&bytes).enumerate() { + let kind = nal[0] & 0x1F; + match dec.push_nal(nal) { + Ok(NalOutcome::PictureBoundary) => { + dec.end_picture().unwrap(); + pictures += 1; + if let Err(e) = dec.push_nal(nal) { + panic!("nal {i} (type {kind}) after {pictures} pictures: {e}"); + } + } + Ok(_) => {} + Err(e) => panic!("nal {i} (type {kind}) after {pictures} pictures: {e}"), + } + while dec.next_frame().is_some() {} + } + dec.flush().unwrap(); + eprintln!("decoded {pictures} pictures"); + let ours = decode_all(&bytes).unwrap(); + let theirs = match std::env::var("EC_H264_DEBUG_REF") { + Ok(p) => { + let raw = std::fs::read(p).unwrap(); + raw.chunks_exact(ours[0].len()).map(<[u8]>::to_vec).collect() + } + Err(_) => ffmpeg_all_frames(&stream, ours[0].len()).unwrap(), + }; + if std::env::var_os("EC_H264_DUMP").is_some() { + let w = 176usize; + for (label, f) in [("ref0", &ours[0]), ("ours1", &ours[1]), ("ff1", &theirs[1])] { + eprintln!("--- {label} MB(0,0) rows 0..4 ---"); + for y in 0..4 { + let row: Vec = (0..16).map(|x| f[y * w + x]).collect(); + eprintln!("{row:?}"); + } + } + } + for (i, a) in ours.iter().enumerate().take(4) { + let best = theirs + .iter() + .enumerate() + .map(|(j, b)| (a.iter().zip(b).filter(|(x, y)| x != y).count(), j)) + .min(); + eprintln!("our frame {i} best matches reference {best:?}"); + } + let w = 176usize; + let h = 144usize; + for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { + let diff = a.iter().zip(b).filter(|(x, y)| x != y).count(); + if diff == 0 { + eprintln!("frame {i}: exact"); + continue; + } + let mut mbs = std::collections::BTreeSet::new(); + for (k, (x, y)) in a.iter().zip(b).enumerate().take(w * h) { + if x != y { + mbs.insert(((k / w) / 16 * (w / 16) + (k % w) / 16, ((k % w) / 16, (k / w) / 16))); + } + } + eprintln!(" first differing MBs: {:?}", mbs.iter().take(6).map(|m| m.1).collect::>()); + let max = a + .iter() + .zip(b) + .map(|(x, y)| (i32::from(*x) - i32::from(*y)).abs()) + .max() + .unwrap_or(0); + eprintln!( + "frame {i}: {diff} bytes differ, max delta {max}, {} luma MBs", + mbs.len() + ); + } +} + +/// JVT conformance, every frame of every vector: our display-order output +/// against the reference decoder YUV that ships with the vector. +/// +/// The first-IDR test above proves intra reconstruction; this one is what +/// proves inter prediction, the decoded picture buffer and output order, +/// because a single wrong motion vector or a reference marked at the wrong +/// moment shows up as a mismatch in some later frame, not the first. +#[test] +fn jvt_full_sequence_bit_exact() { + let base = vectors_dir(); + if !base.is_dir() { + eprintln!("SKIP: {} missing", base.display()); + return; + } + let mut table = String::new(); + let mut passed = 0usize; + let mut refused = Vec::new(); + let mut failed = Vec::new(); + for name in all_vectors(&base) { + let dir = base.join(&name); + let Some(stream) = find_stream(&dir) else { + continue; + }; + let bytes = std::fs::read(&stream).unwrap(); + match decode_all(&bytes) { + Ok(frames) if frames.is_empty() => { + failed.push(format!("{name}: decoded no frames")); + } + Ok(frames) => { + let len = frames[0].len(); + let Some(ref_path) = find_ref_yuv(&dir) else { + table.push_str(&format!("{name:<16} {:>3} frames, no reference YUV\n", frames.len())); + continue; + }; + let reference = std::fs::read(&ref_path).unwrap(); + let want = reference.len() / len; + let mut bad = None; + for (i, f) in frames.iter().enumerate() { + let Some(chunk) = reference.get(i * len..(i + 1) * len) else { + break; + }; + if let Some(pos) = first_diff(f, chunk) { + bad = Some((i, pos)); + break; + } + } + match bad { + None if frames.len() == want => { + passed += 1; + table.push_str(&format!("{name:<16} {:>3}/{want:<3} frames bit-exact\n", frames.len())); + } + None => { + failed.push(format!( + "{name}: {} frames decoded, reference has {want}", + frames.len() + )); + table.push_str(&format!("{name:<16} {:>3}/{want:<3} FRAME COUNT\n", frames.len())); + } + Some((i, pos)) => { + failed.push(format!("{name}: frame {i} differs at byte {pos}")); + table.push_str(&format!("{name:<16} {:>3}/{want:<3} MISMATCH frame {i}\n", frames.len())); + } + } + } + Err(e @ Error::Unsupported { .. }) => { + refused.push(name.clone()); + table.push_str(&format!("{name:<16} refused: {e}\n")); + } + Err(e) => { + failed.push(format!("{name}: {e}")); + table.push_str(&format!("{name:<16} ERROR {e}\n")); + } + } + } + eprintln!("{table}"); + eprintln!( + "full-sequence: {passed} bit-exact, {} refused by name, {} failed", + refused.len(), + failed.len() + ); + assert!(failed.is_empty(), "{failed:#?}"); +}