From f985e44d89c393efed15d6b1ebd95762833c1749 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 09:08:11 +0300 Subject: [PATCH] feat(h264): CAVLC intra decoder, bit-exact on 18 JVT streams I-slice scope: I_4x4 / I_16x16 / I_PCM, full CAVLC residual decode, all intra prediction modes, 4x4 inverse transform + DC Hadamard, dequant with scaling-list support, and the complete in-loop deblocking filter. Everything outside scope (CABAC, FMO, interlace, non-I slices, 8x8 transform, 4:2:2/4:4:4, >8-bit) refuses with a named Unsupported error backed by tests on real conformance streams - never wrong pixels. Perf-first layout: padded planes sized for future inter overreach; per-MB state in flat struct-of-arrays (nz counts, intra modes, QP, slice ids) with no per-MB heap objects; a register-cached BitCursor for slice data; residual parse fused with reconstruction so empty blocks cost one coeff_token read; wide i16x16 SIMD for horizontal deblock edges (a gather/scatter vertical variant measured slower and stayed scalar). Steady-state decode loop is zero-alloc, proven by a counting allocator in the conformance harness. Conformance: first IDR bit-exact vs the JVT reference YUV and ffmpeg on 18 CAVLC streams incl. multi-slice and I_PCM; 6 CABAC/FMO/interlaced streams verified to refuse by name; deterministic corrupt-input sweep (truncations + 2000 single-byte mutations) never panics. Measured on this machine, single thread, deblock included: 1324 ns/MB (193 Mpx/s) on BA1_Sony_D at idle; 1007 ns/MB (254 Mpx/s) on the no-deblock NL1_Sony_D even under background load. --- Cargo.lock | 13 +- crates/ec-h264/Cargo.toml | 16 + crates/ec-h264/src/bits.rs | 286 ++++++++ crates/ec-h264/src/cavlc.rs | 278 ++++++++ crates/ec-h264/src/deblock.rs | 290 ++++++++ crates/ec-h264/src/decoder.rs | 1015 +++++++++++++++++++++++++++ crates/ec-h264/src/lib.rs | 22 + crates/ec-h264/src/pred.rs | 456 ++++++++++++ crates/ec-h264/src/tables.rs | 653 +++++++++++++++++ crates/ec-h264/src/transform.rs | 226 ++++++ crates/ec-h264/tests/conformance.rs | 415 +++++++++++ 11 files changed, 3661 insertions(+), 9 deletions(-) create mode 100644 crates/ec-h264/Cargo.toml create mode 100644 crates/ec-h264/src/bits.rs create mode 100644 crates/ec-h264/src/cavlc.rs create mode 100644 crates/ec-h264/src/deblock.rs create mode 100644 crates/ec-h264/src/decoder.rs create mode 100644 crates/ec-h264/src/lib.rs create mode 100644 crates/ec-h264/src/pred.rs create mode 100644 crates/ec-h264/src/tables.rs create mode 100644 crates/ec-h264/src/transform.rs create mode 100644 crates/ec-h264/tests/conformance.rs diff --git a/Cargo.lock b/Cargo.lock index 25c71d54..f70b6c1b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -13,26 +13,21 @@ name = "ec-core" version = "0.1.0" [[package]] -name = "ec-dsp" +name = "ec-h264" version = "0.1.0" dependencies = [ + "ec-core", + "ec-h264-syntax", "wide", ] [[package]] -name = "ec-riff" +name = "ec-h264-syntax" version = "0.1.0" dependencies = [ "ec-core", ] -[[package]] -name = "hound" -version = "3.5.1" -dependencies = [ - "ec-riff", -] - [[package]] name = "oracle" version = "0.1.0" diff --git a/crates/ec-h264/Cargo.toml b/crates/ec-h264/Cargo.toml new file mode 100644 index 00000000..f3ea4c08 --- /dev/null +++ b/crates/ec-h264/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "ec-h264" +description = "H.264 software decoder (CAVLC intra loop, growing toward full)" +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true + +[dependencies] +ec-core = { workspace = true } +ec-h264-syntax = { path = "../ec-h264-syntax", version = "0.1.0" } +wide = { workspace = true } + +[dev-dependencies] +# The conformance harness walks Annex B itself to drive push_nal. +ec-h264-syntax = { path = "../ec-h264-syntax", version = "0.1.0" } diff --git a/crates/ec-h264/src/bits.rs b/crates/ec-h264/src/bits.rs new file mode 100644 index 00000000..fec78f52 --- /dev/null +++ b/crates/ec-h264/src/bits.rs @@ -0,0 +1,286 @@ +//! Slice-data bit cursor: a 64-bit-cached reader for the CAVLC hot loop. +//! +//! `ec_core::BitReader` is the family-wide, allocation-free contract type and +//! stays the parser for headers. Slice data is different: it is read one to +//! three bits at a time, millions of times per picture, so this cursor keeps +//! the next 32..64 bits left-aligned in a register and refills by whole +//! words. Truncation still surfaces as [`Error::NeedMore`]; the exp-Golomb +//! prefix cap still turns runaway zeros into [`Error::Corrupt`]. + +use ec_core::error::{Error, Result}; + +/// Register-cached MSB-first bit reader over a byte slice. +pub struct BitCursor<'a> { + data: &'a [u8], + /// Upcoming bits, left-aligned. + cache: u64, + /// Valid bit count in `cache`. + cached: u32, + /// Next byte of `data` to load into the cache. + next_byte: usize, + /// Index of the bit just past the `rbsp_stop_one_bit`, for + /// `more_rbsp_data()`; `data.len() * 8` when no stop bit exists. + stop_bit: u64, +} + +impl<'a> BitCursor<'a> { + /// A cursor over `data`, positioned `bit_pos` bits in. + pub fn new(data: &'a [u8], bit_pos: u64) -> BitCursor<'a> { + let stop_bit = match data.iter().rposition(|&b| b != 0) { + Some(i) => i as u64 * 8 + (7 - data[i].trailing_zeros() as u64), + None => data.len() as u64 * 8, + }; + let mut c = BitCursor { + data, + cache: 0, + cached: 0, + next_byte: (bit_pos / 8) as usize, + stop_bit, + }; + c.refill(); + let sub = (bit_pos % 8) as u32; + c.cache <<= sub; + c.cached = c.cached.saturating_sub(sub); + c + } + + /// Bits consumed so far. + #[inline] + pub fn bit_position(&self) -> u64 { + self.next_byte as u64 * 8 - u64::from(self.cached) + } + + /// True while syntax elements remain before the RBSP stop bit + /// (spec 7.2 `more_rbsp_data()`). + #[inline] + pub fn more_rbsp_data(&self) -> bool { + self.bit_position() < self.stop_bit + } + + #[inline] + fn refill(&mut self) { + while self.cached <= 56 { + let Some(&b) = self.data.get(self.next_byte) else { + break; + }; + self.cache |= u64::from(b) << (56 - self.cached); + self.cached += 8; + self.next_byte += 1; + } + } + + /// Bits left in the stream. + #[inline] + pub fn bits_remaining(&self) -> u64 { + (self.data.len() - self.next_byte) as u64 * 8 + u64::from(self.cached) + } + + /// The next 16 bits left-aligned in a u32, zero-padded past the end. + #[inline] + pub fn peek16(&mut self) -> u32 { + if self.cached < 16 { + self.refill(); + } + (self.cache >> 48) as u32 & 0xFFFF + } + + /// Consume `n` bits (`n <= 16` after a `peek16`; general `n <= 32`). + #[inline] + pub fn skip(&mut self, n: u32) -> Result<()> { + if self.cached < n { + self.refill(); + if self.cached < n { + return Err(Error::NeedMore); + } + } + self.cache <<= n; + self.cached -= n; + Ok(()) + } + + /// Read one bit. + #[inline] + pub fn read_bit(&mut self) -> Result { + if self.cached == 0 { + self.refill(); + if self.cached == 0 { + return Err(Error::NeedMore); + } + } + let bit = self.cache >> 63 != 0; + self.cache <<= 1; + self.cached -= 1; + Ok(bit) + } + + /// Read `n` bits (`n <= 32`) MSB-first. + #[inline] + pub fn read_bits(&mut self, n: u32) -> Result { + debug_assert!(n <= 32); + if n == 0 { + return Ok(0); + } + if self.cached < n { + self.refill(); + if self.cached < n { + return Err(Error::NeedMore); + } + } + let v = (self.cache >> (64 - n)) as u32; + self.cache <<= n; + self.cached -= n; + Ok(v) + } + + /// Count leading zero bits up to and including the terminating one bit + /// (level_prefix / exp-Golomb prefix). Capped at `cap` zeros. + #[inline] + pub fn read_prefix_zeros(&mut self, cap: u32) -> Result { + let mut zeros = 0u32; + loop { + if self.cached == 0 { + self.refill(); + if self.cached == 0 { + return Err(Error::NeedMore); + } + } + let lz = (self.cache.leading_zeros()).min(self.cached); + if lz < self.cached { + // Found the 1 bit within the cache. + zeros += lz; + if zeros > cap { + return Err(Error::corrupt("prefix run of zeros too long")); + } + self.cache <<= lz + 1; + self.cached -= lz + 1; + return Ok(zeros); + } + zeros += lz; + if zeros > cap { + return Err(Error::corrupt("prefix run of zeros too long")); + } + self.cache = 0; + self.cached = 0; + self.refill(); + if self.cached == 0 && self.bits_remaining() == 0 { + return Err(Error::NeedMore); + } + } + } + + /// Unsigned exp-Golomb `ue(v)` (prefix capped at 31 zeros, as in + /// `ec_core::BitReader::read_ue`). + #[inline] + pub fn read_ue(&mut self) -> Result { + let zeros = self.read_prefix_zeros(31)?; + if zeros == 0 { + return Ok(0); + } + let suffix = self.read_bits(zeros)?; + Ok((1u32 << zeros) - 1 + suffix) + } + + /// Signed exp-Golomb `se(v)`. + #[inline] + pub fn read_se(&mut self) -> Result { + let k = self.read_ue()? as i64; + let v = if k % 2 == 1 { (k + 1) / 2 } else { -(k / 2) }; + i32::try_from(v).map_err(|_| Error::corrupt("se(v) out of i32 range")) + } + + /// Skip to the next byte boundary (I_PCM alignment). + #[inline] + pub fn align_to_byte(&mut self) { + let sub = (self.bit_position() % 8) as u32; + if sub != 0 { + let n = 8 - sub; + self.cache <<= n; + self.cached -= n.min(self.cached); + } + } + + /// Borrow `n` whole bytes at the current (byte-aligned) position. + pub fn read_bytes(&mut self, n: usize) -> Result<&'a [u8]> { + if !self.bit_position().is_multiple_of(8) { + return Err(Error::corrupt("read_bytes at a non-byte-aligned position")); + } + let start = (self.bit_position() / 8) as usize; + let end = start.checked_add(n).ok_or(Error::NeedMore)?; + let slice = self.data.get(start..end).ok_or(Error::NeedMore)?; + // Drop the cache and reposition after the bytes. + self.cache = 0; + self.cached = 0; + self.next_byte = end; + self.refill(); + Ok(slice) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use ec_core::BitWriter; + + #[test] + fn agrees_with_core_bitreader() { + let mut w = BitWriter::new(); + for v in [0u32, 1, 5, 127, 4096] { + w.write_ue(v); + } + for v in [0i32, -3, 7, -128] { + w.write_se(v); + } + w.write_bits(0b1011, 4); + w.write_bit(true); // stop bit + w.align_to_byte(); + let bytes = w.into_bytes(); + let mut c = BitCursor::new(&bytes, 0); + for v in [0u32, 1, 5, 127, 4096] { + assert_eq!(c.read_ue().unwrap(), v); + } + for v in [0i32, -3, 7, -128] { + assert_eq!(c.read_se().unwrap(), v); + } + assert_eq!(c.read_bits(4).unwrap(), 0b1011); + assert!(!c.more_rbsp_data()); + } + + #[test] + fn peek16_pads_and_skip_tracks_position() { + let data = [0xAB, 0xCD]; + let mut c = BitCursor::new(&data, 4); + assert_eq!(c.bit_position(), 4); + assert_eq!(c.peek16(), 0xBCD0); + c.skip(8).unwrap(); + assert_eq!(c.bit_position(), 12); + assert_eq!(c.peek16(), 0xD000); + assert_eq!(c.read_bits(4).unwrap(), 0xD); + assert!(c.read_bit().is_err()); + } + + #[test] + fn pcm_bytes_and_alignment() { + let data = [0b1000_0000, 0x11, 0x22, 0x33]; + let mut c = BitCursor::new(&data, 0); + assert!(c.read_bit().unwrap()); + c.align_to_byte(); + assert_eq!(c.read_bytes(2).unwrap(), &[0x11, 0x22]); + assert_eq!(c.read_bits(8).unwrap(), 0x33); + assert!(c.read_bytes(1).is_err()); + } + + #[test] + fn long_zero_runs_are_corrupt_or_need_more() { + // 33 zero bits then a 1: exp-Golomb prefix over the cap. + let data = [0, 0, 0, 0, 0b0100_0000]; + let mut c = BitCursor::new(&data, 0); + assert!(matches!(c.read_ue(), Err(Error::Corrupt { .. }))); + // All zeros: NeedMore (no stop bit at all). + let zeros = [0u8; 4]; + let mut c = BitCursor::new(&zeros, 0); + assert!(matches!( + c.read_ue(), + Err(Error::NeedMore | Error::Corrupt { .. }) + )); + } +} diff --git a/crates/ec-h264/src/cavlc.rs b/crates/ec-h264/src/cavlc.rs new file mode 100644 index 00000000..be44e906 --- /dev/null +++ b/crates/ec-h264/src/cavlc.rs @@ -0,0 +1,278 @@ +//! CAVLC residual decoding (spec 9.2). + +use ec_core::error::{Error, Result}; + +use crate::bits::BitCursor; +use crate::tables::{ + COEFF_TOKEN_CHROMA_DC, COEFF_TOKEN_NC0, COEFF_TOKEN_NC2, COEFF_TOKEN_NC4, CoeffTokenEntry, + RUN_BEFORE, TOTAL_ZEROS_4X4, TOTAL_ZEROS_CHROMA_DC, VlcEntry, +}; + +/// Decode one code from a `(len, code, value)` VLC list. The cursor's peek is +/// zero-padded past the end of data, so a truncated stream either matches a +/// code longer than what remains (caught by `skip`) or matches nothing. +#[inline] +fn read_vlc(r: &mut BitCursor<'_>, table: &[VlcEntry]) -> Result { + let peek = r.peek16(); + for &(len, code, value) in table { + if peek >> (16 - len) == u32::from(code) { + r.skip(u32::from(len))?; + return Ok(value); + } + } + if r.bits_remaining() < 16 { + return Err(Error::NeedMore); + } + Err(Error::corrupt("no matching VLC code")) +} + +/// Decode `coeff_token` (spec 9.2.1) returning `(total_coeff, trailing_ones)`. +#[inline] +fn read_coeff_token(r: &mut BitCursor<'_>, nc: i32) -> Result<(u8, u8)> { + if nc >= 8 { + // 6-bit fixed-length code. + let v = r.read_bits(6)?; + return Ok(if v == 3 { + (0, 0) + } else { + ((v / 4 + 1) as u8, (v % 4) as u8) + }); + } + let table: &[CoeffTokenEntry] = match nc { + -1 => COEFF_TOKEN_CHROMA_DC, + 0..=1 => COEFF_TOKEN_NC0, + 2..=3 => COEFF_TOKEN_NC2, + 4..=7 => COEFF_TOKEN_NC4, + _ => return Err(Error::unsupported("CAVLC nC = -2", "4:2:2 chroma DC")), + }; + let peek = r.peek16(); + for &(len, code, tc, t1) in table { + if peek >> (16 - len) == u32::from(code) { + r.skip(u32::from(len))?; + return Ok((tc, t1)); + } + } + if r.bits_remaining() < 16 { + return Err(Error::NeedMore); + } + Err(Error::corrupt("no matching coeff_token code")) +} + +/// `level_prefix` (spec 9.2.2.1): leading zeros before the first 1 bit. +/// Capped: baseline/main constrain it to <= 15, other profiles report +/// <= 11 + bit depth; beyond 25 zeros the stream is broken. +#[inline] +fn read_level_prefix(r: &mut BitCursor<'_>) -> Result { + r.read_prefix_zeros(25) +} + +/// Decode one CAVLC residual block (spec 9.2) into `coeff[0..max_num_coeff]` +/// in scan order. Returns TotalCoeff. `nc` selects the coeff_token VLC: +/// the averaged neighbour count for luma/chroma-AC blocks, -1 for 4:2:0 +/// chroma DC. +/// +/// `coeff` is fully zeroed first; the caller hands the same stack array every +/// time — no allocation. +// The spec's level/run algorithms couple the loop index to state transitions +// (`i == trailing_ones`, positions counted down); ranges mirror clause 9.2. +#[allow(clippy::needless_range_loop)] +pub fn residual_block( + r: &mut BitCursor<'_>, + coeff: &mut [i32; 16], + max_num_coeff: usize, + nc: i32, +) -> Result { + debug_assert!(max_num_coeff <= 16); + *coeff = [0; 16]; + let (total_coeff, trailing_ones) = read_coeff_token(r, nc)?; + let total_coeff = total_coeff as usize; + let trailing_ones = trailing_ones as usize; + if total_coeff == 0 { + return Ok(0); + } + if total_coeff > max_num_coeff { + return Err(Error::corrupt("TotalCoeff exceeds maxNumCoeff")); + } + + // 9.2.2: levels, highest frequency first. + let mut level = [0i32; 16]; + for l in level.iter_mut().take(trailing_ones) { + *l = if r.read_bit()? { -1 } else { 1 }; + } + let mut suffix_length: u32 = u32::from(total_coeff > 10 && trailing_ones < 3); + for i in trailing_ones..total_coeff { + let level_prefix = read_level_prefix(r)?; + let level_suffix_size = if level_prefix == 14 && suffix_length == 0 { + 4 + } else if level_prefix >= 15 { + level_prefix - 3 + } else { + suffix_length + }; + let mut level_code = (level_prefix.min(15) << suffix_length) as i64; + if level_suffix_size > 0 { + level_code += r.read_bits(level_suffix_size)? as i64; + } + if level_prefix >= 15 && suffix_length == 0 { + level_code += 15; + } + if level_prefix >= 16 { + level_code += (1i64 << (level_prefix - 3)) - 4096; + } + if i == trailing_ones && trailing_ones < 3 { + level_code += 2; + } + let v = if level_code % 2 == 0 { + (level_code + 2) >> 1 + } else { + (-level_code - 1) >> 1 + }; + level[i] = + i32::try_from(v).map_err(|_| Error::corrupt("coefficient level out of range"))?; + if suffix_length == 0 { + suffix_length = 1; + } + if level[i].unsigned_abs() > (3 << (suffix_length - 1)) && suffix_length < 6 { + suffix_length += 1; + } + } + + // 9.2.3: runs of zeros. + let mut zeros_left: i32 = if total_coeff == max_num_coeff { + 0 + } else { + let tz = if nc == -1 { + read_vlc(r, TOTAL_ZEROS_CHROMA_DC[total_coeff - 1])? + } else { + read_vlc(r, TOTAL_ZEROS_4X4[total_coeff - 1])? + }; + tz as i32 + }; + + // 9.2.4 fused with 9.2.3: place levels from the highest scan position + // downward, consuming run_before per coefficient. + let mut coeff_num = zeros_left + total_coeff as i32 - 1; + for i in 0..total_coeff { + let run = if i == total_coeff - 1 { + // Last (lowest-frequency) coefficient absorbs the rest. + zeros_left + } else if zeros_left > 0 { + let idx = (zeros_left.min(7) - 1) as usize; + read_vlc(r, RUN_BEFORE[idx])? as i32 + } else { + 0 + }; + if run > zeros_left { + return Err(Error::corrupt("run_before exceeds zerosLeft")); + } + let pos = coeff_num as usize; + if pos >= max_num_coeff { + return Err(Error::corrupt("coefficient position out of block")); + } + coeff[pos] = level[i]; + zeros_left -= run; + coeff_num -= run + 1; + } + Ok(total_coeff as u8) +} + +#[cfg(test)] +mod tests { + use super::*; + use ec_core::BitWriter; + + fn cursor(data: &[u8]) -> BitCursor<'_> { + BitCursor::new(data, 0) + } + + fn reader_of(bits: &str) -> Vec { + let mut w = BitWriter::new(); + for c in bits.chars().filter(|c| !c.is_whitespace()) { + w.write_bit(c == '1'); + } + // Pad so peeks have room. + w.align_to_byte(); + w.write_bytes(&[0xFF; 4]); + w.into_bytes() + } + + #[test] + fn zero_coefficients_single_bit() { + // nC 0: coeff_token (0,0) is "1". + let data = reader_of("1"); + let mut r = cursor(&data); + let mut c = [0i32; 16]; + assert_eq!(residual_block(&mut r, &mut c, 16, 0).unwrap(), 0); + assert_eq!(r.bit_position(), 1); + assert_eq!(c, [0; 16]); + } + + /// Worked example: TotalCoeff 3, TrailingOnes 2, one explicit level. + /// nC=0 coeff_token(2,3) = "0000101"; signs + and -; level_prefix "1" + /// (level_code 0+2=2 -> level 2); total_zeros (tz index 3) = 1 -> "111"; + /// wait: use total_zeros 0 -> "0101" per tzVlcIndex 3. + #[test] + fn trailing_ones_and_one_level() { + // trailing signs: 0 (+1), 1 (-1); level_prefix "1" -> levelCode 2 -> +2 + // total_zeros = 0 -> "0101" (tz3); no run_before reads (zerosLeft 0). + let data = reader_of("0000101 0 1 1 0101"); + let mut r = cursor(&data); + let mut c = [0i32; 16]; + assert_eq!(residual_block(&mut r, &mut c, 16, 0).unwrap(), 3); + // Levels ordered high frequency -> low: +1, -1, +2 at scan 2,1,0. + assert_eq!(&c[..4], &[2, -1, 1, 0]); + } + + /// With total_zeros > 0 the levels spread out by run_before codes. + #[test] + fn runs_spread_levels() { + // nC=0, coeff_token (1,1): "01"; sign 0 -> +1. + // total_zeros for tzVlcIndex 1: value 2 = "010". + // Single coefficient: no run_before read, position = 2. + let data = reader_of("01 0 010"); + let mut r = cursor(&data); + let mut c = [0i32; 16]; + assert_eq!(residual_block(&mut r, &mut c, 16, 0).unwrap(), 1); + assert_eq!(c[2], 1); + assert_eq!(c.iter().filter(|&&x| x != 0).count(), 1); + } + + #[test] + fn chroma_dc_block() { + // nC=-1, coeff_token (1,1) = "1"; sign "1" -> -1; TotalCoeff 1 < 4 so + // total_zeros chroma (tz index 1): 3 = "000". Position = 3. + let data = reader_of("1 1 000"); + let mut r = cursor(&data); + let mut c = [0i32; 16]; + assert_eq!(residual_block(&mut r, &mut c, 4, -1).unwrap(), 1); + assert_eq!(c[3], -1); + } + + #[test] + fn full_block_skips_total_zeros() { + // nC >= 8 uses the 6-bit FLC. (16, 3) = 63 = "111111". + // 3 trailing signs then 13 levels with suffix_length starting at 1. + let mut bits = String::from("111111 000"); + for _ in 0..13 { + bits.push_str("10"); // level_prefix 0, suffix "0" -> levelCode 0 + } + // First non-trailing level: t1 == 3 so no +2 adjustment; levelCode 0 + // -> +1 each. + let data = reader_of(&bits); + let mut r = cursor(&data); + let mut c = [0i32; 16]; + assert_eq!(residual_block(&mut r, &mut c, 16, 9).unwrap(), 16); + assert_eq!(c.iter().filter(|&&x| x != 0).count(), 16); + } + + #[test] + fn truncated_is_need_more() { + let data = [0u8; 1]; // 8 zero bits: valid prefix of a long code + let mut r = cursor(&data); + let mut c = [0i32; 16]; + assert!(matches!( + residual_block(&mut r, &mut c, 16, 0), + Err(Error::NeedMore) + )); + } +} diff --git a/crates/ec-h264/src/deblock.rs b/crates/ec-h264/src/deblock.rs new file mode 100644 index 00000000..8a654599 --- /dev/null +++ b/crates/ec-h264/src/deblock.rs @@ -0,0 +1,290 @@ +//! In-loop deblocking filter (spec 8.7), intra-picture scope: every +//! macroblock is intra, so boundary strength is 4 on macroblock edges and 3 +//! inside (8.7.2.1) — no motion-vector or reference comparisons yet. + +use crate::tables::{ALPHA, BETA, CHROMA_QP, TC0}; + +/// Filter parameters of one edge segment. +#[derive(Debug, Clone, Copy)] +pub struct EdgeParams { + /// indexA-resolved alpha threshold. + pub alpha: i32, + /// indexB-resolved beta threshold. + pub beta: i32, + /// tC0 for bS < 4 (unused for bS 4). + pub tc0: i32, + /// Boundary strength (3 or 4 here). + pub bs: u8, +} + +/// Resolve thresholds (spec 8.7.2.2) for a luma or chroma edge. +/// `qp_avg` = (qPp + qPq + 1) >> 1, offsets are the slice's FilterOffsetA/B. +#[inline] +pub fn edge_params(qp_avg: i32, offset_a: i32, offset_b: i32, bs: u8) -> EdgeParams { + let index_a = (qp_avg + offset_a).clamp(0, 51) as usize; + let index_b = (qp_avg + offset_b).clamp(0, 51) as usize; + EdgeParams { + alpha: i32::from(ALPHA[index_a]), + beta: i32::from(BETA[index_b]), + tc0: i32::from(TC0[(bs - 1).min(2) as usize][index_a]), + bs, + } +} + +/// Map a luma QP to the chroma QP for deblocking (spec 8.7.2 via 8.5.8). +#[inline] +pub fn chroma_qp(qp_luma: i32, offset: i32) -> i32 { + i32::from(CHROMA_QP[(qp_luma + offset).clamp(0, 51) as usize]) +} + +/// Filter one line of samples across a luma edge (spec 8.7.2.3 / 8.7.2.4). +/// +/// `p` indexes the plane; `s` is the distance between consecutive samples +/// across the edge (1 for vertical edges, stride for horizontal), and `edge` +/// is the index of q0. Samples p3..q3 must be in bounds. +#[inline] +pub fn filter_luma_line(data: &mut [u8], edge: usize, s: usize, e: &EdgeParams) { + let q0 = i32::from(data[edge]); + let p0 = i32::from(data[edge - s]); + if (p0 - q0).abs() >= e.alpha { + return; + } + let p1 = i32::from(data[edge - 2 * s]); + let q1 = i32::from(data[edge + s]); + if (p1 - p0).abs() >= e.beta || (q1 - q0).abs() >= e.beta { + return; + } + let p2 = i32::from(data[edge - 3 * s]); + let q2 = i32::from(data[edge + 2 * s]); + let ap = (p2 - p0).abs(); + let aq = (q2 - q0).abs(); + if e.bs < 4 { + let tc = e.tc0 + i32::from(ap < e.beta) + i32::from(aq < e.beta); + let delta = (((q0 - p0) * 4 + (p1 - q1) + 4) >> 3).clamp(-tc, tc); + data[edge - s] = (p0 + delta).clamp(0, 255) as u8; + data[edge] = (q0 - delta).clamp(0, 255) as u8; + if ap < e.beta { + let d = ((p2 + ((p0 + q0 + 1) >> 1) - (p1 << 1)) >> 1).clamp(-e.tc0, e.tc0); + data[edge - 2 * s] = (p1 + d) as u8; + } + if aq < e.beta { + let d = ((q2 + ((p0 + q0 + 1) >> 1) - (q1 << 1)) >> 1).clamp(-e.tc0, e.tc0); + data[edge + s] = (q1 + d) as u8; + } + } else { + // bS == 4 (8.7.2.4). + let strong = (p0 - q0).abs() < (e.alpha >> 2) + 2; + if strong && ap < e.beta { + let p3 = i32::from(data[edge - 4 * s]); + data[edge - s] = ((p2 + 2 * p1 + 2 * p0 + 2 * q0 + q1 + 4) >> 3) as u8; + data[edge - 2 * s] = ((p2 + p1 + p0 + q0 + 2) >> 2) as u8; + data[edge - 3 * s] = ((2 * p3 + 3 * p2 + p1 + p0 + q0 + 4) >> 3) as u8; + } else { + data[edge - s] = ((2 * p1 + p0 + q1 + 2) >> 2) as u8; + } + if strong && aq < e.beta { + let q3 = i32::from(data[edge + 3 * s]); + data[edge] = ((p1 + 2 * p0 + 2 * q0 + 2 * q1 + q2 + 4) >> 3) as u8; + data[edge + s] = ((p0 + q0 + q1 + q2 + 2) >> 2) as u8; + data[edge + 2 * s] = ((2 * q3 + 3 * q2 + q1 + q0 + p0 + 4) >> 3) as u8; + } else { + data[edge] = ((2 * q1 + q0 + p1 + 2) >> 2) as u8; + } + } +} + +/// Filter one line across a chroma edge (chromaStyleFilteringFlag = 1). +#[inline] +pub fn filter_chroma_line(data: &mut [u8], edge: usize, s: usize, e: &EdgeParams) { + let q0 = i32::from(data[edge]); + let p0 = i32::from(data[edge - s]); + if (p0 - q0).abs() >= e.alpha { + return; + } + let p1 = i32::from(data[edge - 2 * s]); + let q1 = i32::from(data[edge + s]); + if (p1 - p0).abs() >= e.beta || (q1 - q0).abs() >= e.beta { + return; + } + if e.bs < 4 { + let tc = e.tc0 + 1; + let delta = (((q0 - p0) * 4 + (p1 - q1) + 4) >> 3).clamp(-tc, tc); + data[edge - s] = (p0 + delta).clamp(0, 255) as u8; + data[edge] = (q0 - delta).clamp(0, 255) as u8; + } else { + data[edge - s] = ((2 * p1 + p0 + q1 + 2) >> 2) as u8; + data[edge] = ((2 * q1 + q0 + p1 + 2) >> 2) as u8; + } +} + +/// Vectorised luma edge filter core (spec 8.7.2.3 / 8.7.2.4), 16 lanes. +/// +/// Takes the eight sample vectors across the edge, returns the six filtered +/// vectors `[p2', p1', p0', q0', q1', q2']`, or `None` when no lane passes +/// the filterSamplesFlag gate. Bit-identical to [`filter_luma_line`] per +/// lane. +#[allow(clippy::too_many_arguments)] +fn luma_edge_core16( + p3: wide::i16x16, + p2: wide::i16x16, + p1: wide::i16x16, + p0: wide::i16x16, + q0: wide::i16x16, + q1: wide::i16x16, + q2: wide::i16x16, + q3: wide::i16x16, + e: &EdgeParams, +) -> Option<[wide::i16x16; 6]> { + use wide::i16x16; + let alpha = i16x16::splat(e.alpha as i16); + let beta = i16x16::splat(e.beta as i16); + let filter = (p0 - q0).abs().simd_lt(alpha) + & (p1 - p0).abs().simd_lt(beta) + & (q1 - q0).abs().simd_lt(beta); + if !filter.any() { + return None; + } + let ap = (p2 - p0).abs().simd_lt(beta); + let aq = (q2 - q0).abs().simd_lt(beta); + let one = i16x16::ONE; + + Some(if e.bs < 4 { + let tc0 = i16x16::splat(e.tc0 as i16); + let tc = tc0 + ap.select(one, i16x16::ZERO) + aq.select(one, i16x16::ZERO); + let four = i16x16::splat(4); + let delta = ((((q0 - p0) << 2u32) + (p1 - q1) + four) >> 3u32) + .max(-tc) + .min(tc); + let avg = (p0 + q0 + one) >> 1u32; + let dp1 = ((p2 + avg - (p1 << 1u32)) >> 1u32).max(-tc0).min(tc0); + let dq1 = ((q2 + avg - (q1 << 1u32)) >> 1u32).max(-tc0).min(tc0); + [ + p2, + (filter & ap).select(p1 + dp1, p1), + filter.select(p0 + delta, p0), + filter.select(q0 - delta, q0), + (filter & aq).select(q1 + dq1, q1), + q2, + ] + } else { + let two = i16x16::splat(2); + let four = i16x16::splat(4); + let strong = (p0 - q0) + .abs() + .simd_lt(i16x16::splat(((e.alpha >> 2) + 2) as i16)); + let sp = filter & strong & ap; + let sq = filter & strong & aq; + let p0s = (p2 + (p1 << 1u32) + (p0 << 1u32) + (q0 << 1u32) + q1 + four) >> 3u32; + let p1s = (p2 + p1 + p0 + q0 + two) >> 2u32; + let p2s = ((p3 << 1u32) + p2 + (p2 << 1u32) + p1 + p0 + q0 + four) >> 3u32; + let p0w = ((p1 << 1u32) + p0 + q1 + two) >> 2u32; + let q0s = (p1 + (p0 << 1u32) + (q0 << 1u32) + (q1 << 1u32) + q2 + four) >> 3u32; + let q1s = (p0 + q0 + q1 + q2 + two) >> 2u32; + let q2s = ((q3 << 1u32) + q2 + (q2 << 1u32) + q1 + q0 + p0 + four) >> 3u32; + let q0w = ((q1 << 1u32) + q0 + p1 + two) >> 2u32; + [ + sp.select(p2s, p2), + sp.select(p1s, p1), + sp.select(p0s, filter.select(p0w, p0)), + sq.select(q0s, filter.select(q0w, q0)), + sq.select(q1s, q1), + sq.select(q2s, q2), + ] + }) +} + +#[inline] +fn load_row16(data: &[u8], at: usize) -> wide::i16x16 { + let mut a = [0i16; 16]; + for (o, &b) in a.iter_mut().zip(&data[at..at + 16]) { + *o = i16::from(b); + } + wide::i16x16::from(a) +} + +#[inline] +fn store_row16(data: &mut [u8], at: usize, v: wide::i16x16) { + let clipped = v.max(wide::i16x16::ZERO).min(wide::i16x16::splat(255)); + for (o, &s) in data[at..at + 16].iter_mut().zip(clipped.as_array().iter()) { + *o = s as u8; + } +} + +/// Filter a whole horizontal luma edge (16 samples wide): the eight rows +/// around the edge are contiguous, so the filter runs 16 lanes at once with +/// masked selects instead of per-pixel branches. `q0_row` indexes the first +/// sample of the q0 row. +pub fn filter_luma_h_edge16(data: &mut [u8], q0_row: usize, stride: usize, e: &EdgeParams) { + let p3 = load_row16(data, q0_row - 4 * stride); + let p2 = load_row16(data, q0_row - 3 * stride); + let p1 = load_row16(data, q0_row - 2 * stride); + let p0 = load_row16(data, q0_row - stride); + let q0 = load_row16(data, q0_row); + let q1 = load_row16(data, q0_row + stride); + let q2 = load_row16(data, q0_row + 2 * stride); + let q3 = load_row16(data, q0_row + 3 * stride); + let Some(out) = luma_edge_core16(p3, p2, p1, p0, q0, q1, q2, q3, e) else { + return; + }; + store_row16(data, q0_row - 3 * stride, out[0]); + store_row16(data, q0_row - 2 * stride, out[1]); + store_row16(data, q0_row - stride, out[2]); + store_row16(data, q0_row, out[3]); + store_row16(data, q0_row + stride, out[4]); + store_row16(data, q0_row + 2 * stride, out[5]); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn thresholds_clamp_and_lookup() { + let e = edge_params(26, 0, 0, 3); + assert_eq!(e.alpha, i32::from(ALPHA[26])); + assert_eq!(e.beta, i32::from(BETA[26])); + assert_eq!(e.tc0, i32::from(TC0[2][26])); + // Offsets push the index outside [0, 51] and clamp. + let e2 = edge_params(51, 12, 12, 4); + assert_eq!(e2.alpha, 255); + let e3 = edge_params(0, -12, -12, 3); + assert_eq!(e3.alpha, 0); + assert_eq!(chroma_qp(51, 0), 39); + assert_eq!(chroma_qp(20, 2), 22); + } + + /// A hard step across a bS=4 edge at moderate QP gets smoothed; a flat + /// area is untouched. + #[test] + fn strong_filter_smooths_step() { + // Line: p3 p2 p1 p0 | q0 q1 q2 q3. + let mut line = [60u8, 60, 60, 60, 80, 80, 80, 80]; + let e = edge_params(32, 0, 0, 4); + filter_luma_line(&mut line, 4, 1, &e); + // (p0, q0) move toward each other. + assert!(line[3] > 60 && line[4] < 80, "{line:?}"); + let mut flat = [90u8; 8]; + filter_luma_line(&mut flat, 4, 1, &e); + assert_eq!(flat, [90; 8]); + } + + /// Above alpha the edge is treated as a real feature and left alone. + #[test] + fn large_step_is_preserved() { + let mut line = [10u8, 10, 10, 10, 200, 200, 200, 200]; + let e = edge_params(26, 0, 0, 4); + filter_luma_line(&mut line, 4, 1, &e); + assert_eq!(line, [10, 10, 10, 10, 200, 200, 200, 200]); + } + + #[test] + fn chroma_filter_touches_only_p0_q0() { + let mut line = [60u8, 60, 60, 60, 74, 74, 74, 74]; + let e = edge_params(32, 0, 0, 3); + filter_chroma_line(&mut line, 4, 1, &e); + assert_eq!(line[2], 60); + assert_eq!(line[5], 74); + assert!(line[3] >= 60 && line[4] <= 74); + assert!(line[3] != 60 || line[4] != 74); + } +} diff --git a/crates/ec-h264/src/decoder.rs b/crates/ec-h264/src/decoder.rs new file mode 100644 index 00000000..aab48b6e --- /dev/null +++ b/crates/ec-h264/src/decoder.rs @@ -0,0 +1,1015 @@ +//! Decoder core: parameter-set store, flat per-picture context, macroblock +//! decode loop, reconstruction and the in-loop filter driver. +//! +//! Layout choices (perf-first): +//! - Planes are padded (`PAD_Y`/`PAD_C` samples each side), so neighbour +//! gathers and future inter-prediction overreach never bounds-check per +//! sample and edge availability is data, not arithmetic. +//! - All per-macroblock state lives in flat struct-of-arrays keyed by +//! macroblock address or 4x4-block coordinate: non-zero coefficient counts +//! (`nz_y`, `nz_c`), intra 4x4 modes, QP, flags, owning slice. No per-MB +//! heap objects anywhere. +//! - Buffers are reused across pictures; a picture start is O(macroblocks) +//! fills, and the slice decode loop performs zero allocations. + +use ec_core::BitReader; +use ec_core::error::{Error, Result}; +use ec_core::frame::{PixelFormat, Plane, VideoFrame}; +use ec_h264_syntax::{ + AnnexBIter, NalHeader, NalUnitType, Pps, SliceHeader, SliceType, Sps, unescape_rbsp, +}; + +use crate::bits::BitCursor; +use crate::cavlc::residual_block; +use crate::deblock::{ + chroma_qp, edge_params, filter_chroma_line, filter_luma_h_edge16, filter_luma_line, +}; +use crate::pred::{Nbr4, PlaneWindow, add_residual_4x4, pred_4x4, pred_16x16, pred_chroma_8x8}; +use crate::tables::{BLK4_POS, CBP_INTRA_420, CHROMA_QP}; +use crate::transform::{ + LevelScale4x4, chroma_dc_transform_420, dequant_4x4, inverse_transform_4x4, luma_dc_transform, + unzigzag, unzigzag_ac15, +}; + +/// Luma plane padding on every side, sized for future inter-prediction +/// filter overreach (16 MB + margin). +const PAD_Y: usize = 32; +/// Chroma plane padding on every side. +const PAD_C: usize = 16; +/// `mb_slice` value for a not-yet-decoded macroblock. +const NO_SLICE: u16 = u16::MAX; + +/// 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)] +enum TrKind { + /// Bottom row of an earlier block in this macroblock: always available. + InMb, + /// The macroblock above. + B, + /// The macroblock above-right. + C, + /// Never available (right column, or blkIdx 3/11). + None, +} + +const TR_KIND: [TrKind; 16] = [ + TrKind::B, + TrKind::B, + TrKind::InMb, + TrKind::None, + TrKind::B, + TrKind::C, + TrKind::InMb, + TrKind::None, + TrKind::InMb, + TrKind::InMb, + TrKind::InMb, + TrKind::None, + TrKind::InMb, + TrKind::None, + TrKind::InMb, + TrKind::None, +]; + +/// A padded 8-bit plane. +#[derive(Debug, Default)] +struct Plane8 { + data: Vec, + stride: usize, + /// Index of sample (0, 0) of the picture. + origin: usize, +} + +impl Plane8 { + fn resize(&mut self, width: usize, height: usize, pad: usize) { + self.stride = width + 2 * pad; + self.origin = pad * self.stride + pad; + self.data.clear(); + self.data.resize(self.stride * (height + 2 * pad), 0); + } + + #[inline] + fn at(&self, x: usize, y: usize) -> usize { + self.origin + y * self.stride + x + } +} + +/// Per-slice values the deblocking filter needs after slice decode ends. +#[derive(Debug, Clone, Copy)] +struct SliceParams { + disable_deblock_idc: u8, + alpha_offset: i32, + beta_offset: i32, + cb_qp_offset: i32, + cr_qp_offset: i32, +} + +/// Flat per-picture decode context (see module docs for the layout story). +#[derive(Debug, Default)] +struct Picture { + sps_id: u8, + mb_w: usize, + mb_h: usize, + y: Plane8, + cb: Plane8, + cr: Plane8, + /// TotalCoeff per luma 4x4 block, `(mb_w * 4) x (mb_h * 4)`. + nz_y: Vec, + /// TotalCoeff per chroma 4x4 block, `(mb_w * 2) x (mb_h * 2)`, Cb and Cr. + nz_c: [Vec; 2], + /// Intra4x4PredMode per luma 4x4 block (2 = DC for non-I4x4 MBs). + i4_modes: Vec, + /// QPY per macroblock (the prediction-chain value; PCM keeps the chain). + mb_qp: Vec, + /// Bit 0: decoded, bit 1: I_PCM, bit 2: Intra_16x16. + mb_flags: Vec, + /// Owning slice index per macroblock, `NO_SLICE` when undecoded. + mb_slice: Vec, + slices: Vec, + decoded_mbs: usize, + complete: bool, +} + +const FLAG_DECODED: u8 = 1; +const FLAG_PCM: u8 = 2; + +impl Picture { + fn start(&mut self, sps: &Sps) { + let mb_w = sps.mb_width as usize; + let mb_h = sps.mb_height as usize; + if self.mb_w != mb_w || self.mb_h != mb_h || self.sps_id != sps.id { + self.mb_w = mb_w; + self.mb_h = mb_h; + self.sps_id = sps.id; + self.y.resize(mb_w * 16, mb_h * 16, PAD_Y); + self.cb.resize(mb_w * 8, mb_h * 8, PAD_C); + self.cr.resize(mb_w * 8, mb_h * 8, PAD_C); + self.nz_y.resize(mb_w * mb_h * 16, 0); + for c in &mut self.nz_c { + c.resize(mb_w * mb_h * 4, 0); + } + self.i4_modes.resize(mb_w * mb_h * 16, 2); + self.mb_qp.resize(mb_w * mb_h, 0); + self.mb_flags.resize(mb_w * mb_h, 0); + self.mb_slice.resize(mb_w * mb_h, NO_SLICE); + } + // Per-MB metadata is rewritten by each decoded macroblock; only the + // "who is decoded" state must be wiped between pictures. + self.mb_slice.fill(NO_SLICE); + self.mb_flags.fill(0); + self.slices.clear(); + self.decoded_mbs = 0; + self.complete = false; + } +} + +/// Streaming H.264 decoder (CAVLC intra scope; unsupported features come back +/// as named [`Error::Unsupported`] values, never wrong pixels). +pub struct Decoder { + sps_map: Vec>, + pps_map: Vec>, + rbsp: Vec, + pic: Picture, + has_picture: bool, + /// Scaling factors for intra Y/Cb/Cr 4x4 lists of the active PPS/SPS. + ls: [LevelScale4x4; 3], + active_pps: Option, +} + +/// What [`Decoder::push_nal`] did with a NAL unit. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum NalOutcome { + /// SPS or PPS stored. + ParameterSet, + /// Non-VCL NAL skipped (SEI, AUD, filler, ...). + Skipped, + /// A slice was decoded into the open picture. + SliceDecoded, + /// The NAL starts a new picture while one is open; it was not consumed. + /// Call [`Decoder::end_picture`] + [`Decoder::frame`], then push it again. + PictureBoundary, +} + +impl Default for Decoder { + fn default() -> Self { + Decoder::new() + } +} + +impl Decoder { + /// A fresh decoder with no parameter sets. + pub fn new() -> Decoder { + Decoder { + sps_map: vec![None; 32], + pps_map: vec![None; 256], + rbsp: Vec::new(), + pic: Picture::default(), + has_picture: false, + ls: [ + LevelScale4x4::new(&[16; 16]), + LevelScale4x4::new(&[16; 16]), + LevelScale4x4::new(&[16; 16]), + ], + active_pps: None, + } + } + + /// Decode the first IDR picture of an Annex B stream and return it. + pub fn decode_first_idr(&mut self, annexb: &[u8]) -> Result { + let mut got_slice = false; + for nal in AnnexBIter::new(annexb) { + match self.push_nal(nal)? { + NalOutcome::PictureBoundary => break, + NalOutcome::SliceDecoded => got_slice = true, + _ => {} + } + } + if !got_slice { + return Err(Error::NeedMore); + } + self.end_picture()?; + self.frame() + } + + /// Feed one NAL unit (header byte first, no start code). + pub fn push_nal(&mut self, nal: &[u8]) -> Result { + let Some((&header_byte, payload)) = nal.split_first() else { + return Err(Error::NeedMore); + }; + let header = NalHeader::parse(header_byte)?; + match header.unit_type { + NalUnitType::Sps => { + let mut rbsp = core::mem::take(&mut self.rbsp); + unescape_rbsp(payload, &mut rbsp); + let sps = Sps::parse(&rbsp); + self.rbsp = rbsp; + let sps = sps?; + let id = sps.id as usize; + self.sps_map[id] = Some(sps); + Ok(NalOutcome::ParameterSet) + } + NalUnitType::Pps => { + let mut rbsp = core::mem::take(&mut self.rbsp); + unescape_rbsp(payload, &mut rbsp); + let pps = Pps::parse(&rbsp, |id| self.sps_map[id as usize].as_ref()); + self.rbsp = rbsp; + let pps = pps?; + let id = pps.id as usize; + self.pps_map[id] = Some(pps); + Ok(NalOutcome::ParameterSet) + } + NalUnitType::Slice | NalUnitType::SliceIdr => { + let mut rbsp = core::mem::take(&mut self.rbsp); + unescape_rbsp(payload, &mut rbsp); + let r = self.decode_slice_rbsp(header, &rbsp); + self.rbsp = rbsp; + r + } + NalUnitType::SliceDataA | NalUnitType::SliceDataB | NalUnitType::SliceDataC => Err( + Error::unsupported("slice data partitioning", "NAL types 2..4 not implemented"), + ), + _ => Ok(NalOutcome::Skipped), + } + } + + /// Run the deblocking filter over the open picture and mark it complete. + pub fn end_picture(&mut self) -> Result<()> { + if !self.has_picture || self.pic.complete { + return Err(Error::corrupt("end_picture without an open picture")); + } + deblock_picture(&mut self.pic); + self.pic.complete = true; + Ok(()) + } + + /// Copy the completed picture out as a cropped I420 frame. + pub fn frame(&self) -> Result { + if !self.pic.complete { + return Err(Error::corrupt("frame() before end_picture()")); + } + let sps = self.sps_map[self.pic.sps_id as usize] + .as_ref() + .ok_or_else(|| Error::corrupt("active SPS vanished"))?; + let (w, h) = (sps.width as usize, sps.height as usize); + let (cx, cy) = (sps.crop.0 as usize, sps.crop.2 as usize); + let copy = |p: &Plane8, x0: usize, y0: usize, w: usize, h: usize| -> Plane { + let mut out = vec![0u8; w * h]; + for row in 0..h { + let src = p.at(x0, y0 + row); + out[row * w..(row + 1) * w].copy_from_slice(&p.data[src..src + w]); + } + Plane::new(out, w) + }; + let planes = vec![ + copy(&self.pic.y, cx, cy, w, h), + copy(&self.pic.cb, cx / 2, cy / 2, w.div_ceil(2), h.div_ceil(2)), + copy(&self.pic.cr, cx / 2, cy / 2, w.div_ceil(2), h.div_ceil(2)), + ]; + let mut frame = VideoFrame::try_new(PixelFormat::I420, w as u32, h as u32, planes)?; + if let Some(vui) = &sps.vui { + frame.color.full_range = vui.video_full_range; + if let Some((p, t, m)) = vui.colour_description { + frame.color.primaries = p; + frame.color.transfer = t; + frame.color.matrix = m; + } + } + Ok(frame) + } + + /// True while a picture is open (started, not completed). + pub fn picture_open(&self) -> bool { + self.has_picture && !self.pic.complete + } + + fn decode_slice_rbsp(&mut self, header: NalHeader, rbsp: &[u8]) -> Result { + // Peek first_mb / slice_type / pps_id to select parameter sets. + let mut peek = BitReader::new(rbsp); + let first_mb = peek.read_ue()?; + let slice_type_code = peek.read_ue()?; + let pps_id = peek.read_ue()?; + if pps_id > 255 { + return Err(Error::corrupt("pic_parameter_set_id > 255")); + } + if self.has_picture && !self.pic.complete && first_mb == 0 && self.pic.decoded_mbs > 0 { + return Ok(NalOutcome::PictureBoundary); + } + let pps = self.pps_map[pps_id as usize] + .as_ref() + .ok_or_else(|| Error::corrupt("slice refers to an unknown PPS"))?; + let sps = self.sps_map[pps.sps_id as usize] + .as_ref() + .ok_or_else(|| Error::corrupt("PPS refers to an unknown SPS"))?; + + check_supported(sps, pps, slice_type_code)?; + let sh = SliceHeader::parse(rbsp, header, sps, pps)?; + if sh.slice_type != SliceType::I { + return Err(Error::unsupported( + "non-I slice", + "P/B/SP/SI slices arrive with inter prediction (S18c)", + )); + } + + if !self.has_picture || self.pic.complete { + self.pic.start(sps); + self.has_picture = true; + if self.active_pps != Some(pps.id) { + let lists = pps.scaling_lists.as_ref().or(sps.scaling_lists.as_ref()); + let weights = match lists { + Some(l) => [&l.list_4x4[0], &l.list_4x4[1], &l.list_4x4[2]], + None => [&[16u8; 16]; 3], + }; + self.ls = [ + LevelScale4x4::new(weights[0]), + LevelScale4x4::new(weights[1]), + LevelScale4x4::new(weights[2]), + ]; + self.active_pps = Some(pps.id); + } + } + if self.pic.sps_id != sps.id { + return Err(Error::corrupt("SPS changed mid-picture")); + } + if self.pic.slices.len() >= usize::from(u16::MAX) { + return Err(Error::corrupt("more than 65534 slices in a picture")); + } + let slice_id = self.pic.slices.len() as u16; + self.pic.slices.push(SliceParams { + disable_deblock_idc: sh.deblock.disable_idc, + alpha_offset: sh.deblock.alpha_c0_offset, + beta_offset: sh.deblock.beta_offset, + cb_qp_offset: pps.chroma_qp_index_offset, + cr_qp_offset: pps.second_chroma_qp_index_offset, + }); + + let mut r = BitCursor::new(rbsp, sh.header_bits); + + let mut ctx = SliceCtx { + slice_id, + qp: sh.slice_qp, + cb_qp_offset: pps.chroma_qp_index_offset, + cr_qp_offset: pps.second_chroma_qp_index_offset, + transform_8x8_mode: pps.transform_8x8_mode, + }; + let mbs = self.pic.mb_w * self.pic.mb_h; + let mut mb_addr = first_mb as usize; + loop { + if mb_addr >= mbs { + return Err(Error::corrupt("macroblock address beyond the picture")); + } + decode_macroblock(&mut self.pic, &self.ls, &mut r, &mut ctx, mb_addr)?; + if !r.more_rbsp_data() { + break; + } + mb_addr += 1; + } + Ok(NalOutcome::SliceDecoded) + } +} + +/// Reject unsupported streams with named reasons before touching pixels. +fn check_supported(sps: &Sps, pps: &Pps, slice_type_code: u32) -> Result<()> { + if pps.entropy_coding_mode { + return Err(Error::unsupported( + "CABAC entropy coding", + "only CAVLC is implemented (S18b)", + )); + } + if pps.num_slice_groups > 1 { + return Err(Error::unsupported( + "FMO slice groups", + "num_slice_groups > 1 not implemented", + )); + } + if sps.chroma_format_idc != 1 { + return Err(Error::unsupported( + "chroma format", + format!("chroma_format_idc {} (only 4:2:0)", sps.chroma_format_idc), + )); + } + if sps.bit_depth_luma != 8 || sps.bit_depth_chroma != 8 { + return Err(Error::unsupported( + "bit depth", + format!( + "{}-bit luma / {}-bit chroma (only 8-bit)", + sps.bit_depth_luma, sps.bit_depth_chroma + ), + )); + } + if !sps.frame_mbs_only { + return Err(Error::unsupported( + "interlaced coding", + "field pictures / MBAFF not implemented", + )); + } + if sps.separate_colour_plane { + return Err(Error::unsupported( + "separate colour planes", + "4:4:4 separate planes not implemented", + )); + } + if sps.transform_bypass { + return Err(Error::unsupported( + "transform bypass", + "qpprime_y_zero_transform_bypass not implemented", + )); + } + if slice_type_code > 9 { + return Err(Error::corrupt("slice_type > 9")); + } + Ok(()) +} + +/// Mutable per-slice decode state. +struct SliceCtx { + slice_id: u16, + qp: i32, + cb_qp_offset: i32, + cr_qp_offset: i32, + transform_8x8_mode: bool, +} + +/// Neighbour-availability snapshot for one macroblock (left, top, +/// top-right). Top-left availability follows from the modes that read it +/// being conformance-restricted; inter prediction will add it back. +#[derive(Clone, Copy)] +struct MbNeighbors { + a: bool, + b: bool, + c: bool, +} + +fn mb_neighbors(pic: &Picture, mb_x: usize, mb_y: usize, slice_id: u16) -> MbNeighbors { + let w = pic.mb_w; + let addr = mb_y * w + mb_x; + let same = |a: usize| pic.mb_slice[a] == slice_id; + MbNeighbors { + a: mb_x > 0 && same(addr - 1), + b: mb_y > 0 && same(addr - w), + c: mb_y > 0 && mb_x + 1 < w && same(addr - w + 1), + } +} + +/// nC for a luma 4x4 block at global block coords `(bx, by)` (spec 9.2.1). +#[inline] +fn luma_nc(pic: &Picture, n: &MbNeighbors, bx: usize, by: usize) -> i32 { + let w4 = pic.mb_w * 4; + let left_avail = if bx.is_multiple_of(4) { n.a } else { true }; + let top_avail = if by.is_multiple_of(4) { n.b } else { true }; + let na = if left_avail && bx > 0 { + i32::from(pic.nz_y[by * w4 + bx - 1]) + } else { + -1 + }; + let nb = if top_avail && by > 0 { + i32::from(pic.nz_y[(by - 1) * w4 + bx]) + } else { + -1 + }; + match (na >= 0, nb >= 0) { + (true, true) => (na + nb + 1) >> 1, + (true, false) => na, + (false, true) => nb, + (false, false) => 0, + } +} + +/// nC for a chroma AC 4x4 block at global chroma block coords. +#[inline] +fn chroma_nc(pic: &Picture, n: &MbNeighbors, comp: usize, cx: usize, cy: usize) -> i32 { + let w2 = pic.mb_w * 2; + let grid = &pic.nz_c[comp]; + let left_avail = if cx.is_multiple_of(2) { n.a } else { true }; + let top_avail = if cy.is_multiple_of(2) { n.b } else { true }; + let na = if left_avail && cx > 0 { + i32::from(grid[cy * w2 + cx - 1]) + } else { + -1 + }; + let nb = if top_avail && cy > 0 { + i32::from(grid[(cy - 1) * w2 + cx]) + } else { + -1 + }; + match (na >= 0, nb >= 0) { + (true, true) => (na + nb + 1) >> 1, + (true, false) => na, + (false, true) => nb, + (false, false) => 0, + } +} + +/// Decode one macroblock of an I slice (spec 7.3.5, 7.4.5) and reconstruct +/// it. `ctx.qp` carries the QPY prediction chain. +// Block loops are indexed: `blk` is simultaneously a bitstream position, a +// geometry key (BLK4_POS) and a grid coordinate; iterators obscure that. +#[allow(clippy::needless_range_loop)] +fn decode_macroblock( + pic: &mut Picture, + ls: &[LevelScale4x4; 3], + r: &mut BitCursor<'_>, + ctx: &mut SliceCtx, + mb_addr: usize, +) -> Result<()> { + let mb_x = mb_addr % pic.mb_w; + let mb_y = mb_addr / pic.mb_w; + if pic.mb_slice[mb_addr] != NO_SLICE { + return Err(Error::corrupt("macroblock decoded twice")); + } + let nbr = mb_neighbors(pic, mb_x, mb_y, ctx.slice_id); + let w4 = pic.mb_w * 4; + let w2 = pic.mb_w * 2; + let (bx0, by0) = (mb_x * 4, mb_y * 4); + let (cx0, cy0) = (mb_x * 2, mb_y * 2); + + let mb_type = r.read_ue()?; + if mb_type > 25 { + return Err(Error::corrupt("I-slice mb_type > 25")); + } + + if mb_type == 25 { + // I_PCM (7.3.5, 8.3.5): raw samples, byte aligned. + r.align_to_byte(); + for y in 0..16 { + let row = r.read_bytes(16)?; + let dst = pic.y.at(mb_x * 16, mb_y * 16 + y); + pic.y.data[dst..dst + 16].copy_from_slice(row); + } + for plane in [&mut pic.cb, &mut pic.cr] { + for y in 0..8 { + let row = r.read_bytes(8)?; + let dst = plane.at(mb_x * 8, mb_y * 8 + y); + plane.data[dst..dst + 8].copy_from_slice(row); + } + } + for dy in 0..4 { + let base = (by0 + dy) * w4 + bx0; + pic.nz_y[base..base + 4].fill(16); + pic.i4_modes[base..base + 4].fill(2); + } + for comp in 0..2 { + for dy in 0..2 { + let base = (cy0 + dy) * w2 + cx0; + pic.nz_c[comp][base..base + 2].fill(16); + } + } + // QPY prediction chain continues unchanged (mb_qp_delta inferred 0); + // the deblocker substitutes 0 via FLAG_PCM (spec 8.7.2). + pic.mb_qp[mb_addr] = ctx.qp as u8; + pic.mb_flags[mb_addr] = FLAG_DECODED | FLAG_PCM; + pic.mb_slice[mb_addr] = ctx.slice_id; + pic.decoded_mbs += 1; + return Ok(()); + } + + let is_i16 = mb_type >= 1; + let (cbp_luma, cbp_chroma, i16_mode) = if is_i16 { + let m = mb_type - 1; + ( + if m >= 12 { 15u8 } else { 0 }, + ((m / 4) % 3) as u8, + (m % 4) as u8, + ) + } else { + (0, 0, 0) // read below via me(v) + }; + + // I_NxN transform size flag (High profile only). + if !is_i16 && ctx.transform_8x8_mode && r.read_bit()? { + return Err(Error::unsupported( + "8x8 transform", + "transform_size_8x8_flag not implemented", + )); + } + + // mb_pred (7.3.5.1): intra 4x4 modes, then chroma mode. + let mut modes = [2u8; 16]; + if !is_i16 { + for blk in 0..16 { + let (dx, dy) = BLK4_POS[blk]; + let (bx, by) = (bx0 + dx as usize, by0 + dy as usize); + // Predicted mode = min of neighbours, DC when either unavailable + // (8.3.1.1; non-I4x4 neighbours were written as 2). + let left_avail = if bx % 4 == 0 { nbr.a } else { true }; + let top_avail = if by % 4 == 0 { nbr.b } else { true }; + let pred = if left_avail && top_avail { + let ma = pic.i4_modes[by * w4 + bx - 1]; + let mb = pic.i4_modes[(by - 1) * w4 + bx]; + ma.min(mb) + } else { + 2 + }; + let mode = if r.read_bit()? { + pred + } else { + let rem = r.read_bits(3)? as u8; + if rem < pred { rem } else { rem + 1 } + }; + pic.i4_modes[by * w4 + bx] = mode; + modes[blk] = mode; + } + } else { + for dy in 0..4 { + let base = (by0 + dy) * w4 + bx0; + pic.i4_modes[base..base + 4].fill(2); + } + } + let chroma_mode = r.read_ue()?; + if chroma_mode > 3 { + return Err(Error::corrupt("intra_chroma_pred_mode > 3")); + } + + // coded_block_pattern me(v) for I_NxN (9.1.2, Table 9-4). + let (cbp_luma, cbp_chroma) = if is_i16 { + (cbp_luma, cbp_chroma) + } else { + let code = r.read_ue()? as usize; + let cbp = if code < 48 { + CBP_INTRA_420[code] + } else { + return Err(Error::corrupt("coded_block_pattern codeNum > 47")); + }; + (cbp & 15, cbp >> 4) + }; + + // mb_qp_delta (7.4.5). + if cbp_luma != 0 || cbp_chroma != 0 || is_i16 { + let delta = r.read_se()?; + if !(-26..=25).contains(&delta) { + return Err(Error::corrupt("mb_qp_delta outside [-26, 25]")); + } + ctx.qp = (ctx.qp + delta + 52) % 52; + } + pic.mb_qp[mb_addr] = ctx.qp as u8; + pic.mb_flags[mb_addr] = FLAG_DECODED; + pic.mb_slice[mb_addr] = ctx.slice_id; + pic.decoded_mbs += 1; + let qp_y = ctx.qp; + let qp_cb = i32::from(CHROMA_QP[(qp_y + ctx.cb_qp_offset).clamp(0, 51) as usize]); + let qp_cr = i32::from(CHROMA_QP[(qp_y + ctx.cr_qp_offset).clamp(0, 51) as usize]); + + // ---- residual parse fused with reconstruction (7.3.5.3 + 8.5) ---- + // + // Bitstream order (luma blocks in Z-order, then chroma DC, then chroma + // AC) equals reconstruction dependency order, so each block reconstructs + // the moment its levels are parsed: no per-MB coefficient arrays, and + // empty blocks cost one coeff_token read plus a prediction write. + let mut scan = [0i32; 16]; + let mut raster = [0i32; 16]; + let mut resid = [0i32; 16]; + if is_i16 { + let mut w = PlaneWindow { + data: &mut pic.y.data, + stride: pic.y.stride, + origin: pic.y.origin + (mb_y * 16) * pic.y.stride + mb_x * 16, + }; + pred_16x16(i16_mode, &mut w, nbr.b, nbr.a); + // Luma DC: un-zigzag over the 4x4 DC array, Hadamard + scale. + let nc = luma_nc(pic, &nbr, bx0, by0); + residual_block(r, &mut scan, 16, nc)?; + unzigzag(&scan, &mut raster); + luma_dc_transform(&mut raster, &ls[0], qp_y); + let dc = raster; + for blk in 0..16 { + let (dx, dy) = BLK4_POS[blk]; + let (bx, by) = (bx0 + dx as usize, by0 + dy as usize); + let tc = if cbp_luma != 0 { + let nc = luma_nc(pic, &nbr, bx, by); + residual_block(r, &mut scan, 15, nc)? + } else { + 0 + }; + pic.nz_y[by * w4 + bx] = tc; + let dc_blk = dc[dy as usize * 4 + dx as usize]; + if tc == 0 && dc_blk == 0 { + continue; // prediction already in place + } + if tc > 0 { + unzigzag_ac15(&scan, &mut raster); + dequant_4x4(&mut raster, &ls[0], qp_y, true); + } else { + raster = [0; 16]; // DC-only block + } + raster[0] = dc_blk; + inverse_transform_4x4(&raster, &mut resid); + let origin = pic + .y + .at(mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4); + add_residual_4x4(&mut pic.y.data, pic.y.stride, origin, &resid); + } + } else { + for blk in 0..16 { + let (dx, dy) = BLK4_POS[blk]; + let (bx, by) = (bx0 + dx as usize, by0 + dy as usize); + let tc = if cbp_luma & (1 << (blk >> 2)) != 0 { + let nc = luma_nc(pic, &nbr, bx, by); + residual_block(r, &mut scan, 16, nc)? + } else { + 0 + }; + pic.nz_y[by * w4 + bx] = tc; + let (x, y) = (mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4); + let n = gather_nbr4(pic, &nbr, blk, x, y); + let mut p = [0u8; 16]; + pred_4x4(modes[blk], &n, &mut p); + let origin = pic.y.at(x, y); + let stride = pic.y.stride; + if tc == 0 { + // Pure prediction: copy the 16 samples in. + for ry in 0..4 { + let row = origin + ry * stride; + pic.y.data[row..row + 4].copy_from_slice(&p[ry * 4..ry * 4 + 4]); + } + continue; + } + unzigzag(&scan, &mut raster); + dequant_4x4(&mut raster, &ls[0], qp_y, false); + inverse_transform_4x4(&raster, &mut resid); + for ry in 0..4 { + let row = origin + ry * stride; + for rx in 0..4 { + let v = i32::from(p[ry * 4 + rx]) + resid[ry * 4 + rx]; + pic.y.data[row + rx] = v.clamp(0, 255) as u8; + } + } + } + } + + // Chroma: predict both components, then DC (Cb, Cr), then AC in + // bitstream order (all Cb blocks, all Cr blocks), reconstructing as + // levels arrive. + for comp in 0..2 { + let plane = if comp == 0 { &mut pic.cb } else { &mut pic.cr }; + let mut w = PlaneWindow { + data: &mut plane.data, + stride: plane.stride, + origin: plane.origin + (mb_y * 8) * plane.stride + mb_x * 8, + }; + pred_chroma_8x8(chroma_mode as u8, &mut w, nbr.b, nbr.a); + } + let mut chroma_dc = [[0i32; 4]; 2]; + if cbp_chroma != 0 { + for (comp, c) in chroma_dc.iter_mut().enumerate() { + residual_block(r, &mut scan, 4, -1)?; + c.copy_from_slice(&scan[..4]); + let (ls_c, qp_c) = if comp == 0 { + (&ls[1], qp_cb) + } else { + (&ls[2], qp_cr) + }; + chroma_dc_transform_420(c, ls_c, qp_c); + } + } + for comp in 0..2 { + for blk in 0..4 { + let (cx, cy) = (cx0 + (blk & 1), cy0 + (blk >> 1)); + let tc = if cbp_chroma == 2 { + let nc = chroma_nc(pic, &nbr, comp, cx, cy); + residual_block(r, &mut scan, 15, nc)? + } else { + 0 + }; + pic.nz_c[comp][cy * w2 + cx] = tc; + if cbp_chroma == 0 { + continue; + } + let dc_blk = chroma_dc[comp][blk]; + if tc == 0 && dc_blk == 0 { + continue; + } + let (plane, ls_c, qp_c) = if comp == 0 { + (&mut pic.cb, &ls[1], qp_cb) + } else { + (&mut pic.cr, &ls[2], qp_cr) + }; + if tc > 0 { + unzigzag_ac15(&scan, &mut raster); + dequant_4x4(&mut raster, ls_c, qp_c, true); + } else { + raster = [0; 16]; // DC-only block + } + raster[0] = dc_blk; + inverse_transform_4x4(&raster, &mut resid); + let origin = plane.at(mb_x * 8 + (blk & 1) * 4, mb_y * 8 + (blk >> 1) * 4); + add_residual_4x4(&mut plane.data, plane.stride, origin, &resid); + } + } + Ok(()) +} + +/// Gather the 13 neighbour samples of a luma 4x4 block (spec 8.3.1.2), +/// including the top-right substitution rule. +fn gather_nbr4(pic: &Picture, nbr: &MbNeighbors, blk: usize, x: usize, y: usize) -> Nbr4 { + let (dx, dy) = BLK4_POS[blk]; + let stride = pic.y.stride; + let o = pic.y.at(x, y); + let have_left = if dx == 0 { nbr.a } else { true }; + let have_top = if dy == 0 { nbr.b } else { true }; + let have_tr = match TR_KIND[blk] { + TrKind::InMb => true, + TrKind::B => nbr.b, + TrKind::C => nbr.c, + TrKind::None => false, + }; + let mut top = [0u8; 8]; + let data = &pic.y.data; + top[..4].copy_from_slice(&data[o - stride..o - stride + 4]); + if have_tr { + top[4..].copy_from_slice(&data[o - stride + 4..o - stride + 8]); + } else if have_top { + let t3 = top[3]; + top[4..].fill(t3); + } + let mut left = [0u8; 4]; + for (i, l) in left.iter_mut().enumerate() { + *l = data[o + i * stride - 1]; + } + Nbr4 { + top, + left, + top_left: data[o - stride - 1], + have_top, + have_left, + } +} + +/// 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) { + let mb_w = pic.mb_w; + for mb_y in 0..pic.mb_h { + for mb_x in 0..mb_w { + let addr = mb_y * mb_w + mb_x; + if pic.mb_flags[addr] & FLAG_DECODED == 0 { + continue; + } + let sid = pic.mb_slice[addr]; + let sp = pic.slices[sid as usize]; + if sp.disable_deblock_idc == 1 { + continue; + } + let decoded = |a: usize| pic.mb_flags[a] & FLAG_DECODED != 0; + let cross_ok = |a: usize| sp.disable_deblock_idc != 2 || pic.mb_slice[a] == sid; + let filter_left = mb_x > 0 && decoded(addr - 1) && cross_ok(addr - 1); + let filter_top = mb_y > 0 && decoded(addr - mb_w) && cross_ok(addr - mb_w); + // Deblocking QP: 0 for I_PCM macroblocks (8.7.2). + let qp_of = |a: usize| -> i32 { + if pic.mb_flags[a] & FLAG_PCM != 0 { + 0 + } else { + i32::from(pic.mb_qp[a]) + } + }; + let qp_q = qp_of(addr); + + // ---- luma ---- + { + let stride = pic.y.stride; + let base = pic.y.at(mb_x * 16, mb_y * 16); + // Vertical edges (filter across columns), left to right. + for e in 0..4 { + if e == 0 && !filter_left { + continue; + } + let (bs, qp_p) = if e == 0 { + (4, qp_of(addr - 1)) + } else { + (3, qp_q) + }; + let params = + edge_params((qp_p + qp_q + 1) >> 1, sp.alpha_offset, sp.beta_offset, bs); + if params.alpha == 0 || params.beta == 0 { + continue; + } + // Vertical edges stay scalar: a gather/scatter SIMD + // variant measured slower than this loop (strided + // per-lane loads dominate). + for k in 0..16 { + filter_luma_line(&mut pic.y.data, base + k * stride + e * 4, 1, ¶ms); + } + } + // Horizontal edges, top to bottom. + for e in 0..4 { + if e == 0 && !filter_top { + continue; + } + let (bs, qp_p) = if e == 0 { + (4, qp_of(addr - mb_w)) + } else { + (3, qp_q) + }; + let params = + edge_params((qp_p + qp_q + 1) >> 1, sp.alpha_offset, sp.beta_offset, bs); + if params.alpha == 0 || params.beta == 0 { + continue; + } + filter_luma_h_edge16(&mut pic.y.data, base + e * 4 * stride, stride, ¶ms); + } + } + + // ---- chroma (Cb, Cr) ---- + for comp in 0..2 { + let (plane, off_sel): (&mut Plane8, fn(&SliceParams) -> i32) = if comp == 0 { + (&mut pic.cb, |s| s.cb_qp_offset) + } else { + (&mut pic.cr, |s| s.cr_qp_offset) + }; + let stride = plane.stride; + let base = plane.origin + (mb_y * 8) * stride + mb_x * 8; + // Chroma QP per side: each macroblock's luma QP mapped with + // the offset of ITS OWN slice's PPS (8.7.2). + let cqp = |a: usize| -> i32 { + let s = pic.slices[pic.mb_slice[a] as usize]; + if pic.mb_flags[a] & FLAG_PCM != 0 { + chroma_qp(0, off_sel(&s)) + } else { + chroma_qp(i32::from(pic.mb_qp[a]), off_sel(&s)) + } + }; + let cq_q = cqp(addr); + for e in 0..2 { + if e == 0 && !filter_left { + continue; + } + let (bs, cq_p) = if e == 0 { + (4, cqp(addr - 1)) + } else { + (3, cq_q) + }; + let params = + edge_params((cq_p + cq_q + 1) >> 1, sp.alpha_offset, sp.beta_offset, bs); + if params.alpha == 0 || params.beta == 0 { + continue; + } + for k in 0..8 { + filter_chroma_line(&mut plane.data, base + k * stride + e * 4, 1, ¶ms); + } + } + for e in 0..2 { + if e == 0 && !filter_top { + continue; + } + let (bs, cq_p) = if e == 0 { + (4, cqp(addr - mb_w)) + } else { + (3, cq_q) + }; + let params = + edge_params((cq_p + cq_q + 1) >> 1, sp.alpha_offset, sp.beta_offset, bs); + if params.alpha == 0 || params.beta == 0 { + continue; + } + for k in 0..8 { + filter_chroma_line( + &mut plane.data, + base + e * 4 * stride + k, + stride, + ¶ms, + ); + } + } + } + } + } +} diff --git a/crates/ec-h264/src/lib.rs b/crates/ec-h264/src/lib.rs new file mode 100644 index 00000000..b7533160 --- /dev/null +++ b/crates/ec-h264/src/lib.rs @@ -0,0 +1,22 @@ +//! H.264 software decoder. +//! +//! Current scope: CAVLC-coded I slices (Intra_4x4, Intra_16x16, I_PCM) of +//! 8-bit 4:2:0 progressive streams, with the full in-loop deblocking filter, +//! decoded bit-exactly against the JVT conformance suite. Everything outside +//! that scope returns a named [`Error::Unsupported`] — never wrong output. +//! +//! Implemented from Rec. ITU-T H.264 (V15, 08/2024) only; no third-party +//! decoder source was consulted. + +#![forbid(unsafe_code)] + +mod bits; +mod cavlc; +mod deblock; +mod decoder; +mod pred; +mod tables; +mod transform; + +pub use decoder::{Decoder, NalOutcome}; +pub use ec_core::error::{Error, Result}; diff --git a/crates/ec-h264/src/pred.rs b/crates/ec-h264/src/pred.rs new file mode 100644 index 00000000..2da646ba --- /dev/null +++ b/crates/ec-h264/src/pred.rs @@ -0,0 +1,456 @@ +//! Intra prediction (spec 8.3.1, 8.3.3, 8.3.4), 8-bit. +//! +//! Kernels operate on a small gathered neighbour set so the hot loop touches +//! the picture plane only twice per block: one gather, one write. All +//! arithmetic is in `i32` with a final `clamp(0, 255)`. + +/// Neighbour samples of a 4x4 block, gathered once (spec 8.3.1.2's 13 +/// samples). `top[4..8]` already has the top-right substitution rule applied: +/// when p[4..7, -1] is unavailable but p[3, -1] is, it is replicated. +#[derive(Debug, Clone, Copy)] +pub struct Nbr4 { + /// p[0..7, -1]. + pub top: [u8; 8], + /// p[-1, 0..3]. + pub left: [u8; 4], + /// p[-1, -1]. + pub top_left: u8, + /// p[x, -1] available. + pub have_top: bool, + /// p[-1, y] available. + pub have_left: bool, +} + +/// Predict a 4x4 block (spec 8.3.1.2.1-9) into `out` in raster order. +/// +/// Modes 0..=8; conformant streams only signal modes whose required samples +/// are available, but unavailable inputs still produce defined output (DC +/// fallbacks) rather than reading junk. +pub fn pred_4x4(mode: u8, n: &Nbr4, out: &mut [u8; 16]) { + let t = |x: usize| i32::from(n.top[x]); + let l = |y: usize| i32::from(n.left[y]); + let tl = i32::from(n.top_left); + match mode { + // Vertical. + 0 => { + for y in 0..4 { + for x in 0..4 { + out[y * 4 + x] = n.top[x]; + } + } + } + // Horizontal. + 1 => { + for y in 0..4 { + out[y * 4..y * 4 + 4].fill(n.left[y]); + } + } + // DC (8-48..8-51). + 2 => { + let v = match (n.have_top, n.have_left) { + (true, true) => (t(0) + t(1) + t(2) + t(3) + l(0) + l(1) + l(2) + l(3) + 4) >> 3, + (false, true) => (l(0) + l(1) + l(2) + l(3) + 2) >> 2, + (true, false) => (t(0) + t(1) + t(2) + t(3) + 2) >> 2, + (false, false) => 128, + }; + out.fill(v as u8); + } + // Diagonal down-left (8-52, 8-53). + 3 => { + for y in 0..4 { + for x in 0..4 { + let v = if x == 3 && y == 3 { + (t(6) + 3 * t(7) + 2) >> 2 + } else { + (t(x + y) + 2 * t(x + y + 1) + t(x + y + 2) + 2) >> 2 + }; + out[y * 4 + x] = v as u8; + } + } + } + // Diagonal down-right (8-54..8-56). Index -1 is the top-left sample. + 4 => { + let te = |i: i32| if i < 0 { tl } else { t(i as usize) }; + let le = |i: i32| if i < 0 { tl } else { l(i as usize) }; + for y in 0..4i32 { + for x in 0..4i32 { + let v = if x > y { + (te(x - y - 2) + 2 * te(x - y - 1) + te(x - y) + 2) >> 2 + } else if x < y { + (le(y - x - 2) + 2 * le(y - x - 1) + le(y - x) + 2) >> 2 + } else { + (t(0) + 2 * tl + l(0) + 2) >> 2 + }; + out[(y * 4 + x) as usize] = v as u8; + } + } + } + // Vertical-right (8-57..8-60). + 5 => { + let te = |i: i32| if i < 0 { tl } else { t(i as usize) }; + let le = |i: i32| if i < 0 { tl } else { l(i as usize) }; + for y in 0..4i32 { + for x in 0..4i32 { + let z = 2 * x - y; + let i = x - (y >> 1); + let v = if z >= 0 && z % 2 == 0 { + (te(i - 1) + te(i) + 1) >> 1 + } else if z >= 0 { + (te(i - 2) + 2 * te(i - 1) + te(i) + 2) >> 2 + } else if z == -1 { + (l(0) + 2 * tl + t(0) + 2) >> 2 + } else { + (le(y - 1) + 2 * le(y - 2) + le(y - 3) + 2) >> 2 + }; + out[(y * 4 + x) as usize] = v as u8; + } + } + } + // Horizontal-down (8-61..8-64). + 6 => { + let te = |i: i32| if i < 0 { tl } else { t(i as usize) }; + let le = |i: i32| if i < 0 { tl } else { l(i as usize) }; + for y in 0..4i32 { + for x in 0..4i32 { + let z = 2 * y - x; + let i = y - (x >> 1); + let v = if z >= 0 && z % 2 == 0 { + (le(i - 1) + le(i) + 1) >> 1 + } else if z >= 0 { + (le(i - 2) + 2 * le(i - 1) + le(i) + 2) >> 2 + } else if z == -1 { + (l(0) + 2 * tl + t(0) + 2) >> 2 + } else { + (te(x - 1) + 2 * te(x - 2) + te(x - 3) + 2) >> 2 + }; + out[(y * 4 + x) as usize] = v as u8; + } + } + } + // Vertical-left (8-65, 8-66). + 7 => { + for y in 0..4usize { + for x in 0..4usize { + let i = x + (y >> 1); + let v = if y % 2 == 0 { + (t(i) + t(i + 1) + 1) >> 1 + } else { + (t(i) + 2 * t(i + 1) + t(i + 2) + 2) >> 2 + }; + out[y * 4 + x] = v as u8; + } + } + } + // Horizontal-up (8-67..8-70). + _ => { + for y in 0..4usize { + for x in 0..4usize { + let z = x + 2 * y; + let i = y + (x >> 1); + let v = if z < 5 && z % 2 == 0 { + (l(i) + l(i + 1) + 1) >> 1 + } else if z < 5 { + (l(i) + 2 * l(i + 1) + l(i + 2) + 2) >> 2 + } else if z == 5 { + (l(2) + 3 * l(3) + 2) >> 2 + } else { + l(3) + }; + out[y * 4 + x] = v as u8; + } + } + } + } +} + +/// A borrowed window into a picture plane for whole-MB prediction: `data` +/// spans the plane, `stride` its pitch, `origin` the index of this MB's +/// top-left sample. +pub struct PlaneWindow<'a> { + /// The full plane. + pub data: &'a mut [u8], + /// Row pitch. + pub stride: usize, + /// Index of the block's top-left sample. + pub origin: usize, +} + +/// Intra_16x16 prediction (spec 8.3.3), writing predictions straight into the +/// plane; residuals are added on top afterwards. +pub fn pred_16x16(mode: u8, w: &mut PlaneWindow<'_>, have_top: bool, have_left: bool) { + pred_nxn::<16>(mode, w, have_top, have_left, 5, 5); +} + +/// Chroma 8x8 prediction for 4:2:0 (spec 8.3.4). Chroma mode numbering +/// differs from luma 16x16: 0 = DC, 1 = Horizontal, 2 = Vertical, 3 = Plane. +pub fn pred_chroma_8x8(mode: u8, w: &mut PlaneWindow<'_>, have_top: bool, have_left: bool) { + match mode { + 0 => pred_chroma_dc(w, have_top, have_left), + 1 => pred_nxn::<8>(1, w, have_top, have_left, 0, 0), + 2 => pred_nxn::<8>(0, w, have_top, have_left, 0, 0), + _ => pred_nxn::<8>(3, w, have_top, have_left, 0, 34), + } +} + +/// Shared V/H/DC/Plane engine for NxN whole-block prediction. `mode` uses the +/// 16x16 numbering (0 V, 1 H, 2 DC, 3 Plane). `dc_shift` = log2(2N), +/// `plane_scale` = 5 for luma, 34 for 4:2:0 chroma. +fn pred_nxn( + mode: u8, + w: &mut PlaneWindow<'_>, + have_top: bool, + have_left: bool, + dc_shift: u32, + plane_scale: i32, +) { + let stride = w.stride; + let o = w.origin; + match mode { + 0 => { + // Vertical: replicate the row above. + let (top, rest) = w.data.split_at_mut(o); + let top_row = &top[o - stride..o - stride + N]; + for y in 0..N { + rest[y * stride..y * stride + N].copy_from_slice(top_row); + } + } + 1 => { + for y in 0..N { + let v = w.data[o + y * stride - 1]; + w.data[o + y * stride..o + y * stride + N].fill(v); + } + } + 2 => { + let mut sum = 0i32; + if have_top { + for x in 0..N { + sum += i32::from(w.data[o - stride + x]); + } + } + if have_left { + for y in 0..N { + sum += i32::from(w.data[o + y * stride - 1]); + } + } + let v = match (have_top, have_left) { + (true, true) => (sum + (1 << (dc_shift - 1))) >> dc_shift, + (true, false) | (false, true) => (sum + (1 << (dc_shift - 2))) >> (dc_shift - 1), + (false, false) => 128, + } as u8; + for y in 0..N { + w.data[o + y * stride..o + y * stride + N].fill(v); + } + } + _ => { + // Plane (8-122..8-127 / 8-144..8-149). half = N/2. + let half = (N / 2) as i32; + let px = |x: i32, y: i32| -> i32 { + let idx = (o as i32 + y * stride as i32 + x) as usize; + i32::from(w.data[idx]) + }; + let mut h = 0i32; + let mut v = 0i32; + for i in 0..half { + h += (i + 1) * (px(half + i, -1) - px(half - 2 - i, -1)); + v += (i + 1) * (px(-1, half + i) - px(-1, half - 2 - i)); + } + let a = 16 * (px(-1, N as i32 - 1) + px(N as i32 - 1, -1)); + let b = (plane_scale * h + 32) >> 6; + let c = (plane_scale * v + 32) >> 6; + for y in 0..N as i32 { + for x in 0..N as i32 { + let p = (a + b * (x - (half - 1)) + c * (y - (half - 1)) + 16) >> 5; + w.data[o + y as usize * stride + x as usize] = p.clamp(0, 255) as u8; + } + } + } + } +} + +/// Chroma DC prediction (spec 8.3.4.1): each 4x4 sub-block averages specific +/// neighbour runs — corner blocks prefer their adjacent edge. +fn pred_chroma_dc(w: &mut PlaneWindow<'_>, have_top: bool, have_left: bool) { + let stride = w.stride; + let o = w.origin; + let sum_top = |data: &[u8], x0: usize| -> i32 { + (0..4).map(|i| i32::from(data[o - stride + x0 + i])).sum() + }; + let sum_left = |data: &[u8], y0: usize| -> i32 { + (0..4) + .map(|i| i32::from(data[o + (y0 + i) * stride - 1])) + .sum() + }; + for by in 0..2 { + for bx in 0..2 { + // (0,0) and (1,1) use both edges; (1,0) prefers top; (0,1) left. + let v = if bx == by { + match (have_top, have_left) { + (true, true) => (sum_top(w.data, bx * 4) + sum_left(w.data, by * 4) + 4) >> 3, + (true, false) => (sum_top(w.data, bx * 4) + 2) >> 2, + (false, true) => (sum_left(w.data, by * 4) + 2) >> 2, + (false, false) => 128, + } + } else if bx == 1 { + match (have_top, have_left) { + (true, _) => (sum_top(w.data, 4) + 2) >> 2, + (false, true) => (sum_left(w.data, 0) + 2) >> 2, + (false, false) => 128, + } + } else { + match (have_left, have_top) { + (true, _) => (sum_left(w.data, 4) + 2) >> 2, + (false, true) => (sum_top(w.data, 0) + 2) >> 2, + (false, false) => 128, + } + } as u8; + for y in 0..4 { + let row = o + (by * 4 + y) * stride + bx * 4; + w.data[row..row + 4].fill(v); + } + } + } +} + +/// Add a 4x4 residual to the plane with clamping (picture construction, +/// spec 8.5.14 path for 8-bit). +#[inline] +pub fn add_residual_4x4(data: &mut [u8], stride: usize, origin: usize, r: &[i32; 16]) { + for y in 0..4 { + let row = origin + y * stride; + for x in 0..4 { + let p = i32::from(data[row + x]) + r[y * 4 + x]; + data[row + x] = p.clamp(0, 255) as u8; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn dc_4x4_fallbacks() { + let n = Nbr4 { + top: [10; 8], + left: [20; 4], + top_left: 0, + have_top: true, + have_left: true, + }; + let mut out = [0u8; 16]; + pred_4x4(2, &n, &mut out); + assert!(out.iter().all(|&v| v == 15)); // (40 + 80 + 4) >> 3 + let n2 = Nbr4 { + have_left: false, + ..n + }; + pred_4x4(2, &n2, &mut out); + assert!(out.iter().all(|&v| v == 10)); + let n3 = Nbr4 { + have_top: false, + have_left: false, + ..n + }; + pred_4x4(2, &n3, &mut out); + assert!(out.iter().all(|&v| v == 128)); + } + + #[test] + fn vertical_and_horizontal_4x4() { + let n = Nbr4 { + top: [1, 2, 3, 4, 5, 6, 7, 8], + left: [9, 10, 11, 12], + top_left: 0, + have_top: true, + have_left: true, + }; + let mut out = [0u8; 16]; + pred_4x4(0, &n, &mut out); + assert_eq!(&out[0..4], &[1, 2, 3, 4]); + assert_eq!(&out[12..16], &[1, 2, 3, 4]); + pred_4x4(1, &n, &mut out); + assert_eq!(out[0], 9); + assert_eq!(out[15], 12); + } + + /// Diagonal down-left of a constant edge stays constant; the (3,3) + /// special tap agrees. + #[test] + fn ddl_constant_edge() { + let n = Nbr4 { + top: [50; 8], + left: [0; 4], + top_left: 0, + have_top: true, + have_left: false, + }; + let mut out = [0u8; 16]; + pred_4x4(3, &n, &mut out); + assert!(out.iter().all(|&v| v == 50)); + } + + /// Plane prediction of a linear ramp reproduces the ramp. + #[test] + fn plane_16x16_ramp() { + let stride = 24usize; + let mut data = vec![0u8; stride * 24]; + // Fill neighbours: top row and left column of a 16x16 at (1, 1). + let origin = stride + 1; + for (x, d) in data.iter_mut().enumerate().take(17) { + *d = (10 + 2 * x) as u8; // includes top-left at x=0 + } + for y in 0..17 { + data[y * stride] = (10 + 3 * y) as u8; + } + let mut w = PlaneWindow { + data: &mut data, + stride, + origin, + }; + pred_16x16(3, &mut w, true, true); + // A perfect plane through those edges: value at (x, y) approximately + // 12 + 2x + 3y. Check corners within rounding of the spec filter. + let v = |x: usize, y: usize| i32::from(data[origin + y * stride + x]); + assert!((v(0, 0) - 17).abs() <= 3, "{}", v(0, 0)); + assert!((v(15, 0) - (12 + 30)).abs() <= 3); + assert!((v(0, 15) - (12 + 45)).abs() <= 3); + assert!((v(15, 15) - (12 + 30 + 45)).abs() <= 3); + } + + #[test] + fn chroma_dc_corner_preferences() { + let stride = 16usize; + let mut data = vec![0u8; stride * 16]; + let origin = stride + 1; + // Top neighbours 40, left neighbours 80. + for x in 0..8 { + data[1 + x] = 40; + } + for y in 0..8 { + data[(1 + y) * stride] = 80; + } + let mut w = PlaneWindow { + data: &mut data, + stride, + origin, + }; + pred_chroma_8x8(0, &mut w, true, true); + let v = |x: usize, y: usize| data[origin + y * stride + x]; + assert_eq!(v(0, 0), 60); // both edges + assert_eq!(v(7, 0), 40); // top preferred + assert_eq!(v(0, 7), 80); // left preferred + assert_eq!(v(7, 7), 60); // both edges + } + + #[test] + fn add_residual_clamps() { + let mut data = vec![250u8; 16]; + let mut r = [0i32; 16]; + r[0] = 100; + r[1] = -300; + add_residual_4x4(&mut data, 4, 0, &r); + assert_eq!(data[0], 255); + assert_eq!(data[1], 0); + assert_eq!(data[2], 250); + } +} diff --git a/crates/ec-h264/src/tables.rs b/crates/ec-h264/src/tables.rs new file mode 100644 index 00000000..0ec97456 --- /dev/null +++ b/crates/ec-h264/src/tables.rs @@ -0,0 +1,653 @@ +//! Constant tables transcribed from Rec. ITU-T H.264 (V15, 08/2024). +//! +//! Every table cites its spec number. VLC codes are stored as +//! `(len, code, value...)` with the code right-aligned in an integer; decoding +//! peeks 16 bits left-aligned and compares prefixes. + +/// One coeff_token entry: (code length, code, TotalCoeff, TrailingOnes). +pub type CoeffTokenEntry = (u8, u16, u8, u8); + +/// Table 9-5, column 0 <= nC < 2. +pub const COEFF_TOKEN_NC0: &[CoeffTokenEntry] = &[ + (1, 0b1, 0, 0), + (2, 0b01, 1, 1), + (3, 0b001, 2, 2), + (5, 0b00011, 3, 3), + (6, 0b000101, 1, 0), + (6, 0b000100, 2, 1), + (6, 0b000011, 4, 3), + (7, 0b0000101, 3, 2), + (7, 0b0000100, 5, 3), + (8, 0b00000111, 2, 0), + (8, 0b00000110, 3, 1), + (8, 0b00000101, 4, 2), + (8, 0b00000100, 6, 3), + (9, 0b000000111, 3, 0), + (9, 0b000000110, 4, 1), + (9, 0b000000101, 5, 2), + (9, 0b000000100, 7, 3), + (10, 0b0000000111, 4, 0), + (10, 0b0000000110, 5, 1), + (10, 0b0000000101, 6, 2), + (10, 0b0000000100, 8, 3), + (11, 0b00000000111, 5, 0), + (11, 0b00000000110, 6, 1), + (11, 0b00000000101, 7, 2), + (11, 0b00000000100, 9, 3), + (13, 0b0000000001111, 6, 0), + (13, 0b0000000001011, 7, 0), + (13, 0b0000000001110, 7, 1), + (13, 0b0000000001000, 8, 0), + (13, 0b0000000001010, 8, 1), + (13, 0b0000000001101, 8, 2), + (13, 0b0000000001001, 9, 2), + (13, 0b0000000001100, 10, 3), + (14, 0b00000000001111, 9, 0), + (14, 0b00000000001110, 9, 1), + (14, 0b00000000001011, 10, 0), + (14, 0b00000000001010, 10, 1), + (14, 0b00000000001101, 10, 2), + (14, 0b00000000001001, 11, 2), + (14, 0b00000000001100, 11, 3), + (14, 0b00000000001000, 12, 3), + (15, 0b000000000001111, 11, 0), + (15, 0b000000000001110, 11, 1), + (15, 0b000000000001011, 12, 0), + (15, 0b000000000001010, 12, 1), + (15, 0b000000000001101, 12, 2), + (15, 0b000000000000001, 13, 1), + (15, 0b000000000001001, 13, 2), + (15, 0b000000000001100, 13, 3), + (15, 0b000000000001000, 14, 3), + (16, 0b0000000000001111, 13, 0), + (16, 0b0000000000001011, 14, 0), + (16, 0b0000000000001110, 14, 1), + (16, 0b0000000000001101, 14, 2), + (16, 0b0000000000000111, 15, 0), + (16, 0b0000000000001010, 15, 1), + (16, 0b0000000000001001, 15, 2), + (16, 0b0000000000001100, 15, 3), + (16, 0b0000000000000100, 16, 0), + (16, 0b0000000000000110, 16, 1), + (16, 0b0000000000000101, 16, 2), + (16, 0b0000000000001000, 16, 3), +]; + +/// Table 9-5, column 2 <= nC < 4. +pub const COEFF_TOKEN_NC2: &[CoeffTokenEntry] = &[ + (2, 0b11, 0, 0), + (2, 0b10, 1, 1), + (3, 0b011, 2, 2), + (4, 0b0101, 3, 3), + (4, 0b0100, 4, 3), + (5, 0b00111, 2, 1), + (5, 0b00110, 5, 3), + (6, 0b001011, 1, 0), + (6, 0b000111, 2, 0), + (6, 0b001010, 3, 1), + (6, 0b001001, 3, 2), + (6, 0b000110, 4, 1), + (6, 0b000101, 4, 2), + (6, 0b001000, 6, 3), + (6, 0b000100, 7, 3), + (7, 0b0000111, 3, 0), + (7, 0b0000110, 5, 1), + (7, 0b0000101, 5, 2), + (7, 0b0000100, 8, 3), + (8, 0b00000111, 4, 0), + (8, 0b00000100, 5, 0), + (8, 0b00000110, 6, 1), + (8, 0b00000101, 6, 2), + (9, 0b000000111, 6, 0), + (9, 0b000000110, 7, 1), + (9, 0b000000101, 7, 2), + (9, 0b000000100, 9, 3), + (11, 0b00000001111, 7, 0), + (11, 0b00000001011, 8, 0), + (11, 0b00000001110, 8, 1), + (11, 0b00000001101, 8, 2), + (11, 0b00000001010, 9, 1), + (11, 0b00000001001, 9, 2), + (11, 0b00000001100, 10, 3), + (11, 0b00000001000, 11, 3), + (12, 0b000000001111, 9, 0), + (12, 0b000000001011, 10, 0), + (12, 0b000000001110, 10, 1), + (12, 0b000000001101, 10, 2), + (12, 0b000000001000, 11, 0), + (12, 0b000000001010, 11, 1), + (12, 0b000000001001, 11, 2), + (12, 0b000000001100, 12, 3), + (13, 0b0000000001111, 12, 0), + (13, 0b0000000001110, 12, 1), + (13, 0b0000000001101, 12, 2), + (13, 0b0000000001011, 13, 0), + (13, 0b0000000001010, 13, 1), + (13, 0b0000000001001, 13, 2), + (13, 0b0000000001100, 13, 3), + (13, 0b0000000000111, 14, 0), + (13, 0b0000000000110, 14, 2), + (13, 0b0000000001000, 14, 3), + (13, 0b0000000000001, 15, 3), + (14, 0b00000000001011, 14, 1), + (14, 0b00000000001001, 15, 0), + (14, 0b00000000001000, 15, 1), + (14, 0b00000000001010, 15, 2), + (14, 0b00000000000111, 16, 0), + (14, 0b00000000000110, 16, 1), + (14, 0b00000000000101, 16, 2), + (14, 0b00000000000100, 16, 3), +]; + +/// Table 9-5, column 4 <= nC < 8. +pub const COEFF_TOKEN_NC4: &[CoeffTokenEntry] = &[ + (4, 0b1111, 0, 0), + (4, 0b1110, 1, 1), + (4, 0b1101, 2, 2), + (4, 0b1100, 3, 3), + (4, 0b1011, 4, 3), + (4, 0b1010, 5, 3), + (4, 0b1001, 6, 3), + (4, 0b1000, 7, 3), + (5, 0b01111, 2, 1), + (5, 0b01100, 3, 1), + (5, 0b01110, 3, 2), + (5, 0b01010, 4, 1), + (5, 0b01011, 4, 2), + (5, 0b01000, 5, 1), + (5, 0b01001, 5, 2), + (5, 0b01101, 8, 3), + (6, 0b001111, 1, 0), + (6, 0b001011, 2, 0), + (6, 0b001000, 3, 0), + (6, 0b001110, 6, 1), + (6, 0b001101, 6, 2), + (6, 0b001010, 7, 1), + (6, 0b001001, 7, 2), + (6, 0b001100, 9, 3), + (7, 0b0001111, 4, 0), + (7, 0b0001011, 5, 0), + (7, 0b0001001, 6, 0), + (7, 0b0001000, 7, 0), + (7, 0b0001110, 8, 1), + (7, 0b0001101, 8, 2), + (7, 0b0001010, 9, 2), + (7, 0b0001100, 10, 3), + (8, 0b00001111, 8, 0), + (8, 0b00001011, 9, 0), + (8, 0b00001110, 9, 1), + (8, 0b00001010, 10, 1), + (8, 0b00001101, 10, 2), + (8, 0b00001001, 11, 2), + (8, 0b00001100, 11, 3), + (8, 0b00001000, 12, 3), + (9, 0b000001111, 10, 0), + (9, 0b000001011, 11, 0), + (9, 0b000001110, 11, 1), + (9, 0b000001000, 12, 0), + (9, 0b000001010, 12, 1), + (9, 0b000001101, 12, 2), + (9, 0b000000111, 13, 1), + (9, 0b000001001, 13, 2), + (9, 0b000001100, 13, 3), + (10, 0b0000001101, 13, 0), + (10, 0b0000001001, 14, 0), + (10, 0b0000001100, 14, 1), + (10, 0b0000001011, 14, 2), + (10, 0b0000001010, 14, 3), + (10, 0b0000000101, 15, 0), + (10, 0b0000001000, 15, 1), + (10, 0b0000000111, 15, 2), + (10, 0b0000000110, 15, 3), + (10, 0b0000000001, 16, 0), + (10, 0b0000000100, 16, 1), + (10, 0b0000000011, 16, 2), + (10, 0b0000000010, 16, 3), +]; + +/// Table 9-5, column nC == -1 (chroma DC, 4:2:0). +pub const COEFF_TOKEN_CHROMA_DC: &[CoeffTokenEntry] = &[ + (1, 0b1, 1, 1), + (2, 0b01, 0, 0), + (3, 0b001, 2, 2), + (6, 0b000111, 1, 0), + (6, 0b000100, 2, 0), + (6, 0b000110, 2, 1), + (6, 0b000011, 3, 0), + (6, 0b000101, 3, 3), + (6, 0b000010, 4, 0), + (7, 0b0000011, 3, 1), + (7, 0b0000010, 3, 2), + (7, 0b0000000, 4, 3), + (8, 0b00000011, 4, 1), + (8, 0b00000010, 4, 2), +]; + +/// One total_zeros / run_before entry: (code length, code, value). +pub type VlcEntry = (u8, u16, u8); + +/// Tables 9-7 and 9-8: total_zeros for 4x4 blocks, indexed by +/// `tzVlcIndex - 1` (tzVlcIndex = TotalCoeff, 1..=15). +pub const TOTAL_ZEROS_4X4: [&[VlcEntry]; 15] = [ + // tzVlcIndex 1 + &[ + (1, 0b1, 0), + (3, 0b011, 1), + (3, 0b010, 2), + (4, 0b0011, 3), + (4, 0b0010, 4), + (5, 0b00011, 5), + (5, 0b00010, 6), + (6, 0b000011, 7), + (6, 0b000010, 8), + (7, 0b0000011, 9), + (7, 0b0000010, 10), + (8, 0b00000011, 11), + (8, 0b00000010, 12), + (9, 0b000000011, 13), + (9, 0b000000010, 14), + (9, 0b000000001, 15), + ], + // tzVlcIndex 2 + &[ + (3, 0b111, 0), + (3, 0b110, 1), + (3, 0b101, 2), + (3, 0b100, 3), + (3, 0b011, 4), + (4, 0b0101, 5), + (4, 0b0100, 6), + (4, 0b0011, 7), + (4, 0b0010, 8), + (5, 0b00011, 9), + (5, 0b00010, 10), + (6, 0b000011, 11), + (6, 0b000010, 12), + (6, 0b000001, 13), + (6, 0b000000, 14), + ], + // tzVlcIndex 3 + &[ + (4, 0b0101, 0), + (3, 0b111, 1), + (3, 0b110, 2), + (3, 0b101, 3), + (4, 0b0100, 4), + (4, 0b0011, 5), + (3, 0b100, 6), + (3, 0b011, 7), + (4, 0b0010, 8), + (5, 0b00011, 9), + (5, 0b00010, 10), + (6, 0b000001, 11), + (5, 0b00001, 12), + (6, 0b000000, 13), + ], + // tzVlcIndex 4 + &[ + (5, 0b00011, 0), + (3, 0b111, 1), + (4, 0b0101, 2), + (4, 0b0100, 3), + (3, 0b110, 4), + (3, 0b101, 5), + (3, 0b100, 6), + (4, 0b0011, 7), + (3, 0b011, 8), + (4, 0b0010, 9), + (5, 0b00010, 10), + (5, 0b00001, 11), + (5, 0b00000, 12), + ], + // tzVlcIndex 5 + &[ + (4, 0b0101, 0), + (4, 0b0100, 1), + (4, 0b0011, 2), + (3, 0b111, 3), + (3, 0b110, 4), + (3, 0b101, 5), + (3, 0b100, 6), + (3, 0b011, 7), + (4, 0b0010, 8), + (5, 0b00001, 9), + (4, 0b0001, 10), + (5, 0b00000, 11), + ], + // tzVlcIndex 6 + &[ + (6, 0b000001, 0), + (5, 0b00001, 1), + (3, 0b111, 2), + (3, 0b110, 3), + (3, 0b101, 4), + (3, 0b100, 5), + (3, 0b011, 6), + (3, 0b010, 7), + (4, 0b0001, 8), + (3, 0b001, 9), + (6, 0b000000, 10), + ], + // tzVlcIndex 7 + &[ + (6, 0b000001, 0), + (5, 0b00001, 1), + (3, 0b101, 2), + (3, 0b100, 3), + (3, 0b011, 4), + (2, 0b11, 5), + (3, 0b010, 6), + (4, 0b0001, 7), + (3, 0b001, 8), + (6, 0b000000, 9), + ], + // tzVlcIndex 8 + &[ + (6, 0b000001, 0), + (4, 0b0001, 1), + (5, 0b00001, 2), + (3, 0b011, 3), + (2, 0b11, 4), + (2, 0b10, 5), + (3, 0b010, 6), + (3, 0b001, 7), + (6, 0b000000, 8), + ], + // tzVlcIndex 9 + &[ + (6, 0b000001, 0), + (6, 0b000000, 1), + (4, 0b0001, 2), + (2, 0b11, 3), + (2, 0b10, 4), + (3, 0b001, 5), + (2, 0b01, 6), + (5, 0b00001, 7), + ], + // tzVlcIndex 10 + &[ + (5, 0b00001, 0), + (5, 0b00000, 1), + (3, 0b001, 2), + (2, 0b11, 3), + (2, 0b10, 4), + (2, 0b01, 5), + (4, 0b0001, 6), + ], + // tzVlcIndex 11 + &[ + (4, 0b0000, 0), + (4, 0b0001, 1), + (3, 0b001, 2), + (3, 0b010, 3), + (1, 0b1, 4), + (3, 0b011, 5), + ], + // tzVlcIndex 12 + &[ + (4, 0b0000, 0), + (4, 0b0001, 1), + (2, 0b01, 2), + (1, 0b1, 3), + (3, 0b001, 4), + ], + // tzVlcIndex 13 + &[(3, 0b000, 0), (3, 0b001, 1), (1, 0b1, 2), (2, 0b01, 3)], + // tzVlcIndex 14 + &[(2, 0b00, 0), (2, 0b01, 1), (1, 0b1, 2)], + // tzVlcIndex 15 + &[(1, 0b0, 0), (1, 0b1, 1)], +]; + +/// Table 9-9 (a): total_zeros for chroma DC 2x2 (4:2:0), by tzVlcIndex 1..=3. +pub const TOTAL_ZEROS_CHROMA_DC: [&[VlcEntry]; 3] = [ + &[(1, 0b1, 0), (2, 0b01, 1), (3, 0b001, 2), (3, 0b000, 3)], + &[(1, 0b1, 0), (2, 0b01, 1), (2, 0b00, 2)], + &[(1, 0b1, 0), (1, 0b0, 1)], +]; + +/// Table 9-10: run_before, indexed by min(zerosLeft, 7) - 1. +pub const RUN_BEFORE: [&[VlcEntry]; 7] = [ + // zerosLeft 1 + &[(1, 0b1, 0), (1, 0b0, 1)], + // zerosLeft 2 + &[(1, 0b1, 0), (2, 0b01, 1), (2, 0b00, 2)], + // zerosLeft 3 + &[(2, 0b11, 0), (2, 0b10, 1), (2, 0b01, 2), (2, 0b00, 3)], + // zerosLeft 4 + &[ + (2, 0b11, 0), + (2, 0b10, 1), + (2, 0b01, 2), + (3, 0b001, 3), + (3, 0b000, 4), + ], + // zerosLeft 5 + &[ + (2, 0b11, 0), + (2, 0b10, 1), + (3, 0b011, 2), + (3, 0b010, 3), + (3, 0b001, 4), + (3, 0b000, 5), + ], + // zerosLeft 6 + &[ + (2, 0b11, 0), + (3, 0b000, 1), + (3, 0b001, 2), + (3, 0b011, 3), + (3, 0b010, 4), + (3, 0b101, 5), + (3, 0b100, 6), + ], + // zerosLeft > 6 + &[ + (3, 0b111, 0), + (3, 0b110, 1), + (3, 0b101, 2), + (3, 0b100, 3), + (3, 0b011, 4), + (3, 0b010, 5), + (3, 0b001, 6), + (4, 0b0001, 7), + (5, 0b00001, 8), + (6, 0b000001, 9), + (7, 0b0000001, 10), + (8, 0b00000001, 11), + (9, 0b000000001, 12), + (10, 0b0000000001, 13), + (11, 0b00000000001, 14), + ], +]; + +/// Table 9-4 (a), Intra_4x4/Intra_8x8 column: codeNum -> coded_block_pattern +/// for ChromaArrayType 1 or 2. +pub const CBP_INTRA_420: [u8; 48] = [ + 47, 31, 15, 0, 23, 27, 29, 30, 7, 11, 13, 14, 39, 43, 45, 46, 16, 3, 5, 10, 12, 19, 21, 26, 28, + 35, 37, 42, 44, 1, 2, 4, 8, 17, 18, 20, 24, 6, 9, 22, 25, 32, 33, 34, 36, 40, 38, 41, +]; + +/// Table 9-4 (b), Intra column: codeNum -> coded_block_pattern for +/// ChromaArrayType 0 or 3. Unused until monochrome / 4:4:4 decode lands; +/// kept beside its sibling so the spec table lives in one place. +#[allow(dead_code)] +pub const CBP_INTRA_MONO: [u8; 16] = [15, 0, 7, 11, 13, 14, 3, 5, 10, 12, 1, 2, 4, 8, 6, 9]; + +/// Table 8-15: QPC as a function of qPI (identity below 30). +pub const CHROMA_QP: [u8; 52] = [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + 26, 27, 28, 29, 29, 30, 31, 32, 32, 33, 34, 34, 35, 35, 36, 36, 37, 37, 37, 38, 38, 38, 39, 39, + 39, 39, +]; + +/// Equation 8-315: normAdjust4x4 v matrix, rows m = qP % 6, columns the three +/// position classes (0: both even, 1: both odd, 2: mixed). +pub const NORM_ADJUST_4X4: [[u16; 3]; 6] = [ + [10, 16, 13], + [11, 18, 14], + [13, 20, 16], + [14, 23, 18], + [16, 25, 20], + [18, 29, 23], +]; + +/// Position class per raster index of a 4x4 block, for [`NORM_ADJUST_4X4`]: +/// (i % 2, j % 2) == (0,0) -> 0, (1,1) -> 1, else 2 (Equation 8-314). +pub const NORM_ADJUST_CLASS_4X4: [u8; 16] = [0, 2, 0, 2, 2, 1, 2, 1, 0, 2, 0, 2, 2, 1, 2, 1]; + +/// Table 8-16: alpha' by indexA. +pub const ALPHA: [u8; 52] = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 5, 6, 7, 8, 9, 10, 12, 13, 15, 17, 20, + 22, 25, 28, 32, 36, 40, 45, 50, 56, 63, 71, 80, 90, 101, 113, 127, 144, 162, 182, 203, 226, + 255, 255, +]; + +/// Table 8-16: beta' by indexB. +pub const BETA: [u8; 52] = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 6, 6, 7, 7, 8, 8, + 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, +]; + +/// Table 8-17: tC0' by [bS - 1][indexA]. +pub const TC0: [[u8; 52]; 3] = [ + [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 6, 6, 7, 8, + ], + [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 5, 5, 6, 7, 8, 8, 10, 11, 12, 13, 15, + ], + [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, + 2, 3, 3, 3, 4, 4, 4, 5, 6, 6, 7, 8, 9, 10, 11, 13, 14, 16, 18, 20, 23, 25, + ], +]; + +/// 4x4 zig-zag scan: scan position -> raster index (Table 8-13, frame scan). +pub const ZIGZAG_4X4: [u8; 16] = [0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15]; + +/// luma4x4BlkIdx -> (x, y) position in 4-sample units within the macroblock +/// (spec 6.4.3 inverse 4x4 luma block scan). +pub const BLK4_POS: [(u8, u8); 16] = [ + (0, 0), + (1, 0), + (0, 1), + (1, 1), + (2, 0), + (3, 0), + (2, 1), + (3, 1), + (0, 2), + (1, 2), + (0, 3), + (1, 3), + (2, 2), + (3, 2), + (2, 3), + (3, 3), +]; + +#[cfg(test)] +mod tests { + use super::*; + + /// Every VLC class must be prefix-free: no code may be a prefix of + /// another. A transcription slip in Table 9-5 would show up here first. + fn assert_prefix_free(name: &str, codes: &[(u8, u16)]) { + for (i, &(la, ca)) in codes.iter().enumerate() { + for &(lb, cb) in codes.iter().skip(i + 1) { + let (ls, cs, ll, cl) = if la <= lb { + (la, ca, lb, cb) + } else { + (lb, cb, la, ca) + }; + assert!( + cl >> (ll - ls) != cs, + "{name}: code {cs:0ls$b} is a prefix of {cl:0ll$b}", + ls = ls as usize, + ll = ll as usize, + ); + } + } + } + + /// Kraft sum of a prefix code: must never exceed 1; the spec's tables + /// leave only long all-zero prefixes unused, so it also stays close to 1. + fn assert_kraft(name: &str, codes: &[(u8, u16)]) { + let sum: f64 = codes.iter().map(|&(l, _)| (0.5f64).powi(l as i32)).sum(); + assert!(sum <= 1.0 + 1e-12, "{name}: Kraft sum {sum} > 1"); + assert!(sum > 0.99, "{name}: Kraft sum {sum} implausibly low"); + } + + #[test] + fn coeff_token_tables_prefix_free_and_complete() { + for (name, table) in [ + ("nc0", COEFF_TOKEN_NC0), + ("nc2", COEFF_TOKEN_NC2), + ("nc4", COEFF_TOKEN_NC4), + ("chroma-dc", COEFF_TOKEN_CHROMA_DC), + ] { + let codes: Vec<(u8, u16)> = table.iter().map(|&(l, c, _, _)| (l, c)).collect(); + assert_prefix_free(name, &codes); + assert_eq!(table.len(), if name == "chroma-dc" { 14 } else { 62 }); + // All (tc, t1) pairs distinct. + let mut pairs: Vec<(u8, u8)> = table.iter().map(|&(_, _, tc, t1)| (tc, t1)).collect(); + pairs.sort_unstable(); + pairs.dedup(); + assert_eq!(pairs.len(), table.len(), "{name}: duplicate (tc, t1)"); + assert_kraft(name, &codes); + } + } + + #[test] + fn total_zeros_and_run_before_prefix_free_and_complete() { + for (i, table) in TOTAL_ZEROS_4X4.iter().enumerate() { + let codes: Vec<(u8, u16)> = table.iter().map(|&(l, c, _)| (l, c)).collect(); + assert_prefix_free("total_zeros", &codes); + // tzVlcIndex = i+1 admits total_zeros 0..=16-(i+1). + assert_eq!(table.len(), 16 - i, "tzVlcIndex {}", i + 1); + let mut vals: Vec = table.iter().map(|&(_, _, v)| v).collect(); + vals.sort_unstable(); + assert_eq!(vals, (0..=(15 - i) as u8).collect::>()); + assert_kraft("total_zeros", &codes); + } + for table in &TOTAL_ZEROS_CHROMA_DC { + let codes: Vec<(u8, u16)> = table.iter().map(|&(l, c, _)| (l, c)).collect(); + assert_prefix_free("total_zeros_chroma", &codes); + assert_kraft("total_zeros_chroma", &codes); + } + for (zl, table) in RUN_BEFORE.iter().enumerate() { + let codes: Vec<(u8, u16)> = table.iter().map(|&(l, c, _)| (l, c)).collect(); + assert_prefix_free("run_before", &codes); + if zl < 6 { + assert_eq!(table.len(), zl + 2); + } + assert_kraft("run_before", &codes); + } + } + + #[test] + fn cbp_tables_are_permutations() { + let mut v = CBP_INTRA_420.to_vec(); + v.sort_unstable(); + assert_eq!(v, (0..48).collect::>()); + let mut v = CBP_INTRA_MONO.to_vec(); + v.sort_unstable(); + assert_eq!(v, (0..16).collect::>()); + } + + #[test] + fn zigzag_is_permutation_and_deblock_tables_sized() { + let mut v = ZIGZAG_4X4.to_vec(); + v.sort_unstable(); + assert_eq!(v, (0..16).collect::>()); + assert_eq!(CHROMA_QP[29], 29); + assert_eq!(CHROMA_QP[30], 29); + assert_eq!(CHROMA_QP[51], 39); + assert_eq!(ALPHA[16], 4); + assert_eq!(BETA[51], 18); + assert_eq!(TC0[2][51], 25); + } +} diff --git a/crates/ec-h264/src/transform.rs b/crates/ec-h264/src/transform.rs new file mode 100644 index 00000000..f595697b --- /dev/null +++ b/crates/ec-h264/src/transform.rs @@ -0,0 +1,226 @@ +//! Inverse transforms and scaling (spec 8.5.9 - 8.5.12). + +use crate::tables::{NORM_ADJUST_4X4, NORM_ADJUST_CLASS_4X4, ZIGZAG_4X4}; + +/// Per-QP scaling factors for one 4x4 weight list: `LevelScale4x4(m, i, j) = +/// weightScale(i, j) * normAdjust4x4(m, i, j)` (Equation 8-313), in raster +/// order, for m = qP % 6. +/// +/// Built once per parameter-set activation; the decode loop indexes it flat. +#[derive(Debug, Clone)] +pub struct LevelScale4x4 { + /// `[m][raster]`. + pub scale: [[i32; 16]; 6], +} + +impl LevelScale4x4 { + /// Build from a raster-order weight list (flat 16s when no scaling matrix). + pub fn new(weight: &[u8; 16]) -> LevelScale4x4 { + let mut scale = [[0i32; 16]; 6]; + for (m, row) in scale.iter_mut().enumerate() { + for (idx, s) in row.iter_mut().enumerate() { + let class = NORM_ADJUST_CLASS_4X4[idx] as usize; + *s = i32::from(weight[idx]) * i32::from(NORM_ADJUST_4X4[m][class]); + } + } + LevelScale4x4 { scale } + } +} + +/// Scale AC/luma-4x4 coefficients in place (spec 8.5.12.1): `block` is in +/// raster order. `skip_dc` is true for Intra_16x16 luma AC and chroma AC +/// blocks whose DC came through the separate DC path (d00 = c00 untouched). +#[inline] +pub fn dequant_4x4(block: &mut [i32; 16], ls: &LevelScale4x4, qp: i32, skip_dc: bool) { + let m = (qp % 6) as usize; + let shift = qp / 6; + let scale = &ls.scale[m]; + let start = usize::from(skip_dc); + if shift >= 4 { + let sh = (shift - 4) as u32; + for i in start..16 { + block[i] = (block[i] * scale[i]) << sh; + } + } else { + let sh = (4 - shift) as u32; + let round = 1i32 << (3 - shift); + for i in start..16 { + block[i] = (block[i] * scale[i] + round) >> sh; + } + } +} + +/// Place scan-order coefficients into raster order using the 4x4 zig-zag. +#[inline] +pub fn unzigzag(scan: &[i32; 16], out: &mut [i32; 16]) { + for (s, &raster) in ZIGZAG_4X4.iter().enumerate() { + out[raster as usize] = scan[s]; + } +} + +/// Un-zigzag a 15-coefficient AC block (Intra_16x16 luma AC / chroma AC): +/// scan position `k` maps to zig-zag position `k + 1`; the DC slot is +/// cleared for the caller to fill from the separate DC path. +#[inline] +pub fn unzigzag_ac15(scan: &[i32; 16], out: &mut [i32; 16]) { + out[0] = 0; + for k in 0..15 { + out[ZIGZAG_4X4[k + 1] as usize] = scan[k]; + } +} + +/// Inverse 4x4 core transform (spec 8.5.12.2): raster-order input `d`, +/// output residuals `r` including the final `(x + 32) >> 6`. +#[inline] +pub fn inverse_transform_4x4(d: &[i32; 16], r: &mut [i32; 16]) { + // Horizontal (each row). + let mut e = [0i32; 16]; + for i in 0..4 { + let o = i * 4; + let (d0, d1, d2, d3) = (d[o], d[o + 1], d[o + 2], d[o + 3]); + let e0 = d0 + d2; + let e1 = d0 - d2; + let e2 = (d1 >> 1) - d3; + let e3 = d1 + (d3 >> 1); + e[o] = e0 + e3; + e[o + 1] = e1 + e2; + e[o + 2] = e1 - e2; + e[o + 3] = e0 - e3; + } + // Vertical (each column) + rounding. + for j in 0..4 { + let (g0, g1, g2, g3) = (e[j], e[4 + j], e[8 + j], e[12 + j]); + let h0 = g0 + g2; + let h1 = g0 - g2; + let h2 = (g1 >> 1) - g3; + let h3 = g1 + (g3 >> 1); + r[j] = (h0 + h3 + 32) >> 6; + r[4 + j] = (h1 + h2 + 32) >> 6; + r[8 + j] = (h1 - h2 + 32) >> 6; + r[12 + j] = (h0 - h3 + 32) >> 6; + } +} + +/// Intra_16x16 luma DC: 4x4 Hadamard + scaling (spec 8.5.10). `c` is the DC +/// coefficient array in raster order (dc of block (bx, by) at `by * 4 + bx`); +/// output overwrites it. +pub fn luma_dc_transform(c: &mut [i32; 16], ls: &LevelScale4x4, qp: i32) { + // Hadamard rows then columns (Equation 8-320). + let mut f = [0i32; 16]; + for i in 0..4 { + let o = i * 4; + let (a, b, cc, d) = (c[o], c[o + 1], c[o + 2], c[o + 3]); + f[o] = a + b + cc + d; + f[o + 1] = a + b - cc - d; + f[o + 2] = a - b - cc + d; + f[o + 3] = a - b + cc - d; + } + let mut g = [0i32; 16]; + for j in 0..4 { + let (a, b, cc, d) = (f[j], f[4 + j], f[8 + j], f[12 + j]); + g[j] = a + b + cc + d; + g[4 + j] = a + b - cc - d; + g[8 + j] = a - b - cc + d; + g[12 + j] = a - b + cc - d; + } + let scale = ls.scale[(qp % 6) as usize][0]; + if qp >= 36 { + let sh = (qp / 6 - 6) as u32; + for (o, &v) in c.iter_mut().zip(&g) { + *o = (v * scale) << sh; + } + } else { + let sh = (6 - qp / 6) as u32; + let round = 1i32 << (5 - qp / 6); + for (o, &v) in c.iter_mut().zip(&g) { + *o = (v * scale + round) >> sh; + } + } +} + +/// Chroma DC for 4:2:0: 2x2 Hadamard + scaling (spec 8.5.11). `c` holds the +/// four DC levels in raster order of the chroma 4x4 blocks; overwritten with +/// the scaled DC values. +pub fn chroma_dc_transform_420(c: &mut [i32; 4], ls: &LevelScale4x4, qp: i32) { + let (c00, c01, c10, c11) = (c[0], c[1], c[2], c[3]); + let f = [ + c00 + c01 + c10 + c11, + c00 - c01 + c10 - c11, + c00 + c01 - c10 - c11, + c00 - c01 - c10 + c11, + ]; + let scale = ls.scale[(qp % 6) as usize][0]; + let sh = (qp / 6) as u32; + for (o, &v) in c.iter_mut().zip(&f) { + *o = ((v * scale) << sh) >> 5; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn flat_ls() -> LevelScale4x4 { + LevelScale4x4::new(&[16; 16]) + } + + /// A pure DC level reconstructs to a flat block whose value follows the + /// dequant ladder: doubling every 6 QP steps. + #[test] + fn dc_only_block_flat_and_qp_ladder() { + let ls = flat_ls(); + let recon = |qp: i32, level: i32| -> i32 { + let mut block = [0i32; 16]; + block[0] = level; + dequant_4x4(&mut block, &ls, qp, false); + let mut r = [0i32; 16]; + inverse_transform_4x4(&block.clone(), &mut r); + assert!(r.iter().all(|&x| x == r[0]), "DC block must be flat"); + r[0] + }; + // LevelScale(m = 0, 0, 0) = 16 * 10 = 160. qp 24: d00 = 160 << 0. + // A DC-only block comes out flat at (d00 + 32) >> 6. + assert_eq!(recon(24, 1), (160 + 32) >> 6); + assert_eq!(recon(30, 1), (320 + 32) >> 6); + assert_eq!(recon(36, 1), (640 + 32) >> 6); + assert_eq!(recon(24, -3), (-480 + 32) >> 6); // floor shift: -7 + } + + /// The inverse transform of zeros is zero, and rounding is symmetric + /// enough that a lone +1/-1 AC level stays bounded. + #[test] + fn zero_in_zero_out_and_unzigzag() { + let mut r = [7i32; 16]; + inverse_transform_4x4(&[0; 16], &mut r); + assert_eq!(r, [0; 16]); + + let mut scan = [0i32; 16]; + scan[1] = 5; // second scan position = raster (0,1) + let mut raster = [0i32; 16]; + unzigzag(&scan, &mut raster); + assert_eq!(raster[1], 5); + assert_eq!(raster.iter().filter(|&&x| x != 0).count(), 1); + } + + /// Luma DC Hadamard of a single coefficient spreads evenly; scaling per + /// 8.5.10 with qp < 36 uses the rounding shift. + #[test] + fn luma_dc_spread() { + let ls = flat_ls(); + let mut c = [0i32; 16]; + c[0] = 8; + luma_dc_transform(&mut c, &ls, 28); + // f = 8 everywhere; scale = LevelScale(28 % 6 = 4, 0, 0) = 16 * 16. + let expected = (8 * 16 * 16 + (1 << (5 - 28 / 6))) >> (6 - 28 / 6); + assert!(c.iter().all(|&x| x == expected)); + } + + #[test] + fn chroma_dc_hadamard() { + let ls = flat_ls(); + let mut c = [4, 0, 0, 0]; + chroma_dc_transform_420(&mut c, &ls, 30); + // f = [4,4,4,4]; scale = LS(0,0,0) = 160; ((4 * 160) << 5) >> 5 = 640. + assert!(c.iter().all(|&x| x == 640), "{c:?}"); + } +} diff --git a/crates/ec-h264/tests/conformance.rs b/crates/ec-h264/tests/conformance.rs new file mode 100644 index 00000000..686613ea --- /dev/null +++ b/crates/ec-h264/tests/conformance.rs @@ -0,0 +1,415 @@ +//! JVT conformance: first IDR picture, bit-exact. +//! +//! Fixture-gated like tools/oracle: fixtures/ is gitignored, so a checkout +//! without `scripts/fetch-vectors.sh` skips loudly instead of failing. +//! +//! Oracles, in order of authority: +//! 1. The reference decoder YUV that ships with each JVT vector (first +//! frame) — ffmpeg-independent. +//! 2. `ffmpeg -i -frames:v 1` raw output, cross-checked when the +//! binary is present. +//! +//! The same binary hosts the zero-allocation proof and the ns/MB +//! measurement so the crate keeps a single integration-test link unit. + +use std::alloc::{GlobalAlloc, Layout, System}; +use std::cell::Cell; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::sync::atomic::{AtomicU64, Ordering}; + +use ec_h264::{Decoder, Error}; + +// --------------------------------------------------------------------------- +// Counting allocator: proves the steady-state decode loop allocates nothing. +// Lives in the test binary only — the shipped crates have no allocator games. +// --------------------------------------------------------------------------- + +struct CountingAlloc; + +static ALLOCS: AtomicU64 = AtomicU64::new(0); + +std::thread_local! { + /// Only the test thread that armed the counter is counted — other test + /// threads (and their ffmpeg child plumbing) allocate freely. + static COUNTING_HERE: Cell = const { Cell::new(false) }; +} + +fn counting_here() -> bool { + COUNTING_HERE.try_with(Cell::get).unwrap_or(false) +} + +unsafe impl GlobalAlloc for CountingAlloc { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + if counting_here() { + ALLOCS.fetch_add(1, Ordering::Relaxed); + } + unsafe { System.alloc(layout) } + } + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + unsafe { System.dealloc(ptr, layout) } + } + unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { + if counting_here() { + ALLOCS.fetch_add(1, Ordering::Relaxed); + } + unsafe { System.realloc(ptr, layout, new_size) } + } +} + +#[global_allocator] +static A: CountingAlloc = CountingAlloc; + +// --------------------------------------------------------------------------- + +fn vectors_dir() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/vectors/h264-jvt") +} + +/// The CAVLC, progressive, single-slice-group streams whose first IDR this +/// decoder must reproduce bit-exactly. +const CAVLC_STREAMS: &[&str] = &[ + "AUD_MW_E", + "BA1_Sony_D", + "BA3_SVA_C", + "BA_MW_D", + "BANM_MW_D", + "BASQP1_Sony_C", + "CI_MW_D", + "MIDR_MW_D", + "NL1_Sony_D", + "NL3_SVA_E", + "NRF_MW_E", + "SVA_BA2_D", + "SVA_CL1_E", + "SVA_NL2_E", + "CVPCMNL2_SVA_C", + // First PPS/picture of these carries no FMO; the first IDR is plain + // CAVLC baseline and must be bit-exact like the rest. + "SVA_FM1_E", + "SL1_SVA_B", + "MR1_BT_A", +]; + +/// Streams that must fail with a named Unsupported error (wrong output is +/// forbidden; refusal strings are claims backed by these tests). +const UNSUPPORTED_STREAMS: &[(&str, &str)] = &[ + ("CABA1_SVA_B", "CABAC"), // entropy_coding_mode_flag = 1 + ("MR9_BT_B", "CABAC"), // Main profile, CABAC + ("CAMACI3_Sony_C", "CABAC"), // CABAC + interlace tools + ("FM2_SVA_C", "FMO"), // num_slice_groups > 1 + ("CVFI1_SVA_C", "interlaced"), // field pictures + ("FI1_Sony_E", "interlaced"), // field pictures +]; + +fn find_stream(dir: &Path) -> Option { + let mut fallback = None; + for entry in std::fs::read_dir(dir).ok()? { + let p = entry.ok()?.path(); + let ext = p.extension()?.to_str()?.to_ascii_lowercase(); + if matches!(ext.as_str(), "jsv" | "264" | "avc" | "26l" | "h264" | "jvt") { + return Some(p); + } + if ext == "bit" { + fallback = Some(p); + } + } + fallback +} + +fn find_ref_yuv(dir: &Path) -> Option { + for entry in std::fs::read_dir(dir).ok()? { + let p = entry.ok()?.path(); + let ext = p.extension()?.to_str()?.to_ascii_lowercase(); + if ext == "yuv" || ext == "qcif" { + return Some(p); + } + } + None +} + +fn ffmpeg_first_frame(stream: &Path) -> Option> { + let out = Command::new("ffmpeg") + .args(["-v", "error", "-i"]) + .arg(stream) + .args([ + "-frames:v", + "1", + "-f", + "rawvideo", + "-pix_fmt", + "yuv420p", + "-", + ]) + .output() + .ok()?; + if !out.status.success() || out.stdout.is_empty() { + return None; + } + Some(out.stdout) +} + +/// Decode the first IDR and return (frame bytes as I420, width, height). +fn decode_first(stream_bytes: &[u8]) -> Result<(Vec, usize, usize), Error> { + let mut dec = Decoder::new(); + let frame = dec.decode_first_idr(stream_bytes)?; + 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")); + } + } + Ok((out, w, h)) +} + +fn first_diff(a: &[u8], b: &[u8]) -> Option { + a.iter().zip(b).position(|(x, y)| x != y) +} + +#[test] +fn jvt_cavlc_first_idr_bit_exact() { + let base = vectors_dir(); + if !base.is_dir() { + eprintln!( + "SKIP: {} missing — run scripts/fetch-vectors.sh", + base.display() + ); + return; + } + let mut passed = Vec::new(); + let mut failed = Vec::new(); + for name in CAVLC_STREAMS { + let dir = base.join(name); + let Some(stream) = find_stream(&dir) else { + eprintln!("SKIP {name}: no bitstream file"); + continue; + }; + let bytes = std::fs::read(&stream).unwrap(); + match decode_first(&bytes) { + Ok((ours, w, h)) => { + let frame_len = w * h * 3 / 2; + // Oracle 1: reference decoder YUV, first frame. + let mut ok = true; + if let Some(ref_path) = find_ref_yuv(&dir) { + let reference = std::fs::read(&ref_path).unwrap(); + assert!( + reference.len() >= frame_len, + "{name}: reference YUV shorter than one frame" + ); + if let Some(pos) = first_diff(&ours, &reference[..frame_len]) { + eprintln!( + "FAIL {name}: differs from reference YUV at byte {pos} \ + (plane offset, {w}x{h}): ours {} ref {}", + ours[pos], reference[pos] + ); + ok = false; + } + } else { + eprintln!("WARN {name}: no reference YUV, ffmpeg only"); + } + // Oracle 2: ffmpeg. + if let Some(ff) = ffmpeg_first_frame(&stream) { + assert!(ff.len() >= frame_len, "{name}: ffmpeg output short"); + if let Some(pos) = first_diff(&ours, &ff[..frame_len]) { + eprintln!( + "FAIL {name}: differs from ffmpeg at byte {pos}: ours {} ff {}", + ours[pos], ff[pos] + ); + ok = false; + } + } + if ok { + passed.push(*name); + } else { + failed.push(*name); + } + } + Err(e) => { + eprintln!("FAIL {name}: decode error: {e}"); + failed.push(*name); + } + } + } + eprintln!( + "PASS table ({} streams bit-exact): {passed:?}", + passed.len() + ); + assert!(failed.is_empty(), "streams not bit-exact: {failed:?}"); + assert!( + passed.len() >= 5, + "fewer than 5 CAVLC conformance streams verified: {passed:?}" + ); +} + +#[test] +fn unsupported_streams_refuse_with_named_errors() { + let base = vectors_dir(); + if !base.is_dir() { + eprintln!("SKIP: fixtures missing"); + return; + } + for (name, what) in UNSUPPORTED_STREAMS { + let dir = base.join(name); + let Some(stream) = find_stream(&dir) else { + eprintln!("SKIP {name}: no bitstream file"); + continue; + }; + let bytes = std::fs::read(&stream).unwrap(); + match decode_first(&bytes) { + Err(Error::Unsupported { what: w, .. }) => { + let w_lower = w.to_lowercase(); + let expect = what.to_lowercase(); + assert!( + w_lower.contains(&expect) + || (expect == "interlaced" && w_lower.contains("interlace")), + "{name}: expected Unsupported({what}), got Unsupported({w})" + ); + } + Ok(_) => panic!("{name}: expected a named Unsupported error, decode succeeded"), + Err(e) => panic!("{name}: expected Unsupported({what}), got: {e}"), + } + } +} + +/// Steady-state decode loop performs zero heap allocations: after one warm-up +/// picture, re-decoding the same slices into the reused picture context +/// (including deblocking) must not allocate. Frame emission (`frame()`) +/// allocates the output planes and is measured separately as nonzero to prove +/// the counter works. +#[test] +fn steady_state_decode_loop_zero_alloc() { + let base = vectors_dir(); + if !base.is_dir() { + eprintln!("SKIP: fixtures missing"); + return; + } + let stream = find_stream(&base.join("BA1_Sony_D")).expect("BA1_Sony_D fixture"); + let bytes = std::fs::read(stream).unwrap(); + let mut dec = Decoder::new(); + // Warm-up: full first picture, growing every reusable buffer. + let _ = dec.decode_first_idr(&bytes).expect("warm-up decode"); + + // Steady state: same IDR slices again, counted. + let nals: Vec<&[u8]> = ec_h264_syntax::AnnexBIter::new(&bytes).collect(); + ALLOCS.store(0, Ordering::SeqCst); + COUNTING_HERE.with(|c| c.set(true)); + let mut decoded = false; + for nal in &nals { + match dec.push_nal(nal) { + Ok(ec_h264::NalOutcome::PictureBoundary) => break, + Ok(ec_h264::NalOutcome::SliceDecoded) => decoded = true, + Ok(_) => {} + Err(e) => panic!("steady-state push failed: {e}"), + } + } + dec.end_picture().expect("end_picture"); + COUNTING_HERE.with(|c| c.set(false)); + assert!(decoded, "no slice decoded in steady-state pass"); + let n = ALLOCS.load(Ordering::SeqCst); + assert_eq!(n, 0, "steady-state decode loop allocated {n} times"); + + // Sanity: the counter is alive — frame emission does allocate. + ALLOCS.store(0, Ordering::SeqCst); + COUNTING_HERE.with(|c| c.set(true)); + let frame = dec.frame().expect("frame"); + COUNTING_HERE.with(|c| c.set(false)); + assert!(frame.width > 0); + assert!( + ALLOCS.load(Ordering::SeqCst) > 0, + "allocation counter appears dead" + ); +} + +/// Decode-rate measurement: ns per macroblock and Mpx/s over the first IDR, +/// printed for the perf report. Run with `--nocapture` to see it. Uses the +/// steady-state path (buffers warm) like a playback loop would. +#[test] +fn ns_per_macroblock_measurement() { + let base = vectors_dir(); + if !base.is_dir() { + eprintln!("SKIP: fixtures missing"); + return; + } + for name in ["BA1_Sony_D", "CI_MW_D", "NL1_Sony_D"] { + let Some(stream) = find_stream(&base.join(name)) else { + continue; + }; + let bytes = std::fs::read(stream).unwrap(); + let mut dec = Decoder::new(); + let frame = dec.decode_first_idr(&bytes).expect("warm-up"); + let (w, h) = (frame.width as u64, frame.height as u64); + let mbs = (w.div_ceil(16)) * (h.div_ceil(16)); + let nals: Vec<&[u8]> = ec_h264_syntax::AnnexBIter::new(&bytes).collect(); + + let iters = 200u32; + let start = std::time::Instant::now(); + for _ in 0..iters { + for nal in &nals { + match dec.push_nal(nal) { + Ok(ec_h264::NalOutcome::PictureBoundary) => break, + Ok(_) => {} + Err(e) => panic!("{e}"), + } + } + dec.end_picture().expect("end_picture"); + } + let elapsed = start.elapsed(); + let ns_per_mb = elapsed.as_nanos() as f64 / f64::from(iters) / mbs as f64; + let mpx_s = (w * h) as f64 * f64::from(iters) / elapsed.as_secs_f64() / 1e6; + eprintln!( + "PERF {name}: {w}x{h}, {mbs} MBs, {ns_per_mb:.0} ns/MB, {mpx_s:.1} Mpx/s \ + (intra IDR, single thread, deblock included, output copy excluded)" + ); + } +} + +/// Corrupt-input smoke sweep (fuzz-lite, deterministic): single-byte +/// mutations and truncations of a real stream must produce `Err` or a frame, +/// never a panic. A cargo-fuzz target owns the deep search later (S18 lane +/// done-criterion); this keeps the invariant enforced in every test run. +#[test] +fn corrupt_streams_never_panic() { + let base = vectors_dir(); + if !base.is_dir() { + eprintln!("SKIP: fixtures missing"); + return; + } + let stream = find_stream(&base.join("BA1_Sony_D")).expect("BA1_Sony_D fixture"); + let bytes = std::fs::read(stream).unwrap(); + + // Truncations at prefix lengths spanning SPS/PPS/slice-header/slice-data. + for len in (0..bytes.len().min(4096)) + .step_by(37) + .chain([bytes.len() / 2]) + { + let mut dec = Decoder::new(); + let _ = dec.decode_first_idr(&bytes[..len]); + } + // Single-byte corruptions: xor a walking pattern through the first 6KB + // (covers parameter sets and the first slices), plus scattered hits. + let mut xorshift = 0x243F_6A88u32; // deterministic PRNG, no rand dep + // Debug builds carry overflow checks but decode ~10x slower; a smaller + // sweep keeps the suite fast while release runs the full one. + let count = if cfg!(debug_assertions) { 400 } else { 2000 }; + let dense = count * 3 / 4; + for i in 0..count { + let mut m = bytes.clone(); + let pos = if i < dense { + i * 4 % m.len().min(6144) + } else { + xorshift ^= xorshift << 13; + xorshift ^= xorshift >> 17; + xorshift ^= xorshift << 5; + (xorshift as usize) % m.len() + }; + m[pos] ^= (0x5Bu8.wrapping_add(i as u8)).max(1); + let mut dec = Decoder::new(); + let _ = dec.decode_first_idr(&m); // must not panic; any Err is fine + } +}