forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB58b009bTahinli2 months ago2045 commits

bits.rs150 lines, 4.4 KiBHistoryRawDownload
1//! Packet-local bit access with the Vorbis end-of-packet convention.
2//!
3//! Reading past the end of a Vorbis packet is not an error. The spec's decode
4//! loops read until the packet runs out and take zeroes after that, which is
5//! how a truncated final packet still decodes to the audio it does hold. So
6//! this reader answers zero past the end and raises a sticky flag; the callers
7//! that must not act on a zero — Huffman decode, header parse — ask [`Bits::eop`].
8
9use ec_core::{BitReaderLsb, BitWriterLsb};
10
11/// LSB-first reader over one packet.
12pub struct Bits<'a> {
13 reader: BitReaderLsb<'a>,
14 eop: bool,
15}
16
17impl<'a> Bits<'a> {
18 /// A reader positioned at the first bit of `data`.
19 pub fn new(data: &'a [u8]) -> Bits<'a> {
20 Bits {
21 reader: BitReaderLsb::new(data),
22 eop: false,
23 }
24 }
25
26 /// `n` bits (`n <= 32`), zero once the packet is exhausted.
27 pub fn read(&mut self, n: u32) -> u32 {
28 match self.reader.read_bits(n) {
29 Ok(v) => v,
30 Err(_) => {
31 self.eop = true;
32 0
33 }
34 }
35 }
36
37 /// One bit, false once the packet is exhausted.
38 pub fn bit(&mut self) -> bool {
39 self.read(1) != 0
40 }
41
42 /// True once a read has run past the end of the packet.
43 pub fn eop(&self) -> bool {
44 self.eop
45 }
46
47 /// Bits left before the end of the packet.
48 pub fn remaining(&self) -> u64 {
49 self.reader.bits_remaining()
50 }
51
52 /// The 32-bit float of Vorbis I §9.2.2 — a 21-bit mantissa, a sign and a
53 /// biased exponent, and *not* IEEE 754: it is decoded with integer
54 /// arithmetic so every decoder agrees on the last bit.
55 pub fn float32(&mut self) -> f32 {
56 let x = self.read(32);
57 float32_unpack(x)
58 }
59}
60
61/// Vorbis I §9.2.2 float unpack, split out because the encoder packs the
62/// inverse of it.
63pub fn float32_unpack(x: u32) -> f32 {
64 let mantissa = i64::from(x & 0x001f_ffff);
65 let sign = x & 0x8000_0000 != 0;
66 let exponent = ((x & 0x7fe0_0000) >> 21) as i32;
67 let mantissa = if sign { -mantissa } else { mantissa };
68 // `exp2` rather than `powi`: the exponent field spans 2^-788..2^235, which
69 // only stays exact as a power of two.
70 (mantissa as f64 * f64::from(exponent - 788).exp2()) as f32
71}
72
73/// The inverse of [`float32_unpack`] for a value an encoder wants to state
74/// exactly: mantissa in `[-2^21, 2^21)` scaled by a power of two.
75pub fn float32_pack(value: f32) -> u32 {
76 if value == 0.0 || !value.is_finite() {
77 return 0;
78 }
79 let sign = value < 0.0;
80 let mut mantissa = f64::from(value.abs());
81 let mut exponent = 0i32;
82 // Normalise into [2^20, 2^21) so the 21-bit mantissa field is fully used.
83 while mantissa >= 2_097_152.0 {
84 mantissa /= 2.0;
85 exponent += 1;
86 }
87 while mantissa < 1_048_576.0 {
88 mantissa *= 2.0;
89 exponent -= 1;
90 }
91 let mantissa = mantissa.round() as u32 & 0x001f_ffff;
92 let exponent = (exponent + 788).clamp(0, 0x3ff) as u32;
93 (u32::from(sign) << 31) | (exponent << 21) | mantissa
94}
95
96/// LSB-first writer over one packet, the mirror of [`Bits`].
97#[derive(Default)]
98pub struct BitsOut {
99 writer: BitWriterLsb,
100}
101
102impl BitsOut {
103 /// An empty packet.
104 pub fn new() -> BitsOut {
105 BitsOut::default()
106 }
107
108 /// Write the low `n` bits of `value`.
109 pub fn write(&mut self, value: u32, n: u32) {
110 self.writer.write_bits(value, n);
111 }
112
113 /// Write one bit.
114 pub fn bit(&mut self, bit: bool) {
115 self.writer.write_bit(bit);
116 }
117
118 /// Bits written so far.
119 pub fn len(&self) -> u64 {
120 self.writer.bit_len()
121 }
122
123 /// The packet, zero-padded to a byte.
124 pub fn finish(self) -> Vec<u8> {
125 self.writer.into_bytes()
126 }
127}
128
129#[cfg(test)]
130mod tests {
131 use super::*;
132
133 #[test]
134 fn float32_round_trips_through_the_spec_format() {
135 for value in [1.0f32, 0.5, -2.25, 1e-6, 1024.0, -0.0009765625] {
136 let packed = float32_pack(value);
137 let back = float32_unpack(packed);
138 assert!(
139 (back - value).abs() <= value.abs() * 1e-6,
140 "{value} -> {packed:#x} -> {back}"
141 );
142 }
143 assert_eq!(float32_unpack(0), 0.0);
144 // A read past the end is zero with the flag raised, not an error.
145 let mut bits = Bits::new(&[0xff]);
146 assert_eq!(bits.read(8), 0xff);
147 assert_eq!(bits.read(1), 0);
148 assert!(bits.eop());
149 }
150}