forge
Explore
Log in

Don't you dare go Hollow

High-profile 8x8 transform, both entropy coders

Browse files at this commit

49bb32ea04bed31fa638f09b8512b7c86155507eAhmet Kaan GümüşParent: d7dca0c
  • feat
    • High-profile 8x8 transform, both entropy coders
Show full message
feat(h264): High-profile 8x8 transform, both entropy coders

transform_size_8x8_flag (7.3.5) in the intra and inter positions with
the neighbour context of 9.3.3.1.1.10, Intra_8x8 prediction with the
reference sample filter of 8.3.2.2.1, the 8x8 residual under CAVLC
(four interleaved 4x4 blocks) and CABAC (ctxBlockCat 5, ctxIdx 402..435
transcribed from Table 9-24, no coded_block_flag), the 8x8 scaling and
inverse transform of 8.5.13 with the 8x8 scaling lists, and the 8.7
rule that an 8x8 macroblock has no transform edge at luma 4 or 12.

This is what real content needs: every H.264 file in the library that
is not Main profile uses it, so eight of twelve were refused by name
before and all twelve now decode 500 frames bit-exactly against ffmpeg.
The MP4 whose Annex B extraction ffmpeg itself could only decode three
frames of is demuxed by ec-mp4 instead, which restores the oracle.

