diff --git a/crates/ec-h264/src/cabac.rs b/crates/ec-h264/src/cabac.rs index 32dbfe56..c237fef5 100644 --- a/crates/ec-h264/src/cabac.rs +++ b/crates/ec-h264/src/cabac.rs @@ -30,37 +30,37 @@ use crate::entropy::{ /// coeff_abs_level_minus1 of the 8x8 luma category, the last range a /// frame-coded 4:2:0 slice reaches; 436 and up are the field-coded and 4:4:4 /// categories this decoder refuses by name). -const NUM_CTX: usize = 436; +pub(crate) const NUM_CTX: usize = 436; /// ctxIdx 276 (end_of_slice_flag and the I_PCM bin of mb_type) is decoded by /// DecodeTerminate and has no adapting state. const CTX_TERMINATE: usize = 276; /// Table 9-40, `ctxIdxBlockCatOffset` for the five 4:2:0 block categories. -const CBF_CAT_OFF: [usize; 5] = [0, 4, 8, 12, 16]; -const SIG_CAT_OFF: [usize; 5] = [0, 15, 29, 44, 47]; -const ABS_CAT_OFF: [usize; 5] = [0, 10, 20, 30, 39]; +pub(crate) const CBF_CAT_OFF: [usize; 5] = [0, 4, 8, 12, 16]; +pub(crate) const SIG_CAT_OFF: [usize; 5] = [0, 15, 29, 44, 47]; +pub(crate) const ABS_CAT_OFF: [usize; 5] = [0, 10, 20, 30, 39]; /// ctxIdxOffset values of Table 9-34 used here. -const OFF_MB_TYPE: usize = 3; -const OFF_SKIP_P: usize = 11; -const OFF_MB_TYPE_P: usize = 14; +pub(crate) const OFF_MB_TYPE: usize = 3; +pub(crate) const OFF_SKIP_P: usize = 11; +pub(crate) const OFF_MB_TYPE_P: usize = 14; const OFF_SUB_TYPE_P: usize = 21; const OFF_SKIP_B: usize = 24; const OFF_MB_TYPE_B: usize = 27; const OFF_SUB_TYPE_B: usize = 36; -const OFF_MVD: [usize; 2] = [40, 47]; +pub(crate) const OFF_MVD: [usize; 2] = [40, 47]; const OFF_REF_IDX: usize = 54; -const OFF_QP_DELTA: usize = 60; -const OFF_CHROMA_PRED: usize = 64; -const OFF_PREV_I4: usize = 68; -const OFF_REM_I4: usize = 69; -const OFF_CBP_LUMA: usize = 73; -const OFF_CBP_CHROMA: usize = 77; -const OFF_CBF: usize = 85; -const OFF_SIG: usize = 105; -const OFF_LAST: usize = 166; -const OFF_ABS: usize = 227; +pub(crate) const OFF_QP_DELTA: usize = 60; +pub(crate) const OFF_CHROMA_PRED: usize = 64; +pub(crate) const OFF_PREV_I4: usize = 68; +pub(crate) const OFF_REM_I4: usize = 69; +pub(crate) const OFF_CBP_LUMA: usize = 73; +pub(crate) const OFF_CBP_CHROMA: usize = 77; +pub(crate) const OFF_CBF: usize = 85; +pub(crate) const OFF_SIG: usize = 105; +pub(crate) const OFF_LAST: usize = 166; +pub(crate) const OFF_ABS: usize = 227; const OFF_TRANSFORM_8X8: usize = 399; /// significant_coeff_flag / last_significant_coeff_flag / coeff_abs_level_minus1 /// of ctxBlockCat 5 (frame coded), Table 9-34. @@ -76,8 +76,8 @@ const OFF_ABS_8X8: usize = 426; /// long, which shifts the prediction-mode bins; resolving the table to fixed /// ctxIdx values here is what makes the two spellings (I slice at ctxIdxOffset /// 3, intra suffix at 17 or 32) one piece of code. -const I_MB_TYPE_CTX: [usize; 6] = [3, 6, 7, 8, 9, 10]; -const I_SUFFIX_CTX_P: [usize; 6] = [17, 18, 19, 19, 20, 20]; +pub(crate) const I_MB_TYPE_CTX: [usize; 6] = [3, 6, 7, 8, 9, 10]; +pub(crate) const I_SUFFIX_CTX_P: [usize; 6] = [17, 18, 19, 19, 20, 20]; const I_SUFFIX_CTX_B: [usize; 6] = [32, 33, 34, 34, 35, 35]; pub(crate) struct Cabac<'a> { @@ -124,42 +124,11 @@ impl<'a> Cabac<'a> { cbp_luma_bins: 0, cur_intra: true, }; - c.init_contexts(slice_qp, init_column.min(3)); + c.state = init_contexts(slice_qp, init_column.min(3)); c.init_engine()?; Ok(c) } - /// 9.3.1.1: pStateIdx and valMPS from the (m, n) table entries and SliceQPY. - fn init_contexts(&mut self, slice_qp: i32, column: usize) { - let qp = slice_qp.clamp(0, 51); - let set = |state: &mut [u8; NUM_CTX], idx: usize, (m, n): (i8, i8)| { - let pre = (((i32::from(m) * qp) >> 4) + i32::from(n)).clamp(1, 126); - state[idx] = if pre <= 63 { - ((63 - pre) as u8) << 1 - } else { - (((pre - 64) as u8) << 1) | 1 - }; - }; - for (i, &mn) in INIT_MB_TYPE_I.iter().enumerate() { - set(&mut self.state, i, mn); - } - for (i, &mn) in INIT_11_59.iter().enumerate() { - set(&mut self.state, 11 + i, mn[column]); - } - for (i, &mn) in INIT_60_69.iter().enumerate() { - set(&mut self.state, 60 + i, mn); - } - for (i, &mn) in INIT_70_275.iter().enumerate() { - set(&mut self.state, 70 + i, mn[column]); - } - for (i, &mn) in INIT_399_401.iter().enumerate() { - set(&mut self.state, OFF_TRANSFORM_8X8 + i, mn[column]); - } - for (i, &mn) in INIT_402_435.iter().enumerate() { - set(&mut self.state, OFF_SIG_8X8 + i, mn[column]); - } - } - /// 9.3.1.2: codIRange = 510, codIOffset = read_bits(9). fn init_engine(&mut self) -> Result<()> { self.range = 510; @@ -716,6 +685,18 @@ impl<'a> Cabac<'a> { Ok(bytes) } + /// The raw engine, for the encoder's round-trip test. + #[cfg(test)] + pub(crate) fn decision_for_test(&mut self, ctx_idx: usize) -> bool { + self.decision(ctx_idx) + } + + /// The raw bypass engine, for the encoder's round-trip test. + #[cfg(test)] + pub(crate) fn bypass_for_test(&mut self) -> bool { + self.bypass() + } + /// end_of_slice_flag (ctxIdx 276, DecodeTerminate). pub(crate) fn more_macroblocks(&mut self) -> Result { debug_assert_eq!(CTX_TERMINATE, 276); @@ -723,9 +704,44 @@ impl<'a> Cabac<'a> { } } +/// 9.3.1.1: pStateIdx and valMPS of every context from the (m, n) table +/// entries and SliceQPY. Shared with the encoder, which has to start from the +/// same state or the two arithmetic coders diverge on the first bin. +pub(crate) fn init_contexts(slice_qp: i32, column: usize) -> [u8; NUM_CTX] { + let qp = slice_qp.clamp(0, 51); + let mut state = [63u8 << 1; NUM_CTX]; + let mut set = |idx: usize, (m, n): (i8, i8)| { + let pre = (((i32::from(m) * qp) >> 4) + i32::from(n)).clamp(1, 126); + state[idx] = if pre <= 63 { + ((63 - pre) as u8) << 1 + } else { + (((pre - 64) as u8) << 1) | 1 + }; + }; + for (i, &mn) in INIT_MB_TYPE_I.iter().enumerate() { + set(i, mn); + } + for (i, &mn) in INIT_11_59.iter().enumerate() { + set(11 + i, mn[column]); + } + for (i, &mn) in INIT_60_69.iter().enumerate() { + set(60 + i, mn); + } + for (i, &mn) in INIT_70_275.iter().enumerate() { + set(70 + i, mn[column]); + } + for (i, &mn) in INIT_399_401.iter().enumerate() { + set(OFF_TRANSFORM_8X8 + i, mn[column]); + } + for (i, &mn) in INIT_402_435.iter().enumerate() { + set(OFF_SIG_8X8 + i, mn[column]); + } + state +} + /// ctxIdxInc for mb_qp_delta bin `k` (Table 9-39 row 60). #[inline] -fn qp_delta_inc(k: i32, first: usize) -> usize { +pub(crate) fn qp_delta_inc(k: i32, first: usize) -> usize { match k { 0 => first, 1 => 2, @@ -736,7 +752,7 @@ fn qp_delta_inc(k: i32, first: usize) -> usize { /// ctxIdxInc for significant_coeff_flag / last_significant_coeff_flag at /// scanning position `i` (9.3.3.1.3, frame coded, no 8x8 categories). #[inline] -fn sig_inc(cat: BlockCat, i: usize) -> usize { +pub(crate) fn sig_inc(cat: BlockCat, i: usize) -> usize { match cat { // ChromaDC with ChromaArrayType 1: Min( levelListIdx / NumC8x8, 2 ). BlockCat::ChromaDc(_) => i.min(2), diff --git a/crates/ec-h264/src/enc/cabac_enc.rs b/crates/ec-h264/src/enc/cabac_enc.rs new file mode 100644 index 00000000..44b28435 --- /dev/null +++ b/crates/ec-h264/src/enc/cabac_enc.rs @@ -0,0 +1,533 @@ +//! CABAC encoding (spec clause 9.3): the arithmetic *encoding* engine of +//! 9.3.4 and the write side of every binarisation the decoder in +//! [`crate::cabac`] reads. +//! +//! Context variables, initialisation tables, ctxIdx offsets and the ctxIdxInc +//! derivations are the decoder's own — this module writes the bins that module +//! reads, in the same order, against the same contexts. The two are held +//! together by the round-trip test of the encoder suite: a single wrong +//! ctxIdx desynchronises the arithmetic coder within a macroblock and the +//! reconstruction stops matching, loudly. +//! +//! Why it exists: CAVLC costs roughly 12% more bits than CABAC at the same +//! quality, and the software encoder edith replaces emits Main-profile CABAC. +//! Matching it on quality at a given bitrate is not possible without this. + +// The scanning position of a residual block is a context key as well as an +// index, exactly as in the decoder; iterating the coefficients would hide it. +#![allow(clippy::needless_range_loop)] + +use ec_core::BitWriter; + +use crate::cabac::{ + ABS_CAT_OFF, CBF_CAT_OFF, I_MB_TYPE_CTX, I_SUFFIX_CTX_P, NUM_CTX, OFF_ABS, OFF_CBF, + OFF_CBP_CHROMA, OFF_CBP_LUMA, OFF_CHROMA_PRED, OFF_LAST, OFF_MB_TYPE, OFF_MB_TYPE_P, OFF_MVD, + OFF_PREV_I4, OFF_QP_DELTA, OFF_REM_I4, OFF_SIG, OFF_SKIP_P, SIG_CAT_OFF, init_contexts, + qp_delta_inc, sig_inc, +}; +use crate::entropy::{BlockCat, FLAG_CHROMA_PRED, FLAG_I16, FLAG_INTER, FLAG_PCM, MbCtx, MbInfo}; + +/// The arithmetic encoder of 9.3.4 plus the context state. +pub(crate) struct CabacEnc { + w: BitWriter, + /// codILow (9.3.4.1). + low: u32, + /// codIRange (9.3.4.1). + range: u32, + /// bitsOutstanding (9.3.4.2). + outstanding: u32, + /// firstBitFlag (9.3.4.2): the leading bit of the arithmetic code word is + /// not written. + first: bool, + state: [u8; NUM_CTX], + ctx: MbCtx, + /// CodedBlockPatternLuma bins written so far in this macroblock. + cbp_luma_bins: u8, + cur_intra: bool, +} + +impl CabacEnc { + /// Start CABAC at the current (byte-aligned) position of `w`; the caller + /// has already written the slice header and the `cabac_alignment_one_bit`s. + pub(crate) fn new(w: BitWriter, slice_qp: i32, init_column: usize) -> CabacEnc { + debug_assert!(w.is_byte_aligned(), "CABAC starts on a byte boundary"); + CabacEnc { + w, + low: 0, + range: 510, + outstanding: 0, + first: true, + state: init_contexts(slice_qp, init_column.min(3)), + ctx: MbCtx::default(), + cbp_luma_bins: 0, + cur_intra: true, + } + } + + // ---- 9.3.4: the encoding engine ---- + + /// PutBit (9.3.4.2), with the outstanding-bit counter of the same clause. + #[inline] + fn put_bit(&mut self, b: u32) { + if self.first { + self.first = false; + } else { + self.w.write_bit(b != 0); + } + while self.outstanding > 0 { + self.w.write_bit(b == 0); + self.outstanding -= 1; + } + } + + /// RenormE (9.3.4.2). + #[inline] + fn renorm(&mut self) { + while self.range < 256 { + if self.low < 256 { + self.put_bit(0); + } else if self.low >= 512 { + self.low -= 512; + self.put_bit(1); + } else { + self.low -= 256; + self.outstanding += 1; + } + self.range <<= 1; + self.low <<= 1; + } + } + + /// EncodeDecision (9.3.4.1), state transition included. + #[inline] + fn decision(&mut self, ctx_idx: usize, bin: bool) { + let s = self.state[ctx_idx]; + let p = usize::from(s >> 1); + let mps = s & 1; + let lps = u32::from(crate::cabac_tables::RANGE_LPS[p][((self.range >> 6) & 3) as usize]); + self.range -= lps; + if bin != (mps != 0) { + self.low += self.range; + self.range = lps; + let mps = if p == 0 { mps ^ 1 } else { mps }; + self.state[ctx_idx] = (crate::cabac_tables::TRANS_LPS[p] << 1) | mps; + } else { + self.state[ctx_idx] = (crate::cabac_tables::TRANS_MPS[p] << 1) | mps; + } + self.renorm(); + } + + /// EncodeBypass (9.3.4.3). + #[inline] + fn bypass(&mut self, bin: bool) { + self.low <<= 1; + if bin { + self.low += self.range; + } + if self.low >= 1024 { + self.put_bit(1); + self.low -= 1024; + } else if self.low < 512 { + self.put_bit(0); + } else { + self.low -= 512; + self.outstanding += 1; + } + } + + /// EncodeTerminate (9.3.4.5); a set bin ends the slice and flushes. + fn terminate(&mut self, bin: bool) { + self.range -= 2; + if bin { + self.low += self.range; + self.flush(); + } else { + self.renorm(); + } + } + + /// EncodeFlush (9.3.4.6). The last of the two bits written here is the + /// `rbsp_stop_one_bit`, so the caller only has to byte-align afterwards. + fn flush(&mut self) { + self.range = 2; + self.renorm(); + self.put_bit((self.low >> 9) & 1); + let v = ((self.low >> 7) & 3) | 1; + self.w.write_bit(v & 2 != 0); + self.w.write_bit(v & 1 != 0); + } + + /// End the slice (`end_of_slice_flag` = 1) and hand back the bitstream, + /// byte aligned. + pub(crate) fn finish(mut self) -> BitWriter { + self.terminate(true); + self.w.align_to_byte(); + self.w + } + + /// Bits written so far, including what the engine still holds. + pub(crate) fn bit_len(&self) -> u64 { + self.w.bit_len() + u64::from(self.outstanding) + } + + /// `end_of_slice_flag` = 0: another macroblock follows. + pub(crate) fn not_end_of_slice(&mut self) { + self.terminate(false); + } + + // ---- neighbourhood ---- + + pub(crate) fn begin_mb(&mut self, ctx: &MbCtx) { + self.ctx = *ctx; + self.cbp_luma_bins = 0; + self.cur_intra = true; + } + + pub(crate) fn set_intra(&mut self, intra: bool) { + self.cur_intra = intra; + } + + /// 9.3.3.1.1.3 for ctxIdxOffset 3 (I-slice mb_type). + fn mb_type_inc(&self) -> usize { + let cond = |n: Option| match n { + None => 0, + Some(i) => usize::from(i.flags & (FLAG_I16 | FLAG_PCM) != 0), + }; + cond(self.ctx.a) + cond(self.ctx.b) + } + + // ---- syntax elements ---- + + /// `mb_skip_flag` of a P slice; `inc` is condTermFlagA + condTermFlagB. + pub(crate) fn mb_skip_flag(&mut self, skipped: bool, inc: usize) { + self.decision(OFF_SKIP_P + inc, skipped); + } + + /// `mb_type` of an I slice (Table 9-36). + pub(crate) fn mb_type_i(&mut self, value: u32) { + let mut ctx = I_MB_TYPE_CTX; + ctx[0] = OFF_MB_TYPE + self.mb_type_inc(); + self.mb_type_intra(&ctx, value); + } + + /// `mb_type` of a P slice: 0..3 inter, or 5 + the I-slice type. + pub(crate) fn mb_type_p(&mut self, value: u32) { + if value >= 5 { + self.decision(OFF_MB_TYPE_P, true); + self.mb_type_intra(&I_SUFFIX_CTX_P, value - 5); + return; + } + self.decision(OFF_MB_TYPE_P, false); + // Table 9-37 / 9-41: b1 then b2, whose context depends on b1. + let (b1, b2) = match value { + 0 => (false, false), // P_L0_16x16 + 1 => (true, true), // P_L0_L0_16x8 + 2 => (true, false), // P_L0_L0_8x16 + _ => (false, true), // P_8x8 + }; + self.decision(OFF_MB_TYPE_P + 1, b1); + self.decision(OFF_MB_TYPE_P + if b1 { 3 } else { 2 }, b2); + } + + /// The Intra part of an mb_type bin string; `value` is the I-slice type. + fn mb_type_intra(&mut self, ctx: &[usize; 6], value: u32) { + if value == 0 { + self.decision(ctx[0], false); // I_NxN + return; + } + self.decision(ctx[0], true); + // I_PCM would set this terminate bin; this encoder never emits I_PCM. + self.terminate(false); + let m = value - 1; + let cbp_luma = m >= 12; + let chroma = (m / 4) % 3; + let mode = m % 4; + self.decision(ctx[1], cbp_luma); + if chroma == 0 { + self.decision(ctx[2], false); + } else { + self.decision(ctx[2], true); + self.decision(ctx[3], chroma == 2); + } + self.decision(ctx[4], mode & 2 != 0); + self.decision(ctx[5], mode & 1 != 0); + } + + /// `prev_intra4x4_pred_mode_flag` and `rem_intra4x4_pred_mode`. + pub(crate) fn intra4x4_pred_mode(&mut self, rem: Option) { + match rem { + None => self.decision(OFF_PREV_I4, true), + Some(r) => { + self.decision(OFF_PREV_I4, false); + for bit in 0..3 { + self.decision(OFF_REM_I4, r >> bit & 1 != 0); + } + } + } + } + + /// `intra_chroma_pred_mode`: TU cMax=3 with the 9.3.3.1.1.8 increment. + pub(crate) fn intra_chroma_pred_mode(&mut self, mode: u8) { + let cond = |n: Option| match n { + None => 0, + Some(i) => usize::from( + i.flags & (FLAG_PCM | FLAG_INTER) == 0 && i.flags & FLAG_CHROMA_PRED != 0, + ), + }; + let inc = cond(self.ctx.a) + cond(self.ctx.b); + if mode == 0 { + self.decision(OFF_CHROMA_PRED + inc, false); + return; + } + self.decision(OFF_CHROMA_PRED + inc, true); + self.decision(OFF_CHROMA_PRED + 3, mode >= 2); + if mode >= 2 { + self.decision(OFF_CHROMA_PRED + 3, mode == 3); + } + } + + /// `coded_block_pattern` (9.3.2.6). + pub(crate) fn coded_block_pattern(&mut self, luma: u8, chroma: u8) { + for bin in 0..4u8 { + let (a, b) = match bin { + 0 => ( + self.cbp_luma_neighbour(self.ctx.a, 1), + self.cbp_luma_neighbour(self.ctx.b, 2), + ), + 1 => (self.cbp_luma_own(0), self.cbp_luma_neighbour(self.ctx.b, 3)), + 2 => (self.cbp_luma_neighbour(self.ctx.a, 3), self.cbp_luma_own(0)), + _ => (self.cbp_luma_own(2), self.cbp_luma_own(1)), + }; + let set = luma & (1 << bin) != 0; + self.decision(OFF_CBP_LUMA + a + 2 * b, set); + if set { + self.cbp_luma_bins |= 1 << bin; + } + } + let chroma_cond = |n: Option, bin: u8| match n { + None => 0, + Some(i) if i.flags & FLAG_PCM != 0 => 1, + Some(i) => { + let c = i.cbp >> 4; + usize::from(if bin == 0 { c != 0 } else { c == 2 }) + } + }; + let inc0 = chroma_cond(self.ctx.a, 0) + 2 * chroma_cond(self.ctx.b, 0); + self.decision(OFF_CBP_CHROMA + inc0, chroma != 0); + if chroma != 0 { + let inc1 = chroma_cond(self.ctx.a, 1) + 2 * chroma_cond(self.ctx.b, 1) + 4; + self.decision(OFF_CBP_CHROMA + inc1, chroma == 2); + } + } + + fn cbp_luma_neighbour(&self, n: Option, blk: u8) -> usize { + match n { + None => 0, + Some(i) if i.flags & FLAG_PCM != 0 => 0, + Some(i) => usize::from(i.cbp & (1 << blk) == 0), + } + } + + fn cbp_luma_own(&self, blk: u8) -> usize { + usize::from(self.cbp_luma_bins & (1 << blk) == 0) + } + + /// `mb_qp_delta`: unary over the Table 9-3 mapping. + pub(crate) fn mb_qp_delta(&mut self, delta: i32) { + let k = if delta > 0 { 2 * delta - 1 } else { -2 * delta }; + let first = usize::from(self.ctx.qp_delta_inc); + for i in 0..k { + self.decision(OFF_QP_DELTA + qp_delta_inc(i, first), true); + } + self.decision(OFF_QP_DELTA + qp_delta_inc(k, first), false); + } + + /// One `mvd_lX` component: UEG3, signed, uCoff 9 (9.3.2.3). + pub(crate) fn mvd(&mut self, comp: usize, inc: usize, value: i32) { + let off = OFF_MVD[comp]; + let abs = value.unsigned_abs(); + if abs == 0 { + self.decision(off + inc, false); + return; + } + self.decision(off + inc, true); + // The decoder's loop counts prefix from 1 and stops on a zero bin. + let mut prefix = 1u32; + while prefix < 9 { + let ctx = off + (2 + prefix as usize).min(6); + if prefix < abs { + self.decision(ctx, true); + prefix += 1; + } else { + self.decision(ctx, false); + break; + } + } + if abs >= 9 { + self.ueg_suffix(abs - 9, 3); + } + self.bypass(value < 0); + } + + /// The bypass-coded k-th order Exp-Golomb suffix of a UEGk bin string. + fn ueg_suffix(&mut self, value: u32, k0: u32) { + let mut k = k0; + let mut v = value; + while v >= 1 << k { + self.bypass(true); + v -= 1 << k; + k += 1; + } + self.bypass(false); + while k > 0 { + k -= 1; + self.bypass(v >> k & 1 != 0); + } + } + + /// One residual block in scan order (7.3.5.3.3): coded_block_flag, the + /// significance map, then the levels highest scanning position first. + /// + /// `na`/`nb` are the neighbouring blocks' non-zero counts, `None` when that + /// neighbour is unavailable, exactly as the decoder receives them. + pub(crate) fn residual_block( + &mut self, + coeff: &[i32], + cat: BlockCat, + na: Option, + nb: Option, + ) -> u8 { + let cat_i = cat.ctx_block_cat(); + let max = cat.max_num_coeff(); + let last = (0..max).rev().find(|&i| coeff[i] != 0); + + let intra = self.cur_intra; + let cond = |n: Option| match n { + None => usize::from(intra), + Some(v) => usize::from(v != 0), + }; + let (a, b) = match cat { + BlockCat::LumaDc => (self.dc_cbf(self.ctx.a, 0), self.dc_cbf(self.ctx.b, 0)), + BlockCat::ChromaDc(c) => ( + self.dc_cbf(self.ctx.a, 1 + c), + self.dc_cbf(self.ctx.b, 1 + c), + ), + _ => (cond(na), cond(nb)), + }; + let Some(last) = last else { + self.decision(OFF_CBF + CBF_CAT_OFF[cat_i] + a + 2 * b, false); + return 0; + }; + self.decision(OFF_CBF + CBF_CAT_OFF[cat_i] + a + 2 * b, true); + + // Significance map. The decoder stops at the last significant position + // and infers the final coefficient, so nothing is written past `last`. + let sig_base = OFF_SIG + SIG_CAT_OFF[cat_i]; + let last_base = OFF_LAST + SIG_CAT_OFF[cat_i]; + for i in 0..max - 1 { + let inc = sig_inc(cat, i); + let significant = coeff[i] != 0; + self.decision(sig_base + inc, significant); + if significant { + self.decision(last_base + inc, i == last); + if i == last { + break; + } + } + } + + // Levels, highest scanning position first (9.3.3.1.3 counters). + let abs_base = OFF_ABS + ABS_CAT_OFF[cat_i]; + let chroma_dc = cat_i == 3; + let mut num_eq1 = 0u32; + let mut num_gt1 = 0u32; + let mut total = 0u8; + for pos in (0..=last).rev() { + let level = coeff[pos]; + if level == 0 { + continue; + } + let inc0 = if num_gt1 != 0 { + 0 + } else { + 4.min(1 + num_eq1) as usize + }; + let inc1 = 5 + (4 - u32::from(chroma_dc)).min(num_gt1) as usize; + let abs_minus1 = level.unsigned_abs() - 1; + let mut prefix = 0u32; + while prefix < 14 { + let ctx_idx = abs_base + if prefix == 0 { inc0 } else { inc1 }; + if prefix < abs_minus1 { + self.decision(ctx_idx, true); + prefix += 1; + } else { + self.decision(ctx_idx, false); + break; + } + } + if abs_minus1 >= 14 { + self.ueg_suffix(abs_minus1 - 14, 0); + } + self.bypass(level < 0); + if abs_minus1 == 0 { + num_eq1 += 1; + } else { + num_gt1 += 1; + } + total += 1; + } + total + } + + fn dc_cbf(&self, n: Option, which: u8) -> usize { + match n { + None => usize::from(self.cur_intra), + Some(i) if i.flags & FLAG_PCM != 0 => 1, + Some(i) => usize::from(i.dc_cbf & (1 << which) != 0), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::cabac::Cabac; + + /// The engine round-trips: a pseudo-random bin string written against a + /// spread of contexts, with bypass and terminate bins mixed in, decodes + /// back identically. This is the property every syntax element rests on. + #[test] + fn engine_round_trips() { + let mut state = 0x2545_F491u32; + let mut rand = move |m: u32| { + state ^= state << 13; + state ^= state >> 17; + state ^= state << 5; + state % m + }; + let mut plan: Vec<(usize, bool, u8)> = Vec::new(); // (ctx, bin, kind) + for _ in 0..4000 { + let kind = if rand(10) == 0 { 1 } else { 0 }; + plan.push((rand(NUM_CTX as u32) as usize, rand(2) == 1, kind)); + } + let mut enc = CabacEnc::new(BitWriter::new(), 26, 0); + for &(ctx, bin, kind) in &plan { + match kind { + 0 => enc.decision(ctx, bin), + _ => enc.bypass(bin), + } + enc.not_end_of_slice(); + } + let bytes = enc.finish().into_bytes(); + + let mut dec = Cabac::new(&bytes, 0, 26, 0).expect("decoder starts"); + for (i, &(ctx, bin, kind)) in plan.iter().enumerate() { + let got = match kind { + 0 => dec.decision_for_test(ctx), + _ => dec.bypass_for_test(), + }; + assert_eq!(got, bin, "bin {i}"); + assert!(dec.more_macroblocks().expect("terminate"), "bin {i} end"); + } + } +} diff --git a/crates/ec-h264/src/enc/entropy.rs b/crates/ec-h264/src/enc/entropy.rs new file mode 100644 index 00000000..017a98cd --- /dev/null +++ b/crates/ec-h264/src/enc/entropy.rs @@ -0,0 +1,194 @@ +//! One writing surface over both entropy coders, mirroring +//! [`crate::entropy::Entropy`] on the decoding side. +//! +//! The macroblock coder writes syntax elements, not bits: which coder is in +//! force changes the bins, the contexts and — for skipped macroblocks — the +//! shape of the slice data itself (`mb_skip_run` against `mb_skip_flag`), and +//! none of that belongs in the mode decision. + +use ec_core::BitWriter; + +use crate::entropy::{BlockCat, MbCtx}; + +use super::cabac_enc::CabacEnc; +use super::vlc::{write_cbp, write_residual_block}; + +pub(crate) enum EncEntropy { + Cavlc { + w: BitWriter, + /// Macroblocks skipped since the last coded one (7.3.4). + skip_run: u32, + }, + Cabac(Box), +} + +impl EncEntropy { + /// A CAVLC writer continuing after the slice header. + pub(crate) fn cavlc(w: BitWriter) -> EncEntropy { + EncEntropy::Cavlc { w, skip_run: 0 } + } + + /// A CABAC writer: `cabac_alignment_one_bit`s to the byte boundary, then + /// the context and engine initialisation of 9.3.1. + pub(crate) fn cabac(mut w: BitWriter, slice_qp: i32, init_column: usize) -> EncEntropy { + while !w.is_byte_aligned() { + w.write_bit(true); + } + EncEntropy::Cabac(Box::new(CabacEnc::new(w, slice_qp, init_column))) + } + + /// Bits written so far, for the row-level rate control. + pub(crate) fn bit_len(&self) -> u64 { + match self { + EncEntropy::Cavlc { w, .. } => w.bit_len(), + EncEntropy::Cabac(c) => c.bit_len(), + } + } + + /// Publish the neighbourhood of the macroblock about to be written. + pub(crate) fn begin_mb(&mut self, ctx: &MbCtx) { + if let EncEntropy::Cabac(c) = self { + c.begin_mb(ctx); + } + } + + /// Declare whether this macroblock is intra coded (9.3.3.1.1.9). + pub(crate) fn set_intra(&mut self, intra: bool) { + if let EncEntropy::Cabac(c) = self { + c.set_intra(intra); + } + } + + /// This macroblock is a skipped one. + pub(crate) fn skipped_mb(&mut self, inc: usize) { + match self { + EncEntropy::Cavlc { skip_run, .. } => *skip_run += 1, + EncEntropy::Cabac(c) => c.mb_skip_flag(true, inc), + } + } + + /// This macroblock is coded; in a P slice that closes any run of skips. + pub(crate) fn coded_mb(&mut self, p_slice: bool, inc: usize) { + if !p_slice { + return; + } + match self { + EncEntropy::Cavlc { w, skip_run } => { + w.write_ue(*skip_run); + *skip_run = 0; + } + EncEntropy::Cabac(c) => c.mb_skip_flag(false, inc), + } + } + + /// `mb_type`, in the slice's own numbering. + pub(crate) fn mb_type(&mut self, p_slice: bool, value: u32) { + match self { + EncEntropy::Cavlc { w, .. } => w.write_ue(value), + EncEntropy::Cabac(c) => { + if p_slice { + c.mb_type_p(value); + } else { + c.mb_type_i(value); + } + } + } + } + + /// One 4x4 intra prediction mode: `None` selects the predicted mode. + pub(crate) fn intra4x4_pred_mode(&mut self, rem: Option) { + match self { + EncEntropy::Cavlc { w, .. } => match rem { + None => w.write_bit(true), + Some(r) => { + w.write_bit(false); + w.write_bits(u32::from(r), 3); + } + }, + EncEntropy::Cabac(c) => c.intra4x4_pred_mode(rem), + } + } + + pub(crate) fn intra_chroma_pred_mode(&mut self, mode: u8) { + match self { + EncEntropy::Cavlc { w, .. } => w.write_ue(u32::from(mode)), + EncEntropy::Cabac(c) => c.intra_chroma_pred_mode(mode), + } + } + + pub(crate) fn coded_block_pattern(&mut self, luma: u8, chroma: u8, intra: bool) { + match self { + EncEntropy::Cavlc { w, .. } => write_cbp(w, luma, chroma, intra), + EncEntropy::Cabac(c) => c.coded_block_pattern(luma, chroma), + } + } + + pub(crate) fn mb_qp_delta(&mut self, delta: i32) { + match self { + EncEntropy::Cavlc { w, .. } => w.write_se(delta), + EncEntropy::Cabac(c) => c.mb_qp_delta(delta), + } + } + + /// One `mvd_lX` component; `inc` is the 9.3.3.1.1.7 increment, unused by + /// CAVLC. + pub(crate) fn mvd(&mut self, comp: usize, inc: usize, value: i32) { + match self { + EncEntropy::Cavlc { w, .. } => w.write_se(value), + EncEntropy::Cabac(c) => c.mvd(comp, inc, value), + } + } + + /// One residual block in scan order; returns its non-zero count, which the + /// caller records for the neighbours. + pub(crate) fn residual_block( + &mut self, + coeff: &[i32], + cat: BlockCat, + na: Option, + nb: Option, + ) -> u8 { + match self { + EncEntropy::Cavlc { w, .. } => { + let nc = if matches!(cat, BlockCat::ChromaDc(_)) { + -1 + } else { + match (na, nb) { + (Some(a), Some(b)) => (i32::from(a) + i32::from(b) + 1) >> 1, + (Some(a), None) => i32::from(a), + (None, Some(b)) => i32::from(b), + (None, None) => 0, + } + }; + write_residual_block(w, coeff, cat.max_num_coeff(), nc) + } + EncEntropy::Cabac(c) => c.residual_block(coeff, cat, na, nb), + } + } + + /// `end_of_slice_flag` after a macroblock (CABAC only). + pub(crate) fn end_of_slice(&mut self, last: bool) { + if let (EncEntropy::Cabac(c), false) = (self, last) { + c.not_end_of_slice(); + } + } + + /// Close the slice and hand back its RBSP. + pub(crate) fn finish(self, p_slice: bool) -> Vec { + match self { + EncEntropy::Cavlc { mut w, skip_run } => { + if p_slice && skip_run > 0 { + // A slice ending in skipped macroblocks says so with a + // final mb_skip_run; writing one when nothing was skipped + // would instead promise another macroblock (7.3.4). + w.write_ue(skip_run); + } + w.write_bit(true); // rbsp_stop_one_bit + w.align_to_byte(); + w.into_bytes() + } + // EncodeFlush already wrote the stop bit (9.3.4.6). + EncEntropy::Cabac(c) => c.finish().into_bytes(), + } + } +} diff --git a/crates/ec-h264/src/enc/headers.rs b/crates/ec-h264/src/enc/headers.rs index f02a0d84..a56cf27f 100644 --- a/crates/ec-h264/src/enc/headers.rs +++ b/crates/ec-h264/src/enc/headers.rs @@ -24,6 +24,8 @@ pub(crate) struct SeqParams { pub timing: (u32, u32), /// Bits per second the level has to carry. pub bitrate: u32, + /// CABAC, which Baseline does not allow: the sequence is then Main. + pub cabac: bool, } /// `log2_max_frame_num`, fixed: 8 bits of frame_num wrap far beyond the one @@ -69,8 +71,10 @@ fn level_idc(p: &SeqParams) -> u8 { /// ASO, no redundant slices, no interlace) that either profile forbids. pub(crate) fn write_sps(p: &SeqParams) -> Vec { let mut w = BitWriter::with_capacity(32); - w.write_bits(66, 8); // profile_idc: Baseline - w.write_bits(0b1100_0000, 8); // constraint_set0_flag, constraint_set1_flag + // Main when CABAC is in force (Baseline has no CABAC), Baseline otherwise; + // constraint_set1_flag says the stream also obeys the Main constraints. + w.write_bits(if p.cabac { 77 } else { 66 }, 8); + w.write_bits(if p.cabac { 0b0100_0000 } else { 0b1100_0000 }, 8); w.write_bits(u32::from(level_idc(p)), 8); w.write_ue(0); // seq_parameter_set_id w.write_ue(LOG2_MAX_FRAME_NUM - 4); @@ -110,11 +114,11 @@ pub(crate) fn write_sps(p: &SeqParams) -> Vec { } /// Write the picture parameter set RBSP (7.3.2.2). -pub(crate) fn write_pps() -> Vec { +pub(crate) fn write_pps(cabac: bool) -> Vec { let mut w = BitWriter::with_capacity(8); w.write_ue(0); // pic_parameter_set_id w.write_ue(0); // seq_parameter_set_id - w.write_bit(false); // entropy_coding_mode_flag: CAVLC + w.write_bit(cabac); // entropy_coding_mode_flag w.write_bit(false); // bottom_field_pic_order_in_frame_present_flag w.write_ue(0); // num_slice_groups_minus1 w.write_ue(0); // num_ref_idx_l0_default_active_minus1 @@ -141,6 +145,8 @@ pub(crate) struct SliceParams { /// `idr_pic_id`, alternating between consecutive IDR pictures. pub idr_pic_id: u32, pub qp: i32, + /// CABAC is in force, so a P slice carries cabac_init_idc. + pub cabac: bool, } /// Write a slice header (7.3.3) into `w`; slice data follows immediately. @@ -166,6 +172,9 @@ pub(crate) fn write_slice_header(w: &mut BitWriter, s: &SliceParams) { } else { w.write_bit(false); // adaptive_ref_pic_marking_mode_flag: sliding window } + if s.cabac && s.slice_type != SliceType::I { + w.write_ue(0); // cabac_init_idc + } w.write_se(s.qp - 26); // slice_qp_delta, pic_init_qp_minus26 being 0 // deblocking_filter_control_present_flag is 0: the filter is on, offsets 0. } @@ -189,15 +198,23 @@ mod tests { mb_h: height.div_ceil(16), timing: (1000, 60000), bitrate: 8_000_000, + cabac: true, } } /// The parameter sets this encoder writes are the ones the decoder's own - /// parser reads back, geometry, cropping and all. + /// parser reads back, geometry, cropping, profile and entropy coder alike. #[test] fn parameter_sets_parse_back() { - for (w, h) in [(1920, 1080), (640, 480), (854, 482), (16, 16)] { - let p = params(w, h); + for (w, h, cabac) in [ + (1920, 1080, true), + (1920, 1080, false), + (640, 480, true), + (854, 482, false), + (16, 16, true), + ] { + let mut p = params(w, h); + p.cabac = cabac; let sps = Sps::parse(&write_sps(&p)).expect("SPS parses"); assert_eq!((sps.width, sps.height), (w, h), "{w}x{h} crop"); assert_eq!(sps.mb_width, p.mb_w); @@ -207,8 +224,9 @@ mod tests { assert!(sps.frame_mbs_only); let vui = sps.vui.as_ref().expect("VUI present"); assert_eq!(vui.timing_info, Some((1000, 60000, true))); - let pps = Pps::parse(&write_pps(), |_| Some(&sps)).expect("PPS parses"); - assert!(!pps.entropy_coding_mode); + assert_eq!(sps.profile_idc, if cabac { 77 } else { 66 }); + let pps = Pps::parse(&write_pps(cabac), |_| Some(&sps)).expect("PPS parses"); + assert_eq!(pps.entropy_coding_mode, cabac); assert_eq!(pps.pic_init_qp, 26); } } @@ -228,7 +246,7 @@ mod tests { fn slice_header_parses_back() { let p = params(320, 240); let sps = Sps::parse(&write_sps(&p)).unwrap(); - let pps = Pps::parse(&write_pps(), |_| Some(&sps)).unwrap(); + let pps = Pps::parse(&write_pps(true), |_| Some(&sps)).unwrap(); for (idr, slice_type, first_mb, qp) in [ (true, SliceType::I, 0u32, 30i32), (false, SliceType::P, 40, 18), @@ -243,6 +261,7 @@ mod tests { idr, idr_pic_id: 1, qp, + cabac: true, }, ); trailing(&mut w); diff --git a/crates/ec-h264/src/enc/mb.rs b/crates/ec-h264/src/enc/mb.rs index 9f981bfd..860424bf 100644 --- a/crates/ec-h264/src/enc/mb.rs +++ b/crates/ec-h264/src/enc/mb.rs @@ -12,15 +12,16 @@ // the arrays instead would hide which geometry each loop names. #![allow(clippy::needless_range_loop)] -use ec_core::BitWriter; use ec_h264_syntax::SliceType; use wide::i16x16; use crate::decoder::{MbNeighbors, chroma_nz_pair, gather_nbr4, luma_nz_pair, mb_neighbors}; use crate::dpb::{BLK_SKIP, Picture}; -use crate::entropy::{FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_I16, FLAG_INTER, FLAG_SKIP}; +use crate::entropy::{ + BlockCat, FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_I16, FLAG_INTER, FLAG_SKIP, MbCtx, MbInfo, +}; use crate::inter::{RefPlane, integer_origin, mc_chroma, mc_luma}; -use crate::mv::{MvCtx, predict_mv, write_block, write_intra_mb, write_mvd}; +use crate::mv::{MvCtx, neighbour_mvd, predict_mv, write_block, write_intra_mb, write_mvd}; use crate::pred::{PlaneWindow, add_residual_4x4, pred_4x4, pred_16x16, pred_chroma_8x8}; use crate::tables::{BLK4_POS, CHROMA_QP}; use crate::transform::{ @@ -28,11 +29,11 @@ use crate::transform::{ unzigzag, unzigzag_ac15, }; +use super::entropy::EncEntropy; use super::quant::{ forward_4x4, forward_hadamard_2x2, forward_hadamard_4x4, quant_4x4, quant_chroma_dc, quant_luma_dc, }; -use super::vlc::{write_cbp, write_residual_block}; /// Speed/quality ladder. Two rungs, because the two the incumbent exposed are /// the two edith actually picks between. @@ -70,9 +71,14 @@ pub(crate) struct MbEnc<'a> { /// Lagrangian multiplier in the SATD domain. pub lambda: i32, pub preset: Preset, - /// Macroblocks skipped since the last coded one (`mb_skip_run`, 7.3.4). - pub skip_run: u32, pub ls: LevelScale4x4, + /// Neighbourhood of the macroblock being written (CABAC). + pub mb_ctx: MbCtx, + /// ctxIdxInc for this macroblock's mb_skip_flag. + pub skip_inc: usize, + /// `qp_delta_inc` of 9.3.3.1.1.5: whether the previous macroblock in this + /// slice carried a non-zero mb_qp_delta. + pub qp_delta_inc: u8, } /// Quantised levels of one macroblock, scan order per block. @@ -131,10 +137,26 @@ fn satd16( plane: &[u8], pstride: usize, po: usize, +) -> i32 { + satd_block(src, sstride, sx, sy, plane, pstride, po, 16, 16) +} + +/// The same over a `w` x `h` partition. +#[allow(clippy::too_many_arguments)] +fn satd_block( + src: &[u8], + sstride: usize, + sx: usize, + sy: usize, + plane: &[u8], + pstride: usize, + po: usize, + w: usize, + h: usize, ) -> i32 { let mut sum = 0; - for by in 0..4 { - for bx in 0..4 { + for by in 0..h / 4 { + for bx in 0..w / 4 { sum += satd4( src, sstride, @@ -148,27 +170,38 @@ fn satd16( sum } +/// Sum of absolute differences of a `w` x `h` block against a prediction with +/// its own pitch. This is the motion search's inner loop and nothing else in +/// the encoder is called as often, so a full-width row goes through one vector. #[allow(clippy::too_many_arguments)] -/// Sum of absolute differences of a 16x16 macroblock against a prediction of -/// any pitch, sixteen samples at a time: this is the motion search's inner -/// loop and nothing else in the encoder is called as often. -fn sad16( +fn sad( src: &[u8], sstride: usize, sx: usize, sy: usize, pred: &[u8], - po: usize, pstride: usize, + w: usize, + h: usize, ) -> i32 { - let mut acc = i16x16::ZERO; - for row in 0..16 { - let a = load16(src, (sy + row) * sstride + sx); - let b = load16(pred, po + row * pstride); - acc += (a - b).abs(); + if w == 16 { + let mut acc = i16x16::ZERO; + for y in 0..h { + let a = load16(src, (sy + y) * sstride + sx); + let b = load16(pred, y * pstride); + acc += (a - b).abs(); + } + return acc.to_array().iter().map(|&v| i32::from(v)).sum(); } - let lanes = acc.to_array(); - lanes.iter().map(|&v| i32::from(v)).sum() + let mut sum = 0; + for y in 0..h { + let s = &src[(sy + y) * sstride + sx..]; + let p = &pred[y * pstride..]; + for x in 0..w { + sum += (i32::from(s[x]) - i32::from(p[x])).abs(); + } + } + sum } /// Sixteen samples widened to 16-bit lanes; the tail past the slice is zero, @@ -184,30 +217,6 @@ fn load16(data: &[u8], at: usize) -> i16x16 { i16x16::from(a) } -/// Sum of absolute differences of a `w` x `h` block against a prediction with -/// its own pitch. -#[allow(clippy::too_many_arguments)] -fn sad( - src: &[u8], - sstride: usize, - sx: usize, - sy: usize, - pred: &[u8], - pstride: usize, - w: usize, - h: usize, -) -> i32 { - let mut sum = 0; - for y in 0..h { - let s = &src[(sy + y) * sstride + sx..]; - let p = &pred[y * pstride..]; - for x in 0..w { - sum += (i32::from(s[x]) - i32::from(p[x])).abs(); - } - } - sum -} - /// Bits an exp-Golomb `se(v)` costs, for the motion-vector cost term. #[inline] pub(crate) fn se_bits(v: i32) -> i32 { @@ -238,10 +247,24 @@ fn modes_allowed(have_top: bool, have_left: bool, have_tl: bool) -> [bool; 9] { /// Code one macroblock: decide its mode, reconstruct it into `pic` and write /// its syntax into `w`. -pub(crate) fn encode_mb(pic: &mut Picture, e: &mut MbEnc<'_>, w: &mut BitWriter, mb_addr: usize) { +pub(crate) fn encode_mb(pic: &mut Picture, e: &mut MbEnc<'_>, w: &mut EncEntropy, mb_addr: usize) { let mb_x = mb_addr % pic.mb_w; let mb_y = mb_addr / pic.mb_w; let nbr = mb_neighbors(pic, mb_x, mb_y, e.slice_id); + // The neighbourhood CABAC reads, captured before anything is written. + let info = |addr: usize| MbInfo { + flags: pic.mb_flags[addr], + cbp: pic.mb_cbp[addr], + dc_cbf: pic.mb_dc_cbf[addr], + }; + e.mb_ctx = MbCtx { + a: nbr.a.then(|| info(mb_addr - 1)), + b: nbr.b.then(|| info(mb_addr - pic.mb_w)), + qp_delta_inc: e.qp_delta_inc, + }; + // ctxIdxInc for mb_skip_flag (9.3.3.1.1.1). + e.skip_inc = usize::from(nbr.a && pic.mb_flags[mb_addr - 1] & FLAG_SKIP == 0) + + usize::from(nbr.b && pic.mb_flags[mb_addr - pic.mb_w] & FLAG_SKIP == 0); // Clear this macroblock's motion state, as the decoder does before parsing. let w4 = pic.mb_w * 4; @@ -280,34 +303,31 @@ pub(crate) fn encode_mb(pic: &mut Picture, e: &mut MbEnc<'_>, w: &mut BitWriter, } } -/// The intra decision taken before any reconstruction: best Intra_16x16 mode, -/// and whether the 4x4 modes look cheaper. +/// The Intra_16x16 mode this macroblock would use, and what it would cost: +/// the *inter or intra* decision needs a number before anything is coded, and +/// this is the cheap one. Intra_16x16 against Intra_4x4 is decided later, on +/// real rate and real distortion (see [`encode_intra_mb`]). struct IntraCost { i16_mode: u8, i16_cost: i32, - i4_cost: i32, - /// True when Intra_4x4 is allowed at all for this picture and preset. + /// True when Intra_4x4 may be used at all for this picture and preset. allow_i4: bool, } impl IntraCost { fn best(&self) -> i32 { + // Intra_4x4 usually beats this when it is allowed; the margin below is + // what keeps a P macroblock from going intra on the 16x16 cost alone. if self.allow_i4 { - self.i16_cost.min(self.i4_cost) + self.i16_cost * 3 / 4 } else { self.i16_cost } } - - fn use_i4(&self) -> bool { - self.allow_i4 && self.i4_cost < self.i16_cost - } } -/// Estimate both intra costs. The 4x4 estimate predicts from the *source* -/// samples inside the macroblock (they are written into the plane first), which -/// is the standard approximation: reconstruction is not available until the -/// mode is chosen, and the two differ by less than the decision margin. +/// Best Intra_16x16 mode by SATD, leaving nothing behind in the plane that a +/// later branch does not overwrite. fn intra_pre_cost( pic: &mut Picture, e: &MbEnc<'_>, @@ -340,56 +360,63 @@ fn intra_pre_cost( best = (cost, mode); } } + IntraCost { + i16_mode: best.1, + i16_cost: best.0, + allow_i4: e.slice_type == SliceType::I || e.preset == Preset::Balanced, + } +} + +/// How a P macroblock is partitioned, in the mb_type numbering of Table 7-13. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum PShape { + /// P_L0_16x16. + Whole, + /// P_L0_L0_16x8: a top and a bottom half. + Horizontal, + /// P_L0_L0_8x16: a left and a right half. + Vertical, +} - let allow_i4 = e.slice_type == SliceType::I || e.preset == Preset::Balanced; - let mut i4_cost = i32::MAX; - if allow_i4 { - // Source samples stand in for the not-yet-reconstructed neighbours. - for y in 0..16 { - let dst = origin + y * stride; - let s = (sy + y) * e.src.stride + sx; - pic.y.data[dst..dst + 16].copy_from_slice(&e.src.y[s..s + 16]); +impl PShape { + /// mb_type of Table 7-13. + fn mb_type(self) -> u32 { + match self { + PShape::Whole => 0, + PShape::Horizontal => 1, + PShape::Vertical => 2, } - let mut sum = 0; - for blk in 0..16 { - let (dx, dy) = BLK4_POS[blk]; - let (x, y) = (sx + dx as usize * 4, sy + dy as usize * 4); - let n = gather_nbr4(pic, nbr, blk, x, y); - let have_tl = match (dx, dy) { - (0, 0) => nbr.d, - (0, _) => nbr.a, - (_, 0) => nbr.b, - _ => true, - }; - let allowed = modes_allowed(n.have_top, n.have_left, have_tl); - let mut best4 = i32::MAX; - let mut p = [0u8; 16]; - for mode in 0..9u8 { - if !allowed[mode as usize] { - continue; - } - pred_4x4(mode, &n, &mut p); - let c = satd4(&e.src.y, e.src.stride, x, y, &p, 4) + e.lambda * 3; - best4 = best4.min(c); - } - sum += best4; + } + + fn parts(self) -> usize { + usize::from(self != PShape::Whole) + 1 + } + + /// Partition `part`'s origin in 4x4 blocks and its size in luma samples. + fn geometry(self, part: usize) -> ((usize, usize), (usize, usize)) { + match self { + PShape::Whole => ((0, 0), (16, 16)), + PShape::Horizontal => ((0, part * 2), (16, 8)), + PShape::Vertical => ((part * 2, 0), (8, 16)), } - // Sixteen mode signals and a coded_block_pattern the 16x16 form does - // not pay for. - i4_cost = sum + e.lambda * 16; } - IntraCost { - i16_mode: best.1, - i16_cost: best.0, - i4_cost, - allow_i4, + + /// `MbPartWidth`/`MbPartHeight` in 4x4 blocks, which select the + /// directional shortcuts of 8.4.1.3. + fn part_blocks(self) -> (usize, usize) { + match self { + PShape::Whole => (4, 4), + PShape::Horizontal => (4, 2), + PShape::Vertical => (2, 4), + } } } /// The inter decision for a P macroblock. struct InterChoice { - mv: [i16; 2], - mvp: [i16; 2], + shape: PShape, + /// One motion vector per partition. + mv: [[i16; 2]; 2], /// The P_Skip motion vector of 8.4.1.1. skip_mv: [i16; 2], cost: i32, @@ -428,169 +455,148 @@ fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> Inter pad: reference.y.pad, }; let (sx, sy) = (mb_x * 16, mb_y * 16); - let mut buf = [0u8; 256]; let sw = e.src.stride; - // Whole-sample candidates read the reference plane in place; only the - // sub-sample refinement pays for interpolation. The search runs on SAD, - // which is what a search can afford; the winner is re-costed on SATD below - // because the intra candidates are SATD and the two scales differ. - let mut cost_of = |mv: [i16; 2], satd: bool| -> i32 { - let bits = e.lambda - * (se_bits(i32::from(mv[0] - mvp[0])) + se_bits(i32::from(mv[1] - mvp[1]))) - / 2; - if !satd && mv[0] & 3 == 0 && mv[1] & 3 == 0 { - let o = integer_origin( - &plane, - sx as i32 + (mv[0] >> 2) as i32, - sy as i32 + (mv[1] >> 2) as i32, - 16, - 16, - ); - return sad16(&e.src.y, sw, sx, sy, plane.data, o, plane.stride) + bits; - } - mc_luma(&plane, sx as i32, sy as i32, mv, 16, 16, 16, &mut buf); - let d = if satd { - satd16(&e.src.y, sw, sx, sy, &buf, 16, 0) - } else { - sad16(&e.src.y, sw, sx, sy, &buf, 0, 16) - }; - d + bits + let range = match e.preset { + Preset::Fast => 16i16, + Preset::Balanced => 48, }; - // Candidates: the predictor, the skip vector, zero, and the vectors of the - // neighbouring partitions. - let mut best = ([0i16; 2], i32::MAX); - for cand in [mvp, skip_mv, [0, 0], n[0].mv, n[1].mv, n[2].mv] { - let c = cost_of(cand, false); - if c < best.1 { - best = (cand, c); - } - } - // A macroblock the prediction already fits is not searched further: on real - // content most of them are, and the search is the encoder's hot loop. - // A macroblock the prediction already fits within half a level a sample is - // not searched further: on real content most of them are, and this doubles - // the encoder's speed for 0.2 dB (measured, 1080p screen capture; camera - // content shows no loss at all). - const GOOD_ENOUGH: i32 = 16 * 16 / 2; - if best.1 > GOOD_ENOUGH { - // Diamond refinement at whole samples, coarse to fine. - let range = match e.preset { - Preset::Fast => 16i16, - Preset::Balanced => 48, + // One search over a `w` x `h` partition at `(px, py)` samples inside the + // macroblock, seeded with the candidate vectors of its neighbourhood. + let search = |px: usize, py: usize, w: usize, h: usize, mvp: [i16; 2], seeds: &[[i16; 2]]| { + let (x0, y0) = (sx + px, sy + py); + let mut buf = [0u8; 256]; + // Whole-sample candidates read the reference plane in place; only the + // sub-sample refinement pays for interpolation. The search runs on SAD, + // which is what a search can afford; the winner is re-costed on SATD + // because the intra candidates are SATD and the two scales differ. + let mut cost_of = |mv: [i16; 2], satd: bool| -> i32 { + let bits = e.lambda + * (se_bits(i32::from(mv[0] - mvp[0])) + se_bits(i32::from(mv[1] - mvp[1]))) + / 2; + if !satd && mv[0] & 3 == 0 && mv[1] & 3 == 0 { + let o = integer_origin( + &plane, + x0 as i32 + (mv[0] >> 2) as i32, + y0 as i32 + (mv[1] >> 2) as i32, + w, + h, + ); + return sad(&e.src.y, sw, x0, y0, &plane.data[o..], plane.stride, w, h) + bits; + } + mc_luma(&plane, x0 as i32, y0 as i32, mv, w, h, w, &mut buf); + let d = if satd { + satd_block(&e.src.y, sw, x0, y0, &buf, w, 0, w, h) + } else { + sad(&e.src.y, sw, x0, y0, &buf, w, w, h) + }; + d + bits }; - let mut step = 4i16 * 4; // four whole samples, in quarter units - while step >= 4 { - let mut improved = true; - while improved { - improved = false; - for (dx, dy) in [(step, 0), (-step, 0), (0, step), (0, -step)] { - let cand = [best.0[0] + dx, best.0[1] + dy]; - if (cand[0] - mvp[0]).abs() > range * 4 || (cand[1] - mvp[1]).abs() > range * 4 - { - continue; - } - let c = cost_of(cand, false); - if c < best.1 { - best = (cand, c); - improved = true; - } - } + + let mut best = ([0i16; 2], i32::MAX); + for &cand in seeds { + let c = cost_of(cand, false); + if c < best.1 { + best = (cand, c); } - step /= 2; } - // Half then quarter sample. - for step in [2i16, 1] { - let mut improved = true; - while improved { - improved = false; - for (dx, dy) in [ - (step, 0), - (-step, 0), - (0, step), - (0, -step), - (step, step), - (-step, -step), - (step, -step), - (-step, step), - ] { - let cand = [best.0[0] + dx, best.0[1] + dy]; - let c = cost_of(cand, false); - if c < best.1 { - best = (cand, c); - improved = true; + // A partition the prediction already fits within half a level a sample + // is not searched further: on real content most of them are, and the + // search is the encoder's hot loop. + let good_enough = (w * h / 2) as i32; + if best.1 > good_enough { + let mut step = 4i16 * 4; // four whole samples, in quarter units + while step >= 4 { + let mut improved = true; + while improved { + improved = false; + for (dx, dy) in [(step, 0), (-step, 0), (0, step), (0, -step)] { + let cand = [best.0[0] + dx, best.0[1] + dy]; + if (cand[0] - mvp[0]).abs() > range * 4 + || (cand[1] - mvp[1]).abs() > range * 4 + { + continue; + } + let c = cost_of(cand, false); + if c < best.1 { + best = (cand, c); + improved = true; + } } } - if e.preset == Preset::Fast { - break; + step /= 2; + } + for step in [2i16, 1] { + let mut improved = true; + while improved { + improved = false; + for (dx, dy) in [ + (step, 0), + (-step, 0), + (0, step), + (0, -step), + (step, step), + (-step, -step), + (step, -step), + (-step, step), + ] { + let cand = [best.0[0] + dx, best.0[1] + dy]; + let c = cost_of(cand, false); + if c < best.1 { + best = (cand, c); + improved = true; + } + } + if e.preset == Preset::Fast { + break; + } } } } + (best.0, cost_of(best.0, true)) + }; + + let seeds = [mvp, skip_mv, [0, 0], n[0].mv, n[1].mv, n[2].mv]; + let (mv16, cost16) = search(0, 0, 16, 16, mvp, &seeds); + let skip_cost = { + let mut buf = [0u8; 256]; + mc_luma(&plane, sx as i32, sy as i32, skip_mv, 16, 16, 16, &mut buf); + satd_block(&e.src.y, sw, sx, sy, &buf, 16, 0, 16, 16) - e.lambda * 4 + }; + + let mut best = (PShape::Whole, [mv16, mv16], cost16); + // Halves, seeded with the whole-macroblock winner. The predictor used here + // is the whole-macroblock one rather than each half's own: the real + // predictors are derived in coding order when the choice is made, and this + // only has to rank the shapes. A macroblock the 16x16 search already fits + // is left alone — splitting it could only spend bits. + // + // Measured: two more searches per macroblock buy 0.1-0.2 dB on screen + // capture and nothing on camera content, for roughly twice the search + // time. That is a Balanced trade, not a Fast one. + if e.preset == Preset::Balanced && cost16 > 16 * 16 { + for shape in [PShape::Horizontal, PShape::Vertical] { + let mut total = e.lambda * 6; // the partition's own signalling + let mut mvs = [[0i16; 2]; 2]; + for part in 0..2 { + let ((bx, by), (w, h)) = shape.geometry(part); + let seeds = [mv16, mvp, skip_mv, [0, 0]]; + let (mv, cost) = search(bx * 4, by * 4, w, h, mvp, &seeds); + mvs[part] = mv; + total += cost; + } + if total < best.2 { + best = (shape, mvs, total); + } + } } - // Re-cost both candidates on SATD for the comparison against intra, and - // for the skip decision (which trades a whole macroblock of bits). - let searched = cost_of(best.0, true); - let skip_cost = cost_of(skip_mv, true) - e.lambda * 4; InterChoice { - mv: best.0, - mvp, + shape: best.0, + mv: best.1, skip_mv, - cost: searched.min(skip_cost), - prefer_skip: skip_cost <= searched, - } -} - -/// Motion-compensate a whole macroblock into the picture planes. -fn compensate_mb(pic: &mut Picture, reference: &Picture, mb_x: usize, mb_y: usize, mv: [i16; 2]) { - let (x0, y0) = ((mb_x * 16) as i32, (mb_y * 16) as i32); - let plane = RefPlane { - data: &reference.y.data, - stride: reference.y.stride, - origin: reference.y.origin, - width: reference.y.width, - height: reference.y.height, - pad: reference.y.pad, - }; - let stride = pic.y.stride; - let origin = pic.y.at(mb_x * 16, mb_y * 16); - mc_luma( - &plane, - x0, - y0, - mv, - 16, - 16, - stride, - &mut pic.y.data[origin..], - ); - for comp in 0..2 { - let src = if comp == 0 { - &reference.cb - } else { - &reference.cr - }; - let plane = RefPlane { - data: &src.data, - stride: src.stride, - origin: src.origin, - width: src.width, - height: src.height, - pad: src.pad, - }; - let dst = if comp == 0 { &mut pic.cb } else { &mut pic.cr }; - let stride = dst.stride; - let origin = dst.at(mb_x * 8, mb_y * 8); - mc_chroma( - &plane, - x0 / 2, - y0 / 2, - mv, - 8, - 8, - stride, - &mut dst.data[origin..], - ); + cost: best.2.min(skip_cost), + prefer_skip: best.0 == PShape::Whole && skip_cost <= best.2, } } @@ -617,19 +623,84 @@ fn code_luma_4x4( - i32::from(pic.y.data[origin + ry * stride + rx]); } } + let source = d; forward_4x4(&mut d); let nz = quant_4x4(&d, qp, intra, false, &mut lv.luma[blk]); lv.luma_nz[blk] = nz; - if nz > 0 { - lv.cbp_luma |= 1 << (blk >> 2); - let mut raster = [0i32; 16]; - unzigzag(&lv.luma[blk], &mut raster); - dequant_4x4(&mut raster, &e.ls, qp, false); - let mut resid = [0i32; 16]; - inverse_transform_4x4(&raster, &mut resid); - add_residual_4x4(&mut pic.y.data, stride, origin, &resid); + if nz == 0 { + continue; + } + let mut raster = [0i32; 16]; + unzigzag(&lv.luma[blk], &mut raster); + dequant_4x4(&mut raster, &e.ls, qp, false); + let mut resid = [0i32; 16]; + inverse_transform_4x4(&raster, &mut resid); + // Is the block worth its bits? A block whose residual barely moves the + // reconstruction is pure quantisation churn; dropping it is the cheap + // half of rate-distortion optimised quantisation, and the half that + // pays. Intra blocks are left alone: their reconstruction is what the + // next block in the macroblock predicts from. + if !intra && !worth_coding(&source, &resid, &lv.luma[blk], qp) { + lv.luma[blk] = [0; 16]; + lv.luma_nz[blk] = 0; + continue; } + lv.cbp_luma |= 1 << (blk >> 2); + add_residual_4x4(&mut pic.y.data, stride, origin, &resid); + } +} + +/// How much of the mode-decision lambda the zero-block test uses. +/// +/// [`block_bits`] counts a level at its exp-Golomb-ish width, which is what +/// CAVLC spends and an over-estimate of what CABAC spends; the multiplier +/// brings the rate term back to the coder actually in force. Measured over +/// 0.0, 0.4 and 1.0 on 1080p camera and screen-capture clips: 0.4 is the only +/// one that gains on screen content (+0.13 to +0.39 dB at matched bitrate) +/// without costing camera content. +const ZERO_BLOCK_LAMBDA: f64 = 0.4; + +/// The rate-distortion test behind the per-block zero decision: coding the +/// block has to buy more squared error than its bits are worth. +fn worth_coding(source: &[i32; 16], resid: &[i32; 16], levels: &[i32; 16], qp: i32) -> bool { + let mut ssd_zero = 0i64; + let mut ssd_coded = 0i64; + for i in 0..16 { + let z = i64::from(source[i]); + let c = i64::from(source[i] - resid[i]); + ssd_zero += z * z; + ssd_coded += c * c; + } + ssd_coded as f64 + ZERO_BLOCK_LAMBDA * lambda_ssd(qp) * (block_bits(levels) as f64) + < ssd_zero as f64 +} + +/// Predict and code the luma of an Intra_16x16 macroblock. +#[allow(clippy::too_many_arguments)] +fn code_i16_luma( + pic: &mut Picture, + e: &MbEnc<'_>, + mb_x: usize, + mb_y: usize, + qp: i32, + mode: u8, + nbr: &MbNeighbors, + lv: &mut Levels, +) { + let w4 = pic.mb_w * 4; + for dy in 0..4 { + let base = (mb_y * 4 + dy) * w4 + mb_x * 4; + pic.i4_modes[base..base + 4].fill(2); } + let stride = pic.y.stride; + let origin = pic.y.at(mb_x * 16, mb_y * 16); + let mut win = PlaneWindow { + data: &mut pic.y.data, + stride, + origin, + }; + pred_16x16(mode, &mut win, nbr.b, nbr.a); + code_luma_i16(pic, e, mb_x, mb_y, qp, lv); } /// The Intra_16x16 luma path (8.5.10 in reverse then forward again). @@ -732,9 +803,24 @@ fn code_chroma( - i32::from(plane.data[origin + ry * stride + rx]); } } + let source = d; forward_4x4(&mut d); dc_lists[comp][blk] = d[0]; - let nz = quant_4x4(&d, qp_c, intra, true, &mut ac[comp][blk]); + let mut nz = quant_4x4(&d, qp_c, intra, true, &mut ac[comp][blk]); + if nz > 0 { + // The same zero decision as luma, against the AC part alone: + // the DC of this block travels through the 2x2 Hadamard and is + // decided with the other three. + let mut raster = [0i32; 16]; + unzigzag_ac15(&ac[comp][blk], &mut raster); + dequant_4x4(&mut raster, &e.ls, qp_c, true); + let mut resid = [0i32; 16]; + inverse_transform_4x4(&raster, &mut resid); + if !worth_coding(&source, &resid, &ac[comp][blk], qp_c) { + ac[comp][blk] = [0; 16]; + nz = 0; + } + } lv.chroma_nz[comp][blk] = nz; if nz > 0 { any_ac = true; @@ -857,11 +943,152 @@ fn choose_chroma_mode( best.1 } -/// Code an intra macroblock, Intra_16x16 or Intra_4x4. +/// Code the luma of an Intra_4x4 macroblock: per block, choose the prediction +/// mode against the *reconstructed* neighbours and reconstruct it immediately, +/// because the next block predicts from it. Returns the chosen modes and the +/// modes they were predicted to be. +fn code_intra_4x4( + pic: &mut Picture, + e: &MbEnc<'_>, + mb_x: usize, + mb_y: usize, + qp: i32, + nbr: &MbNeighbors, + lv: &mut Levels, +) -> ([u8; 16], [u8; 16]) { + let w4 = pic.mb_w * 4; + let (bx0, by0) = (mb_x * 4, mb_y * 4); + let mut modes = [2u8; 16]; + let mut pred_modes = [2u8; 16]; + for blk in 0..16 { + let (dx, dy) = BLK4_POS[blk]; + let (bx, by) = (bx0 + dx as usize, by0 + dy as usize); + let (x, y) = (mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4); + let left_avail = if dx == 0 { nbr.a } else { true }; + let top_avail = if dy == 0 { nbr.b } else { true }; + let predicted = if left_avail && top_avail { + pic.i4_modes[by * w4 + bx - 1].min(pic.i4_modes[(by - 1) * w4 + bx]) + } else { + 2 + }; + pred_modes[blk] = predicted; + let n = gather_nbr4(pic, nbr, blk, x, y); + let have_tl = match (dx, dy) { + (0, 0) => nbr.d, + (0, _) => nbr.a, + (_, 0) => nbr.b, + _ => true, + }; + let allowed = modes_allowed(n.have_top, n.have_left, have_tl); + let mut best = (i32::MAX, predicted.min(2)); + let mut p = [0u8; 16]; + for mode in 0..9u8 { + if !allowed[mode as usize] { + continue; + } + pred_4x4(mode, &n, &mut p); + let bits = if mode == predicted { 1 } else { 4 }; + let c = satd4(&e.src.y, e.src.stride, x, y, &p, 4) + e.lambda * bits; + if c < best.0 { + best = (c, mode); + } + } + let mode = best.1; + modes[blk] = mode; + pic.i4_modes[by * w4 + bx] = mode; + // Prediction into the plane, then residual and reconstruction. + pred_4x4(mode, &n, &mut p); + let stride = pic.y.stride; + let origin = pic.y.at(x, y); + for ry in 0..4 { + let row = origin + ry * stride; + pic.y.data[row..row + 4].copy_from_slice(&p[ry * 4..ry * 4 + 4]); + } + let mut d = [0i32; 16]; + for ry in 0..4 { + for rx in 0..4 { + d[ry * 4 + rx] = i32::from(e.src.y[(y + ry) * e.src.stride + x + rx]) + - i32::from(p[ry * 4 + rx]); + } + } + forward_4x4(&mut d); + let nz = quant_4x4(&d, qp, true, false, &mut lv.luma[blk]); + lv.luma_nz[blk] = nz; + if nz > 0 { + lv.cbp_luma |= 1 << (blk >> 2); + let mut raster = [0i32; 16]; + unzigzag(&lv.luma[blk], &mut raster); + dequant_4x4(&mut raster, &e.ls, qp, false); + let mut resid = [0i32; 16]; + inverse_transform_4x4(&raster, &mut resid); + add_residual_4x4(&mut pic.y.data, stride, origin, &resid); + } + } + (modes, pred_modes) +} + +/// Squared error of the luma macroblock against the source. +fn ssd_luma(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> i64 { + let stride = pic.y.stride; + let origin = pic.y.at(mb_x * 16, mb_y * 16); + let mut sum = 0i64; + for row in 0..16 { + let s = (mb_y * 16 + row) * e.src.stride + mb_x * 16; + for x in 0..16 { + let d = i64::from(e.src.y[s + x]) - i64::from(pic.y.data[origin + row * stride + x]); + sum += d * d; + } + } + sum +} + +/// Copy the luma macroblock out of the plane, and back in. +fn save_luma(pic: &Picture, mb_x: usize, mb_y: usize, out: &mut [u8; 256]) { + let stride = pic.y.stride; + let origin = pic.y.at(mb_x * 16, mb_y * 16); + for row in 0..16 { + out[row * 16..row * 16 + 16].copy_from_slice(&pic.y.data[origin + row * stride..][..16]); + } +} + +fn restore_luma(pic: &mut Picture, mb_x: usize, mb_y: usize, src: &[u8; 256]) { + let stride = pic.y.stride; + let origin = pic.y.at(mb_x * 16, mb_y * 16); + for row in 0..16 { + pic.y.data[origin + row * stride..][..16].copy_from_slice(&src[row * 16..row * 16 + 16]); + } +} + +/// Bits the luma residual and the mode signalling of an intra macroblock cost, +/// to the accuracy the mode decision needs. +fn intra_bits(lv: &Levels, i4: Option<(&[u8; 16], &[u8; 16])>) -> i64 { + let mut bits = estimate_luma_bits(lv); + match i4 { + // Sixteen mode signals plus the coded_block_pattern the 16x16 form + // derives from its macroblock type instead. + Some((modes, pred)) => { + bits += 6; + for blk in 0..16 { + bits += if modes[blk] == pred[blk] { 1 } else { 4 }; + } + } + None => bits += 8, + } + bits +} + +/// Code an intra macroblock, choosing Intra_16x16 against Intra_4x4 on real +/// rate and real distortion. +/// +/// A SATD estimate of the 4x4 form has to predict from the source samples +/// inside the macroblock — the reconstruction it would predict from does not +/// exist until the mode is chosen — and on flat or text-heavy pictures that +/// estimate misjudges which form wins. Coding both and measuring is worth +/// more than it costs: it is 1.1 dB on screen capture at matched bitrate. fn encode_intra_mb( pic: &mut Picture, e: &mut MbEnc<'_>, - w: &mut BitWriter, + w: &mut EncEntropy, mb_addr: usize, nbr: MbNeighbors, cost: IntraCost, @@ -873,101 +1100,52 @@ fn encode_intra_mb( let qp = e.target_qp; write_intra_mb(pic, mb_x, mb_y); let mut lv = Levels::default(); - let use_i4 = cost.use_i4(); let mut modes = [2u8; 16]; let mut pred_modes = [2u8; 16]; + let mut use_i4 = false; - if use_i4 { - // Per block: choose the mode against reconstructed neighbours, then - // reconstruct it immediately — the next block predicts from it. + if cost.allow_i4 { + let mut lv4 = Levels::default(); + let (m4, p4) = code_intra_4x4(pic, e, mb_x, mb_y, qp, &nbr, &mut lv4); + let cost4 = ssd_luma(pic, e, mb_x, mb_y) as f64 + + lambda_ssd(qp) * intra_bits(&lv4, Some((&m4, &p4))) as f64; + let mut recon4 = [0u8; 256]; + save_luma(pic, mb_x, mb_y, &mut recon4); + let mut modes4 = [2u8; 16]; for blk in 0..16 { let (dx, dy) = BLK4_POS[blk]; - let (bx, by) = (bx0 + dx as usize, by0 + dy as usize); - let (x, y) = (mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4); - let left_avail = if dx == 0 { nbr.a } else { true }; - let top_avail = if dy == 0 { nbr.b } else { true }; - let predicted = if left_avail && top_avail { - pic.i4_modes[by * w4 + bx - 1].min(pic.i4_modes[(by - 1) * w4 + bx]) - } else { - 2 - }; - pred_modes[blk] = predicted; - let n = gather_nbr4(pic, &nbr, blk, x, y); - let have_tl = match (dx, dy) { - (0, 0) => nbr.d, - (0, _) => nbr.a, - (_, 0) => nbr.b, - _ => true, - }; - let allowed = modes_allowed(n.have_top, n.have_left, have_tl); - let mut best = (i32::MAX, predicted.min(2)); - let mut p = [0u8; 16]; - for mode in 0..9u8 { - if !allowed[mode as usize] { - continue; - } - pred_4x4(mode, &n, &mut p); - let bits = if mode == predicted { 1 } else { 4 }; - let c = satd4(&e.src.y, e.src.stride, x, y, &p, 4) + e.lambda * bits; - if c < best.0 { - best = (c, mode); - } - } - let mode = best.1; - modes[blk] = mode; - pic.i4_modes[by * w4 + bx] = mode; - // Prediction into the plane, then residual and reconstruction. - pred_4x4(mode, &n, &mut p); - let stride = pic.y.stride; - let origin = pic.y.at(x, y); - for ry in 0..4 { - let row = origin + ry * stride; - pic.y.data[row..row + 4].copy_from_slice(&p[ry * 4..ry * 4 + 4]); - } - let mut d = [0i32; 16]; - for ry in 0..4 { - for rx in 0..4 { - d[ry * 4 + rx] = i32::from(e.src.y[(y + ry) * e.src.stride + x + rx]) - - i32::from(p[ry * 4 + rx]); - } - } - forward_4x4(&mut d); - let nz = quant_4x4(&d, qp, true, false, &mut lv.luma[blk]); - lv.luma_nz[blk] = nz; - if nz > 0 { - lv.cbp_luma |= 1 << (blk >> 2); - let mut raster = [0i32; 16]; - unzigzag(&lv.luma[blk], &mut raster); - dequant_4x4(&mut raster, &e.ls, qp, false); - let mut resid = [0i32; 16]; - inverse_transform_4x4(&raster, &mut resid); - add_residual_4x4(&mut pic.y.data, stride, origin, &resid); + modes4[blk] = pic.i4_modes[(by0 + dy as usize) * w4 + bx0 + dx as usize]; + } + + let mut lv16 = Levels::default(); + code_i16_luma(pic, e, mb_x, mb_y, qp, cost.i16_mode, &nbr, &mut lv16); + let cost16 = + ssd_luma(pic, e, mb_x, mb_y) as f64 + lambda_ssd(qp) * intra_bits(&lv16, None) as f64; + + if cost4 <= cost16 { + use_i4 = true; + restore_luma(pic, mb_x, mb_y, &recon4); + for blk in 0..16 { + let (dx, dy) = BLK4_POS[blk]; + pic.i4_modes[(by0 + dy as usize) * w4 + bx0 + dx as usize] = modes4[blk]; } + lv = lv4; + modes = m4; + pred_modes = p4; + } else { + lv = lv16; } } else { - for dy in 0..4 { - let base = (by0 + dy) * w4 + bx0; - pic.i4_modes[base..base + 4].fill(2); - } - let stride = pic.y.stride; - let origin = pic.y.at(mb_x * 16, mb_y * 16); - let mut win = PlaneWindow { - data: &mut pic.y.data, - stride, - origin, - }; - pred_16x16(cost.i16_mode, &mut win, nbr.b, nbr.a); - code_luma_i16(pic, e, mb_x, mb_y, qp, &mut lv); + code_i16_luma(pic, e, mb_x, mb_y, qp, cost.i16_mode, &nbr, &mut lv); } let chroma_mode = choose_chroma_mode(pic, e, &nbr, mb_x, mb_y); code_chroma(pic, e, mb_x, mb_y, qp, true, &mut lv); // ---- syntax ---- - if e.slice_type == SliceType::P { - w.write_ue(e.skip_run); - e.skip_run = 0; - } + w.begin_mb(&e.mb_ctx); + w.coded_mb(e.slice_type == SliceType::P, e.skip_inc); + w.set_intra(true); let intra_type = if use_i4 { 0 } else { @@ -975,26 +1153,24 @@ fn encode_intra_mb( + 4 * u32::from(lv.cbp_chroma) + if lv.cbp_luma != 0 { 12 } else { 0 } }; - let offset = if e.slice_type == SliceType::P { 5 } else { 0 }; - w.write_ue(intra_type + offset); + let p_slice = e.slice_type == SliceType::P; + let offset = if p_slice { 5 } else { 0 }; + w.mb_type(p_slice, intra_type + offset); if use_i4 { for blk in 0..16 { - if modes[blk] == pred_modes[blk] { - w.write_bit(true); + let rem = if modes[blk] == pred_modes[blk] { + None + } else if modes[blk] > pred_modes[blk] { + Some(modes[blk] - 1) } else { - w.write_bit(false); - let rem = if modes[blk] > pred_modes[blk] { - modes[blk] - 1 - } else { - modes[blk] - }; - w.write_bits(u32::from(rem), 3); - } + Some(modes[blk]) + }; + w.intra4x4_pred_mode(rem); } } - w.write_ue(u32::from(chroma_mode)); + w.intra_chroma_pred_mode(chroma_mode); if use_i4 { - write_cbp(w, lv.cbp_luma, lv.cbp_chroma, true); + w.coded_block_pattern(lv.cbp_luma, lv.cbp_chroma, true); } finish_mb( pic, @@ -1044,30 +1220,47 @@ fn ssd_mb(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> i64 { sum } +/// Rough bit cost of a macroblock's luma residual. +fn estimate_luma_bits(lv: &Levels) -> i64 { + let mut bits = 0; + for blk in 0..16 { + if lv.cbp_luma & (1 << (blk >> 2)) != 0 { + bits += block_bits(&lv.luma[blk]); + } + } + if lv.cbp_luma == 15 { + // Intra_16x16 also carries the DC block. + bits += block_bits(&lv.dc); + } + bits +} + +/// Bits one residual block costs, to the accuracy a mode decision needs. +fn block_bits(b: &[i32]) -> i64 { + let mut n = 0i64; + for &l in b { + if l != 0 { + n += 2 * (64 - u64::from(l.unsigned_abs()).leading_zeros() as i64) + 1; + } + } + if n > 0 { n + 6 } else { 2 } +} + /// Rough bit cost of a macroblock's residual, for the skip decision: a level /// costs its magnitude's exp-Golomb-ish width, a coded block its token. fn estimate_bits(lv: &Levels) -> i64 { let mut bits = 10i64; - let block = |b: &[i32]| -> i64 { - let mut n = 0i64; - for &l in b { - if l != 0 { - n += 2 * (64 - u64::from(l.unsigned_abs()).leading_zeros() as i64) + 1; - } - } - if n > 0 { n + 6 } else { 2 } - }; for blk in 0..16 { if lv.cbp_luma & (1 << (blk >> 2)) != 0 { - bits += block(&lv.luma[blk]); + bits += block_bits(&lv.luma[blk]); } } if lv.cbp_chroma != 0 { for comp in 0..2 { - bits += block(&lv.chroma_dc[comp][..4]); + bits += block_bits(&lv.chroma_dc[comp][..4]); if lv.cbp_chroma == 2 { for blk in 0..4 { - bits += block(&lv.chroma[comp][blk][..15]); + bits += block_bits(&lv.chroma[comp][blk][..15]); } } } @@ -1081,11 +1274,63 @@ fn lambda_ssd(qp: i32) -> f64 { 0.85 * ((f64::from(qp) - 12.0) / 3.0).exp2() } -/// Code a P macroblock: skip, or one 16x16 partition. +/// Motion-compensate one partition into the picture planes. +fn compensate_part( + pic: &mut Picture, + reference: &Picture, + mb_x: usize, + mb_y: usize, + (bx, by): (usize, usize), + (w, h): (usize, usize), + mv: [i16; 2], +) { + let (x0, y0) = ((mb_x * 16 + bx * 4) as i32, (mb_y * 16 + by * 4) as i32); + let plane = RefPlane { + data: &reference.y.data, + stride: reference.y.stride, + origin: reference.y.origin, + width: reference.y.width, + height: reference.y.height, + pad: reference.y.pad, + }; + let stride = pic.y.stride; + let origin = pic.y.at(mb_x * 16 + bx * 4, mb_y * 16 + by * 4); + mc_luma(&plane, x0, y0, mv, w, h, stride, &mut pic.y.data[origin..]); + for comp in 0..2 { + let src = if comp == 0 { + &reference.cb + } else { + &reference.cr + }; + let plane = RefPlane { + data: &src.data, + stride: src.stride, + origin: src.origin, + width: src.width, + height: src.height, + pad: src.pad, + }; + let dst = if comp == 0 { &mut pic.cb } else { &mut pic.cr }; + let stride = dst.stride; + let origin = dst.at(mb_x * 8 + bx * 2, mb_y * 8 + by * 2); + mc_chroma( + &plane, + x0 / 2, + y0 / 2, + mv, + w / 2, + h / 2, + stride, + &mut dst.data[origin..], + ); + } +} + +/// Code a P macroblock: skip, one 16x16 partition, or two halves. fn encode_inter_mb( pic: &mut Picture, e: &mut MbEnc<'_>, - w: &mut BitWriter, + w: &mut EncEntropy, mb_addr: usize, nbr: MbNeighbors, choice: InterChoice, @@ -1095,18 +1340,71 @@ fn encode_inter_mb( let reference = e.reference.expect("a P macroblock has a reference"); let ref_id = reference.id; let qp = e.target_qp; - let mv = if choice.prefer_skip { - choice.skip_mv + let shape = if choice.prefer_skip { + PShape::Whole } else { - choice.mv + choice.shape + }; + + // Motion vectors, their predictors and the reconstruction, partition by + // partition and in coding order: a partition's predictor reads the motion + // of the partitions before it (8.4.1.3), so the order is not free. + let mut ctx = MvCtx { + mb_x, + mb_y, + slice_id: e.slice_id, + written: 0, }; + let (part_w, part_h) = shape.part_blocks(); + let mut mvd = [[0i16; 2]; 2]; + let mut inc = [[0usize; 2]; 2]; + for part in 0..shape.parts() { + let ((bx, by), (pw, ph)) = shape.geometry(part); + let mv = if choice.prefer_skip { + choice.skip_mv + } else { + choice.mv[part] + }; + let n = ctx.neighbours(pic, bx, by, part_w, 0); + let mvp = predict_mv(&n, 0, part_w, part_h, part); + // ctxIdxInc from the neighbouring partitions' absolute mvd + // (9.3.3.1.1.7), read before this partition writes its own. + let (gx, gy) = ((mb_x * 4 + bx) as i32, (mb_y * 4 + by) as i32); + for comp in 0..2 { + let sum = neighbour_mvd(pic, &ctx, gx - 1, gy, 0)[comp] + + neighbour_mvd(pic, &ctx, gx, gy - 1, 0)[comp]; + inc[part][comp] = if sum > 32 { + 2 + } else if sum > 2 { + 1 + } else { + 0 + }; + } + mvd[part] = [mv[0] - mvp[0], mv[1] - mvp[1]]; + compensate_part(pic, reference, mb_x, mb_y, (bx, by), (pw, ph), mv); + for py in by..by + ph / 4 { + for px in bx..bx + pw / 4 { + write_block( + pic, + &mut ctx, + px, + py, + [mv, [0, 0]], + [0, -1], + [ref_id, -1], + 0, + ); + write_mvd(pic, mb_x, mb_y, px, py, 0, mvd[part]); + } + } + } - compensate_mb(pic, reference, mb_x, mb_y, mv); - // Skipping is only *available* on the P_Skip vector, and only worth taking - // when the residual it drops is worth less than the bits it saves: on - // static content a macroblock whose residual is pure quantisation churn - // costs bits every picture and improves nothing. - let may_skip = mv == choice.skip_mv; + // Skipping is only *available* on the P_Skip vector of a whole macroblock, + // and only worth taking when the residual it drops is worth less than the + // bits it saves: on static content a macroblock whose residual is pure + // quantisation churn costs bits every picture and improves nothing. + let may_skip = choice.prefer_skip; let ssd_skip = may_skip.then(|| ssd_mb(pic, e, mb_x, mb_y)); let mut lv = Levels::default(); code_luma_4x4(pic, e, mb_x, mb_y, qp, false, &mut lv); @@ -1120,7 +1418,7 @@ fn encode_inter_mb( ssd_mb(pic, e, mb_x, mb_y) as f64 + lambda_ssd(qp) * estimate_bits(&lv) as f64; if ssd_skip as f64 <= coded { // Put the prediction back: the residual has been added to it. - compensate_mb(pic, reference, mb_x, mb_y, mv); + compensate_part(pic, reference, mb_x, mb_y, (0, 0), (16, 16), choice.skip_mv); true } else { false @@ -1128,26 +1426,13 @@ fn encode_inter_mb( } }; - let mut ctx = MvCtx { - mb_x, - mb_y, - slice_id: e.slice_id, - written: 0, - }; let w4 = pic.mb_w * 4; if skip { for py in 0..4 { for px in 0..4 { - write_block( - pic, - &mut ctx, - px, - py, - [mv, [0, 0]], - [0, -1], - [ref_id, -1], - BLK_SKIP, - ); + let idx = (mb_y * 4 + py) * w4 + mb_x * 4 + px; + pic.blk[idx] = BLK_SKIP; + pic.mvd_abs[idx] = [0; 4]; } } for dy in 0..4 { @@ -1167,39 +1452,27 @@ fn encode_inter_mb( pic.mb_dc_cbf[mb_addr] = 0; pic.mb_slice[mb_addr] = e.slice_id; pic.decoded_mbs += 1; - e.skip_run += 1; + e.qp_delta_inc = 0; + w.skipped_mb(e.skip_inc); return; } - - let mvd = [mv[0] - choice.mvp[0], mv[1] - choice.mvp[1]]; - for py in 0..4 { - for px in 0..4 { - write_block( - pic, - &mut ctx, - px, - py, - [mv, [0, 0]], - [0, -1], - [ref_id, -1], - 0, - ); - write_mvd(pic, mb_x, mb_y, px, py, 0, mvd); - } - } for dy in 0..4 { let base = (mb_y * 4 + dy) * w4 + mb_x * 4; pic.i4_modes[base..base + 4].fill(2); } // ---- syntax ---- - w.write_ue(e.skip_run); - e.skip_run = 0; - w.write_ue(0); // mb_type P_L0_16x16 + w.begin_mb(&e.mb_ctx); + w.coded_mb(true, e.skip_inc); + w.set_intra(false); + w.mb_type(true, shape.mb_type()); // num_ref_idx_l0_active is 1, so ref_idx_l0 is not coded. - w.write_se(i32::from(mvd[0])); - w.write_se(i32::from(mvd[1])); - write_cbp(w, lv.cbp_luma, lv.cbp_chroma, false); + for part in 0..shape.parts() { + for comp in 0..2 { + w.mvd(comp, inc[part][comp], i32::from(mvd[part][comp])); + } + } + w.coded_block_pattern(lv.cbp_luma, lv.cbp_chroma, false); finish_mb( pic, e, @@ -1230,7 +1503,7 @@ struct MbRecord { fn finish_mb( pic: &mut Picture, e: &mut MbEnc<'_>, - w: &mut BitWriter, + w: &mut EncEntropy, mb_addr: usize, nbr: &MbNeighbors, lv: &Levels, @@ -1245,12 +1518,15 @@ fn finish_mb( let coded = lv.cbp_luma != 0 || lv.cbp_chroma != 0 || m.is_i16; let qp_y = if coded { - w.write_se(m.qp - e.qp); + let delta = m.qp - e.qp; + w.mb_qp_delta(delta); + e.qp_delta_inc = u8::from(delta != 0); e.qp = m.qp; m.qp } else { // No residual: the QP prediction chain is untouched (7.4.5), and the // deblocking filter uses the chain value. + e.qp_delta_inc = 0; e.qp }; pic.mb_qp[mb_addr] = qp_y as u8; @@ -1270,8 +1546,7 @@ fn finish_mb( // Luma DC (Intra_16x16 only), then the luma blocks in Z-order. if m.is_i16 { let (na, nb) = luma_nz_pair(pic, nbr, bx0, by0); - let nc = nc_of(na, nb); - let tc = write_residual_block(w, &lv.dc, 16, nc); + let tc = w.residual_block(&lv.dc, BlockCat::LumaDc, na, nb); dc_cbf |= u8::from(tc != 0); } for blk in 0..16 { @@ -1285,13 +1560,12 @@ fn finish_mb( }; let tc = if coded_block { let (na, nb) = luma_nz_pair(pic, nbr, bx, by); - let nc = nc_of(na, nb); - let (levels, max) = if m.is_i16 { - (&lv.luma[blk][..15], 15) + let (levels, cat) = if m.is_i16 { + (&lv.luma[blk][..15], BlockCat::LumaAc) } else { - (&lv.luma[blk][..16], 16) + (&lv.luma[blk][..16], BlockCat::Luma4x4) }; - write_residual_block(w, levels, max, nc) + w.residual_block(levels, cat, na, nb) } else { 0 }; @@ -1300,7 +1574,12 @@ fn finish_mb( // Chroma DC then chroma AC, in bitstream order. if lv.cbp_chroma != 0 { for comp in 0..2 { - let tc = write_residual_block(w, &lv.chroma_dc[comp][..4], 4, -1); + let tc = w.residual_block( + &lv.chroma_dc[comp][..4], + BlockCat::ChromaDc(comp as u8), + None, + None, + ); dc_cbf |= u8::from(tc != 0) << (1 + comp); } } @@ -1309,8 +1588,7 @@ fn finish_mb( let (cx, cy) = (cx0 + (blk & 1), cy0 + (blk >> 1)); let tc = if lv.cbp_chroma == 2 { let (na, nb) = chroma_nz_pair(pic, nbr, comp, cx, cy); - let nc = nc_of(na, nb); - write_residual_block(w, &lv.chroma[comp][blk][..15], 15, nc) + w.residual_block(&lv.chroma[comp][blk][..15], BlockCat::ChromaAc, na, nb) } else { 0 }; @@ -1319,14 +1597,3 @@ fn finish_mb( } pic.mb_dc_cbf[mb_addr] = dc_cbf; } - -/// nC from the two neighbouring non-zero counts (9.2.1). -#[inline] -fn nc_of(na: Option, nb: Option) -> i32 { - match (na, nb) { - (Some(a), Some(b)) => (i32::from(a) + i32::from(b) + 1) >> 1, - (Some(a), None) => i32::from(a), - (None, Some(b)) => i32::from(b), - (None, None) => 0, - } -} diff --git a/crates/ec-h264/src/enc/mod.rs b/crates/ec-h264/src/enc/mod.rs index 7efa7df7..7d571fc3 100644 --- a/crates/ec-h264/src/enc/mod.rs +++ b/crates/ec-h264/src/enc/mod.rs @@ -20,6 +20,8 @@ //! once over the whole picture, across slice boundaries exactly as a decoder //! runs it. No `unsafe`, no shared mutable state at all. +mod cabac_enc; +mod entropy; mod headers; mod mb; mod quant; @@ -35,6 +37,7 @@ use crate::decoder::deblock_picture; use crate::dpb::{Picture, SliceParams as DeblockParams}; use crate::transform::LevelScale4x4; +use entropy::EncEntropy; use headers::{SeqParams, SliceParams, write_pps, write_slice_header, write_sps}; use mb::{MbEnc, Source, encode_mb}; use rc::RateControl; @@ -59,6 +62,10 @@ pub struct EncoderConfig { pub bframes: u32, /// Speed/quality rung. pub preset: Preset, + /// Entropy coder: CABAC (Main profile) or CAVLC (Baseline). CABAC costs + /// roughly 12% fewer bits at the same reconstruction, which is why it is + /// the default; CAVLC is there for a decoder that cannot do better. + pub cabac: bool, /// Worker threads, which is also the number of slices per picture; 0 means /// as many as the machine has. pub threads: usize, @@ -77,6 +84,7 @@ impl EncoderConfig { gop_size: 250, bframes: 0, preset: Preset::Fast, + cabac: true, threads: 0, qp: 26, } @@ -184,10 +192,11 @@ impl Encoder { mb_h, timing, bitrate: cfg.bitrate, + cabac: cfg.cabac, }; let sps_rbsp = write_sps(&seq); let sps = Sps::parse(&sps_rbsp)?; - let pps_rbsp = write_pps(); + let pps_rbsp = write_pps(cfg.cabac); let threads = if cfg.threads == 0 { std::thread::available_parallelism().map_or(1, |n| n.get()) } else { @@ -311,6 +320,7 @@ impl Encoder { first_mb: (row0 * mb_w) as u32, rows: (row0, row1), qp, + cabac: cfg.cabac, frame_num, idr, idr_pic_id, @@ -434,6 +444,7 @@ struct BandJob<'a> { /// Macroblock rows `[start, end)`. rows: (usize, usize), qp: i32, + cabac: bool, frame_num: u32, idr: bool, idr_pic_id: u32, @@ -453,8 +464,16 @@ fn code_band(pic: &mut Picture, job: BandJob<'_>) -> Vec { idr: job.idr, idr_pic_id: job.idr_pic_id, qp: job.qp, + cabac: job.cabac, }, ); + // CABAC starts on a byte boundary after cabac_alignment_one_bit (7.3.4). + let mut w = if job.cabac { + // cabac_init_idc 0 is the initialisation column this encoder writes. + EncEntropy::cabac(w, job.qp, usize::from(job.slice_type != SliceType::I)) + } else { + EncEntropy::cavlc(w) + }; let header_bits = w.bit_len(); let mut e = MbEnc { src: job.src, @@ -465,8 +484,10 @@ fn code_band(pic: &mut Picture, job: BandJob<'_>) -> Vec { target_qp: job.qp, lambda: lambda_for(job.qp), preset: job.cfg.preset, - skip_run: 0, ls: LevelScale4x4::new(&[16; 16]), + mb_ctx: crate::entropy::MbCtx::default(), + skip_inc: 0, + qp_delta_inc: 0, }; let rows = job.rows.1 - job.rows.0; for (n, mb_y) in (job.rows.0..job.rows.1).enumerate() { @@ -480,17 +501,13 @@ fn code_band(pic: &mut Picture, job: BandJob<'_>) -> Vec { e.lambda = lambda_for(e.target_qp); } for mb_x in 0..mb_w { - encode_mb(pic, &mut e, &mut w, mb_y * mb_w + mb_x); + let addr = mb_y * mb_w + mb_x; + encode_mb(pic, &mut e, &mut w, addr); + // end_of_slice_flag, which CABAC codes after every macroblock. + w.end_of_slice(mb_y + 1 == job.rows.1 && mb_x + 1 == mb_w); } } - if job.slice_type == SliceType::P && e.skip_run > 0 { - // A slice that ends in skipped macroblocks says so with a final - // mb_skip_run; writing one when nothing was skipped would instead tell - // the decoder another macroblock follows (7.3.4). - w.write_ue(e.skip_run); - } - headers::trailing(&mut w); - w.into_bytes() + w.finish(job.slice_type == SliceType::P) } /// Lagrangian multiplier for mode decision in the SATD domain. diff --git a/crates/ec-h264/src/enc/rc.rs b/crates/ec-h264/src/enc/rc.rs index b0e247ab..fd475def 100644 --- a/crates/ec-h264/src/enc/rc.rs +++ b/crates/ec-h264/src/enc/rc.rs @@ -76,6 +76,11 @@ impl RateControl { qp = qp.clamp(self.last_qp[kind] - down, self.last_qp[kind] + up); // Leaky bucket: 1.5 QP per picture of debt, capped. qp += (self.buffer / (self.base.max(1.0) * 4.0) * 2.0).clamp(-2.0, 2.0); + // The quantiser floor is a measured choice, not a spec limit: below QP 10 + // this encoder spends large numbers of bits on differences a viewer + // cannot see, and on static content it spends them re-coding pictures + // that were already right. Asking for a bitrate that QP 10 cannot fill + // therefore returns a smaller file rather than a wasteful one. qp.round().clamp(10.0, 51.0) as i32 }