Skip to main content

dsi_bitstream/codes/
exp_golomb.rs

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