From 990d3ac834b35f8b8e1d8144d1bebee332a92f1e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 14 Aug 2026 12:43:41 +0300 Subject: [PATCH] feat(h265): integer transforms, quantiser and the CABAC coder The inverse transform and the dequantiser are the normative ones, so the encoder's reconstruction is what a decoder produces. Only the first 16 columns of the 32x32 matrix are typed in; the rest follow from the matrix's own symmetry, and tests check both the printed second half and orthogonality, because a mistyped column is the classic defect here. The CABAC coder can run in counting mode - identical context updates, no bytes kept - which is how rate-distortion decisions are priced at the rate they actually cost. A spec-derived decoder in the tests reads back what the encoder writes. --- crates/ec-h265/Cargo.toml | 11 + crates/ec-h265/src/cabac.rs | 597 ++++++++++++++++++++++++++++++++ crates/ec-h265/src/lib.rs | 7 + crates/ec-h265/src/residual.rs | 510 +++++++++++++++++++++++++++ crates/ec-h265/src/transform.rs | 454 ++++++++++++++++++++++++ 5 files changed, 1579 insertions(+) create mode 100644 crates/ec-h265/Cargo.toml create mode 100644 crates/ec-h265/src/cabac.rs create mode 100644 crates/ec-h265/src/lib.rs create mode 100644 crates/ec-h265/src/residual.rs create mode 100644 crates/ec-h265/src/transform.rs diff --git a/crates/ec-h265/Cargo.toml b/crates/ec-h265/Cargo.toml new file mode 100644 index 00000000..b1299a49 --- /dev/null +++ b/crates/ec-h265/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "ec-h265" +description = "Intra-only HEVC (H.265) encoder with wavefront-parallel encoding inside one call." +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true + +[dependencies] +ec-core.workspace = true +ec-h265-syntax.workspace = true diff --git a/crates/ec-h265/src/cabac.rs b/crates/ec-h265/src/cabac.rs new file mode 100644 index 00000000..a3e96322 --- /dev/null +++ b/crates/ec-h265/src/cabac.rs @@ -0,0 +1,597 @@ +//! The CABAC arithmetic coder and its context variables (clause 9.3). +//! +//! Two things live here that are usually separate: the encoder that writes bins, +//! and the same encoder in *counting* mode, which runs the identical context +//! updates but throws the bytes away and keeps the bit count. Rate-distortion +//! decisions are made against that count, so the rate a decision is judged by is +//! the rate it actually costs — no bit-estimate table to drift out of step with +//! the coder. + +/// Number of context variables this encoder keeps. +pub const NUM_CONTEXTS: usize = ctx::TOTAL; + +/// Context index layout: one named base per syntax element, I-slice only. +pub mod ctx { + /// `split_cu_flag`, 3 contexts. + pub const SPLIT_CU: usize = 0; + /// `part_mode`, 1 context in an I slice. + pub const PART_MODE: usize = SPLIT_CU + 3; + /// `prev_intra_luma_pred_flag`. + pub const PREV_INTRA_LUMA_PRED: usize = PART_MODE + 1; + /// `intra_chroma_pred_mode`. + pub const INTRA_CHROMA_PRED_MODE: usize = PREV_INTRA_LUMA_PRED + 1; + /// `split_transform_flag`, 3 contexts. + pub const SPLIT_TRANSFORM: usize = INTRA_CHROMA_PRED_MODE + 1; + /// `cbf_luma`, 2 contexts. + pub const CBF_LUMA: usize = SPLIT_TRANSFORM + 3; + /// `cbf_cb` / `cbf_cr`, 4 contexts. + pub const CBF_CHROMA: usize = CBF_LUMA + 2; + /// `last_sig_coeff_x_prefix`, 18 contexts. + pub const LAST_X: usize = CBF_CHROMA + 4; + /// `last_sig_coeff_y_prefix`, 18 contexts. + pub const LAST_Y: usize = LAST_X + 18; + /// `coded_sub_block_flag`, 4 contexts. + pub const CODED_SUB_BLOCK: usize = LAST_Y + 18; + /// `sig_coeff_flag`, 44 contexts (42 transform + 2 transform-skip). + pub const SIG_COEFF: usize = CODED_SUB_BLOCK + 4; + /// `coeff_abs_level_greater1_flag`, 24 contexts. + pub const GREATER1: usize = SIG_COEFF + 44; + /// `coeff_abs_level_greater2_flag`, 6 contexts. + pub const GREATER2: usize = GREATER1 + 24; + /// Total context count. + pub const TOTAL: usize = GREATER2 + 6; +} + +/// `initValue` for every context, initType 0 (I slices), Tables 9-7 to 9-31. +#[rustfmt::skip] +const INIT_VALUES: [u8; ctx::TOTAL] = [ + // split_cu_flag (Table 9-7) + 139, 141, 157, + // part_mode (Table 9-11) + 184, + // prev_intra_luma_pred_flag (Table 9-12) + 184, + // intra_chroma_pred_mode (Table 9-13) + 63, + // split_transform_flag (Table 9-20) + 153, 138, 138, + // cbf_luma (Table 9-21) + 111, 141, + // cbf_cb / cbf_cr (Table 9-22) + 94, 138, 182, 154, + // last_sig_coeff_x_prefix (Table 9-26) + 110, 110, 124, 125, 140, 153, 125, 127, 140, 109, 111, 143, 127, 111, 79, 108, 123, 63, + // last_sig_coeff_y_prefix (Table 9-27) + 110, 110, 124, 125, 140, 153, 125, 127, 140, 109, 111, 143, 127, 111, 79, 108, 123, 63, + // coded_sub_block_flag (Table 9-28) + 91, 171, 134, 141, + // sig_coeff_flag (Table 9-29), ctxIdx 0..41 then the two transform-skip ones + 111, 111, 125, 110, 110, 94, 124, 108, 124, 107, 125, 141, 179, 153, 125, 107, + 125, 141, 179, 153, 125, 107, 125, 141, 179, 153, 125, 140, 139, 182, 182, 152, + 136, 152, 136, 153, 136, 139, 111, 136, 139, 111, + 141, 111, + // coeff_abs_level_greater1_flag (Table 9-30) + 140, 92, 137, 138, 140, 152, 138, 139, 153, 74, 149, 92, 139, 107, 122, 152, + 140, 179, 166, 182, 140, 227, 122, 197, + // coeff_abs_level_greater2_flag (Table 9-31) + 138, 153, 136, 167, 152, 152, +]; + +/// `rangeTabLps[pStateIdx][qRangeIdx]` (Table 9-52). +#[rustfmt::skip] +const RANGE_TAB_LPS: [[u8; 4]; 64] = [ + [128, 176, 208, 240], [128, 167, 197, 227], [128, 158, 187, 216], [123, 150, 178, 205], + [116, 142, 169, 195], [111, 135, 160, 185], [105, 128, 152, 175], [100, 122, 144, 166], + [95, 116, 137, 158], [90, 110, 130, 150], [85, 104, 123, 142], [81, 99, 117, 135], + [77, 94, 111, 128], [73, 89, 105, 122], [69, 85, 100, 116], [66, 80, 95, 110], + [62, 76, 90, 104], [59, 72, 86, 99], [56, 69, 81, 94], [53, 65, 77, 89], + [51, 62, 73, 85], [48, 59, 69, 80], [46, 56, 66, 76], [43, 53, 63, 72], + [41, 50, 59, 69], [39, 48, 56, 65], [37, 45, 54, 62], [35, 43, 51, 59], + [33, 41, 48, 56], [32, 39, 46, 53], [30, 37, 43, 50], [29, 35, 41, 48], + [27, 33, 39, 45], [26, 31, 37, 43], [24, 30, 35, 41], [23, 28, 33, 39], + [22, 27, 32, 37], [21, 26, 30, 35], [20, 24, 29, 33], [19, 23, 27, 31], + [18, 22, 26, 30], [17, 21, 25, 28], [16, 20, 23, 27], [15, 19, 22, 25], + [14, 18, 21, 24], [14, 17, 20, 23], [13, 16, 19, 22], [12, 15, 18, 21], + [12, 14, 17, 20], [11, 14, 16, 19], [11, 13, 15, 18], [10, 12, 15, 17], + [10, 12, 14, 16], [9, 11, 13, 15], [9, 11, 12, 14], [8, 10, 12, 14], + [8, 9, 11, 13], [7, 9, 11, 12], [7, 9, 10, 12], [7, 8, 10, 11], + [6, 8, 9, 11], [6, 7, 9, 10], [6, 7, 8, 9], [2, 2, 2, 2], +]; + +/// `transIdxLps[pStateIdx]` (Table 9-53). +#[rustfmt::skip] +const TRANS_IDX_LPS: [u8; 64] = [ + 0, 0, 1, 2, 2, 4, 4, 5, 6, 7, 8, 9, 9, 11, 11, 12, + 13, 13, 15, 15, 16, 16, 18, 18, 19, 19, 21, 21, 22, 22, 23, 24, + 24, 25, 26, 26, 27, 27, 28, 29, 29, 30, 30, 30, 31, 32, 32, 33, + 33, 33, 34, 34, 35, 35, 35, 36, 36, 36, 37, 37, 37, 38, 38, 63, +]; + +/// `transIdxMps[pStateIdx]` (Table 9-53). +#[rustfmt::skip] +const TRANS_IDX_MPS: [u8; 64] = [ + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, + 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, + 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, + 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 62, 63, +]; + +/// The context variables, `pStateIdx << 1 | valMps` per entry. +#[derive(Clone, PartialEq, Eq, Debug)] +pub struct Contexts { + state: [u8; ctx::TOTAL], +} + +impl Contexts { + /// Initialise every context for an I slice at `slice_qp` (9.3.2.2). + pub fn new(slice_qp: i32) -> Contexts { + let qp = slice_qp.clamp(0, 51); + let mut state = [0u8; ctx::TOTAL]; + for (i, &init_value) in INIT_VALUES.iter().enumerate() { + let slope_idx = (init_value >> 4) as i32; + let offset_idx = (init_value & 15) as i32; + let m = slope_idx * 5 - 45; + let n = (offset_idx << 3) - 16; + let pre_ctx_state = (((m * qp) >> 4) + n).clamp(1, 126); + let val_mps = i32::from(pre_ctx_state > 63); + let p_state = if val_mps == 1 { + pre_ctx_state - 64 + } else { + 63 - pre_ctx_state + }; + state[i] = ((p_state as u8) << 1) | val_mps as u8; + } + Contexts { state } + } +} + +/// A rollback point for [`CabacEncoder`]. +/// +/// A plain [`CabacEncoder::snapshot`] rewinds by truncation, which is all a +/// trial-and-discard needs. A [`CabacEncoder::snapshot_since`] also carries the +/// bytes written since an earlier point, which is what a trial-and-*keep* needs: +/// a second trial overwrites the first one's bytes in place, so rewinding to a +/// length alone would leave the loser's bytes in the winner's positions. +#[derive(Clone)] +pub struct CabacState { + low: u32, + range: u32, + bits_outstanding: u32, + first_bit: bool, + bits: u64, + out_len: usize, + tail_base: usize, + tail: Vec, + partial: u8, + partial_bits: u8, + contexts: Contexts, +} + +/// The CABAC encoding engine (9.3.5). +#[derive(Clone)] +pub struct CabacEncoder { + low: u32, + range: u32, + bits_outstanding: u32, + first_bit: bool, + /// Bits written, counted whether or not they are kept. + bits: u64, + /// `None` while estimating a rate rather than producing a bitstream. + out: Option>, + /// While set, bins are coded and counted but no bytes are kept — what a + /// rate-distortion trial wants, since its bytes are about to be thrown away. + counting: bool, + partial: u8, + partial_bits: u8, + /// Context variables, public to the modules that index them by name. + pub contexts: Contexts, +} + +impl CabacEncoder { + /// A fresh engine writing into its own buffer. + pub fn new(contexts: Contexts) -> CabacEncoder { + CabacEncoder { + low: 0, + range: 510, + bits_outstanding: 0, + first_bit: true, + bits: 0, + out: Some(Vec::new()), + counting: false, + partial: 0, + partial_bits: 0, + contexts, + } + } + + /// An engine that counts bits and writes nothing — the rate half of every + /// rate-distortion decision. + pub fn counter(contexts: Contexts) -> CabacEncoder { + let mut enc = CabacEncoder::new(contexts); + enc.out = None; + enc + } + + /// Bits produced so far, including the ones a counting engine discards. + pub fn bit_count(&self) -> u64 { + self.bits + } + + /// Code bins without keeping their bytes; the counter still runs. + pub fn set_counting(&mut self, counting: bool) { + self.counting = counting; + } + + fn write_bit(&mut self, bit: u32) { + self.bits += 1; + if self.counting { + return; + } + if let Some(out) = &mut self.out { + self.partial = (self.partial << 1) | (bit as u8); + self.partial_bits += 1; + if self.partial_bits == 8 { + out.push(self.partial); + self.partial = 0; + self.partial_bits = 0; + } + } + } + + fn put_bit(&mut self, bit: u32) { + if self.first_bit { + self.first_bit = false; + } else { + self.write_bit(bit); + } + while self.bits_outstanding > 0 { + self.write_bit(1 - bit); + self.bits_outstanding -= 1; + } + } + + 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.bits_outstanding += 1; + } + self.range <<= 1; + self.low <<= 1; + } + } + + /// Take a snapshot the encoder can be rolled back to. + /// + /// This is what makes exact rate measurement affordable: a trial encode runs + /// into the real coder, its bits are read off the counter, and the coder is + /// put back. The cost is one 129-byte context copy, not a copy of the + /// substream written so far. + pub fn snapshot(&self) -> CabacState { + let out_len = self.out.as_ref().map_or(0, |o| o.len()); + CabacState { + low: self.low, + range: self.range, + bits_outstanding: self.bits_outstanding, + first_bit: self.first_bit, + bits: self.bits, + out_len, + tail_base: out_len, + tail: Vec::new(), + partial: self.partial, + partial_bits: self.partial_bits, + contexts: self.contexts.clone(), + } + } + + /// A snapshot that also carries the bytes written since `base`, so that + /// restoring it puts those bytes back after a competing trial overwrote + /// them. + pub fn snapshot_since(&self, base: &CabacState) -> CabacState { + let mut state = self.snapshot(); + state.tail_base = base.out_len; + if let Some(out) = &self.out { + state.tail = out[base.out_len..].to_vec(); + } + state + } + + /// Roll back to a snapshot. + pub fn restore(&mut self, state: &CabacState) { + self.low = state.low; + self.range = state.range; + self.bits_outstanding = state.bits_outstanding; + self.first_bit = state.first_bit; + self.bits = state.bits; + self.partial = state.partial; + self.partial_bits = state.partial_bits; + self.contexts.clone_from(&state.contexts); + if let Some(out) = &mut self.out { + out.truncate(state.tail_base); + out.extend_from_slice(&state.tail); + debug_assert_eq!(out.len(), state.out_len); + } + } + + /// Encode one context-coded bin (9.3.5.3). + #[inline] + pub fn encode_bin(&mut self, ctx_idx: usize, bin: u32) { + let state = self.contexts.state[ctx_idx]; + let p_state = (state >> 1) as usize; + let val_mps = u32::from(state & 1); + let q_range_idx = ((self.range >> 6) & 3) as usize; + let lps_range = u32::from(RANGE_TAB_LPS[p_state][q_range_idx]); + self.range -= lps_range; + if bin != val_mps { + self.low += self.range; + self.range = lps_range; + let new_mps = if p_state == 0 { 1 - val_mps } else { val_mps }; + self.contexts.state[ctx_idx] = (TRANS_IDX_LPS[p_state] << 1) | new_mps as u8; + } else { + self.contexts.state[ctx_idx] = (TRANS_IDX_MPS[p_state] << 1) | val_mps as u8; + } + self.renorm(); + } + + /// Encode one bypass bin (9.3.5.5). + #[inline] + pub fn encode_bypass(&mut self, bin: u32) { + self.low <<= 1; + if bin != 0 { + 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.bits_outstanding += 1; + } + } + + /// Encode `count` bypass bins from the low bits of `value`, most + /// significant first. + pub fn encode_bypass_bits(&mut self, value: u32, count: u32) { + for i in (0..count).rev() { + self.encode_bypass((value >> i) & 1); + } + } + + /// Encode a terminating bin: `end_of_slice_segment_flag` or + /// `end_of_subset_one_bit` (9.3.5.6). A one flushes the engine. + pub fn encode_terminate(&mut self, bin: u32) { + self.range -= 2; + if bin != 0 { + self.low += self.range; + self.flush(); + } else { + self.renorm(); + } + } + + fn flush(&mut self) { + self.range = 2; + self.renorm(); + self.put_bit((self.low >> 9) & 1); + // The last two bits, the low one always set: it is the + // rbsp_stop_one_bit or the alignment_bit_equal_to_one. + self.write_bit((self.low >> 8) & 1); + self.write_bit(1); + } + + /// Finish a substream: pad the last byte with zeros and hand back the bytes. + /// + /// Only valid after [`CabacEncoder::encode_terminate`] with a one bin, which + /// is where the flush happened. + pub fn finish(mut self) -> Vec { + let mut out = self.out.take().unwrap_or_default(); + if self.partial_bits > 0 { + out.push(self.partial << (8 - self.partial_bits)); + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn context_init_matches_the_worked_formula() { + // initValue 154 is the "no slope" entry: m = 0, n = 64, so every QP + // lands on preCtxState 64, valMps 1, pStateIdx 0. + let init_value: u8 = 154; + let m = (init_value >> 4) as i32 * 5 - 45; + let n = (((init_value & 15) as i32) << 3) - 16; + assert_eq!((m, n), (0, 64)); + // And a real one: split_cu_flag ctx 0 (139) at QP 30. + let ctxs = Contexts::new(30); + let m = (139u8 >> 4) as i32 * 5 - 45; + let n = (((139u8 & 15) as i32) << 3) - 16; + let pre = (((m * 30) >> 4) + n).clamp(1, 126); + let expect = if pre > 63 { + (((pre - 64) as u8) << 1) | 1 + } else { + ((63 - pre) as u8) << 1 + }; + assert_eq!(ctxs.state[ctx::SPLIT_CU], expect); + } + + #[test] + fn state_tables_are_consistent() { + // Every LPS transition moves towards the uncertain end, every MPS + // transition towards the certain one, and state 63 is absorbing. + for s in 0..64usize { + assert!(TRANS_IDX_LPS[s] as usize <= s); + assert!(TRANS_IDX_MPS[s] as usize >= s); + assert!(TRANS_IDX_MPS[s] < 64 && TRANS_IDX_LPS[s] < 64); + // rangeTabLps shrinks as the state gets more certain. + if s > 0 { + for q in 0..4 { + assert!(RANGE_TAB_LPS[s][q] <= RANGE_TAB_LPS[s - 1][q]); + } + } + } + assert_eq!(TRANS_IDX_LPS[63], 63); + assert_eq!(TRANS_IDX_MPS[63], 63); + } + + #[test] + fn counting_engine_tracks_the_writing_engine() { + let mut writer = CabacEncoder::new(Contexts::new(30)); + let mut counter = CabacEncoder::counter(Contexts::new(30)); + for i in 0..500u32 { + let bin = (i * 7 % 5) & 1; + writer.encode_bin(ctx::SIG_COEFF + (i as usize % 44), bin); + counter.encode_bin(ctx::SIG_COEFF + (i as usize % 44), bin); + writer.encode_bypass(bin); + counter.encode_bypass(bin); + } + assert_eq!(writer.bit_count(), counter.bit_count()); + assert_eq!(writer.contexts, counter.contexts); + } + + /// The decoding engine of 9.3.4.3, written from the normative flowcharts, + /// as an oracle for the encoder above. + struct RefDecoder<'a> { + data: &'a [u8], + bit: usize, + range: u32, + offset: u32, + contexts: Contexts, + } + + impl<'a> RefDecoder<'a> { + fn new(data: &'a [u8], contexts: Contexts) -> RefDecoder<'a> { + let mut d = RefDecoder { + data, + bit: 0, + range: 510, + offset: 0, + contexts, + }; + for _ in 0..9 { + d.offset = (d.offset << 1) | d.read_bit(); + } + d + } + + fn read_bit(&mut self) -> u32 { + let byte = self.data.get(self.bit / 8).copied().unwrap_or(0); + let bit = u32::from((byte >> (7 - (self.bit % 8))) & 1); + self.bit += 1; + bit + } + + fn decode_bin(&mut self, ctx_idx: usize) -> u32 { + let state = self.contexts.state[ctx_idx]; + let p_state = (state >> 1) as usize; + let val_mps = u32::from(state & 1); + let q = ((self.range >> 6) & 3) as usize; + let lps = u32::from(RANGE_TAB_LPS[p_state][q]); + self.range -= lps; + let bin; + if self.offset >= self.range { + bin = 1 - val_mps; + self.offset -= self.range; + self.range = lps; + let new_mps = if p_state == 0 { 1 - val_mps } else { val_mps }; + self.contexts.state[ctx_idx] = (TRANS_IDX_LPS[p_state] << 1) | new_mps as u8; + } else { + bin = val_mps; + self.contexts.state[ctx_idx] = (TRANS_IDX_MPS[p_state] << 1) | val_mps as u8; + } + while self.range < 256 { + self.range <<= 1; + self.offset = (self.offset << 1) | self.read_bit(); + } + bin + } + + fn decode_bypass(&mut self) -> u32 { + self.offset = (self.offset << 1) | self.read_bit(); + if self.offset >= self.range { + self.offset -= self.range; + 1 + } else { + 0 + } + } + + fn decode_terminate(&mut self) -> u32 { + self.range -= 2; + if self.offset >= self.range { + 1 + } else { + while self.range < 256 { + self.range <<= 1; + self.offset = (self.offset << 1) | self.read_bit(); + } + 0 + } + } + } + + #[test] + fn the_spec_decoder_reads_back_what_the_encoder_wrote() { + // A long mixed sequence: context bins across many contexts, bypass bins, + // and the terminating bin that flushes. If the engine's carry handling + // or state transitions were wrong, this diverges within a few bins — + // which is exactly the failure a real decoder shows as a broken picture. + let mut plan: Vec<(usize, u32, u8)> = Vec::new(); // (ctx or 0, bin, kind) + let mut seed = 12345u32; + let mut rand = move || { + seed = seed.wrapping_mul(1103515245).wrapping_add(12345); + (seed >> 16) & 0x7fff + }; + for i in 0..3000 { + let kind = if i % 7 == 3 { 1 } else { 0 }; + let ctx = (rand() as usize) % ctx::TOTAL; + let bin = if i % 5 == 0 { 1 } else { rand() & 1 }; + plan.push((ctx, bin, kind)); + } + let mut enc = CabacEncoder::new(Contexts::new(32)); + for &(ctx_idx, bin, kind) in &plan { + if kind == 0 { + enc.encode_bin(ctx_idx, bin); + } else { + enc.encode_bypass(bin); + } + } + enc.encode_terminate(1); + let bytes = enc.finish(); + + let mut dec = RefDecoder::new(&bytes, Contexts::new(32)); + for (i, &(ctx_idx, bin, kind)) in plan.iter().enumerate() { + let got = if kind == 0 { + dec.decode_bin(ctx_idx) + } else { + dec.decode_bypass() + }; + assert_eq!(got, bin, "bin {i} (ctx {ctx_idx}, kind {kind})"); + } + assert_eq!(dec.decode_terminate(), 1, "terminating bin"); + } + + #[test] + fn a_skewed_symbol_stream_compresses() { + // 4000 zeros through one adapting context must cost far less than 4000 + // bits — the property that makes the engine an arithmetic coder at all. + let mut enc = CabacEncoder::new(Contexts::new(30)); + for _ in 0..4000 { + enc.encode_bin(ctx::SIG_COEFF, 0); + } + enc.encode_terminate(1); + let bits = enc.bit_count(); + let bytes = enc.finish(); + assert!(bits < 400, "{bits} bits for 4000 skewed bins"); + assert!(!bytes.is_empty()); + } +} diff --git a/crates/ec-h265/src/lib.rs b/crates/ec-h265/src/lib.rs new file mode 100644 index 00000000..272aaecf --- /dev/null +++ b/crates/ec-h265/src/lib.rs @@ -0,0 +1,7 @@ +//! Intra-only HEVC encoder. +#![forbid(unsafe_code)] +#![warn(missing_docs)] + +pub mod cabac; +pub mod residual; +pub mod transform; diff --git a/crates/ec-h265/src/residual.rs b/crates/ec-h265/src/residual.rs new file mode 100644 index 00000000..a2c77c5d --- /dev/null +++ b/crates/ec-h265/src/residual.rs @@ -0,0 +1,510 @@ +//! `residual_coding()` (7.3.8.11) and the scan orders it walks (6.5.3 - 6.5.5). + +use crate::cabac::{CabacEncoder, ctx}; +use std::sync::LazyLock; + +/// Scan orders: `SCANS[log2BlockSize][scanIdx][pos] = (x, y)`. +/// +/// Built once rather than typed in — the diagonal scan is four lines of the +/// spec's own pseudo-code, and generating it cannot go wrong the way a +/// transcribed 64-entry table can. +static SCANS: LazyLock<[[Vec<(u8, u8)>; 3]; 4]> = LazyLock::new(|| { + std::array::from_fn(|log2_size| { + let size = 1usize << log2_size; + std::array::from_fn(|scan_idx| match scan_idx { + 1 => (0..size * size) + .map(|i| ((i % size) as u8, (i / size) as u8)) + .collect(), + 2 => (0..size * size) + .map(|i| ((i / size) as u8, (i % size) as u8)) + .collect(), + _ => { + // 6.5.3, up-right diagonal. + let mut out = Vec::with_capacity(size * size); + let (mut x, mut y) = (0usize, 0usize); + loop { + loop { + if x < size && y < size { + out.push((x as u8, y as u8)); + } + if y == 0 { + break; + } + y -= 1; + x += 1; + } + y = x + 1; + x = 0; + if out.len() >= size * size { + break; + } + } + out + } + }) + }) +}); + +/// `ctxIdxMap[i]` for 4x4 blocks (Table 9-50); index 15 is never queried +/// because that position is always the last significant one. +const CTX_IDX_MAP: [usize; 16] = [0, 1, 4, 5, 2, 3, 4, 5, 6, 6, 8, 8, 7, 7, 8, 8]; + +/// The scan order for one block size and scan index. +pub fn scan(log2_size: u32, scan_idx: usize) -> &'static [(u8, u8)] { + &SCANS[log2_size as usize][scan_idx] +} + +/// Truncated-Rice + EGk binarization of `coeff_abs_level_remaining` (9.3.3.11). +fn encode_remaining(enc: &mut CabacEncoder, value: u32, rice: u32) { + let c_max = 4 << rice; + if value < c_max { + let prefix = value >> rice; + for _ in 0..prefix { + enc.encode_bypass(1); + } + enc.encode_bypass(0); + if rice > 0 { + enc.encode_bypass_bits(value & ((1 << rice) - 1), rice); + } + } else { + for _ in 0..4 { + enc.encode_bypass(1); + } + let mut rest = value - c_max; + let mut k = rice + 1; + loop { + if rest >= (1 << k) { + enc.encode_bypass(1); + rest -= 1 << k; + k += 1; + } else { + enc.encode_bypass(0); + enc.encode_bypass_bits(rest, k); + break; + } + } + } +} + +/// `last_sig_coeff_*_prefix` for a coordinate, and its suffix bit count. +fn last_prefix(coord: u32) -> (u32, u32) { + if coord < 4 { + (coord, 0) + } else { + let log2 = 31 - coord.leading_zeros(); + let prefix = 2 * log2 + ((coord >> (log2 - 1)) & 1); + (prefix, (prefix >> 1) - 1) + } +} + +/// Encode one transform block's levels. +/// +/// `levels` is row-major `n x n` with `levels[y * n + x]`, `c_idx` is 0 for luma +/// and 1/2 for chroma, and at least one level must be non-zero (the caller codes +/// a `cbf` of zero instead). +pub fn encode_residual( + enc: &mut CabacEncoder, + levels: &[i32], + log2_size: u32, + c_idx: usize, + scan_idx: usize, +) { + let n = 1usize << log2_size; + let sub_wide = n >> 2; + let sub_scan = scan(log2_size - 2, scan_idx); + let pos_scan = scan(2, scan_idx); + let chroma = c_idx > 0; + + // The last significant coefficient in scan order. + let mut last_sub = 0usize; + let mut last_pos = 0usize; + 'outer: for i in (0..sub_scan.len()).rev() { + let (xs, ys) = sub_scan[i]; + for p in (0..16).rev() { + let (xp, yp) = pos_scan[p]; + let xc = (xs as usize) * 4 + xp as usize; + let yc = (ys as usize) * 4 + yp as usize; + if levels[yc * n + xc] != 0 { + last_sub = i; + last_pos = p; + break 'outer; + } + } + } + let (last_xs, last_ys) = sub_scan[last_sub]; + let (last_xp, last_yp) = pos_scan[last_pos]; + let mut last_x = (last_xs as u32) * 4 + last_xp as u32; + let mut last_y = (last_ys as u32) * 4 + last_yp as u32; + if scan_idx == 2 { + std::mem::swap(&mut last_x, &mut last_y); + } + + // last_sig_coeff_x/y prefix and suffix (9.3.4.2.3 for the contexts). + let (offset, shift) = if c_idx == 0 { + ( + 3 * (log2_size - 2) + ((log2_size - 1) >> 2), + (log2_size + 1) >> 2, + ) + } else { + (15, log2_size - 2) + }; + let c_max = (log2_size << 1) - 1; + let (x_prefix, x_suffix_bits) = last_prefix(last_x); + let (y_prefix, y_suffix_bits) = last_prefix(last_y); + for (prefix, base) in [(x_prefix, ctx::LAST_X), (y_prefix, ctx::LAST_Y)] { + for bin in 0..prefix { + enc.encode_bin(base + ((bin >> shift) + offset) as usize, 1); + } + if prefix < c_max { + enc.encode_bin(base + ((prefix >> shift) + offset) as usize, 0); + } + } + if x_suffix_bits > 0 { + let base = (1 << x_suffix_bits) * (2 + (x_prefix & 1)); + enc.encode_bypass_bits(last_x - base, x_suffix_bits); + } + if y_suffix_bits > 0 { + let base = (1 << y_suffix_bits) * (2 + (y_prefix & 1)); + enc.encode_bypass_bits(last_y - base, y_suffix_bits); + } + + let mut csbf = [false; 64]; + csbf[last_ys as usize * sub_wide + last_xs as usize] = true; + // The DC sub-block is always coded (7.4.9.11 inference). + let (dc_xs, dc_ys) = sub_scan[0]; + csbf[dc_ys as usize * sub_wide + dc_xs as usize] = true; + // Mark every sub-block that holds a level, so the neighbour contexts below + // see the same flags the decoder will. + for &(xs, ys) in sub_scan.iter().take(last_sub) { + let (xs, ys) = (xs as usize, ys as usize); + let mut any = false; + for row in 0..4 { + let base = (ys * 4 + row) * n + xs * 4; + if levels[base..base + 4].iter().any(|&v| v != 0) { + any = true; + break; + } + } + if any { + csbf[ys * sub_wide + xs] = true; + } + } + + let mut greater1_ctx = 1u32; + for i in (0..=last_sub).rev() { + let (xs, ys) = sub_scan[i]; + let (xs, ys) = (xs as usize, ys as usize); + let coded = csbf[ys * sub_wide + xs]; + let mut infer_dc_sig = false; + if i < last_sub && i > 0 { + let mut csbf_ctx = 0; + if xs < sub_wide - 1 && csbf[ys * sub_wide + xs + 1] { + csbf_ctx += 1; + } + if ys < sub_wide - 1 && csbf[(ys + 1) * sub_wide + xs] { + csbf_ctx += 1; + } + let inc = if chroma { + 2 + csbf_ctx.min(1) + } else { + csbf_ctx.min(1) + }; + enc.encode_bin(ctx::CODED_SUB_BLOCK + inc, u32::from(coded)); + infer_dc_sig = true; + } + if !coded { + continue; + } + + // sig_coeff_flag over the sub-block, high scan position first. + let mut significant = [false; 16]; + if i == last_sub { + significant[last_pos] = true; + } + let first = if i == last_sub { last_pos as i32 - 1 } else { 15 }; + let mut scan_pos = first; + while scan_pos >= 0 { + let p = scan_pos as usize; + scan_pos -= 1; + let (xp, yp) = pos_scan[p]; + let xc = xs * 4 + xp as usize; + let yc = ys * 4 + yp as usize; + let sig = levels[yc * n + xc] != 0; + if p > 0 || !infer_dc_sig { + let inc = sig_ctx_inc(xc, yc, xs, ys, sub_wide, &csbf, log2_size, c_idx, scan_idx); + enc.encode_bin(ctx::SIG_COEFF + inc, u32::from(sig)); + } + significant[p] = sig; + if sig { + infer_dc_sig = false; + } + } + if infer_dc_sig { + // The flag was not coded because it is inferred to be one. + significant[0] = true; + } + + let mut order = [0usize; 16]; + let mut order_len = 0; + for p in (0..16).rev() { + if significant[p] { + order[order_len] = p; + order_len += 1; + } + } + let order = &order[..order_len]; + if order.is_empty() { + continue; + } + + // coeff_abs_level_greater1_flag, first eight only (9.3.4.2.6). + let mut ctx_set = if i == 0 || chroma { 0 } else { 2 }; + if greater1_ctx == 0 { + ctx_set += 1; + } + greater1_ctx = 1; + let mut last_greater1 = None; + let mut greater1 = [false; 16]; + for &p in order.iter().take(8) { + let (xp, yp) = pos_scan[p]; + let level = levels[(ys * 4 + yp as usize) * n + xs * 4 + xp as usize].unsigned_abs(); + let flag = level > 1; + let inc = ctx_set * 4 + greater1_ctx.min(3) + if chroma { 16 } else { 0 }; + enc.encode_bin(ctx::GREATER1 + inc as usize, u32::from(flag)); + greater1[p] = flag; + if flag { + if last_greater1.is_none() { + last_greater1 = Some(p); + } + greater1_ctx = 0; + } else if greater1_ctx > 0 { + greater1_ctx += 1; + } + } + + // coeff_abs_level_greater2_flag for the first greater-than-one level. + let mut greater2 = false; + if let Some(p) = last_greater1 { + let (xp, yp) = pos_scan[p]; + let level = levels[(ys * 4 + yp as usize) * n + xs * 4 + xp as usize].unsigned_abs(); + greater2 = level > 2; + let inc = ctx_set + if chroma { 4 } else { 0 }; + enc.encode_bin(ctx::GREATER2 + inc as usize, u32::from(greater2)); + } + + // Signs, then the remaining magnitudes. Sign data hiding is off, so + // every significant coefficient carries its own sign bit. + for &p in order { + let (xp, yp) = pos_scan[p]; + let level = levels[(ys * 4 + yp as usize) * n + xs * 4 + xp as usize]; + enc.encode_bypass(u32::from(level < 0)); + } + let mut rice = 0u32; + let mut num_sig = 0usize; + for &p in order { + let (xp, yp) = pos_scan[p]; + let level = levels[(ys * 4 + yp as usize) * n + xs * 4 + xp as usize].unsigned_abs(); + let coded_greater1 = num_sig < 8; + let base_level = 1 + + u32::from(coded_greater1 && greater1[p]) + + u32::from(last_greater1 == Some(p) && greater2); + let threshold = if num_sig < 8 { + if last_greater1 == Some(p) { 3 } else { 2 } + } else { + 1 + }; + if base_level == threshold { + let remaining = level - base_level; + encode_remaining(enc, remaining, rice); + rice = (rice + u32::from(level > (3 << rice))).min(4); + } + num_sig += 1; + } + } +} + +/// `ctxInc` for `sig_coeff_flag` (9.3.4.2.5). +#[allow(clippy::too_many_arguments)] +fn sig_ctx_inc( + xc: usize, + yc: usize, + xs: usize, + ys: usize, + sub_wide: usize, + csbf: &[bool], + log2_size: u32, + c_idx: usize, + scan_idx: usize, +) -> usize { + let mut sig_ctx; + if log2_size == 2 { + sig_ctx = CTX_IDX_MAP[(yc << 2) + xc]; + } else if xc + yc == 0 { + sig_ctx = 0; + } else { + let mut prev_csbf = 0usize; + if xs < sub_wide - 1 && csbf[ys * sub_wide + xs + 1] { + prev_csbf += 1; + } + if ys < sub_wide - 1 && csbf[(ys + 1) * sub_wide + xs] { + prev_csbf += 2; + } + let (xp, yp) = (xc & 3, yc & 3); + sig_ctx = match prev_csbf { + 0 => { + if xp + yp == 0 { + 2 + } else if xp + yp < 3 { + 1 + } else { + 0 + } + } + 1 => { + if yp == 0 { + 2 + } else if yp == 1 { + 1 + } else { + 0 + } + } + 2 => { + if xp == 0 { + 2 + } else if xp == 1 { + 1 + } else { + 0 + } + } + _ => 2, + }; + if c_idx == 0 { + if xs + ys > 0 { + sig_ctx += 3; + } + if log2_size == 3 { + sig_ctx += if scan_idx == 0 { 9 } else { 15 }; + } else { + sig_ctx += 21; + } + } else if log2_size == 3 { + sig_ctx += 9; + } else { + sig_ctx += 12; + } + } + if c_idx == 0 { sig_ctx } else { 27 + sig_ctx } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::cabac::Contexts; + + #[test] + fn diagonal_scan_matches_the_spec_walk() { + // 4x4 up-right diagonal, from 6.5.3. + let expect: Vec<(u8, u8)> = vec![ + (0, 0), + (0, 1), + (1, 0), + (0, 2), + (1, 1), + (2, 0), + (0, 3), + (1, 2), + (2, 1), + (3, 0), + (1, 3), + (2, 2), + (3, 1), + (2, 3), + (3, 2), + (3, 3), + ]; + assert_eq!(scan(2, 0), &expect[..]); + // Horizontal and vertical are the plain raster orders. + assert_eq!(scan(2, 1)[..4], [(0, 0), (1, 0), (2, 0), (3, 0)]); + assert_eq!(scan(2, 2)[..4], [(0, 0), (0, 1), (0, 2), (0, 3)]); + // Every size is a permutation of its block. + for log2 in 0..4u32 { + for idx in 0..3 { + let s = scan(log2, idx); + let size = 1usize << log2; + assert_eq!(s.len(), size * size); + let mut seen = vec![false; size * size]; + for &(x, y) in s { + let slot = y as usize * size + x as usize; + assert!(!seen[slot]); + seen[slot] = true; + } + } + } + } + + #[test] + fn last_position_binarization_inverts_the_spec_formula() { + for coord in 0..32u32 { + let (prefix, suffix_bits) = last_prefix(coord); + let decoded = if suffix_bits == 0 { + prefix + } else { + let base = (1 << ((prefix >> 1) - 1)) * (2 + (prefix & 1)); + let suffix = coord - base; + assert!(suffix < (1 << suffix_bits), "coord {coord}"); + base + suffix + }; + assert_eq!(decoded, coord); + assert!(prefix <= 9, "coord {coord} prefix {prefix}"); + } + } + + #[test] + fn residual_coding_costs_less_for_sparser_blocks() { + // Not a bit-exactness check — that is the ffmpeg conformance test — but + // the invariant that makes rate-distortion decisions meaningful: fewer + // and smaller levels must cost fewer bits. + let mut sparse = vec![0i32; 64]; + sparse[0] = 1; + let mut dense = vec![0i32; 64]; + for (i, v) in dense.iter_mut().enumerate() { + *v = ((i % 7) as i32) - 3; + } + let mut costs = Vec::new(); + for levels in [&sparse, &dense] { + let mut enc = CabacEncoder::counter(Contexts::new(30)); + encode_residual(&mut enc, levels, 3, 0, 0); + costs.push(enc.bit_count()); + } + assert!(costs[0] < costs[1], "{costs:?}"); + assert!(costs[0] > 0); + } + + #[test] + fn every_block_size_and_scan_codes_without_panicking() { + for log2 in 2..=5u32 { + let n = 1usize << log2; + for scan_idx in 0..3 { + for c_idx in [0usize, 1] { + let mut levels = vec![0i32; n * n]; + for (i, v) in levels.iter_mut().enumerate() { + *v = match i % 11 { + 0 => 0, + 1 => 1, + 2 => -2, + 3 => 3, + 4 => -17, + 5 => 400, + _ => 0, + }; + } + let mut enc = CabacEncoder::counter(Contexts::new(27)); + encode_residual(&mut enc, &levels, log2, c_idx, scan_idx); + assert!(enc.bit_count() > 0); + } + } + } + } +} diff --git a/crates/ec-h265/src/transform.rs b/crates/ec-h265/src/transform.rs new file mode 100644 index 00000000..b185e32a --- /dev/null +++ b/crates/ec-h265/src/transform.rs @@ -0,0 +1,454 @@ +//! The integer transforms and the quantizer (8.6.2 - 8.6.4). +//! +//! The *inverse* path here is normative: a decoder does exactly this, so the +//! encoder's reconstruction runs the same code and is bit-identical to what any +//! conformant decoder produces. The forward path and the quantizer are the +//! encoder's own choice; what makes them correct is that they invert the +//! normative path — which is what [`tests::round_trip_recovers_flat_blocks`] +//! and the ffmpeg conformance test in `tests/` check. +//! +//! One transcription safeguard is worth naming: only the first 16 columns of the +//! 32x32 matrix are typed in. The rest follow from `M[m][31 - n] = (-1)^m M[m][n]`, +//! which the spec's own second half satisfies, and a test asserts that half back +//! entry by entry. A wrong column is the classic defect in this kind of table +//! (it cost this family a week in H.264), so the table is checked against +//! orthogonality as well as against the printed values. + +/// Columns 0..15 of `transMatrix` (8-319), rows 0..31. +/// +/// The size-N transform uses rows `k * (32 / N)` and columns `0..N`. +#[rustfmt::skip] +const TRANS_MATRIX_HALF: [[i32; 16]; 32] = [ + [64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64], + [90, 90, 88, 85, 82, 78, 73, 67, 61, 54, 46, 38, 31, 22, 13, 4], + [90, 87, 80, 70, 57, 43, 25, 9, -9, -25, -43, -57, -70, -80, -87, -90], + [90, 82, 67, 46, 22, -4, -31, -54, -73, -85, -90, -88, -78, -61, -38, -13], + [89, 75, 50, 18, -18, -50, -75, -89, -89, -75, -50, -18, 18, 50, 75, 89], + [88, 67, 31, -13, -54, -82, -90, -78, -46, -4, 38, 73, 90, 85, 61, 22], + [87, 57, 9, -43, -80, -90, -70, -25, 25, 70, 90, 80, 43, -9, -57, -87], + [85, 46, -13, -67, -90, -73, -22, 38, 82, 88, 54, -4, -61, -90, -78, -31], + [83, 36, -36, -83, -83, -36, 36, 83, 83, 36, -36, -83, -83, -36, 36, 83], + [82, 22, -54, -90, -61, 13, 78, 85, 31, -46, -90, -67, 4, 73, 88, 38], + [80, 9, -70, -87, -25, 57, 90, 43, -43, -90, -57, 25, 87, 70, -9, -80], + [78, -4, -82, -73, 13, 85, 67, -22, -88, -61, 31, 90, 54, -38, -90, -46], + [75, -18, -89, -50, 50, 89, 18, -75, -75, 18, 89, 50, -50, -89, -18, 75], + [73, -31, -90, -22, 78, 67, -38, -90, -13, 82, 61, -46, -88, -4, 85, 54], + [70, -43, -87, 9, 90, 25, -80, -57, 57, 80, -25, -90, -9, 87, 43, -70], + [67, -54, -78, 38, 85, -22, -90, 4, 90, 13, -88, -31, 82, 46, -73, -61], + [64, -64, -64, 64, 64, -64, -64, 64, 64, -64, -64, 64, 64, -64, -64, 64], + [61, -73, -46, 82, 31, -88, -13, 90, -4, -90, 22, 85, -38, -78, 54, 67], + [57, -80, -25, 90, -9, -87, 43, 70, -70, -43, 87, 9, -90, 25, 80, -57], + [54, -85, -4, 88, -46, -61, 82, 13, -90, 38, 67, -78, -22, 90, -31, -73], + [50, -89, 18, 75, -75, -18, 89, -50, -50, 89, -18, -75, 75, 18, -89, 50], + [46, -90, 38, 54, -90, 31, 61, -88, 22, 67, -85, 13, 73, -82, 4, 78], + [43, -90, 57, 25, -87, 70, 9, -80, 80, -9, -70, 87, -25, -57, 90, -43], + [38, -88, 73, -4, -67, 90, -46, -31, 85, -78, 13, 61, -90, 54, 22, -82], + [36, -83, 83, -36, -36, 83, -83, 36, 36, -83, 83, -36, -36, 83, -83, 36], + [31, -78, 90, -61, 4, 54, -88, 82, -38, -22, 73, -90, 67, -13, -46, 85], + [25, -70, 90, -80, 43, 9, -57, 87, -87, 57, -9, -43, 80, -90, 70, -25], + [22, -61, 85, -90, 73, -38, -4, 46, -78, 90, -82, 54, -13, -31, 67, -88], + [18, -50, 75, -89, 89, -75, 50, -18, -18, 50, -75, 89, -89, 75, -50, 18], + [13, -38, 61, -78, 88, -90, 85, -73, 54, -31, 4, 22, -46, 67, -82, 90], + [9, -25, 43, -57, 70, -80, 87, -90, 90, -87, 80, -70, 57, -43, 25, -9], + [4, -13, 22, -31, 38, -46, 54, -61, 67, -73, 78, -82, 85, -88, 90, -90], +]; + +/// `transMatrix` for `trType = 1`: the 4x4 DST used for luma intra 4x4 blocks +/// (8-316). +#[rustfmt::skip] +const DST_MATRIX: [[i32; 4]; 4] = [ + [29, 55, 74, 84], + [74, 74, 0, -74], + [84, -29, -74, 55], + [55, -84, 74, -29], +]; + +/// `M[m][n]` of the 32-point matrix, mirrored out of the stored half. +#[inline] +fn m32(row: usize, col: usize) -> i32 { + if col < 16 { + TRANS_MATRIX_HALF[row][col] + } else if row % 2 == 0 { + TRANS_MATRIX_HALF[row][31 - col] + } else { + -TRANS_MATRIX_HALF[row][31 - col] + } +} + +/// `levelScale[k]`, 8.6.3. +const LEVEL_SCALE: [i32; 6] = [40, 45, 51, 57, 64, 72]; + +/// The quantizer's reciprocal of [`LEVEL_SCALE`], `round(2^20 / levelScale)`. +/// +/// Derived rather than transcribed: the product of the two is 2^20 to within a +/// count, which is the whole design of the HEVC quantizer, and +/// [`tests::quant_scale_is_the_reciprocal`] holds it to that. +const QUANT_SCALE: [i32; 6] = [26_214, 23_302, 20_560, 18_396, 16_384, 14_564]; + +/// Largest and smallest coefficient a Main-profile decoder may hold (`CoeffMin`, +/// `CoeffMax` for `extended_precision_processing_flag = 0`). +const COEFF_MIN: i32 = -32_768; +const COEFF_MAX: i32 = 32_767; + +/// One-dimensional inverse transform, `y[i] = sum_j M[j][i] * x[j]`. +/// +/// Split even/odd once per level: the even rows of the size-N matrix *are* the +/// size-N/2 matrix, so the recursion costs ~N^2/3 multiplies where the plain +/// product costs N^2. +fn inverse_1d(n: usize, src: &[i32], dst: &mut [i32]) { + if n == 1 { + dst[0] = 64 * src[0]; + return; + } + let half = n / 2; + let stride = 32 / n; + let mut even_src = [0i32; 16]; + for j in 0..half { + even_src[j] = src[2 * j]; + } + let mut even = [0i32; 16]; + inverse_1d(half, &even_src[..half], &mut even[..half]); + for x in 0..half { + let mut odd = 0i32; + for j in 0..half { + odd += m32((2 * j + 1) * stride, x) * src[2 * j + 1]; + } + dst[x] = even[x] + odd; + dst[n - 1 - x] = even[x] - odd; + } +} + +/// One-dimensional forward transform, `c[k] = sum_x M[k][x] * src[x]`. +fn forward_1d(n: usize, src: &[i32], dst: &mut [i32]) { + if n == 1 { + dst[0] = 64 * src[0]; + return; + } + let half = n / 2; + let stride = 32 / n; + let mut sums = [0i32; 16]; + let mut diffs = [0i32; 16]; + for x in 0..half { + sums[x] = src[x] + src[n - 1 - x]; + diffs[x] = src[x] - src[n - 1 - x]; + } + let mut even = [0i32; 16]; + forward_1d(half, &sums[..half], &mut even[..half]); + for j in 0..half { + dst[2 * j] = even[j]; + let mut odd = 0i32; + for x in 0..half { + odd += m32((2 * j + 1) * stride, x) * diffs[x]; + } + dst[2 * j + 1] = odd; + } +} + +/// Forward 4x4 DST (the inverse of the normative `trType = 1` transform). +fn forward_dst4(src: &[i32; 4], dst: &mut [i32; 4]) { + for (k, out) in dst.iter_mut().enumerate() { + *out = (0..4).map(|x| DST_MATRIX[k][x] * src[x]).sum(); + } +} + +/// Inverse 4x4 DST, `y[i] = sum_j M[j][i] * x[j]` (8-315). +fn inverse_dst4(src: &[i32; 4], dst: &mut [i32; 4]) { + for (i, out) in dst.iter_mut().enumerate() { + *out = (0..4).map(|j| DST_MATRIX[j][i] * src[j]).sum(); + } +} + +/// True when a block takes the DST: luma, intra, 4x4 (8.6.4.1). +pub fn uses_dst(size: usize, is_luma: bool) -> bool { + is_luma && size == 4 +} + +/// Forward transform of an `n x n` residual block into coefficients. +/// +/// `residual` and `coeffs` are both row-major `n x n`; `coeffs[v * n + k]` is +/// vertical frequency `v`, horizontal frequency `k`, which is the order the +/// scans and the residual coder index. +pub fn forward_transform(residual: &[i32], coeffs: &mut [i32], n: usize, dst_type: bool) { + let log2n = n.trailing_zeros() as i32; + // 8-bit input: shift1 = log2N + bitDepth - 9, shift2 = log2N + 6. Together + // they leave the DC at 128 x the mean residual whatever the block size, + // which is what the dequantiser's shift assumes. + let shift1 = log2n - 1; + let shift2 = log2n + 6; + let round1 = 1 << (shift1 - 1); + let round2 = 1 << (shift2 - 1); + let mut tmp = [0i32; 32 * 32]; + let mut row = [0i32; 32]; + let mut out = [0i32; 32]; + for y in 0..n { + row[..n].copy_from_slice(&residual[y * n..y * n + n]); + if dst_type { + let mut src4 = [0i32; 4]; + src4.copy_from_slice(&row[..4]); + let mut dst4 = [0i32; 4]; + forward_dst4(&src4, &mut dst4); + out[..4].copy_from_slice(&dst4); + } else { + forward_1d(n, &row[..n], &mut out[..n]); + } + // Transposed store: the second pass then runs over what were columns. + for (k, &value) in out[..n].iter().enumerate() { + tmp[k * n + y] = (value + round1) >> shift1; + } + } + for k in 0..n { + row[..n].copy_from_slice(&tmp[k * n..k * n + n]); + if dst_type { + let mut src4 = [0i32; 4]; + src4.copy_from_slice(&row[..4]); + let mut dst4 = [0i32; 4]; + forward_dst4(&src4, &mut dst4); + out[..4].copy_from_slice(&dst4); + } else { + forward_1d(n, &row[..n], &mut out[..n]); + } + for (v, &value) in out[..n].iter().enumerate() { + coeffs[v * n + k] = (value + round2) >> shift2; + } + } +} + +/// Inverse transform of scaled coefficients into residual samples, exactly as +/// clause 8.6.4 specifies including its intermediate clipping. +pub fn inverse_transform(scaled: &[i32], residual: &mut [i32], n: usize, dst_type: bool) { + let mut e = [0i32; 32 * 32]; + let mut col = [0i32; 32]; + let mut out = [0i32; 32]; + // Stage 1: every column, i.e. along the vertical frequency index. + for k in 0..n { + for y in 0..n { + col[y] = scaled[y * n + k]; + } + if dst_type { + let mut src4 = [0i32; 4]; + src4.copy_from_slice(&col[..4]); + let mut dst4 = [0i32; 4]; + inverse_dst4(&src4, &mut dst4); + out[..4].copy_from_slice(&dst4); + } else { + inverse_1d(n, &col[..n], &mut out[..n]); + } + for y in 0..n { + e[y * n + k] = ((out[y] + 64) >> 7).clamp(COEFF_MIN, COEFF_MAX); + } + } + // Stage 2: every row, then the bit-depth shift (8-299). + const BD_SHIFT: i32 = 12; // 20 - bitDepth, 8-bit + let round = 1 << (BD_SHIFT - 1); + for y in 0..n { + col[..n].copy_from_slice(&e[y * n..y * n + n]); + if dst_type { + let mut src4 = [0i32; 4]; + src4.copy_from_slice(&col[..4]); + let mut dst4 = [0i32; 4]; + inverse_dst4(&src4, &mut dst4); + out[..4].copy_from_slice(&dst4); + } else { + inverse_1d(n, &col[..n], &mut out[..n]); + } + for x in 0..n { + residual[y * n + x] = (out[x] + round) >> BD_SHIFT; + } + } +} + +/// Quantise coefficients in place, returning the number of non-zero levels. +/// +/// The rounding offset is a third of a step, which is the intra bias every +/// encoder in this class uses: it costs a little distortion at the rounding +/// boundary and buys back more in rate. +pub fn quantize(coeffs: &[i32], levels: &mut [i32], n: usize, qp: i32) -> usize { + let log2n = n.trailing_zeros() as i32; + let qbits = 21 + qp / 6 - log2n; + let scale = QUANT_SCALE[(qp % 6) as usize] as i64; + let offset = (1i64 << qbits) / 3; + let mut nonzero = 0; + for (i, &c) in coeffs[..n * n].iter().enumerate() { + let magnitude = ((c.unsigned_abs() as i64 * scale + offset) >> qbits) as i32; + let level = magnitude.min(COEFF_MAX); + levels[i] = if c < 0 { -level } else { level }; + if level != 0 { + nonzero += 1; + } + } + nonzero +} + +/// Scale levels back into coefficients, exactly as clause 8.6.3 specifies. +pub fn dequantize(levels: &[i32], scaled: &mut [i32], n: usize, qp: i32) { + let log2n = n.trailing_zeros() as i32; + let bd_shift = log2n + 3; // bitDepth + Log2(nTbS) + 10 - 15, 8-bit + let round = 1i64 << (bd_shift - 1); + let scale = (16 * LEVEL_SCALE[(qp % 6) as usize]) as i64; + let shift = qp / 6; + for (i, &level) in levels[..n * n].iter().enumerate() { + let value = (((level as i64 * scale) << shift) + round) >> bd_shift; + scaled[i] = value.clamp(COEFF_MIN as i64, COEFF_MAX as i64) as i32; + } +} + +/// The chroma QP a luma QP maps to for 4:2:0 (Table 8-10), before any offset. +pub fn chroma_qp(qp_luma: i32, offset: i32) -> i32 { + let qpi = (qp_luma + offset).clamp(0, 57); + if qpi < 30 { + qpi + } else if qpi > 43 { + qpi - 6 + } else { + const TABLE: [i32; 14] = [29, 30, 31, 32, 33, 33, 34, 34, 35, 35, 36, 36, 37, 37]; + TABLE[(qpi - 30) as usize] + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn mirrored_half_matches_the_spec_second_table() { + // Spot values from transMatrixCol16to31 (8-321): row, column, value. + let spec: &[(usize, usize, i32)] = &[ + (0, 16, 64), + (0, 31, 64), + (1, 16, -4), + (1, 31, -90), + (2, 16, -90), + (2, 31, 90), + (3, 16, 13), + (3, 23, 73), + (4, 16, 89), + (8, 16, 83), + (16, 16, 64), + (16, 17, -64), + (31, 16, 90), + (31, 31, -4), + (30, 16, -9), + (29, 31, -13), + ]; + for &(row, col, value) in spec { + assert_eq!(m32(row, col), value, "M[{row}][{col}]"); + } + } + + #[test] + fn matrix_rows_are_orthogonal() { + // Every size's rows: orthogonal, and all of equal norm. A single mistyped + // entry breaks both. + for log2n in 2..=5u32 { + let n = 1usize << log2n; + let stride = 32 / n; + let norm: i32 = (0..n).map(|x| m32(0, x) * m32(0, x)).sum(); + for a in 0..n { + let self_dot: i32 = (0..n).map(|x| m32(a * stride, x) * m32(a * stride, x)).sum(); + // 64^2 * n is exact for the DC row; the others are within the + // rounding the integer matrix carries. + assert!( + (self_dot - norm).abs() * 200 < norm, + "row {a} of {n}: norm {self_dot} vs {norm}" + ); + for b in a + 1..n { + let dot: i32 = (0..n) + .map(|x| m32(a * stride, x) * m32(b * stride, x)) + .sum(); + assert!(dot.abs() * 100 < norm, "rows {a},{b} of {n}: dot {dot}"); + } + } + } + } + + #[test] + fn quant_scale_is_the_reciprocal() { + for k in 0..6 { + let product = QUANT_SCALE[k] as i64 * LEVEL_SCALE[k] as i64; + assert!((product - (1 << 20)).abs() < 64, "k={k}: {product}"); + assert_eq!(QUANT_SCALE[k], ((1 << 20) as f64 / LEVEL_SCALE[k] as f64).round() as i32); + } + } + + fn round_trip(residual: &[i32], n: usize, qp: i32, dst: bool) -> Vec { + let mut coeffs = vec![0i32; n * n]; + forward_transform(residual, &mut coeffs, n, dst); + let mut levels = vec![0i32; n * n]; + quantize(&coeffs, &mut levels, n, qp); + let mut scaled = vec![0i32; n * n]; + dequantize(&levels, &mut scaled, n, qp); + let mut out = vec![0i32; n * n]; + inverse_transform(&scaled, &mut out, n, dst); + out + } + + #[test] + fn round_trip_recovers_flat_blocks() { + // A constant residual stays constant at any QP — only the DC level + // survives — and at low QP it comes back to its own value. At QP 40 one + // level step *is* 16 samples, so accuracy is asserted where accuracy is + // on offer and flatness everywhere. + for &n in &[4usize, 8, 16, 32] { + for &qp in &[0i32, 12, 22, 27, 40, 51] { + let residual = vec![20i32; n * n]; + let out = round_trip(&residual, n, qp, false); + assert!(out.iter().all(|&v| v == out[0]), "n={n} qp={qp}: {out:?}"); + if qp <= 22 { + assert!((out[0] - 20).abs() <= 2, "n={n} qp={qp}: {}", out[0]); + } + } + } + } + + #[test] + fn round_trip_is_near_lossless_at_low_qp() { + // A textured block at QP 4 comes back within a sample or two; this is + // what proves the forward transform is the inverse of the normative one + // rather than merely self-consistent. + for &n in &[4usize, 8, 16, 32] { + for dst in [false, true] { + if dst && n != 4 { + continue; + } + let residual: Vec = (0..n * n) + .map(|i| (((i * 37) % 61) as i32) - 30) + .collect(); + let out = round_trip(&residual, n, 4, dst); + let worst = residual + .iter() + .zip(&out) + .map(|(a, b)| (a - b).abs()) + .max() + .unwrap(); + assert!(worst <= 3, "n={n} dst={dst}: worst {worst}"); + } + } + } + + #[test] + fn dc_only_coefficient_is_flat_after_inverse() { + // The spec's inverse of a DC-only block is a constant; a transposed + // matrix index would tilt it. + for &n in &[4usize, 8, 16, 32] { + let mut scaled = vec![0i32; n * n]; + scaled[0] = 4096; + let mut out = vec![0i32; n * n]; + inverse_transform(&scaled, &mut out, n, false); + assert!(out.iter().all(|&v| v == out[0]), "n={n}: {out:?}"); + // 4096 / 128: the two-stage inverse divides by 2^7 after the first + // pass and 2^12 after the second, against 64 x 64 of matrix gain. + assert_eq!(out[0], 32); + } + } + + #[test] + fn chroma_qp_table() { + assert_eq!(chroma_qp(29, 0), 29); + assert_eq!(chroma_qp(30, 0), 29); + assert_eq!(chroma_qp(35, 0), 33); + assert_eq!(chroma_qp(43, 0), 37); + assert_eq!(chroma_qp(44, 0), 38); + assert_eq!(chroma_qp(51, 0), 45); + assert_eq!(chroma_qp(30, -2), 28); + } +}