Coverage: 51 quantisers x both coders all-intra, P and B sequences with
and without sub-8x8 partitions, and a parameter-set assertion so an
encoder silently dropping back to 4x4 cannot make the sweep vacuous.
crates/ec-h264-syntax/src/lib.rsmodified+2 -2
@@ -23,8 +23,8 @@ pub mod sps;
2323 pub use nal::{AnnexBIter, NalHeader, NalUnitType, unescape_rbsp};
2424 pub use pps::Pps;
2525 pub use slice::{
26- DeblockControl, DecRefPicMarking, Mmco, PredWeightTable, RefPicListMod, SliceHeader,
27- SliceType, WeightEntry,
26+ DeblockControl, DecRefPicMarking, Mmco, PredWeightTable, RefPicListMod, SliceHeader, SliceType,
27+ WeightEntry,
2828 };
2929 pub use sps::{BitstreamRestriction, Hrd, ScalingLists, Sps, Vui};
3030
crates/ec-h264/Cargo.tomlmodified+3 -0
@@ -14,3 +14,6 @@ wide = { workspace = true }
1414 [dev-dependencies]
1515 # The conformance harness walks Annex B itself to drive push_nal.
1616 ec-h264-syntax = { workspace = true }
17+# ... and demuxes an MP4 directly where ffmpeg's own Annex B extraction of it
18+# produces a stream ffmpeg then cannot decode.
19+ec-mp4 = { workspace = true }
crates/ec-h264/src/cabac.rsmodified+69 -17
@@ -1,10 +1,11 @@
11 //! CABAC slice-data parsing (spec clause 9.3): arithmetic decoding engine,
22 //! context variables, binarizations and context selection.
33 //!
4-//! Scope is what a frame-coded 4:2:0 8-bit stream needs, I, P and B; every
5-//! other tool the decoder refuses by name before reaching this module, so the
6-//! contexts, block categories and initialisation columns that only field or
7-//! 8x8-transform coding reads are absent rather than transcribed untested.
4+//! Scope is what a frame-coded 4:2:0 8-bit stream needs, I, P and B, with or
5+//! without the High-profile 8x8 transform; every other tool the decoder refuses
6+//! by name before reaching this module, so the contexts, block categories and
7+//! initialisation columns that only field or 4:4:4 coding reads are absent
8+//! rather than transcribed untested.
89 //!
910 //! The engine keeps codIRange and codIOffset in `u32` with the spec's exact
1011 //! integer steps — no probability floats, no shortcuts — and reads its bits
@@ -17,16 +18,19 @@ use ec_core::error::{Error, Result};
1718
1819 use crate::bits::BitCursor;
1920 use crate::cabac_tables::{
20- INIT_11_59, INIT_60_69, INIT_70_275, INIT_399_401, INIT_MB_TYPE_I, RANGE_LPS, TRANS_LPS,
21- TRANS_MPS,
21+ INIT_11_59, INIT_60_69, INIT_70_275, INIT_399_401, INIT_402_435, INIT_MB_TYPE_I, LAST_8X8,
22+ RANGE_LPS, SIG_8X8_FRAME, TRANS_LPS, TRANS_MPS,
2223 };
2324 use crate::entropy::{
24- BlockCat, FLAG_CHROMA_PRED, FLAG_DIRECT, FLAG_I16, FLAG_INTER, FLAG_PCM, MbCtx, MbInfo,
25+ BlockCat, FLAG_CHROMA_PRED, FLAG_DIRECT, FLAG_I16, FLAG_INTER, FLAG_PCM, FLAG_TRANS8X8, MbCtx,
26+ MbInfo,
2527 };
2628
27-/// Highest ctxIdx this decoder can address, plus one (399..401 is the
28-/// transform_size_8x8_flag block, the last range a frame-coded slice reaches).
29-const NUM_CTX: usize = 402;
29+/// Highest ctxIdx this decoder can address, plus one (426..435 is
30+/// coeff_abs_level_minus1 of the 8x8 luma category, the last range a
31+/// frame-coded 4:2:0 slice reaches; 436 and up are the field-coded and 4:4:4
32+/// categories this decoder refuses by name).
33+const NUM_CTX: usize = 436;
3034
3135 /// ctxIdx 276 (end_of_slice_flag and the I_PCM bin of mb_type) is decoded by
3236 /// DecodeTerminate and has no adapting state.
@@ -58,6 +62,11 @@ const OFF_SIG: usize = 105;
5862 const OFF_LAST: usize = 166;
5963 const OFF_ABS: usize = 227;
6064 const OFF_TRANSFORM_8X8: usize = 399;
65+/// significant_coeff_flag / last_significant_coeff_flag / coeff_abs_level_minus1
66+/// of ctxBlockCat 5 (frame coded), Table 9-34.
67+const OFF_SIG_8X8: usize = 402;
68+const OFF_LAST_8X8: usize = 417;
69+const OFF_ABS_8X8: usize = 426;
6170
6271 /// The ctxIdx values the Intra_16x16 part of an mb_type bin string uses, in
6372 /// bin order: `[b0, CodedBlockPatternLuma, chroma bin 0, chroma bin 1,
@@ -146,6 +155,9 @@ impl<'a> Cabac<'a> {
146155 for (i, &mn) in INIT_399_401.iter().enumerate() {
147156 set(&mut self.state, OFF_TRANSFORM_8X8 + i, mn[column]);
148157 }
158+ for (i, &mn) in INIT_402_435.iter().enumerate() {
159+ set(&mut self.state, OFF_SIG_8X8 + i, mn[column]);
160+ }
149161 }
150162
151163 /// 9.3.1.2: codIRange = 510, codIOffset = read_bits(9).
@@ -415,11 +427,15 @@ impl<'a> Cabac<'a> {
415427 Ok(if self.bypass() { -value } else { value })
416428 }
417429
418- /// transform_size_8x8_flag (9.3.3.1.1.10).
430+ /// transform_size_8x8_flag (9.3.3.1.1.10): a neighbour counts when it is
431+ /// available and carried the flag itself.
419432 pub(crate) fn transform_size_8x8_flag(&mut self) -> Result<bool> {
420- // No neighbour can carry the flag: a macroblock that set it is refused
421- // before its state is ever stored, so ctxIdxInc is always 0 here.
422- Ok(self.decision(OFF_TRANSFORM_8X8))
433+ let cond = |n: Option<MbInfo>| match n {
434+ None => 0,
435+ Some(i) => usize::from(i.flags & FLAG_TRANS8X8 != 0),
436+ };
437+ let inc = cond(self.ctx.a) + cond(self.ctx.b);
438+ Ok(self.decision(OFF_TRANSFORM_8X8 + inc))
423439 }
424440
425441 /// prev_intra4x4_pred_mode_flag, then rem_intra4x4_pred_mode as FL cMax=7
@@ -580,8 +596,44 @@ impl<'a> Cabac<'a> {
580596 }
581597 sig[num - 1] = true;
582598
583- // Levels, highest scanning position first (9.3.3.1.3 counters).
584- let abs_base = OFF_ABS + ABS_CAT_OFF[cat_i];
599+ self.decode_levels(coeff, &sig, num, OFF_ABS + ABS_CAT_OFF[cat_i], cat_i == 3)
600+ }
601+
602+ /// residual_block_cabac for a luma 8x8 block (ctxBlockCat 5).
603+ ///
604+ /// There is no coded_block_flag here: with ChromaArrayType other than 3,
605+ /// 7.3.5.3.3 sends the flag only when maxNumCoeff differs from 64, so the
606+ /// coded_block_pattern bit that selected this block is the whole signal and
607+ /// the flag is inferred to be 1.
608+ pub(crate) fn residual_block_8x8(&mut self, coeff: &mut [i32; 64]) -> Result<u8> {
609+ *coeff = [0; 64];
610+ let mut sig = [false; 64];
611+ let mut num = 64;
612+ let mut i = 0;
613+ while i + 1 < num {
614+ if self.decision(OFF_SIG_8X8 + usize::from(SIG_8X8_FRAME[i])) {
615+ sig[i] = true;
616+ if self.decision(OFF_LAST_8X8 + usize::from(LAST_8X8[i])) {
617+ num = i + 1;
618+ }
619+ }
620+ i += 1;
621+ }
622+ sig[num - 1] = true;
623+ self.decode_levels(coeff, &sig, num, OFF_ABS_8X8, false)
624+ }
625+
626+ /// coeff_abs_level_minus1 and coeff_sign_flag over a decoded significance
627+ /// map, highest scanning position first (9.3.3.1.3 counters). Returns the
628+ /// number of levels written.
629+ fn decode_levels(
630+ &mut self,
631+ coeff: &mut [i32],
632+ sig: &[bool],
633+ num: usize,
634+ abs_base: usize,
635+ chroma_dc: bool,
636+ ) -> Result<u8> {
585637 let mut num_eq1 = 0u32;
586638 let mut num_gt1 = 0u32;
587639 let mut total = 0u8;
@@ -594,7 +646,7 @@ impl<'a> Cabac<'a> {
594646 } else {
595647 4.min(1 + num_eq1) as usize
596648 };
597- let inc1 = 5 + (4 - u32::from(cat_i == 3)).min(num_gt1) as usize;
649+ let inc1 = 5 + (4 - u32::from(chroma_dc)).min(num_gt1) as usize;
598650 // Prefix: TU with cMax = uCoff = 14.
599651 let mut prefix = 0u32;
600652 while prefix < 14 {
crates/ec-h264/src/cabac_tables.rsmodified+59 -3
@@ -3,15 +3,16 @@
33 //! The initialisation values of Tables 9-12 to 9-21 for every ctxIdx a
44 //! frame-coded 4:2:0 slice can reach: 0..10 (I-slice mb_type), 11..59 (the
55 //! inter elements: mb_skip_flag, P and B mb_type and sub_mb_type, mvd,
6-//! ref_idx), 60..69 (shared by all slice types), 70..275 and 399..401.
6+//! ref_idx), 60..69 (shared by all slice types), 70..275, 399..401 (the
7+//! transform size flag) and 402..435 (the frame-coded 8x8 luma residual).
78 //!
89 //! Where a ctxIdx has cabac_init_idc columns they are stored as
910 //! `[I/SI, idc 0, idc 1, idc 2]` and [`crate::cabac::Cabac`] selects the column
1011 //! once per slice. ctxIdx 11..53 are never read by an I slice; their I column
1112 //! repeats the idc-0 values so the arrays stay rectangular.
1213 //!
13-//! Absent on purpose: the field-coded significance contexts (277..398) and the
14-//! 8x8 transform categories (402..1023) — both tools are refused by name, so
14+//! Absent on purpose: the field-coded significance contexts (277..398, 436..459)
15+//! and the 4:4:4 categories (460..1023) — both tools are refused by name, so
1516 //! transcribing their numbers would ship values no oracle here exercises.
1617
1718 /// Table 9-12, ctxIdx 0..10: mb_type in I slices.
@@ -310,6 +311,61 @@ pub(crate) const INIT_70_275: [[(i8, i8); 4]; 206] = [
310311 [(-14, 97), (-8, 85), (-4, 78), (-10, 87)],
311312 ];
312313
314+/// Table 9-24, ctxIdx 402..435: the frame-coded 8x8 luma residual contexts
315+/// (significant_coeff_flag 402..416, last_significant_coeff_flag 417..425,
316+/// coeff_abs_level_minus1 426..435), all four initialisation columns.
317+pub(crate) const INIT_402_435: [[(i8, i8); 4]; 34] = [
318+ [(-17, 120), (-4, 79), (-5, 85), (-3, 78)],
319+ [(-20, 112), (-7, 71), (-6, 81), (-8, 74)],
320+ [(-18, 114), (-5, 69), (-10, 77), (-9, 72)],
321+ [(-11, 85), (-9, 70), (-7, 81), (-10, 72)],
322+ [(-15, 92), (-8, 66), (-17, 80), (-18, 75)],
323+ [(-14, 89), (-10, 68), (-18, 73), (-12, 71)],
324+ [(-26, 71), (-19, 73), (-4, 74), (-11, 63)],
325+ [(-15, 81), (-12, 69), (-10, 83), (-5, 70)],
326+ [(-14, 80), (-16, 70), (-9, 71), (-17, 75)],
327+ [(0, 68), (-15, 67), (-9, 67), (-14, 72)],
328+ [(-14, 70), (-20, 62), (-1, 61), (-16, 67)],
329+ [(-24, 56), (-19, 70), (-8, 66), (-8, 53)],
330+ [(-23, 68), (-16, 66), (-14, 66), (-14, 59)],
331+ [(-24, 50), (-22, 65), (0, 59), (-9, 52)],
332+ [(-11, 74), (-20, 63), (2, 59), (-11, 68)],
333+ [(23, -13), (9, -2), (17, -10), (9, -2)],
334+ [(26, -13), (26, -9), (32, -13), (30, -10)],
335+ [(40, -15), (33, -9), (42, -9), (31, -4)],
336+ [(49, -14), (39, -7), (49, -5), (33, -1)],
337+ [(44, 3), (41, -2), (53, 0), (33, 7)],
338+ [(45, 6), (45, 3), (64, 3), (31, 12)],
339+ [(44, 34), (49, 9), (68, 10), (37, 23)],
340+ [(33, 54), (45, 27), (66, 27), (31, 38)],
341+ [(19, 82), (36, 59), (47, 57), (20, 64)],
342+ [(-3, 75), (-6, 66), (-5, 71), (-9, 71)],
343+ [(-1, 23), (-7, 35), (0, 24), (-7, 37)],
344+ [(1, 34), (-7, 42), (-1, 36), (-8, 44)],
345+ [(1, 43), (-8, 45), (-2, 42), (-11, 49)],
346+ [(0, 54), (-5, 48), (-2, 52), (-10, 56)],
347+ [(-2, 55), (-12, 56), (-9, 57), (-12, 59)],
348+ [(0, 61), (-6, 60), (-6, 63), (-8, 63)],
349+ [(1, 64), (-5, 62), (-4, 65), (-9, 67)],
350+ [(0, 68), (-8, 66), (-4, 67), (-6, 68)],
351+ [(-9, 92), (-8, 76), (-7, 82), (-10, 79)],
352+];
353+
354+/// Table 9-43, frame-coded column: ctxIdxInc of significant_coeff_flag for
355+/// ctxBlockCat 5, indexed by levelListIdx 0..62.
356+pub(crate) const SIG_8X8_FRAME: [u8; 63] = [
357+ 0, 1, 2, 3, 4, 5, 5, 4, 4, 3, 3, 4, 4, 4, 5, 5, 4, 4, 4, 4, 3, 3, 6, 7, 7, 7, 8, 9, 10, 9, 8,
358+ 7, 7, 6, 11, 12, 13, 11, 6, 7, 8, 9, 14, 10, 9, 8, 6, 11, 12, 13, 11, 6, 9, 14, 10, 9, 11, 12,
359+ 13, 11, 14, 10, 12,
360+];
361+
362+/// Table 9-43, last column: ctxIdxInc of last_significant_coeff_flag for
363+/// ctxBlockCat 5, indexed by levelListIdx 0..62.
364+pub(crate) const LAST_8X8: [u8; 63] = [
365+ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
366+ 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8,
367+];
368+
313369 /// Table 9-16, ctxIdx 399..401: transform_size_8x8_flag.
314370 pub(crate) const INIT_399_401: [[(i8, i8); 4]; 3] = [
315371 [(31, 21), (12, 40), (25, 32), (21, 33)],
crates/ec-h264/src/decoder.rsmodified+234 -19
@@ -38,18 +38,22 @@ use crate::dpb::{
3838 };
3939 use crate::entropy::{
4040 BlockCat, Entropy, FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_DIRECT, FLAG_I16, FLAG_INTER, FLAG_PCM,
41- FLAG_SKIP, MbCtx, MbInfo,
41+ FLAG_SKIP, FLAG_TRANS8X8, MbCtx, MbInfo,
4242 };
4343 use crate::inter::{RefPlane, Weights, combine, mc_chroma, mc_luma};
4444 use crate::mv::{
4545 B_SHAPES, B_SUB, MbShape, MvCtx, P_SHAPES, P_SUB, Pred, SubShape, min_positive, neighbour_mvd,
4646 predict_mv, ref_idx_cond, write_block, write_intra_mb, write_mvd,
4747 };
48-use crate::pred::{Nbr4, PlaneWindow, add_residual_4x4, pred_4x4, pred_16x16, pred_chroma_8x8};
48+use crate::pred::{
49+ Nbr4, Nbr8, PlaneWindow, add_residual_4x4, add_residual_8x8, filter_nbr8, pred_4x4, pred_8x8,
50+ pred_16x16, pred_chroma_8x8,
51+};
4952 use crate::tables::{BLK4_POS, CHROMA_QP};
5053 use crate::transform::{
51- LevelScale4x4, chroma_dc_transform_420, dequant_4x4, inverse_transform_4x4, luma_dc_transform,
52- unzigzag, unzigzag_ac15,
54+ LevelScale4x4, LevelScale8x8, chroma_dc_transform_420, dequant_4x4, dequant_8x8,
55+ inverse_transform_4x4, inverse_transform_8x8, luma_dc_transform, unzigzag, unzigzag_8x8,
56+ unzigzag_ac15,
5357 };
5458
5559 /// Where a 4x4 block's top-right neighbour samples come from, per
@@ -110,6 +114,9 @@ pub struct Decoder {
110114 has_picture: bool,
111115 /// Scaling factors of the active PPS/SPS, `[intra, inter][Y, Cb, Cr]`.
112116 ls: [[LevelScale4x4; 3]; 2],
117+ /// The same for the 8x8 luma transform, `[intra, inter]` (4:2:0 has no 8x8
118+ /// chroma transform).
119+ ls8: [LevelScale8x8; 2],
113120 active_pps: Option<u32>,
114121 /// `seq_parameter_set_id` of the most recently stored SPS, so a container
115122 /// entry path can publish the picture size before the first slice.
@@ -174,6 +181,7 @@ impl Decoder {
174181 dpb: Dpb::default(),
175182 has_picture: false,
176183 ls: flat_scaling(),
184+ ls8: [LevelScale8x8::new(&[16; 64]), LevelScale8x8::new(&[16; 64])],
177185 active_pps: None,
178186 last_sps: None,
179187 cur_info: PicInfo {
@@ -526,6 +534,7 @@ impl Decoder {
526534 &mut self.cur,
527535 &self.dpb.frames,
528536 &self.ls,
537+ &self.ls8,
529538 &mut r,
530539 &mut ctx,
531540 mb_addr,
@@ -543,6 +552,7 @@ impl Decoder {
543552 &mut self.cur,
544553 &self.dpb.frames,
545554 &self.ls,
555+ &self.ls8,
546556 &mut r,
547557 &mut ctx,
548558 mb_addr,
@@ -566,6 +576,7 @@ impl Decoder {
566576 &mut self.cur,
567577 &self.dpb.frames,
568578 &self.ls,
579+ &self.ls8,
569580 &mut r,
570581 &mut ctx,
571582 mb_addr,
@@ -678,6 +689,11 @@ impl Decoder {
678689 LevelScale4x4::new(weights[1][2]),
679690 ],
680691 ];
692+ let w8 = match lists {
693+ Some(l) => [&l.list_8x8[0], &l.list_8x8[1]],
694+ None => [&[16u8; 64]; 2],
695+ };
696+ self.ls8 = [LevelScale8x8::new(w8[0]), LevelScale8x8::new(w8[1])];
681697 self.active_pps = Some(pps.id);
682698 }
683699 Ok(())
@@ -865,12 +881,16 @@ impl SliceCtx {
865881 }
866882 }
867883
868-/// Neighbour-availability snapshot for one macroblock (left, top, top-right).
884+/// Neighbour-availability snapshot for one macroblock (left, top, top-right,
885+/// top-left). The top-left neighbour is only read by the Intra_8x8 reference
886+/// filter of 8.3.2.2.1, which changes its end taps when the corner sample is
887+/// missing.
869888 #[derive(Clone, Copy)]
870889 struct MbNeighbors {
871890 a: bool,
872891 b: bool,
873892 c: bool,
893+ d: bool,
874894 }
875895
876896 fn mb_neighbors(pic: &Picture, mb_x: usize, mb_y: usize, slice_id: u16) -> MbNeighbors {
@@ -881,6 +901,7 @@ fn mb_neighbors(pic: &Picture, mb_x: usize, mb_y: usize, slice_id: u16) -> MbNei
881901 a: mb_x > 0 && same(addr - 1),
882902 b: mb_y > 0 && same(addr - w),
883903 c: mb_y > 0 && mb_x + 1 < w && same(addr - w + 1),
904+ d: mb_y > 0 && mb_x > 0 && same(addr - w - 1),
884905 }
885906 }
886907
@@ -894,6 +915,7 @@ fn intra_neighbors(pic: &Picture, mb_x: usize, mb_y: usize, n: MbNeighbors) -> M
894915 a: n.a && intra(addr - 1),
895916 b: n.b && intra(addr - w),
896917 c: n.c && intra(addr - w + 1),
918+ d: n.d && intra(addr - w - 1),
897919 }
898920 }
899921
@@ -950,6 +972,7 @@ fn decode_macroblock(
950972 pic: &mut Picture,
951973 refs: &[Picture],
952974 ls: &[[LevelScale4x4; 3]; 2],
975+ ls8: &[LevelScale8x8; 2],
953976 r: &mut Entropy<'_>,
954977 ctx: &mut SliceCtx,
955978 mb_addr: usize,
@@ -1023,7 +1046,9 @@ fn decode_macroblock(
10231046 };
10241047 r.set_intra(intra_type.is_some());
10251048 if let Some(shape) = shape {
1026- return decode_inter_mb(pic, refs, ls, r, ctx, mb_addr, shape, skipped, mb_type, nbr);
1049+ return decode_inter_mb(
1050+ pic, refs, ls, ls8, r, ctx, mb_addr, shape, skipped, mb_type, nbr,
1051+ );
10271052 }
10281053 let mb_type = intra_type.expect("an intra macroblock type");
10291054 write_intra_mb(pic, mb_x, mb_y);
@@ -1082,18 +1107,45 @@ fn decode_macroblock(
10821107 (0, 0, 0) // read below via me(v)
10831108 };
10841109
1085- // I_NxN transform size flag (High profile only).
1086- if !is_i16 && ctx.transform_8x8_mode && r.transform_size_8x8_flag()? {
1087- return Err(Error::unsupported(
1088- "8x8 transform",
1089- "transform_size_8x8_flag 1 selects the 8x8 intra prediction of \
1090- clause 8.3.2 and the 8x8 transform of 8.5.13; not implemented",
1091- ));
1092- }
1110+ // I_NxN transform size flag (7.3.5, High profile only): it selects
1111+ // Intra_8x8 prediction and the 8x8 transform for this macroblock.
1112+ let trans8x8 = !is_i16 && ctx.transform_8x8_mode && r.transform_size_8x8_flag()?;
10931113
1094- // mb_pred (7.3.5.1): intra 4x4 modes, then chroma mode.
1114+ // mb_pred (7.3.5.1): intra 4x4 or 8x8 modes, then chroma mode.
10951115 let mut modes = [2u8; 16];
1096- if !is_i16 {
1116+ let mut modes8 = [2u8; 4];
1117+ if trans8x8 {
1118+ // Intra_8x8: four modes, predicted by 8.3.2.1 from the neighbouring
1119+ // block modes. Every 4x4 slot of an 8x8 block carries its mode, which
1120+ // is exactly what 8.3.1.1 and 8.3.2.1 read back from a neighbour
1121+ // whichever size that neighbour used.
1122+ for blk8 in 0..4 {
1123+ let (bx, by) = (bx0 + (blk8 % 2) * 2, by0 + (blk8 / 2) * 2);
1124+ let left_avail = if blk8.is_multiple_of(2) {
1125+ intra_nbr.a
1126+ } else {
1127+ true
1128+ };
1129+ let top_avail = if blk8 < 2 { intra_nbr.b } else { true };
1130+ let pred = if left_avail && top_avail {
1131+ let ma = pic.i4_modes[by * w4 + bx - 1];
1132+ let mb = pic.i4_modes[(by - 1) * w4 + bx];
1133+ ma.min(mb)
1134+ } else {
1135+ 2
1136+ };
1137+ let mode = match r.intra4x4_pred_mode()? {
1138+ None => pred,
1139+ Some(rem) if rem < pred => rem,
1140+ Some(rem) => rem + 1,
1141+ };
1142+ modes8[blk8] = mode;
1143+ for dy in 0..2 {
1144+ let base = (by + dy) * w4 + bx;
1145+ pic.i4_modes[base..base + 2].fill(mode);
1146+ }
1147+ }
1148+ } else if !is_i16 {
10971149 for blk in 0..16 {
10981150 let (dx, dy) = BLK4_POS[blk];
10991151 let (bx, by) = (bx0 + dx as usize, by0 + dy as usize);
@@ -1134,6 +1186,7 @@ fn decode_macroblock(
11341186 finish_macroblock(
11351187 pic,
11361188 &ls[0],
1189+ &ls8[0],
11371190 r,
11381191 ctx,
11391192 mb_addr,
@@ -1145,9 +1198,11 @@ fn decode_macroblock(
11451198 cbp_luma,
11461199 cbp_chroma,
11471200 modes,
1201+ modes8,
1202+ trans8x8,
11481203 chroma_mode,
11491204 intra: true,
1150- flags: if is_i16 { FLAG_I16 } else { 0 },
1205+ flags: if is_i16 { FLAG_I16 } else { 0 } | if trans8x8 { FLAG_TRANS8X8 } else { 0 },
11511206 },
11521207 )
11531208 }
@@ -1165,6 +1220,10 @@ struct MbFinish {
11651220 cbp_luma: u8,
11661221 cbp_chroma: u8,
11671222 modes: [u8; 16],
1223+ /// Intra8x8PredMode per 8x8 block, when `trans8x8` and `intra`.
1224+ modes8: [u8; 4],
1225+ /// transform_size_8x8_flag: the luma residual is four 8x8 transform blocks.
1226+ trans8x8: bool,
11681227 chroma_mode: u8,
11691228 intra: bool,
11701229 flags: u8,
@@ -1183,6 +1242,7 @@ struct MbFinish {
11831242 fn finish_macroblock(
11841243 pic: &mut Picture,
11851244 ls: &[LevelScale4x4; 3],
1245+ ls8: &LevelScale8x8,
11861246 r: &mut Entropy<'_>,
11871247 ctx: &mut SliceCtx,
11881248 mb_addr: usize,
@@ -1265,6 +1325,69 @@ fn finish_macroblock(
12651325 .at(mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4);
12661326 add_residual_4x4(&mut pic.y.data, pic.y.stride, origin, &resid);
12671327 }
1328+ } else if m.trans8x8 {
1329+ // 8x8 transform (8.5.13): predict, parse and reconstruct one 8x8 block
1330+ // at a time, because an Intra_8x8 block predicts from the reconstructed
1331+ // samples of the blocks before it.
1332+ let mut scan8 = [0i32; 64];
1333+ let mut raster8 = [0i32; 64];
1334+ let mut resid8 = [0i32; 64];
1335+ for blk8 in 0..4 {
1336+ let (x, y) = (mb_x * 16 + (blk8 % 2) * 8, mb_y * 16 + (blk8 / 2) * 8);
1337+ let (bx, by) = (bx0 + (blk8 % 2) * 2, by0 + (blk8 / 2) * 2);
1338+ let origin = pic.y.at(x, y);
1339+ let stride = pic.y.stride;
1340+ if m.intra {
1341+ let n = filter_nbr8(&gather_nbr8(pic, &m.pred_nbr, blk8, x, y));
1342+ let mut p = [0u8; 64];
1343+ pred_8x8(m.modes8[blk8], &n, &mut p);
1344+ for ry in 0..8 {
1345+ let row = origin + ry * stride;
1346+ pic.y.data[row..row + 8].copy_from_slice(&p[ry * 8..ry * 8 + 8]);
1347+ }
1348+ }
1349+ if cbp_luma & (1 << blk8) == 0 {
1350+ for dy in 0..2 {
1351+ let base = (by + dy) * w4 + bx;
1352+ pic.nz_y[base..base + 2].fill(0);
1353+ }
1354+ continue;
1355+ }
1356+ let tc = if r.is_cabac() {
1357+ // ctxBlockCat 5: one 64-coefficient block, and every 4x4 slot
1358+ // of it reports the block's own count to the neighbours
1359+ // (9.3.3.1.1.9 resolves them to the 8x8 transform block).
1360+ let tc = r.residual_block_8x8(&mut scan8)?;
1361+ for dy in 0..2 {
1362+ let base = (by + dy) * w4 + bx;
1363+ pic.nz_y[base..base + 2].fill(tc.min(16));
1364+ }
1365+ tc
1366+ } else {
1367+ // CAVLC codes the same 64 coefficients as four interleaved 4x4
1368+ // blocks (7.3.5.3.1), each with its own nC neighbourhood.
1369+ let mut tc = 0u8;
1370+ for i4 in 0..4 {
1371+ let (dx, dy) = BLK4_POS[blk8 * 4 + i4];
1372+ let (sx, sy) = (bx0 + dx as usize, by0 + dy as usize);
1373+ let (na, nb) = luma_nz_pair(pic, nbr, sx, sy);
1374+ let n = r.residual_block(&mut scan, BlockCat::Luma4x4, na, nb)?;
1375+ pic.nz_y[sy * w4 + sx] = n;
1376+ tc += n;
1377+ for i in 0..16 {
1378+ scan8[4 * i + i4] = scan[i];
1379+ }
1380+ }
1381+ tc
1382+ };
1383+ if tc == 0 {
1384+ continue;
1385+ }
1386+ unzigzag_8x8(&scan8, &mut raster8);
1387+ dequant_8x8(&mut raster8, ls8, qp_y);
1388+ inverse_transform_8x8(&raster8, &mut resid8);
1389+ add_residual_8x8(&mut pic.y.data, stride, origin, &resid8);
1390+ }
12681391 } else {
12691392 for blk in 0..16 {
12701393 let (dx, dy) = BLK4_POS[blk];
@@ -1388,6 +1511,7 @@ fn decode_inter_mb(
13881511 pic: &mut Picture,
13891512 refs: &[Picture],
13901513 ls: &[[LevelScale4x4; 3]; 2],
1514+ ls8: &[LevelScale8x8; 2],
13911515 r: &mut Entropy<'_>,
13921516 ctx: &mut SliceCtx,
13931517 mb_addr: usize,
@@ -1611,10 +1735,28 @@ fn decode_inter_mb(
16111735 pic.i4_modes[base..base + 4].fill(2);
16121736 }
16131737 let (cbp_luma, cbp_chroma) = r.coded_block_pattern_inter()?;
1738+ // transform_size_8x8_flag (7.3.5): only when every 8x8 of this macroblock
1739+ // is predicted as a whole, because an 8x8 transform block may not straddle
1740+ // two motion partitions.
1741+ let no_sub_lt_8x8 = !shape.sub
1742+ || (0..4).all(|p| {
1743+ let s = motion.sub[p];
1744+ if s.pred == Pred::Direct {
1745+ ctx.direct_8x8_inference
1746+ } else {
1747+ s.parts == 1
1748+ }
1749+ });
1750+ let trans8x8 = cbp_luma != 0
1751+ && ctx.transform_8x8_mode
1752+ && no_sub_lt_8x8
1753+ && (!direct_mb || ctx.direct_8x8_inference)
1754+ && r.transform_size_8x8_flag()?;
16141755 // The inter scaling lists (Table 7-2 lists 3..5) govern an inter residual.
16151756 finish_macroblock(
16161757 pic,
16171758 &ls[1],
1759+ &ls8[1],
16181760 r,
16191761 ctx,
16201762 mb_addr,
@@ -1626,9 +1768,12 @@ fn decode_inter_mb(
16261768 cbp_luma,
16271769 cbp_chroma,
16281770 modes: [2; 16],
1771+ modes8: [2; 4],
1772+ trans8x8,
16291773 chroma_mode: 0,
16301774 intra: false,
1631- flags: if b && mb_type == 0 { FLAG_DIRECT } else { 0 },
1775+ flags: if b && mb_type == 0 { FLAG_DIRECT } else { 0 }
1776+ | if trans8x8 { FLAG_TRANS8X8 } else { 0 },
16321777 },
16331778 )
16341779 }
@@ -2042,6 +2187,52 @@ fn gather_nbr4(pic: &Picture, nbr: &MbNeighbors, blk: usize, x: usize, y: usize)
20422187 }
20432188 }
20442189
2190+/// Gather the 25 neighbour samples of an Intra_8x8 luma block (spec 8.3.2.2),
2191+/// including the top-right substitution rule, unfiltered.
2192+///
2193+/// `blk8` is luma8x8BlkIdx: block 1 reaches the above-right macroblock for its
2194+/// top-right run, block 2 finds it inside this macroblock, and block 3 has none
2195+/// (the samples right of it are not decoded yet).
2196+fn gather_nbr8(pic: &Picture, nbr: &MbNeighbors, blk8: usize, x: usize, y: usize) -> Nbr8 {
2197+ let stride = pic.y.stride;
2198+ let o = pic.y.at(x, y);
2199+ let data = &pic.y.data;
2200+ let have_top = if blk8 < 2 { nbr.b } else { true };
2201+ let have_left = if blk8.is_multiple_of(2) { nbr.a } else { true };
2202+ let have_tr = match blk8 {
2203+ 0 => nbr.b,
2204+ 1 => nbr.c,
2205+ 2 => true,
2206+ _ => false,
2207+ };
2208+ let have_tl = match blk8 {
2209+ 0 => nbr.d,
2210+ 1 => nbr.b,
2211+ 2 => nbr.a,
2212+ _ => true,
2213+ };
2214+ let mut top = [0u8; 16];
2215+ top[..8].copy_from_slice(&data[o - stride..o - stride + 8]);
2216+ if have_tr {
2217+ top[8..].copy_from_slice(&data[o - stride + 8..o - stride + 16]);
2218+ } else {
2219+ let t7 = top[7];
2220+ top[8..].fill(t7);
2221+ }
2222+ let mut left = [0u8; 8];
2223+ for (i, l) in left.iter_mut().enumerate() {
2224+ *l = data[o + i * stride - 1];
2225+ }
2226+ Nbr8 {
2227+ top,
2228+ left,
2229+ top_left: data[o - stride - 1],
2230+ have_top,
2231+ have_left,
2232+ have_tl,
2233+ }
2234+}
2235+
20452236 /// Whole-picture deblocking (spec 8.7): macroblocks in raster order, all
20462237 /// vertical edges then all horizontal edges per macroblock, then chroma.
20472238 // `e` and `j` are edge and segment positions inside the macroblock, used to
@@ -2074,6 +2265,11 @@ fn deblock_picture(pic: &mut Picture) {
20742265 }
20752266 };
20762267 let qp_q = qp_of(addr);
2268+ // 8.7: an 8x8-transform macroblock has no transform edge at luma
2269+ // 4 or 12, so those internal edges are not filtered. Chroma is
2270+ // unaffected for 4:2:0 (its internal edge sits on luma edge 8).
2271+ let internal =
2272+ |e: usize| e.is_multiple_of(2) || pic.mb_flags[addr] & FLAG_TRANS8X8 == 0;
20772273
20782274 // Boundary strengths, per 4-sample segment of each edge (8.7.2.1).
20792275 let mut bs_v = [[0u8; 4]; 4];
@@ -2098,6 +2294,9 @@ fn deblock_picture(pic: &mut Picture) {
20982294 if e == 0 && !filter_left {
20992295 continue;
21002296 }
2297+ if !internal(e) {
2298+ continue;
2299+ }
21012300 let qp_p = if e == 0 { qp_of(addr - 1) } else { qp_q };
21022301 let qp_avg = (qp_p + qp_q + 1) >> 1;
21032302 // Vertical edges stay scalar: a gather/scatter SIMD
@@ -2128,6 +2327,9 @@ fn deblock_picture(pic: &mut Picture) {
21282327 if e == 0 && !filter_top {
21292328 continue;
21302329 }
2330+ if !internal(e) {
2331+ continue;
2332+ }
21312333 let qp_p = if e == 0 { qp_of(addr - mb_w) } else { qp_q };
21322334 let qp_avg = (qp_p + qp_q + 1) >> 1;
21332335 let bs = bs_h[e];
@@ -2271,7 +2473,20 @@ fn boundary_strength(
22712473 if intra {
22722474 return if mb_edge { 4 } else { 3 };
22732475 }
2274- if pic.nz_y[p] != 0 || pic.nz_y[q] != 0 {
2476+ // "the transform block containing the sample has non-zero levels": for an
2477+ // 8x8-transform macroblock that is the whole 8x8, whose four 4x4 slots
2478+ // carry per-slot counts under CAVLC (7.3.5.3.1 splits it into four blocks).
2479+ let coded = |mb: usize, bx: usize, by: usize| -> bool {
2480+ if pic.mb_flags[mb] & FLAG_TRANS8X8 == 0 {
2481+ return pic.nz_y[by * w4 + bx] != 0;
2482+ }
2483+ let (ox, oy) = (bx & !1, by & !1);
2484+ pic.nz_y[oy * w4 + ox] != 0
2485+ || pic.nz_y[oy * w4 + ox + 1] != 0
2486+ || pic.nz_y[(oy + 1) * w4 + ox] != 0
2487+ || pic.nz_y[(oy + 1) * w4 + ox + 1] != 0
2488+ };
2489+ if coded(p_mb, pbx, pby) || coded(q_mb, qbx, qby) {
22752490 return 2;
22762491 }
22772492 let (pr, qr) = (pic.ref_id[p], pic.ref_id[q]);
crates/ec-h264/src/entropy.rsmodified+15 -1
@@ -38,6 +38,9 @@ pub(crate) const FLAG_INTER: u8 = 16;
3838 pub(crate) const FLAG_DIRECT: u8 = 32;
3939 /// mb_type is P_Skip or B_Skip (9.3.3.1.1.1).
4040 pub(crate) const FLAG_SKIP: u8 = 64;
41+/// transform_size_8x8_flag is 1: the luma residual is four 8x8 transform
42+/// blocks, and an Intra_NxN macroblock predicts in 8x8 blocks (8.3.2).
43+pub(crate) const FLAG_TRANS8X8: u8 = 128;
4144
4245 /// Residual block class (spec Table 9-42, the 4:2:0 subset this decoder codes).
4346 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
@@ -101,7 +104,7 @@ pub(crate) struct MbCtx {
101104
102105 /// The slice-data syntax reader.
103106 ///
104-/// The CABAC variant is much the larger of the two (it carries 402 context
107+/// The CABAC variant is much the larger of the two (it carries 436 context
105108 /// variables), and stays inline on purpose: one of these lives per slice on the
106109 /// stack, so boxing it would trade a compile-time size warning for a heap
107110 /// allocation in a decode loop that is otherwise allocation free.
@@ -372,6 +375,17 @@ impl<'a> Entropy<'a> {
372375 }
373376 }
374377
378+ /// Decode one 8x8 luma residual block into `coeff[0..64]` in scan order,
379+ /// returning the number of non-zero coefficients. CABAC only: a CAVLC 8x8
380+ /// block is coded as four interleaved 4x4 blocks (7.3.5.3.1), which the
381+ /// caller reads through [`Entropy::residual_block`].
382+ pub(crate) fn residual_block_8x8(&mut self, coeff: &mut [i32; 64]) -> Result<u8> {
383+ match self {
384+ Entropy::Cavlc(_) => Err(Error::corrupt("8x8 residual block read from a CAVLC slice")),
385+ Entropy::Cabac(c) => c.residual_block_8x8(coeff),
386+ }
387+ }
388+
375389 /// The 384 raw bytes of an I_PCM macroblock (256 luma, 2x64 chroma), after
376390 /// alignment. A CABAC reader restarts its arithmetic engine afterwards
377391 /// (clause 9.3.1.2).
crates/ec-h264/src/pred.rsmodified+303 -0
@@ -163,6 +163,216 @@ pub fn pred_4x4(mode: u8, n: &Nbr4, out: &mut [u8; 16]) {
163163 }
164164 }
165165
166+/// Neighbour samples of an 8x8 luma block (spec 8.3.2.2's 25 samples), already
167+/// low-pass filtered by [`filter_nbr8`]. `top[8..16]` carries the top-right
168+/// substitution rule.
169+#[derive(Debug, Clone, Copy)]
170+pub struct Nbr8 {
171+ /// p'[0..15, -1].
172+ pub top: [u8; 16],
173+ /// p'[-1, 0..7].
174+ pub left: [u8; 8],
175+ /// p'[-1, -1].
176+ pub top_left: u8,
177+ /// p[x, -1] available.
178+ pub have_top: bool,
179+ /// p[-1, y] available.
180+ pub have_left: bool,
181+ /// p[-1, -1] available. Its own neighbour (the above-left macroblock for
182+ /// block 0), not the conjunction of the two runs.
183+ pub have_tl: bool,
184+}
185+
186+/// Reference sample filtering for Intra_8x8 prediction (spec 8.3.2.2.1).
187+///
188+/// Input is the unfiltered neighbourhood; each of the three runs (top row,
189+/// corner, left column) is filtered only when it is wholly available, exactly
190+/// as the clause states, so an edge block keeps the raw samples the prediction
191+/// modes it is allowed to signal actually read.
192+pub fn filter_nbr8(n: &Nbr8) -> Nbr8 {
193+ let mut out = *n;
194+ let have_tl = n.have_tl;
195+ if n.have_top {
196+ let t = |i: usize| i32::from(n.top[i]);
197+ out.top[0] = if have_tl {
198+ ((i32::from(n.top_left) + 2 * t(0) + t(1) + 2) >> 2) as u8
199+ } else {
200+ ((3 * t(0) + t(1) + 2) >> 2) as u8
201+ };
202+ for x in 1..15 {
203+ out.top[x] = ((t(x - 1) + 2 * t(x) + t(x + 1) + 2) >> 2) as u8;
204+ }
205+ out.top[15] = ((t(14) + 3 * t(15) + 2) >> 2) as u8;
206+ }
207+ if have_tl {
208+ // 8-82 to 8-84: which taps the corner takes depends on which of its two
209+ // adjacent samples exist.
210+ let (tl, t0, l0) = (
211+ i32::from(n.top_left),
212+ i32::from(n.top[0]),
213+ i32::from(n.left[0]),
214+ );
215+ out.top_left = match (n.have_top, n.have_left) {
216+ (true, true) => ((t0 + 2 * tl + l0 + 2) >> 2) as u8,
217+ (true, false) => ((3 * tl + t0 + 2) >> 2) as u8,
218+ (false, true) => ((3 * tl + l0 + 2) >> 2) as u8,
219+ (false, false) => n.top_left,
220+ };
221+ }
222+ if n.have_left {
223+ let l = |i: usize| i32::from(n.left[i]);
224+ out.left[0] = if have_tl {
225+ ((i32::from(n.top_left) + 2 * l(0) + l(1) + 2) >> 2) as u8
226+ } else {
227+ ((3 * l(0) + l(1) + 2) >> 2) as u8
228+ };
229+ for y in 1..7 {
230+ out.left[y] = ((l(y - 1) + 2 * l(y) + l(y + 1) + 2) >> 2) as u8;
231+ }
232+ out.left[7] = ((l(6) + 3 * l(7) + 2) >> 2) as u8;
233+ }
234+ out
235+}
236+
237+/// Predict an 8x8 luma block (spec 8.3.2.2.2 - 8.3.2.2.10) into `out` in raster
238+/// order. `n` must already be filtered by [`filter_nbr8`].
239+// x and y are sample coordinates that also index the neighbour runs; the
240+// clause's index arithmetic is what the loops spell out.
241+#[allow(clippy::needless_range_loop)]
242+pub fn pred_8x8(mode: u8, n: &Nbr8, out: &mut [u8; 64]) {
243+ let t = |x: i32| i32::from(n.top[x as usize]);
244+ let l = |y: i32| i32::from(n.left[y as usize]);
245+ let tl = i32::from(n.top_left);
246+ // Index -1 of either run is the corner sample.
247+ let te = |i: i32| if i < 0 { tl } else { t(i) };
248+ let le = |i: i32| if i < 0 { tl } else { l(i) };
249+ match mode {
250+ // Vertical (8-89).
251+ 0 => {
252+ for y in 0..8 {
253+ out[y * 8..y * 8 + 8].copy_from_slice(&n.top[..8]);
254+ }
255+ }
256+ // Horizontal (8-90).
257+ 1 => {
258+ for y in 0..8 {
259+ out[y * 8..y * 8 + 8].fill(n.left[y]);
260+ }
261+ }
262+ // DC (8-91..8-94).
263+ 2 => {
264+ let sum_t: i32 = (0..8).map(t).sum();
265+ let sum_l: i32 = (0..8).map(l).sum();
266+ let v = match (n.have_top, n.have_left) {
267+ (true, true) => (sum_t + sum_l + 8) >> 4,
268+ (true, false) => (sum_t + 4) >> 3,
269+ (false, true) => (sum_l + 4) >> 3,
270+ (false, false) => 128,
271+ };
272+ out.fill(v as u8);
273+ }
274+ // Diagonal down-left (8-95, 8-96).
275+ 3 => {
276+ for y in 0..8i32 {
277+ for x in 0..8i32 {
278+ let v = if x == 7 && y == 7 {
279+ (t(14) + 3 * t(15) + 2) >> 2
280+ } else {
281+ (t(x + y) + 2 * t(x + y + 1) + t(x + y + 2) + 2) >> 2
282+ };
283+ out[(y * 8 + x) as usize] = v as u8;
284+ }
285+ }
286+ }
287+ // Diagonal down-right (8-97..8-99).
288+ 4 => {
289+ for y in 0..8i32 {
290+ for x in 0..8i32 {
291+ let v = if x > y {
292+ (te(x - y - 2) + 2 * te(x - y - 1) + t(x - y) + 2) >> 2
293+ } else if x < y {
294+ (le(y - x - 2) + 2 * le(y - x - 1) + l(y - x) + 2) >> 2
295+ } else {
296+ (t(0) + 2 * tl + l(0) + 2) >> 2
297+ };
298+ out[(y * 8 + x) as usize] = v as u8;
299+ }
300+ }
301+ }
302+ // Vertical-right (8-100..8-103).
303+ 5 => {
304+ for y in 0..8i32 {
305+ for x in 0..8i32 {
306+ let z = 2 * x - y;
307+ let i = x - (y >> 1);
308+ let v = if z >= 0 && z % 2 == 0 {
309+ (te(i - 1) + te(i) + 1) >> 1
310+ } else if z >= 0 {
311+ (te(i - 2) + 2 * te(i - 1) + te(i) + 2) >> 2
312+ } else if z == -1 {
313+ (l(0) + 2 * tl + t(0) + 2) >> 2
314+ } else {
315+ (l(y - 2 * x - 1) + 2 * l(y - 2 * x - 2) + le(y - 2 * x - 3) + 2) >> 2
316+ };
317+ out[(y * 8 + x) as usize] = v as u8;
318+ }
319+ }
320+ }
321+ // Horizontal-down (8-104..8-107).
322+ 6 => {
323+ for y in 0..8i32 {
324+ for x in 0..8i32 {
325+ let z = 2 * y - x;
326+ let i = y - (x >> 1);
327+ let v = if z >= 0 && z % 2 == 0 {
328+ (le(i - 1) + le(i) + 1) >> 1
329+ } else if z >= 0 {
330+ (le(i - 2) + 2 * le(i - 1) + le(i) + 2) >> 2
331+ } else if z == -1 {
332+ (l(0) + 2 * tl + t(0) + 2) >> 2
333+ } else {
334+ (t(x - 2 * y - 1) + 2 * t(x - 2 * y - 2) + te(x - 2 * y - 3) + 2) >> 2
335+ };
336+ out[(y * 8 + x) as usize] = v as u8;
337+ }
338+ }
339+ }
340+ // Vertical-left (8-108, 8-109).
341+ 7 => {
342+ for y in 0..8i32 {
343+ for x in 0..8i32 {
344+ let i = x + (y >> 1);
345+ let v = if y % 2 == 0 {
346+ (t(i) + t(i + 1) + 1) >> 1
347+ } else {
348+ (t(i) + 2 * t(i + 1) + t(i + 2) + 2) >> 2
349+ };
350+ out[(y * 8 + x) as usize] = v as u8;
351+ }
352+ }
353+ }
354+ // Horizontal-up (8-110..8-113).
355+ _ => {
356+ for y in 0..8i32 {
357+ for x in 0..8i32 {
358+ let z = x + 2 * y;
359+ let i = y + (x >> 1);
360+ let v = if z < 13 && z % 2 == 0 {
361+ (l(i) + l(i + 1) + 1) >> 1
362+ } else if z < 13 {
363+ (l(i) + 2 * l(i + 1) + l(i + 2) + 2) >> 2
364+ } else if z == 13 {
365+ (l(6) + 3 * l(7) + 2) >> 2
366+ } else {
367+ l(7)
368+ };
369+ out[(y * 8 + x) as usize] = v as u8;
370+ }
371+ }
372+ }
373+ }
374+}
375+
166376 /// A borrowed window into a picture plane for whole-MB prediction: `data`
167377 /// spans the plane, `stride` its pitch, `origin` the index of this MB's
168378 /// top-left sample.
@@ -324,10 +534,103 @@ pub fn add_residual_4x4(data: &mut [u8], stride: usize, origin: usize, r: &[i32;
324534 }
325535 }
326536
537+/// Add an 8x8 residual to the plane with clamping (spec 8.5.13 / picture
538+/// construction).
539+#[inline]
540+pub fn add_residual_8x8(data: &mut [u8], stride: usize, origin: usize, r: &[i32; 64]) {
541+ for y in 0..8 {
542+ let row = origin + y * stride;
543+ for x in 0..8 {
544+ let p = i32::from(data[row + x]) + r[y * 8 + x];
545+ data[row + x] = p.clamp(0, 255) as u8;
546+ }
547+ }
548+}
549+
327550 #[cfg(test)]
328551 mod tests {
329552 use super::*;
330553
554+ /// A constant neighbourhood survives the reference filter and every 8x8
555+ /// mode reproduces it: the filters are normalised (1+2+1)/4 and the modes
556+ /// are weighted averages of the same samples.
557+ #[test]
558+ fn constant_neighbourhood_is_a_fixed_point() {
559+ let n = Nbr8 {
560+ top: [77; 16],
561+ left: [77; 8],
562+ top_left: 77,
563+ have_top: true,
564+ have_left: true,
565+ have_tl: true,
566+ };
567+ let f = filter_nbr8(&n);
568+ assert_eq!(f.top, [77; 16]);
569+ assert_eq!(f.left, [77; 8]);
570+ assert_eq!(f.top_left, 77);
571+ for mode in 0..9u8 {
572+ let mut out = [0u8; 64];
573+ pred_8x8(mode, &f, &mut out);
574+ assert!(out.iter().all(|&v| v == 77), "mode {mode}: {out:?}");
575+ }
576+ }
577+
578+ /// The reference filter of 8.3.2.2.1 with the corner unavailable uses the
579+ /// 3:1 end taps, and never runs over a run that is not wholly available.
580+ #[test]
581+ fn reference_filter_edges() {
582+ let mut top = [0u8; 16];
583+ for (x, t) in top.iter_mut().enumerate() {
584+ *t = (x * 4) as u8;
585+ }
586+ let n = Nbr8 {
587+ top,
588+ left: [100; 8],
589+ top_left: 9,
590+ have_top: true,
591+ have_left: false,
592+ have_tl: false,
593+ };
594+ let f = filter_nbr8(&n);
595+ // No left run: p'[0, -1] takes 8-79, and the left column is untouched.
596+ // 8-79 with p[0, -1] = 0 and p[1, -1] = 4.
597+ assert_eq!(f.top[0], ((4 + 2) >> 2) as u8);
598+ // 8-80 over p[0..2, -1] = 0, 4, 8.
599+ assert_eq!(f.top[1], ((2 * 4 + 8 + 2) >> 2) as u8);
600+ assert_eq!(f.top[15], ((56 + 3 * 60 + 2) >> 2) as u8);
601+ assert_eq!(f.left, [100; 8]);
602+ assert_eq!(f.top_left, 9);
603+ // DC with no left run averages the top run alone (8-93).
604+ let mut out = [0u8; 64];
605+ pred_8x8(2, &f, &mut out);
606+ let sum: i32 = (0..8).map(|i| i32::from(f.top[i])).sum();
607+ assert!(out.iter().all(|&v| i32::from(v) == (sum + 4) >> 3));
608+ }
609+
610+ /// Vertical and horizontal 8x8 copy the filtered runs.
611+ #[test]
612+ fn vertical_horizontal_8x8() {
613+ let mut top = [0u8; 16];
614+ for (x, t) in top.iter_mut().enumerate() {
615+ *t = (x * 3) as u8;
616+ }
617+ let n = Nbr8 {
618+ top,
619+ left: [1, 2, 3, 4, 5, 6, 7, 8],
620+ top_left: 0,
621+ have_top: true,
622+ have_left: true,
623+ have_tl: true,
624+ };
625+ let mut out = [0u8; 64];
626+ pred_8x8(0, &n, &mut out);
627+ assert_eq!(&out[..8], &n.top[..8]);
628+ assert_eq!(&out[56..], &n.top[..8]);
629+ pred_8x8(1, &n, &mut out);
630+ assert_eq!(out[0], 1);
631+ assert_eq!(out[63], 8);
632+ }
633+
331634 #[test]
332635 fn dc_4x4_fallbacks() {
333636 let n = Nbr4 {
crates/ec-h264/src/tables.rsmodified+15 -0
@@ -503,6 +503,17 @@ pub const NORM_ADJUST_4X4: [[u16; 3]; 6] = [
503503 /// (i % 2, j % 2) == (0,0) -> 0, (1,1) -> 1, else 2 (Equation 8-314).
504504 pub const NORM_ADJUST_CLASS_4X4: [u8; 16] = [0, 2, 0, 2, 2, 1, 2, 1, 0, 2, 0, 2, 2, 1, 2, 1];
505505
506+/// Equation 8-318: normAdjust8x8 v matrix, rows m = qP % 6, columns the six
507+/// position classes of Equation 8-317.
508+pub const NORM_ADJUST_8X8: [[u16; 6]; 6] = [
509+ [20, 18, 32, 19, 25, 24],
510+ [22, 19, 35, 21, 28, 26],
511+ [26, 23, 42, 24, 33, 31],
512+ [28, 25, 45, 26, 35, 33],
513+ [32, 28, 51, 30, 40, 38],
514+ [36, 32, 58, 34, 46, 43],
515+];
516+
506517 /// Table 8-16: alpha' by indexA.
507518 pub const ALPHA: [u8; 52] = [
508519 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,
@@ -540,6 +551,10 @@ pub const TC0: [[u8; 52]; 3] = [
540551 /// 4x4 zig-zag scan: scan position -> raster index (Table 8-13, frame scan).
541552 pub const ZIGZAG_4X4: [u8; 16] = [0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15];
542553
554+/// 8x8 zig-zag scan: scan position -> raster index (Table 8-14, frame scan).
555+/// Shared with the scaling-list parser, which reads the same scan.
556+pub use ec_h264_syntax::sps::ZIGZAG_8X8;
557+
543558 /// luma4x4BlkIdx -> (x, y) position in 4-sample units within the macroblock
544559 /// (spec 6.4.3 inverse 4x4 luma block scan).
545560 pub const BLK4_POS: [(u8, u8); 16] = [
crates/ec-h264/src/transform.rsmodified+137 -2
@@ -1,6 +1,8 @@
1-//! Inverse transforms and scaling (spec 8.5.9 - 8.5.12).
1+//! Inverse transforms and scaling (spec 8.5.9 - 8.5.13).
22
3-use crate::tables::{NORM_ADJUST_4X4, NORM_ADJUST_CLASS_4X4, ZIGZAG_4X4};
3+use crate::tables::{
4+ NORM_ADJUST_4X4, NORM_ADJUST_8X8, NORM_ADJUST_CLASS_4X4, ZIGZAG_4X4, ZIGZAG_8X8,
5+};
46
57 /// Per-QP scaling factors for one 4x4 weight list: `LevelScale4x4(m, i, j) =
68 /// weightScale(i, j) * normAdjust4x4(m, i, j)` (Equation 8-313), in raster
@@ -50,6 +52,139 @@ pub fn dequant_4x4(block: &mut [i32; 16], ls: &LevelScale4x4, qp: i32, skip_dc:
5052 }
5153 }
5254
55+/// Per-QP scaling factors for one 8x8 weight list: `LevelScale8x8(m, i, j) =
56+/// weightScale8x8(i, j) * normAdjust8x8(m, i, j)` (Equation 8-316), in raster
57+/// order, for m = qP % 6.
58+#[derive(Debug, Clone)]
59+pub struct LevelScale8x8 {
60+ /// `[m][raster]`.
61+ pub scale: [[i32; 64]; 6],
62+}
63+
64+/// `normAdjust8x8` position class of raster position `(i, j)` (Equation 8-317),
65+/// where `i` is the row and `j` the column.
66+const fn norm_class_8x8(i: usize, j: usize) -> usize {
67+ let (i4, j4, i2, j2) = (i % 4, j % 4, i % 2, j % 2);
68+ if i4 == 0 && j4 == 0 {
69+ 0
70+ } else if i2 == 1 && j2 == 1 {
71+ 1
72+ } else if i4 == 2 && j4 == 2 {
73+ 2
74+ } else if (i4 == 0 && j2 == 1) || (i2 == 1 && j4 == 0) {
75+ 3
76+ } else if (i4 == 0 && j4 == 2) || (i4 == 2 && j4 == 0) {
77+ 4
78+ } else {
79+ 5
80+ }
81+}
82+
83+impl LevelScale8x8 {
84+ /// Build from a raster-order 8x8 weight list (flat 16s when no scaling
85+ /// matrix is in force).
86+ pub fn new(weight: &[u8; 64]) -> LevelScale8x8 {
87+ let mut scale = [[0i32; 64]; 6];
88+ for (m, row) in scale.iter_mut().enumerate() {
89+ for (idx, s) in row.iter_mut().enumerate() {
90+ let class = norm_class_8x8(idx / 8, idx % 8);
91+ *s = i32::from(weight[idx]) * i32::from(NORM_ADJUST_8X8[m][class]);
92+ }
93+ }
94+ LevelScale8x8 { scale }
95+ }
96+}
97+
98+/// Scale an 8x8 luma block in place (spec 8.5.13.1), raster order.
99+#[inline]
100+pub fn dequant_8x8(block: &mut [i32; 64], ls: &LevelScale8x8, qp: i32) {
101+ let scale = &ls.scale[(qp % 6) as usize];
102+ if qp >= 36 {
103+ let sh = (qp / 6 - 6) as u32;
104+ for i in 0..64 {
105+ block[i] = (block[i] * scale[i]) << sh;
106+ }
107+ } else {
108+ let sh = (6 - qp / 6) as u32;
109+ let round = 1i32 << (5 - qp / 6);
110+ for i in 0..64 {
111+ block[i] = (block[i] * scale[i] + round) >> sh;
112+ }
113+ }
114+}
115+
116+/// Place scan-order coefficients of an 8x8 block into raster order using the
117+/// 8x8 zig-zag (Table 8-14).
118+#[inline]
119+pub fn unzigzag_8x8(scan: &[i32; 64], out: &mut [i32; 64]) {
120+ for (s, &raster) in ZIGZAG_8X8.iter().enumerate() {
121+ out[raster as usize] = scan[s];
122+ }
123+}
124+
125+/// One pass of the 8x8 inverse core transform (Equations 8-358 to 8-381) over
126+/// eight values.
127+#[inline]
128+fn idct8_1d(d: [i32; 8]) -> [i32; 8] {
129+ let e = [
130+ d[0] + d[4],
131+ -d[3] + d[5] - d[7] - (d[7] >> 1),
132+ d[0] - d[4],
133+ d[1] + d[7] - d[3] - (d[3] >> 1),
134+ (d[2] >> 1) - d[6],
135+ -d[1] + d[7] + d[5] + (d[5] >> 1),
136+ d[2] + (d[6] >> 1),
137+ d[3] + d[5] + d[1] + (d[1] >> 1),
138+ ];
139+ let f = [
140+ e[0] + e[6],
141+ e[1] + (e[7] >> 2),
142+ e[2] + e[4],
143+ e[3] + (e[5] >> 2),
144+ e[2] - e[4],
145+ (e[3] >> 2) - e[5],
146+ e[0] - e[6],
147+ e[7] - (e[1] >> 2),
148+ ];
149+ [
150+ f[0] + f[7],
151+ f[2] + f[5],
152+ f[4] + f[3],
153+ f[6] + f[1],
154+ f[6] - f[1],
155+ f[4] - f[3],
156+ f[2] - f[5],
157+ f[0] - f[7],
158+ ]
159+}
160+
161+/// Inverse 8x8 core transform (spec 8.5.13.2): raster-order input `d`, output
162+/// residuals `r` including the final `(x + 32) >> 6`.
163+pub fn inverse_transform_8x8(d: &[i32; 64], r: &mut [i32; 64]) {
164+ let mut g = [0i32; 64];
165+ for i in 0..8 {
166+ let o = i * 8;
167+ let row: [i32; 8] = d[o..o + 8].try_into().expect("eight coefficients");
168+ g[o..o + 8].copy_from_slice(&idct8_1d(row));
169+ }
170+ for j in 0..8 {
171+ let col = [
172+ g[j],
173+ g[8 + j],
174+ g[16 + j],
175+ g[24 + j],
176+ g[32 + j],
177+ g[40 + j],
178+ g[48 + j],
179+ g[56 + j],
180+ ];
181+ let m = idct8_1d(col);
182+ for (i, &v) in m.iter().enumerate() {
183+ r[i * 8 + j] = (v + 32) >> 6;
184+ }
185+ }
186+}
187+
53188 /// Place scan-order coefficients into raster order using the 4x4 zig-zag.
54189 #[inline]
55190 pub fn unzigzag(scan: &[i32; 16], out: &mut [i32; 16]) {
crates/ec-h264/tests/conformance.rsmodified+292 -36
@@ -866,34 +866,6 @@ fn refusals_name_a_feature_the_stream_really_uses() {
866866 ],
867867 "frame_mbs_only_flag 0",
868868 ),
869- (
870- "transform8x8",
871- &[
872- "-profile:v",
873- "high",
874- "-qp",
875- "26",
876- "-x264-params",
877- "cabac=0:8x8dct=1",
878- ],
879- "8x8 transform",
880- ),
881- // The 8x8 transform is refused under CABAC too, where the flag is a
882- // context-coded bin rather than a raw one.
883- (
884- "transform8x8-cabac",
885- &[
886- "-profile:v",
887- "high",
888- "-qp",
889- "26",
890- "-coder",
891- "ac",
892- "-x264-params",
893- "8x8dct=1",
894- ],
895- "8x8 transform",
896- ),
897869 (
898870 "yuv422",
899871 &[
@@ -1735,6 +1707,94 @@ fn extract_annexb(src: &Path, dst: &Path, frames: usize) -> bool {
17351707 )
17361708 }
17371709
1710+/// The same comparison, but demuxed from the container by [`ec_mp4`] instead
1711+/// of extracted to Annex B by ffmpeg's bitstream filter.
1712+///
1713+/// Some real MP4s produce an elementary stream that ffmpeg itself then decodes
1714+/// only three frames of, silently. That is a property of the extraction, not of
1715+/// the file: reading the sample table directly and handing the `avcC` and the
1716+/// length-prefixed samples to the packet entry surface leaves the oracle able to
1717+/// decode the original file, so the comparison is real again.
1718+fn compare_container_streamed(
1719+ source: &Path,
1720+ frames_wanted: usize,
1721+) -> Result<StreamedResult, String> {
1722+ use ec_core::registry::{Decoder as _, Demuxer as _};
1723+ use std::io::Read;
1724+
1725+ let file = std::fs::File::open(source).map_err(|e| e.to_string())?;
1726+ let mut demux = ec_mp4::Mp4Demuxer::new(std::io::BufReader::new(file))
1727+ .map_err(|e| format!("ec-mp4 open: {e}"))?;
1728+ let (stream_index, params) = demux
1729+ .streams()
1730+ .iter()
1731+ .find(|s| s.params.codec == ec_core::registry::CodecId::H264)
1732+ .map(|s| (s.index, s.params.clone()))
1733+ .ok_or("no H.264 track")?;
1734+ let mut dec = ec_h264::H264Decoder::new(params).map_err(|e| format!("{e}"))?;
1735+
1736+ let mut child = Command::new("ffmpeg")
1737+ .args(["-v", "error", "-i"])
1738+ .arg(source)
1739+ .args([
1740+ "-map",
1741+ "0:v:0",
1742+ "-frames:v",
1743+ &frames_wanted.to_string(),
1744+ "-f",
1745+ "rawvideo",
1746+ "-pix_fmt",
1747+ "yuv420p",
1748+ "-",
1749+ ])
1750+ .stdout(std::process::Stdio::piped())
1751+ .stderr(std::process::Stdio::null())
1752+ .spawn()
1753+ .map_err(|e| e.to_string())?;
1754+ let mut out = child.stdout.take().expect("piped stdout");
1755+
1756+ let mut reference = Vec::new();
1757+ let mut result = StreamedResult::default();
1758+ let mut oracle_open = true;
1759+ let mut take = |frame: Vec<u8>, result: &mut StreamedResult, reference: &mut Vec<u8>| {
1760+ result.produced += 1;
1761+ if !oracle_open || result.compared >= frames_wanted {
1762+ return;
1763+ }
1764+ reference.resize(frame.len(), 0);
1765+ if out.read_exact(reference).is_err() {
1766+ oracle_open = false;
1767+ return;
1768+ }
1769+ if let Some(pos) = first_diff(&frame, reference) {
1770+ result.diffs.push((result.compared, pos));
1771+ }
1772+ result.compared += 1;
1773+ };
1774+ let mut drain =
1775+ |dec: &mut ec_h264::H264Decoder, result: &mut StreamedResult, reference: &mut Vec<u8>| {
1776+ while let Ok(ec_core::frame::Frame::Video(f)) = dec.receive_frame() {
1777+ take(frame_bytes(&f), result, reference);
1778+ }
1779+ };
1780+ while result.produced < frames_wanted {
1781+ let packet = match demux.next_packet() {
1782+ Ok(p) => p,
1783+ Err(_) => break,
1784+ };
1785+ if packet.stream != stream_index {
1786+ continue;
1787+ }
1788+ dec.send_packet(&packet).map_err(|e| format!("{e}"))?;
1789+ drain(&mut dec, &mut result, &mut reference);
1790+ }
1791+ dec.flush().map_err(|e| format!("{e}"))?;
1792+ drain(&mut dec, &mut result, &mut reference);
1793+ let _ = child.kill();
1794+ let _ = child.wait();
1795+ Ok(result)
1796+}
1797+
17381798 /// Decode real H.264 files from this machine's library, several hundred frames
17391799 /// each, frame for frame against ffmpeg.
17401800 ///
@@ -1802,15 +1862,47 @@ fn real_library_streams_match_ffmpeg() {
18021862 r.compared
18031863 ));
18041864 }
1805- // The oracle stopped before we did. That is ffmpeg giving up on the
1806- // elementary stream the bitstream filter produced, not a claim about
1807- // this decoder, so the file is reported and not counted either way.
1865+ // The oracle stopped before we did: ffmpeg gave up on the elementary
1866+ // stream its own bitstream filter produced. That is a property of
1867+ // the extraction, so the file is re-run straight out of the
1868+ // container, where the oracle can read the original samples.
18081869 Ok(r) if r.compared < r.produced.min(MIN_FRAMES) => {
1809- table.push_str(&format!(
1810- "{name:<40} {container:<12} {width:>5}px oracle short: ffmpeg gave \
1811- {} frames, we decoded {}\n",
1812- r.compared, r.produced
1813- ));
1870+ match compare_container_streamed(Path::new(path), FRAMES) {
1871+ Ok(c) if !c.diffs.is_empty() => {
1872+ failures.push(format!(
1873+ "{name} (container demux): {} of {} frames differ",
1874+ c.diffs.len(),
1875+ c.compared
1876+ ));
1877+ table.push_str(&format!(
1878+ "{name:<40} {container:<12} {width:>5}px MISMATCH {} of {} \
1879+ (container demux)\n",
1880+ c.diffs.len(),
1881+ c.compared
1882+ ));
1883+ }
1884+ Ok(c) if c.compared >= MIN_FRAMES => {
1885+ decoded += 1;
1886+ table.push_str(&format!(
1887+ "{name:<40} {container:<12} {width:>5}px {:>4} frames bit-exact \
1888+ (container demux)\n",
1889+ c.compared
1890+ ));
1891+ }
1892+ Ok(c) => {
1893+ table.push_str(&format!(
1894+ "{name:<40} {container:<12} {width:>5}px oracle short both ways: \
1895+ ffmpeg gave {} frames, we decoded {}\n",
1896+ c.compared, c.produced
1897+ ));
1898+ }
1899+ Err(e) => {
1900+ table.push_str(&format!(
1901+ "{name:<40} {container:<12} {width:>5}px oracle short, container \
1902+ demux failed: {e}\n"
1903+ ));
1904+ }
1905+ }
18141906 }
18151907 Ok(r) => {
18161908 decoded += 1;
@@ -1989,3 +2081,167 @@ fn spatial_direct_over_a_b_reference_matches_ffmpeg() {
19892081 let _ = std::fs::remove_dir_all(&dir);
19902082 assert!(failures.is_empty(), "{failures:#?}");
19912083 }
2084+
2085+/// True when the stream's picture parameter set enables the 8x8 transform.
2086+///
2087+/// Without this the sweep below would silently prove nothing: an encoder that
2088+/// quietly dropped back to 4x4 would pass every comparison while never coding
2089+/// a single transform_size_8x8_flag.
2090+fn pps_enables_8x8(stream: &Path) -> bool {
2091+ let bytes = std::fs::read(stream).unwrap_or_default();
2092+ let mut rbsp = Vec::new();
2093+ let mut sps = None;
2094+ for nal in ec_h264_syntax::AnnexBIter::new(&bytes) {
2095+ let Some((&header, payload)) = nal.split_first() else {
2096+ continue;
2097+ };
2098+ let Ok(h) = ec_h264_syntax::NalHeader::parse(header) else {
2099+ continue;
2100+ };
2101+ ec_h264_syntax::unescape_rbsp(payload, &mut rbsp);
2102+ match h.unit_type {
2103+ ec_h264_syntax::NalUnitType::Sps => sps = ec_h264_syntax::Sps::parse(&rbsp).ok(),
2104+ ec_h264_syntax::NalUnitType::Pps => {
2105+ if let Ok(p) = ec_h264_syntax::Pps::parse(&rbsp, |_| sps.as_ref()) {
2106+ return p.transform_8x8_mode;
2107+ }
2108+ }
2109+ _ => {}
2110+ }
2111+ }
2112+ false
2113+}
2114+
2115+/// The High-profile 8x8 transform, which every real-world encoder turns on by
2116+/// default: transform_size_8x8_flag, Intra_8x8 prediction with its reference
2117+/// filter (8.3.2), the 8x8 residual under both entropy coders and the 8x8
2118+/// inverse transform of 8.5.13.
2119+///
2120+/// The quantiser sweep matters twice over here: the 8x8 dequant ladder of
2121+/// 8.5.13.1 has its own rounding branch at QP 36, and under CABAC the whole
2122+/// ctxIdx 402..435 initialisation is a function of SliceQPY.
2123+#[test]
2124+fn high_profile_8x8_matches_ffmpeg() {
2125+ if !have_ffmpeg() {
2126+ eprintln!("SKIP: ffmpeg not on PATH");
2127+ return;
2128+ }
2129+ let dir = scratch("high8x8");
2130+ let mut failures = Vec::new();
2131+ // High profile with the 8x8 transform forced on, in both entropy coders.
2132+ let modes: [(&str, &[&str]); 2] = [
2133+ ("cabac", &["-profile:v", "high", "-coder", "ac"]),
2134+ ("cavlc", &["-profile:v", "high", "-coder", "0"]),
2135+ ];
2136+ for (mode, profile) in modes {
2137+ let mut checked = 0usize;
2138+ for qp in 1..=51u32 {
2139+ let mut extra = profile.to_vec();
2140+ let qp_string = qp.to_string();
2141+ extra.extend(["-qp", &qp_string, "-x264-params", "8x8dct=1:i8x8=1"]);
2142+ let tag = format!("i8-{mode}-q{qp}");
2143+ match round_trip(&dir, &tag, "176x144", &extra) {
2144+ Ok(0) => {
2145+ assert!(
2146+ pps_enables_8x8(&dir.join(format!("{tag}.264"))),
2147+ "{tag}: encoder did not enable the 8x8 transform"
2148+ );
2149+ checked += 1;
2150+ }
2151+ Ok(n) => failures.push(format!("intra {mode} qp {qp}: {n} bytes differ")),
2152+ Err(e) => failures.push(e),
2153+ }
2154+ }
2155+ assert!(
2156+ checked >= 40,
2157+ "too few {mode} quantisers exercised: {checked}"
2158+ );
2159+ eprintln!("8x8 intra {mode}: {checked} quantisers bit-exact against ffmpeg");
2160+ }
2161+ let _ = std::fs::remove_dir_all(&dir);
2162+ assert!(failures.is_empty(), "{failures:#?}");
2163+}
2164+
2165+/// The same transform in inter macroblocks: P and B partitions carry the flag
2166+/// only when no 8x8 is split further (7.3.5), the residual rides the inter
2167+/// scaling list, and the deblocker must leave the internal 4-sample edges of an
2168+/// 8x8 macroblock alone (8.7).
2169+#[test]
2170+fn high_profile_8x8_inter_sequences_match_ffmpeg() {
2171+ if !have_ffmpeg() {
2172+ eprintln!("SKIP: ffmpeg not on PATH");
2173+ return;
2174+ }
2175+ let dir = scratch("high8x8-seq");
2176+ let mut failures = Vec::new();
2177+ let cases: &[(&str, &[&str])] = &[
2178+ (
2179+ "p-cabac",
2180+ &["-profile:v", "high", "-coder", "ac", "-bf", "0"],
2181+ ),
2182+ (
2183+ "p-cavlc",
2184+ &["-profile:v", "high", "-coder", "0", "-bf", "0"],
2185+ ),
2186+ (
2187+ "b-cabac",
2188+ &[
2189+ "-profile:v",
2190+ "high",
2191+ "-coder",
2192+ "ac",
2193+ "-bf",
2194+ "2",
2195+ "-x264-params",
2196+ "b-adapt=0",
2197+ ],
2198+ ),
2199+ (
2200+ "b-cavlc",
2201+ &[
2202+ "-profile:v",
2203+ "high",
2204+ "-coder",
2205+ "0",
2206+ "-bf",
2207+ "2",
2208+ "-x264-params",
2209+ "b-adapt=0",
2210+ ],
2211+ ),
2212+ // Sub-8x8 partitions: every macroblock that splits below 8x8 must not
2213+ // carry the flag, and the neighbouring context has to agree.
2214+ (
2215+ "subpart",
2216+ &[
2217+ "-profile:v",
2218+ "high",
2219+ "-coder",
2220+ "ac",
2221+ "-bf",
2222+ "0",
2223+ "-x264-params",
2224+ "partitions=all:8x8dct=1",
2225+ ],
2226+ ),
2227+ ];
2228+ for (tag, extra) in cases {
2229+ let mut args = extra.to_vec();
2230+ args.extend(["-qp", "26"]);
2231+ match x264_encode_gop(&dir, tag, "176x144", 12, &args) {
2232+ None => failures.push(format!("{tag}: ffmpeg cannot encode")),
2233+ Some(stream) => match compare_sequence(&stream) {
2234+ Ok(n) => {
2235+ assert!(
2236+ pps_enables_8x8(&stream),
2237+ "{tag}: encoder did not enable the 8x8 transform"
2238+ );
2239+ eprintln!("8x8 {tag}: {n} frames bit-exact");
2240+ }
2241+ Err(e) => failures.push(format!("{tag}: {e}")),
2242+ },
2243+ }
2244+ }
2245+ let _ = std::fs::remove_dir_all(&dir);
2246+ assert!(failures.is_empty(), "{failures:#?}");
2247+}