forge
Explore
Log in

Don't you dare go Hollow

Intra_8x8 prediction and the 8x8 transform for inter residuals, chosen on rate-distortion cost

Browse files at this commit

4e4673b796d321a7b959c555a0a71e26c7dabe62Ahmet Kaan GümüşParent: 655dfcc
  • feat
    • Intra_8x8 prediction and the 8x8 transform for inter residuals, chosen on rate-distortion cost
Show full message
feat(h264-enc): Intra_8x8 prediction and the 8x8 transform for inter residuals, chosen on rate-distortion cost

transform_size_8x8_flag now follows a real decision: Intra_8x8 is coded
alongside Intra_4x4 and Intra_16x16 (decoder's filtered reference samples
and neighbour-mode rule), P macroblocks try both transform sizes on the
same prediction, and the residual writer takes the cat-5 / interleaved
path. Encoder::transform_8x8_mbs() counts what was chosen; the
reconstruction, ffmpeg and VA-API gates run with 8x8 macroblocks present.
crates/ec-h264/src/decoder.rsmodified+10 -2
@@ -327,7 +327,9 @@ impl Decoder {
327327 .ok_or_else(|| Error::corrupt("active SPS vanished"))?;
328328 let pic = core::mem::take(&mut self.cur);
329329 let marking = self.has_marking.then_some(&self.cur_marking);
330- let stored = self.dpb.store(pic, &sps, &self.cur_info, marking, output_ok);
330+ let stored = self
331+ .dpb
332+ .store(pic, &sps, &self.cur_info, marking, output_ok);
331333 self.sps_map[sps_id] = Some(sps);
332334 stored?;
333335 self.has_picture = false;
@@ -2309,7 +2311,13 @@ pub(crate) fn gather_nbr4(
23092311 /// `blk8` is luma8x8BlkIdx: block 1 reaches the above-right macroblock for its
23102312 /// top-right run, block 2 finds it inside this macroblock, and block 3 has none
23112313 /// (the samples right of it are not decoded yet).
2312-fn gather_nbr8(pic: &Picture, nbr: &MbNeighbors, blk8: usize, x: usize, y: usize) -> Nbr8 {
2314+pub(crate) fn gather_nbr8(
2315+ pic: &Picture,
2316+ nbr: &MbNeighbors,
2317+ blk8: usize,
2318+ x: usize,
2319+ y: usize,
2320+) -> Nbr8 {
23132321 let stride = pic.y.stride;
23142322 let o = pic.y.at(x, y);
23152323 let data = &pic.y.data;
crates/ec-h264/src/enc/cabac_enc.rsmodified+16 -3
@@ -432,7 +432,10 @@ impl CabacEnc {
432432 na: Option<u8>,
433433 nb: Option<u8>,
434434 ) -> u8 {
435- debug_assert!(cat != BlockCat::Luma8x8, "cat 5 goes through residual_block_8x8");
435+ debug_assert!(
436+ cat != BlockCat::Luma8x8,
437+ "cat 5 goes through residual_block_8x8"
438+ );
436439 let cat_i = cat.ctx_block_cat();
437440 let max = cat.max_num_coeff();
438441 let last = (0..max).rev().find(|&i| coeff[i] != 0);
@@ -478,7 +481,13 @@ impl CabacEnc {
478481 /// coeff_abs_level_minus1 and coeff_sign_flag of `coeff[..=last]`, highest
479482 /// scanning position first (9.3.3.1.3 counters). Returns the number of
480483 /// levels written.
481- fn encode_levels(&mut self, coeff: &[i32], last: usize, abs_base: usize, chroma_dc: bool) -> u8 {
484+ fn encode_levels(
485+ &mut self,
486+ coeff: &[i32],
487+ last: usize,
488+ abs_base: usize,
489+ chroma_dc: bool,
490+ ) -> u8 {
482491 let mut num_eq1 = 0u32;
483492 let mut num_gt1 = 0u32;
484493 let mut total = 0u8;
@@ -618,7 +627,11 @@ mod tests {
618627 let mut dec = Cabac::new(&bytes, 0, 30, 0).expect("decoder starts");
619628 for (i, (ctx, flag, c)) in plan.iter().enumerate() {
620629 dec.begin_mb(ctx);
621- assert_eq!(dec.transform_size_8x8_flag().expect("flag"), *flag, "flag {i}");
630+ assert_eq!(
631+ dec.transform_size_8x8_flag().expect("flag"),
632+ *flag,
633+ "flag {i}"
634+ );
622635 let mut got = [0i32; 64];
623636 dec.residual_block_8x8(&mut got).expect("block");
624637 assert_eq!(&got[..], &c[..], "block {i}");
crates/ec-h264/src/enc/entropy.rsmodified+4 -0
@@ -193,6 +193,10 @@ impl EncEntropy {
193193 }
194194 }
195195
196+ pub(crate) fn is_cabac(&self) -> bool {
197+ matches!(self, EncEntropy::Cabac(_))
198+ }
199+
196200 /// `end_of_slice_flag` after a macroblock (CABAC only).
197201 pub(crate) fn end_of_slice(&mut self, last: bool) {
198202 if let (EncEntropy::Cabac(c), false) = (self, last) {
crates/ec-h264/src/enc/headers.rsmodified+1 -2
@@ -264,8 +264,7 @@ mod tests {
264264 assert_eq!(sps.chroma_format_idc, 1);
265265 assert_eq!(sps.bit_depth_luma, 8);
266266 }
267- let pps =
268- Pps::parse(&write_pps(cabac, t8x8), |_| Some(&sps)).expect("PPS parses");
267+ let pps = Pps::parse(&write_pps(cabac, t8x8), |_| Some(&sps)).expect("PPS parses");
269268 assert_eq!(pps.entropy_coding_mode, cabac);
270269 assert_eq!(pps.pic_init_qp, 26);
271270 assert_eq!(pps.transform_8x8_mode, t8x8);
crates/ec-h264/src/enc/mb.rsmodified+282 -28
@@ -15,24 +15,31 @@
1515 use ec_h264_syntax::SliceType;
1616 use wide::i16x16;
1717
18-use crate::decoder::{MbNeighbors, chroma_nz_pair, gather_nbr4, luma_nz_pair, mb_neighbors};
18+use crate::decoder::{
19+ MbNeighbors, chroma_nz_pair, gather_nbr4, gather_nbr8, luma_nz_pair, mb_neighbors,
20+};
1921 use crate::dpb::{BLK_SKIP, Picture};
2022 use crate::entropy::{
21- BlockCat, FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_I16, FLAG_INTER, FLAG_SKIP, MbCtx, MbInfo,
23+ BlockCat, FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_I16, FLAG_INTER, FLAG_SKIP, FLAG_TRANS8X8,
24+ MbCtx, MbInfo,
2225 };
2326 use crate::inter::{RefPlane, integer_origin, mc_chroma, mc_luma};
2427 use crate::mv::{MvCtx, neighbour_mvd, predict_mv, write_block, write_intra_mb, write_mvd};
25-use crate::pred::{PlaneWindow, add_residual_4x4, pred_4x4, pred_16x16, pred_chroma_8x8};
28+use crate::pred::{
29+ PlaneWindow, add_residual_4x4, add_residual_8x8, filter_nbr8, pred_4x4, pred_8x8, pred_16x16,
30+ pred_chroma_8x8,
31+};
2632 use crate::tables::{BLK4_POS, CHROMA_QP};
2733 use crate::transform::{
28- LevelScale4x4, chroma_dc_transform_420, dequant_4x4, inverse_transform_4x4, luma_dc_transform,
29- unzigzag, unzigzag_ac15,
34+ LevelScale4x4, LevelScale8x8, chroma_dc_transform_420, dequant_4x4, dequant_8x8,
35+ inverse_transform_4x4, inverse_transform_8x8, luma_dc_transform, unzigzag, unzigzag_8x8,
36+ unzigzag_ac15,
3037 };
3138
32-use super::entropy::EncEntropy;
39+use super::entropy::{EncEntropy, sub_block_4x4};
3340 use super::quant::{
34- forward_4x4, forward_hadamard_2x2, forward_hadamard_4x4, quant_4x4, quant_chroma_dc,
35- quant_luma_dc,
41+ forward_4x4, forward_8x8, forward_hadamard_2x2, forward_hadamard_4x4, quant_4x4, quant_8x8,
42+ quant_chroma_dc, quant_luma_dc,
3643 };
3744
3845 /// Speed/quality ladder. Two rungs, because the two the incumbent exposed are
@@ -75,6 +82,7 @@ pub(crate) struct MbEnc<'a> {
7582 /// be written for every eligible macroblock (7.3.5).
7683 pub transform_8x8: bool,
7784 pub ls: LevelScale4x4,
85+ pub ls8: LevelScale8x8,
7886 /// Neighbourhood of the macroblock being written (CABAC).
7987 pub mb_ctx: MbCtx,
8088 /// ctxIdxInc for this macroblock's mb_skip_flag.
@@ -85,12 +93,15 @@ pub(crate) struct MbEnc<'a> {
8593 }
8694
8795 /// Quantised levels of one macroblock, scan order per block.
88-#[derive(Default)]
8996 struct Levels {
9097 /// Luma AC/4x4 blocks in Z-order; only `[..15]` is used under Intra_16x16.
9198 luma: [[i32; 16]; 16],
9299 /// Non-zero count per luma block, Z-order.
93100 luma_nz: [u8; 16],
101+ /// transform_size_8x8_flag: the luma residual is `luma8`, not `luma`.
102+ trans8: bool,
103+ /// Luma 8x8 blocks in 8x8 zig-zag order.
104+ luma8: [[i32; 64]; 4],
94105 /// Intra_16x16 luma DC, scan order.
95106 dc: [i32; 16],
96107 /// Chroma DC per component.
@@ -102,6 +113,23 @@ struct Levels {
102113 cbp_chroma: u8,
103114 }
104115
116+impl Default for Levels {
117+ fn default() -> Levels {
118+ Levels {
119+ luma: [[0; 16]; 16],
120+ luma_nz: [0; 16],
121+ trans8: false,
122+ luma8: [[0; 64]; 4],
123+ dc: [0; 16],
124+ chroma_dc: [[0; 16]; 2],
125+ chroma: [[[0; 16]; 4]; 2],
126+ chroma_nz: [[0; 4]; 2],
127+ cbp_luma: 0,
128+ cbp_chroma: 0,
129+ }
130+ }
131+}
132+
105133 /// 4x4 Hadamard sum of absolute transformed differences between the source at
106134 /// `(sx, sy)` and a 4x4 prediction.
107135 fn satd4(src: &[u8], sstride: usize, sx: usize, sy: usize, pred: &[u8], pstride: usize) -> i32 {
@@ -665,10 +693,10 @@ const ZERO_BLOCK_LAMBDA: f64 = 0.4;
665693
666694 /// The rate-distortion test behind the per-block zero decision: coding the
667695 /// block has to buy more squared error than its bits are worth.
668-fn worth_coding(source: &[i32; 16], resid: &[i32; 16], levels: &[i32; 16], qp: i32) -> bool {
696+fn worth_coding(source: &[i32], resid: &[i32], levels: &[i32], qp: i32) -> bool {
669697 let mut ssd_zero = 0i64;
670698 let mut ssd_coded = 0i64;
671- for i in 0..16 {
699+ for i in 0..source.len() {
672700 let z = i64::from(source[i]);
673701 let c = i64::from(source[i] - resid[i]);
674702 ssd_zero += z * z;
@@ -1030,6 +1058,136 @@ fn code_intra_4x4(
10301058 (modes, pred_modes)
10311059 }
10321060
1061+/// Predicted Intra_8x8 mode of `blk8` (8.3.2.1): the decoder's rule, read
1062+/// from the 4x4 slots every size writes its mode into.
1063+fn predicted_mode8(pic: &Picture, nbr: &MbNeighbors, bx: usize, by: usize, blk8: usize) -> u8 {
1064+ let w4 = pic.mb_w * 4;
1065+ let left_avail = if blk8.is_multiple_of(2) { nbr.a } else { true };
1066+ let top_avail = if blk8 < 2 { nbr.b } else { true };
1067+ if left_avail && top_avail {
1068+ pic.i4_modes[by * w4 + bx - 1].min(pic.i4_modes[(by - 1) * w4 + bx])
1069+ } else {
1070+ 2
1071+ }
1072+}
1073+
1074+/// Residual of one 8x8 luma block against the prediction already in the
1075+/// plane: forward transform, quantise, and — when anything survives —
1076+/// reconstruct with the decoder's own inverse. Returns the non-zero count.
1077+fn code_block_8x8(
1078+ pic: &mut Picture,
1079+ e: &MbEnc<'_>,
1080+ x: usize,
1081+ y: usize,
1082+ qp: i32,
1083+ intra: bool,
1084+ out: &mut [i32; 64],
1085+) -> u8 {
1086+ let stride = pic.y.stride;
1087+ let origin = pic.y.at(x, y);
1088+ let mut d = [0i32; 64];
1089+ for ry in 0..8 {
1090+ for rx in 0..8 {
1091+ d[ry * 8 + rx] = i32::from(e.src.y[(y + ry) * e.src.stride + x + rx])
1092+ - i32::from(pic.y.data[origin + ry * stride + rx]);
1093+ }
1094+ }
1095+ let nz = quant_8x8(&forward_8x8(&d), &e.ls8, qp, intra, out);
1096+ if nz == 0 {
1097+ return 0;
1098+ }
1099+ let mut raster = [0i32; 64];
1100+ unzigzag_8x8(out, &mut raster);
1101+ dequant_8x8(&mut raster, &e.ls8, qp);
1102+ let mut resid = [0i32; 64];
1103+ inverse_transform_8x8(&raster, &mut resid);
1104+ if !intra && !worth_coding(&d, &resid, out, qp) {
1105+ *out = [0; 64];
1106+ return 0;
1107+ }
1108+ add_residual_8x8(&mut pic.y.data, stride, origin, &resid);
1109+ nz
1110+}
1111+
1112+/// Code the luma of an Intra_8x8 macroblock, the 8x8 sibling of
1113+/// [`code_intra_4x4`]: neighbours are the decoder's filtered reference
1114+/// samples, and every 4x4 mode slot of a block carries its mode.
1115+fn code_intra_8x8(
1116+ pic: &mut Picture,
1117+ e: &MbEnc<'_>,
1118+ mb_x: usize,
1119+ mb_y: usize,
1120+ qp: i32,
1121+ nbr: &MbNeighbors,
1122+ lv: &mut Levels,
1123+) -> ([u8; 4], [u8; 4]) {
1124+ let w4 = pic.mb_w * 4;
1125+ let mut modes = [2u8; 4];
1126+ let mut pred_modes = [2u8; 4];
1127+ lv.trans8 = true;
1128+ for blk8 in 0..4 {
1129+ let (bx, by) = (mb_x * 4 + (blk8 % 2) * 2, mb_y * 4 + (blk8 / 2) * 2);
1130+ let (x, y) = (mb_x * 16 + (blk8 % 2) * 8, mb_y * 16 + (blk8 / 2) * 8);
1131+ let predicted = predicted_mode8(pic, nbr, bx, by, blk8);
1132+ pred_modes[blk8] = predicted;
1133+ let n = filter_nbr8(&gather_nbr8(pic, nbr, blk8, x, y));
1134+ let allowed = modes_allowed(n.have_top, n.have_left, n.have_tl);
1135+ let mut best = (i32::MAX, predicted.min(2));
1136+ let mut p = [0u8; 64];
1137+ for mode in 0..9u8 {
1138+ if !allowed[mode as usize] {
1139+ continue;
1140+ }
1141+ pred_8x8(mode, &n, &mut p);
1142+ let bits = if mode == predicted { 1 } else { 4 };
1143+ let mut c = e.lambda * bits;
1144+ for q in 0..4 {
1145+ let (ox, oy) = ((q % 2) * 4, (q / 2) * 4);
1146+ c += satd4(&e.src.y, e.src.stride, x + ox, y + oy, &p[oy * 8 + ox..], 8);
1147+ }
1148+ if c < best.0 {
1149+ best = (c, mode);
1150+ }
1151+ }
1152+ let mode = best.1;
1153+ modes[blk8] = mode;
1154+ for dy in 0..2 {
1155+ let base = (by + dy) * w4 + bx;
1156+ pic.i4_modes[base..base + 2].fill(mode);
1157+ }
1158+ pred_8x8(mode, &n, &mut p);
1159+ let stride = pic.y.stride;
1160+ let origin = pic.y.at(x, y);
1161+ for ry in 0..8 {
1162+ let row = origin + ry * stride;
1163+ pic.y.data[row..row + 8].copy_from_slice(&p[ry * 8..ry * 8 + 8]);
1164+ }
1165+ if code_block_8x8(pic, e, x, y, qp, true, &mut lv.luma8[blk8]) > 0 {
1166+ lv.cbp_luma |= 1 << blk8;
1167+ }
1168+ }
1169+ (modes, pred_modes)
1170+}
1171+
1172+/// The inter residual under the 8x8 transform, prediction already in the
1173+/// plane: the sibling of [`code_luma_4x4`].
1174+fn code_luma_8x8(
1175+ pic: &mut Picture,
1176+ e: &MbEnc<'_>,
1177+ mb_x: usize,
1178+ mb_y: usize,
1179+ qp: i32,
1180+ lv: &mut Levels,
1181+) {
1182+ lv.trans8 = true;
1183+ for blk8 in 0..4 {
1184+ let (x, y) = (mb_x * 16 + (blk8 % 2) * 8, mb_y * 16 + (blk8 / 2) * 8);
1185+ if code_block_8x8(pic, e, x, y, qp, false, &mut lv.luma8[blk8]) > 0 {
1186+ lv.cbp_luma |= 1 << blk8;
1187+ }
1188+ }
1189+}
1190+
10331191 /// Squared error of the luma macroblock against the source.
10341192 fn ssd_luma(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> i64 {
10351193 let stride = pic.y.stride;
@@ -1064,14 +1222,14 @@ fn restore_luma(pic: &mut Picture, mb_x: usize, mb_y: usize, src: &[u8; 256]) {
10641222
10651223 /// Bits the luma residual and the mode signalling of an intra macroblock cost,
10661224 /// to the accuracy the mode decision needs.
1067-fn intra_bits(lv: &Levels, i4: Option<(&[u8; 16], &[u8; 16])>) -> i64 {
1225+fn intra_bits(lv: &Levels, i4: Option<(&[u8], &[u8])>) -> i64 {
10681226 let mut bits = estimate_luma_bits(lv);
10691227 match i4 {
1070- // Sixteen mode signals plus the coded_block_pattern the 16x16 form
1071- // derives from its macroblock type instead.
1228+ // Sixteen (or four) mode signals plus the coded_block_pattern the
1229+ // 16x16 form derives from its macroblock type instead.
10721230 Some((modes, pred)) => {
10731231 bits += 6;
1074- for blk in 0..16 {
1232+ for blk in 0..modes.len() {
10751233 bits += if modes[blk] == pred[blk] { 1 } else { 4 };
10761234 }
10771235 }
@@ -1105,7 +1263,10 @@ fn encode_intra_mb(
11051263 let mut lv = Levels::default();
11061264 let mut modes = [2u8; 16];
11071265 let mut pred_modes = [2u8; 16];
1266+ let mut modes8 = [2u8; 4];
1267+ let mut pred_modes8 = [2u8; 4];
11081268 let mut use_i4 = false;
1269+ let mut use_i8 = false;
11091270
11101271 if cost.allow_i4 {
11111272 let mut lv4 = Levels::default();
@@ -1120,12 +1281,37 @@ fn encode_intra_mb(
11201281 modes4[blk] = pic.i4_modes[(by0 + dy as usize) * w4 + bx0 + dx as usize];
11211282 }
11221283
1284+ // Intra_8x8 on the same terms, when the PPS allows it.
1285+ let mut lv8 = Levels::default();
1286+ let mut recon8 = [0u8; 256];
1287+ let cost8 = if e.transform_8x8 {
1288+ let (m8, p8) = code_intra_8x8(pic, e, mb_x, mb_y, qp, &nbr, &mut lv8);
1289+ modes8 = m8;
1290+ pred_modes8 = p8;
1291+ save_luma(pic, mb_x, mb_y, &mut recon8);
1292+ ssd_luma(pic, e, mb_x, mb_y) as f64
1293+ + lambda_ssd(qp) * intra_bits(&lv8, Some((&m8, &p8))) as f64
1294+ } else {
1295+ f64::INFINITY
1296+ };
1297+
11231298 let mut lv16 = Levels::default();
11241299 code_i16_luma(pic, e, mb_x, mb_y, qp, cost.i16_mode, &nbr, &mut lv16);
11251300 let cost16 =
11261301 ssd_luma(pic, e, mb_x, mb_y) as f64 + lambda_ssd(qp) * intra_bits(&lv16, None) as f64;
11271302
1128- if cost4 <= cost16 {
1303+ if cost8 <= cost4 && cost8 <= cost16 {
1304+ use_i4 = true;
1305+ use_i8 = true;
1306+ restore_luma(pic, mb_x, mb_y, &recon8);
1307+ for blk8 in 0..4 {
1308+ for dy in 0..2 {
1309+ let base = (by0 + (blk8 / 2) * 2 + dy) * w4 + bx0 + (blk8 % 2) * 2;
1310+ pic.i4_modes[base..base + 2].fill(modes8[blk8]);
1311+ }
1312+ }
1313+ lv = lv8;
1314+ } else if cost4 <= cost16 {
11291315 use_i4 = true;
11301316 restore_luma(pic, mb_x, mb_y, &recon4);
11311317 for blk in 0..16 {
@@ -1161,10 +1347,16 @@ fn encode_intra_mb(
11611347 w.mb_type(p_slice, intra_type + offset);
11621348 if use_i4 {
11631349 if e.transform_8x8 {
1164- // corner-cut: always 0 until Intra_8x8 prediction exists (E4).
1165- w.transform_size_8x8_flag(false);
1350+ w.transform_size_8x8_flag(use_i8);
11661351 }
1167- for blk in 0..16 {
1352+ // prev_intra8x8_pred_mode_flag / rem_intra8x8_pred_mode share the 4x4
1353+ // elements' binarisation and contexts (9.3.2.2, Table 9-34).
1354+ let (modes, pred_modes): (&[u8], &[u8]) = if use_i8 {
1355+ (&modes8, &pred_modes8)
1356+ } else {
1357+ (&modes, &pred_modes)
1358+ };
1359+ for blk in 0..modes.len() {
11681360 let rem = if modes[blk] == pred_modes[blk] {
11691361 None
11701362 } else if modes[blk] > pred_modes[blk] {
@@ -1230,6 +1422,14 @@ fn ssd_mb(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> i64 {
12301422 /// Rough bit cost of a macroblock's luma residual.
12311423 fn estimate_luma_bits(lv: &Levels) -> i64 {
12321424 let mut bits = 0;
1425+ if lv.trans8 {
1426+ for blk8 in 0..4 {
1427+ if lv.cbp_luma & (1 << blk8) != 0 {
1428+ bits += block_bits(&lv.luma8[blk8]);
1429+ }
1430+ }
1431+ return bits;
1432+ }
12331433 for blk in 0..16 {
12341434 if lv.cbp_luma & (1 << (blk >> 2)) != 0 {
12351435 bits += block_bits(&lv.luma[blk]);
@@ -1256,12 +1456,7 @@ fn block_bits(b: &[i32]) -> i64 {
12561456 /// Rough bit cost of a macroblock's residual, for the skip decision: a level
12571457 /// costs its magnitude's exp-Golomb-ish width, a coded block its token.
12581458 fn estimate_bits(lv: &Levels) -> i64 {
1259- let mut bits = 10i64;
1260- for blk in 0..16 {
1261- if lv.cbp_luma & (1 << (blk >> 2)) != 0 {
1262- bits += block_bits(&lv.luma[blk]);
1263- }
1264- }
1459+ let mut bits = 10 + estimate_luma_bits(lv);
12651460 if lv.cbp_chroma != 0 {
12661461 for comp in 0..2 {
12671462 bits += block_bits(&lv.chroma_dc[comp][..4]);
@@ -1414,7 +1609,29 @@ fn encode_inter_mb(
14141609 let may_skip = choice.prefer_skip;
14151610 let ssd_skip = may_skip.then(|| ssd_mb(pic, e, mb_x, mb_y));
14161611 let mut lv = Levels::default();
1417- code_luma_4x4(pic, e, mb_x, mb_y, qp, false, &mut lv);
1612+ if e.transform_8x8 {
1613+ // Both transform sizes on the same prediction; the cheaper
1614+ // rate-distortion cost is coded.
1615+ let mut pred = [0u8; 256];
1616+ save_luma(pic, mb_x, mb_y, &mut pred);
1617+ code_luma_4x4(pic, e, mb_x, mb_y, qp, false, &mut lv);
1618+ let cost4 =
1619+ ssd_luma(pic, e, mb_x, mb_y) as f64 + lambda_ssd(qp) * estimate_luma_bits(&lv) as f64;
1620+ let mut recon4 = [0u8; 256];
1621+ save_luma(pic, mb_x, mb_y, &mut recon4);
1622+ restore_luma(pic, mb_x, mb_y, &pred);
1623+ let mut lv8 = Levels::default();
1624+ code_luma_8x8(pic, e, mb_x, mb_y, qp, &mut lv8);
1625+ let cost8 =
1626+ ssd_luma(pic, e, mb_x, mb_y) as f64 + lambda_ssd(qp) * estimate_luma_bits(&lv8) as f64;
1627+ if cost8 < cost4 {
1628+ lv = lv8;
1629+ } else {
1630+ restore_luma(pic, mb_x, mb_y, &recon4);
1631+ }
1632+ } else {
1633+ code_luma_4x4(pic, e, mb_x, mb_y, qp, false, &mut lv);
1634+ }
14181635 code_chroma(pic, e, mb_x, mb_y, qp, false, &mut lv);
14191636 let empty = lv.cbp_luma == 0 && lv.cbp_chroma == 0;
14201637 let skip = match ssd_skip {
@@ -1481,9 +1698,9 @@ fn encode_inter_mb(
14811698 }
14821699 w.coded_block_pattern(lv.cbp_luma, lv.cbp_chroma, false);
14831700 // Every shape this encoder emits is 8x8-aligned, so the decoder reads the
1484- // flag whenever luma is coded. corner-cut: always 0 until E4 decides.
1701+ // flag whenever luma is coded.
14851702 if lv.cbp_luma != 0 && e.transform_8x8 {
1486- w.transform_size_8x8_flag(false);
1703+ w.transform_size_8x8_flag(lv.trans8);
14871704 }
14881705 finish_mb(
14891706 pic,
@@ -1545,6 +1762,12 @@ fn finish_mb(
15451762 pic.mb_flags[mb_addr] = FLAG_DECODED
15461763 | if m.is_i16 { FLAG_I16 } else { 0 }
15471764 | if m.intra { 0 } else { FLAG_INTER }
1765+ // The flag only reaches the stream when the decoder reads it (7.3.5).
1766+ | if lv.trans8 && (m.intra || lv.cbp_luma != 0) {
1767+ FLAG_TRANS8X8
1768+ } else {
1769+ 0
1770+ }
15481771 | if m.intra && m.chroma_mode != 0 {
15491772 FLAG_CHROMA_PRED
15501773 } else {
@@ -1561,7 +1784,38 @@ fn finish_mb(
15611784 let tc = w.residual_block(&lv.dc, BlockCat::LumaDc, na, nb);
15621785 dc_cbf |= u8::from(tc != 0);
15631786 }
1787+ if lv.trans8 {
1788+ // The decoder's 8x8 branch: CABAC codes one cat-5 block and reports
1789+ // its count in every 4x4 slot; CAVLC codes four interleaved 4x4
1790+ // blocks, each with its own nC and count.
1791+ for blk8 in 0..4 {
1792+ let (bx, by) = (bx0 + (blk8 % 2) * 2, by0 + (blk8 / 2) * 2);
1793+ if lv.cbp_luma & (1 << blk8) == 0 {
1794+ for dy in 0..2 {
1795+ let base = (by + dy) * w4 + bx;
1796+ pic.nz_y[base..base + 2].fill(0);
1797+ }
1798+ } else if w.is_cabac() {
1799+ let tc = w.residual_block(&lv.luma8[blk8], BlockCat::Luma8x8, None, None);
1800+ for dy in 0..2 {
1801+ let base = (by + dy) * w4 + bx;
1802+ pic.nz_y[base..base + 2].fill(tc.min(16));
1803+ }
1804+ } else {
1805+ for i4 in 0..4 {
1806+ let (dx, dy) = BLK4_POS[blk8 * 4 + i4];
1807+ let (sx, sy) = (bx0 + dx as usize, by0 + dy as usize);
1808+ let (na, nb) = luma_nz_pair(pic, nbr, sx, sy);
1809+ let sub = sub_block_4x4(&lv.luma8[blk8], i4);
1810+ pic.nz_y[sy * w4 + sx] = w.residual_block(&sub, BlockCat::Luma4x4, na, nb);
1811+ }
1812+ }
1813+ }
1814+ }
15641815 for blk in 0..16 {
1816+ if lv.trans8 {
1817+ break;
1818+ }
15651819 let (dx, dy) = BLK4_POS[blk];
15661820 let (bx, by) = (bx0 + dx as usize, by0 + dy as usize);
15671821 let group = 1 << (blk >> 2);
crates/ec-h264/src/enc/mod.rsmodified+21 -1
@@ -35,7 +35,8 @@ use ec_h264_syntax::{SliceType, Sps};
3535
3636 use crate::decoder::deblock_picture;
3737 use crate::dpb::{Picture, SliceParams as DeblockParams};
38-use crate::transform::LevelScale4x4;
38+use crate::entropy::{FLAG_INTER, FLAG_TRANS8X8};
39+use crate::transform::{LevelScale4x4, LevelScale8x8};
3940
4041 use entropy::EncEntropy;
4142 use headers::{SeqParams, SliceParams, write_pps, write_slice_header, write_sps};
@@ -139,6 +140,8 @@ pub struct Encoder {
139140 next_id: i32,
140141 /// True once a reference picture exists.
141142 have_reference: bool,
143+ /// Macroblocks coded with transform_size_8x8_flag set: (intra, inter).
144+ t8x8_mbs: (u64, u64),
142145 }
143146
144147 /// A picture handed to the encoder: three planes, no padding assumptions.
@@ -242,11 +245,18 @@ impl Encoder {
242245 idr_pic_id: 0,
243246 next_id: 0,
244247 have_reference: false,
248+ t8x8_mbs: (0, 0),
245249 cfg,
246250 })
247251 }
248252
249253 /// The configuration in force.
254+ /// Macroblocks coded so far with `transform_size_8x8_flag` set, as
255+ /// `(intra, inter)`: the 8x8 transform's share of the stream.
256+ pub fn transform_8x8_mbs(&self) -> (u64, u64) {
257+ self.t8x8_mbs
258+ }
259+
250260 pub fn config(&self) -> &EncoderConfig {
251261 &self.cfg
252262 }
@@ -366,6 +376,15 @@ impl Encoder {
366376 for (band, worker) in bands.iter().skip(1).zip(rest.iter()) {
367377 merge_band(master, worker, *band);
368378 }
379+ for &f in &master.mb_flags {
380+ if f & FLAG_TRANS8X8 != 0 {
381+ if f & FLAG_INTER != 0 {
382+ self.t8x8_mbs.1 += 1;
383+ } else {
384+ self.t8x8_mbs.0 += 1;
385+ }
386+ }
387+ }
369388 deblock_picture(master);
370389 master.extend_borders();
371390 master.complete = true;
@@ -501,6 +520,7 @@ fn code_band(pic: &mut Picture, job: BandJob<'_>) -> Vec<u8> {
501520 preset: job.cfg.preset,
502521 transform_8x8: job.cfg.transform_8x8,
503522 ls: LevelScale4x4::new(&[16; 16]),
523+ ls8: LevelScale8x8::new(&[16; 64]),
504524 mb_ctx: crate::entropy::MbCtx::default(),
505525 skip_inc: 0,
506526 qp_delta_inc: 0,
crates/ec-h264/src/enc/quant.rsmodified+7 -4
@@ -266,9 +266,7 @@ pub(crate) fn quant_chroma_dc(coef: &[i32; 4], qp: i32, intra: bool, out: &mut [
266266 #[cfg(test)]
267267 mod tests {
268268 use super::*;
269- use crate::transform::{
270- LevelScale8x8, dequant_8x8, inverse_transform_8x8, unzigzag_8x8,
271- };
269+ use crate::transform::{LevelScale8x8, dequant_8x8, inverse_transform_8x8, unzigzag_8x8};
272270
273271 fn ls8() -> LevelScale8x8 {
274272 LevelScale8x8::new(&[16; 64])
@@ -330,7 +328,12 @@ mod tests {
330328 let mut out = [0i32; 64];
331329 inverse_transform_8x8(&raster, &mut out);
332330 for i in 0..64 {
333- assert!((out[i] - src[i]).abs() <= 1, "i {i}: {} vs {}", out[i], src[i]);
331+ assert!(
332+ (out[i] - src[i]).abs() <= 1,
333+ "i {i}: {} vs {}",
334+ out[i],
335+ src[i]
336+ );
334337 }
335338 }
336339
crates/ec-h264/src/enc/vlc.rsmodified+6 -1
@@ -267,7 +267,12 @@ mod tests {
267267 let mut w = BitWriter::new();
268268 let mut tcs = [0u8; 4];
269269 for j in 0..4 {
270- tcs[j] = write_residual_block(&mut w, &super::super::entropy::sub_block_4x4(&c8, j), 16, j as i32 * 3);
270+ tcs[j] = write_residual_block(
271+ &mut w,
272+ &super::super::entropy::sub_block_4x4(&c8, j),
273+ 16,
274+ j as i32 * 3,
275+ );
271276 }
272277 w.write_bit(true);
273278 w.align_to_byte();
crates/ec-h264/tests/encode.rsmodified+78 -0
@@ -153,6 +153,13 @@ fn reconstruction_matches_the_decoder() {
153153 stream.extend_from_slice(&picture.au);
154154 recons.push(enc.reconstruction().expect("a reconstruction"));
155155 }
156+ if t8x8 {
157+ let (intra, inter) = enc.transform_8x8_mbs();
158+ assert!(
159+ intra > 0 && inter > 0,
160+ "{w}x{h} qp {qp} cabac {cabac}: 8x8 MBs intra {intra} inter {inter}"
161+ );
162+ }
156163 let decoded = decode_all(&stream);
157164 assert_eq!(
158165 decoded.len(),
@@ -324,6 +331,7 @@ fn encode_clip(
324331 cfg.gop_size = 10;
325332 cfg.threads = 3;
326333 configure(&mut cfg);
334+ let t8x8 = cfg.transform_8x8;
327335 let mut enc = Encoder::new(cfg).expect("encoder");
328336 let mut clip = Clip::new(w, h);
329337 let mut stream = Vec::new();
@@ -333,9 +341,78 @@ fn encode_clip(
333341 stream.extend_from_slice(&enc.encode(&clip.view()).expect("encode").au);
334342 recons.push(enc.reconstruction().expect("reconstruction"));
335343 }
344+ if t8x8 {
345+ let (intra, inter) = enc.transform_8x8_mbs();
346+ assert!(intra > 0 && inter > 0, "8x8 MBs intra {intra} inter {inter}");
347+ }
336348 (stream, recons)
337349 }
338350
351+/// Flat gradients and glyph-like rectangles: the content the 8x8 transform
352+/// exists for. A 10-frame clip with the flag on must beat the flag off by at
353+/// least 0.3 dB at equal bits, or by 5% fewer bits at equal PSNR.
354+#[test]
355+fn eight_by_eight_gains_on_flat_and_text() {
356+ let (w, h) = (320, 240);
357+ let render = |t: usize, clip: &mut Clip| {
358+ for y in 0..h {
359+ for x in 0..w {
360+ let grad = (x * 3 / 4 + y / 2 + t) as u8 / 2 + 40;
361+ // Glyph rows: 12x16 cells, a 2-sample stem and a bar.
362+ let (cx, cy) = ((x + t) % 12, y % 16);
363+ let glyph = y > h / 3 && cy >= 3 && cy < 13 && (cx < 2 || (cy == 8 && cx < 8));
364+ clip.y[y * w + x] = if glyph { 20 } else { grad };
365+ }
366+ }
367+ clip.u.fill(128);
368+ clip.v.fill(128);
369+ };
370+ let run = |t8x8: bool, qp: i32| {
371+ let mut cfg = EncoderConfig::new(w as u32, h as u32);
372+ cfg.qp = qp;
373+ cfg.gop_size = 10;
374+ cfg.transform_8x8 = t8x8;
375+ let mut enc = Encoder::new(cfg).expect("encoder");
376+ let mut clip = Clip::new(w, h);
377+ let (mut bits, mut sum_psnr) = (0usize, 0.0);
378+ let mut share = 0.0;
379+ for t in 0..10 {
380+ render(t, &mut clip);
381+ bits += enc.encode(&clip.view()).expect("encode").au.len() * 8;
382+ let rec = enc.reconstruction().expect("reconstruction");
383+ sum_psnr += psnr(&clip.y, &rec.0);
384+ }
385+ if t8x8 {
386+ let (i, p) = enc.transform_8x8_mbs();
387+ share = (i + p) as f64 / (10.0 * (w / 16 * h / 16) as f64);
388+ }
389+ (bits as f64, sum_psnr / 10.0, share)
390+ };
391+ // Interpolate the off curve at the on point's bits / PSNR.
392+ let qp = 30;
393+ let (bits_on, psnr_on, share) = run(true, qp);
394+ let off: Vec<_> = [qp - 2, qp, qp + 2].iter().map(|&q| run(false, q)).collect();
395+ let (bits_off, psnr_off, _) = off[1];
396+ // Local slopes of the off curve, from the neighbouring QPs.
397+ let dpsnr_dbits = (off[0].1 - off[2].1) / (off[0].0 - off[2].0);
398+ let psnr_off_at_on_bits = psnr_off + (bits_on - bits_off) * dpsnr_dbits;
399+ let bits_off_at_on_psnr = bits_off + (psnr_on - psnr_off) / dpsnr_dbits;
400+ let gain_db = psnr_on - psnr_off_at_on_bits;
401+ let saving = 1.0 - bits_on / bits_off_at_on_psnr;
402+ eprintln!(
403+ "8x8 qp {qp}: on {bits_on:.0} bits {psnr_on:.2} dB, off {bits_off:.0} bits {psnr_off:.2} dB; \
404+ gain at equal bits {gain_db:+.2} dB, saving at equal PSNR {:.1}%, 8x8 MB share {:.1}%",
405+ saving * 100.0,
406+ share * 100.0
407+ );
408+ assert!(share > 0.0, "no 8x8 macroblocks were coded");
409+ assert!(
410+ gain_db >= 0.3 || saving >= 0.05,
411+ "8x8 gain {gain_db:+.2} dB / {:.1}% is below the bar",
412+ saving * 100.0
413+ );
414+}
415+
339416 /// ffmpeg's decode of our stream is our reconstruction, sample for sample,
340417 /// across a QP sweep and at a size that is not a multiple of a macroblock.
341418 #[test]
@@ -400,6 +477,7 @@ fn vaapi_decodes_our_stream() {
400477 let (w, h) = (352, 288);
401478 let (stream, recons) = encode_clip(w, h, 6, |cfg| {
402479 cfg.qp = 26;
480+ cfg.transform_8x8 = true;
403481 });
404482 let Some(decoded) = ffmpeg_decode(
405483 &stream,
fixturesadded+1 -0
@@ -0,0 +1 @@
1+/home/user/Documents/Code/Rust/edith_codecs/fixtures
\ No newline at end of file