forge
Explore
Log in

Don't you dare go Hollow

CAVLC intra decoder, bit-exact on 18 JVT streams

Browse files at this commit

f985e44d89c393efed15d6b1ebd95762833c1749Ahmet Kaan GümüşParent: f07dac7
  • feat
    • CAVLC intra decoder, bit-exact on 18 JVT streams
Show full message
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.lockmodified+4 -9
@@ -13,26 +13,21 @@ name = "ec-core"
13 version = "0.1.0"13 version = "0.1.0"
14 14
15 [[package]]15 [[package]]
16-name = "ec-dsp"16+name = "ec-h264"
17 version = "0.1.0"17 version = "0.1.0"
18 dependencies = [18 dependencies = [
19+ "ec-core",
20+ "ec-h264-syntax",
19 "wide",21 "wide",
20 ]22 ]
21 23
22 [[package]]24 [[package]]
23-name = "ec-riff"25+name = "ec-h264-syntax"
24 version = "0.1.0"26 version = "0.1.0"
25 dependencies = [27 dependencies = [
26 "ec-core",28 "ec-core",
27 ]29 ]
28 30
29-[[package]]
30-name = "hound"
31-version = "3.5.1"
32-dependencies = [
33- "ec-riff",
34-]
35-
36 [[package]]31 [[package]]
37 name = "oracle"32 name = "oracle"
38 version = "0.1.0"33 version = "0.1.0"
crates/ec-h264/Cargo.tomladded+16 -0
@@ -0,0 +1,16 @@
1+[package]
2+name = "ec-h264"
3+description = "H.264 software decoder (CAVLC intra loop, growing toward full)"
4+version.workspace = true
5+edition.workspace = true
6+license.workspace = true
7+authors.workspace = true
8+
9+[dependencies]
10+ec-core = { workspace = true }
11+ec-h264-syntax = { path = "../ec-h264-syntax", version = "0.1.0" }
12+wide = { workspace = true }
13+
14+[dev-dependencies]
15+# The conformance harness walks Annex B itself to drive push_nal.
16+ec-h264-syntax = { path = "../ec-h264-syntax", version = "0.1.0" }
crates/ec-h264/src/bits.rsadded+286 -0
@@ -0,0 +1,286 @@
1+//! Slice-data bit cursor: a 64-bit-cached reader for the CAVLC hot loop.
2+//!
3+//! `ec_core::BitReader` is the family-wide, allocation-free contract type and
4+//! stays the parser for headers. Slice data is different: it is read one to
5+//! three bits at a time, millions of times per picture, so this cursor keeps
6+//! the next 32..64 bits left-aligned in a register and refills by whole
7+//! words. Truncation still surfaces as [`Error::NeedMore`]; the exp-Golomb
8+//! prefix cap still turns runaway zeros into [`Error::Corrupt`].
9+
10+use ec_core::error::{Error, Result};
11+
12+/// Register-cached MSB-first bit reader over a byte slice.
13+pub struct BitCursor<'a> {
14+ data: &'a [u8],
15+ /// Upcoming bits, left-aligned.
16+ cache: u64,
17+ /// Valid bit count in `cache`.
18+ cached: u32,
19+ /// Next byte of `data` to load into the cache.
20+ next_byte: usize,
21+ /// Index of the bit just past the `rbsp_stop_one_bit`, for
22+ /// `more_rbsp_data()`; `data.len() * 8` when no stop bit exists.
23+ stop_bit: u64,
24+}
25+
26+impl<'a> BitCursor<'a> {
27+ /// A cursor over `data`, positioned `bit_pos` bits in.
28+ pub fn new(data: &'a [u8], bit_pos: u64) -> BitCursor<'a> {
29+ let stop_bit = match data.iter().rposition(|&b| b != 0) {
30+ Some(i) => i as u64 * 8 + (7 - data[i].trailing_zeros() as u64),
31+ None => data.len() as u64 * 8,
32+ };
33+ let mut c = BitCursor {
34+ data,
35+ cache: 0,
36+ cached: 0,
37+ next_byte: (bit_pos / 8) as usize,
38+ stop_bit,
39+ };
40+ c.refill();
41+ let sub = (bit_pos % 8) as u32;
42+ c.cache <<= sub;
43+ c.cached = c.cached.saturating_sub(sub);
44+ c
45+ }
46+
47+ /// Bits consumed so far.
48+ #[inline]
49+ pub fn bit_position(&self) -> u64 {
50+ self.next_byte as u64 * 8 - u64::from(self.cached)
51+ }
52+
53+ /// True while syntax elements remain before the RBSP stop bit
54+ /// (spec 7.2 `more_rbsp_data()`).
55+ #[inline]
56+ pub fn more_rbsp_data(&self) -> bool {
57+ self.bit_position() < self.stop_bit
58+ }
59+
60+ #[inline]
61+ fn refill(&mut self) {
62+ while self.cached <= 56 {
63+ let Some(&b) = self.data.get(self.next_byte) else {
64+ break;
65+ };
66+ self.cache |= u64::from(b) << (56 - self.cached);
67+ self.cached += 8;
68+ self.next_byte += 1;
69+ }
70+ }
71+
72+ /// Bits left in the stream.
73+ #[inline]
74+ pub fn bits_remaining(&self) -> u64 {
75+ (self.data.len() - self.next_byte) as u64 * 8 + u64::from(self.cached)
76+ }
77+
78+ /// The next 16 bits left-aligned in a u32, zero-padded past the end.
79+ #[inline]
80+ pub fn peek16(&mut self) -> u32 {
81+ if self.cached < 16 {
82+ self.refill();
83+ }
84+ (self.cache >> 48) as u32 & 0xFFFF
85+ }
86+
87+ /// Consume `n` bits (`n <= 16` after a `peek16`; general `n <= 32`).
88+ #[inline]
89+ pub fn skip(&mut self, n: u32) -> Result<()> {
90+ if self.cached < n {
91+ self.refill();
92+ if self.cached < n {
93+ return Err(Error::NeedMore);
94+ }
95+ }
96+ self.cache <<= n;
97+ self.cached -= n;
98+ Ok(())
99+ }
100+
101+ /// Read one bit.
102+ #[inline]
103+ pub fn read_bit(&mut self) -> Result<bool> {
104+ if self.cached == 0 {
105+ self.refill();
106+ if self.cached == 0 {
107+ return Err(Error::NeedMore);
108+ }
109+ }
110+ let bit = self.cache >> 63 != 0;
111+ self.cache <<= 1;
112+ self.cached -= 1;
113+ Ok(bit)
114+ }
115+
116+ /// Read `n` bits (`n <= 32`) MSB-first.
117+ #[inline]
118+ pub fn read_bits(&mut self, n: u32) -> Result<u32> {
119+ debug_assert!(n <= 32);
120+ if n == 0 {
121+ return Ok(0);
122+ }
123+ if self.cached < n {
124+ self.refill();
125+ if self.cached < n {
126+ return Err(Error::NeedMore);
127+ }
128+ }
129+ let v = (self.cache >> (64 - n)) as u32;
130+ self.cache <<= n;
131+ self.cached -= n;
132+ Ok(v)
133+ }
134+
135+ /// Count leading zero bits up to and including the terminating one bit
136+ /// (level_prefix / exp-Golomb prefix). Capped at `cap` zeros.
137+ #[inline]
138+ pub fn read_prefix_zeros(&mut self, cap: u32) -> Result<u32> {
139+ let mut zeros = 0u32;
140+ loop {
141+ if self.cached == 0 {
142+ self.refill();
143+ if self.cached == 0 {
144+ return Err(Error::NeedMore);
145+ }
146+ }
147+ let lz = (self.cache.leading_zeros()).min(self.cached);
148+ if lz < self.cached {
149+ // Found the 1 bit within the cache.
150+ zeros += lz;
151+ if zeros > cap {
152+ return Err(Error::corrupt("prefix run of zeros too long"));
153+ }
154+ self.cache <<= lz + 1;
155+ self.cached -= lz + 1;
156+ return Ok(zeros);
157+ }
158+ zeros += lz;
159+ if zeros > cap {
160+ return Err(Error::corrupt("prefix run of zeros too long"));
161+ }
162+ self.cache = 0;
163+ self.cached = 0;
164+ self.refill();
165+ if self.cached == 0 && self.bits_remaining() == 0 {
166+ return Err(Error::NeedMore);
167+ }
168+ }
169+ }
170+
171+ /// Unsigned exp-Golomb `ue(v)` (prefix capped at 31 zeros, as in
172+ /// `ec_core::BitReader::read_ue`).
173+ #[inline]
174+ pub fn read_ue(&mut self) -> Result<u32> {
175+ let zeros = self.read_prefix_zeros(31)?;
176+ if zeros == 0 {
177+ return Ok(0);
178+ }
179+ let suffix = self.read_bits(zeros)?;
180+ Ok((1u32 << zeros) - 1 + suffix)
181+ }
182+
183+ /// Signed exp-Golomb `se(v)`.
184+ #[inline]
185+ pub fn read_se(&mut self) -> Result<i32> {
186+ let k = self.read_ue()? as i64;
187+ let v = if k % 2 == 1 { (k + 1) / 2 } else { -(k / 2) };
188+ i32::try_from(v).map_err(|_| Error::corrupt("se(v) out of i32 range"))
189+ }
190+
191+ /// Skip to the next byte boundary (I_PCM alignment).
192+ #[inline]
193+ pub fn align_to_byte(&mut self) {
194+ let sub = (self.bit_position() % 8) as u32;
195+ if sub != 0 {
196+ let n = 8 - sub;
197+ self.cache <<= n;
198+ self.cached -= n.min(self.cached);
199+ }
200+ }
201+
202+ /// Borrow `n` whole bytes at the current (byte-aligned) position.
203+ pub fn read_bytes(&mut self, n: usize) -> Result<&'a [u8]> {
204+ if !self.bit_position().is_multiple_of(8) {
205+ return Err(Error::corrupt("read_bytes at a non-byte-aligned position"));
206+ }
207+ let start = (self.bit_position() / 8) as usize;
208+ let end = start.checked_add(n).ok_or(Error::NeedMore)?;
209+ let slice = self.data.get(start..end).ok_or(Error::NeedMore)?;
210+ // Drop the cache and reposition after the bytes.
211+ self.cache = 0;
212+ self.cached = 0;
213+ self.next_byte = end;
214+ self.refill();
215+ Ok(slice)
216+ }
217+}
218+
219+#[cfg(test)]
220+mod tests {
221+ use super::*;
222+ use ec_core::BitWriter;
223+
224+ #[test]
225+ fn agrees_with_core_bitreader() {
226+ let mut w = BitWriter::new();
227+ for v in [0u32, 1, 5, 127, 4096] {
228+ w.write_ue(v);
229+ }
230+ for v in [0i32, -3, 7, -128] {
231+ w.write_se(v);
232+ }
233+ w.write_bits(0b1011, 4);
234+ w.write_bit(true); // stop bit
235+ w.align_to_byte();
236+ let bytes = w.into_bytes();
237+ let mut c = BitCursor::new(&bytes, 0);
238+ for v in [0u32, 1, 5, 127, 4096] {
239+ assert_eq!(c.read_ue().unwrap(), v);
240+ }
241+ for v in [0i32, -3, 7, -128] {
242+ assert_eq!(c.read_se().unwrap(), v);
243+ }
244+ assert_eq!(c.read_bits(4).unwrap(), 0b1011);
245+ assert!(!c.more_rbsp_data());
246+ }
247+
248+ #[test]
249+ fn peek16_pads_and_skip_tracks_position() {
250+ let data = [0xAB, 0xCD];
251+ let mut c = BitCursor::new(&data, 4);
252+ assert_eq!(c.bit_position(), 4);
253+ assert_eq!(c.peek16(), 0xBCD0);
254+ c.skip(8).unwrap();
255+ assert_eq!(c.bit_position(), 12);
256+ assert_eq!(c.peek16(), 0xD000);
257+ assert_eq!(c.read_bits(4).unwrap(), 0xD);
258+ assert!(c.read_bit().is_err());
259+ }
260+
261+ #[test]
262+ fn pcm_bytes_and_alignment() {
263+ let data = [0b1000_0000, 0x11, 0x22, 0x33];
264+ let mut c = BitCursor::new(&data, 0);
265+ assert!(c.read_bit().unwrap());
266+ c.align_to_byte();
267+ assert_eq!(c.read_bytes(2).unwrap(), &[0x11, 0x22]);
268+ assert_eq!(c.read_bits(8).unwrap(), 0x33);
269+ assert!(c.read_bytes(1).is_err());
270+ }
271+
272+ #[test]
273+ fn long_zero_runs_are_corrupt_or_need_more() {
274+ // 33 zero bits then a 1: exp-Golomb prefix over the cap.
275+ let data = [0, 0, 0, 0, 0b0100_0000];
276+ let mut c = BitCursor::new(&data, 0);
277+ assert!(matches!(c.read_ue(), Err(Error::Corrupt { .. })));
278+ // All zeros: NeedMore (no stop bit at all).
279+ let zeros = [0u8; 4];
280+ let mut c = BitCursor::new(&zeros, 0);
281+ assert!(matches!(
282+ c.read_ue(),
283+ Err(Error::NeedMore | Error::Corrupt { .. })
284+ ));
285+ }
286+}
crates/ec-h264/src/cavlc.rsadded+278 -0
@@ -0,0 +1,278 @@
1+//! CAVLC residual decoding (spec 9.2).
2+
3+use ec_core::error::{Error, Result};
4+
5+use crate::bits::BitCursor;
6+use crate::tables::{
7+ COEFF_TOKEN_CHROMA_DC, COEFF_TOKEN_NC0, COEFF_TOKEN_NC2, COEFF_TOKEN_NC4, CoeffTokenEntry,
8+ RUN_BEFORE, TOTAL_ZEROS_4X4, TOTAL_ZEROS_CHROMA_DC, VlcEntry,
9+};
10+
11+/// Decode one code from a `(len, code, value)` VLC list. The cursor's peek is
12+/// zero-padded past the end of data, so a truncated stream either matches a
13+/// code longer than what remains (caught by `skip`) or matches nothing.
14+#[inline]
15+fn read_vlc(r: &mut BitCursor<'_>, table: &[VlcEntry]) -> Result<u8> {
16+ let peek = r.peek16();
17+ for &(len, code, value) in table {
18+ if peek >> (16 - len) == u32::from(code) {
19+ r.skip(u32::from(len))?;
20+ return Ok(value);
21+ }
22+ }
23+ if r.bits_remaining() < 16 {
24+ return Err(Error::NeedMore);
25+ }
26+ Err(Error::corrupt("no matching VLC code"))
27+}
28+
29+/// Decode `coeff_token` (spec 9.2.1) returning `(total_coeff, trailing_ones)`.
30+#[inline]
31+fn read_coeff_token(r: &mut BitCursor<'_>, nc: i32) -> Result<(u8, u8)> {
32+ if nc >= 8 {
33+ // 6-bit fixed-length code.
34+ let v = r.read_bits(6)?;
35+ return Ok(if v == 3 {
36+ (0, 0)
37+ } else {
38+ ((v / 4 + 1) as u8, (v % 4) as u8)
39+ });
40+ }
41+ let table: &[CoeffTokenEntry] = match nc {
42+ -1 => COEFF_TOKEN_CHROMA_DC,
43+ 0..=1 => COEFF_TOKEN_NC0,
44+ 2..=3 => COEFF_TOKEN_NC2,
45+ 4..=7 => COEFF_TOKEN_NC4,
46+ _ => return Err(Error::unsupported("CAVLC nC = -2", "4:2:2 chroma DC")),
47+ };
48+ let peek = r.peek16();
49+ for &(len, code, tc, t1) in table {
50+ if peek >> (16 - len) == u32::from(code) {
51+ r.skip(u32::from(len))?;
52+ return Ok((tc, t1));
53+ }
54+ }
55+ if r.bits_remaining() < 16 {
56+ return Err(Error::NeedMore);
57+ }
58+ Err(Error::corrupt("no matching coeff_token code"))
59+}
60+
61+/// `level_prefix` (spec 9.2.2.1): leading zeros before the first 1 bit.
62+/// Capped: baseline/main constrain it to <= 15, other profiles report
63+/// <= 11 + bit depth; beyond 25 zeros the stream is broken.
64+#[inline]
65+fn read_level_prefix(r: &mut BitCursor<'_>) -> Result<u32> {
66+ r.read_prefix_zeros(25)
67+}
68+
69+/// Decode one CAVLC residual block (spec 9.2) into `coeff[0..max_num_coeff]`
70+/// in scan order. Returns TotalCoeff. `nc` selects the coeff_token VLC:
71+/// the averaged neighbour count for luma/chroma-AC blocks, -1 for 4:2:0
72+/// chroma DC.
73+///
74+/// `coeff` is fully zeroed first; the caller hands the same stack array every
75+/// time — no allocation.
76+// The spec's level/run algorithms couple the loop index to state transitions
77+// (`i == trailing_ones`, positions counted down); ranges mirror clause 9.2.
78+#[allow(clippy::needless_range_loop)]
79+pub fn residual_block(
80+ r: &mut BitCursor<'_>,
81+ coeff: &mut [i32; 16],
82+ max_num_coeff: usize,
83+ nc: i32,
84+) -> Result<u8> {
85+ debug_assert!(max_num_coeff <= 16);
86+ *coeff = [0; 16];
87+ let (total_coeff, trailing_ones) = read_coeff_token(r, nc)?;
88+ let total_coeff = total_coeff as usize;
89+ let trailing_ones = trailing_ones as usize;
90+ if total_coeff == 0 {
91+ return Ok(0);
92+ }
93+ if total_coeff > max_num_coeff {
94+ return Err(Error::corrupt("TotalCoeff exceeds maxNumCoeff"));
95+ }
96+
97+ // 9.2.2: levels, highest frequency first.
98+ let mut level = [0i32; 16];
99+ for l in level.iter_mut().take(trailing_ones) {
100+ *l = if r.read_bit()? { -1 } else { 1 };
101+ }
102+ let mut suffix_length: u32 = u32::from(total_coeff > 10 && trailing_ones < 3);
103+ for i in trailing_ones..total_coeff {
104+ let level_prefix = read_level_prefix(r)?;
105+ let level_suffix_size = if level_prefix == 14 && suffix_length == 0 {
106+ 4
107+ } else if level_prefix >= 15 {
108+ level_prefix - 3
109+ } else {
110+ suffix_length
111+ };
112+ let mut level_code = (level_prefix.min(15) << suffix_length) as i64;
113+ if level_suffix_size > 0 {
114+ level_code += r.read_bits(level_suffix_size)? as i64;
115+ }
116+ if level_prefix >= 15 && suffix_length == 0 {
117+ level_code += 15;
118+ }
119+ if level_prefix >= 16 {
120+ level_code += (1i64 << (level_prefix - 3)) - 4096;
121+ }
122+ if i == trailing_ones && trailing_ones < 3 {
123+ level_code += 2;
124+ }
125+ let v = if level_code % 2 == 0 {
126+ (level_code + 2) >> 1
127+ } else {
128+ (-level_code - 1) >> 1
129+ };
130+ level[i] =
131+ i32::try_from(v).map_err(|_| Error::corrupt("coefficient level out of range"))?;
132+ if suffix_length == 0 {
133+ suffix_length = 1;
134+ }
135+ if level[i].unsigned_abs() > (3 << (suffix_length - 1)) && suffix_length < 6 {
136+ suffix_length += 1;
137+ }
138+ }
139+
140+ // 9.2.3: runs of zeros.
141+ let mut zeros_left: i32 = if total_coeff == max_num_coeff {
142+ 0
143+ } else {
144+ let tz = if nc == -1 {
145+ read_vlc(r, TOTAL_ZEROS_CHROMA_DC[total_coeff - 1])?
146+ } else {
147+ read_vlc(r, TOTAL_ZEROS_4X4[total_coeff - 1])?
148+ };
149+ tz as i32
150+ };
151+
152+ // 9.2.4 fused with 9.2.3: place levels from the highest scan position
153+ // downward, consuming run_before per coefficient.
154+ let mut coeff_num = zeros_left + total_coeff as i32 - 1;
155+ for i in 0..total_coeff {
156+ let run = if i == total_coeff - 1 {
157+ // Last (lowest-frequency) coefficient absorbs the rest.
158+ zeros_left
159+ } else if zeros_left > 0 {
160+ let idx = (zeros_left.min(7) - 1) as usize;
161+ read_vlc(r, RUN_BEFORE[idx])? as i32
162+ } else {
163+ 0
164+ };
165+ if run > zeros_left {
166+ return Err(Error::corrupt("run_before exceeds zerosLeft"));
167+ }
168+ let pos = coeff_num as usize;
169+ if pos >= max_num_coeff {
170+ return Err(Error::corrupt("coefficient position out of block"));
171+ }
172+ coeff[pos] = level[i];
173+ zeros_left -= run;
174+ coeff_num -= run + 1;
175+ }
176+ Ok(total_coeff as u8)
177+}
178+
179+#[cfg(test)]
180+mod tests {
181+ use super::*;
182+ use ec_core::BitWriter;
183+
184+ fn cursor(data: &[u8]) -> BitCursor<'_> {
185+ BitCursor::new(data, 0)
186+ }
187+
188+ fn reader_of(bits: &str) -> Vec<u8> {
189+ let mut w = BitWriter::new();
190+ for c in bits.chars().filter(|c| !c.is_whitespace()) {
191+ w.write_bit(c == '1');
192+ }
193+ // Pad so peeks have room.
194+ w.align_to_byte();
195+ w.write_bytes(&[0xFF; 4]);
196+ w.into_bytes()
197+ }
198+
199+ #[test]
200+ fn zero_coefficients_single_bit() {
201+ // nC 0: coeff_token (0,0) is "1".
202+ let data = reader_of("1");
203+ let mut r = cursor(&data);
204+ let mut c = [0i32; 16];
205+ assert_eq!(residual_block(&mut r, &mut c, 16, 0).unwrap(), 0);
206+ assert_eq!(r.bit_position(), 1);
207+ assert_eq!(c, [0; 16]);
208+ }
209+
210+ /// Worked example: TotalCoeff 3, TrailingOnes 2, one explicit level.
211+ /// nC=0 coeff_token(2,3) = "0000101"; signs + and -; level_prefix "1"
212+ /// (level_code 0+2=2 -> level 2); total_zeros (tz index 3) = 1 -> "111";
213+ /// wait: use total_zeros 0 -> "0101" per tzVlcIndex 3.
214+ #[test]
215+ fn trailing_ones_and_one_level() {
216+ // trailing signs: 0 (+1), 1 (-1); level_prefix "1" -> levelCode 2 -> +2
217+ // total_zeros = 0 -> "0101" (tz3); no run_before reads (zerosLeft 0).
218+ let data = reader_of("0000101 0 1 1 0101");
219+ let mut r = cursor(&data);
220+ let mut c = [0i32; 16];
221+ assert_eq!(residual_block(&mut r, &mut c, 16, 0).unwrap(), 3);
222+ // Levels ordered high frequency -> low: +1, -1, +2 at scan 2,1,0.
223+ assert_eq!(&c[..4], &[2, -1, 1, 0]);
224+ }
225+
226+ /// With total_zeros > 0 the levels spread out by run_before codes.
227+ #[test]
228+ fn runs_spread_levels() {
229+ // nC=0, coeff_token (1,1): "01"; sign 0 -> +1.
230+ // total_zeros for tzVlcIndex 1: value 2 = "010".
231+ // Single coefficient: no run_before read, position = 2.
232+ let data = reader_of("01 0 010");
233+ let mut r = cursor(&data);
234+ let mut c = [0i32; 16];
235+ assert_eq!(residual_block(&mut r, &mut c, 16, 0).unwrap(), 1);
236+ assert_eq!(c[2], 1);
237+ assert_eq!(c.iter().filter(|&&x| x != 0).count(), 1);
238+ }
239+
240+ #[test]
241+ fn chroma_dc_block() {
242+ // nC=-1, coeff_token (1,1) = "1"; sign "1" -> -1; TotalCoeff 1 < 4 so
243+ // total_zeros chroma (tz index 1): 3 = "000". Position = 3.
244+ let data = reader_of("1 1 000");
245+ let mut r = cursor(&data);
246+ let mut c = [0i32; 16];
247+ assert_eq!(residual_block(&mut r, &mut c, 4, -1).unwrap(), 1);
248+ assert_eq!(c[3], -1);
249+ }
250+
251+ #[test]
252+ fn full_block_skips_total_zeros() {
253+ // nC >= 8 uses the 6-bit FLC. (16, 3) = 63 = "111111".
254+ // 3 trailing signs then 13 levels with suffix_length starting at 1.
255+ let mut bits = String::from("111111 000");
256+ for _ in 0..13 {
257+ bits.push_str("10"); // level_prefix 0, suffix "0" -> levelCode 0
258+ }
259+ // First non-trailing level: t1 == 3 so no +2 adjustment; levelCode 0
260+ // -> +1 each.
261+ let data = reader_of(&bits);
262+ let mut r = cursor(&data);
263+ let mut c = [0i32; 16];
264+ assert_eq!(residual_block(&mut r, &mut c, 16, 9).unwrap(), 16);
265+ assert_eq!(c.iter().filter(|&&x| x != 0).count(), 16);
266+ }
267+
268+ #[test]
269+ fn truncated_is_need_more() {
270+ let data = [0u8; 1]; // 8 zero bits: valid prefix of a long code
271+ let mut r = cursor(&data);
272+ let mut c = [0i32; 16];
273+ assert!(matches!(
274+ residual_block(&mut r, &mut c, 16, 0),
275+ Err(Error::NeedMore)
276+ ));
277+ }
278+}
crates/ec-h264/src/deblock.rsadded+290 -0
@@ -0,0 +1,290 @@
1+//! In-loop deblocking filter (spec 8.7), intra-picture scope: every
2+//! macroblock is intra, so boundary strength is 4 on macroblock edges and 3
3+//! inside (8.7.2.1) — no motion-vector or reference comparisons yet.
4+
5+use crate::tables::{ALPHA, BETA, CHROMA_QP, TC0};
6+
7+/// Filter parameters of one edge segment.
8+#[derive(Debug, Clone, Copy)]
9+pub struct EdgeParams {
10+ /// indexA-resolved alpha threshold.
11+ pub alpha: i32,
12+ /// indexB-resolved beta threshold.
13+ pub beta: i32,
14+ /// tC0 for bS < 4 (unused for bS 4).
15+ pub tc0: i32,
16+ /// Boundary strength (3 or 4 here).
17+ pub bs: u8,
18+}
19+
20+/// Resolve thresholds (spec 8.7.2.2) for a luma or chroma edge.
21+/// `qp_avg` = (qPp + qPq + 1) >> 1, offsets are the slice's FilterOffsetA/B.
22+#[inline]
23+pub fn edge_params(qp_avg: i32, offset_a: i32, offset_b: i32, bs: u8) -> EdgeParams {
24+ let index_a = (qp_avg + offset_a).clamp(0, 51) as usize;
25+ let index_b = (qp_avg + offset_b).clamp(0, 51) as usize;
26+ EdgeParams {
27+ alpha: i32::from(ALPHA[index_a]),
28+ beta: i32::from(BETA[index_b]),
29+ tc0: i32::from(TC0[(bs - 1).min(2) as usize][index_a]),
30+ bs,
31+ }
32+}
33+
34+/// Map a luma QP to the chroma QP for deblocking (spec 8.7.2 via 8.5.8).
35+#[inline]
36+pub fn chroma_qp(qp_luma: i32, offset: i32) -> i32 {
37+ i32::from(CHROMA_QP[(qp_luma + offset).clamp(0, 51) as usize])
38+}
39+
40+/// Filter one line of samples across a luma edge (spec 8.7.2.3 / 8.7.2.4).
41+///
42+/// `p` indexes the plane; `s` is the distance between consecutive samples
43+/// across the edge (1 for vertical edges, stride for horizontal), and `edge`
44+/// is the index of q0. Samples p3..q3 must be in bounds.
45+#[inline]
46+pub fn filter_luma_line(data: &mut [u8], edge: usize, s: usize, e: &EdgeParams) {
47+ let q0 = i32::from(data[edge]);
48+ let p0 = i32::from(data[edge - s]);
49+ if (p0 - q0).abs() >= e.alpha {
50+ return;
51+ }
52+ let p1 = i32::from(data[edge - 2 * s]);
53+ let q1 = i32::from(data[edge + s]);
54+ if (p1 - p0).abs() >= e.beta || (q1 - q0).abs() >= e.beta {
55+ return;
56+ }
57+ let p2 = i32::from(data[edge - 3 * s]);
58+ let q2 = i32::from(data[edge + 2 * s]);
59+ let ap = (p2 - p0).abs();
60+ let aq = (q2 - q0).abs();
61+ if e.bs < 4 {
62+ let tc = e.tc0 + i32::from(ap < e.beta) + i32::from(aq < e.beta);
63+ let delta = (((q0 - p0) * 4 + (p1 - q1) + 4) >> 3).clamp(-tc, tc);
64+ data[edge - s] = (p0 + delta).clamp(0, 255) as u8;
65+ data[edge] = (q0 - delta).clamp(0, 255) as u8;
66+ if ap < e.beta {
67+ let d = ((p2 + ((p0 + q0 + 1) >> 1) - (p1 << 1)) >> 1).clamp(-e.tc0, e.tc0);
68+ data[edge - 2 * s] = (p1 + d) as u8;
69+ }
70+ if aq < e.beta {
71+ let d = ((q2 + ((p0 + q0 + 1) >> 1) - (q1 << 1)) >> 1).clamp(-e.tc0, e.tc0);
72+ data[edge + s] = (q1 + d) as u8;
73+ }
74+ } else {
75+ // bS == 4 (8.7.2.4).
76+ let strong = (p0 - q0).abs() < (e.alpha >> 2) + 2;
77+ if strong && ap < e.beta {
78+ let p3 = i32::from(data[edge - 4 * s]);
79+ data[edge - s] = ((p2 + 2 * p1 + 2 * p0 + 2 * q0 + q1 + 4) >> 3) as u8;
80+ data[edge - 2 * s] = ((p2 + p1 + p0 + q0 + 2) >> 2) as u8;
81+ data[edge - 3 * s] = ((2 * p3 + 3 * p2 + p1 + p0 + q0 + 4) >> 3) as u8;
82+ } else {
83+ data[edge - s] = ((2 * p1 + p0 + q1 + 2) >> 2) as u8;
84+ }
85+ if strong && aq < e.beta {
86+ let q3 = i32::from(data[edge + 3 * s]);
87+ data[edge] = ((p1 + 2 * p0 + 2 * q0 + 2 * q1 + q2 + 4) >> 3) as u8;
88+ data[edge + s] = ((p0 + q0 + q1 + q2 + 2) >> 2) as u8;
89+ data[edge + 2 * s] = ((2 * q3 + 3 * q2 + q1 + q0 + p0 + 4) >> 3) as u8;
90+ } else {
91+ data[edge] = ((2 * q1 + q0 + p1 + 2) >> 2) as u8;
92+ }
93+ }
94+}
95+
96+/// Filter one line across a chroma edge (chromaStyleFilteringFlag = 1).
97+#[inline]
98+pub fn filter_chroma_line(data: &mut [u8], edge: usize, s: usize, e: &EdgeParams) {
99+ let q0 = i32::from(data[edge]);
100+ let p0 = i32::from(data[edge - s]);
101+ if (p0 - q0).abs() >= e.alpha {
102+ return;
103+ }
104+ let p1 = i32::from(data[edge - 2 * s]);
105+ let q1 = i32::from(data[edge + s]);
106+ if (p1 - p0).abs() >= e.beta || (q1 - q0).abs() >= e.beta {
107+ return;
108+ }
109+ if e.bs < 4 {
110+ let tc = e.tc0 + 1;
111+ let delta = (((q0 - p0) * 4 + (p1 - q1) + 4) >> 3).clamp(-tc, tc);
112+ data[edge - s] = (p0 + delta).clamp(0, 255) as u8;
113+ data[edge] = (q0 - delta).clamp(0, 255) as u8;
114+ } else {
115+ data[edge - s] = ((2 * p1 + p0 + q1 + 2) >> 2) as u8;
116+ data[edge] = ((2 * q1 + q0 + p1 + 2) >> 2) as u8;
117+ }
118+}
119+
120+/// Vectorised luma edge filter core (spec 8.7.2.3 / 8.7.2.4), 16 lanes.
121+///
122+/// Takes the eight sample vectors across the edge, returns the six filtered
123+/// vectors `[p2', p1', p0', q0', q1', q2']`, or `None` when no lane passes
124+/// the filterSamplesFlag gate. Bit-identical to [`filter_luma_line`] per
125+/// lane.
126+#[allow(clippy::too_many_arguments)]
127+fn luma_edge_core16(
128+ p3: wide::i16x16,
129+ p2: wide::i16x16,
130+ p1: wide::i16x16,
131+ p0: wide::i16x16,
132+ q0: wide::i16x16,
133+ q1: wide::i16x16,
134+ q2: wide::i16x16,
135+ q3: wide::i16x16,
136+ e: &EdgeParams,
137+) -> Option<[wide::i16x16; 6]> {
138+ use wide::i16x16;
139+ let alpha = i16x16::splat(e.alpha as i16);
140+ let beta = i16x16::splat(e.beta as i16);
141+ let filter = (p0 - q0).abs().simd_lt(alpha)
142+ & (p1 - p0).abs().simd_lt(beta)
143+ & (q1 - q0).abs().simd_lt(beta);
144+ if !filter.any() {
145+ return None;
146+ }
147+ let ap = (p2 - p0).abs().simd_lt(beta);
148+ let aq = (q2 - q0).abs().simd_lt(beta);
149+ let one = i16x16::ONE;
150+
151+ Some(if e.bs < 4 {
152+ let tc0 = i16x16::splat(e.tc0 as i16);
153+ let tc = tc0 + ap.select(one, i16x16::ZERO) + aq.select(one, i16x16::ZERO);
154+ let four = i16x16::splat(4);
155+ let delta = ((((q0 - p0) << 2u32) + (p1 - q1) + four) >> 3u32)
156+ .max(-tc)
157+ .min(tc);
158+ let avg = (p0 + q0 + one) >> 1u32;
159+ let dp1 = ((p2 + avg - (p1 << 1u32)) >> 1u32).max(-tc0).min(tc0);
160+ let dq1 = ((q2 + avg - (q1 << 1u32)) >> 1u32).max(-tc0).min(tc0);
161+ [
162+ p2,
163+ (filter & ap).select(p1 + dp1, p1),
164+ filter.select(p0 + delta, p0),
165+ filter.select(q0 - delta, q0),
166+ (filter & aq).select(q1 + dq1, q1),
167+ q2,
168+ ]
169+ } else {
170+ let two = i16x16::splat(2);
171+ let four = i16x16::splat(4);
172+ let strong = (p0 - q0)
173+ .abs()
174+ .simd_lt(i16x16::splat(((e.alpha >> 2) + 2) as i16));
175+ let sp = filter & strong & ap;
176+ let sq = filter & strong & aq;
177+ let p0s = (p2 + (p1 << 1u32) + (p0 << 1u32) + (q0 << 1u32) + q1 + four) >> 3u32;
178+ let p1s = (p2 + p1 + p0 + q0 + two) >> 2u32;
179+ let p2s = ((p3 << 1u32) + p2 + (p2 << 1u32) + p1 + p0 + q0 + four) >> 3u32;
180+ let p0w = ((p1 << 1u32) + p0 + q1 + two) >> 2u32;
181+ let q0s = (p1 + (p0 << 1u32) + (q0 << 1u32) + (q1 << 1u32) + q2 + four) >> 3u32;
182+ let q1s = (p0 + q0 + q1 + q2 + two) >> 2u32;
183+ let q2s = ((q3 << 1u32) + q2 + (q2 << 1u32) + q1 + q0 + p0 + four) >> 3u32;
184+ let q0w = ((q1 << 1u32) + q0 + p1 + two) >> 2u32;
185+ [
186+ sp.select(p2s, p2),
187+ sp.select(p1s, p1),
188+ sp.select(p0s, filter.select(p0w, p0)),
189+ sq.select(q0s, filter.select(q0w, q0)),
190+ sq.select(q1s, q1),
191+ sq.select(q2s, q2),
192+ ]
193+ })
194+}
195+
196+#[inline]
197+fn load_row16(data: &[u8], at: usize) -> wide::i16x16 {
198+ let mut a = [0i16; 16];
199+ for (o, &b) in a.iter_mut().zip(&data[at..at + 16]) {
200+ *o = i16::from(b);
201+ }
202+ wide::i16x16::from(a)
203+}
204+
205+#[inline]
206+fn store_row16(data: &mut [u8], at: usize, v: wide::i16x16) {
207+ let clipped = v.max(wide::i16x16::ZERO).min(wide::i16x16::splat(255));
208+ for (o, &s) in data[at..at + 16].iter_mut().zip(clipped.as_array().iter()) {
209+ *o = s as u8;
210+ }
211+}
212+
213+/// Filter a whole horizontal luma edge (16 samples wide): the eight rows
214+/// around the edge are contiguous, so the filter runs 16 lanes at once with
215+/// masked selects instead of per-pixel branches. `q0_row` indexes the first
216+/// sample of the q0 row.
217+pub fn filter_luma_h_edge16(data: &mut [u8], q0_row: usize, stride: usize, e: &EdgeParams) {
218+ let p3 = load_row16(data, q0_row - 4 * stride);
219+ let p2 = load_row16(data, q0_row - 3 * stride);
220+ let p1 = load_row16(data, q0_row - 2 * stride);
221+ let p0 = load_row16(data, q0_row - stride);
222+ let q0 = load_row16(data, q0_row);
223+ let q1 = load_row16(data, q0_row + stride);
224+ let q2 = load_row16(data, q0_row + 2 * stride);
225+ let q3 = load_row16(data, q0_row + 3 * stride);
226+ let Some(out) = luma_edge_core16(p3, p2, p1, p0, q0, q1, q2, q3, e) else {
227+ return;
228+ };
229+ store_row16(data, q0_row - 3 * stride, out[0]);
230+ store_row16(data, q0_row - 2 * stride, out[1]);
231+ store_row16(data, q0_row - stride, out[2]);
232+ store_row16(data, q0_row, out[3]);
233+ store_row16(data, q0_row + stride, out[4]);
234+ store_row16(data, q0_row + 2 * stride, out[5]);
235+}
236+
237+#[cfg(test)]
238+mod tests {
239+ use super::*;
240+
241+ #[test]
242+ fn thresholds_clamp_and_lookup() {
243+ let e = edge_params(26, 0, 0, 3);
244+ assert_eq!(e.alpha, i32::from(ALPHA[26]));
245+ assert_eq!(e.beta, i32::from(BETA[26]));
246+ assert_eq!(e.tc0, i32::from(TC0[2][26]));
247+ // Offsets push the index outside [0, 51] and clamp.
248+ let e2 = edge_params(51, 12, 12, 4);
249+ assert_eq!(e2.alpha, 255);
250+ let e3 = edge_params(0, -12, -12, 3);
251+ assert_eq!(e3.alpha, 0);
252+ assert_eq!(chroma_qp(51, 0), 39);
253+ assert_eq!(chroma_qp(20, 2), 22);
254+ }
255+
256+ /// A hard step across a bS=4 edge at moderate QP gets smoothed; a flat
257+ /// area is untouched.
258+ #[test]
259+ fn strong_filter_smooths_step() {
260+ // Line: p3 p2 p1 p0 | q0 q1 q2 q3.
261+ let mut line = [60u8, 60, 60, 60, 80, 80, 80, 80];
262+ let e = edge_params(32, 0, 0, 4);
263+ filter_luma_line(&mut line, 4, 1, &e);
264+ // (p0, q0) move toward each other.
265+ assert!(line[3] > 60 && line[4] < 80, "{line:?}");
266+ let mut flat = [90u8; 8];
267+ filter_luma_line(&mut flat, 4, 1, &e);
268+ assert_eq!(flat, [90; 8]);
269+ }
270+
271+ /// Above alpha the edge is treated as a real feature and left alone.
272+ #[test]
273+ fn large_step_is_preserved() {
274+ let mut line = [10u8, 10, 10, 10, 200, 200, 200, 200];
275+ let e = edge_params(26, 0, 0, 4);
276+ filter_luma_line(&mut line, 4, 1, &e);
277+ assert_eq!(line, [10, 10, 10, 10, 200, 200, 200, 200]);
278+ }
279+
280+ #[test]
281+ fn chroma_filter_touches_only_p0_q0() {
282+ let mut line = [60u8, 60, 60, 60, 74, 74, 74, 74];
283+ let e = edge_params(32, 0, 0, 3);
284+ filter_chroma_line(&mut line, 4, 1, &e);
285+ assert_eq!(line[2], 60);
286+ assert_eq!(line[5], 74);
287+ assert!(line[3] >= 60 && line[4] <= 74);
288+ assert!(line[3] != 60 || line[4] != 74);
289+ }
290+}
crates/ec-h264/src/decoder.rsadded+1015 -0
@@ -0,0 +1,1015 @@
1+//! Decoder core: parameter-set store, flat per-picture context, macroblock
2+//! decode loop, reconstruction and the in-loop filter driver.
3+//!
4+//! Layout choices (perf-first):
5+//! - Planes are padded (`PAD_Y`/`PAD_C` samples each side), so neighbour
6+//! gathers and future inter-prediction overreach never bounds-check per
7+//! sample and edge availability is data, not arithmetic.
8+//! - All per-macroblock state lives in flat struct-of-arrays keyed by
9+//! macroblock address or 4x4-block coordinate: non-zero coefficient counts
10+//! (`nz_y`, `nz_c`), intra 4x4 modes, QP, flags, owning slice. No per-MB
11+//! heap objects anywhere.
12+//! - Buffers are reused across pictures; a picture start is O(macroblocks)
13+//! fills, and the slice decode loop performs zero allocations.
14+
15+use ec_core::BitReader;
16+use ec_core::error::{Error, Result};
17+use ec_core::frame::{PixelFormat, Plane, VideoFrame};
18+use ec_h264_syntax::{
19+ AnnexBIter, NalHeader, NalUnitType, Pps, SliceHeader, SliceType, Sps, unescape_rbsp,
20+};
21+
22+use crate::bits::BitCursor;
23+use crate::cavlc::residual_block;
24+use crate::deblock::{
25+ chroma_qp, edge_params, filter_chroma_line, filter_luma_h_edge16, filter_luma_line,
26+};
27+use crate::pred::{Nbr4, PlaneWindow, add_residual_4x4, pred_4x4, pred_16x16, pred_chroma_8x8};
28+use crate::tables::{BLK4_POS, CBP_INTRA_420, CHROMA_QP};
29+use crate::transform::{
30+ LevelScale4x4, chroma_dc_transform_420, dequant_4x4, inverse_transform_4x4, luma_dc_transform,
31+ unzigzag, unzigzag_ac15,
32+};
33+
34+/// Luma plane padding on every side, sized for future inter-prediction
35+/// filter overreach (16 MB + margin).
36+const PAD_Y: usize = 32;
37+/// Chroma plane padding on every side.
38+const PAD_C: usize = 16;
39+/// `mb_slice` value for a not-yet-decoded macroblock.
40+const NO_SLICE: u16 = u16::MAX;
41+
42+/// Where a 4x4 block's top-right neighbour samples come from, per
43+/// luma4x4BlkIdx (derivation of 6.4.12 + the 8.3.1.2 blkIdx 3/11 rule).
44+#[derive(Clone, Copy, PartialEq)]
45+enum TrKind {
46+ /// Bottom row of an earlier block in this macroblock: always available.
47+ InMb,
48+ /// The macroblock above.
49+ B,
50+ /// The macroblock above-right.
51+ C,
52+ /// Never available (right column, or blkIdx 3/11).
53+ None,
54+}
55+
56+const TR_KIND: [TrKind; 16] = [
57+ TrKind::B,
58+ TrKind::B,
59+ TrKind::InMb,
60+ TrKind::None,
61+ TrKind::B,
62+ TrKind::C,
63+ TrKind::InMb,
64+ TrKind::None,
65+ TrKind::InMb,
66+ TrKind::InMb,
67+ TrKind::InMb,
68+ TrKind::None,
69+ TrKind::InMb,
70+ TrKind::None,
71+ TrKind::InMb,
72+ TrKind::None,
73+];
74+
75+/// A padded 8-bit plane.
76+#[derive(Debug, Default)]
77+struct Plane8 {
78+ data: Vec<u8>,
79+ stride: usize,
80+ /// Index of sample (0, 0) of the picture.
81+ origin: usize,
82+}
83+
84+impl Plane8 {
85+ fn resize(&mut self, width: usize, height: usize, pad: usize) {
86+ self.stride = width + 2 * pad;
87+ self.origin = pad * self.stride + pad;
88+ self.data.clear();
89+ self.data.resize(self.stride * (height + 2 * pad), 0);
90+ }
91+
92+ #[inline]
93+ fn at(&self, x: usize, y: usize) -> usize {
94+ self.origin + y * self.stride + x
95+ }
96+}
97+
98+/// Per-slice values the deblocking filter needs after slice decode ends.
99+#[derive(Debug, Clone, Copy)]
100+struct SliceParams {
101+ disable_deblock_idc: u8,
102+ alpha_offset: i32,
103+ beta_offset: i32,
104+ cb_qp_offset: i32,
105+ cr_qp_offset: i32,
106+}
107+
108+/// Flat per-picture decode context (see module docs for the layout story).
109+#[derive(Debug, Default)]
110+struct Picture {
111+ sps_id: u8,
112+ mb_w: usize,
113+ mb_h: usize,
114+ y: Plane8,
115+ cb: Plane8,
116+ cr: Plane8,
117+ /// TotalCoeff per luma 4x4 block, `(mb_w * 4) x (mb_h * 4)`.
118+ nz_y: Vec<u8>,
119+ /// TotalCoeff per chroma 4x4 block, `(mb_w * 2) x (mb_h * 2)`, Cb and Cr.
120+ nz_c: [Vec<u8>; 2],
121+ /// Intra4x4PredMode per luma 4x4 block (2 = DC for non-I4x4 MBs).
122+ i4_modes: Vec<u8>,
123+ /// QPY per macroblock (the prediction-chain value; PCM keeps the chain).
124+ mb_qp: Vec<u8>,
125+ /// Bit 0: decoded, bit 1: I_PCM, bit 2: Intra_16x16.
126+ mb_flags: Vec<u8>,
127+ /// Owning slice index per macroblock, `NO_SLICE` when undecoded.
128+ mb_slice: Vec<u16>,
129+ slices: Vec<SliceParams>,
130+ decoded_mbs: usize,
131+ complete: bool,
132+}
133+
134+const FLAG_DECODED: u8 = 1;
135+const FLAG_PCM: u8 = 2;
136+
137+impl Picture {
138+ fn start(&mut self, sps: &Sps) {
139+ let mb_w = sps.mb_width as usize;
140+ let mb_h = sps.mb_height as usize;
141+ if self.mb_w != mb_w || self.mb_h != mb_h || self.sps_id != sps.id {
142+ self.mb_w = mb_w;
143+ self.mb_h = mb_h;
144+ self.sps_id = sps.id;
145+ self.y.resize(mb_w * 16, mb_h * 16, PAD_Y);
146+ self.cb.resize(mb_w * 8, mb_h * 8, PAD_C);
147+ self.cr.resize(mb_w * 8, mb_h * 8, PAD_C);
148+ self.nz_y.resize(mb_w * mb_h * 16, 0);
149+ for c in &mut self.nz_c {
150+ c.resize(mb_w * mb_h * 4, 0);
151+ }
152+ self.i4_modes.resize(mb_w * mb_h * 16, 2);
153+ self.mb_qp.resize(mb_w * mb_h, 0);
154+ self.mb_flags.resize(mb_w * mb_h, 0);
155+ self.mb_slice.resize(mb_w * mb_h, NO_SLICE);
156+ }
157+ // Per-MB metadata is rewritten by each decoded macroblock; only the
158+ // "who is decoded" state must be wiped between pictures.
159+ self.mb_slice.fill(NO_SLICE);
160+ self.mb_flags.fill(0);
161+ self.slices.clear();
162+ self.decoded_mbs = 0;
163+ self.complete = false;
164+ }
165+}
166+
167+/// Streaming H.264 decoder (CAVLC intra scope; unsupported features come back
168+/// as named [`Error::Unsupported`] values, never wrong pixels).
169+pub struct Decoder {
170+ sps_map: Vec<Option<Sps>>,
171+ pps_map: Vec<Option<Pps>>,
172+ rbsp: Vec<u8>,
173+ pic: Picture,
174+ has_picture: bool,
175+ /// Scaling factors for intra Y/Cb/Cr 4x4 lists of the active PPS/SPS.
176+ ls: [LevelScale4x4; 3],
177+ active_pps: Option<u32>,
178+}
179+
180+/// What [`Decoder::push_nal`] did with a NAL unit.
181+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
182+pub enum NalOutcome {
183+ /// SPS or PPS stored.
184+ ParameterSet,
185+ /// Non-VCL NAL skipped (SEI, AUD, filler, ...).
186+ Skipped,
187+ /// A slice was decoded into the open picture.
188+ SliceDecoded,
189+ /// The NAL starts a new picture while one is open; it was not consumed.
190+ /// Call [`Decoder::end_picture`] + [`Decoder::frame`], then push it again.
191+ PictureBoundary,
192+}
193+
194+impl Default for Decoder {
195+ fn default() -> Self {
196+ Decoder::new()
197+ }
198+}
199+
200+impl Decoder {
201+ /// A fresh decoder with no parameter sets.
202+ pub fn new() -> Decoder {
203+ Decoder {
204+ sps_map: vec![None; 32],
205+ pps_map: vec![None; 256],
206+ rbsp: Vec::new(),
207+ pic: Picture::default(),
208+ has_picture: false,
209+ ls: [
210+ LevelScale4x4::new(&[16; 16]),
211+ LevelScale4x4::new(&[16; 16]),
212+ LevelScale4x4::new(&[16; 16]),
213+ ],
214+ active_pps: None,
215+ }
216+ }
217+
218+ /// Decode the first IDR picture of an Annex B stream and return it.
219+ pub fn decode_first_idr(&mut self, annexb: &[u8]) -> Result<VideoFrame> {
220+ let mut got_slice = false;
221+ for nal in AnnexBIter::new(annexb) {
222+ match self.push_nal(nal)? {
223+ NalOutcome::PictureBoundary => break,
224+ NalOutcome::SliceDecoded => got_slice = true,
225+ _ => {}
226+ }
227+ }
228+ if !got_slice {
229+ return Err(Error::NeedMore);
230+ }
231+ self.end_picture()?;
232+ self.frame()
233+ }
234+
235+ /// Feed one NAL unit (header byte first, no start code).
236+ pub fn push_nal(&mut self, nal: &[u8]) -> Result<NalOutcome> {
237+ let Some((&header_byte, payload)) = nal.split_first() else {
238+ return Err(Error::NeedMore);
239+ };
240+ let header = NalHeader::parse(header_byte)?;
241+ match header.unit_type {
242+ NalUnitType::Sps => {
243+ let mut rbsp = core::mem::take(&mut self.rbsp);
244+ unescape_rbsp(payload, &mut rbsp);
245+ let sps = Sps::parse(&rbsp);
246+ self.rbsp = rbsp;
247+ let sps = sps?;
248+ let id = sps.id as usize;
249+ self.sps_map[id] = Some(sps);
250+ Ok(NalOutcome::ParameterSet)
251+ }
252+ NalUnitType::Pps => {
253+ let mut rbsp = core::mem::take(&mut self.rbsp);
254+ unescape_rbsp(payload, &mut rbsp);
255+ let pps = Pps::parse(&rbsp, |id| self.sps_map[id as usize].as_ref());
256+ self.rbsp = rbsp;
257+ let pps = pps?;
258+ let id = pps.id as usize;
259+ self.pps_map[id] = Some(pps);
260+ Ok(NalOutcome::ParameterSet)
261+ }
262+ NalUnitType::Slice | NalUnitType::SliceIdr => {
263+ let mut rbsp = core::mem::take(&mut self.rbsp);
264+ unescape_rbsp(payload, &mut rbsp);
265+ let r = self.decode_slice_rbsp(header, &rbsp);
266+ self.rbsp = rbsp;
267+ r
268+ }
269+ NalUnitType::SliceDataA | NalUnitType::SliceDataB | NalUnitType::SliceDataC => Err(
270+ Error::unsupported("slice data partitioning", "NAL types 2..4 not implemented"),
271+ ),
272+ _ => Ok(NalOutcome::Skipped),
273+ }
274+ }
275+
276+ /// Run the deblocking filter over the open picture and mark it complete.
277+ pub fn end_picture(&mut self) -> Result<()> {
278+ if !self.has_picture || self.pic.complete {
279+ return Err(Error::corrupt("end_picture without an open picture"));
280+ }
281+ deblock_picture(&mut self.pic);
282+ self.pic.complete = true;
283+ Ok(())
284+ }
285+
286+ /// Copy the completed picture out as a cropped I420 frame.
287+ pub fn frame(&self) -> Result<VideoFrame> {
288+ if !self.pic.complete {
289+ return Err(Error::corrupt("frame() before end_picture()"));
290+ }
291+ let sps = self.sps_map[self.pic.sps_id as usize]
292+ .as_ref()
293+ .ok_or_else(|| Error::corrupt("active SPS vanished"))?;
294+ let (w, h) = (sps.width as usize, sps.height as usize);
295+ let (cx, cy) = (sps.crop.0 as usize, sps.crop.2 as usize);
296+ let copy = |p: &Plane8, x0: usize, y0: usize, w: usize, h: usize| -> Plane {
297+ let mut out = vec![0u8; w * h];
298+ for row in 0..h {
299+ let src = p.at(x0, y0 + row);
300+ out[row * w..(row + 1) * w].copy_from_slice(&p.data[src..src + w]);
301+ }
302+ Plane::new(out, w)
303+ };
304+ let planes = vec![
305+ copy(&self.pic.y, cx, cy, w, h),
306+ copy(&self.pic.cb, cx / 2, cy / 2, w.div_ceil(2), h.div_ceil(2)),
307+ copy(&self.pic.cr, cx / 2, cy / 2, w.div_ceil(2), h.div_ceil(2)),
308+ ];
309+ let mut frame = VideoFrame::try_new(PixelFormat::I420, w as u32, h as u32, planes)?;
310+ if let Some(vui) = &sps.vui {
311+ frame.color.full_range = vui.video_full_range;
312+ if let Some((p, t, m)) = vui.colour_description {
313+ frame.color.primaries = p;
314+ frame.color.transfer = t;
315+ frame.color.matrix = m;
316+ }
317+ }
318+ Ok(frame)
319+ }
320+
321+ /// True while a picture is open (started, not completed).
322+ pub fn picture_open(&self) -> bool {
323+ self.has_picture && !self.pic.complete
324+ }
325+
326+ fn decode_slice_rbsp(&mut self, header: NalHeader, rbsp: &[u8]) -> Result<NalOutcome> {
327+ // Peek first_mb / slice_type / pps_id to select parameter sets.
328+ let mut peek = BitReader::new(rbsp);
329+ let first_mb = peek.read_ue()?;
330+ let slice_type_code = peek.read_ue()?;
331+ let pps_id = peek.read_ue()?;
332+ if pps_id > 255 {
333+ return Err(Error::corrupt("pic_parameter_set_id > 255"));
334+ }
335+ if self.has_picture && !self.pic.complete && first_mb == 0 && self.pic.decoded_mbs > 0 {
336+ return Ok(NalOutcome::PictureBoundary);
337+ }
338+ let pps = self.pps_map[pps_id as usize]
339+ .as_ref()
340+ .ok_or_else(|| Error::corrupt("slice refers to an unknown PPS"))?;
341+ let sps = self.sps_map[pps.sps_id as usize]
342+ .as_ref()
343+ .ok_or_else(|| Error::corrupt("PPS refers to an unknown SPS"))?;
344+
345+ check_supported(sps, pps, slice_type_code)?;
346+ let sh = SliceHeader::parse(rbsp, header, sps, pps)?;
347+ if sh.slice_type != SliceType::I {
348+ return Err(Error::unsupported(
349+ "non-I slice",
350+ "P/B/SP/SI slices arrive with inter prediction (S18c)",
351+ ));
352+ }
353+
354+ if !self.has_picture || self.pic.complete {
355+ self.pic.start(sps);
356+ self.has_picture = true;
357+ if self.active_pps != Some(pps.id) {
358+ let lists = pps.scaling_lists.as_ref().or(sps.scaling_lists.as_ref());
359+ let weights = match lists {
360+ Some(l) => [&l.list_4x4[0], &l.list_4x4[1], &l.list_4x4[2]],
361+ None => [&[16u8; 16]; 3],
362+ };
363+ self.ls = [
364+ LevelScale4x4::new(weights[0]),
365+ LevelScale4x4::new(weights[1]),
366+ LevelScale4x4::new(weights[2]),
367+ ];
368+ self.active_pps = Some(pps.id);
369+ }
370+ }
371+ if self.pic.sps_id != sps.id {
372+ return Err(Error::corrupt("SPS changed mid-picture"));
373+ }
374+ if self.pic.slices.len() >= usize::from(u16::MAX) {
375+ return Err(Error::corrupt("more than 65534 slices in a picture"));
376+ }
377+ let slice_id = self.pic.slices.len() as u16;
378+ self.pic.slices.push(SliceParams {
379+ disable_deblock_idc: sh.deblock.disable_idc,
380+ alpha_offset: sh.deblock.alpha_c0_offset,
381+ beta_offset: sh.deblock.beta_offset,
382+ cb_qp_offset: pps.chroma_qp_index_offset,
383+ cr_qp_offset: pps.second_chroma_qp_index_offset,
384+ });
385+
386+ let mut r = BitCursor::new(rbsp, sh.header_bits);
387+
388+ let mut ctx = SliceCtx {
389+ slice_id,
390+ qp: sh.slice_qp,
391+ cb_qp_offset: pps.chroma_qp_index_offset,
392+ cr_qp_offset: pps.second_chroma_qp_index_offset,
393+ transform_8x8_mode: pps.transform_8x8_mode,
394+ };
395+ let mbs = self.pic.mb_w * self.pic.mb_h;
396+ let mut mb_addr = first_mb as usize;
397+ loop {
398+ if mb_addr >= mbs {
399+ return Err(Error::corrupt("macroblock address beyond the picture"));
400+ }
401+ decode_macroblock(&mut self.pic, &self.ls, &mut r, &mut ctx, mb_addr)?;
402+ if !r.more_rbsp_data() {
403+ break;
404+ }
405+ mb_addr += 1;
406+ }
407+ Ok(NalOutcome::SliceDecoded)
408+ }
409+}
410+
411+/// Reject unsupported streams with named reasons before touching pixels.
412+fn check_supported(sps: &Sps, pps: &Pps, slice_type_code: u32) -> Result<()> {
413+ if pps.entropy_coding_mode {
414+ return Err(Error::unsupported(
415+ "CABAC entropy coding",
416+ "only CAVLC is implemented (S18b)",
417+ ));
418+ }
419+ if pps.num_slice_groups > 1 {
420+ return Err(Error::unsupported(
421+ "FMO slice groups",
422+ "num_slice_groups > 1 not implemented",
423+ ));
424+ }
425+ if sps.chroma_format_idc != 1 {
426+ return Err(Error::unsupported(
427+ "chroma format",
428+ format!("chroma_format_idc {} (only 4:2:0)", sps.chroma_format_idc),
429+ ));
430+ }
431+ if sps.bit_depth_luma != 8 || sps.bit_depth_chroma != 8 {
432+ return Err(Error::unsupported(
433+ "bit depth",
434+ format!(
435+ "{}-bit luma / {}-bit chroma (only 8-bit)",
436+ sps.bit_depth_luma, sps.bit_depth_chroma
437+ ),
438+ ));
439+ }
440+ if !sps.frame_mbs_only {
441+ return Err(Error::unsupported(
442+ "interlaced coding",
443+ "field pictures / MBAFF not implemented",
444+ ));
445+ }
446+ if sps.separate_colour_plane {
447+ return Err(Error::unsupported(
448+ "separate colour planes",
449+ "4:4:4 separate planes not implemented",
450+ ));
451+ }
452+ if sps.transform_bypass {
453+ return Err(Error::unsupported(
454+ "transform bypass",
455+ "qpprime_y_zero_transform_bypass not implemented",
456+ ));
457+ }
458+ if slice_type_code > 9 {
459+ return Err(Error::corrupt("slice_type > 9"));
460+ }
461+ Ok(())
462+}
463+
464+/// Mutable per-slice decode state.
465+struct SliceCtx {
466+ slice_id: u16,
467+ qp: i32,
468+ cb_qp_offset: i32,
469+ cr_qp_offset: i32,
470+ transform_8x8_mode: bool,
471+}
472+
473+/// Neighbour-availability snapshot for one macroblock (left, top,
474+/// top-right). Top-left availability follows from the modes that read it
475+/// being conformance-restricted; inter prediction will add it back.
476+#[derive(Clone, Copy)]
477+struct MbNeighbors {
478+ a: bool,
479+ b: bool,
480+ c: bool,
481+}
482+
483+fn mb_neighbors(pic: &Picture, mb_x: usize, mb_y: usize, slice_id: u16) -> MbNeighbors {
484+ let w = pic.mb_w;
485+ let addr = mb_y * w + mb_x;
486+ let same = |a: usize| pic.mb_slice[a] == slice_id;
487+ MbNeighbors {
488+ a: mb_x > 0 && same(addr - 1),
489+ b: mb_y > 0 && same(addr - w),
490+ c: mb_y > 0 && mb_x + 1 < w && same(addr - w + 1),
491+ }
492+}
493+
494+/// nC for a luma 4x4 block at global block coords `(bx, by)` (spec 9.2.1).
495+#[inline]
496+fn luma_nc(pic: &Picture, n: &MbNeighbors, bx: usize, by: usize) -> i32 {
497+ let w4 = pic.mb_w * 4;
498+ let left_avail = if bx.is_multiple_of(4) { n.a } else { true };
499+ let top_avail = if by.is_multiple_of(4) { n.b } else { true };
500+ let na = if left_avail && bx > 0 {
501+ i32::from(pic.nz_y[by * w4 + bx - 1])
502+ } else {
503+ -1
504+ };
505+ let nb = if top_avail && by > 0 {
506+ i32::from(pic.nz_y[(by - 1) * w4 + bx])
507+ } else {
508+ -1
509+ };
510+ match (na >= 0, nb >= 0) {
511+ (true, true) => (na + nb + 1) >> 1,
512+ (true, false) => na,
513+ (false, true) => nb,
514+ (false, false) => 0,
515+ }
516+}
517+
518+/// nC for a chroma AC 4x4 block at global chroma block coords.
519+#[inline]
520+fn chroma_nc(pic: &Picture, n: &MbNeighbors, comp: usize, cx: usize, cy: usize) -> i32 {
521+ let w2 = pic.mb_w * 2;
522+ let grid = &pic.nz_c[comp];
523+ let left_avail = if cx.is_multiple_of(2) { n.a } else { true };
524+ let top_avail = if cy.is_multiple_of(2) { n.b } else { true };
525+ let na = if left_avail && cx > 0 {
526+ i32::from(grid[cy * w2 + cx - 1])
527+ } else {
528+ -1
529+ };
530+ let nb = if top_avail && cy > 0 {
531+ i32::from(grid[(cy - 1) * w2 + cx])
532+ } else {
533+ -1
534+ };
535+ match (na >= 0, nb >= 0) {
536+ (true, true) => (na + nb + 1) >> 1,
537+ (true, false) => na,
538+ (false, true) => nb,
539+ (false, false) => 0,
540+ }
541+}
542+
543+/// Decode one macroblock of an I slice (spec 7.3.5, 7.4.5) and reconstruct
544+/// it. `ctx.qp` carries the QPY prediction chain.
545+// Block loops are indexed: `blk` is simultaneously a bitstream position, a
546+// geometry key (BLK4_POS) and a grid coordinate; iterators obscure that.
547+#[allow(clippy::needless_range_loop)]
548+fn decode_macroblock(
549+ pic: &mut Picture,
550+ ls: &[LevelScale4x4; 3],
551+ r: &mut BitCursor<'_>,
552+ ctx: &mut SliceCtx,
553+ mb_addr: usize,
554+) -> Result<()> {
555+ let mb_x = mb_addr % pic.mb_w;
556+ let mb_y = mb_addr / pic.mb_w;
557+ if pic.mb_slice[mb_addr] != NO_SLICE {
558+ return Err(Error::corrupt("macroblock decoded twice"));
559+ }
560+ let nbr = mb_neighbors(pic, mb_x, mb_y, ctx.slice_id);
561+ let w4 = pic.mb_w * 4;
562+ let w2 = pic.mb_w * 2;
563+ let (bx0, by0) = (mb_x * 4, mb_y * 4);
564+ let (cx0, cy0) = (mb_x * 2, mb_y * 2);
565+
566+ let mb_type = r.read_ue()?;
567+ if mb_type > 25 {
568+ return Err(Error::corrupt("I-slice mb_type > 25"));
569+ }
570+
571+ if mb_type == 25 {
572+ // I_PCM (7.3.5, 8.3.5): raw samples, byte aligned.
573+ r.align_to_byte();
574+ for y in 0..16 {
575+ let row = r.read_bytes(16)?;
576+ let dst = pic.y.at(mb_x * 16, mb_y * 16 + y);
577+ pic.y.data[dst..dst + 16].copy_from_slice(row);
578+ }
579+ for plane in [&mut pic.cb, &mut pic.cr] {
580+ for y in 0..8 {
581+ let row = r.read_bytes(8)?;
582+ let dst = plane.at(mb_x * 8, mb_y * 8 + y);
583+ plane.data[dst..dst + 8].copy_from_slice(row);
584+ }
585+ }
586+ for dy in 0..4 {
587+ let base = (by0 + dy) * w4 + bx0;
588+ pic.nz_y[base..base + 4].fill(16);
589+ pic.i4_modes[base..base + 4].fill(2);
590+ }
591+ for comp in 0..2 {
592+ for dy in 0..2 {
593+ let base = (cy0 + dy) * w2 + cx0;
594+ pic.nz_c[comp][base..base + 2].fill(16);
595+ }
596+ }
597+ // QPY prediction chain continues unchanged (mb_qp_delta inferred 0);
598+ // the deblocker substitutes 0 via FLAG_PCM (spec 8.7.2).
599+ pic.mb_qp[mb_addr] = ctx.qp as u8;
600+ pic.mb_flags[mb_addr] = FLAG_DECODED | FLAG_PCM;
601+ pic.mb_slice[mb_addr] = ctx.slice_id;
602+ pic.decoded_mbs += 1;
603+ return Ok(());
604+ }
605+
606+ let is_i16 = mb_type >= 1;
607+ let (cbp_luma, cbp_chroma, i16_mode) = if is_i16 {
608+ let m = mb_type - 1;
609+ (
610+ if m >= 12 { 15u8 } else { 0 },
611+ ((m / 4) % 3) as u8,
612+ (m % 4) as u8,
613+ )
614+ } else {
615+ (0, 0, 0) // read below via me(v)
616+ };
617+
618+ // I_NxN transform size flag (High profile only).
619+ if !is_i16 && ctx.transform_8x8_mode && r.read_bit()? {
620+ return Err(Error::unsupported(
621+ "8x8 transform",
622+ "transform_size_8x8_flag not implemented",
623+ ));
624+ }
625+
626+ // mb_pred (7.3.5.1): intra 4x4 modes, then chroma mode.
627+ let mut modes = [2u8; 16];
628+ if !is_i16 {
629+ for blk in 0..16 {
630+ let (dx, dy) = BLK4_POS[blk];
631+ let (bx, by) = (bx0 + dx as usize, by0 + dy as usize);
632+ // Predicted mode = min of neighbours, DC when either unavailable
633+ // (8.3.1.1; non-I4x4 neighbours were written as 2).
634+ let left_avail = if bx % 4 == 0 { nbr.a } else { true };
635+ let top_avail = if by % 4 == 0 { nbr.b } else { true };
636+ let pred = if left_avail && top_avail {
637+ let ma = pic.i4_modes[by * w4 + bx - 1];
638+ let mb = pic.i4_modes[(by - 1) * w4 + bx];
639+ ma.min(mb)
640+ } else {
641+ 2
642+ };
643+ let mode = if r.read_bit()? {
644+ pred
645+ } else {
646+ let rem = r.read_bits(3)? as u8;
647+ if rem < pred { rem } else { rem + 1 }
648+ };
649+ pic.i4_modes[by * w4 + bx] = mode;
650+ modes[blk] = mode;
651+ }
652+ } else {
653+ for dy in 0..4 {
654+ let base = (by0 + dy) * w4 + bx0;
655+ pic.i4_modes[base..base + 4].fill(2);
656+ }
657+ }
658+ let chroma_mode = r.read_ue()?;
659+ if chroma_mode > 3 {
660+ return Err(Error::corrupt("intra_chroma_pred_mode > 3"));
661+ }
662+
663+ // coded_block_pattern me(v) for I_NxN (9.1.2, Table 9-4).
664+ let (cbp_luma, cbp_chroma) = if is_i16 {
665+ (cbp_luma, cbp_chroma)
666+ } else {
667+ let code = r.read_ue()? as usize;
668+ let cbp = if code < 48 {
669+ CBP_INTRA_420[code]
670+ } else {
671+ return Err(Error::corrupt("coded_block_pattern codeNum > 47"));
672+ };
673+ (cbp & 15, cbp >> 4)
674+ };
675+
676+ // mb_qp_delta (7.4.5).
677+ if cbp_luma != 0 || cbp_chroma != 0 || is_i16 {
678+ let delta = r.read_se()?;
679+ if !(-26..=25).contains(&delta) {
680+ return Err(Error::corrupt("mb_qp_delta outside [-26, 25]"));
681+ }
682+ ctx.qp = (ctx.qp + delta + 52) % 52;
683+ }
684+ pic.mb_qp[mb_addr] = ctx.qp as u8;
685+ pic.mb_flags[mb_addr] = FLAG_DECODED;
686+ pic.mb_slice[mb_addr] = ctx.slice_id;
687+ pic.decoded_mbs += 1;
688+ let qp_y = ctx.qp;
689+ let qp_cb = i32::from(CHROMA_QP[(qp_y + ctx.cb_qp_offset).clamp(0, 51) as usize]);
690+ let qp_cr = i32::from(CHROMA_QP[(qp_y + ctx.cr_qp_offset).clamp(0, 51) as usize]);
691+
692+ // ---- residual parse fused with reconstruction (7.3.5.3 + 8.5) ----
693+ //
694+ // Bitstream order (luma blocks in Z-order, then chroma DC, then chroma
695+ // AC) equals reconstruction dependency order, so each block reconstructs
696+ // the moment its levels are parsed: no per-MB coefficient arrays, and
697+ // empty blocks cost one coeff_token read plus a prediction write.
698+ let mut scan = [0i32; 16];
699+ let mut raster = [0i32; 16];
700+ let mut resid = [0i32; 16];
701+ if is_i16 {
702+ let mut w = PlaneWindow {
703+ data: &mut pic.y.data,
704+ stride: pic.y.stride,
705+ origin: pic.y.origin + (mb_y * 16) * pic.y.stride + mb_x * 16,
706+ };
707+ pred_16x16(i16_mode, &mut w, nbr.b, nbr.a);
708+ // Luma DC: un-zigzag over the 4x4 DC array, Hadamard + scale.
709+ let nc = luma_nc(pic, &nbr, bx0, by0);
710+ residual_block(r, &mut scan, 16, nc)?;
711+ unzigzag(&scan, &mut raster);
712+ luma_dc_transform(&mut raster, &ls[0], qp_y);
713+ let dc = raster;
714+ for blk in 0..16 {
715+ let (dx, dy) = BLK4_POS[blk];
716+ let (bx, by) = (bx0 + dx as usize, by0 + dy as usize);
717+ let tc = if cbp_luma != 0 {
718+ let nc = luma_nc(pic, &nbr, bx, by);
719+ residual_block(r, &mut scan, 15, nc)?
720+ } else {
721+ 0
722+ };
723+ pic.nz_y[by * w4 + bx] = tc;
724+ let dc_blk = dc[dy as usize * 4 + dx as usize];
725+ if tc == 0 && dc_blk == 0 {
726+ continue; // prediction already in place
727+ }
728+ if tc > 0 {
729+ unzigzag_ac15(&scan, &mut raster);
730+ dequant_4x4(&mut raster, &ls[0], qp_y, true);
731+ } else {
732+ raster = [0; 16]; // DC-only block
733+ }
734+ raster[0] = dc_blk;
735+ inverse_transform_4x4(&raster, &mut resid);
736+ let origin = pic
737+ .y
738+ .at(mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4);
739+ add_residual_4x4(&mut pic.y.data, pic.y.stride, origin, &resid);
740+ }
741+ } else {
742+ for blk in 0..16 {
743+ let (dx, dy) = BLK4_POS[blk];
744+ let (bx, by) = (bx0 + dx as usize, by0 + dy as usize);
745+ let tc = if cbp_luma & (1 << (blk >> 2)) != 0 {
746+ let nc = luma_nc(pic, &nbr, bx, by);
747+ residual_block(r, &mut scan, 16, nc)?
748+ } else {
749+ 0
750+ };
751+ pic.nz_y[by * w4 + bx] = tc;
752+ let (x, y) = (mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4);
753+ let n = gather_nbr4(pic, &nbr, blk, x, y);
754+ let mut p = [0u8; 16];
755+ pred_4x4(modes[blk], &n, &mut p);
756+ let origin = pic.y.at(x, y);
757+ let stride = pic.y.stride;
758+ if tc == 0 {
759+ // Pure prediction: copy the 16 samples in.
760+ for ry in 0..4 {
761+ let row = origin + ry * stride;
762+ pic.y.data[row..row + 4].copy_from_slice(&p[ry * 4..ry * 4 + 4]);
763+ }
764+ continue;
765+ }
766+ unzigzag(&scan, &mut raster);
767+ dequant_4x4(&mut raster, &ls[0], qp_y, false);
768+ inverse_transform_4x4(&raster, &mut resid);
769+ for ry in 0..4 {
770+ let row = origin + ry * stride;
771+ for rx in 0..4 {
772+ let v = i32::from(p[ry * 4 + rx]) + resid[ry * 4 + rx];
773+ pic.y.data[row + rx] = v.clamp(0, 255) as u8;
774+ }
775+ }
776+ }
777+ }
778+
779+ // Chroma: predict both components, then DC (Cb, Cr), then AC in
780+ // bitstream order (all Cb blocks, all Cr blocks), reconstructing as
781+ // levels arrive.
782+ for comp in 0..2 {
783+ let plane = if comp == 0 { &mut pic.cb } else { &mut pic.cr };
784+ let mut w = PlaneWindow {
785+ data: &mut plane.data,
786+ stride: plane.stride,
787+ origin: plane.origin + (mb_y * 8) * plane.stride + mb_x * 8,
788+ };
789+ pred_chroma_8x8(chroma_mode as u8, &mut w, nbr.b, nbr.a);
790+ }
791+ let mut chroma_dc = [[0i32; 4]; 2];
792+ if cbp_chroma != 0 {
793+ for (comp, c) in chroma_dc.iter_mut().enumerate() {
794+ residual_block(r, &mut scan, 4, -1)?;
795+ c.copy_from_slice(&scan[..4]);
796+ let (ls_c, qp_c) = if comp == 0 {
797+ (&ls[1], qp_cb)
798+ } else {
799+ (&ls[2], qp_cr)
800+ };
801+ chroma_dc_transform_420(c, ls_c, qp_c);
802+ }
803+ }
804+ for comp in 0..2 {
805+ for blk in 0..4 {
806+ let (cx, cy) = (cx0 + (blk & 1), cy0 + (blk >> 1));
807+ let tc = if cbp_chroma == 2 {
808+ let nc = chroma_nc(pic, &nbr, comp, cx, cy);
809+ residual_block(r, &mut scan, 15, nc)?
810+ } else {
811+ 0
812+ };
813+ pic.nz_c[comp][cy * w2 + cx] = tc;
814+ if cbp_chroma == 0 {
815+ continue;
816+ }
817+ let dc_blk = chroma_dc[comp][blk];
818+ if tc == 0 && dc_blk == 0 {
819+ continue;
820+ }
821+ let (plane, ls_c, qp_c) = if comp == 0 {
822+ (&mut pic.cb, &ls[1], qp_cb)
823+ } else {
824+ (&mut pic.cr, &ls[2], qp_cr)
825+ };
826+ if tc > 0 {
827+ unzigzag_ac15(&scan, &mut raster);
828+ dequant_4x4(&mut raster, ls_c, qp_c, true);
829+ } else {
830+ raster = [0; 16]; // DC-only block
831+ }
832+ raster[0] = dc_blk;
833+ inverse_transform_4x4(&raster, &mut resid);
834+ let origin = plane.at(mb_x * 8 + (blk & 1) * 4, mb_y * 8 + (blk >> 1) * 4);
835+ add_residual_4x4(&mut plane.data, plane.stride, origin, &resid);
836+ }
837+ }
838+ Ok(())
839+}
840+
841+/// Gather the 13 neighbour samples of a luma 4x4 block (spec 8.3.1.2),
842+/// including the top-right substitution rule.
843+fn gather_nbr4(pic: &Picture, nbr: &MbNeighbors, blk: usize, x: usize, y: usize) -> Nbr4 {
844+ let (dx, dy) = BLK4_POS[blk];
845+ let stride = pic.y.stride;
846+ let o = pic.y.at(x, y);
847+ let have_left = if dx == 0 { nbr.a } else { true };
848+ let have_top = if dy == 0 { nbr.b } else { true };
849+ let have_tr = match TR_KIND[blk] {
850+ TrKind::InMb => true,
851+ TrKind::B => nbr.b,
852+ TrKind::C => nbr.c,
853+ TrKind::None => false,
854+ };
855+ let mut top = [0u8; 8];
856+ let data = &pic.y.data;
857+ top[..4].copy_from_slice(&data[o - stride..o - stride + 4]);
858+ if have_tr {
859+ top[4..].copy_from_slice(&data[o - stride + 4..o - stride + 8]);
860+ } else if have_top {
861+ let t3 = top[3];
862+ top[4..].fill(t3);
863+ }
864+ let mut left = [0u8; 4];
865+ for (i, l) in left.iter_mut().enumerate() {
866+ *l = data[o + i * stride - 1];
867+ }
868+ Nbr4 {
869+ top,
870+ left,
871+ top_left: data[o - stride - 1],
872+ have_top,
873+ have_left,
874+ }
875+}
876+
877+/// Whole-picture deblocking (spec 8.7): macroblocks in raster order, all
878+/// vertical edges then all horizontal edges per macroblock, then chroma.
879+fn deblock_picture(pic: &mut Picture) {
880+ let mb_w = pic.mb_w;
881+ for mb_y in 0..pic.mb_h {
882+ for mb_x in 0..mb_w {
883+ let addr = mb_y * mb_w + mb_x;
884+ if pic.mb_flags[addr] & FLAG_DECODED == 0 {
885+ continue;
886+ }
887+ let sid = pic.mb_slice[addr];
888+ let sp = pic.slices[sid as usize];
889+ if sp.disable_deblock_idc == 1 {
890+ continue;
891+ }
892+ let decoded = |a: usize| pic.mb_flags[a] & FLAG_DECODED != 0;
893+ let cross_ok = |a: usize| sp.disable_deblock_idc != 2 || pic.mb_slice[a] == sid;
894+ let filter_left = mb_x > 0 && decoded(addr - 1) && cross_ok(addr - 1);
895+ let filter_top = mb_y > 0 && decoded(addr - mb_w) && cross_ok(addr - mb_w);
896+ // Deblocking QP: 0 for I_PCM macroblocks (8.7.2).
897+ let qp_of = |a: usize| -> i32 {
898+ if pic.mb_flags[a] & FLAG_PCM != 0 {
899+ 0
900+ } else {
901+ i32::from(pic.mb_qp[a])
902+ }
903+ };
904+ let qp_q = qp_of(addr);
905+
906+ // ---- luma ----
907+ {
908+ let stride = pic.y.stride;
909+ let base = pic.y.at(mb_x * 16, mb_y * 16);
910+ // Vertical edges (filter across columns), left to right.
911+ for e in 0..4 {
912+ if e == 0 && !filter_left {
913+ continue;
914+ }
915+ let (bs, qp_p) = if e == 0 {
916+ (4, qp_of(addr - 1))
917+ } else {
918+ (3, qp_q)
919+ };
920+ let params =
921+ edge_params((qp_p + qp_q + 1) >> 1, sp.alpha_offset, sp.beta_offset, bs);
922+ if params.alpha == 0 || params.beta == 0 {
923+ continue;
924+ }
925+ // Vertical edges stay scalar: a gather/scatter SIMD
926+ // variant measured slower than this loop (strided
927+ // per-lane loads dominate).
928+ for k in 0..16 {
929+ filter_luma_line(&mut pic.y.data, base + k * stride + e * 4, 1, &params);
930+ }
931+ }
932+ // Horizontal edges, top to bottom.
933+ for e in 0..4 {
934+ if e == 0 && !filter_top {
935+ continue;
936+ }
937+ let (bs, qp_p) = if e == 0 {
938+ (4, qp_of(addr - mb_w))
939+ } else {
940+ (3, qp_q)
941+ };
942+ let params =
943+ edge_params((qp_p + qp_q + 1) >> 1, sp.alpha_offset, sp.beta_offset, bs);
944+ if params.alpha == 0 || params.beta == 0 {
945+ continue;
946+ }
947+ filter_luma_h_edge16(&mut pic.y.data, base + e * 4 * stride, stride, &params);
948+ }
949+ }
950+
951+ // ---- chroma (Cb, Cr) ----
952+ for comp in 0..2 {
953+ let (plane, off_sel): (&mut Plane8, fn(&SliceParams) -> i32) = if comp == 0 {
954+ (&mut pic.cb, |s| s.cb_qp_offset)
955+ } else {
956+ (&mut pic.cr, |s| s.cr_qp_offset)
957+ };
958+ let stride = plane.stride;
959+ let base = plane.origin + (mb_y * 8) * stride + mb_x * 8;
960+ // Chroma QP per side: each macroblock's luma QP mapped with
961+ // the offset of ITS OWN slice's PPS (8.7.2).
962+ let cqp = |a: usize| -> i32 {
963+ let s = pic.slices[pic.mb_slice[a] as usize];
964+ if pic.mb_flags[a] & FLAG_PCM != 0 {
965+ chroma_qp(0, off_sel(&s))
966+ } else {
967+ chroma_qp(i32::from(pic.mb_qp[a]), off_sel(&s))
968+ }
969+ };
970+ let cq_q = cqp(addr);
971+ for e in 0..2 {
972+ if e == 0 && !filter_left {
973+ continue;
974+ }
975+ let (bs, cq_p) = if e == 0 {
976+ (4, cqp(addr - 1))
977+ } else {
978+ (3, cq_q)
979+ };
980+ let params =
981+ edge_params((cq_p + cq_q + 1) >> 1, sp.alpha_offset, sp.beta_offset, bs);
982+ if params.alpha == 0 || params.beta == 0 {
983+ continue;
984+ }
985+ for k in 0..8 {
986+ filter_chroma_line(&mut plane.data, base + k * stride + e * 4, 1, &params);
987+ }
988+ }
989+ for e in 0..2 {
990+ if e == 0 && !filter_top {
991+ continue;
992+ }
993+ let (bs, cq_p) = if e == 0 {
994+ (4, cqp(addr - mb_w))
995+ } else {
996+ (3, cq_q)
997+ };
998+ let params =
999+ edge_params((cq_p + cq_q + 1) >> 1, sp.alpha_offset, sp.beta_offset, bs);
1000+ if params.alpha == 0 || params.beta == 0 {
1001+ continue;
1002+ }
1003+ for k in 0..8 {
1004+ filter_chroma_line(
1005+ &mut plane.data,
1006+ base + e * 4 * stride + k,
1007+ stride,
1008+ &params,
1009+ );
1010+ }
1011+ }
1012+ }
1013+ }
1014+ }
1015+}
crates/ec-h264/src/lib.rsadded+22 -0
@@ -0,0 +1,22 @@
1+//! H.264 software decoder.
2+//!
3+//! Current scope: CAVLC-coded I slices (Intra_4x4, Intra_16x16, I_PCM) of
4+//! 8-bit 4:2:0 progressive streams, with the full in-loop deblocking filter,
5+//! decoded bit-exactly against the JVT conformance suite. Everything outside
6+//! that scope returns a named [`Error::Unsupported`] — never wrong output.
7+//!
8+//! Implemented from Rec. ITU-T H.264 (V15, 08/2024) only; no third-party
9+//! decoder source was consulted.
10+
11+#![forbid(unsafe_code)]
12+
13+mod bits;
14+mod cavlc;
15+mod deblock;
16+mod decoder;
17+mod pred;
18+mod tables;
19+mod transform;
20+
21+pub use decoder::{Decoder, NalOutcome};
22+pub use ec_core::error::{Error, Result};
crates/ec-h264/src/pred.rsadded+456 -0
@@ -0,0 +1,456 @@
1+//! Intra prediction (spec 8.3.1, 8.3.3, 8.3.4), 8-bit.
2+//!
3+//! Kernels operate on a small gathered neighbour set so the hot loop touches
4+//! the picture plane only twice per block: one gather, one write. All
5+//! arithmetic is in `i32` with a final `clamp(0, 255)`.
6+
7+/// Neighbour samples of a 4x4 block, gathered once (spec 8.3.1.2's 13
8+/// samples). `top[4..8]` already has the top-right substitution rule applied:
9+/// when p[4..7, -1] is unavailable but p[3, -1] is, it is replicated.
10+#[derive(Debug, Clone, Copy)]
11+pub struct Nbr4 {
12+ /// p[0..7, -1].
13+ pub top: [u8; 8],
14+ /// p[-1, 0..3].
15+ pub left: [u8; 4],
16+ /// p[-1, -1].
17+ pub top_left: u8,
18+ /// p[x, -1] available.
19+ pub have_top: bool,
20+ /// p[-1, y] available.
21+ pub have_left: bool,
22+}
23+
24+/// Predict a 4x4 block (spec 8.3.1.2.1-9) into `out` in raster order.
25+///
26+/// Modes 0..=8; conformant streams only signal modes whose required samples
27+/// are available, but unavailable inputs still produce defined output (DC
28+/// fallbacks) rather than reading junk.
29+pub fn pred_4x4(mode: u8, n: &Nbr4, out: &mut [u8; 16]) {
30+ let t = |x: usize| i32::from(n.top[x]);
31+ let l = |y: usize| i32::from(n.left[y]);
32+ let tl = i32::from(n.top_left);
33+ match mode {
34+ // Vertical.
35+ 0 => {
36+ for y in 0..4 {
37+ for x in 0..4 {
38+ out[y * 4 + x] = n.top[x];
39+ }
40+ }
41+ }
42+ // Horizontal.
43+ 1 => {
44+ for y in 0..4 {
45+ out[y * 4..y * 4 + 4].fill(n.left[y]);
46+ }
47+ }
48+ // DC (8-48..8-51).
49+ 2 => {
50+ let v = match (n.have_top, n.have_left) {
51+ (true, true) => (t(0) + t(1) + t(2) + t(3) + l(0) + l(1) + l(2) + l(3) + 4) >> 3,
52+ (false, true) => (l(0) + l(1) + l(2) + l(3) + 2) >> 2,
53+ (true, false) => (t(0) + t(1) + t(2) + t(3) + 2) >> 2,
54+ (false, false) => 128,
55+ };
56+ out.fill(v as u8);
57+ }
58+ // Diagonal down-left (8-52, 8-53).
59+ 3 => {
60+ for y in 0..4 {
61+ for x in 0..4 {
62+ let v = if x == 3 && y == 3 {
63+ (t(6) + 3 * t(7) + 2) >> 2
64+ } else {
65+ (t(x + y) + 2 * t(x + y + 1) + t(x + y + 2) + 2) >> 2
66+ };
67+ out[y * 4 + x] = v as u8;
68+ }
69+ }
70+ }
71+ // Diagonal down-right (8-54..8-56). Index -1 is the top-left sample.
72+ 4 => {
73+ let te = |i: i32| if i < 0 { tl } else { t(i as usize) };
74+ let le = |i: i32| if i < 0 { tl } else { l(i as usize) };
75+ for y in 0..4i32 {
76+ for x in 0..4i32 {
77+ let v = if x > y {
78+ (te(x - y - 2) + 2 * te(x - y - 1) + te(x - y) + 2) >> 2
79+ } else if x < y {
80+ (le(y - x - 2) + 2 * le(y - x - 1) + le(y - x) + 2) >> 2
81+ } else {
82+ (t(0) + 2 * tl + l(0) + 2) >> 2
83+ };
84+ out[(y * 4 + x) as usize] = v as u8;
85+ }
86+ }
87+ }
88+ // Vertical-right (8-57..8-60).
89+ 5 => {
90+ let te = |i: i32| if i < 0 { tl } else { t(i as usize) };
91+ let le = |i: i32| if i < 0 { tl } else { l(i as usize) };
92+ for y in 0..4i32 {
93+ for x in 0..4i32 {
94+ let z = 2 * x - y;
95+ let i = x - (y >> 1);
96+ let v = if z >= 0 && z % 2 == 0 {
97+ (te(i - 1) + te(i) + 1) >> 1
98+ } else if z >= 0 {
99+ (te(i - 2) + 2 * te(i - 1) + te(i) + 2) >> 2
100+ } else if z == -1 {
101+ (l(0) + 2 * tl + t(0) + 2) >> 2
102+ } else {
103+ (le(y - 1) + 2 * le(y - 2) + le(y - 3) + 2) >> 2
104+ };
105+ out[(y * 4 + x) as usize] = v as u8;
106+ }
107+ }
108+ }
109+ // Horizontal-down (8-61..8-64).
110+ 6 => {
111+ let te = |i: i32| if i < 0 { tl } else { t(i as usize) };
112+ let le = |i: i32| if i < 0 { tl } else { l(i as usize) };
113+ for y in 0..4i32 {
114+ for x in 0..4i32 {
115+ let z = 2 * y - x;
116+ let i = y - (x >> 1);
117+ let v = if z >= 0 && z % 2 == 0 {
118+ (le(i - 1) + le(i) + 1) >> 1
119+ } else if z >= 0 {
120+ (le(i - 2) + 2 * le(i - 1) + le(i) + 2) >> 2
121+ } else if z == -1 {
122+ (l(0) + 2 * tl + t(0) + 2) >> 2
123+ } else {
124+ (te(x - 1) + 2 * te(x - 2) + te(x - 3) + 2) >> 2
125+ };
126+ out[(y * 4 + x) as usize] = v as u8;
127+ }
128+ }
129+ }
130+ // Vertical-left (8-65, 8-66).
131+ 7 => {
132+ for y in 0..4usize {
133+ for x in 0..4usize {
134+ let i = x + (y >> 1);
135+ let v = if y % 2 == 0 {
136+ (t(i) + t(i + 1) + 1) >> 1
137+ } else {
138+ (t(i) + 2 * t(i + 1) + t(i + 2) + 2) >> 2
139+ };
140+ out[y * 4 + x] = v as u8;
141+ }
142+ }
143+ }
144+ // Horizontal-up (8-67..8-70).
145+ _ => {
146+ for y in 0..4usize {
147+ for x in 0..4usize {
148+ let z = x + 2 * y;
149+ let i = y + (x >> 1);
150+ let v = if z < 5 && z % 2 == 0 {
151+ (l(i) + l(i + 1) + 1) >> 1
152+ } else if z < 5 {
153+ (l(i) + 2 * l(i + 1) + l(i + 2) + 2) >> 2
154+ } else if z == 5 {
155+ (l(2) + 3 * l(3) + 2) >> 2
156+ } else {
157+ l(3)
158+ };
159+ out[y * 4 + x] = v as u8;
160+ }
161+ }
162+ }
163+ }
164+}
165+
166+/// A borrowed window into a picture plane for whole-MB prediction: `data`
167+/// spans the plane, `stride` its pitch, `origin` the index of this MB's
168+/// top-left sample.
169+pub struct PlaneWindow<'a> {
170+ /// The full plane.
171+ pub data: &'a mut [u8],
172+ /// Row pitch.
173+ pub stride: usize,
174+ /// Index of the block's top-left sample.
175+ pub origin: usize,
176+}
177+
178+/// Intra_16x16 prediction (spec 8.3.3), writing predictions straight into the
179+/// plane; residuals are added on top afterwards.
180+pub fn pred_16x16(mode: u8, w: &mut PlaneWindow<'_>, have_top: bool, have_left: bool) {
181+ pred_nxn::<16>(mode, w, have_top, have_left, 5, 5);
182+}
183+
184+/// Chroma 8x8 prediction for 4:2:0 (spec 8.3.4). Chroma mode numbering
185+/// differs from luma 16x16: 0 = DC, 1 = Horizontal, 2 = Vertical, 3 = Plane.
186+pub fn pred_chroma_8x8(mode: u8, w: &mut PlaneWindow<'_>, have_top: bool, have_left: bool) {
187+ match mode {
188+ 0 => pred_chroma_dc(w, have_top, have_left),
189+ 1 => pred_nxn::<8>(1, w, have_top, have_left, 0, 0),
190+ 2 => pred_nxn::<8>(0, w, have_top, have_left, 0, 0),
191+ _ => pred_nxn::<8>(3, w, have_top, have_left, 0, 34),
192+ }
193+}
194+
195+/// Shared V/H/DC/Plane engine for NxN whole-block prediction. `mode` uses the
196+/// 16x16 numbering (0 V, 1 H, 2 DC, 3 Plane). `dc_shift` = log2(2N),
197+/// `plane_scale` = 5 for luma, 34 for 4:2:0 chroma.
198+fn pred_nxn<const N: usize>(
199+ mode: u8,
200+ w: &mut PlaneWindow<'_>,
201+ have_top: bool,
202+ have_left: bool,
203+ dc_shift: u32,
204+ plane_scale: i32,
205+) {
206+ let stride = w.stride;
207+ let o = w.origin;
208+ match mode {
209+ 0 => {
210+ // Vertical: replicate the row above.
211+ let (top, rest) = w.data.split_at_mut(o);
212+ let top_row = &top[o - stride..o - stride + N];
213+ for y in 0..N {
214+ rest[y * stride..y * stride + N].copy_from_slice(top_row);
215+ }
216+ }
217+ 1 => {
218+ for y in 0..N {
219+ let v = w.data[o + y * stride - 1];
220+ w.data[o + y * stride..o + y * stride + N].fill(v);
221+ }
222+ }
223+ 2 => {
224+ let mut sum = 0i32;
225+ if have_top {
226+ for x in 0..N {
227+ sum += i32::from(w.data[o - stride + x]);
228+ }
229+ }
230+ if have_left {
231+ for y in 0..N {
232+ sum += i32::from(w.data[o + y * stride - 1]);
233+ }
234+ }
235+ let v = match (have_top, have_left) {
236+ (true, true) => (sum + (1 << (dc_shift - 1))) >> dc_shift,
237+ (true, false) | (false, true) => (sum + (1 << (dc_shift - 2))) >> (dc_shift - 1),
238+ (false, false) => 128,
239+ } as u8;
240+ for y in 0..N {
241+ w.data[o + y * stride..o + y * stride + N].fill(v);
242+ }
243+ }
244+ _ => {
245+ // Plane (8-122..8-127 / 8-144..8-149). half = N/2.
246+ let half = (N / 2) as i32;
247+ let px = |x: i32, y: i32| -> i32 {
248+ let idx = (o as i32 + y * stride as i32 + x) as usize;
249+ i32::from(w.data[idx])
250+ };
251+ let mut h = 0i32;
252+ let mut v = 0i32;
253+ for i in 0..half {
254+ h += (i + 1) * (px(half + i, -1) - px(half - 2 - i, -1));
255+ v += (i + 1) * (px(-1, half + i) - px(-1, half - 2 - i));
256+ }
257+ let a = 16 * (px(-1, N as i32 - 1) + px(N as i32 - 1, -1));
258+ let b = (plane_scale * h + 32) >> 6;
259+ let c = (plane_scale * v + 32) >> 6;
260+ for y in 0..N as i32 {
261+ for x in 0..N as i32 {
262+ let p = (a + b * (x - (half - 1)) + c * (y - (half - 1)) + 16) >> 5;
263+ w.data[o + y as usize * stride + x as usize] = p.clamp(0, 255) as u8;
264+ }
265+ }
266+ }
267+ }
268+}
269+
270+/// Chroma DC prediction (spec 8.3.4.1): each 4x4 sub-block averages specific
271+/// neighbour runs — corner blocks prefer their adjacent edge.
272+fn pred_chroma_dc(w: &mut PlaneWindow<'_>, have_top: bool, have_left: bool) {
273+ let stride = w.stride;
274+ let o = w.origin;
275+ let sum_top = |data: &[u8], x0: usize| -> i32 {
276+ (0..4).map(|i| i32::from(data[o - stride + x0 + i])).sum()
277+ };
278+ let sum_left = |data: &[u8], y0: usize| -> i32 {
279+ (0..4)
280+ .map(|i| i32::from(data[o + (y0 + i) * stride - 1]))
281+ .sum()
282+ };
283+ for by in 0..2 {
284+ for bx in 0..2 {
285+ // (0,0) and (1,1) use both edges; (1,0) prefers top; (0,1) left.
286+ let v = if bx == by {
287+ match (have_top, have_left) {
288+ (true, true) => (sum_top(w.data, bx * 4) + sum_left(w.data, by * 4) + 4) >> 3,
289+ (true, false) => (sum_top(w.data, bx * 4) + 2) >> 2,
290+ (false, true) => (sum_left(w.data, by * 4) + 2) >> 2,
291+ (false, false) => 128,
292+ }
293+ } else if bx == 1 {
294+ match (have_top, have_left) {
295+ (true, _) => (sum_top(w.data, 4) + 2) >> 2,
296+ (false, true) => (sum_left(w.data, 0) + 2) >> 2,
297+ (false, false) => 128,
298+ }
299+ } else {
300+ match (have_left, have_top) {
301+ (true, _) => (sum_left(w.data, 4) + 2) >> 2,
302+ (false, true) => (sum_top(w.data, 0) + 2) >> 2,
303+ (false, false) => 128,
304+ }
305+ } as u8;
306+ for y in 0..4 {
307+ let row = o + (by * 4 + y) * stride + bx * 4;
308+ w.data[row..row + 4].fill(v);
309+ }
310+ }
311+ }
312+}
313+
314+/// Add a 4x4 residual to the plane with clamping (picture construction,
315+/// spec 8.5.14 path for 8-bit).
316+#[inline]
317+pub fn add_residual_4x4(data: &mut [u8], stride: usize, origin: usize, r: &[i32; 16]) {
318+ for y in 0..4 {
319+ let row = origin + y * stride;
320+ for x in 0..4 {
321+ let p = i32::from(data[row + x]) + r[y * 4 + x];
322+ data[row + x] = p.clamp(0, 255) as u8;
323+ }
324+ }
325+}
326+
327+#[cfg(test)]
328+mod tests {
329+ use super::*;
330+
331+ #[test]
332+ fn dc_4x4_fallbacks() {
333+ let n = Nbr4 {
334+ top: [10; 8],
335+ left: [20; 4],
336+ top_left: 0,
337+ have_top: true,
338+ have_left: true,
339+ };
340+ let mut out = [0u8; 16];
341+ pred_4x4(2, &n, &mut out);
342+ assert!(out.iter().all(|&v| v == 15)); // (40 + 80 + 4) >> 3
343+ let n2 = Nbr4 {
344+ have_left: false,
345+ ..n
346+ };
347+ pred_4x4(2, &n2, &mut out);
348+ assert!(out.iter().all(|&v| v == 10));
349+ let n3 = Nbr4 {
350+ have_top: false,
351+ have_left: false,
352+ ..n
353+ };
354+ pred_4x4(2, &n3, &mut out);
355+ assert!(out.iter().all(|&v| v == 128));
356+ }
357+
358+ #[test]
359+ fn vertical_and_horizontal_4x4() {
360+ let n = Nbr4 {
361+ top: [1, 2, 3, 4, 5, 6, 7, 8],
362+ left: [9, 10, 11, 12],
363+ top_left: 0,
364+ have_top: true,
365+ have_left: true,
366+ };
367+ let mut out = [0u8; 16];
368+ pred_4x4(0, &n, &mut out);
369+ assert_eq!(&out[0..4], &[1, 2, 3, 4]);
370+ assert_eq!(&out[12..16], &[1, 2, 3, 4]);
371+ pred_4x4(1, &n, &mut out);
372+ assert_eq!(out[0], 9);
373+ assert_eq!(out[15], 12);
374+ }
375+
376+ /// Diagonal down-left of a constant edge stays constant; the (3,3)
377+ /// special tap agrees.
378+ #[test]
379+ fn ddl_constant_edge() {
380+ let n = Nbr4 {
381+ top: [50; 8],
382+ left: [0; 4],
383+ top_left: 0,
384+ have_top: true,
385+ have_left: false,
386+ };
387+ let mut out = [0u8; 16];
388+ pred_4x4(3, &n, &mut out);
389+ assert!(out.iter().all(|&v| v == 50));
390+ }
391+
392+ /// Plane prediction of a linear ramp reproduces the ramp.
393+ #[test]
394+ fn plane_16x16_ramp() {
395+ let stride = 24usize;
396+ let mut data = vec![0u8; stride * 24];
397+ // Fill neighbours: top row and left column of a 16x16 at (1, 1).
398+ let origin = stride + 1;
399+ for (x, d) in data.iter_mut().enumerate().take(17) {
400+ *d = (10 + 2 * x) as u8; // includes top-left at x=0
401+ }
402+ for y in 0..17 {
403+ data[y * stride] = (10 + 3 * y) as u8;
404+ }
405+ let mut w = PlaneWindow {
406+ data: &mut data,
407+ stride,
408+ origin,
409+ };
410+ pred_16x16(3, &mut w, true, true);
411+ // A perfect plane through those edges: value at (x, y) approximately
412+ // 12 + 2x + 3y. Check corners within rounding of the spec filter.
413+ let v = |x: usize, y: usize| i32::from(data[origin + y * stride + x]);
414+ assert!((v(0, 0) - 17).abs() <= 3, "{}", v(0, 0));
415+ assert!((v(15, 0) - (12 + 30)).abs() <= 3);
416+ assert!((v(0, 15) - (12 + 45)).abs() <= 3);
417+ assert!((v(15, 15) - (12 + 30 + 45)).abs() <= 3);
418+ }
419+
420+ #[test]
421+ fn chroma_dc_corner_preferences() {
422+ let stride = 16usize;
423+ let mut data = vec![0u8; stride * 16];
424+ let origin = stride + 1;
425+ // Top neighbours 40, left neighbours 80.
426+ for x in 0..8 {
427+ data[1 + x] = 40;
428+ }
429+ for y in 0..8 {
430+ data[(1 + y) * stride] = 80;
431+ }
432+ let mut w = PlaneWindow {
433+ data: &mut data,
434+ stride,
435+ origin,
436+ };
437+ pred_chroma_8x8(0, &mut w, true, true);
438+ let v = |x: usize, y: usize| data[origin + y * stride + x];
439+ assert_eq!(v(0, 0), 60); // both edges
440+ assert_eq!(v(7, 0), 40); // top preferred
441+ assert_eq!(v(0, 7), 80); // left preferred
442+ assert_eq!(v(7, 7), 60); // both edges
443+ }
444+
445+ #[test]
446+ fn add_residual_clamps() {
447+ let mut data = vec![250u8; 16];
448+ let mut r = [0i32; 16];
449+ r[0] = 100;
450+ r[1] = -300;
451+ add_residual_4x4(&mut data, 4, 0, &r);
452+ assert_eq!(data[0], 255);
453+ assert_eq!(data[1], 0);
454+ assert_eq!(data[2], 250);
455+ }
456+}
crates/ec-h264/src/tables.rsadded+653 -0
@@ -0,0 +1,653 @@
1+//! Constant tables transcribed from Rec. ITU-T H.264 (V15, 08/2024).
2+//!
3+//! Every table cites its spec number. VLC codes are stored as
4+//! `(len, code, value...)` with the code right-aligned in an integer; decoding
5+//! peeks 16 bits left-aligned and compares prefixes.
6+
7+/// One coeff_token entry: (code length, code, TotalCoeff, TrailingOnes).
8+pub type CoeffTokenEntry = (u8, u16, u8, u8);
9+
10+/// Table 9-5, column 0 <= nC < 2.
11+pub const COEFF_TOKEN_NC0: &[CoeffTokenEntry] = &[
12+ (1, 0b1, 0, 0),
13+ (2, 0b01, 1, 1),
14+ (3, 0b001, 2, 2),
15+ (5, 0b00011, 3, 3),
16+ (6, 0b000101, 1, 0),
17+ (6, 0b000100, 2, 1),
18+ (6, 0b000011, 4, 3),
19+ (7, 0b0000101, 3, 2),
20+ (7, 0b0000100, 5, 3),
21+ (8, 0b00000111, 2, 0),
22+ (8, 0b00000110, 3, 1),
23+ (8, 0b00000101, 4, 2),
24+ (8, 0b00000100, 6, 3),
25+ (9, 0b000000111, 3, 0),
26+ (9, 0b000000110, 4, 1),
27+ (9, 0b000000101, 5, 2),
28+ (9, 0b000000100, 7, 3),
29+ (10, 0b0000000111, 4, 0),
30+ (10, 0b0000000110, 5, 1),
31+ (10, 0b0000000101, 6, 2),
32+ (10, 0b0000000100, 8, 3),
33+ (11, 0b00000000111, 5, 0),
34+ (11, 0b00000000110, 6, 1),
35+ (11, 0b00000000101, 7, 2),
36+ (11, 0b00000000100, 9, 3),
37+ (13, 0b0000000001111, 6, 0),
38+ (13, 0b0000000001011, 7, 0),
39+ (13, 0b0000000001110, 7, 1),
40+ (13, 0b0000000001000, 8, 0),
41+ (13, 0b0000000001010, 8, 1),
42+ (13, 0b0000000001101, 8, 2),
43+ (13, 0b0000000001001, 9, 2),
44+ (13, 0b0000000001100, 10, 3),
45+ (14, 0b00000000001111, 9, 0),
46+ (14, 0b00000000001110, 9, 1),
47+ (14, 0b00000000001011, 10, 0),
48+ (14, 0b00000000001010, 10, 1),
49+ (14, 0b00000000001101, 10, 2),
50+ (14, 0b00000000001001, 11, 2),
51+ (14, 0b00000000001100, 11, 3),
52+ (14, 0b00000000001000, 12, 3),
53+ (15, 0b000000000001111, 11, 0),
54+ (15, 0b000000000001110, 11, 1),
55+ (15, 0b000000000001011, 12, 0),
56+ (15, 0b000000000001010, 12, 1),
57+ (15, 0b000000000001101, 12, 2),
58+ (15, 0b000000000000001, 13, 1),
59+ (15, 0b000000000001001, 13, 2),
60+ (15, 0b000000000001100, 13, 3),
61+ (15, 0b000000000001000, 14, 3),
62+ (16, 0b0000000000001111, 13, 0),
63+ (16, 0b0000000000001011, 14, 0),
64+ (16, 0b0000000000001110, 14, 1),
65+ (16, 0b0000000000001101, 14, 2),
66+ (16, 0b0000000000000111, 15, 0),
67+ (16, 0b0000000000001010, 15, 1),
68+ (16, 0b0000000000001001, 15, 2),
69+ (16, 0b0000000000001100, 15, 3),
70+ (16, 0b0000000000000100, 16, 0),
71+ (16, 0b0000000000000110, 16, 1),
72+ (16, 0b0000000000000101, 16, 2),
73+ (16, 0b0000000000001000, 16, 3),
74+];
75+
76+/// Table 9-5, column 2 <= nC < 4.
77+pub const COEFF_TOKEN_NC2: &[CoeffTokenEntry] = &[
78+ (2, 0b11, 0, 0),
79+ (2, 0b10, 1, 1),
80+ (3, 0b011, 2, 2),
81+ (4, 0b0101, 3, 3),
82+ (4, 0b0100, 4, 3),
83+ (5, 0b00111, 2, 1),
84+ (5, 0b00110, 5, 3),
85+ (6, 0b001011, 1, 0),
86+ (6, 0b000111, 2, 0),
87+ (6, 0b001010, 3, 1),
88+ (6, 0b001001, 3, 2),
89+ (6, 0b000110, 4, 1),
90+ (6, 0b000101, 4, 2),
91+ (6, 0b001000, 6, 3),
92+ (6, 0b000100, 7, 3),
93+ (7, 0b0000111, 3, 0),
94+ (7, 0b0000110, 5, 1),
95+ (7, 0b0000101, 5, 2),
96+ (7, 0b0000100, 8, 3),
97+ (8, 0b00000111, 4, 0),
98+ (8, 0b00000100, 5, 0),
99+ (8, 0b00000110, 6, 1),
100+ (8, 0b00000101, 6, 2),
101+ (9, 0b000000111, 6, 0),
102+ (9, 0b000000110, 7, 1),
103+ (9, 0b000000101, 7, 2),
104+ (9, 0b000000100, 9, 3),
105+ (11, 0b00000001111, 7, 0),
106+ (11, 0b00000001011, 8, 0),
107+ (11, 0b00000001110, 8, 1),
108+ (11, 0b00000001101, 8, 2),
109+ (11, 0b00000001010, 9, 1),
110+ (11, 0b00000001001, 9, 2),
111+ (11, 0b00000001100, 10, 3),
112+ (11, 0b00000001000, 11, 3),
113+ (12, 0b000000001111, 9, 0),
114+ (12, 0b000000001011, 10, 0),
115+ (12, 0b000000001110, 10, 1),
116+ (12, 0b000000001101, 10, 2),
117+ (12, 0b000000001000, 11, 0),
118+ (12, 0b000000001010, 11, 1),
119+ (12, 0b000000001001, 11, 2),
120+ (12, 0b000000001100, 12, 3),
121+ (13, 0b0000000001111, 12, 0),
122+ (13, 0b0000000001110, 12, 1),
123+ (13, 0b0000000001101, 12, 2),
124+ (13, 0b0000000001011, 13, 0),
125+ (13, 0b0000000001010, 13, 1),
126+ (13, 0b0000000001001, 13, 2),
127+ (13, 0b0000000001100, 13, 3),
128+ (13, 0b0000000000111, 14, 0),
129+ (13, 0b0000000000110, 14, 2),
130+ (13, 0b0000000001000, 14, 3),
131+ (13, 0b0000000000001, 15, 3),
132+ (14, 0b00000000001011, 14, 1),
133+ (14, 0b00000000001001, 15, 0),
134+ (14, 0b00000000001000, 15, 1),
135+ (14, 0b00000000001010, 15, 2),
136+ (14, 0b00000000000111, 16, 0),
137+ (14, 0b00000000000110, 16, 1),
138+ (14, 0b00000000000101, 16, 2),
139+ (14, 0b00000000000100, 16, 3),
140+];
141+
142+/// Table 9-5, column 4 <= nC < 8.
143+pub const COEFF_TOKEN_NC4: &[CoeffTokenEntry] = &[
144+ (4, 0b1111, 0, 0),
145+ (4, 0b1110, 1, 1),
146+ (4, 0b1101, 2, 2),
147+ (4, 0b1100, 3, 3),
148+ (4, 0b1011, 4, 3),
149+ (4, 0b1010, 5, 3),
150+ (4, 0b1001, 6, 3),
151+ (4, 0b1000, 7, 3),
152+ (5, 0b01111, 2, 1),
153+ (5, 0b01100, 3, 1),
154+ (5, 0b01110, 3, 2),
155+ (5, 0b01010, 4, 1),
156+ (5, 0b01011, 4, 2),
157+ (5, 0b01000, 5, 1),
158+ (5, 0b01001, 5, 2),
159+ (5, 0b01101, 8, 3),
160+ (6, 0b001111, 1, 0),
161+ (6, 0b001011, 2, 0),
162+ (6, 0b001000, 3, 0),
163+ (6, 0b001110, 6, 1),
164+ (6, 0b001101, 6, 2),
165+ (6, 0b001010, 7, 1),
166+ (6, 0b001001, 7, 2),
167+ (6, 0b001100, 9, 3),
168+ (7, 0b0001111, 4, 0),
169+ (7, 0b0001011, 5, 0),
170+ (7, 0b0001001, 6, 0),
171+ (7, 0b0001000, 7, 0),
172+ (7, 0b0001110, 8, 1),
173+ (7, 0b0001101, 8, 2),
174+ (7, 0b0001010, 9, 2),
175+ (7, 0b0001100, 10, 3),
176+ (8, 0b00001111, 8, 0),
177+ (8, 0b00001011, 9, 0),
178+ (8, 0b00001110, 9, 1),
179+ (8, 0b00001010, 10, 1),
180+ (8, 0b00001101, 10, 2),
181+ (8, 0b00001001, 11, 2),
182+ (8, 0b00001100, 11, 3),
183+ (8, 0b00001000, 12, 3),
184+ (9, 0b000001111, 10, 0),
185+ (9, 0b000001011, 11, 0),
186+ (9, 0b000001110, 11, 1),
187+ (9, 0b000001000, 12, 0),
188+ (9, 0b000001010, 12, 1),
189+ (9, 0b000001101, 12, 2),
190+ (9, 0b000000111, 13, 1),
191+ (9, 0b000001001, 13, 2),
192+ (9, 0b000001100, 13, 3),
193+ (10, 0b0000001101, 13, 0),
194+ (10, 0b0000001001, 14, 0),
195+ (10, 0b0000001100, 14, 1),
196+ (10, 0b0000001011, 14, 2),
197+ (10, 0b0000001010, 14, 3),
198+ (10, 0b0000000101, 15, 0),
199+ (10, 0b0000001000, 15, 1),
200+ (10, 0b0000000111, 15, 2),
201+ (10, 0b0000000110, 15, 3),
202+ (10, 0b0000000001, 16, 0),
203+ (10, 0b0000000100, 16, 1),
204+ (10, 0b0000000011, 16, 2),
205+ (10, 0b0000000010, 16, 3),
206+];
207+
208+/// Table 9-5, column nC == -1 (chroma DC, 4:2:0).
209+pub const COEFF_TOKEN_CHROMA_DC: &[CoeffTokenEntry] = &[
210+ (1, 0b1, 1, 1),
211+ (2, 0b01, 0, 0),
212+ (3, 0b001, 2, 2),
213+ (6, 0b000111, 1, 0),
214+ (6, 0b000100, 2, 0),
215+ (6, 0b000110, 2, 1),
216+ (6, 0b000011, 3, 0),
217+ (6, 0b000101, 3, 3),
218+ (6, 0b000010, 4, 0),
219+ (7, 0b0000011, 3, 1),
220+ (7, 0b0000010, 3, 2),
221+ (7, 0b0000000, 4, 3),
222+ (8, 0b00000011, 4, 1),
223+ (8, 0b00000010, 4, 2),
224+];
225+
226+/// One total_zeros / run_before entry: (code length, code, value).
227+pub type VlcEntry = (u8, u16, u8);
228+
229+/// Tables 9-7 and 9-8: total_zeros for 4x4 blocks, indexed by
230+/// `tzVlcIndex - 1` (tzVlcIndex = TotalCoeff, 1..=15).
231+pub const TOTAL_ZEROS_4X4: [&[VlcEntry]; 15] = [
232+ // tzVlcIndex 1
233+ &[
234+ (1, 0b1, 0),
235+ (3, 0b011, 1),
236+ (3, 0b010, 2),
237+ (4, 0b0011, 3),
238+ (4, 0b0010, 4),
239+ (5, 0b00011, 5),
240+ (5, 0b00010, 6),
241+ (6, 0b000011, 7),
242+ (6, 0b000010, 8),
243+ (7, 0b0000011, 9),
244+ (7, 0b0000010, 10),
245+ (8, 0b00000011, 11),
246+ (8, 0b00000010, 12),
247+ (9, 0b000000011, 13),
248+ (9, 0b000000010, 14),
249+ (9, 0b000000001, 15),
250+ ],
251+ // tzVlcIndex 2
252+ &[
253+ (3, 0b111, 0),
254+ (3, 0b110, 1),
255+ (3, 0b101, 2),
256+ (3, 0b100, 3),
257+ (3, 0b011, 4),
258+ (4, 0b0101, 5),
259+ (4, 0b0100, 6),
260+ (4, 0b0011, 7),
261+ (4, 0b0010, 8),
262+ (5, 0b00011, 9),
263+ (5, 0b00010, 10),
264+ (6, 0b000011, 11),
265+ (6, 0b000010, 12),
266+ (6, 0b000001, 13),
267+ (6, 0b000000, 14),
268+ ],
269+ // tzVlcIndex 3
270+ &[
271+ (4, 0b0101, 0),
272+ (3, 0b111, 1),
273+ (3, 0b110, 2),
274+ (3, 0b101, 3),
275+ (4, 0b0100, 4),
276+ (4, 0b0011, 5),
277+ (3, 0b100, 6),
278+ (3, 0b011, 7),
279+ (4, 0b0010, 8),
280+ (5, 0b00011, 9),
281+ (5, 0b00010, 10),
282+ (6, 0b000001, 11),
283+ (5, 0b00001, 12),
284+ (6, 0b000000, 13),
285+ ],
286+ // tzVlcIndex 4
287+ &[
288+ (5, 0b00011, 0),
289+ (3, 0b111, 1),
290+ (4, 0b0101, 2),
291+ (4, 0b0100, 3),
292+ (3, 0b110, 4),
293+ (3, 0b101, 5),
294+ (3, 0b100, 6),
295+ (4, 0b0011, 7),
296+ (3, 0b011, 8),
297+ (4, 0b0010, 9),
298+ (5, 0b00010, 10),
299+ (5, 0b00001, 11),
300+ (5, 0b00000, 12),
301+ ],
302+ // tzVlcIndex 5
303+ &[
304+ (4, 0b0101, 0),
305+ (4, 0b0100, 1),
306+ (4, 0b0011, 2),
307+ (3, 0b111, 3),
308+ (3, 0b110, 4),
309+ (3, 0b101, 5),
310+ (3, 0b100, 6),
311+ (3, 0b011, 7),
312+ (4, 0b0010, 8),
313+ (5, 0b00001, 9),
314+ (4, 0b0001, 10),
315+ (5, 0b00000, 11),
316+ ],
317+ // tzVlcIndex 6
318+ &[
319+ (6, 0b000001, 0),
320+ (5, 0b00001, 1),
321+ (3, 0b111, 2),
322+ (3, 0b110, 3),
323+ (3, 0b101, 4),
324+ (3, 0b100, 5),
325+ (3, 0b011, 6),
326+ (3, 0b010, 7),
327+ (4, 0b0001, 8),
328+ (3, 0b001, 9),
329+ (6, 0b000000, 10),
330+ ],
331+ // tzVlcIndex 7
332+ &[
333+ (6, 0b000001, 0),
334+ (5, 0b00001, 1),
335+ (3, 0b101, 2),
336+ (3, 0b100, 3),
337+ (3, 0b011, 4),
338+ (2, 0b11, 5),
339+ (3, 0b010, 6),
340+ (4, 0b0001, 7),
341+ (3, 0b001, 8),
342+ (6, 0b000000, 9),
343+ ],
344+ // tzVlcIndex 8
345+ &[
346+ (6, 0b000001, 0),
347+ (4, 0b0001, 1),
348+ (5, 0b00001, 2),
349+ (3, 0b011, 3),
350+ (2, 0b11, 4),
351+ (2, 0b10, 5),
352+ (3, 0b010, 6),
353+ (3, 0b001, 7),
354+ (6, 0b000000, 8),
355+ ],
356+ // tzVlcIndex 9
357+ &[
358+ (6, 0b000001, 0),
359+ (6, 0b000000, 1),
360+ (4, 0b0001, 2),
361+ (2, 0b11, 3),
362+ (2, 0b10, 4),
363+ (3, 0b001, 5),
364+ (2, 0b01, 6),
365+ (5, 0b00001, 7),
366+ ],
367+ // tzVlcIndex 10
368+ &[
369+ (5, 0b00001, 0),
370+ (5, 0b00000, 1),
371+ (3, 0b001, 2),
372+ (2, 0b11, 3),
373+ (2, 0b10, 4),
374+ (2, 0b01, 5),
375+ (4, 0b0001, 6),
376+ ],
377+ // tzVlcIndex 11
378+ &[
379+ (4, 0b0000, 0),
380+ (4, 0b0001, 1),
381+ (3, 0b001, 2),
382+ (3, 0b010, 3),
383+ (1, 0b1, 4),
384+ (3, 0b011, 5),
385+ ],
386+ // tzVlcIndex 12
387+ &[
388+ (4, 0b0000, 0),
389+ (4, 0b0001, 1),
390+ (2, 0b01, 2),
391+ (1, 0b1, 3),
392+ (3, 0b001, 4),
393+ ],
394+ // tzVlcIndex 13
395+ &[(3, 0b000, 0), (3, 0b001, 1), (1, 0b1, 2), (2, 0b01, 3)],
396+ // tzVlcIndex 14
397+ &[(2, 0b00, 0), (2, 0b01, 1), (1, 0b1, 2)],
398+ // tzVlcIndex 15
399+ &[(1, 0b0, 0), (1, 0b1, 1)],
400+];
401+
402+/// Table 9-9 (a): total_zeros for chroma DC 2x2 (4:2:0), by tzVlcIndex 1..=3.
403+pub const TOTAL_ZEROS_CHROMA_DC: [&[VlcEntry]; 3] = [
404+ &[(1, 0b1, 0), (2, 0b01, 1), (3, 0b001, 2), (3, 0b000, 3)],
405+ &[(1, 0b1, 0), (2, 0b01, 1), (2, 0b00, 2)],
406+ &[(1, 0b1, 0), (1, 0b0, 1)],
407+];
408+
409+/// Table 9-10: run_before, indexed by min(zerosLeft, 7) - 1.
410+pub const RUN_BEFORE: [&[VlcEntry]; 7] = [
411+ // zerosLeft 1
412+ &[(1, 0b1, 0), (1, 0b0, 1)],
413+ // zerosLeft 2
414+ &[(1, 0b1, 0), (2, 0b01, 1), (2, 0b00, 2)],
415+ // zerosLeft 3
416+ &[(2, 0b11, 0), (2, 0b10, 1), (2, 0b01, 2), (2, 0b00, 3)],
417+ // zerosLeft 4
418+ &[
419+ (2, 0b11, 0),
420+ (2, 0b10, 1),
421+ (2, 0b01, 2),
422+ (3, 0b001, 3),
423+ (3, 0b000, 4),
424+ ],
425+ // zerosLeft 5
426+ &[
427+ (2, 0b11, 0),
428+ (2, 0b10, 1),
429+ (3, 0b011, 2),
430+ (3, 0b010, 3),
431+ (3, 0b001, 4),
432+ (3, 0b000, 5),
433+ ],
434+ // zerosLeft 6
435+ &[
436+ (2, 0b11, 0),
437+ (3, 0b000, 1),
438+ (3, 0b001, 2),
439+ (3, 0b011, 3),
440+ (3, 0b010, 4),
441+ (3, 0b101, 5),
442+ (3, 0b100, 6),
443+ ],
444+ // zerosLeft > 6
445+ &[
446+ (3, 0b111, 0),
447+ (3, 0b110, 1),
448+ (3, 0b101, 2),
449+ (3, 0b100, 3),
450+ (3, 0b011, 4),
451+ (3, 0b010, 5),
452+ (3, 0b001, 6),
453+ (4, 0b0001, 7),
454+ (5, 0b00001, 8),
455+ (6, 0b000001, 9),
456+ (7, 0b0000001, 10),
457+ (8, 0b00000001, 11),
458+ (9, 0b000000001, 12),
459+ (10, 0b0000000001, 13),
460+ (11, 0b00000000001, 14),
461+ ],
462+];
463+
464+/// Table 9-4 (a), Intra_4x4/Intra_8x8 column: codeNum -> coded_block_pattern
465+/// for ChromaArrayType 1 or 2.
466+pub const CBP_INTRA_420: [u8; 48] = [
467+ 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,
468+ 35, 37, 42, 44, 1, 2, 4, 8, 17, 18, 20, 24, 6, 9, 22, 25, 32, 33, 34, 36, 40, 38, 41,
469+];
470+
471+/// Table 9-4 (b), Intra column: codeNum -> coded_block_pattern for
472+/// ChromaArrayType 0 or 3. Unused until monochrome / 4:4:4 decode lands;
473+/// kept beside its sibling so the spec table lives in one place.
474+#[allow(dead_code)]
475+pub const CBP_INTRA_MONO: [u8; 16] = [15, 0, 7, 11, 13, 14, 3, 5, 10, 12, 1, 2, 4, 8, 6, 9];
476+
477+/// Table 8-15: QPC as a function of qPI (identity below 30).
478+pub const CHROMA_QP: [u8; 52] = [
479+ 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,
480+ 26, 27, 28, 29, 29, 30, 31, 32, 32, 33, 34, 34, 35, 35, 36, 36, 37, 37, 37, 38, 38, 38, 39, 39,
481+ 39, 39,
482+];
483+
484+/// Equation 8-315: normAdjust4x4 v matrix, rows m = qP % 6, columns the three
485+/// position classes (0: both even, 1: both odd, 2: mixed).
486+pub const NORM_ADJUST_4X4: [[u16; 3]; 6] = [
487+ [10, 16, 13],
488+ [11, 18, 14],
489+ [13, 20, 16],
490+ [14, 23, 18],
491+ [16, 25, 20],
492+ [18, 29, 23],
493+];
494+
495+/// Position class per raster index of a 4x4 block, for [`NORM_ADJUST_4X4`]:
496+/// (i % 2, j % 2) == (0,0) -> 0, (1,1) -> 1, else 2 (Equation 8-314).
497+pub const NORM_ADJUST_CLASS_4X4: [u8; 16] = [0, 2, 0, 2, 2, 1, 2, 1, 0, 2, 0, 2, 2, 1, 2, 1];
498+
499+/// Table 8-16: alpha' by indexA.
500+pub const ALPHA: [u8; 52] = [
501+ 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,
502+ 22, 25, 28, 32, 36, 40, 45, 50, 56, 63, 71, 80, 90, 101, 113, 127, 144, 162, 182, 203, 226,
503+ 255, 255,
504+];
505+
506+/// Table 8-16: beta' by indexB.
507+pub const BETA: [u8; 52] = [
508+ 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,
509+ 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18,
510+];
511+
512+/// Table 8-17: tC0' by [bS - 1][indexA].
513+pub const TC0: [[u8; 52]; 3] = [
514+ [
515+ 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,
516+ 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 6, 6, 7, 8,
517+ ],
518+ [
519+ 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,
520+ 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 5, 5, 6, 7, 8, 8, 10, 11, 12, 13, 15,
521+ ],
522+ [
523+ 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,
524+ 2, 3, 3, 3, 4, 4, 4, 5, 6, 6, 7, 8, 9, 10, 11, 13, 14, 16, 18, 20, 23, 25,
525+ ],
526+];
527+
528+/// 4x4 zig-zag scan: scan position -> raster index (Table 8-13, frame scan).
529+pub const ZIGZAG_4X4: [u8; 16] = [0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15];
530+
531+/// luma4x4BlkIdx -> (x, y) position in 4-sample units within the macroblock
532+/// (spec 6.4.3 inverse 4x4 luma block scan).
533+pub const BLK4_POS: [(u8, u8); 16] = [
534+ (0, 0),
535+ (1, 0),
536+ (0, 1),
537+ (1, 1),
538+ (2, 0),
539+ (3, 0),
540+ (2, 1),
541+ (3, 1),
542+ (0, 2),
543+ (1, 2),
544+ (0, 3),
545+ (1, 3),
546+ (2, 2),
547+ (3, 2),
548+ (2, 3),
549+ (3, 3),
550+];
551+
552+#[cfg(test)]
553+mod tests {
554+ use super::*;
555+
556+ /// Every VLC class must be prefix-free: no code may be a prefix of
557+ /// another. A transcription slip in Table 9-5 would show up here first.
558+ fn assert_prefix_free(name: &str, codes: &[(u8, u16)]) {
559+ for (i, &(la, ca)) in codes.iter().enumerate() {
560+ for &(lb, cb) in codes.iter().skip(i + 1) {
561+ let (ls, cs, ll, cl) = if la <= lb {
562+ (la, ca, lb, cb)
563+ } else {
564+ (lb, cb, la, ca)
565+ };
566+ assert!(
567+ cl >> (ll - ls) != cs,
568+ "{name}: code {cs:0ls$b} is a prefix of {cl:0ll$b}",
569+ ls = ls as usize,
570+ ll = ll as usize,
571+ );
572+ }
573+ }
574+ }
575+
576+ /// Kraft sum of a prefix code: must never exceed 1; the spec's tables
577+ /// leave only long all-zero prefixes unused, so it also stays close to 1.
578+ fn assert_kraft(name: &str, codes: &[(u8, u16)]) {
579+ let sum: f64 = codes.iter().map(|&(l, _)| (0.5f64).powi(l as i32)).sum();
580+ assert!(sum <= 1.0 + 1e-12, "{name}: Kraft sum {sum} > 1");
581+ assert!(sum > 0.99, "{name}: Kraft sum {sum} implausibly low");
582+ }
583+
584+ #[test]
585+ fn coeff_token_tables_prefix_free_and_complete() {
586+ for (name, table) in [
587+ ("nc0", COEFF_TOKEN_NC0),
588+ ("nc2", COEFF_TOKEN_NC2),
589+ ("nc4", COEFF_TOKEN_NC4),
590+ ("chroma-dc", COEFF_TOKEN_CHROMA_DC),
591+ ] {
592+ let codes: Vec<(u8, u16)> = table.iter().map(|&(l, c, _, _)| (l, c)).collect();
593+ assert_prefix_free(name, &codes);
594+ assert_eq!(table.len(), if name == "chroma-dc" { 14 } else { 62 });
595+ // All (tc, t1) pairs distinct.
596+ let mut pairs: Vec<(u8, u8)> = table.iter().map(|&(_, _, tc, t1)| (tc, t1)).collect();
597+ pairs.sort_unstable();
598+ pairs.dedup();
599+ assert_eq!(pairs.len(), table.len(), "{name}: duplicate (tc, t1)");
600+ assert_kraft(name, &codes);
601+ }
602+ }
603+
604+ #[test]
605+ fn total_zeros_and_run_before_prefix_free_and_complete() {
606+ for (i, table) in TOTAL_ZEROS_4X4.iter().enumerate() {
607+ let codes: Vec<(u8, u16)> = table.iter().map(|&(l, c, _)| (l, c)).collect();
608+ assert_prefix_free("total_zeros", &codes);
609+ // tzVlcIndex = i+1 admits total_zeros 0..=16-(i+1).
610+ assert_eq!(table.len(), 16 - i, "tzVlcIndex {}", i + 1);
611+ let mut vals: Vec<u8> = table.iter().map(|&(_, _, v)| v).collect();
612+ vals.sort_unstable();
613+ assert_eq!(vals, (0..=(15 - i) as u8).collect::<Vec<_>>());
614+ assert_kraft("total_zeros", &codes);
615+ }
616+ for table in &TOTAL_ZEROS_CHROMA_DC {
617+ let codes: Vec<(u8, u16)> = table.iter().map(|&(l, c, _)| (l, c)).collect();
618+ assert_prefix_free("total_zeros_chroma", &codes);
619+ assert_kraft("total_zeros_chroma", &codes);
620+ }
621+ for (zl, table) in RUN_BEFORE.iter().enumerate() {
622+ let codes: Vec<(u8, u16)> = table.iter().map(|&(l, c, _)| (l, c)).collect();
623+ assert_prefix_free("run_before", &codes);
624+ if zl < 6 {
625+ assert_eq!(table.len(), zl + 2);
626+ }
627+ assert_kraft("run_before", &codes);
628+ }
629+ }
630+
631+ #[test]
632+ fn cbp_tables_are_permutations() {
633+ let mut v = CBP_INTRA_420.to_vec();
634+ v.sort_unstable();
635+ assert_eq!(v, (0..48).collect::<Vec<u8>>());
636+ let mut v = CBP_INTRA_MONO.to_vec();
637+ v.sort_unstable();
638+ assert_eq!(v, (0..16).collect::<Vec<u8>>());
639+ }
640+
641+ #[test]
642+ fn zigzag_is_permutation_and_deblock_tables_sized() {
643+ let mut v = ZIGZAG_4X4.to_vec();
644+ v.sort_unstable();
645+ assert_eq!(v, (0..16).collect::<Vec<u8>>());
646+ assert_eq!(CHROMA_QP[29], 29);
647+ assert_eq!(CHROMA_QP[30], 29);
648+ assert_eq!(CHROMA_QP[51], 39);
649+ assert_eq!(ALPHA[16], 4);
650+ assert_eq!(BETA[51], 18);
651+ assert_eq!(TC0[2][51], 25);
652+ }
653+}
crates/ec-h264/src/transform.rsadded+226 -0
@@ -0,0 +1,226 @@
1+//! Inverse transforms and scaling (spec 8.5.9 - 8.5.12).
2+
3+use crate::tables::{NORM_ADJUST_4X4, NORM_ADJUST_CLASS_4X4, ZIGZAG_4X4};
4+
5+/// Per-QP scaling factors for one 4x4 weight list: `LevelScale4x4(m, i, j) =
6+/// weightScale(i, j) * normAdjust4x4(m, i, j)` (Equation 8-313), in raster
7+/// order, for m = qP % 6.
8+///
9+/// Built once per parameter-set activation; the decode loop indexes it flat.
10+#[derive(Debug, Clone)]
11+pub struct LevelScale4x4 {
12+ /// `[m][raster]`.
13+ pub scale: [[i32; 16]; 6],
14+}
15+
16+impl LevelScale4x4 {
17+ /// Build from a raster-order weight list (flat 16s when no scaling matrix).
18+ pub fn new(weight: &[u8; 16]) -> LevelScale4x4 {
19+ let mut scale = [[0i32; 16]; 6];
20+ for (m, row) in scale.iter_mut().enumerate() {
21+ for (idx, s) in row.iter_mut().enumerate() {
22+ let class = NORM_ADJUST_CLASS_4X4[idx] as usize;
23+ *s = i32::from(weight[idx]) * i32::from(NORM_ADJUST_4X4[m][class]);
24+ }
25+ }
26+ LevelScale4x4 { scale }
27+ }
28+}
29+
30+/// Scale AC/luma-4x4 coefficients in place (spec 8.5.12.1): `block` is in
31+/// raster order. `skip_dc` is true for Intra_16x16 luma AC and chroma AC
32+/// blocks whose DC came through the separate DC path (d00 = c00 untouched).
33+#[inline]
34+pub fn dequant_4x4(block: &mut [i32; 16], ls: &LevelScale4x4, qp: i32, skip_dc: bool) {
35+ let m = (qp % 6) as usize;
36+ let shift = qp / 6;
37+ let scale = &ls.scale[m];
38+ let start = usize::from(skip_dc);
39+ if shift >= 4 {
40+ let sh = (shift - 4) as u32;
41+ for i in start..16 {
42+ block[i] = (block[i] * scale[i]) << sh;
43+ }
44+ } else {
45+ let sh = (4 - shift) as u32;
46+ let round = 1i32 << (3 - shift);
47+ for i in start..16 {
48+ block[i] = (block[i] * scale[i] + round) >> sh;
49+ }
50+ }
51+}
52+
53+/// Place scan-order coefficients into raster order using the 4x4 zig-zag.
54+#[inline]
55+pub fn unzigzag(scan: &[i32; 16], out: &mut [i32; 16]) {
56+ for (s, &raster) in ZIGZAG_4X4.iter().enumerate() {
57+ out[raster as usize] = scan[s];
58+ }
59+}
60+
61+/// Un-zigzag a 15-coefficient AC block (Intra_16x16 luma AC / chroma AC):
62+/// scan position `k` maps to zig-zag position `k + 1`; the DC slot is
63+/// cleared for the caller to fill from the separate DC path.
64+#[inline]
65+pub fn unzigzag_ac15(scan: &[i32; 16], out: &mut [i32; 16]) {
66+ out[0] = 0;
67+ for k in 0..15 {
68+ out[ZIGZAG_4X4[k + 1] as usize] = scan[k];
69+ }
70+}
71+
72+/// Inverse 4x4 core transform (spec 8.5.12.2): raster-order input `d`,
73+/// output residuals `r` including the final `(x + 32) >> 6`.
74+#[inline]
75+pub fn inverse_transform_4x4(d: &[i32; 16], r: &mut [i32; 16]) {
76+ // Horizontal (each row).
77+ let mut e = [0i32; 16];
78+ for i in 0..4 {
79+ let o = i * 4;
80+ let (d0, d1, d2, d3) = (d[o], d[o + 1], d[o + 2], d[o + 3]);
81+ let e0 = d0 + d2;
82+ let e1 = d0 - d2;
83+ let e2 = (d1 >> 1) - d3;
84+ let e3 = d1 + (d3 >> 1);
85+ e[o] = e0 + e3;
86+ e[o + 1] = e1 + e2;
87+ e[o + 2] = e1 - e2;
88+ e[o + 3] = e0 - e3;
89+ }
90+ // Vertical (each column) + rounding.
91+ for j in 0..4 {
92+ let (g0, g1, g2, g3) = (e[j], e[4 + j], e[8 + j], e[12 + j]);
93+ let h0 = g0 + g2;
94+ let h1 = g0 - g2;
95+ let h2 = (g1 >> 1) - g3;
96+ let h3 = g1 + (g3 >> 1);
97+ r[j] = (h0 + h3 + 32) >> 6;
98+ r[4 + j] = (h1 + h2 + 32) >> 6;
99+ r[8 + j] = (h1 - h2 + 32) >> 6;
100+ r[12 + j] = (h0 - h3 + 32) >> 6;
101+ }
102+}
103+
104+/// Intra_16x16 luma DC: 4x4 Hadamard + scaling (spec 8.5.10). `c` is the DC
105+/// coefficient array in raster order (dc of block (bx, by) at `by * 4 + bx`);
106+/// output overwrites it.
107+pub fn luma_dc_transform(c: &mut [i32; 16], ls: &LevelScale4x4, qp: i32) {
108+ // Hadamard rows then columns (Equation 8-320).
109+ let mut f = [0i32; 16];
110+ for i in 0..4 {
111+ let o = i * 4;
112+ let (a, b, cc, d) = (c[o], c[o + 1], c[o + 2], c[o + 3]);
113+ f[o] = a + b + cc + d;
114+ f[o + 1] = a + b - cc - d;
115+ f[o + 2] = a - b - cc + d;
116+ f[o + 3] = a - b + cc - d;
117+ }
118+ let mut g = [0i32; 16];
119+ for j in 0..4 {
120+ let (a, b, cc, d) = (f[j], f[4 + j], f[8 + j], f[12 + j]);
121+ g[j] = a + b + cc + d;
122+ g[4 + j] = a + b - cc - d;
123+ g[8 + j] = a - b - cc + d;
124+ g[12 + j] = a - b + cc - d;
125+ }
126+ let scale = ls.scale[(qp % 6) as usize][0];
127+ if qp >= 36 {
128+ let sh = (qp / 6 - 6) as u32;
129+ for (o, &v) in c.iter_mut().zip(&g) {
130+ *o = (v * scale) << sh;
131+ }
132+ } else {
133+ let sh = (6 - qp / 6) as u32;
134+ let round = 1i32 << (5 - qp / 6);
135+ for (o, &v) in c.iter_mut().zip(&g) {
136+ *o = (v * scale + round) >> sh;
137+ }
138+ }
139+}
140+
141+/// Chroma DC for 4:2:0: 2x2 Hadamard + scaling (spec 8.5.11). `c` holds the
142+/// four DC levels in raster order of the chroma 4x4 blocks; overwritten with
143+/// the scaled DC values.
144+pub fn chroma_dc_transform_420(c: &mut [i32; 4], ls: &LevelScale4x4, qp: i32) {
145+ let (c00, c01, c10, c11) = (c[0], c[1], c[2], c[3]);
146+ let f = [
147+ c00 + c01 + c10 + c11,
148+ c00 - c01 + c10 - c11,
149+ c00 + c01 - c10 - c11,
150+ c00 - c01 - c10 + c11,
151+ ];
152+ let scale = ls.scale[(qp % 6) as usize][0];
153+ let sh = (qp / 6) as u32;
154+ for (o, &v) in c.iter_mut().zip(&f) {
155+ *o = ((v * scale) << sh) >> 5;
156+ }
157+}
158+
159+#[cfg(test)]
160+mod tests {
161+ use super::*;
162+
163+ fn flat_ls() -> LevelScale4x4 {
164+ LevelScale4x4::new(&[16; 16])
165+ }
166+
167+ /// A pure DC level reconstructs to a flat block whose value follows the
168+ /// dequant ladder: doubling every 6 QP steps.
169+ #[test]
170+ fn dc_only_block_flat_and_qp_ladder() {
171+ let ls = flat_ls();
172+ let recon = |qp: i32, level: i32| -> i32 {
173+ let mut block = [0i32; 16];
174+ block[0] = level;
175+ dequant_4x4(&mut block, &ls, qp, false);
176+ let mut r = [0i32; 16];
177+ inverse_transform_4x4(&block.clone(), &mut r);
178+ assert!(r.iter().all(|&x| x == r[0]), "DC block must be flat");
179+ r[0]
180+ };
181+ // LevelScale(m = 0, 0, 0) = 16 * 10 = 160. qp 24: d00 = 160 << 0.
182+ // A DC-only block comes out flat at (d00 + 32) >> 6.
183+ assert_eq!(recon(24, 1), (160 + 32) >> 6);
184+ assert_eq!(recon(30, 1), (320 + 32) >> 6);
185+ assert_eq!(recon(36, 1), (640 + 32) >> 6);
186+ assert_eq!(recon(24, -3), (-480 + 32) >> 6); // floor shift: -7
187+ }
188+
189+ /// The inverse transform of zeros is zero, and rounding is symmetric
190+ /// enough that a lone +1/-1 AC level stays bounded.
191+ #[test]
192+ fn zero_in_zero_out_and_unzigzag() {
193+ let mut r = [7i32; 16];
194+ inverse_transform_4x4(&[0; 16], &mut r);
195+ assert_eq!(r, [0; 16]);
196+
197+ let mut scan = [0i32; 16];
198+ scan[1] = 5; // second scan position = raster (0,1)
199+ let mut raster = [0i32; 16];
200+ unzigzag(&scan, &mut raster);
201+ assert_eq!(raster[1], 5);
202+ assert_eq!(raster.iter().filter(|&&x| x != 0).count(), 1);
203+ }
204+
205+ /// Luma DC Hadamard of a single coefficient spreads evenly; scaling per
206+ /// 8.5.10 with qp < 36 uses the rounding shift.
207+ #[test]
208+ fn luma_dc_spread() {
209+ let ls = flat_ls();
210+ let mut c = [0i32; 16];
211+ c[0] = 8;
212+ luma_dc_transform(&mut c, &ls, 28);
213+ // f = 8 everywhere; scale = LevelScale(28 % 6 = 4, 0, 0) = 16 * 16.
214+ let expected = (8 * 16 * 16 + (1 << (5 - 28 / 6))) >> (6 - 28 / 6);
215+ assert!(c.iter().all(|&x| x == expected));
216+ }
217+
218+ #[test]
219+ fn chroma_dc_hadamard() {
220+ let ls = flat_ls();
221+ let mut c = [4, 0, 0, 0];
222+ chroma_dc_transform_420(&mut c, &ls, 30);
223+ // f = [4,4,4,4]; scale = LS(0,0,0) = 160; ((4 * 160) << 5) >> 5 = 640.
224+ assert!(c.iter().all(|&x| x == 640), "{c:?}");
225+ }
226+}
crates/ec-h264/tests/conformance.rsadded+415 -0
@@ -0,0 +1,415 @@
1+//! JVT conformance: first IDR picture, bit-exact.
2+//!
3+//! Fixture-gated like tools/oracle: fixtures/ is gitignored, so a checkout
4+//! without `scripts/fetch-vectors.sh` skips loudly instead of failing.
5+//!
6+//! Oracles, in order of authority:
7+//! 1. The reference decoder YUV that ships with each JVT vector (first
8+//! frame) — ffmpeg-independent.
9+//! 2. `ffmpeg -i <stream> -frames:v 1` raw output, cross-checked when the
10+//! binary is present.
11+//!
12+//! The same binary hosts the zero-allocation proof and the ns/MB
13+//! measurement so the crate keeps a single integration-test link unit.
14+
15+use std::alloc::{GlobalAlloc, Layout, System};
16+use std::cell::Cell;
17+use std::path::{Path, PathBuf};
18+use std::process::Command;
19+use std::sync::atomic::{AtomicU64, Ordering};
20+
21+use ec_h264::{Decoder, Error};
22+
23+// ---------------------------------------------------------------------------
24+// Counting allocator: proves the steady-state decode loop allocates nothing.
25+// Lives in the test binary only — the shipped crates have no allocator games.
26+// ---------------------------------------------------------------------------
27+
28+struct CountingAlloc;
29+
30+static ALLOCS: AtomicU64 = AtomicU64::new(0);
31+
32+std::thread_local! {
33+ /// Only the test thread that armed the counter is counted — other test
34+ /// threads (and their ffmpeg child plumbing) allocate freely.
35+ static COUNTING_HERE: Cell<bool> = const { Cell::new(false) };
36+}
37+
38+fn counting_here() -> bool {
39+ COUNTING_HERE.try_with(Cell::get).unwrap_or(false)
40+}
41+
42+unsafe impl GlobalAlloc for CountingAlloc {
43+ unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
44+ if counting_here() {
45+ ALLOCS.fetch_add(1, Ordering::Relaxed);
46+ }
47+ unsafe { System.alloc(layout) }
48+ }
49+ unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
50+ unsafe { System.dealloc(ptr, layout) }
51+ }
52+ unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
53+ if counting_here() {
54+ ALLOCS.fetch_add(1, Ordering::Relaxed);
55+ }
56+ unsafe { System.realloc(ptr, layout, new_size) }
57+ }
58+}
59+
60+#[global_allocator]
61+static A: CountingAlloc = CountingAlloc;
62+
63+// ---------------------------------------------------------------------------
64+
65+fn vectors_dir() -> PathBuf {
66+ Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/vectors/h264-jvt")
67+}
68+
69+/// The CAVLC, progressive, single-slice-group streams whose first IDR this
70+/// decoder must reproduce bit-exactly.
71+const CAVLC_STREAMS: &[&str] = &[
72+ "AUD_MW_E",
73+ "BA1_Sony_D",
74+ "BA3_SVA_C",
75+ "BA_MW_D",
76+ "BANM_MW_D",
77+ "BASQP1_Sony_C",
78+ "CI_MW_D",
79+ "MIDR_MW_D",
80+ "NL1_Sony_D",
81+ "NL3_SVA_E",
82+ "NRF_MW_E",
83+ "SVA_BA2_D",
84+ "SVA_CL1_E",
85+ "SVA_NL2_E",
86+ "CVPCMNL2_SVA_C",
87+ // First PPS/picture of these carries no FMO; the first IDR is plain
88+ // CAVLC baseline and must be bit-exact like the rest.
89+ "SVA_FM1_E",
90+ "SL1_SVA_B",
91+ "MR1_BT_A",
92+];
93+
94+/// Streams that must fail with a named Unsupported error (wrong output is
95+/// forbidden; refusal strings are claims backed by these tests).
96+const UNSUPPORTED_STREAMS: &[(&str, &str)] = &[
97+ ("CABA1_SVA_B", "CABAC"), // entropy_coding_mode_flag = 1
98+ ("MR9_BT_B", "CABAC"), // Main profile, CABAC
99+ ("CAMACI3_Sony_C", "CABAC"), // CABAC + interlace tools
100+ ("FM2_SVA_C", "FMO"), // num_slice_groups > 1
101+ ("CVFI1_SVA_C", "interlaced"), // field pictures
102+ ("FI1_Sony_E", "interlaced"), // field pictures
103+];
104+
105+fn find_stream(dir: &Path) -> Option<PathBuf> {
106+ let mut fallback = None;
107+ for entry in std::fs::read_dir(dir).ok()? {
108+ let p = entry.ok()?.path();
109+ let ext = p.extension()?.to_str()?.to_ascii_lowercase();
110+ if matches!(ext.as_str(), "jsv" | "264" | "avc" | "26l" | "h264" | "jvt") {
111+ return Some(p);
112+ }
113+ if ext == "bit" {
114+ fallback = Some(p);
115+ }
116+ }
117+ fallback
118+}
119+
120+fn find_ref_yuv(dir: &Path) -> Option<PathBuf> {
121+ for entry in std::fs::read_dir(dir).ok()? {
122+ let p = entry.ok()?.path();
123+ let ext = p.extension()?.to_str()?.to_ascii_lowercase();
124+ if ext == "yuv" || ext == "qcif" {
125+ return Some(p);
126+ }
127+ }
128+ None
129+}
130+
131+fn ffmpeg_first_frame(stream: &Path) -> Option<Vec<u8>> {
132+ let out = Command::new("ffmpeg")
133+ .args(["-v", "error", "-i"])
134+ .arg(stream)
135+ .args([
136+ "-frames:v",
137+ "1",
138+ "-f",
139+ "rawvideo",
140+ "-pix_fmt",
141+ "yuv420p",
142+ "-",
143+ ])
144+ .output()
145+ .ok()?;
146+ if !out.status.success() || out.stdout.is_empty() {
147+ return None;
148+ }
149+ Some(out.stdout)
150+}
151+
152+/// Decode the first IDR and return (frame bytes as I420, width, height).
153+fn decode_first(stream_bytes: &[u8]) -> Result<(Vec<u8>, usize, usize), Error> {
154+ let mut dec = Decoder::new();
155+ let frame = dec.decode_first_idr(stream_bytes)?;
156+ let (w, h) = (frame.width as usize, frame.height as usize);
157+ let mut out = Vec::with_capacity(w * h * 3 / 2);
158+ let dims = [
159+ (w, h),
160+ (w.div_ceil(2), h.div_ceil(2)),
161+ (w.div_ceil(2), h.div_ceil(2)),
162+ ];
163+ for (plane, (pw, ph)) in frame.planes.iter().zip(dims) {
164+ for y in 0..ph {
165+ out.extend_from_slice(plane.row(y, pw).expect("plane row"));
166+ }
167+ }
168+ Ok((out, w, h))
169+}
170+
171+fn first_diff(a: &[u8], b: &[u8]) -> Option<usize> {
172+ a.iter().zip(b).position(|(x, y)| x != y)
173+}
174+
175+#[test]
176+fn jvt_cavlc_first_idr_bit_exact() {
177+ let base = vectors_dir();
178+ if !base.is_dir() {
179+ eprintln!(
180+ "SKIP: {} missing — run scripts/fetch-vectors.sh",
181+ base.display()
182+ );
183+ return;
184+ }
185+ let mut passed = Vec::new();
186+ let mut failed = Vec::new();
187+ for name in CAVLC_STREAMS {
188+ let dir = base.join(name);
189+ let Some(stream) = find_stream(&dir) else {
190+ eprintln!("SKIP {name}: no bitstream file");
191+ continue;
192+ };
193+ let bytes = std::fs::read(&stream).unwrap();
194+ match decode_first(&bytes) {
195+ Ok((ours, w, h)) => {
196+ let frame_len = w * h * 3 / 2;
197+ // Oracle 1: reference decoder YUV, first frame.
198+ let mut ok = true;
199+ if let Some(ref_path) = find_ref_yuv(&dir) {
200+ let reference = std::fs::read(&ref_path).unwrap();
201+ assert!(
202+ reference.len() >= frame_len,
203+ "{name}: reference YUV shorter than one frame"
204+ );
205+ if let Some(pos) = first_diff(&ours, &reference[..frame_len]) {
206+ eprintln!(
207+ "FAIL {name}: differs from reference YUV at byte {pos} \
208+ (plane offset, {w}x{h}): ours {} ref {}",
209+ ours[pos], reference[pos]
210+ );
211+ ok = false;
212+ }
213+ } else {
214+ eprintln!("WARN {name}: no reference YUV, ffmpeg only");
215+ }
216+ // Oracle 2: ffmpeg.
217+ if let Some(ff) = ffmpeg_first_frame(&stream) {
218+ assert!(ff.len() >= frame_len, "{name}: ffmpeg output short");
219+ if let Some(pos) = first_diff(&ours, &ff[..frame_len]) {
220+ eprintln!(
221+ "FAIL {name}: differs from ffmpeg at byte {pos}: ours {} ff {}",
222+ ours[pos], ff[pos]
223+ );
224+ ok = false;
225+ }
226+ }
227+ if ok {
228+ passed.push(*name);
229+ } else {
230+ failed.push(*name);
231+ }
232+ }
233+ Err(e) => {
234+ eprintln!("FAIL {name}: decode error: {e}");
235+ failed.push(*name);
236+ }
237+ }
238+ }
239+ eprintln!(
240+ "PASS table ({} streams bit-exact): {passed:?}",
241+ passed.len()
242+ );
243+ assert!(failed.is_empty(), "streams not bit-exact: {failed:?}");
244+ assert!(
245+ passed.len() >= 5,
246+ "fewer than 5 CAVLC conformance streams verified: {passed:?}"
247+ );
248+}
249+
250+#[test]
251+fn unsupported_streams_refuse_with_named_errors() {
252+ let base = vectors_dir();
253+ if !base.is_dir() {
254+ eprintln!("SKIP: fixtures missing");
255+ return;
256+ }
257+ for (name, what) in UNSUPPORTED_STREAMS {
258+ let dir = base.join(name);
259+ let Some(stream) = find_stream(&dir) else {
260+ eprintln!("SKIP {name}: no bitstream file");
261+ continue;
262+ };
263+ let bytes = std::fs::read(&stream).unwrap();
264+ match decode_first(&bytes) {
265+ Err(Error::Unsupported { what: w, .. }) => {
266+ let w_lower = w.to_lowercase();
267+ let expect = what.to_lowercase();
268+ assert!(
269+ w_lower.contains(&expect)
270+ || (expect == "interlaced" && w_lower.contains("interlace")),
271+ "{name}: expected Unsupported({what}), got Unsupported({w})"
272+ );
273+ }
274+ Ok(_) => panic!("{name}: expected a named Unsupported error, decode succeeded"),
275+ Err(e) => panic!("{name}: expected Unsupported({what}), got: {e}"),
276+ }
277+ }
278+}
279+
280+/// Steady-state decode loop performs zero heap allocations: after one warm-up
281+/// picture, re-decoding the same slices into the reused picture context
282+/// (including deblocking) must not allocate. Frame emission (`frame()`)
283+/// allocates the output planes and is measured separately as nonzero to prove
284+/// the counter works.
285+#[test]
286+fn steady_state_decode_loop_zero_alloc() {
287+ let base = vectors_dir();
288+ if !base.is_dir() {
289+ eprintln!("SKIP: fixtures missing");
290+ return;
291+ }
292+ let stream = find_stream(&base.join("BA1_Sony_D")).expect("BA1_Sony_D fixture");
293+ let bytes = std::fs::read(stream).unwrap();
294+ let mut dec = Decoder::new();
295+ // Warm-up: full first picture, growing every reusable buffer.
296+ let _ = dec.decode_first_idr(&bytes).expect("warm-up decode");
297+
298+ // Steady state: same IDR slices again, counted.
299+ let nals: Vec<&[u8]> = ec_h264_syntax::AnnexBIter::new(&bytes).collect();
300+ ALLOCS.store(0, Ordering::SeqCst);
301+ COUNTING_HERE.with(|c| c.set(true));
302+ let mut decoded = false;
303+ for nal in &nals {
304+ match dec.push_nal(nal) {
305+ Ok(ec_h264::NalOutcome::PictureBoundary) => break,
306+ Ok(ec_h264::NalOutcome::SliceDecoded) => decoded = true,
307+ Ok(_) => {}
308+ Err(e) => panic!("steady-state push failed: {e}"),
309+ }
310+ }
311+ dec.end_picture().expect("end_picture");
312+ COUNTING_HERE.with(|c| c.set(false));
313+ assert!(decoded, "no slice decoded in steady-state pass");
314+ let n = ALLOCS.load(Ordering::SeqCst);
315+ assert_eq!(n, 0, "steady-state decode loop allocated {n} times");
316+
317+ // Sanity: the counter is alive — frame emission does allocate.
318+ ALLOCS.store(0, Ordering::SeqCst);
319+ COUNTING_HERE.with(|c| c.set(true));
320+ let frame = dec.frame().expect("frame");
321+ COUNTING_HERE.with(|c| c.set(false));
322+ assert!(frame.width > 0);
323+ assert!(
324+ ALLOCS.load(Ordering::SeqCst) > 0,
325+ "allocation counter appears dead"
326+ );
327+}
328+
329+/// Decode-rate measurement: ns per macroblock and Mpx/s over the first IDR,
330+/// printed for the perf report. Run with `--nocapture` to see it. Uses the
331+/// steady-state path (buffers warm) like a playback loop would.
332+#[test]
333+fn ns_per_macroblock_measurement() {
334+ let base = vectors_dir();
335+ if !base.is_dir() {
336+ eprintln!("SKIP: fixtures missing");
337+ return;
338+ }
339+ for name in ["BA1_Sony_D", "CI_MW_D", "NL1_Sony_D"] {
340+ let Some(stream) = find_stream(&base.join(name)) else {
341+ continue;
342+ };
343+ let bytes = std::fs::read(stream).unwrap();
344+ let mut dec = Decoder::new();
345+ let frame = dec.decode_first_idr(&bytes).expect("warm-up");
346+ let (w, h) = (frame.width as u64, frame.height as u64);
347+ let mbs = (w.div_ceil(16)) * (h.div_ceil(16));
348+ let nals: Vec<&[u8]> = ec_h264_syntax::AnnexBIter::new(&bytes).collect();
349+
350+ let iters = 200u32;
351+ let start = std::time::Instant::now();
352+ for _ in 0..iters {
353+ for nal in &nals {
354+ match dec.push_nal(nal) {
355+ Ok(ec_h264::NalOutcome::PictureBoundary) => break,
356+ Ok(_) => {}
357+ Err(e) => panic!("{e}"),
358+ }
359+ }
360+ dec.end_picture().expect("end_picture");
361+ }
362+ let elapsed = start.elapsed();
363+ let ns_per_mb = elapsed.as_nanos() as f64 / f64::from(iters) / mbs as f64;
364+ let mpx_s = (w * h) as f64 * f64::from(iters) / elapsed.as_secs_f64() / 1e6;
365+ eprintln!(
366+ "PERF {name}: {w}x{h}, {mbs} MBs, {ns_per_mb:.0} ns/MB, {mpx_s:.1} Mpx/s \
367+ (intra IDR, single thread, deblock included, output copy excluded)"
368+ );
369+ }
370+}
371+
372+/// Corrupt-input smoke sweep (fuzz-lite, deterministic): single-byte
373+/// mutations and truncations of a real stream must produce `Err` or a frame,
374+/// never a panic. A cargo-fuzz target owns the deep search later (S18 lane
375+/// done-criterion); this keeps the invariant enforced in every test run.
376+#[test]
377+fn corrupt_streams_never_panic() {
378+ let base = vectors_dir();
379+ if !base.is_dir() {
380+ eprintln!("SKIP: fixtures missing");
381+ return;
382+ }
383+ let stream = find_stream(&base.join("BA1_Sony_D")).expect("BA1_Sony_D fixture");
384+ let bytes = std::fs::read(stream).unwrap();
385+
386+ // Truncations at prefix lengths spanning SPS/PPS/slice-header/slice-data.
387+ for len in (0..bytes.len().min(4096))
388+ .step_by(37)
389+ .chain([bytes.len() / 2])
390+ {
391+ let mut dec = Decoder::new();
392+ let _ = dec.decode_first_idr(&bytes[..len]);
393+ }
394+ // Single-byte corruptions: xor a walking pattern through the first 6KB
395+ // (covers parameter sets and the first slices), plus scattered hits.
396+ let mut xorshift = 0x243F_6A88u32; // deterministic PRNG, no rand dep
397+ // Debug builds carry overflow checks but decode ~10x slower; a smaller
398+ // sweep keeps the suite fast while release runs the full one.
399+ let count = if cfg!(debug_assertions) { 400 } else { 2000 };
400+ let dense = count * 3 / 4;
401+ for i in 0..count {
402+ let mut m = bytes.clone();
403+ let pos = if i < dense {
404+ i * 4 % m.len().min(6144)
405+ } else {
406+ xorshift ^= xorshift << 13;
407+ xorshift ^= xorshift >> 17;
408+ xorshift ^= xorshift << 5;
409+ (xorshift as usize) % m.len()
410+ };
411+ m[pos] ^= (0x5Bu8.wrapping_add(i as u8)).max(1);
412+ let mut dec = Decoder::new();
413+ let _ = dec.decode_first_idr(&m); // must not panic; any Err is fine
414+ }
415+}