forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB00c1b3fTahinli2 months ago1999 commits

floor.rs334 lines, 11.1 KiBHistoryRawDownload
1//! Floor decode and curve synthesis — the spectral envelope a residue rides on.
2//!
3//! Two floor types share nothing but their job. Floor 1 (§7.2) is a
4//! piecewise-linear curve in a 0.54 dB quantised log domain, drawn with
5//! integer Bresenham arithmetic so every decoder draws the same line. Floor 0
6//! (§6.2) is an LSP filter response evaluated on a Bark-spaced map — only old
7//! encoders emit it, and the Xiph `lsp-test` vectors are exactly those.
8
9use std::sync::LazyLock;
10
11use crate::bits::Bits;
12use crate::codebook::{Codebook, ilog};
13use crate::setup::{Floor0, Floor1};
14
15/// §7.2.4's amplitude table, 256 entries of `10^((y - 255) * 140/256 / 20)`.
16///
17/// The spec prints the values; this states the law behind them, which is the
18/// same table to within a float ulp (its first entry, `1.0649863e-07`, is
19/// `10^(-255 * 0.02734375)` exactly). Generated rather than pasted so the
20/// relationship to the 140 dB the floor spans stays visible.
21static INVERSE_DB: LazyLock<[f32; 256]> = LazyLock::new(|| {
22 let mut table = [0.0f32; 256];
23 for (y, slot) in table.iter_mut().enumerate() {
24 *slot = 10f64.powf((y as f64 - 255.0) * (140.0 / 256.0) / 20.0) as f32;
25 }
26 table
27});
28
29/// What a floor packet said, kept until the residue is in and the curve is
30/// multiplied through.
31pub enum FloorState {
32 /// The channel codes no audio in this packet.
33 Unused,
34 /// Floor 1 amplitudes, in coding order, with their step-2 flags.
35 One {
36 /// Final Y value per coding-order index.
37 y: Vec<i32>,
38 /// Whether the value was coded rather than predicted.
39 step2: Vec<bool>,
40 },
41 /// Floor 0 amplitude and LSP coefficients.
42 Zero {
43 /// Coded amplitude.
44 amplitude: u32,
45 /// LSP coefficients.
46 coefficients: Vec<f32>,
47 },
48}
49
50impl FloorState {
51 /// True when the channel has no spectrum this packet.
52 pub fn is_unused(&self) -> bool {
53 matches!(self, FloorState::Unused)
54 }
55}
56
57/// Decode a floor-1 packet header (§7.2.2 and §7.2.3), amplitudes only.
58pub fn decode_floor1(floor: &Floor1, codebooks: &[Codebook], bits: &mut Bits) -> FloorState {
59 if !bits.bit() || bits.eop() {
60 return FloorState::Unused;
61 }
62 let range = [256i32, 128, 86, 64][(floor.multiplier - 1) as usize];
63 let values = floor.x_list.len();
64 let mut y = vec![0i32; values];
65 let field = ilog((range - 1) as u32);
66 y[0] = bits.read(field) as i32;
67 y[1] = bits.read(field) as i32;
68
69 let mut offset = 2usize;
70 for &class in &floor.partition_classes {
71 let dimensions = floor.class_dimensions[class];
72 let subclass_bits = floor.class_subclasses[class];
73 let mask = (1u32 << subclass_bits) - 1;
74 let mut class_value = 0u32;
75 if subclass_bits > 0 {
76 let book = &codebooks[floor.class_masterbooks[class]];
77 match book.decode_scalar(bits) {
78 Some(value) => class_value = value,
79 None => return FloorState::Unused,
80 }
81 }
82 for _ in 0..dimensions {
83 let book = floor.subclass_books[class][(class_value & mask) as usize];
84 class_value >>= subclass_bits;
85 if offset >= values {
86 break;
87 }
88 y[offset] = match book {
89 book if book >= 0 => match codebooks[book as usize].decode_scalar(bits) {
90 Some(value) => value as i32,
91 None => return FloorState::Unused,
92 },
93 _ => 0,
94 };
95 offset += 1;
96 }
97 }
98 if bits.eop() {
99 return FloorState::Unused;
100 }
101
102 // §7.2.3 amplitude synthesis: every value past the first two is a
103 // correction to the line its two already-coded neighbours predict, folded
104 // into the room that line leaves above and below.
105 let mut final_y = y.clone();
106 let mut step2 = vec![false; values];
107 step2[0] = true;
108 step2[1] = true;
109 for i in 2..values {
110 let (low, high) = floor.neighbours[i];
111 let predicted = render_point(
112 floor.x_list[low],
113 final_y[low],
114 floor.x_list[high],
115 final_y[high],
116 floor.x_list[i],
117 );
118 let val = y[i];
119 let high_room = range - predicted;
120 let low_room = predicted;
121 let room = high_room.min(low_room) * 2;
122 if val != 0 {
123 step2[low] = true;
124 step2[high] = true;
125 step2[i] = true;
126 final_y[i] = match val >= room {
127 true => match high_room > low_room {
128 true => val - low_room + predicted,
129 false => predicted - val + high_room - 1,
130 },
131 false => match val & 1 == 1 {
132 true => predicted - (val + 1) / 2,
133 false => predicted + val / 2,
134 },
135 };
136 } else {
137 step2[i] = false;
138 final_y[i] = predicted;
139 }
140 final_y[i] = final_y[i].clamp(0, range - 1);
141 }
142 FloorState::One { y: final_y, step2 }
143}
144
145/// Draw the floor-1 curve into `out` (§7.2.4), one value per coefficient.
146pub fn render_floor1(floor: &Floor1, y: &[i32], step2: &[bool], out: &mut [f32]) {
147 let n = out.len();
148 let table = &*INVERSE_DB;
149 let multiplier = floor.multiplier;
150 let mut lx = 0usize;
151 let mut ly = y[0] * multiplier;
152 let mut hx = 0usize;
153 let mut hy = ly;
154 for &i in floor.sorted.iter().skip(1) {
155 if !step2[i] {
156 continue;
157 }
158 hy = y[i] * multiplier;
159 hx = floor.x_list[i] as usize;
160 render_line(lx, ly, hx, hy, out, table);
161 lx = hx;
162 ly = hy;
163 }
164 if hx < n {
165 render_line(hx, hy, n, hy, out, table);
166 }
167}
168
169/// §7.2.2 `render_point`: the height a line between two coded values has at `x`.
170fn render_point(x0: u32, y0: i32, x1: u32, y1: i32, x: u32) -> i32 {
171 let dy = y1 - y0;
172 let adx = (x1 - x0) as i32;
173 let ady = dy.abs();
174 let off = (ady * (x - x0) as i32) / adx;
175 match dy < 0 {
176 true => y0 - off,
177 false => y0 + off,
178 }
179}
180
181/// §7.2.4 `render_line`: integer Bresenham, so two decoders never disagree by
182/// one sample of tilt.
183fn render_line(x0: usize, y0: i32, x1: usize, y1: i32, out: &mut [f32], table: &[f32; 256]) {
184 let n = out.len();
185 let dy = y1 - y0;
186 let adx = (x1 - x0) as i32;
187 if adx <= 0 {
188 return;
189 }
190 let mut ady = dy.abs();
191 let base = dy / adx;
192 let sy = match dy < 0 {
193 true => base - 1,
194 false => base + 1,
195 };
196 ady -= base.abs() * adx;
197 let mut y = y0;
198 let mut err = 0i32;
199 if x0 < n {
200 out[x0] = table[y.clamp(0, 255) as usize];
201 }
202 let end = x1.min(n);
203 for slot in out[(x0 + 1).min(end)..end].iter_mut() {
204 err += ady;
205 if err >= adx {
206 err -= adx;
207 y += sy;
208 } else {
209 y += base;
210 }
211 *slot = table[y.clamp(0, 255) as usize];
212 }
213}
214
215/// Decode a floor-0 packet header (§6.2.2): an amplitude and an LSP vector.
216pub fn decode_floor0(floor: &Floor0, codebooks: &[Codebook], bits: &mut Bits) -> FloorState {
217 let amplitude = bits.read(floor.amplitude_bits);
218 if bits.eop() {
219 return FloorState::Unused;
220 }
221 if amplitude == 0 {
222 return FloorState::Unused;
223 }
224 // §6.2.2 states the book number in `ilog(number_of_books)` bits — the count
225 // itself, not the largest index, which is one bit wider than it looks.
226 let index = bits.read(ilog(floor.books.len() as u32)) as usize;
227 let Some(&book) = floor.books.get(index) else {
228 return FloorState::Unused;
229 };
230 let book = &codebooks[book];
231 if !book.has_values() {
232 return FloorState::Unused;
233 }
234 let mut coefficients = Vec::with_capacity(floor.order);
235 let mut last = 0.0f32;
236 while coefficients.len() < floor.order {
237 let Some(vector) = book.decode_vector(bits) else {
238 return FloorState::Unused;
239 };
240 for &value in vector {
241 coefficients.push(value + last);
242 }
243 last = *coefficients.last().unwrap_or(&0.0);
244 }
245 coefficients.truncate(floor.order);
246 FloorState::Zero {
247 amplitude,
248 coefficients,
249 }
250}
251
252/// Draw the floor-0 curve into `out` (§6.2.3): the LSP pair evaluated on a
253/// Bark-spaced frequency map, one height per Bark bin.
254pub fn render_floor0(floor: &Floor0, amplitude: u32, coefficients: &[f32], out: &mut [f32]) {
255 let n = out.len();
256 if n == 0 || coefficients.is_empty() {
257 out.fill(0.0);
258 return;
259 }
260 let order = coefficients.len();
261 let bark_size = floor.bark_map_size as f64;
262 let scale = bark_size / bark(0.5 * f64::from(floor.rate));
263 let map: Vec<f64> = (0..n)
264 .map(|i| {
265 let hz = f64::from(floor.rate) * 0.5 * i as f64 / n as f64;
266 (bark(hz) * scale).floor().clamp(0.0, bark_size - 1.0)
267 })
268 .collect();
269 let amplitude_max = ((1u64 << floor.amplitude_bits) - 1) as f64;
270 let offset = f64::from(floor.amplitude_offset);
271 let cos_theta: Vec<f64> = coefficients.iter().map(|&c| f64::from(c).cos()).collect();
272
273 let mut i = 0usize;
274 while i < n {
275 let bin = map[i];
276 let omega = std::f64::consts::PI * bin / bark_size;
277 let cos_omega = omega.cos();
278 // P and Q are the two LSP polynomials on the unit circle; their
279 // prefactors are the (1 +- z^-1) factors the odd and even orders differ
280 // by, and each root contributes 4(cos(theta) - cos(omega))^2.
281 let (mut p, mut q) = match order % 2 {
282 1 => (1.0 - cos_omega * cos_omega, 0.25),
283 _ => ((1.0 - cos_omega) * 0.5, (1.0 + cos_omega) * 0.5),
284 };
285 let mut j = 1usize;
286 while j < order {
287 let d = cos_theta[j] - cos_omega;
288 p *= 4.0 * d * d;
289 j += 2;
290 }
291 let mut j = 0usize;
292 while j < order {
293 let d = cos_theta[j] - cos_omega;
294 q *= 4.0 * d * d;
295 j += 2;
296 }
297 let value = (0.11512925
298 * (f64::from(amplitude) * offset / (amplitude_max * (p + q).sqrt()) - offset))
299 .exp() as f32;
300 while i < n && map[i] == bin {
301 out[i] = value;
302 i += 1;
303 }
304 }
305}
306
307/// §6.2.3's Bark scale.
308fn bark(x: f64) -> f64 {
309 13.1 * (0.00074 * x).atan() + 2.24 * (0.0000000185 * x * x).atan() + 0.0001 * x
310}
311
312#[cfg(test)]
313mod tests {
314 use super::*;
315
316 #[test]
317 fn inverse_db_table_matches_the_spec_endpoints() {
318 let table = &*INVERSE_DB;
319 assert!((table[0] - 1.0649863e-07).abs() < 1e-13, "{}", table[0]);
320 assert!((table[255] - 1.0).abs() < 1e-6, "{}", table[255]);
321 // Monotonic, which is what makes a bigger Y a louder floor.
322 assert!(table.windows(2).all(|w| w[1] > w[0]));
323 }
324
325 #[test]
326 fn render_line_draws_the_spec_slope() {
327 let mut out = vec![0.0f32; 8];
328 let table = &*INVERSE_DB;
329 render_line(0, 0, 8, 16, &mut out, table);
330 // Sixteen steps over eight samples is two per sample, starting at zero.
331 let expect: Vec<f32> = (0..8).map(|i| table[i * 2]).collect();
332 assert_eq!(out, expect);
333 }
334}