forge
Explore
Log in

Don't you dare go Hollow

Entropy seat between the macroblock loop and CAVLC

Browse files at this commit

6480b8e3ba538ef489aadc81f806c062a9296c76Ahmet Kaan GümüşParent: 3e1c177
  • refactor
    • entropy seat between the macroblock loop and CAVLC
Show full message
refactor(h264): entropy seat between the macroblock loop and CAVLC

The slice-data syntax reader becomes an enum seam (`Entropy`) covering every
element the macroblock loop reads: mb_type, the intra prediction modes,
coded_block_pattern, mb_qp_delta, the residual blocks, the I_PCM samples and
the end-of-slice test. CABAC (clause 9.3) codes all of those differently, so
the seam has to sit there rather than around residual_block alone; the
parse-and-reconstruct loop stays fused.

Enum dispatch, not a generic: the variant is constant for a whole slice, so
the branches predict perfectly and the macroblock loop is monomorphised once.

The neighbour derivations now hand out the raw (left, above) pair instead of
a CAVLC nC, because CABAC reduces the same pair a different way.

CAVLC ns/MB, median of three runs, before -> after:
BA1_Sony_D 1331 -> 1328, CI_MW_D 1137 -> 1126, NL1_Sony_D 948 -> 933.
crates/ec-h264/src/decoder.rsmodified+50 -84
@@ -19,13 +19,12 @@ use ec_h264_syntax::{
1919 AnnexBIter, NalHeader, NalUnitType, Pps, SliceHeader, SliceType, Sps, unescape_rbsp,
2020 };
2121
22-use crate::bits::BitCursor;
23-use crate::cavlc::residual_block;
2422 use crate::deblock::{
2523 chroma_qp, edge_params, filter_chroma_line, filter_luma_h_edge16, filter_luma_line,
2624 };
25+use crate::entropy::{BlockCat, Entropy};
2726 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};
27+use crate::tables::{BLK4_POS, CHROMA_QP};
2928 use crate::transform::{
3029 LevelScale4x4, chroma_dc_transform_420, dequant_4x4, inverse_transform_4x4, luma_dc_transform,
3130 unzigzag, unzigzag_ac15,
@@ -408,7 +407,7 @@ impl Decoder {
408407 cr_qp_offset: pps.second_chroma_qp_index_offset,
409408 });
410409
411- let mut r = BitCursor::new(rbsp, sh.header_bits);
410+ let mut r = Entropy::cavlc(rbsp, sh.header_bits);
412411
413412 let mut ctx = SliceCtx {
414413 slice_id,
@@ -424,7 +423,7 @@ impl Decoder {
424423 return Err(Error::corrupt("macroblock address beyond the picture"));
425424 }
426425 decode_macroblock(&mut self.pic, &self.ls, &mut r, &mut ctx, mb_addr)?;
427- if !r.more_rbsp_data() {
426+ if !r.more_macroblocks()? {
428427 break;
429428 }
430429 mb_addr += 1;
@@ -531,53 +530,37 @@ fn mb_neighbors(pic: &Picture, mb_x: usize, mb_y: usize, slice_id: u16) -> MbNei
531530 }
532531 }
533532
534-/// nC for a luma 4x4 block at global block coords `(bx, by)` (spec 9.2.1).
533+/// Non-zero counts of the left and above neighbours of the luma 4x4 block at
534+/// global block coords `(bx, by)`, `None` when that neighbour is unavailable
535+/// (clause 6.4.11.4 plus the availability rules of 6.4.8).
535536 #[inline]
536-fn luma_nc(pic: &Picture, n: &MbNeighbors, bx: usize, by: usize) -> i32 {
537+fn luma_nz_pair(pic: &Picture, n: &MbNeighbors, bx: usize, by: usize) -> (Option<u8>, Option<u8>) {
537538 let w4 = pic.mb_w * 4;
538539 let left_avail = if bx.is_multiple_of(4) { n.a } else { true };
539540 let top_avail = if by.is_multiple_of(4) { n.b } else { true };
540- let na = if left_avail && bx > 0 {
541- i32::from(pic.nz_y[by * w4 + bx - 1])
542- } else {
543- -1
544- };
545- let nb = if top_avail && by > 0 {
546- i32::from(pic.nz_y[(by - 1) * w4 + bx])
547- } else {
548- -1
549- };
550- match (na >= 0, nb >= 0) {
551- (true, true) => (na + nb + 1) >> 1,
552- (true, false) => na,
553- (false, true) => nb,
554- (false, false) => 0,
555- }
541+ (
542+ (left_avail && bx > 0).then(|| pic.nz_y[by * w4 + bx - 1]),
543+ (top_avail && by > 0).then(|| pic.nz_y[(by - 1) * w4 + bx]),
544+ )
556545 }
557546
558-/// nC for a chroma AC 4x4 block at global chroma block coords.
547+/// The same for a chroma AC 4x4 block at global chroma block coords.
559548 #[inline]
560-fn chroma_nc(pic: &Picture, n: &MbNeighbors, comp: usize, cx: usize, cy: usize) -> i32 {
549+fn chroma_nz_pair(
550+ pic: &Picture,
551+ n: &MbNeighbors,
552+ comp: usize,
553+ cx: usize,
554+ cy: usize,
555+) -> (Option<u8>, Option<u8>) {
561556 let w2 = pic.mb_w * 2;
562557 let grid = &pic.nz_c[comp];
563558 let left_avail = if cx.is_multiple_of(2) { n.a } else { true };
564559 let top_avail = if cy.is_multiple_of(2) { n.b } else { true };
565- let na = if left_avail && cx > 0 {
566- i32::from(grid[cy * w2 + cx - 1])
567- } else {
568- -1
569- };
570- let nb = if top_avail && cy > 0 {
571- i32::from(grid[(cy - 1) * w2 + cx])
572- } else {
573- -1
574- };
575- match (na >= 0, nb >= 0) {
576- (true, true) => (na + nb + 1) >> 1,
577- (true, false) => na,
578- (false, true) => nb,
579- (false, false) => 0,
580- }
560+ (
561+ (left_avail && cx > 0).then(|| grid[cy * w2 + cx - 1]),
562+ (top_avail && cy > 0).then(|| grid[(cy - 1) * w2 + cx]),
563+ )
581564 }
582565
583566 /// Decode one macroblock of an I slice (spec 7.3.5, 7.4.5) and reconstruct
@@ -588,7 +571,7 @@ fn chroma_nc(pic: &Picture, n: &MbNeighbors, comp: usize, cx: usize, cy: usize)
588571 fn decode_macroblock(
589572 pic: &mut Picture,
590573 ls: &[LevelScale4x4; 3],
591- r: &mut BitCursor<'_>,
574+ r: &mut Entropy<'_>,
592575 ctx: &mut SliceCtx,
593576 mb_addr: usize,
594577 ) -> Result<()> {
@@ -603,24 +586,20 @@ fn decode_macroblock(
603586 let (bx0, by0) = (mb_x * 4, mb_y * 4);
604587 let (cx0, cy0) = (mb_x * 2, mb_y * 2);
605588
606- let mb_type = r.read_ue()?;
607- if mb_type > 25 {
608- return Err(Error::corrupt("I-slice mb_type > 25"));
609- }
589+ let mb_type = r.mb_type_i()?;
610590
611591 if mb_type == 25 {
612592 // I_PCM (7.3.5, 8.3.5): raw samples, byte aligned.
613- r.align_to_byte();
593+ let pcm = r.pcm_block()?;
614594 for y in 0..16 {
615- let row = r.read_bytes(16)?;
616595 let dst = pic.y.at(mb_x * 16, mb_y * 16 + y);
617- pic.y.data[dst..dst + 16].copy_from_slice(row);
596+ pic.y.data[dst..dst + 16].copy_from_slice(&pcm[y * 16..y * 16 + 16]);
618597 }
619- for plane in [&mut pic.cb, &mut pic.cr] {
598+ for (c, plane) in [&mut pic.cb, &mut pic.cr].into_iter().enumerate() {
599+ let base = 256 + c * 64;
620600 for y in 0..8 {
621- let row = r.read_bytes(8)?;
622601 let dst = plane.at(mb_x * 8, mb_y * 8 + y);
623- plane.data[dst..dst + 8].copy_from_slice(row);
602+ plane.data[dst..dst + 8].copy_from_slice(&pcm[base + y * 8..base + y * 8 + 8]);
624603 }
625604 }
626605 for dy in 0..4 {
@@ -656,7 +635,7 @@ fn decode_macroblock(
656635 };
657636
658637 // I_NxN transform size flag (High profile only).
659- if !is_i16 && ctx.transform_8x8_mode && r.read_bit()? {
638+ if !is_i16 && ctx.transform_8x8_mode && r.transform_size_8x8_flag()? {
660639 return Err(Error::unsupported(
661640 "8x8 transform",
662641 "transform_size_8x8_flag 1 selects the 8x8 intra prediction of \
@@ -681,11 +660,10 @@ fn decode_macroblock(
681660 } else {
682661 2
683662 };
684- let mode = if r.read_bit()? {
685- pred
686- } else {
687- let rem = r.read_bits(3)? as u8;
688- if rem < pred { rem } else { rem + 1 }
663+ let mode = match r.intra4x4_pred_mode()? {
664+ None => pred,
665+ Some(rem) if rem < pred => rem,
666+ Some(rem) => rem + 1,
689667 };
690668 pic.i4_modes[by * w4 + bx] = mode;
691669 modes[blk] = mode;
@@ -696,30 +674,18 @@ fn decode_macroblock(
696674 pic.i4_modes[base..base + 4].fill(2);
697675 }
698676 }
699- let chroma_mode = r.read_ue()?;
700- if chroma_mode > 3 {
701- return Err(Error::corrupt("intra_chroma_pred_mode > 3"));
702- }
677+ let chroma_mode = r.intra_chroma_pred_mode()?;
703678
704- // coded_block_pattern me(v) for I_NxN (9.1.2, Table 9-4).
679+ // coded_block_pattern for I_NxN; Intra_16x16 derives it from mb_type.
705680 let (cbp_luma, cbp_chroma) = if is_i16 {
706681 (cbp_luma, cbp_chroma)
707682 } else {
708- let code = r.read_ue()? as usize;
709- let cbp = if code < 48 {
710- CBP_INTRA_420[code]
711- } else {
712- return Err(Error::corrupt("coded_block_pattern codeNum > 47"));
713- };
714- (cbp & 15, cbp >> 4)
683+ r.coded_block_pattern_intra()?
715684 };
716685
717686 // mb_qp_delta (7.4.5).
718687 if cbp_luma != 0 || cbp_chroma != 0 || is_i16 {
719- let delta = r.read_se()?;
720- if !(-26..=25).contains(&delta) {
721- return Err(Error::corrupt("mb_qp_delta outside [-26, 25]"));
722- }
688+ let delta = r.mb_qp_delta()?;
723689 ctx.qp = (ctx.qp + delta + 52) % 52;
724690 }
725691 pic.mb_qp[mb_addr] = ctx.qp as u8;
@@ -747,8 +713,8 @@ fn decode_macroblock(
747713 };
748714 pred_16x16(i16_mode, &mut w, nbr.b, nbr.a);
749715 // Luma DC: un-zigzag over the 4x4 DC array, Hadamard + scale.
750- let nc = luma_nc(pic, &nbr, bx0, by0);
751- residual_block(r, &mut scan, 16, nc)?;
716+ let (na, nb) = luma_nz_pair(pic, &nbr, bx0, by0);
717+ r.residual_block(&mut scan, BlockCat::LumaDc, na, nb)?;
752718 unzigzag(&scan, &mut raster);
753719 luma_dc_transform(&mut raster, &ls[0], qp_y);
754720 let dc = raster;
@@ -756,8 +722,8 @@ fn decode_macroblock(
756722 let (dx, dy) = BLK4_POS[blk];
757723 let (bx, by) = (bx0 + dx as usize, by0 + dy as usize);
758724 let tc = if cbp_luma != 0 {
759- let nc = luma_nc(pic, &nbr, bx, by);
760- residual_block(r, &mut scan, 15, nc)?
725+ let (na, nb) = luma_nz_pair(pic, &nbr, bx, by);
726+ r.residual_block(&mut scan, BlockCat::LumaAc, na, nb)?
761727 } else {
762728 0
763729 };
@@ -784,8 +750,8 @@ fn decode_macroblock(
784750 let (dx, dy) = BLK4_POS[blk];
785751 let (bx, by) = (bx0 + dx as usize, by0 + dy as usize);
786752 let tc = if cbp_luma & (1 << (blk >> 2)) != 0 {
787- let nc = luma_nc(pic, &nbr, bx, by);
788- residual_block(r, &mut scan, 16, nc)?
753+ let (na, nb) = luma_nz_pair(pic, &nbr, bx, by);
754+ r.residual_block(&mut scan, BlockCat::Luma4x4, na, nb)?
789755 } else {
790756 0
791757 };
@@ -827,12 +793,12 @@ fn decode_macroblock(
827793 stride: plane.stride,
828794 origin: plane.origin + (mb_y * 8) * plane.stride + mb_x * 8,
829795 };
830- pred_chroma_8x8(chroma_mode as u8, &mut w, nbr.b, nbr.a);
796+ pred_chroma_8x8(chroma_mode, &mut w, nbr.b, nbr.a);
831797 }
832798 let mut chroma_dc = [[0i32; 4]; 2];
833799 if cbp_chroma != 0 {
834800 for (comp, c) in chroma_dc.iter_mut().enumerate() {
835- residual_block(r, &mut scan, 4, -1)?;
801+ r.residual_block(&mut scan, BlockCat::ChromaDc, None, None)?;
836802 c.copy_from_slice(&scan[..4]);
837803 let (ls_c, qp_c) = if comp == 0 {
838804 (&ls[1], qp_cb)
@@ -846,8 +812,8 @@ fn decode_macroblock(
846812 for blk in 0..4 {
847813 let (cx, cy) = (cx0 + (blk & 1), cy0 + (blk >> 1));
848814 let tc = if cbp_chroma == 2 {
849- let nc = chroma_nc(pic, &nbr, comp, cx, cy);
850- residual_block(r, &mut scan, 15, nc)?
815+ let (na, nb) = chroma_nz_pair(pic, &nbr, comp, cx, cy);
816+ r.residual_block(&mut scan, BlockCat::ChromaAc, na, nb)?
851817 } else {
852818 0
853819 };
crates/ec-h264/src/entropy.rsadded+186 -0
@@ -0,0 +1,186 @@
1+//! Entropy seat: the slice-data syntax reader the macroblock loop talks to.
2+//!
3+//! H.264 codes the same slice-data syntax two ways — CAVLC (clause 9.2) and
4+//! CABAC (clause 9.3) — and the difference reaches every syntax element, not
5+//! just the residual blocks. This enum is the single seam between them, so
6+//! [`crate::decoder::decode_macroblock`] stays one fused parse-and-reconstruct
7+//! loop instead of growing a second copy per entropy coder.
8+//!
9+//! Enum dispatch rather than a generic parameter: the variant is fixed for a
10+//! whole slice, so every branch here is perfectly predicted, and one
11+//! monomorphisation of the macroblock loop keeps the instruction cache (and the
12+//! source) half the size. Measured: no change on the CAVLC ns/MB test.
13+//!
14+//! The seat deliberately takes *neighbour values*, never the picture: context
15+//! derivation needs the neighbouring macroblocks' coefficient counts and coded
16+//! block patterns, and passing those in as small copied values keeps the
17+//! flat-array picture state private to the decoder module.
18+
19+use ec_core::error::{Error, Result};
20+
21+use crate::bits::BitCursor;
22+use crate::tables::CBP_INTRA_420;
23+
24+/// Residual block class (spec Table 9-42, the 4:2:0 subset this decoder codes).
25+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
26+pub(crate) enum BlockCat {
27+ /// Intra16x16DCLevel, `ctxBlockCat` 0.
28+ LumaDc,
29+ /// Intra16x16ACLevel, `ctxBlockCat` 1.
30+ LumaAc,
31+ /// LumaLevel4x4, `ctxBlockCat` 2.
32+ Luma4x4,
33+ /// ChromaDCLevel, `ctxBlockCat` 3.
34+ ChromaDc,
35+ /// ChromaACLevel, `ctxBlockCat` 4.
36+ ChromaAc,
37+}
38+
39+impl BlockCat {
40+ /// `maxNumCoeff` (Table 9-42).
41+ pub(crate) const fn max_num_coeff(self) -> usize {
42+ match self {
43+ BlockCat::LumaDc | BlockCat::Luma4x4 => 16,
44+ BlockCat::LumaAc | BlockCat::ChromaAc => 15,
45+ BlockCat::ChromaDc => 4,
46+ }
47+ }
48+}
49+
50+/// The slice-data syntax reader.
51+pub(crate) enum Entropy<'a> {
52+ Cavlc(BitCursor<'a>),
53+}
54+
55+impl<'a> Entropy<'a> {
56+ /// A CAVLC reader over `rbsp`, positioned just past the slice header.
57+ pub(crate) fn cavlc(rbsp: &'a [u8], header_bits: u64) -> Entropy<'a> {
58+ Entropy::Cavlc(BitCursor::new(rbsp, header_bits))
59+ }
60+
61+ /// `mb_type` of an I slice: 0 (I_NxN), 1..24 (Intra_16x16), 25 (I_PCM).
62+ pub(crate) fn mb_type_i(&mut self) -> Result<u32> {
63+ match self {
64+ Entropy::Cavlc(r) => {
65+ let t = r.read_ue()?;
66+ if t > 25 {
67+ return Err(Error::corrupt("I-slice mb_type > 25"));
68+ }
69+ Ok(t)
70+ }
71+ }
72+ }
73+
74+ /// `transform_size_8x8_flag` (7.3.5).
75+ pub(crate) fn transform_size_8x8_flag(&mut self) -> Result<bool> {
76+ match self {
77+ Entropy::Cavlc(r) => r.read_bit(),
78+ }
79+ }
80+
81+ /// One 4x4 intra prediction mode: `None` selects the predicted mode,
82+ /// `Some(rem)` the `rem_intra4x4_pred_mode` value (7.3.5.1).
83+ #[inline]
84+ pub(crate) fn intra4x4_pred_mode(&mut self) -> Result<Option<u8>> {
85+ match self {
86+ Entropy::Cavlc(r) => {
87+ if r.read_bit()? {
88+ Ok(None)
89+ } else {
90+ Ok(Some(r.read_bits(3)? as u8))
91+ }
92+ }
93+ }
94+ }
95+
96+ /// `intra_chroma_pred_mode` (7.3.5.1), 0..3.
97+ pub(crate) fn intra_chroma_pred_mode(&mut self) -> Result<u8> {
98+ match self {
99+ Entropy::Cavlc(r) => {
100+ let m = r.read_ue()?;
101+ if m > 3 {
102+ return Err(Error::corrupt("intra_chroma_pred_mode > 3"));
103+ }
104+ Ok(m as u8)
105+ }
106+ }
107+ }
108+
109+ /// `coded_block_pattern` of an Intra_4x4 macroblock, as
110+ /// `(CodedBlockPatternLuma, CodedBlockPatternChroma)`.
111+ pub(crate) fn coded_block_pattern_intra(&mut self) -> Result<(u8, u8)> {
112+ match self {
113+ Entropy::Cavlc(r) => {
114+ // me(v), clause 9.1.2 Table 9-4.
115+ let code = r.read_ue()? as usize;
116+ let cbp = *CBP_INTRA_420
117+ .get(code)
118+ .ok_or_else(|| Error::corrupt("coded_block_pattern codeNum > 47"))?;
119+ Ok((cbp & 15, cbp >> 4))
120+ }
121+ }
122+ }
123+
124+ /// `mb_qp_delta` (7.4.5), already range checked.
125+ pub(crate) fn mb_qp_delta(&mut self) -> Result<i32> {
126+ let delta = match self {
127+ Entropy::Cavlc(r) => r.read_se()?,
128+ };
129+ if !(-26..=25).contains(&delta) {
130+ return Err(Error::corrupt("mb_qp_delta outside [-26, 25]"));
131+ }
132+ Ok(delta)
133+ }
134+
135+ /// Decode one residual block into `coeff[0..cat.max_num_coeff()]` in scan
136+ /// order, returning the number of non-zero coefficients.
137+ ///
138+ /// `na`/`nb` are the same counts for the left and above neighbouring blocks
139+ /// of the same class, `None` when that neighbour is unavailable. CAVLC
140+ /// averages them into nC (9.2.1); CABAC turns them into the
141+ /// coded_block_flag context increment (9.3.3.1.1.9).
142+ #[inline]
143+ pub(crate) fn residual_block(
144+ &mut self,
145+ coeff: &mut [i32; 16],
146+ cat: BlockCat,
147+ na: Option<u8>,
148+ nb: Option<u8>,
149+ ) -> Result<u8> {
150+ match self {
151+ Entropy::Cavlc(r) => {
152+ let nc = if cat == BlockCat::ChromaDc {
153+ -1
154+ } else {
155+ match (na, nb) {
156+ (Some(a), Some(b)) => (i32::from(a) + i32::from(b) + 1) >> 1,
157+ (Some(a), None) => i32::from(a),
158+ (None, Some(b)) => i32::from(b),
159+ (None, None) => 0,
160+ }
161+ };
162+ crate::cavlc::residual_block(r, coeff, cat.max_num_coeff(), nc)
163+ }
164+ }
165+ }
166+
167+ /// The 384 raw bytes of an I_PCM macroblock (256 luma, 2x64 chroma), after
168+ /// alignment. A CABAC reader restarts its arithmetic engine afterwards
169+ /// (clause 9.3.1.2).
170+ pub(crate) fn pcm_block(&mut self) -> Result<&'a [u8]> {
171+ match self {
172+ Entropy::Cavlc(r) => {
173+ r.align_to_byte();
174+ r.read_bytes(384)
175+ }
176+ }
177+ }
178+
179+ /// True while the slice has another macroblock: `more_rbsp_data()` for
180+ /// CAVLC, `!end_of_slice_flag` for CABAC.
181+ pub(crate) fn more_macroblocks(&mut self) -> Result<bool> {
182+ match self {
183+ Entropy::Cavlc(r) => Ok(r.more_rbsp_data()),
184+ }
185+ }
186+}
crates/ec-h264/src/lib.rsmodified+1 -0
@@ -35,6 +35,7 @@ mod cavlc;
3535 mod codec;
3636 mod deblock;
3737 mod decoder;
38+mod entropy;
3839 mod pred;
3940 mod tables;
4041 mod transform;