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