Merge branch 'h264-8x8': High-profile 8x8 transform (Intra_8x8, inter 8x8, CABAC cat-5, CAVLC interleave)
Browse files at this commit11 changed files +897 -63
- crates/ec-h264/src/cabac.rs +4 -4
- crates/ec-h264/src/decoder.rs +10 -2
- crates/ec-h264/src/enc/cabac_enc.rs +116 -8
- crates/ec-h264/src/enc/entropy.rs +31 -0
- crates/ec-h264/src/enc/headers.rs +52 -12
- crates/ec-h264/src/enc/mb.rs +295 -24
- crates/ec-h264/src/enc/mod.rs +38 -2
- crates/ec-h264/src/enc/quant.rs +179 -1
- crates/ec-h264/src/enc/vlc.rs +43 -0
- crates/ec-h264/src/entropy.rs +7 -0
- crates/ec-h264/tests/encode.rs +122 -10
crates/ec-h264/src/cabac.rsmodified+4 -4
| @@ -61,12 +61,12 @@ pub(crate) const OFF_CBF: usize = 85; | ||
| 61 | 61 | pub(crate) const OFF_SIG: usize = 105; |
| 62 | 62 | pub(crate) const OFF_LAST: usize = 166; |
| 63 | 63 | pub(crate) const OFF_ABS: usize = 227; |
| 64 | -const OFF_TRANSFORM_8X8: usize = 399; | |
| 64 | +pub(crate) const OFF_TRANSFORM_8X8: usize = 399; | |
| 65 | 65 | /// significant_coeff_flag / last_significant_coeff_flag / coeff_abs_level_minus1 |
| 66 | 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; | |
| 67 | +pub(crate) const OFF_SIG_8X8: usize = 402; | |
| 68 | +pub(crate) const OFF_LAST_8X8: usize = 417; | |
| 69 | +pub(crate) const OFF_ABS_8X8: usize = 426; | |
| 70 | 70 | |
| 71 | 71 | /// The ctxIdx values the Intra_16x16 part of an mb_type bin string uses, in |
| 72 | 72 | /// bin order: `[b0, CodedBlockPatternLuma, chroma bin 0, chroma bin 1, |
crates/ec-h264/src/decoder.rsmodified+10 -2
| @@ -327,7 +327,9 @@ impl Decoder { | ||
| 327 | 327 | .ok_or_else(|| Error::corrupt("active SPS vanished"))?; |
| 328 | 328 | let pic = core::mem::take(&mut self.cur); |
| 329 | 329 | 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); | |
| 331 | 333 | self.sps_map[sps_id] = Some(sps); |
| 332 | 334 | stored?; |
| 333 | 335 | self.has_picture = false; |
| @@ -2309,7 +2311,13 @@ pub(crate) fn gather_nbr4( | ||
| 2309 | 2311 | /// `blk8` is luma8x8BlkIdx: block 1 reaches the above-right macroblock for its |
| 2310 | 2312 | /// top-right run, block 2 finds it inside this macroblock, and block 3 has none |
| 2311 | 2313 | /// (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 { | |
| 2313 | 2321 | let stride = pic.y.stride; |
| 2314 | 2322 | let o = pic.y.at(x, y); |
| 2315 | 2323 | let data = &pic.y.data; |
crates/ec-h264/src/enc/cabac_enc.rsmodified+116 -8
| @@ -20,12 +20,15 @@ | ||
| 20 | 20 | use ec_core::BitWriter; |
| 21 | 21 | |
| 22 | 22 | use crate::cabac::{ |
| 23 | - ABS_CAT_OFF, CBF_CAT_OFF, I_MB_TYPE_CTX, I_SUFFIX_CTX_P, NUM_CTX, OFF_ABS, OFF_CBF, | |
| 24 | - OFF_CBP_CHROMA, OFF_CBP_LUMA, OFF_CHROMA_PRED, OFF_LAST, OFF_MB_TYPE, OFF_MB_TYPE_P, OFF_MVD, | |
| 25 | - OFF_PREV_I4, OFF_QP_DELTA, OFF_REM_I4, OFF_SIG, OFF_SKIP_P, SIG_CAT_OFF, init_contexts, | |
| 26 | - qp_delta_inc, sig_inc, | |
| 23 | + ABS_CAT_OFF, CBF_CAT_OFF, I_MB_TYPE_CTX, I_SUFFIX_CTX_P, NUM_CTX, OFF_ABS, OFF_ABS_8X8, | |
| 24 | + OFF_CBF, OFF_CBP_CHROMA, OFF_CBP_LUMA, OFF_CHROMA_PRED, OFF_LAST, OFF_LAST_8X8, OFF_MB_TYPE, | |
| 25 | + OFF_MB_TYPE_P, OFF_MVD, OFF_PREV_I4, OFF_QP_DELTA, OFF_REM_I4, OFF_SIG, OFF_SIG_8X8, | |
| 26 | + OFF_SKIP_P, OFF_TRANSFORM_8X8, SIG_CAT_OFF, init_contexts, qp_delta_inc, sig_inc, | |
| 27 | +}; | |
| 28 | +use crate::cabac_tables::{LAST_8X8, SIG_8X8_FRAME}; | |
| 29 | +use crate::entropy::{ | |
| 30 | + BlockCat, FLAG_CHROMA_PRED, FLAG_I16, FLAG_INTER, FLAG_PCM, FLAG_TRANS8X8, MbCtx, MbInfo, | |
| 27 | 31 | }; |
| 28 | -use crate::entropy::{BlockCat, FLAG_CHROMA_PRED, FLAG_I16, FLAG_INTER, FLAG_PCM, MbCtx, MbInfo}; | |
| 29 | 32 | |
| 30 | 33 | /// The arithmetic encoder of 9.3.4 plus the context state. |
| 31 | 34 | pub(crate) struct CabacEnc { |
| @@ -385,6 +388,38 @@ impl CabacEnc { | ||
| 385 | 388 | } |
| 386 | 389 | } |
| 387 | 390 | |
| 391 | + /// transform_size_8x8_flag (9.3.3.1.1.10), mirroring the decoder's | |
| 392 | + /// neighbour condition: available and carrying the flag itself. | |
| 393 | + pub(crate) fn transform_size_8x8_flag(&mut self, flag: bool) { | |
| 394 | + let cond = |n: Option<MbInfo>| match n { | |
| 395 | + None => 0, | |
| 396 | + Some(i) => usize::from(i.flags & FLAG_TRANS8X8 != 0), | |
| 397 | + }; | |
| 398 | + let inc = cond(self.ctx.a) + cond(self.ctx.b); | |
| 399 | + self.decision(OFF_TRANSFORM_8X8 + inc, flag); | |
| 400 | + } | |
| 401 | + | |
| 402 | + /// One luma 8x8 residual block in 8x8 zigzag order (ctxBlockCat 5). No | |
| 403 | + /// coded_block_flag: for 4:2:0 the coded_block_pattern bit is the whole | |
| 404 | + /// signal (7.3.5.3.3), so an all-zero block must not reach here. | |
| 405 | + pub(crate) fn residual_block_8x8(&mut self, coeff: &[i32; 64]) -> u8 { | |
| 406 | + let last = (0..64) | |
| 407 | + .rev() | |
| 408 | + .find(|&i| coeff[i] != 0) | |
| 409 | + .expect("an 8x8 block with cbp set has a coefficient"); | |
| 410 | + for i in 0..63 { | |
| 411 | + let significant = coeff[i] != 0; | |
| 412 | + self.decision(OFF_SIG_8X8 + usize::from(SIG_8X8_FRAME[i]), significant); | |
| 413 | + if significant { | |
| 414 | + self.decision(OFF_LAST_8X8 + usize::from(LAST_8X8[i]), i == last); | |
| 415 | + if i == last { | |
| 416 | + break; | |
| 417 | + } | |
| 418 | + } | |
| 419 | + } | |
| 420 | + self.encode_levels(coeff, last, OFF_ABS_8X8, false) | |
| 421 | + } | |
| 422 | + | |
| 388 | 423 | /// One residual block in scan order (7.3.5.3.3): coded_block_flag, the |
| 389 | 424 | /// significance map, then the levels highest scanning position first. |
| 390 | 425 | /// |
| @@ -397,6 +432,10 @@ impl CabacEnc { | ||
| 397 | 432 | na: Option<u8>, |
| 398 | 433 | nb: Option<u8>, |
| 399 | 434 | ) -> u8 { |
| 435 | + debug_assert!( | |
| 436 | + cat != BlockCat::Luma8x8, | |
| 437 | + "cat 5 goes through residual_block_8x8" | |
| 438 | + ); | |
| 400 | 439 | let cat_i = cat.ctx_block_cat(); |
| 401 | 440 | let max = cat.max_num_coeff(); |
| 402 | 441 | let last = (0..max).rev().find(|&i| coeff[i] != 0); |
| @@ -436,9 +475,19 @@ impl CabacEnc { | ||
| 436 | 475 | } |
| 437 | 476 | } |
| 438 | 477 | |
| 439 | - // Levels, highest scanning position first (9.3.3.1.3 counters). | |
| 440 | - let abs_base = OFF_ABS + ABS_CAT_OFF[cat_i]; | |
| 441 | - let chroma_dc = cat_i == 3; | |
| 478 | + self.encode_levels(coeff, last, OFF_ABS + ABS_CAT_OFF[cat_i], cat_i == 3) | |
| 479 | + } | |
| 480 | + | |
| 481 | + /// coeff_abs_level_minus1 and coeff_sign_flag of `coeff[..=last]`, highest | |
| 482 | + /// scanning position first (9.3.3.1.3 counters). Returns the number of | |
| 483 | + /// levels written. | |
| 484 | + fn encode_levels( | |
| 485 | + &mut self, | |
| 486 | + coeff: &[i32], | |
| 487 | + last: usize, | |
| 488 | + abs_base: usize, | |
| 489 | + chroma_dc: bool, | |
| 490 | + ) -> u8 { | |
| 442 | 491 | let mut num_eq1 = 0u32; |
| 443 | 492 | let mut num_gt1 = 0u32; |
| 444 | 493 | let mut total = 0u8; |
| @@ -530,4 +579,63 @@ mod tests { | ||
| 530 | 579 | assert!(dec.more_macroblocks().expect("terminate"), "bin {i} end"); |
| 531 | 580 | } |
| 532 | 581 | } |
| 582 | + | |
| 583 | + /// transform_size_8x8_flag under every neighbour combination and ctxBlockCat | |
| 584 | + /// 5 blocks over a spread of densities and magnitudes all decode back | |
| 585 | + /// through the decoder's own syntax readers. | |
| 586 | + #[test] | |
| 587 | + fn cat5_blocks_and_transform_flag_round_trip() { | |
| 588 | + let mut state = 0x9E37_79B9u32; | |
| 589 | + let mut rand = move |m: u32| { | |
| 590 | + state ^= state << 13; | |
| 591 | + state ^= state >> 17; | |
| 592 | + state ^= state << 5; | |
| 593 | + state % m | |
| 594 | + }; | |
| 595 | + let nbr = |t: bool| MbInfo { | |
| 596 | + flags: if t { FLAG_TRANS8X8 } else { 0 }, | |
| 597 | + cbp: 0, | |
| 598 | + dc_cbf: 0, | |
| 599 | + }; | |
| 600 | + let mut plan: Vec<(MbCtx, bool, [i32; 64])> = Vec::new(); | |
| 601 | + for n in 0..300 { | |
| 602 | + let ctx = MbCtx { | |
| 603 | + a: [None, Some(nbr(false)), Some(nbr(true))][rand(3) as usize], | |
| 604 | + b: [None, Some(nbr(false)), Some(nbr(true))][rand(3) as usize], | |
| 605 | + qp_delta_inc: 0, | |
| 606 | + }; | |
| 607 | + let mut c = [0i32; 64]; | |
| 608 | + let density = [1, 3, 8, 20, 64][rand(5) as usize]; | |
| 609 | + let mag = [1, 2, 5, 40, 3000][rand(5) as usize]; | |
| 610 | + for _ in 0..density { | |
| 611 | + let v = rand(mag) as i32 + 1; | |
| 612 | + c[rand(64) as usize] = if rand(2) == 0 { v } else { -v }; | |
| 613 | + } | |
| 614 | + c[if n % 7 == 0 { 63 } else { 0 }] = 1; // non-empty; exercise the last position | |
| 615 | + plan.push((ctx, rand(2) == 1, c)); | |
| 616 | + } | |
| 617 | + let mut enc = CabacEnc::new(BitWriter::new(), 30, 0); | |
| 618 | + for (ctx, flag, c) in &plan { | |
| 619 | + enc.begin_mb(ctx); | |
| 620 | + enc.transform_size_8x8_flag(*flag); | |
| 621 | + let tc = enc.residual_block_8x8(c); | |
| 622 | + assert_eq!(usize::from(tc), c.iter().filter(|&&v| v != 0).count()); | |
| 623 | + enc.not_end_of_slice(); | |
| 624 | + } | |
| 625 | + let bytes = enc.finish().into_bytes(); | |
| 626 | + | |
| 627 | + let mut dec = Cabac::new(&bytes, 0, 30, 0).expect("decoder starts"); | |
| 628 | + for (i, (ctx, flag, c)) in plan.iter().enumerate() { | |
| 629 | + dec.begin_mb(ctx); | |
| 630 | + assert_eq!( | |
| 631 | + dec.transform_size_8x8_flag().expect("flag"), | |
| 632 | + *flag, | |
| 633 | + "flag {i}" | |
| 634 | + ); | |
| 635 | + let mut got = [0i32; 64]; | |
| 636 | + dec.residual_block_8x8(&mut got).expect("block"); | |
| 637 | + assert_eq!(&got[..], &c[..], "block {i}"); | |
| 638 | + assert!(dec.more_macroblocks().expect("terminate"), "block {i} end"); | |
| 639 | + } | |
| 640 | + } | |
| 533 | 641 | } |
crates/ec-h264/src/enc/entropy.rsmodified+31 -0
| @@ -13,6 +13,12 @@ use crate::entropy::{BlockCat, MbCtx}; | ||
| 13 | 13 | use super::cabac_enc::CabacEnc; |
| 14 | 14 | use super::vlc::{write_cbp, write_residual_block}; |
| 15 | 15 | |
| 16 | +/// CAVLC's 4x4 sub-block `j` of an 8x8 block in 8x8 zigzag order (7.3.5.3.1, | |
| 17 | +/// 8.5.7): coefficient `i` of sub-block `j` is `c8[4 * i + j]`. | |
| 18 | +pub(crate) fn sub_block_4x4(c8: &[i32; 64], j: usize) -> [i32; 16] { | |
| 19 | + std::array::from_fn(|i| c8[4 * i + j]) | |
| 20 | +} | |
| 21 | + | |
| 16 | 22 | pub(crate) enum EncEntropy { |
| 17 | 23 | Cavlc { |
| 18 | 24 | w: BitWriter, |
| @@ -109,6 +115,16 @@ impl EncEntropy { | ||
| 109 | 115 | } |
| 110 | 116 | } |
| 111 | 117 | |
| 118 | + /// `transform_size_8x8_flag` (7.3.5), where the decoder reads it: after | |
| 119 | + /// mb_type for an Intra_NxN macroblock, after coded_block_pattern for an | |
| 120 | + /// eligible inter one. | |
| 121 | + pub(crate) fn transform_size_8x8_flag(&mut self, flag: bool) { | |
| 122 | + match self { | |
| 123 | + EncEntropy::Cavlc { w, .. } => w.write_bit(flag), | |
| 124 | + EncEntropy::Cabac(c) => c.transform_size_8x8_flag(flag), | |
| 125 | + } | |
| 126 | + } | |
| 127 | + | |
| 112 | 128 | pub(crate) fn intra_chroma_pred_mode(&mut self, mode: u8) { |
| 113 | 129 | match self { |
| 114 | 130 | EncEntropy::Cavlc { w, .. } => w.write_ue(u32::from(mode)), |
| @@ -141,6 +157,11 @@ impl EncEntropy { | ||
| 141 | 157 | |
| 142 | 158 | /// One residual block in scan order; returns its non-zero count, which the |
| 143 | 159 | /// caller records for the neighbours. |
| 160 | + /// | |
| 161 | + /// `Luma8x8` (64 coefficients, 8x8 zigzag order) is CABAC only; the decoder | |
| 162 | + /// records its count in all four 4x4 slots. Under CAVLC the caller writes | |
| 163 | + /// the four [`sub_block_4x4`] blocks as `Luma4x4`, each with its own nC | |
| 164 | + /// and its own count (decoder.rs finish_macroblock, CAVLC branch). | |
| 144 | 165 | pub(crate) fn residual_block( |
| 145 | 166 | &mut self, |
| 146 | 167 | coeff: &[i32], |
| @@ -148,6 +169,12 @@ impl EncEntropy { | ||
| 148 | 169 | na: Option<u8>, |
| 149 | 170 | nb: Option<u8>, |
| 150 | 171 | ) -> u8 { |
| 172 | + if cat == BlockCat::Luma8x8 { | |
| 173 | + let EncEntropy::Cabac(c) = self else { | |
| 174 | + unreachable!("CAVLC codes an 8x8 block as four interleaved 4x4 blocks"); | |
| 175 | + }; | |
| 176 | + return c.residual_block_8x8(coeff.try_into().expect("64 coefficients")); | |
| 177 | + } | |
| 151 | 178 | match self { |
| 152 | 179 | EncEntropy::Cavlc { w, .. } => { |
| 153 | 180 | let nc = if matches!(cat, BlockCat::ChromaDc(_)) { |
| @@ -166,6 +193,10 @@ impl EncEntropy { | ||
| 166 | 193 | } |
| 167 | 194 | } |
| 168 | 195 | |
| 196 | + pub(crate) fn is_cabac(&self) -> bool { | |
| 197 | + matches!(self, EncEntropy::Cabac(_)) | |
| 198 | + } | |
| 199 | + | |
| 169 | 200 | /// `end_of_slice_flag` after a macroblock (CABAC only). |
| 170 | 201 | pub(crate) fn end_of_slice(&mut self, last: bool) { |
| 171 | 202 | if let (EncEntropy::Cabac(c), false) = (self, last) { |
crates/ec-h264/src/enc/headers.rsmodified+52 -12
| @@ -26,6 +26,10 @@ pub(crate) struct SeqParams { | ||
| 26 | 26 | pub bitrate: u32, |
| 27 | 27 | /// CABAC, which Baseline does not allow: the sequence is then Main. |
| 28 | 28 | pub cabac: bool, |
| 29 | + /// 8x8 transform (High profile). Forces `profile_idc` 100 with no | |
| 30 | + /// constraint flags, and the High-profile SPS tail (7.3.2.1.1 subset: | |
| 31 | + /// 4:2:0 8-bit, no scaling matrices, no transform bypass). | |
| 32 | + pub transform_8x8: bool, | |
| 29 | 33 | } |
| 30 | 34 | |
| 31 | 35 | /// `log2_max_frame_num`, fixed: 8 bits of frame_num wrap far beyond the one |
| @@ -73,10 +77,23 @@ pub(crate) fn write_sps(p: &SeqParams) -> Vec<u8> { | ||
| 73 | 77 | let mut w = BitWriter::with_capacity(32); |
| 74 | 78 | // Main when CABAC is in force (Baseline has no CABAC), Baseline otherwise; |
| 75 | 79 | // constraint_set1_flag says the stream also obeys the Main constraints. |
| 76 | - w.write_bits(if p.cabac { 77 } else { 66 }, 8); | |
| 77 | - w.write_bits(if p.cabac { 0b0100_0000 } else { 0b1100_0000 }, 8); | |
| 80 | + // 8x8 transform needs High profile (100), which sets no constraint flags. | |
| 81 | + if p.transform_8x8 { | |
| 82 | + w.write_bits(100, 8); | |
| 83 | + w.write_bits(0, 8); | |
| 84 | + } else { | |
| 85 | + w.write_bits(if p.cabac { 77 } else { 66 }, 8); | |
| 86 | + w.write_bits(if p.cabac { 0b0100_0000 } else { 0b1100_0000 }, 8); | |
| 87 | + } | |
| 78 | 88 | w.write_bits(u32::from(level_idc(p)), 8); |
| 79 | 89 | w.write_ue(0); // seq_parameter_set_id |
| 90 | + if p.transform_8x8 { | |
| 91 | + w.write_ue(1); // chroma_format_idc: 4:2:0 | |
| 92 | + w.write_ue(0); // bit_depth_luma_minus8 | |
| 93 | + w.write_ue(0); // bit_depth_chroma_minus8 | |
| 94 | + w.write_bit(false); // qpprime_y_zero_transform_bypass_flag | |
| 95 | + w.write_bit(false); // seq_scaling_matrix_present_flag | |
| 96 | + } | |
| 80 | 97 | w.write_ue(LOG2_MAX_FRAME_NUM - 4); |
| 81 | 98 | w.write_ue(2); // pic_order_cnt_type 2: output order is decode order |
| 82 | 99 | w.write_ue(1); // max_num_ref_frames |
| @@ -114,7 +131,7 @@ pub(crate) fn write_sps(p: &SeqParams) -> Vec<u8> { | ||
| 114 | 131 | } |
| 115 | 132 | |
| 116 | 133 | /// Write the picture parameter set RBSP (7.3.2.2). |
| 117 | -pub(crate) fn write_pps(cabac: bool) -> Vec<u8> { | |
| 134 | +pub(crate) fn write_pps(cabac: bool, transform_8x8: bool) -> Vec<u8> { | |
| 118 | 135 | let mut w = BitWriter::with_capacity(8); |
| 119 | 136 | w.write_ue(0); // pic_parameter_set_id |
| 120 | 137 | w.write_ue(0); // seq_parameter_set_id |
| @@ -131,6 +148,11 @@ pub(crate) fn write_pps(cabac: bool) -> Vec<u8> { | ||
| 131 | 148 | w.write_bit(false); // deblocking_filter_control_present_flag |
| 132 | 149 | w.write_bit(false); // constrained_intra_pred_flag |
| 133 | 150 | w.write_bit(false); // redundant_pic_cnt_present_flag |
| 151 | + if transform_8x8 { | |
| 152 | + w.write_bit(true); // transform_8x8_mode_flag | |
| 153 | + w.write_bit(false); // pic_scaling_matrix_present_flag | |
| 154 | + w.write_se(0); // second_chroma_qp_index_offset | |
| 155 | + } | |
| 134 | 156 | trailing(&mut w); |
| 135 | 157 | w.into_bytes() |
| 136 | 158 | } |
| @@ -199,6 +221,7 @@ mod tests { | ||
| 199 | 221 | timing: (1000, 60000), |
| 200 | 222 | bitrate: 8_000_000, |
| 201 | 223 | cabac: true, |
| 224 | + transform_8x8: false, | |
| 202 | 225 | } |
| 203 | 226 | } |
| 204 | 227 | |
| @@ -206,15 +229,18 @@ mod tests { | ||
| 206 | 229 | /// parser reads back, geometry, cropping, profile and entropy coder alike. |
| 207 | 230 | #[test] |
| 208 | 231 | fn parameter_sets_parse_back() { |
| 209 | - for (w, h, cabac) in [ | |
| 210 | - (1920, 1080, true), | |
| 211 | - (1920, 1080, false), | |
| 212 | - (640, 480, true), | |
| 213 | - (854, 482, false), | |
| 214 | - (16, 16, true), | |
| 232 | + for (w, h, cabac, t8x8) in [ | |
| 233 | + (1920, 1080, true, false), | |
| 234 | + (1920, 1080, false, false), | |
| 235 | + (640, 480, true, false), | |
| 236 | + (854, 482, false, false), | |
| 237 | + (16, 16, true, false), | |
| 238 | + (640, 480, true, true), | |
| 239 | + (640, 480, false, true), | |
| 215 | 240 | ] { |
| 216 | 241 | let mut p = params(w, h); |
| 217 | 242 | p.cabac = cabac; |
| 243 | + p.transform_8x8 = t8x8; | |
| 218 | 244 | let sps = Sps::parse(&write_sps(&p)).expect("SPS parses"); |
| 219 | 245 | assert_eq!((sps.width, sps.height), (w, h), "{w}x{h} crop"); |
| 220 | 246 | assert_eq!(sps.mb_width, p.mb_w); |
| @@ -224,10 +250,24 @@ mod tests { | ||
| 224 | 250 | assert!(sps.frame_mbs_only); |
| 225 | 251 | let vui = sps.vui.as_ref().expect("VUI present"); |
| 226 | 252 | assert_eq!(vui.timing_info, Some((1000, 60000, true))); |
| 227 | - assert_eq!(sps.profile_idc, if cabac { 77 } else { 66 }); | |
| 228 | - let pps = Pps::parse(&write_pps(cabac), |_| Some(&sps)).expect("PPS parses"); | |
| 253 | + assert_eq!( | |
| 254 | + sps.profile_idc, | |
| 255 | + if t8x8 { | |
| 256 | + 100 | |
| 257 | + } else if cabac { | |
| 258 | + 77 | |
| 259 | + } else { | |
| 260 | + 66 | |
| 261 | + } | |
| 262 | + ); | |
| 263 | + if t8x8 { | |
| 264 | + assert_eq!(sps.chroma_format_idc, 1); | |
| 265 | + assert_eq!(sps.bit_depth_luma, 8); | |
| 266 | + } | |
| 267 | + let pps = Pps::parse(&write_pps(cabac, t8x8), |_| Some(&sps)).expect("PPS parses"); | |
| 229 | 268 | assert_eq!(pps.entropy_coding_mode, cabac); |
| 230 | 269 | assert_eq!(pps.pic_init_qp, 26); |
| 270 | + assert_eq!(pps.transform_8x8_mode, t8x8); | |
| 231 | 271 | } |
| 232 | 272 | } |
| 233 | 273 | |
| @@ -246,7 +286,7 @@ mod tests { | ||
| 246 | 286 | fn slice_header_parses_back() { |
| 247 | 287 | let p = params(320, 240); |
| 248 | 288 | let sps = Sps::parse(&write_sps(&p)).unwrap(); |
| 249 | - let pps = Pps::parse(&write_pps(true), |_| Some(&sps)).unwrap(); | |
| 289 | + let pps = Pps::parse(&write_pps(true, false), |_| Some(&sps)).unwrap(); | |
| 250 | 290 | for (idr, slice_type, first_mb, qp) in [ |
| 251 | 291 | (true, SliceType::I, 0u32, 30i32), |
| 252 | 292 | (false, SliceType::P, 40, 18), |
crates/ec-h264/src/enc/mb.rsmodified+295 -24
| @@ -15,24 +15,31 @@ | ||
| 15 | 15 | use ec_h264_syntax::SliceType; |
| 16 | 16 | use wide::i16x16; |
| 17 | 17 | |
| 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 | +}; | |
| 19 | 21 | use crate::dpb::{BLK_SKIP, Picture}; |
| 20 | 22 | 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, | |
| 22 | 25 | }; |
| 23 | 26 | use crate::inter::{RefPlane, integer_origin, mc_chroma, mc_luma}; |
| 24 | 27 | 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 | +}; | |
| 26 | 32 | use crate::tables::{BLK4_POS, CHROMA_QP}; |
| 27 | 33 | 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, | |
| 30 | 37 | }; |
| 31 | 38 | |
| 32 | -use super::entropy::EncEntropy; | |
| 39 | +use super::entropy::{EncEntropy, sub_block_4x4}; | |
| 33 | 40 | 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, | |
| 36 | 43 | }; |
| 37 | 44 | |
| 38 | 45 | /// Speed/quality ladder. Two rungs, because the two the incumbent exposed are |
| @@ -71,7 +78,11 @@ pub(crate) struct MbEnc<'a> { | ||
| 71 | 78 | /// Lagrangian multiplier in the SATD domain. |
| 72 | 79 | pub lambda: i32, |
| 73 | 80 | pub preset: Preset, |
| 81 | + /// The PPS carries transform_8x8_mode_flag: transform_size_8x8_flag must | |
| 82 | + /// be written for every eligible macroblock (7.3.5). | |
| 83 | + pub transform_8x8: bool, | |
| 74 | 84 | pub ls: LevelScale4x4, |
| 85 | + pub ls8: LevelScale8x8, | |
| 75 | 86 | /// Neighbourhood of the macroblock being written (CABAC). |
| 76 | 87 | pub mb_ctx: MbCtx, |
| 77 | 88 | /// ctxIdxInc for this macroblock's mb_skip_flag. |
| @@ -82,12 +93,15 @@ pub(crate) struct MbEnc<'a> { | ||
| 82 | 93 | } |
| 83 | 94 | |
| 84 | 95 | /// Quantised levels of one macroblock, scan order per block. |
| 85 | -#[derive(Default)] | |
| 86 | 96 | struct Levels { |
| 87 | 97 | /// Luma AC/4x4 blocks in Z-order; only `[..15]` is used under Intra_16x16. |
| 88 | 98 | luma: [[i32; 16]; 16], |
| 89 | 99 | /// Non-zero count per luma block, Z-order. |
| 90 | 100 | 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], | |
| 91 | 105 | /// Intra_16x16 luma DC, scan order. |
| 92 | 106 | dc: [i32; 16], |
| 93 | 107 | /// Chroma DC per component. |
| @@ -99,6 +113,23 @@ struct Levels { | ||
| 99 | 113 | cbp_chroma: u8, |
| 100 | 114 | } |
| 101 | 115 | |
| 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 | + | |
| 102 | 133 | /// 4x4 Hadamard sum of absolute transformed differences between the source at |
| 103 | 134 | /// `(sx, sy)` and a 4x4 prediction. |
| 104 | 135 | fn satd4(src: &[u8], sstride: usize, sx: usize, sy: usize, pred: &[u8], pstride: usize) -> i32 { |
| @@ -662,10 +693,10 @@ const ZERO_BLOCK_LAMBDA: f64 = 0.4; | ||
| 662 | 693 | |
| 663 | 694 | /// The rate-distortion test behind the per-block zero decision: coding the |
| 664 | 695 | /// block has to buy more squared error than its bits are worth. |
| 665 | -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 { | |
| 666 | 697 | let mut ssd_zero = 0i64; |
| 667 | 698 | let mut ssd_coded = 0i64; |
| 668 | - for i in 0..16 { | |
| 699 | + for i in 0..source.len() { | |
| 669 | 700 | let z = i64::from(source[i]); |
| 670 | 701 | let c = i64::from(source[i] - resid[i]); |
| 671 | 702 | ssd_zero += z * z; |
| @@ -1027,6 +1058,136 @@ fn code_intra_4x4( | ||
| 1027 | 1058 | (modes, pred_modes) |
| 1028 | 1059 | } |
| 1029 | 1060 | |
| 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 | + | |
| 1030 | 1191 | /// Squared error of the luma macroblock against the source. |
| 1031 | 1192 | fn ssd_luma(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> i64 { |
| 1032 | 1193 | let stride = pic.y.stride; |
| @@ -1061,14 +1222,14 @@ fn restore_luma(pic: &mut Picture, mb_x: usize, mb_y: usize, src: &[u8; 256]) { | ||
| 1061 | 1222 | |
| 1062 | 1223 | /// Bits the luma residual and the mode signalling of an intra macroblock cost, |
| 1063 | 1224 | /// to the accuracy the mode decision needs. |
| 1064 | -fn intra_bits(lv: &Levels, i4: Option<(&[u8; 16], &[u8; 16])>) -> i64 { | |
| 1225 | +fn intra_bits(lv: &Levels, i4: Option<(&[u8], &[u8])>) -> i64 { | |
| 1065 | 1226 | let mut bits = estimate_luma_bits(lv); |
| 1066 | 1227 | match i4 { |
| 1067 | - // Sixteen mode signals plus the coded_block_pattern the 16x16 form | |
| 1068 | - // 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. | |
| 1069 | 1230 | Some((modes, pred)) => { |
| 1070 | 1231 | bits += 6; |
| 1071 | - for blk in 0..16 { | |
| 1232 | + for blk in 0..modes.len() { | |
| 1072 | 1233 | bits += if modes[blk] == pred[blk] { 1 } else { 4 }; |
| 1073 | 1234 | } |
| 1074 | 1235 | } |
| @@ -1102,7 +1263,10 @@ fn encode_intra_mb( | ||
| 1102 | 1263 | let mut lv = Levels::default(); |
| 1103 | 1264 | let mut modes = [2u8; 16]; |
| 1104 | 1265 | let mut pred_modes = [2u8; 16]; |
| 1266 | + let mut modes8 = [2u8; 4]; | |
| 1267 | + let mut pred_modes8 = [2u8; 4]; | |
| 1105 | 1268 | let mut use_i4 = false; |
| 1269 | + let mut use_i8 = false; | |
| 1106 | 1270 | |
| 1107 | 1271 | if cost.allow_i4 { |
| 1108 | 1272 | let mut lv4 = Levels::default(); |
| @@ -1117,12 +1281,37 @@ fn encode_intra_mb( | ||
| 1117 | 1281 | modes4[blk] = pic.i4_modes[(by0 + dy as usize) * w4 + bx0 + dx as usize]; |
| 1118 | 1282 | } |
| 1119 | 1283 | |
| 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 | + | |
| 1120 | 1298 | let mut lv16 = Levels::default(); |
| 1121 | 1299 | code_i16_luma(pic, e, mb_x, mb_y, qp, cost.i16_mode, &nbr, &mut lv16); |
| 1122 | 1300 | let cost16 = |
| 1123 | 1301 | ssd_luma(pic, e, mb_x, mb_y) as f64 + lambda_ssd(qp) * intra_bits(&lv16, None) as f64; |
| 1124 | 1302 | |
| 1125 | - 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 { | |
| 1126 | 1315 | use_i4 = true; |
| 1127 | 1316 | restore_luma(pic, mb_x, mb_y, &recon4); |
| 1128 | 1317 | for blk in 0..16 { |
| @@ -1157,7 +1346,17 @@ fn encode_intra_mb( | ||
| 1157 | 1346 | let offset = if p_slice { 5 } else { 0 }; |
| 1158 | 1347 | w.mb_type(p_slice, intra_type + offset); |
| 1159 | 1348 | if use_i4 { |
| 1160 | - for blk in 0..16 { | |
| 1349 | + if e.transform_8x8 { | |
| 1350 | + w.transform_size_8x8_flag(use_i8); | |
| 1351 | + } | |
| 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() { | |
| 1161 | 1360 | let rem = if modes[blk] == pred_modes[blk] { |
| 1162 | 1361 | None |
| 1163 | 1362 | } else if modes[blk] > pred_modes[blk] { |
| @@ -1223,6 +1422,19 @@ fn ssd_mb(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> i64 { | ||
| 1223 | 1422 | /// Rough bit cost of a macroblock's luma residual. |
| 1224 | 1423 | fn estimate_luma_bits(lv: &Levels) -> i64 { |
| 1225 | 1424 | let mut bits = 0; |
| 1425 | + if lv.trans8 { | |
| 1426 | + for blk8 in 0..4 { | |
| 1427 | + if lv.cbp_luma & (1 << blk8) != 0 { | |
| 1428 | + // A level's position costs two more bits in a 64-coefficient | |
| 1429 | + // significance map than in a 16-coefficient one; measured | |
| 1430 | + // against the coded size on the text clip, without this the | |
| 1431 | + // estimate undercharges Intra_8x8 by ~44 bits a macroblock. | |
| 1432 | + let b = &lv.luma8[blk8]; | |
| 1433 | + bits += block_bits(b) + 2 * b.iter().filter(|&&l| l != 0).count() as i64; | |
| 1434 | + } | |
| 1435 | + } | |
| 1436 | + return bits; | |
| 1437 | + } | |
| 1226 | 1438 | for blk in 0..16 { |
| 1227 | 1439 | if lv.cbp_luma & (1 << (blk >> 2)) != 0 { |
| 1228 | 1440 | bits += block_bits(&lv.luma[blk]); |
| @@ -1249,12 +1461,7 @@ fn block_bits(b: &[i32]) -> i64 { | ||
| 1249 | 1461 | /// Rough bit cost of a macroblock's residual, for the skip decision: a level |
| 1250 | 1462 | /// costs its magnitude's exp-Golomb-ish width, a coded block its token. |
| 1251 | 1463 | fn estimate_bits(lv: &Levels) -> i64 { |
| 1252 | - let mut bits = 10i64; | |
| 1253 | - for blk in 0..16 { | |
| 1254 | - if lv.cbp_luma & (1 << (blk >> 2)) != 0 { | |
| 1255 | - bits += block_bits(&lv.luma[blk]); | |
| 1256 | - } | |
| 1257 | - } | |
| 1464 | + let mut bits = 10 + estimate_luma_bits(lv); | |
| 1258 | 1465 | if lv.cbp_chroma != 0 { |
| 1259 | 1466 | for comp in 0..2 { |
| 1260 | 1467 | bits += block_bits(&lv.chroma_dc[comp][..4]); |
| @@ -1407,7 +1614,29 @@ fn encode_inter_mb( | ||
| 1407 | 1614 | let may_skip = choice.prefer_skip; |
| 1408 | 1615 | let ssd_skip = may_skip.then(|| ssd_mb(pic, e, mb_x, mb_y)); |
| 1409 | 1616 | let mut lv = Levels::default(); |
| 1410 | - code_luma_4x4(pic, e, mb_x, mb_y, qp, false, &mut lv); | |
| 1617 | + if e.transform_8x8 { | |
| 1618 | + // Both transform sizes on the same prediction; the cheaper | |
| 1619 | + // rate-distortion cost is coded. | |
| 1620 | + let mut pred = [0u8; 256]; | |
| 1621 | + save_luma(pic, mb_x, mb_y, &mut pred); | |
| 1622 | + code_luma_4x4(pic, e, mb_x, mb_y, qp, false, &mut lv); | |
| 1623 | + let cost4 = | |
| 1624 | + ssd_luma(pic, e, mb_x, mb_y) as f64 + lambda_ssd(qp) * estimate_luma_bits(&lv) as f64; | |
| 1625 | + let mut recon4 = [0u8; 256]; | |
| 1626 | + save_luma(pic, mb_x, mb_y, &mut recon4); | |
| 1627 | + restore_luma(pic, mb_x, mb_y, &pred); | |
| 1628 | + let mut lv8 = Levels::default(); | |
| 1629 | + code_luma_8x8(pic, e, mb_x, mb_y, qp, &mut lv8); | |
| 1630 | + let cost8 = | |
| 1631 | + ssd_luma(pic, e, mb_x, mb_y) as f64 + lambda_ssd(qp) * estimate_luma_bits(&lv8) as f64; | |
| 1632 | + if cost8 < cost4 { | |
| 1633 | + lv = lv8; | |
| 1634 | + } else { | |
| 1635 | + restore_luma(pic, mb_x, mb_y, &recon4); | |
| 1636 | + } | |
| 1637 | + } else { | |
| 1638 | + code_luma_4x4(pic, e, mb_x, mb_y, qp, false, &mut lv); | |
| 1639 | + } | |
| 1411 | 1640 | code_chroma(pic, e, mb_x, mb_y, qp, false, &mut lv); |
| 1412 | 1641 | let empty = lv.cbp_luma == 0 && lv.cbp_chroma == 0; |
| 1413 | 1642 | let skip = match ssd_skip { |
| @@ -1473,6 +1702,11 @@ fn encode_inter_mb( | ||
| 1473 | 1702 | } |
| 1474 | 1703 | } |
| 1475 | 1704 | w.coded_block_pattern(lv.cbp_luma, lv.cbp_chroma, false); |
| 1705 | + // Every shape this encoder emits is 8x8-aligned, so the decoder reads the | |
| 1706 | + // flag whenever luma is coded. | |
| 1707 | + if lv.cbp_luma != 0 && e.transform_8x8 { | |
| 1708 | + w.transform_size_8x8_flag(lv.trans8); | |
| 1709 | + } | |
| 1476 | 1710 | finish_mb( |
| 1477 | 1711 | pic, |
| 1478 | 1712 | e, |
| @@ -1533,6 +1767,12 @@ fn finish_mb( | ||
| 1533 | 1767 | pic.mb_flags[mb_addr] = FLAG_DECODED |
| 1534 | 1768 | | if m.is_i16 { FLAG_I16 } else { 0 } |
| 1535 | 1769 | | if m.intra { 0 } else { FLAG_INTER } |
| 1770 | + // The flag only reaches the stream when the decoder reads it (7.3.5). | |
| 1771 | + | if lv.trans8 && (m.intra || lv.cbp_luma != 0) { | |
| 1772 | + FLAG_TRANS8X8 | |
| 1773 | + } else { | |
| 1774 | + 0 | |
| 1775 | + } | |
| 1536 | 1776 | | if m.intra && m.chroma_mode != 0 { |
| 1537 | 1777 | FLAG_CHROMA_PRED |
| 1538 | 1778 | } else { |
| @@ -1549,7 +1789,38 @@ fn finish_mb( | ||
| 1549 | 1789 | let tc = w.residual_block(&lv.dc, BlockCat::LumaDc, na, nb); |
| 1550 | 1790 | dc_cbf |= u8::from(tc != 0); |
| 1551 | 1791 | } |
| 1792 | + if lv.trans8 { | |
| 1793 | + // The decoder's 8x8 branch: CABAC codes one cat-5 block and reports | |
| 1794 | + // its count in every 4x4 slot; CAVLC codes four interleaved 4x4 | |
| 1795 | + // blocks, each with its own nC and count. | |
| 1796 | + for blk8 in 0..4 { | |
| 1797 | + let (bx, by) = (bx0 + (blk8 % 2) * 2, by0 + (blk8 / 2) * 2); | |
| 1798 | + if lv.cbp_luma & (1 << blk8) == 0 { | |
| 1799 | + for dy in 0..2 { | |
| 1800 | + let base = (by + dy) * w4 + bx; | |
| 1801 | + pic.nz_y[base..base + 2].fill(0); | |
| 1802 | + } | |
| 1803 | + } else if w.is_cabac() { | |
| 1804 | + let tc = w.residual_block(&lv.luma8[blk8], BlockCat::Luma8x8, None, None); | |
| 1805 | + for dy in 0..2 { | |
| 1806 | + let base = (by + dy) * w4 + bx; | |
| 1807 | + pic.nz_y[base..base + 2].fill(tc.min(16)); | |
| 1808 | + } | |
| 1809 | + } else { | |
| 1810 | + for i4 in 0..4 { | |
| 1811 | + let (dx, dy) = BLK4_POS[blk8 * 4 + i4]; | |
| 1812 | + let (sx, sy) = (bx0 + dx as usize, by0 + dy as usize); | |
| 1813 | + let (na, nb) = luma_nz_pair(pic, nbr, sx, sy); | |
| 1814 | + let sub = sub_block_4x4(&lv.luma8[blk8], i4); | |
| 1815 | + pic.nz_y[sy * w4 + sx] = w.residual_block(&sub, BlockCat::Luma4x4, na, nb); | |
| 1816 | + } | |
| 1817 | + } | |
| 1818 | + } | |
| 1819 | + } | |
| 1552 | 1820 | for blk in 0..16 { |
| 1821 | + if lv.trans8 { | |
| 1822 | + break; | |
| 1823 | + } | |
| 1553 | 1824 | let (dx, dy) = BLK4_POS[blk]; |
| 1554 | 1825 | let (bx, by) = (bx0 + dx as usize, by0 + dy as usize); |
| 1555 | 1826 | let group = 1 << (blk >> 2); |
crates/ec-h264/src/enc/mod.rsmodified+38 -2
| @@ -35,7 +35,8 @@ use ec_h264_syntax::{SliceType, Sps}; | ||
| 35 | 35 | |
| 36 | 36 | use crate::decoder::deblock_picture; |
| 37 | 37 | 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}; | |
| 39 | 40 | |
| 40 | 41 | use entropy::EncEntropy; |
| 41 | 42 | use headers::{SeqParams, SliceParams, write_pps, write_slice_header, write_sps}; |
| @@ -71,6 +72,19 @@ pub struct EncoderConfig { | ||
| 71 | 72 | pub threads: usize, |
| 72 | 73 | /// Quantiser for constant-QP mode (`bitrate` zero). |
| 73 | 74 | pub qp: i32, |
| 75 | + /// 8x8 transform (High profile). Off by default. | |
| 76 | + /// | |
| 77 | + /// NOT SAFE TO SET YET: this only flips the SPS/PPS High-profile tail | |
| 78 | + /// (`profile_idc` 100, `transform_8x8_mode_flag`). Once the PPS carries | |
| 79 | + /// that flag, a conformant decoder unconditionally reads an extra | |
| 80 | + /// `transform_size_8x8_flag` per macroblock (7.3.5: every non-I16x16 | |
| 81 | + /// intra macroblock, and every inter macroblock with a nonzero luma cbp — | |
| 82 | + /// see `decoder.rs:1151` and `:1789-1793`). Nothing in `enc::entropy` / | |
| 83 | + /// `enc::mb` writes that bit yet, so turning this on desyncs every real | |
| 84 | + /// stream (headers.rs's own tests only exercise the parameter sets, not a | |
| 85 | + /// full encode). Wiring that emission — and then the mode decision that | |
| 86 | + /// actually picks 8x8 blocks — is later work. | |
| 87 | + pub transform_8x8: bool, | |
| 74 | 88 | } |
| 75 | 89 | |
| 76 | 90 | impl EncoderConfig { |
| @@ -87,6 +101,7 @@ impl EncoderConfig { | ||
| 87 | 101 | cabac: true, |
| 88 | 102 | threads: 0, |
| 89 | 103 | qp: 26, |
| 104 | + transform_8x8: false, | |
| 90 | 105 | } |
| 91 | 106 | } |
| 92 | 107 | } |
| @@ -125,6 +140,8 @@ pub struct Encoder { | ||
| 125 | 140 | next_id: i32, |
| 126 | 141 | /// True once a reference picture exists. |
| 127 | 142 | have_reference: bool, |
| 143 | + /// Macroblocks coded with transform_size_8x8_flag set: (intra, inter). | |
| 144 | + t8x8_mbs: (u64, u64), | |
| 128 | 145 | } |
| 129 | 146 | |
| 130 | 147 | /// A picture handed to the encoder: three planes, no padding assumptions. |
| @@ -193,10 +210,11 @@ impl Encoder { | ||
| 193 | 210 | timing, |
| 194 | 211 | bitrate: cfg.bitrate, |
| 195 | 212 | cabac: cfg.cabac, |
| 213 | + transform_8x8: cfg.transform_8x8, | |
| 196 | 214 | }; |
| 197 | 215 | let sps_rbsp = write_sps(&seq); |
| 198 | 216 | let sps = Sps::parse(&sps_rbsp)?; |
| 199 | - let pps_rbsp = write_pps(cfg.cabac); | |
| 217 | + let pps_rbsp = write_pps(cfg.cabac, cfg.transform_8x8); | |
| 200 | 218 | let threads = if cfg.threads == 0 { |
| 201 | 219 | std::thread::available_parallelism().map_or(1, |n| n.get()) |
| 202 | 220 | } else { |
| @@ -227,11 +245,18 @@ impl Encoder { | ||
| 227 | 245 | idr_pic_id: 0, |
| 228 | 246 | next_id: 0, |
| 229 | 247 | have_reference: false, |
| 248 | + t8x8_mbs: (0, 0), | |
| 230 | 249 | cfg, |
| 231 | 250 | }) |
| 232 | 251 | } |
| 233 | 252 | |
| 234 | 253 | /// 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 | + | |
| 235 | 260 | pub fn config(&self) -> &EncoderConfig { |
| 236 | 261 | &self.cfg |
| 237 | 262 | } |
| @@ -351,6 +376,15 @@ impl Encoder { | ||
| 351 | 376 | for (band, worker) in bands.iter().skip(1).zip(rest.iter()) { |
| 352 | 377 | merge_band(master, worker, *band); |
| 353 | 378 | } |
| 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 | + } | |
| 354 | 388 | deblock_picture(master); |
| 355 | 389 | master.extend_borders(); |
| 356 | 390 | master.complete = true; |
| @@ -484,7 +518,9 @@ fn code_band(pic: &mut Picture, job: BandJob<'_>) -> Vec<u8> { | ||
| 484 | 518 | target_qp: job.qp, |
| 485 | 519 | lambda: lambda_for(job.qp), |
| 486 | 520 | preset: job.cfg.preset, |
| 521 | + transform_8x8: job.cfg.transform_8x8, | |
| 487 | 522 | ls: LevelScale4x4::new(&[16; 16]), |
| 523 | + ls8: LevelScale8x8::new(&[16; 64]), | |
| 488 | 524 | mb_ctx: crate::entropy::MbCtx::default(), |
| 489 | 525 | skip_inc: 0, |
| 490 | 526 | qp_delta_inc: 0, |
crates/ec-h264/src/enc/quant.rsmodified+179 -1
| @@ -11,7 +11,8 @@ | ||
| 11 | 11 | //! 16 ~= 2^21`, which is what makes `level = (|c| * MF + f) >> (15 + qp / 6)` |
| 12 | 12 | //! invert the decoder's dequantisation. |
| 13 | 13 | |
| 14 | -use crate::tables::{NORM_ADJUST_CLASS_4X4, ZIGZAG_4X4}; | |
| 14 | +use crate::tables::{NORM_ADJUST_CLASS_4X4, ZIGZAG_4X4, ZIGZAG_8X8}; | |
| 15 | +use crate::transform::LevelScale8x8; | |
| 15 | 16 | |
| 16 | 17 | /// Quantisation multipliers per `qp % 6`, indexed by the same position class |
| 17 | 18 | /// as [`NORM_ADJUST_CLASS_4X4`] (0 = even/even, 1 = odd/odd, 2 = mixed). |
| @@ -85,6 +86,112 @@ pub(crate) fn forward_hadamard_2x2(d: &mut [i32; 4]) { | ||
| 85 | 86 | d[3] = a - b - c + e; |
| 86 | 87 | } |
| 87 | 88 | |
| 89 | +/// Forward 8x8 core transform (the exact algebraic inverse of `idct8_1d` / | |
| 90 | +/// [`crate::transform::inverse_transform_8x8`]), raster in, scaled coefficients | |
| 91 | +/// out. | |
| 92 | +/// | |
| 93 | +/// `idct8_1d`'s matrix `M` (one 1D pass) is not its own transpose-inverse pair | |
| 94 | +/// the way the 4x4 transform's small butterfly nearly is: `M^T * M` is | |
| 95 | +/// diagonal but `M * M^T` is not, so a hand-picked small-integer transpose | |
| 96 | +/// leaks between frequencies by ~15%, which is too much for the ±1-per-sample | |
| 97 | +/// tolerance this encoder's residuals need (up to ±255, far past the small | |
| 98 | +/// ranges a 4x4 block sees). [`FWD8`] is `11560 * M^-1`, computed once by | |
| 99 | +/// exact rational matrix inversion (`M^-1 * M = I` exactly), so applying it in | |
| 100 | +/// the same row-then-column order `idct8_1d` uses, then the real inverse | |
| 101 | +/// transform, reproduces the input exactly, scaled by a single known constant | |
| 102 | +/// (`11560^2 / 64 = 2_088_025`, see [`quant_8x8`]) — no leakage at all, only | |
| 103 | +/// the ordinary quantiser rounding. | |
| 104 | +const FWD8: [[i64; 8]; 8] = [ | |
| 105 | + [1445, 1445, 1445, 1445, 1445, 1445, 1445, 1445], | |
| 106 | + [1920, 1600, 960, 480, -480, -960, -1600, -1920], | |
| 107 | + [2312, 1156, -1156, -2312, -2312, -1156, 1156, 2312], | |
| 108 | + [1600, -480, -1920, -960, 960, 1920, 480, -1600], | |
| 109 | + [1445, -1445, -1445, 1445, 1445, -1445, -1445, 1445], | |
| 110 | + [960, -1920, 480, 1600, -1600, -480, 1920, -960], | |
| 111 | + [1156, -2312, 2312, -1156, -1156, 2312, -2312, 1156], | |
| 112 | + [480, -960, 1600, -1920, 1920, -1600, 960, -480], | |
| 113 | +]; | |
| 114 | + | |
| 115 | +/// One 1D pass of [`FWD8`] over eight values. | |
| 116 | +#[inline] | |
| 117 | +fn fwd8_1d(d: [i64; 8]) -> [i64; 8] { | |
| 118 | + std::array::from_fn(|i| (0..8).map(|j| FWD8[i][j] * d[j]).sum()) | |
| 119 | +} | |
| 120 | + | |
| 121 | +/// Forward 8x8 transform (raster in, raster out), unnormalised: the caller | |
| 122 | +/// (`quant_8x8`) divides out the `2_088_025` gain along with the usual | |
| 123 | +/// per-position quantiser scale. | |
| 124 | +pub(crate) fn forward_8x8(d: &[i32; 64]) -> [i64; 64] { | |
| 125 | + let mut g = [0i64; 64]; | |
| 126 | + for i in 0..8 { | |
| 127 | + let o = i * 8; | |
| 128 | + let row: [i64; 8] = std::array::from_fn(|k| i64::from(d[o + k])); | |
| 129 | + g[o..o + 8].copy_from_slice(&fwd8_1d(row)); | |
| 130 | + } | |
| 131 | + let mut r = [0i64; 64]; | |
| 132 | + for j in 0..8 { | |
| 133 | + let col = [ | |
| 134 | + g[j], | |
| 135 | + g[8 + j], | |
| 136 | + g[16 + j], | |
| 137 | + g[24 + j], | |
| 138 | + g[32 + j], | |
| 139 | + g[40 + j], | |
| 140 | + g[48 + j], | |
| 141 | + g[56 + j], | |
| 142 | + ]; | |
| 143 | + for (i, v) in fwd8_1d(col).into_iter().enumerate() { | |
| 144 | + r[i * 8 + j] = v; | |
| 145 | + } | |
| 146 | + } | |
| 147 | + r | |
| 148 | +} | |
| 149 | + | |
| 150 | +/// `raw / denom`, rounded with the same 1/3 (intra) or 1/6 (inter) dead zone | |
| 151 | +/// as [`round_offset`], expressed as plain division instead of a | |
| 152 | +/// precomputed shift because [`forward_8x8`]'s coefficients already carry | |
| 153 | +/// far more headroom than a `<<15`-ish fixed point would give. | |
| 154 | +#[inline] | |
| 155 | +fn round_div(raw: i64, denom: i64, intra: bool) -> i64 { | |
| 156 | + (raw + denom / if intra { 3 } else { 6 }) / denom | |
| 157 | +} | |
| 158 | + | |
| 159 | +/// Quantise an 8x8 [`forward_8x8`] output into scan (zig-zag) order, undoing | |
| 160 | +/// both the `2_088_025` transform gain and the per-position [`LevelScale8x8`] | |
| 161 | +/// / QP scale that [`crate::transform::dequant_8x8`] will re-apply. | |
| 162 | +pub(crate) fn quant_8x8( | |
| 163 | + coef: &[i64; 64], | |
| 164 | + ls: &LevelScale8x8, | |
| 165 | + qp: i32, | |
| 166 | + intra: bool, | |
| 167 | + out: &mut [i32; 64], | |
| 168 | +) -> u8 { | |
| 169 | + // 11560^2 / 64, see FWD8's doc comment. | |
| 170 | + const TOTAL_SCALE: i64 = 2_088_025; | |
| 171 | + let m = (qp % 6) as usize; | |
| 172 | + let shift = qp / 6; | |
| 173 | + let p = 6 - shift; // dequant_8x8's exponent, mirrored; qp >= 36 makes it negative. | |
| 174 | + let scale = &ls.scale[m]; | |
| 175 | + let mut nz = 0; | |
| 176 | + *out = [0; 64]; | |
| 177 | + for k in 0..64 { | |
| 178 | + let raster = ZIGZAG_8X8[k] as usize; | |
| 179 | + let c = coef[raster]; | |
| 180 | + let denom = TOTAL_SCALE * i64::from(scale[raster]); | |
| 181 | + let (num, denom) = if p >= 0 { | |
| 182 | + ((c.unsigned_abs() as i64) << p, denom) | |
| 183 | + } else { | |
| 184 | + (c.unsigned_abs() as i64, denom << -p) | |
| 185 | + }; | |
| 186 | + let level = round_div(num, denom, intra) as i32; | |
| 187 | + if level != 0 { | |
| 188 | + nz += 1; | |
| 189 | + } | |
| 190 | + out[k] = if c < 0 { -level } else { level }; | |
| 191 | + } | |
| 192 | + nz | |
| 193 | +} | |
| 194 | + | |
| 88 | 195 | /// Quantise a transformed 4x4 block into scan (zig-zag) order. |
| 89 | 196 | /// |
| 90 | 197 | /// `skip_dc` leaves scan position 0 out and writes the fifteen AC levels into |
| @@ -159,6 +266,77 @@ pub(crate) fn quant_chroma_dc(coef: &[i32; 4], qp: i32, intra: bool, out: &mut [ | ||
| 159 | 266 | #[cfg(test)] |
| 160 | 267 | mod tests { |
| 161 | 268 | use super::*; |
| 269 | + use crate::transform::{LevelScale8x8, dequant_8x8, inverse_transform_8x8, unzigzag_8x8}; | |
| 270 | + | |
| 271 | + fn ls8() -> LevelScale8x8 { | |
| 272 | + LevelScale8x8::new(&[16; 64]) | |
| 273 | + } | |
| 274 | + | |
| 275 | + /// `forward_8x8` -> `quant_8x8` -> [`dequant_8x8`] -> [`inverse_transform_8x8`] | |
| 276 | + /// lands within the same dead-zone-quantiser bound as the 4x4 path (one | |
| 277 | + /// step, which doubles every six QP — see `ac_round_trip_within_a_quantiser_step` | |
| 278 | + /// above), at every QP, for 1000+ trials of random content across the full | |
| 279 | + /// 8-bit residual range: the property that makes `FWD8` a valid forward | |
| 280 | + /// companion to the normative inverse. With no quantisation at all | |
| 281 | + /// (`round_trip_8x8_identity_within_one_sample` below) the bound tightens | |
| 282 | + /// to the inverse transform's own `+32 >> 6` rounding, ±1. | |
| 283 | + #[test] | |
| 284 | + fn round_trip_8x8_within_a_quantiser_step() { | |
| 285 | + let ls = ls8(); | |
| 286 | + for qp in 0..52 { | |
| 287 | + let step = 1 << (qp / 6); | |
| 288 | + let mut worst = 0i32; | |
| 289 | + for seed in 0..20u32 { | |
| 290 | + let src: [i32; 64] = std::array::from_fn(|i| { | |
| 291 | + let v = (seed.wrapping_mul(2654435761)) | |
| 292 | + .wrapping_add((i as u32).wrapping_mul(2654435761)) | |
| 293 | + >> 20; | |
| 294 | + (v as i32 % 511) - 255 | |
| 295 | + }); | |
| 296 | + let coef = forward_8x8(&src); | |
| 297 | + let mut scan = [0i32; 64]; | |
| 298 | + quant_8x8(&coef, &ls, qp, true, &mut scan); | |
| 299 | + let mut raster = [0i32; 64]; | |
| 300 | + unzigzag_8x8(&scan, &mut raster); | |
| 301 | + dequant_8x8(&mut raster, &ls, qp); | |
| 302 | + let mut out = [0i32; 64]; | |
| 303 | + inverse_transform_8x8(&raster, &mut out); | |
| 304 | + for i in 0..64 { | |
| 305 | + worst = worst.max((out[i] - src[i]).abs()); | |
| 306 | + } | |
| 307 | + } | |
| 308 | + assert!( | |
| 309 | + worst <= 2 + 2 * step, | |
| 310 | + "qp {qp}: worst error {worst} over step {step}" | |
| 311 | + ); | |
| 312 | + } | |
| 313 | + } | |
| 314 | + | |
| 315 | + /// With no quantisation at all (level = raw coefficient), the round trip | |
| 316 | + /// is exact up to the inverse transform's own `+32 >> 6` rounding. | |
| 317 | + #[test] | |
| 318 | + fn round_trip_8x8_identity_within_one_sample() { | |
| 319 | + let src: [i32; 64] = std::array::from_fn(|i| ((i * 7) % 511) as i32 - 255); | |
| 320 | + let coef = forward_8x8(&src); | |
| 321 | + // coef = 2_088_025 * exact_pre_shift_value; divide that out directly, | |
| 322 | + // bypassing any QP-driven quantiser step. | |
| 323 | + let mut raster = [0i32; 64]; | |
| 324 | + for i in 0..64 { | |
| 325 | + let v = coef[i] as f64 / 2_088_025.0; | |
| 326 | + raster[i] = v.round() as i32; | |
| 327 | + } | |
| 328 | + let mut out = [0i32; 64]; | |
| 329 | + inverse_transform_8x8(&raster, &mut out); | |
| 330 | + for i in 0..64 { | |
| 331 | + assert!( | |
| 332 | + (out[i] - src[i]).abs() <= 1, | |
| 333 | + "i {i}: {} vs {}", | |
| 334 | + out[i], | |
| 335 | + src[i] | |
| 336 | + ); | |
| 337 | + } | |
| 338 | + } | |
| 339 | + | |
| 162 | 340 | use crate::transform::{ |
| 163 | 341 | LevelScale4x4, chroma_dc_transform_420, dequant_4x4, inverse_transform_4x4, |
| 164 | 342 | luma_dc_transform, unzigzag, |
crates/ec-h264/src/enc/vlc.rsmodified+43 -0
| @@ -248,6 +248,49 @@ mod tests { | ||
| 248 | 248 | } |
| 249 | 249 | } |
| 250 | 250 | |
| 251 | + /// An 8x8 block written as four interleaved 4x4 blocks reads back through | |
| 252 | + /// the decoder's 4x4 path into the same 64 coefficients, with the | |
| 253 | + /// decoder's reassembly rule (`scan8[4 * i + i4] = scan[i]`). | |
| 254 | + #[test] | |
| 255 | + fn interleaved_8x8_round_trips() { | |
| 256 | + let mut state = 0xC0FF_EE00u32; | |
| 257 | + let mut rand = move |m: u32| { | |
| 258 | + state = state.wrapping_mul(1664525).wrapping_add(1013904223); | |
| 259 | + (state >> 16) % m | |
| 260 | + }; | |
| 261 | + for _ in 0..200 { | |
| 262 | + let mut c8 = [0i32; 64]; | |
| 263 | + for _ in 0..rand(64) { | |
| 264 | + let v = rand(70) as i32 + 1; | |
| 265 | + c8[rand(64) as usize] = if rand(2) == 0 { v } else { -v }; | |
| 266 | + } | |
| 267 | + let mut w = BitWriter::new(); | |
| 268 | + let mut tcs = [0u8; 4]; | |
| 269 | + for j in 0..4 { | |
| 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 | + ); | |
| 276 | + } | |
| 277 | + w.write_bit(true); | |
| 278 | + w.align_to_byte(); | |
| 279 | + let bytes = w.into_bytes(); | |
| 280 | + let mut r = BitCursor::new(&bytes, 0); | |
| 281 | + let mut got = [0i32; 64]; | |
| 282 | + for j in 0..4 { | |
| 283 | + let mut scan = [0i32; 16]; | |
| 284 | + let tc = residual_block(&mut r, &mut scan, 16, j as i32 * 3).expect("decodes"); | |
| 285 | + assert_eq!(tc, tcs[j]); | |
| 286 | + for i in 0..16 { | |
| 287 | + got[4 * i + j] = scan[i]; | |
| 288 | + } | |
| 289 | + } | |
| 290 | + assert_eq!(got, c8); | |
| 291 | + } | |
| 292 | + } | |
| 293 | + | |
| 251 | 294 | /// Every block this writer emits decodes back to the same levels, over a |
| 252 | 295 | /// spread that covers empty blocks, trailing ones, long runs, the |
| 253 | 296 | /// suffix-length ladder and the escape codes. |
crates/ec-h264/src/entropy.rsmodified+7 -0
| @@ -55,6 +55,11 @@ pub(crate) enum BlockCat { | ||
| 55 | 55 | ChromaDc(u8), |
| 56 | 56 | /// ChromaACLevel, `ctxBlockCat` 4. |
| 57 | 57 | ChromaAc, |
| 58 | + /// LumaLevel8x8, `ctxBlockCat` 5: one 64-coefficient block under | |
| 59 | + /// transform_size_8x8_flag. CABAC codes it whole (no coded_block_flag for | |
| 60 | + /// 4:2:0); CAVLC never sees this category, it codes the block as four | |
| 61 | + /// interleaved `Luma4x4` blocks (7.3.5.3.1). | |
| 62 | + Luma8x8, | |
| 58 | 63 | } |
| 59 | 64 | |
| 60 | 65 | impl BlockCat { |
| @@ -64,6 +69,7 @@ impl BlockCat { | ||
| 64 | 69 | BlockCat::LumaDc | BlockCat::Luma4x4 => 16, |
| 65 | 70 | BlockCat::LumaAc | BlockCat::ChromaAc => 15, |
| 66 | 71 | BlockCat::ChromaDc(_) => 4, |
| 72 | + BlockCat::Luma8x8 => 64, | |
| 67 | 73 | } |
| 68 | 74 | } |
| 69 | 75 | |
| @@ -75,6 +81,7 @@ impl BlockCat { | ||
| 75 | 81 | BlockCat::Luma4x4 => 2, |
| 76 | 82 | BlockCat::ChromaDc(_) => 3, |
| 77 | 83 | BlockCat::ChromaAc => 4, |
| 84 | + BlockCat::Luma8x8 => 5, | |
| 78 | 85 | } |
| 79 | 86 | } |
| 80 | 87 | } |
crates/ec-h264/tests/encode.rsmodified+122 -10
| @@ -126,14 +126,17 @@ fn psnr(a: &[u8], b: &[u8]) -> f64 { | ||
| 126 | 126 | /// sample, over a QP sweep, both presets, single and multi threaded. |
| 127 | 127 | #[test] |
| 128 | 128 | fn reconstruction_matches_the_decoder() { |
| 129 | + let mut t8x8_mbs = (0, 0); | |
| 129 | 130 | for (w, h) in [(176, 144), (208, 122), (64, 48)] { |
| 130 | 131 | let mut clip = Clip::new(w, h); |
| 131 | 132 | for qp in [12, 24, 33, 44] { |
| 132 | - for (threads, preset, cabac) in [ | |
| 133 | - (1usize, Preset::Fast, true), | |
| 134 | - (4, Preset::Balanced, true), | |
| 135 | - (1, Preset::Fast, false), | |
| 136 | - (3, Preset::Balanced, false), | |
| 133 | + for (threads, preset, cabac, t8x8) in [ | |
| 134 | + (1usize, Preset::Fast, true, false), | |
| 135 | + (4, Preset::Balanced, true, false), | |
| 136 | + (1, Preset::Fast, false, false), | |
| 137 | + (3, Preset::Balanced, false, false), | |
| 138 | + (2, Preset::Balanced, true, true), | |
| 139 | + (2, Preset::Balanced, false, true), | |
| 137 | 140 | ] { |
| 138 | 141 | let mut cfg = EncoderConfig::new(w as u32, h as u32); |
| 139 | 142 | cfg.qp = qp; |
| @@ -141,6 +144,7 @@ fn reconstruction_matches_the_decoder() { | ||
| 141 | 144 | cfg.threads = threads; |
| 142 | 145 | cfg.preset = preset; |
| 143 | 146 | cfg.cabac = cabac; |
| 147 | + cfg.transform_8x8 = t8x8; | |
| 144 | 148 | let mut enc = Encoder::new(cfg).expect("encoder"); |
| 145 | 149 | let mut stream = Vec::new(); |
| 146 | 150 | let mut recons = Vec::new(); |
| @@ -150,6 +154,11 @@ fn reconstruction_matches_the_decoder() { | ||
| 150 | 154 | stream.extend_from_slice(&picture.au); |
| 151 | 155 | recons.push(enc.reconstruction().expect("a reconstruction")); |
| 152 | 156 | } |
| 157 | + if t8x8 { | |
| 158 | + let (intra, inter) = enc.transform_8x8_mbs(); | |
| 159 | + t8x8_mbs.0 += intra; | |
| 160 | + t8x8_mbs.1 += inter; | |
| 161 | + } | |
| 153 | 162 | let decoded = decode_all(&stream); |
| 154 | 163 | assert_eq!( |
| 155 | 164 | decoded.len(), |
| @@ -173,6 +182,13 @@ fn reconstruction_matches_the_decoder() { | ||
| 173 | 182 | } |
| 174 | 183 | } |
| 175 | 184 | } |
| 185 | + // The flag-on streams above really carried 8x8 macroblocks of both kinds. | |
| 186 | + assert!( | |
| 187 | + t8x8_mbs.0 > 0 && t8x8_mbs.1 > 0, | |
| 188 | + "8x8 MBs across the sweep: intra {} inter {}", | |
| 189 | + t8x8_mbs.0, | |
| 190 | + t8x8_mbs.1 | |
| 191 | + ); | |
| 176 | 192 | } |
| 177 | 193 | |
| 178 | 194 | /// Quality tracks the quantiser, and a low QP is close to lossless: a stream |
| @@ -316,7 +332,7 @@ fn encode_clip( | ||
| 316 | 332 | h: usize, |
| 317 | 333 | frames: usize, |
| 318 | 334 | configure: impl FnOnce(&mut EncoderConfig), |
| 319 | -) -> (Vec<u8>, Vec<Planes>) { | |
| 335 | +) -> (Vec<u8>, Vec<Planes>, (u64, u64)) { | |
| 320 | 336 | let mut cfg = EncoderConfig::new(w as u32, h as u32); |
| 321 | 337 | cfg.gop_size = 10; |
| 322 | 338 | cfg.threads = 3; |
| @@ -330,7 +346,90 @@ fn encode_clip( | ||
| 330 | 346 | stream.extend_from_slice(&enc.encode(&clip.view()).expect("encode").au); |
| 331 | 347 | recons.push(enc.reconstruction().expect("reconstruction")); |
| 332 | 348 | } |
| 333 | - (stream, recons) | |
| 349 | + (stream, recons, enc.transform_8x8_mbs()) | |
| 350 | +} | |
| 351 | + | |
| 352 | +/// Flat gradients and glyph-like rectangles: the content the 8x8 transform | |
| 353 | +/// exists for. A 10-frame clip with the flag on must beat the flag off by at | |
| 354 | +/// least 0.3 dB at equal bits, or by 5% fewer bits at equal PSNR. | |
| 355 | +#[test] | |
| 356 | +fn eight_by_eight_gains_on_flat_and_text() { | |
| 357 | + let (w, h) = (320, 240); | |
| 358 | + let render = |t: usize, clip: &mut Clip| { | |
| 359 | + // A half-sample pan per frame: inter prediction has a residual to code. | |
| 360 | + let sx = |x: usize| x * 2 + t; | |
| 361 | + for y in 0..h { | |
| 362 | + for x in 0..w { | |
| 363 | + let (px, py) = (sx(x) as f64 / 2.0, y as f64); | |
| 364 | + // Curved shading: smooth but not a plane, so no 16x16 mode | |
| 365 | + // predicts it for free. | |
| 366 | + let shade = 70.0 + px * px / 900.0 + py * py / 700.0 - px * py / 1500.0; | |
| 367 | + // Gentle texture with a 20-sample period: residual energy that | |
| 368 | + // spans more than a 4x4 block, which is what the 8x8 transform | |
| 369 | + // is for. | |
| 370 | + let tri = |v: f64| ((v % 20.0) - 10.0).abs() - 5.0; | |
| 371 | + let shade = shade + tri(px) * tri(py) / 1.5; | |
| 372 | + // Glyph rows: 16x24 cells, stroke pattern hashed per cell. | |
| 373 | + let (cell, cx, cy) = (sx(x) / 32, (sx(x) / 2) % 16, y % 24); | |
| 374 | + let hash = (cell * 2654435761usize.wrapping_add(y / 24 * 40503)) >> 7; | |
| 375 | + let stem = (2..5).contains(&cx); | |
| 376 | + let bar = (10..13).contains(&cy) && cx < 12 && hash & 1 == 1; | |
| 377 | + let foot = cy >= 19 && (2..13).contains(&cx) && hash & 2 == 2; | |
| 378 | + let glyph = y > h / 3 && (3..22).contains(&cy) && (stem || bar || foot); | |
| 379 | + clip.y[y * w + x] = if glyph { 24 } else { shade.min(235.0) as u8 }; | |
| 380 | + } | |
| 381 | + } | |
| 382 | + clip.u.fill(128); | |
| 383 | + clip.v.fill(128); | |
| 384 | + }; | |
| 385 | + let run = |t8x8: bool, qp: i32| { | |
| 386 | + let mut cfg = EncoderConfig::new(w as u32, h as u32); | |
| 387 | + cfg.qp = qp; | |
| 388 | + cfg.gop_size = 10; | |
| 389 | + cfg.transform_8x8 = t8x8; | |
| 390 | + let mut enc = Encoder::new(cfg).expect("encoder"); | |
| 391 | + let mut clip = Clip::new(w, h); | |
| 392 | + let (mut bits, mut sum_psnr) = (0usize, 0.0); | |
| 393 | + let mut share = 0.0; | |
| 394 | + for t in 0..10 { | |
| 395 | + render(t, &mut clip); | |
| 396 | + bits += enc.encode(&clip.view()).expect("encode").au.len() * 8; | |
| 397 | + let rec = enc.reconstruction().expect("reconstruction"); | |
| 398 | + sum_psnr += psnr(&clip.y, &rec.0); | |
| 399 | + } | |
| 400 | + if t8x8 { | |
| 401 | + let (i, p) = enc.transform_8x8_mbs(); | |
| 402 | + eprintln!("8x8 MBs: intra {i} inter {p}"); | |
| 403 | + share = (i + p) as f64 / (10.0 * (w / 16 * h / 16) as f64); | |
| 404 | + } | |
| 405 | + (bits as f64, sum_psnr / 10.0, share) | |
| 406 | + }; | |
| 407 | + // Interpolate the off curve at the on point's bits / PSNR. | |
| 408 | + let qp = 26; | |
| 409 | + let (bits_on, psnr_on, share) = run(true, qp); | |
| 410 | + let off: Vec<_> = [qp - 2, qp, qp + 2] | |
| 411 | + .iter() | |
| 412 | + .map(|&q| run(false, q)) | |
| 413 | + .collect(); | |
| 414 | + let (bits_off, psnr_off, _) = off[1]; | |
| 415 | + // Local slopes of the off curve, from the neighbouring QPs. | |
| 416 | + let dpsnr_dbits = (off[0].1 - off[2].1) / (off[0].0 - off[2].0); | |
| 417 | + let psnr_off_at_on_bits = psnr_off + (bits_on - bits_off) * dpsnr_dbits; | |
| 418 | + let bits_off_at_on_psnr = bits_off + (psnr_on - psnr_off) / dpsnr_dbits; | |
| 419 | + let gain_db = psnr_on - psnr_off_at_on_bits; | |
| 420 | + let saving = 1.0 - bits_on / bits_off_at_on_psnr; | |
| 421 | + eprintln!( | |
| 422 | + "8x8 qp {qp}: on {bits_on:.0} bits {psnr_on:.2} dB, off {bits_off:.0} bits {psnr_off:.2} dB; \ | |
| 423 | + gain at equal bits {gain_db:+.2} dB, saving at equal PSNR {:.1}%, 8x8 MB share {:.1}%", | |
| 424 | + saving * 100.0, | |
| 425 | + share * 100.0 | |
| 426 | + ); | |
| 427 | + assert!(share > 0.0, "no 8x8 macroblocks were coded"); | |
| 428 | + assert!( | |
| 429 | + gain_db >= 0.3 || saving >= 0.05, | |
| 430 | + "8x8 gain {gain_db:+.2} dB / {:.1}% is below the bar", | |
| 431 | + saving * 100.0 | |
| 432 | + ); | |
| 334 | 433 | } |
| 335 | 434 | |
| 336 | 435 | /// ffmpeg's decode of our stream is our reconstruction, sample for sample, |
| @@ -341,13 +440,18 @@ fn ffmpeg_decodes_bit_exactly() { | ||
| 341 | 440 | eprintln!("SKIP ffmpeg_decodes_bit_exactly: no ffmpeg on PATH"); |
| 342 | 441 | return; |
| 343 | 442 | } |
| 443 | + let mut t8x8_mbs = (0, 0); | |
| 344 | 444 | for (w, h) in [(176, 144), (322, 242)] { |
| 345 | 445 | for qp in [10, 20, 28, 37, 47] { |
| 346 | 446 | let cavlc = qp % 2 == 0; // both entropy coders across the sweep |
| 347 | - let (stream, recons) = encode_clip(w, h, 6, |cfg| { | |
| 447 | + let t8x8 = qp % 3 == 1; // High-profile PPS with the per-MB flag | |
| 448 | + let (stream, recons, (intra, inter)) = encode_clip(w, h, 6, |cfg| { | |
| 348 | 449 | cfg.qp = qp; |
| 349 | 450 | cfg.cabac = !cavlc; |
| 451 | + cfg.transform_8x8 = t8x8; | |
| 350 | 452 | }); |
| 453 | + t8x8_mbs.0 += intra; | |
| 454 | + t8x8_mbs.1 += inter; | |
| 351 | 455 | let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes our stream"); |
| 352 | 456 | assert_eq!(decoded.len(), recons.len(), "{w}x{h} qp {qp}: frame count"); |
| 353 | 457 | for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() { |
| @@ -357,6 +461,12 @@ fn ffmpeg_decodes_bit_exactly() { | ||
| 357 | 461 | } |
| 358 | 462 | } |
| 359 | 463 | } |
| 464 | + assert!( | |
| 465 | + t8x8_mbs.0 > 0 && t8x8_mbs.1 > 0, | |
| 466 | + "8x8 MBs across the sweep: intra {} inter {}", | |
| 467 | + t8x8_mbs.0, | |
| 468 | + t8x8_mbs.1 | |
| 469 | + ); | |
| 360 | 470 | } |
| 361 | 471 | |
| 362 | 472 | /// The same stream under constant bitrate, which is the mode edith exports in. |
| @@ -367,7 +477,7 @@ fn ffmpeg_decodes_a_cbr_stream_bit_exactly() { | ||
| 367 | 477 | return; |
| 368 | 478 | } |
| 369 | 479 | let (w, h) = (352, 288); |
| 370 | - let (stream, recons) = encode_clip(w, h, 12, |cfg| { | |
| 480 | + let (stream, recons, _) = encode_clip(w, h, 12, |cfg| { | |
| 371 | 481 | cfg.bitrate = 2_000_000; |
| 372 | 482 | cfg.framerate = 25.0; |
| 373 | 483 | }); |
| @@ -393,9 +503,11 @@ fn vaapi_decodes_our_stream() { | ||
| 393 | 503 | return; |
| 394 | 504 | } |
| 395 | 505 | let (w, h) = (352, 288); |
| 396 | - let (stream, recons) = encode_clip(w, h, 6, |cfg| { | |
| 506 | + let (stream, recons, (intra, inter)) = encode_clip(w, h, 6, |cfg| { | |
| 397 | 507 | cfg.qp = 26; |
| 508 | + cfg.transform_8x8 = true; | |
| 398 | 509 | }); |
| 510 | + assert!(intra + inter > 0, "no 8x8 macroblocks in the VA-API stream"); | |
| 399 | 511 | let Some(decoded) = ffmpeg_decode( |
| 400 | 512 | &stream, |
| 401 | 513 | w, |