dsi_bitstream/codes/exp_golomb.rs
1/*
2 * SPDX-FileCopyrightText: 2023 Sebastiano Vigna
3 *
4 * SPDX-License-Identifier: Apache-2.0 OR LGPL-2.1-or-later
5 */
6
7//! Exponential Golomb codes.
8//!
9//! Exponential Golomb codes are a variant of Golomb codes with power-of-two
10//! modulus (i.e., [Rice codes](super::rice)) in which the prefix is written
11//! using [Elias γ code](super::gamma) instead of unary code. More precisely,
12//! the exponential Golomb code with parameter *k* ≥ 0 of a natural number *n*
13//! is given ⌊*x* / 2*ᵏ*⌋ in [γ code](super::gamma) followed by *x* mod 2*ᵏ* in
14//! binary *k*-bit representations.
15//!
16//! The implied distribution of an exponential Golomb code with parameter *k* is
17//! ≈ 2²*ᵏ*/2*x*².
18//!
19//! Note that the exponential Golomb code for *k* = 0 is exactly the [γ
20//! code](super::gamma).
21//!
22//! The supported range is [0 . . 2⁶⁴ – 1) for *k* = 0 and [0 . . 2⁶⁴) for *k*
23//! in [1 . . 64).
24//!
25//!
26//! Exponential Golomb codes are used in the [H.264
27//! (MPEG-4)](https://en.wikipedia.org/wiki/Advanced_Video_Coding) and
28//! [H.265](https://en.wikipedia.org/wiki/High_Efficiency_Video_Coding)
29//! standards.
30
31use super::gamma::{GammaRead, GammaWrite, len_gamma};
32use crate::traits::*;
33
34/// Returns the length of the exponential Golomb code for `n` with parameter `k`.
35#[must_use]
36#[inline(always)]
37pub fn len_exp_golomb(n: u64, k: usize) -> usize {
38 debug_assert!(k < 64);
39 len_gamma(n >> k) + k
40}
41
42/// Trait for reading exponential Golomb codes.
43pub trait ExpGolombRead<E: Endianness>: BitRead<E> + GammaRead<E> {
44 #[inline(always)]
45 fn read_exp_golomb(&mut self, k: usize) -> Result<u64, Self::Error> {
46 debug_assert!(k < 64);
47 Ok((self.read_gamma()? << k) + self.read_bits(k)?)
48 }
49}
50
51/// Trait for writing exponential Golomb codes.
52pub trait ExpGolombWrite<E: Endianness>: BitWrite<E> + GammaWrite<E> {
53 #[inline(always)]
54 fn write_exp_golomb(&mut self, n: u64, k: usize) -> Result<usize, Self::Error> {
55 debug_assert!(k < 64);
56 let mut written_bits = self.write_gamma(n >> k)?;
57 #[cfg(feature = "checks")]
58 {
59 // Clean up n in case checks are enabled
60 let n = n & (1_u128 << k).wrapping_sub(1) as u64;
61 written_bits += self.write_bits(n, k)?;
62 }
63 #[cfg(not(feature = "checks"))]
64 {
65 written_bits += self.write_bits(n, k)?;
66 }
67 Ok(written_bits)
68 }
69}
70
71impl<E: Endianness, B: BitRead<E> + GammaRead<E>> ExpGolombRead<E> for B {}
72impl<E: Endianness, B: BitWrite<E> + GammaWrite<E>> ExpGolombWrite<E> for B {}