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//! Exponential Golomb codes are used in the [H.264
23//! (MPEG-4)](https://en.wikipedia.org/wiki/Advanced_Video_Coding) and
24//! [H.265](https://en.wikipedia.org/wiki/High_Efficiency_Video_Coding)
25//! standards.
26
27use super::gamma::{len_gamma, GammaRead, GammaWrite};
28use crate::traits::*;
29
30/// Returns the length of the exponential Golomb code for `n` with parameter `k`.
31#[must_use]
32#[inline(always)]
33pub fn len_exp_golomb(n: u64, k: usize) -> usize {
34 len_gamma(n >> k) + k
35}
36
37/// Trait for reading exponential Golomb codes.
38pub trait ExpGolombRead<E: Endianness>: BitRead<E> + GammaRead<E> {
39 #[inline(always)]
40 fn read_exp_golomb(&mut self, k: usize) -> Result<u64, Self::Error> {
41 Ok((self.read_gamma()? << k) + self.read_bits(k)?)
42 }
43}
44
45/// Trait for writing exponential Golomb codes.
46pub trait ExpGolombWrite<E: Endianness>: BitWrite<E> + GammaWrite<E> {
47 #[inline(always)]
48 fn write_exp_golomb(&mut self, n: u64, k: usize) -> Result<usize, Self::Error> {
49 let mut written_bits = self.write_gamma(n >> k)?;
50 #[cfg(feature = "checks")]
51 {
52 // Clean up n in case checks are enabled
53 let n = n & (1_u128 << k).wrapping_sub(1) as u64;
54 written_bits += self.write_bits(n, k)?;
55 }
56 #[cfg(not(feature = "checks"))]
57 {
58 written_bits += self.write_bits(n, k)?;
59 }
60 Ok(written_bits)
61 }
62}
63
64impl<E: Endianness, B: BitRead<E> + GammaRead<E>> ExpGolombRead<E> for B {}
65impl<E: Endianness, B: BitWrite<E> + GammaWrite<E>> ExpGolombWrite<E> for B {}