forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBdfeffbcTahinli2 months ago3180 commits

celt.rs3137 lines, 108.3 KiBHistoryRawDownload
1//! The CELT (MDCT) layer of Opus — RFC 6716 Section 4.3.
2//!
3//! CELT codes a frame as a per-band energy envelope plus a unit-norm shape per
4//! band, the shape being a PVQ codeword. Decoding is therefore: coarse and fine
5//! energy, an implicit bit allocation that both sides must derive identically,
6//! PVQ shapes with spreading/folding, denormalisation by the energy, and an
7//! inverse MDCT with overlap-add, post-filter and de-emphasis.
8//!
9//! Two notes on where the numbers come from. RFC 6716 Section 6 makes the
10//! reference decoder in its Appendix A normative — "should the description
11//! contradict the source code of the reference implementation, the latter shall
12//! take precedence" — and Section 4.3 defers several tables to it by name
13//! (`e_prob_model`, `cache_caps50`, `tf_select_table`, `LOG2_FRAC_TABLE`,
14//! band_allocation). Those constants are reproduced here from that appendix,
15//! because a decoder that invents them does not decode Opus. Everything with a
16//! closed form (the window, `eband` boundaries, PVQ combinatorics) is computed
17//! or written from the prose instead.
18//!
19//! The MDCT is *not* a DFT: sizes here are 15*2^k (120, 240, 480, 960
20//! coefficients), so the transform runs as a 15-point stage over
21//! [`ec_dsp::Fft`] power-of-two sub-transforms — an `N/4`-point complex FFT
22//! exactly as the reference does it, never an O(N^2) direct evaluation.
23
24use ec_core::{Error, Result};
25
26use crate::range::{RangeDecoder, RangeEncoder};
27
28/// Bands in the 48 kHz mode.
29pub const NB_BANDS: usize = 21;
30/// Band boundaries in units of 2.5 ms MDCT bins (Table 55).
31pub(crate) const E_BANDS: [usize; NB_BANDS + 1] = [
32 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 34, 40, 48, 60, 78, 100,
33];
34/// MDCT bins in a 2.5 ms frame; the window overlap is the same length.
35pub(crate) const SHORT_MDCT: usize = 120;
36/// Samples of overlap between consecutive frames.
37pub(crate) const OVERLAP: usize = 120;
38/// Longest post-filter period, and the history the comb filter needs.
39#[allow(dead_code)]
40const MAX_PERIOD: usize = 1024;
41/// Shortest post-filter period.
42const MIN_PERIOD: usize = 15;
43/// Synthesis history kept per channel.
44const DECODE_BUFFER: usize = 2048;
45/// Allocation resolution: 1/8 bit.
46pub(crate) const BITRES: u32 = 3;
47/// Most fine-energy bits a band can get.
48pub(crate) const MAX_FINE_BITS: i32 = 8;
49pub(crate) const FINE_OFFSET: i32 = 21;
50pub(crate) const QTHETA_OFFSET: i32 = 4;
51pub(crate) const QTHETA_OFFSET_TWOPHASE: i32 = 16;
52
53/// `logN400`: `log2(N)` per band in 1/8 bits, for the fine-energy offset.
54pub(crate) const LOG_N: [i32; NB_BANDS] = [
55 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 16, 16, 16, 21, 21, 24, 29, 34, 36,
56];
57
58/// Mean energy per band, subtracted before quantisation (`eMeans`, in log2).
59pub(crate) const E_MEANS: [f32; NB_BANDS] = [
60 6.4375, 6.25, 5.75, 5.3125, 5.0625, 4.8125, 4.5, 4.375, 4.875, 4.6875, 4.5625, 4.4375, 4.875,
61 4.625, 4.3125, 4.5, 4.375, 4.625, 4.75, 4.4375, 3.75,
62];
63
64/// Static allocation table (Table 57), `[quality][band]`, 1/32 bit per bin.
65pub(crate) const BAND_ALLOCATION: [[u8; NB_BANDS]; 11] = [
66 [0; NB_BANDS],
67 [
68 90, 80, 75, 69, 63, 56, 49, 40, 34, 29, 20, 18, 10, 0, 0, 0, 0, 0, 0, 0, 0,
69 ],
70 [
71 110, 100, 90, 84, 78, 71, 65, 58, 51, 45, 39, 32, 26, 20, 12, 0, 0, 0, 0, 0, 0,
72 ],
73 [
74 118, 110, 103, 93, 86, 80, 75, 70, 65, 59, 53, 47, 40, 31, 23, 15, 4, 0, 0, 0, 0,
75 ],
76 [
77 126, 119, 112, 104, 95, 89, 83, 78, 72, 66, 60, 54, 47, 39, 32, 25, 17, 12, 1, 0, 0,
78 ],
79 [
80 134, 127, 120, 114, 103, 97, 91, 85, 78, 72, 66, 60, 54, 47, 41, 35, 29, 23, 16, 10, 1,
81 ],
82 [
83 144, 137, 130, 124, 113, 107, 101, 95, 88, 82, 76, 70, 64, 57, 51, 45, 39, 33, 26, 15, 1,
84 ],
85 [
86 152, 145, 138, 132, 123, 117, 111, 105, 98, 92, 86, 80, 74, 67, 61, 55, 49, 43, 36, 20, 1,
87 ],
88 [
89 162, 155, 148, 142, 133, 127, 121, 115, 108, 102, 96, 90, 84, 77, 71, 65, 59, 53, 46, 30, 1,
90 ],
91 [
92 172, 165, 158, 152, 143, 137, 131, 125, 118, 112, 106, 100, 94, 87, 81, 75, 69, 63, 56, 45,
93 20,
94 ],
95 [
96 200, 200, 200, 200, 200, 200, 200, 200, 198, 193, 188, 183, 178, 173, 168, 163, 158, 153,
97 148, 129, 104,
98 ],
99];
100
101/// Laplace parameters for coarse energy, `[LM][intra][2*band]` (`e_prob_model`).
102pub(crate) const E_PROB_MODEL: [[[u8; 42]; 2]; 4] = [
103 [
104 [
105 72, 127, 65, 129, 66, 128, 65, 128, 64, 128, 62, 128, 64, 128, 64, 128, 92, 78, 92, 79,
106 92, 78, 90, 79, 116, 41, 115, 40, 114, 40, 132, 26, 132, 26, 145, 17, 161, 12, 176, 10,
107 177, 11,
108 ],
109 [
110 24, 179, 48, 138, 54, 135, 54, 132, 53, 134, 56, 133, 55, 132, 55, 132, 61, 114, 70,
111 96, 74, 88, 75, 88, 87, 74, 89, 66, 91, 67, 100, 59, 108, 50, 120, 40, 122, 37, 97, 43,
112 78, 50,
113 ],
114 ],
115 [
116 [
117 83, 78, 84, 81, 88, 75, 86, 74, 87, 71, 90, 73, 93, 74, 93, 74, 109, 40, 114, 36, 117,
118 34, 117, 34, 143, 17, 145, 18, 146, 19, 162, 12, 165, 10, 178, 7, 189, 6, 190, 8, 177,
119 9,
120 ],
121 [
122 23, 178, 54, 115, 63, 102, 66, 98, 69, 99, 74, 89, 71, 91, 73, 91, 78, 89, 86, 80, 92,
123 66, 93, 64, 102, 59, 103, 60, 104, 60, 117, 52, 123, 44, 138, 35, 133, 31, 97, 38, 77,
124 45,
125 ],
126 ],
127 [
128 [
129 61, 90, 93, 60, 105, 42, 107, 41, 110, 45, 116, 38, 113, 38, 112, 38, 124, 26, 132, 27,
130 136, 19, 140, 20, 155, 14, 159, 16, 158, 18, 170, 13, 177, 10, 187, 8, 192, 6, 175, 9,
131 159, 10,
132 ],
133 [
134 21, 178, 59, 110, 71, 86, 75, 85, 84, 83, 91, 66, 88, 73, 87, 72, 92, 75, 98, 72, 105,
135 58, 107, 54, 115, 52, 114, 55, 112, 56, 129, 51, 132, 40, 150, 33, 140, 29, 98, 35, 77,
136 42,
137 ],
138 ],
139 [
140 [
141 42, 121, 96, 66, 108, 43, 111, 40, 117, 44, 123, 32, 120, 36, 119, 33, 127, 33, 134,
142 34, 139, 21, 147, 23, 152, 20, 158, 25, 154, 26, 166, 21, 173, 16, 184, 13, 184, 10,
143 150, 13, 139, 15,
144 ],
145 [
146 22, 178, 63, 114, 74, 82, 84, 83, 92, 82, 103, 62, 96, 72, 96, 67, 101, 73, 107, 72,
147 113, 55, 118, 52, 125, 52, 118, 52, 117, 55, 135, 49, 137, 39, 157, 32, 145, 29, 97,
148 33, 77, 40,
149 ],
150 ],
151];
152
153/// Inter-frame prediction gain for coarse energy, per LM (`pred_coef`).
154pub(crate) const PRED_COEF: [f32; 4] = [
155 29440.0 / 32768.0,
156 26112.0 / 32768.0,
157 21248.0 / 32768.0,
158 16384.0 / 32768.0,
159];
160/// Intra-frame (across bands) prediction gain, per LM (`beta_coef`).
161pub(crate) const BETA_COEF: [f32; 4] = [
162 30147.0 / 32768.0,
163 22282.0 / 32768.0,
164 12124.0 / 32768.0,
165 6554.0 / 32768.0,
166];
167/// The same for an intra frame.
168pub(crate) const BETA_INTRA: f32 = 4915.0 / 32768.0;
169
170/// TF resolution adjustment, `[LM][4*transient + 2*tf_select + tf_change]`
171/// (Tables 60-63).
172pub(crate) const TF_SELECT: [[i32; 8]; 4] = [
173 [0, -1, 0, -1, 0, -1, 0, -1],
174 [0, -1, 0, -2, 1, 0, 1, -1],
175 [0, -2, 0, -3, 2, 0, 1, -1],
176 [0, -2, 0, -3, 3, 0, 1, -1],
177];
178
179/// Conservative `log2` in 1/8 bits, used to reserve the intensity parameter.
180pub(crate) const LOG2_FRAC: [i32; 24] = [
181 0, 8, 13, 16, 19, 21, 23, 24, 26, 27, 28, 29, 30, 31, 32, 32, 33, 34, 34, 35, 36, 36, 37, 37,
182];
183
184/// Index into [`CACHE_BITS`] per `[LM+1][band]` (`cache_index50`).
185const CACHE_INDEX: [i16; 105] = [
186 -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 41, 41, 41, 82, 82, 123, 164, 200, 222, 0, 0, 0, 0,
187 0, 0, 0, 0, 41, 41, 41, 41, 123, 123, 123, 164, 164, 240, 266, 283, 295, 41, 41, 41, 41, 41,
188 41, 41, 41, 123, 123, 123, 123, 240, 240, 240, 266, 266, 305, 318, 328, 336, 123, 123, 123,
189 123, 123, 123, 123, 123, 240, 240, 240, 240, 305, 305, 305, 318, 318, 343, 351, 358, 364, 240,
190 240, 240, 240, 240, 240, 240, 240, 305, 305, 305, 305, 343, 343, 343, 351, 351, 370, 376, 382,
191 387,
192];
193
194/// Bits (minus one) to code `k` pulses in each band size (`cache_bits50`).
195pub(crate) const CACHE_BITS: [u8; 392] = [
196 40, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
197 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 40, 15, 23, 28, 31, 34, 36, 38, 39, 41, 42, 43, 44, 45, 46, 47,
198 47, 49, 50, 51, 52, 53, 54, 55, 55, 57, 58, 59, 60, 61, 62, 63, 63, 65, 66, 67, 68, 69, 70, 71,
199 71, 40, 20, 33, 41, 48, 53, 57, 61, 64, 66, 69, 71, 73, 75, 76, 78, 80, 82, 85, 87, 89, 91, 92,
200 94, 96, 98, 101, 103, 105, 107, 108, 110, 112, 114, 117, 119, 121, 123, 124, 126, 128, 40, 23,
201 39, 51, 60, 67, 73, 79, 83, 87, 91, 94, 97, 100, 102, 105, 107, 111, 115, 118, 121, 124, 126,
202 129, 131, 135, 139, 142, 145, 148, 150, 153, 155, 159, 163, 166, 169, 172, 174, 177, 179, 35,
203 28, 49, 65, 78, 89, 99, 107, 114, 120, 126, 132, 136, 141, 145, 149, 153, 159, 165, 171, 176,
204 180, 185, 189, 192, 199, 205, 211, 216, 220, 225, 229, 232, 239, 245, 251, 21, 33, 58, 79, 97,
205 112, 125, 137, 148, 157, 166, 174, 182, 189, 195, 201, 207, 217, 227, 235, 243, 251, 17, 35,
206 63, 86, 106, 123, 139, 152, 165, 177, 187, 197, 206, 214, 222, 230, 237, 250, 25, 31, 55, 75,
207 91, 105, 117, 128, 138, 146, 154, 161, 168, 174, 180, 185, 190, 200, 208, 215, 222, 229, 235,
208 240, 245, 255, 16, 36, 65, 89, 110, 128, 144, 159, 173, 185, 196, 207, 217, 226, 234, 242, 250,
209 11, 41, 74, 103, 128, 151, 172, 191, 209, 225, 241, 255, 9, 43, 79, 110, 138, 163, 186, 207,
210 227, 246, 12, 39, 71, 99, 123, 144, 164, 182, 198, 214, 228, 241, 253, 9, 44, 81, 113, 142,
211 168, 192, 214, 235, 255, 7, 49, 90, 127, 160, 191, 220, 247, 6, 51, 95, 134, 170, 203, 234, 7,
212 47, 87, 123, 155, 184, 212, 237, 6, 52, 97, 137, 174, 208, 240, 5, 57, 106, 151, 192, 231, 5,
213 59, 111, 158, 202, 243, 5, 55, 103, 147, 187, 224, 5, 60, 113, 161, 206, 248, 4, 65, 122, 175,
214 224, 4, 67, 127, 182, 234,
215];
216
217/// Per-band allocation ceiling, `[2*LM + stereo][band]` (`cache_caps50`).
218pub(crate) const CACHE_CAPS: [u8; 168] = [
219 224, 224, 224, 224, 224, 224, 224, 224, 160, 160, 160, 160, 185, 185, 185, 178, 178, 168, 134,
220 61, 37, 224, 224, 224, 224, 224, 224, 224, 224, 240, 240, 240, 240, 207, 207, 207, 198, 198,
221 183, 144, 66, 40, 160, 160, 160, 160, 160, 160, 160, 160, 185, 185, 185, 185, 193, 193, 193,
222 183, 183, 172, 138, 64, 38, 240, 240, 240, 240, 240, 240, 240, 240, 207, 207, 207, 207, 204,
223 204, 204, 193, 193, 180, 143, 66, 40, 185, 185, 185, 185, 185, 185, 185, 185, 193, 193, 193,
224 193, 193, 193, 193, 183, 183, 172, 138, 65, 39, 207, 207, 207, 207, 207, 207, 207, 207, 204,
225 204, 204, 204, 201, 201, 201, 188, 188, 176, 141, 66, 40, 193, 193, 193, 193, 193, 193, 193,
226 193, 193, 193, 193, 193, 194, 194, 194, 184, 184, 173, 139, 65, 39, 204, 204, 204, 204, 204,
227 204, 204, 204, 201, 201, 201, 201, 198, 198, 198, 187, 187, 175, 140, 66, 40,
228];
229
230/// Hadamard interleave order for 2, 4, 8 and 16 blocks (`ordery_table`).
231const ORDERY: [usize; 30] = [
232 1, 0, //
233 3, 0, 2, 1, //
234 7, 0, 4, 3, 6, 1, 5, 2, //
235 15, 0, 8, 7, 12, 3, 11, 4, 14, 1, 9, 6, 13, 2, 10, 5,
236];
237
238pub(crate) const TRIM_ICDF: [u8; 11] = [126, 124, 119, 109, 87, 41, 19, 9, 4, 2, 0];
239pub(crate) const SPREAD_ICDF: [u8; 4] = [25, 23, 2, 0];
240const TAPSET_ICDF: [u8; 3] = [2, 1, 0];
241pub(crate) const SMALL_ENERGY_ICDF: [u8; 3] = [2, 1, 0];
242
243/// Post-filter tap sets (Section 4.3.7.1).
244const POSTFILTER_GAINS: [[f32; 3]; 3] = [
245 [0.306_640_63, 0.217_041_02, 0.129_638_67],
246 [0.463_867_2, 0.268_066_4, 0.0],
247 [0.799_804_7, 0.100_097_66, 0.0],
248];
249
250/// De-emphasis coefficient, `1/(1 - 0.85 z^-1)` at 48 kHz.
251pub(crate) const PREEMPH: f32 = 0.850_006_1;
252/// Internal signal scale; the output is divided by this.
253pub(crate) const SIG_SCALE: f32 = 32768.0;
254
255pub(crate) const SPREAD_NONE: usize = 0;
256pub(crate) const SPREAD_LIGHT: usize = 1;
257pub(crate) const SPREAD_NORMAL: usize = 2;
258pub(crate) const SPREAD_AGGRESSIVE: usize = 3;
259
260/// `ilog(x)`: index of the highest set bit plus one.
261#[inline]
262pub(crate) fn ilog(x: u32) -> i32 {
263 (32 - x.leading_zeros()) as i32
264}
265
266/// Integer square root, `floor(sqrt(x))`.
267fn isqrt32(x: u32) -> u32 {
268 if x == 0 {
269 return 0;
270 }
271 let mut r = (x as f64).sqrt() as u32;
272 // Correct the float estimate; never trust it at the boundary.
273 while r > 0 && (r as u64) * (r as u64) > x as u64 {
274 r -= 1;
275 }
276 while ((r + 1) as u64) * ((r + 1) as u64) <= x as u64 {
277 r += 1;
278 }
279 r
280}
281
282/// The CELT low-overlap window (Section 4.3.7), computed rather than tabulated.
283pub(crate) fn overlap_window() -> Vec<f32> {
284 (0..OVERLAP)
285 .map(|i| {
286 let inner = (core::f64::consts::FRAC_PI_2 * (i as f64 + 0.5) / OVERLAP as f64).sin();
287 (core::f64::consts::FRAC_PI_2 * inner * inner).sin() as f32
288 })
289 .collect()
290}
291
292// ---------------------------------------------------------------------------
293// The N/4 FFT and the inverse MDCT
294// ---------------------------------------------------------------------------
295
296/// A complex inverse FFT of the sizes CELT needs (`15 * 2^k`).
297///
298/// Two backends behind one signature, selected at compile time:
299///
300/// - default, the in-project shape: [`ec_dsp::Fft`] covers the `2^k` factor
301/// and the factor of 15 is one extra decimation stage (3 x 5), so the whole
302/// transform stays `O(n log n)` without a mixed-radix kernel in the DSP
303/// crate;
304/// - under the optional `fft-rustfft` feature, a rustfft plan plans the size
305/// directly (pure Rust, runtime-detected AVX butterflies, no C). The
306/// family's dependency-free build stays the default; the feature is the
307/// measured speed option.
308///
309/// Both deliver the same contract: an UNSCALED inverse transform,
310/// `X[k] = sum x[n] exp(+2 pi i n k / N)`, over split-complex buffers.
311#[cfg(not(feature = "fft-rustfft"))]
312mod fft15 {
313 use super::dft15;
314 use ec_dsp::Fft;
315
316 #[derive(Clone, Debug)]
317 pub(crate) struct Fft15 {
318 n: usize,
319 /// Sub-transform of length `n/15`.
320 sub: Fft<f32>,
321 /// `exp(2 pi i * k1 * n2 / n)` twiddles, split.
322 tw_re: Vec<f32>,
323 tw_im: Vec<f32>,
324 scratch_re: Vec<f32>,
325 scratch_im: Vec<f32>,
326 }
327
328 impl Fft15 {
329 pub(crate) fn new(n: usize) -> Fft15 {
330 assert!(n.is_multiple_of(15) && (n / 15).is_power_of_two());
331 let l = n / 15;
332 let mut tw_re = vec![0.0; n];
333 let mut tw_im = vec![0.0; n];
334 for k1 in 0..15 {
335 for n2 in 0..l {
336 let a = 2.0 * core::f64::consts::PI * (k1 * n2) as f64 / n as f64;
337 tw_re[k1 * l + n2] = a.cos() as f32;
338 tw_im[k1 * l + n2] = a.sin() as f32;
339 }
340 }
341 Fft15 {
342 n,
343 sub: Fft::new(l),
344 tw_re,
345 tw_im,
346 scratch_re: vec![0.0; n],
347 scratch_im: vec![0.0; n],
348 }
349 }
350
351 /// Unscaled inverse transform.
352 pub(crate) fn inverse(&mut self, re: &mut [f32], im: &mut [f32]) {
353 let n = self.n;
354 let l = n / 15;
355 debug_assert_eq!(re.len(), n);
356 // Stage 1: 15-point DFTs over n1 at stride L, twiddled on the way
357 // out.
358 for n2 in 0..l {
359 let mut xr = [0.0f32; 15];
360 let mut xi = [0.0f32; 15];
361 for n1 in 0..15 {
362 xr[n1] = re[l * n1 + n2];
363 xi[n1] = im[l * n1 + n2];
364 }
365 let (yr, yi) = dft15(&xr, &xi);
366 for k1 in 0..15 {
367 let (tr, ti) = (self.tw_re[k1 * l + n2], self.tw_im[k1 * l + n2]);
368 self.scratch_re[k1 * l + n2] = yr[k1] * tr - yi[k1] * ti;
369 self.scratch_im[k1 * l + n2] = yr[k1] * ti + yi[k1] * tr;
370 }
371 }
372 // Stage 2: L-point transforms, one per k1, written out at stride
373 // 15. ec-dsp scales its inverse by 1/L; undo that to keep the
374 // transform unscaled, which is what the MDCT expects.
375 for k1 in 0..15 {
376 let rr = &mut self.scratch_re[k1 * l..(k1 + 1) * l];
377 let ii = &mut self.scratch_im[k1 * l..(k1 + 1) * l];
378 self.sub.inverse_split(rr, ii);
379 for (k2, (&r, &i)) in rr.iter().zip(ii.iter()).enumerate() {
380 re[k1 + 15 * k2] = r * l as f32;
381 im[k1 + 15 * k2] = i * l as f32;
382 }
383 }
384 }
385 }
386}
387
388#[cfg(feature = "fft-rustfft")]
389mod fft15 {
390 use rustfft::num_complex::Complex;
391 use std::sync::Arc;
392
393 #[derive(Clone)]
394 pub(crate) struct Fft15 {
395 n: usize,
396 plan: Arc<dyn rustfft::Fft<f32>>,
397 cbuf: Vec<Complex<f32>>,
398 /// Preallocated once: `process` would allocate this per call, and the
399 /// encoder's steady-state loop is a zero-allocation contract.
400 scratch: Vec<Complex<f32>>,
401 }
402
403 impl core::fmt::Debug for Fft15 {
404 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
405 f.debug_struct("Fft15").field("n", &self.n).finish()
406 }
407 }
408
409 impl Fft15 {
410 pub(crate) fn new(n: usize) -> Fft15 {
411 assert!(n.is_multiple_of(15) && (n / 15).is_power_of_two());
412 let mut planner = rustfft::FftPlanner::<f32>::new();
413 let plan = planner.plan_fft_inverse(n);
414 let cbuf = vec![Complex::ZERO; n];
415 let scratch = vec![Complex::ZERO; plan.get_inplace_scratch_len()];
416 Fft15 {
417 n,
418 plan,
419 cbuf,
420 scratch,
421 }
422 }
423
424 /// Unscaled inverse transform. rustfft does not scale, which is
425 /// exactly the contract here.
426 pub(crate) fn inverse(&mut self, re: &mut [f32], im: &mut [f32]) {
427 for (c, (r, i)) in self.cbuf.iter_mut().zip(re.iter().zip(im.iter())) {
428 *c = Complex::new(*r, *i);
429 }
430 self.plan
431 .process_with_scratch(&mut self.cbuf, &mut self.scratch);
432 for ((c, r), i) in self.cbuf.iter().zip(re.iter_mut()).zip(im.iter_mut()) {
433 *r = c.re;
434 *i = c.im;
435 }
436 }
437 }
438}
439
440pub(crate) use fft15::Fft15;
441
442/// A 15-point DFT as 5 radix-3 stages then 3 radix-5 stages (Cooley-Tukey on
443/// 15 = 3*5), which costs about a third of the direct evaluation.
444#[cfg(not(feature = "fft-rustfft"))]
445#[inline]
446fn dft15(xr: &[f32; 15], xi: &[f32; 15]) -> ([f32; 15], [f32; 15]) {
447 // exp(+2 pi i / 3) and the two fifth-root cosines/sines.
448 const C3: f32 = -0.5;
449 const S3: f32 = 0.866_025_4;
450 const C5_1: f32 = 0.309_017;
451 const S5_1: f32 = 0.951_056_5;
452 const C5_2: f32 = -0.809_017;
453 const S5_2: f32 = 0.587_785_25;
454 // exp(+2 pi i * (n2*k1) / 15) for n2 in 0..5, k1 in 0..3.
455 const TW_RE: [[f32; 3]; 5] = [
456 [1.0, 1.0, 1.0],
457 [1.0, 0.913_545_5, 0.669_130_6],
458 [1.0, 0.669_130_6, -0.104_528_46],
459 [1.0, 0.309_017, -0.809_017],
460 [1.0, -0.104_528_46, -0.978_147_6],
461 ];
462 const TW_IM: [[f32; 3]; 5] = [
463 [0.0, 0.0, 0.0],
464 [0.0, 0.406_736_65, 0.743_144_8],
465 [0.0, 0.743_144_8, 0.994_521_9],
466 [0.0, 0.951_056_5, 0.587_785_25],
467 [0.0, 0.994_521_9, -0.207_911_69],
468 ];
469 // Radix-3 over n1 (stride 5), one per n2.
470 let mut ar = [[0.0f32; 3]; 5];
471 let mut ai = [[0.0f32; 3]; 5];
472 for n2 in 0..5 {
473 let (r0, i0) = (xr[n2], xi[n2]);
474 let (r1, i1) = (xr[5 + n2], xi[5 + n2]);
475 let (r2, i2) = (xr[10 + n2], xi[10 + n2]);
476 let (sr, si) = (r1 + r2, i1 + i2);
477 let (dr, di) = (r1 - r2, i1 - i2);
478 ar[n2][0] = r0 + sr;
479 ai[n2][0] = i0 + si;
480 let (tr, ti) = (r0 + C3 * sr, i0 + C3 * si);
481 // Multiplying (dr, di) by i gives (-di, dr).
482 ar[n2][1] = tr - S3 * di;
483 ai[n2][1] = ti + S3 * dr;
484 ar[n2][2] = tr + S3 * di;
485 ai[n2][2] = ti - S3 * dr;
486 // Twiddle by exp(+2 pi i n2 k1 / 15).
487 for k1 in 1..3 {
488 let (tr, ti) = (TW_RE[n2][k1], TW_IM[n2][k1]);
489 let (r, i) = (ar[n2][k1], ai[n2][k1]);
490 ar[n2][k1] = r * tr - i * ti;
491 ai[n2][k1] = r * ti + i * tr;
492 }
493 }
494 // Radix-5 over n2, one per k1; output index is k1 + 3*k2.
495 let mut yr = [0.0f32; 15];
496 let mut yi = [0.0f32; 15];
497 for k1 in 0..3 {
498 let (r0, i0) = (ar[0][k1], ai[0][k1]);
499 let (r1, i1) = (ar[1][k1], ai[1][k1]);
500 let (r2, i2) = (ar[2][k1], ai[2][k1]);
501 let (r3, i3) = (ar[3][k1], ai[3][k1]);
502 let (r4, i4) = (ar[4][k1], ai[4][k1]);
503 let (s1r, s1i) = (r1 + r4, i1 + i4);
504 let (d1r, d1i) = (r1 - r4, i1 - i4);
505 let (s2r, s2i) = (r2 + r3, i2 + i3);
506 let (d2r, d2i) = (r2 - r3, i2 - i3);
507 yr[k1] = r0 + s1r + s2r;
508 yi[k1] = i0 + s1i + s2i;
509 let (m1r, m1i) = (r0 + C5_1 * s1r + C5_2 * s2r, i0 + C5_1 * s1i + C5_2 * s2i);
510 let (n1r, n1i) = (S5_1 * d1r + S5_2 * d2r, S5_1 * d1i + S5_2 * d2i);
511 let (m2r, m2i) = (r0 + C5_2 * s1r + C5_1 * s2r, i0 + C5_2 * s1i + C5_1 * s2i);
512 let (n2r, n2i) = (S5_2 * d1r - S5_1 * d2r, S5_2 * d1i - S5_1 * d2i);
513 yr[k1 + 3] = m1r - n1i;
514 yi[k1 + 3] = m1i + n1r;
515 yr[k1 + 12] = m1r + n1i;
516 yi[k1 + 12] = m1i - n1r;
517 yr[k1 + 6] = m2r - n2i;
518 yi[k1 + 6] = m2i + n2r;
519 yr[k1 + 9] = m2r + n2i;
520 yi[k1 + 9] = m2i - n2r;
521 }
522 (yr, yi)
523}
524
525/// One inverse-MDCT plan: spectrum length `l = 15 * 2^k`, window `2*l`.
526#[derive(Clone, Debug)]
527struct ImdctPlan {
528 /// Spectrum length.
529 l: usize,
530 fft: Fft15,
531 /// `cos(2 pi (i + 1/8) / (2 l))` and its sine, for the pre/post rotation.
532 rot_re: Vec<f32>,
533 rot_im: Vec<f32>,
534 fre: Vec<f32>,
535 fim: Vec<f32>,
536 out: Vec<f32>,
537}
538
539impl ImdctPlan {
540 fn new(l: usize) -> ImdctPlan {
541 let n = 2 * l;
542 let quarter = l / 2;
543 let mut rot_re = vec![0.0; quarter];
544 let mut rot_im = vec![0.0; quarter];
545 for i in 0..quarter {
546 let a = 2.0 * core::f64::consts::PI * (i as f64 + 0.125) / n as f64;
547 rot_re[i] = a.cos() as f32;
548 rot_im[i] = a.sin() as f32;
549 }
550 ImdctPlan {
551 l,
552 fft: Fft15::new(quarter),
553 rot_re,
554 rot_im,
555 fre: vec![0.0; quarter],
556 fim: vec![0.0; quarter],
557 out: vec![0.0; 2 * l],
558 }
559 }
560
561 /// Transforms `l` coefficients read at `stride` into `l + OVERLAP` windowed
562 /// time samples, added into `out` starting at `out_off`.
563 ///
564 /// The window is the low-overlap one: zero outside a `l + OVERLAP` span,
565 /// which is why the output is that long and not `2*l`.
566 fn inverse(
567 &mut self,
568 spectrum: &[f32],
569 stride: usize,
570 window: &[f32],
571 out: &mut [f32],
572 out_off: usize,
573 ) {
574 let l = self.l;
575 let quarter = l / 2;
576 // Pre-rotation: z[i] = -(x[l-1-2i] + j x[2i]) * exp(j 2pi (i+1/8)/2l).
577 for i in 0..quarter {
578 let a = spectrum[(2 * i) * stride];
579 let b = spectrum[(l - 1 - 2 * i) * stride];
580 let (c, s) = (self.rot_re[i], self.rot_im[i]);
581 self.fre[i] = -(b * c - a * s);
582 self.fim[i] = -(b * s + a * c);
583 }
584 self.fft.inverse(&mut self.fre, &mut self.fim);
585 // Post-rotation by the same angles.
586 for i in 0..quarter {
587 let (re, im) = (self.fre[i], self.fim[i]);
588 let (c, s) = (self.rot_re[i], self.rot_im[i]);
589 self.fre[i] = re * c - im * s;
590 self.fim[i] = im * c + re * s;
591 }
592 // De-shuffle into the time-domain half-window, then mirror for TDAC.
593 // t[] holds the l samples that the window's two halves fold onto.
594 let t = &mut self.out[..l];
595 for i in 0..quarter {
596 t[2 * i] = -self.fre[i];
597 t[2 * i + 1] = self.fim[quarter - 1 - i];
598 }
599 // out is indexed from `out_off - (l - OVERLAP)/2` in the reference;
600 // shift it so the first written sample lands on out_off.
601 // The window is zero outside a span of `l + OVERLAP`, so that is all
602 // that is written: `flat` samples straight through at each end, and
603 // `OVERLAP/2` windowed samples mirrored onto the frame's own tails.
604 let base = out_off;
605 let flat = quarter - OVERLAP / 2;
606 let mirror = quarter + OVERLAP / 2; // index of t[quarter-1] in `out`
607 for i in 0..flat {
608 out[base + mirror - 1 - i] = t[quarter - 1 - i];
609 }
610 for i in flat..quarter {
611 let x = t[quarter - 1 - i];
612 let w = i - flat;
613 out[base + w] -= window[w] * x;
614 out[base + mirror - 1 - i] += window[OVERLAP - 1 - w] * x;
615 }
616 for i in 0..flat {
617 out[base + mirror + i] = t[quarter + i];
618 }
619 for i in flat..quarter {
620 let x = t[quarter + i];
621 let w = i - flat;
622 out[base + l + OVERLAP - 1 - w] = window[w] * x;
623 out[base + mirror + i] = window[OVERLAP - 1 - w] * x;
624 }
625 }
626}
627
628// ---------------------------------------------------------------------------
629// PVQ
630// ---------------------------------------------------------------------------
631
632/// Offsets of each `U` row in the flat table below (`CELT_PVQ_U_ROW`, the
633/// non-custom reference build's layout): row `m` holds `U(m, c)` at index
634/// `PVQ_U_ROW[m] + c` for `c ≥ m`, exploiting the symmetry `U(n, k) = U(k, n)`.
635/// The walks below only ever read entries with `min(n, k) ≤ 14`, which holds
636/// because every entry they read is bounded by `i < V(n, k)` — a bound the
637/// range decode enforces and the cache-bounded allocation guarantees.
638const PVQ_U_ROW: [usize; 16] = [
639 0, 176, 351, 525, 698, 870, 1041, 1131, 1178, 1207, 1226, 1240, 1248, 1254, 1257, 1272,
640];
641const PVQ_U_LEN: usize = PVQ_U_ROW[15];
642
643/// The flat `U` table, computed at compile time from the same recurrence the
644/// row-stepping used, `U(m,c) = U(m-1,c) + U(m,c-1) + U(m-1,c-1)` off
645/// `U(0,0) = 1` (Section 4.3.4.2), in wrapping arithmetic: unreachable entries
646/// wrap exactly as the runtime stepping wrapped.
647const fn compute_pvq_u() -> [u32; PVQ_U_LEN] {
648 // The full triangle for a ≤ 14, b ≤ 176 (the widest standard band),
649 // then scattered so `U(m, c)` sits at `PVQ_U_ROW[m] + c`.
650 let mut uu = [[0u32; 177]; 15];
651 uu[0][0] = 1; // U(0,0)=1; U(0,b>0) = U(a>0,0) = 0.
652 let mut a = 1;
653 while a < 15 {
654 let mut b = 1;
655 while b < 177 {
656 uu[a][b] = uu[a - 1][b].wrapping_add(uu[a][b - 1]).wrapping_add(uu[a - 1][b - 1]);
657 b += 1;
658 }
659 a += 1;
660 }
661 let mut d = [0u32; PVQ_U_LEN];
662 let mut m = 0;
663 while m < 15 {
664 let start = PVQ_U_ROW[m] + m; // raw start of row m
665 let end = if m < 14 {
666 PVQ_U_ROW[m + 1] + (m + 1)
667 } else {
668 PVQ_U_ROW[15]
669 };
670 let mut p = start;
671 while p < end {
672 d[p] = uu[m][p - PVQ_U_ROW[m]];
673 p += 1;
674 }
675 m += 1;
676 }
677 d
678}
679
680static PVQ_U: [u32; PVQ_U_LEN] = compute_pvq_u();
681
682/// `U(n, k)` from the table.
683#[inline]
684pub(crate) fn pvq_u(n: usize, k: usize) -> u32 {
685 let (lo, hi) = if n < k { (n, k) } else { (k, n) };
686 debug_assert!(lo <= 14, "U({n},{k}) outside the reference table");
687 PVQ_U[PVQ_U_ROW[lo] + hi]
688}
689
690/// `V(n, k) = U(n,k) + U(n,k+1)`: the size of the `(n, k)` PVQ codebook.
691#[inline]
692pub(crate) fn pvq_v(n: usize, k: usize) -> u32 {
693 pvq_u(n, k).wrapping_add(pvq_u(n, k + 1))
694}
695
696/// Decodes one PVQ codeword of `k` pulses in `n` dimensions.
697///
698/// The reference Appendix A unranking walk (`cwrsi`), with the `U` row read
699/// from the table instead of stepped one dimension at a time: `O(N)` lookups
700/// rather than `O(N·K)` row arithmetic.
701pub(crate) fn decode_pulses(dec: &mut RangeDecoder, n: usize, k: usize, y: &mut [i32]) {
702 let v = pvq_v(n, k);
703 let mut i = dec.dec_uint(v.max(2));
704 let dims = n;
705 let mut n = n;
706 let mut k = k;
707 for slot in y.iter_mut().take(dims) {
708 if n > 2 {
709 let mut p = pvq_u(n, k + 1);
710 let neg = i >= p;
711 if neg {
712 i -= p;
713 }
714 let k0 = k;
715 p = pvq_u(n, k);
716 while p > i {
717 k -= 1;
718 p = pvq_u(n, k);
719 }
720 i -= p;
721 let mag = (k0 - k) as i32;
722 *slot = if neg { -mag } else { mag };
723 n -= 1;
724 } else if n == 2 {
725 // `U(2, k) = 2k-1` and `U(2, k+1) = 2k+1`: one sign, then the
726 // largest split the index leaves room for.
727 let p = 2 * k as u32 + 1;
728 let neg = i >= p;
729 if neg {
730 i -= p;
731 }
732 let k0 = k;
733 k = ((i + 1) >> 1) as usize;
734 if k != 0 {
735 i -= 2 * k as u32 - 1;
736 }
737 let mag = (k0 - k) as i32;
738 *slot = if neg { -mag } else { mag };
739 n -= 1;
740 } else {
741 // `U(1, k)` is 1 for k ≥ 1 and 0 at k = 0, so `V(1, k) = 2`: the
742 // index is one sign plus a remainder that is already zero here.
743 let neg = i >= 1;
744 if neg {
745 i -= 1;
746 }
747 debug_assert_eq!(i, 0, "PVQ index overrun at the last dimension");
748 *slot = if neg { -(k as i32) } else { k as i32 };
749 }
750 }
751}
752
753// ---------------------------------------------------------------------------
754// Decoder
755// ---------------------------------------------------------------------------
756
757/// Where a band's folding source lives: in the running normalised spectrum, or
758/// in the scratch copy taken before that spectrum is rewritten in place.
759#[derive(Clone, Copy, Debug, PartialEq, Eq)]
760enum Lowband {
761 None,
762 Norm(usize),
763 Scratch(usize),
764}
765
766impl Lowband {
767 fn offset(self, n: usize) -> Lowband {
768 match self {
769 Lowband::None => Lowband::None,
770 Lowband::Norm(l) => Lowband::Norm(l + n),
771 Lowband::Scratch(o) => Lowband::Scratch(o + n),
772 }
773 }
774}
775
776/// Everything one band decode needs; a struct because the recursion changes
777/// only two or three fields at a time.
778#[derive(Clone, Copy, Debug)]
779struct BandArgs {
780 /// Band index.
781 i: usize,
782 /// Offset of the band in the coefficient buffer.
783 x: usize,
784 /// Offset of the second channel, when this is a stereo band.
785 y: Option<usize>,
786 /// Coefficients in the band.
787 n: usize,
788 /// Bits allocated, in 1/8th bits.
789 b: i32,
790 spread: usize,
791 /// Short blocks the band is split over.
792 blocks: usize,
793 intensity: usize,
794 tf_change: i32,
795 lowband: Lowband,
796 /// Recursion depth of the split.
797 level: i32,
798 lm: i32,
799 /// Where to write the normalised band for later folding.
800 lowband_out: Option<usize>,
801 gain: f32,
802 /// Which blocks may be folded into, one bit each.
803 fill: u32,
804}
805
806/// The folding PRNG (`celt_lcg_rand`).
807#[inline]
808fn celt_lcg_rand(seed: u32) -> u32 {
809 seed.wrapping_mul(1664525).wrapping_add(1013904223)
810}
811
812/// Start of a band's pulse-cache row. `lm` is `-1` for a twice-split band.
813pub(crate) fn cache_index(band: usize, lm: i32) -> usize {
814 let row = (lm + 1) as usize;
815 let idx = CACHE_INDEX[row * NB_BANDS + band];
816 debug_assert!(idx >= 0, "no pulse cache for band {band} at LM {lm}");
817 idx.max(0) as usize
818}
819
820#[derive(Clone, Copy, Debug, PartialEq, Eq)]
821pub(crate) struct AllocationResult {
822 pub(crate) coded_bands: usize,
823 pub(crate) intensity: usize,
824 pub(crate) dual_stereo: bool,
825 pub(crate) balance: i32,
826}
827
828enum AllocationMode<'a, 'b> {
829 Decode(&'a mut RangeDecoder<'b>),
830 Encode {
831 enc: &'a mut RangeEncoder,
832 intensity: usize,
833 dual_stereo: bool,
834 prev_coded_bands: usize,
835 },
836}
837
838impl AllocationMode<'_, '_> {
839 fn keep_band(&mut self, j: usize, band_bits: i32, band_width: i32, lm: usize) -> bool {
840 match self {
841 AllocationMode::Decode(dec) => dec.dec_bit_logp(1),
842 AllocationMode::Encode {
843 enc,
844 prev_coded_bands,
845 ..
846 } => {
847 let hysteresis = if j < *prev_coded_bands { 7 } else { 9 };
848 let stay = band_bits > ((hysteresis * band_width) << lm << BITRES) >> 4;
849 enc.enc_bit_logp(stay, 1);
850 stay
851 }
852 }
853 }
854
855 fn code_intensity(&mut self, start: usize, coded_bands: usize, intensity_rsv: i32) -> usize {
856 match self {
857 AllocationMode::Decode(dec) => {
858 if intensity_rsv > 0 {
859 start + dec.dec_uint((coded_bands + 1 - start) as u32) as usize
860 } else {
861 0
862 }
863 }
864 AllocationMode::Encode { enc, intensity, .. } => {
865 if intensity_rsv > 0 {
866 *intensity = (*intensity).min(coded_bands);
867 enc.enc_uint(
868 (*intensity - start) as u32,
869 (coded_bands + 1 - start) as u32,
870 );
871 *intensity
872 } else {
873 *intensity = 0;
874 0
875 }
876 }
877 }
878 }
879
880 fn code_dual_stereo(&mut self, dual_stereo_rsv: i32) -> bool {
881 match self {
882 AllocationMode::Decode(dec) => {
883 if dual_stereo_rsv > 0 {
884 dec.dec_bit_logp(1)
885 } else {
886 false
887 }
888 }
889 AllocationMode::Encode {
890 enc, dual_stereo, ..
891 } => {
892 if dual_stereo_rsv > 0 {
893 enc.enc_bit_logp(*dual_stereo, 1);
894 *dual_stereo
895 } else {
896 *dual_stereo = false;
897 false
898 }
899 }
900 }
901 }
902}
903
904#[allow(clippy::too_many_arguments)]
905pub(crate) fn compute_allocation_decode(
906 dec: &mut RangeDecoder,
907 start: usize,
908 end: usize,
909 alloc_trim: i32,
910 total: i32,
911 c: usize,
912 lm: usize,
913 offsets: &[i32; NB_BANDS],
914 caps: &[i32; NB_BANDS],
915 pulses: &mut [i32; NB_BANDS],
916 fine_quant: &mut [i32; NB_BANDS],
917 fine_priority: &mut [i32; NB_BANDS],
918) -> AllocationResult {
919 compute_allocation_shared(
920 AllocationMode::Decode(dec),
921 start,
922 end,
923 alloc_trim,
924 total,
925 c,
926 lm,
927 offsets,
928 caps,
929 pulses,
930 fine_quant,
931 fine_priority,
932 )
933}
934
935#[allow(clippy::too_many_arguments)]
936pub(crate) fn compute_allocation_encode(
937 enc: &mut RangeEncoder,
938 start: usize,
939 end: usize,
940 alloc_trim: i32,
941 total: i32,
942 c: usize,
943 lm: usize,
944 offsets: &[i32; NB_BANDS],
945 caps: &[i32; NB_BANDS],
946 pulses: &mut [i32; NB_BANDS],
947 fine_quant: &mut [i32; NB_BANDS],
948 fine_priority: &mut [i32; NB_BANDS],
949 intensity: usize,
950 dual_stereo: bool,
951 prev_coded_bands: usize,
952) -> AllocationResult {
953 compute_allocation_shared(
954 AllocationMode::Encode {
955 enc,
956 intensity,
957 dual_stereo,
958 prev_coded_bands,
959 },
960 start,
961 end,
962 alloc_trim,
963 total,
964 c,
965 lm,
966 offsets,
967 caps,
968 pulses,
969 fine_quant,
970 fine_priority,
971 )
972}
973
974#[allow(clippy::too_many_arguments)]
975fn compute_allocation_shared(
976 mut mode: AllocationMode<'_, '_>,
977 start: usize,
978 end: usize,
979 alloc_trim: i32,
980 total: i32,
981 c: usize,
982 lm: usize,
983 offsets: &[i32; NB_BANDS],
984 caps: &[i32; NB_BANDS],
985 pulses: &mut [i32; NB_BANDS],
986 fine_quant: &mut [i32; NB_BANDS],
987 fine_priority: &mut [i32; NB_BANDS],
988) -> AllocationResult {
989 let mut total = total.max(0);
990 let mut skip_start = start;
991 let skip_rsv = if total >= 1 << BITRES { 1 << BITRES } else { 0 };
992 total -= skip_rsv;
993 let mut intensity_rsv = 0;
994 let mut dual_stereo_rsv = 0;
995 if c == 2 {
996 intensity_rsv = LOG2_FRAC[end - start];
997 if intensity_rsv > total {
998 intensity_rsv = 0;
999 } else {
1000 total -= intensity_rsv;
1001 dual_stereo_rsv = if total >= 1 << BITRES { 1 << BITRES } else { 0 };
1002 total -= dual_stereo_rsv;
1003 }
1004 }
1005
1006 let mut thresh = [0i32; NB_BANDS];
1007 let mut trim_offset = [0i32; NB_BANDS];
1008 for j in start..end {
1009 let width = (E_BANDS[j + 1] - E_BANDS[j]) as i32;
1010 thresh[j] = ((c as i32) << BITRES).max((((3 * width) << lm) << BITRES) >> 4);
1011 trim_offset[j] = (c as i32
1012 * width
1013 * (alloc_trim - 5 - lm as i32)
1014 * (end - j - 1) as i32
1015 * (1 << (lm as u32 + BITRES)))
1016 >> 6;
1017 if (width << lm) == 1 {
1018 trim_offset[j] -= (c as i32) << BITRES;
1019 }
1020 }
1021
1022 let mut lo = 1i32;
1023 let mut hi = BAND_ALLOCATION.len() as i32 - 1;
1024 while lo <= hi {
1025 let mid = (lo + hi) >> 1;
1026 let mut psum = 0;
1027 let mut done = false;
1028 for j in (start..end).rev() {
1029 let width = (E_BANDS[j + 1] - E_BANDS[j]) as i32;
1030 let mut bitsj = (c as i32 * width * BAND_ALLOCATION[mid as usize][j] as i32) << lm >> 2;
1031 if bitsj > 0 {
1032 bitsj = 0.max(bitsj + trim_offset[j]);
1033 }
1034 bitsj += offsets[j];
1035 if bitsj >= thresh[j] || done {
1036 done = true;
1037 psum += bitsj.min(caps[j]);
1038 } else if bitsj >= (c as i32) << BITRES {
1039 psum += (c as i32) << BITRES;
1040 }
1041 }
1042 if psum > total {
1043 hi = mid - 1;
1044 } else {
1045 lo = mid + 1;
1046 }
1047 }
1048 let hi = lo;
1049 let lo = lo - 1;
1050
1051 let mut bits1 = [0i32; NB_BANDS];
1052 let mut bits2 = [0i32; NB_BANDS];
1053 for j in start..end {
1054 let width = (E_BANDS[j + 1] - E_BANDS[j]) as i32;
1055 let mut b1 = (c as i32 * width * BAND_ALLOCATION[lo as usize][j] as i32) << lm >> 2;
1056 let mut b2 = if hi as usize >= BAND_ALLOCATION.len() {
1057 caps[j]
1058 } else {
1059 (c as i32 * width * BAND_ALLOCATION[hi as usize][j] as i32) << lm >> 2
1060 };
1061 if b1 > 0 {
1062 b1 = 0.max(b1 + trim_offset[j]);
1063 }
1064 if b2 > 0 {
1065 b2 = 0.max(b2 + trim_offset[j]);
1066 }
1067 if lo > 0 {
1068 b1 += offsets[j];
1069 }
1070 b2 += offsets[j];
1071 if offsets[j] > 0 {
1072 skip_start = j;
1073 }
1074 bits1[j] = b1;
1075 bits2[j] = 0.max(b2 - b1);
1076 }
1077
1078 const ALLOC_STEPS: u32 = 6;
1079 let alloc_floor = (c as i32) << BITRES;
1080 let stereo = c > 1;
1081 let log_m = (lm as i32) << BITRES;
1082
1083 let mut lo = 0i32;
1084 let mut hi = 1i32 << ALLOC_STEPS;
1085 for _ in 0..ALLOC_STEPS {
1086 let mid = (lo + hi) >> 1;
1087 let mut psum = 0;
1088 let mut done = false;
1089 for j in (start..end).rev() {
1090 let tmp = bits1[j] + ((mid * bits2[j]) >> ALLOC_STEPS);
1091 if tmp >= thresh[j] || done {
1092 done = true;
1093 psum += tmp.min(caps[j]);
1094 } else if tmp >= alloc_floor {
1095 psum += alloc_floor;
1096 }
1097 }
1098 if psum > total {
1099 hi = mid;
1100 } else {
1101 lo = mid;
1102 }
1103 }
1104
1105 let mut psum = 0;
1106 let mut done = false;
1107 for j in (start..end).rev() {
1108 let mut tmp = bits1[j] + ((lo * bits2[j]) >> ALLOC_STEPS);
1109 if tmp < thresh[j] && !done {
1110 tmp = if tmp >= alloc_floor { alloc_floor } else { 0 };
1111 } else {
1112 done = true;
1113 }
1114 tmp = tmp.min(caps[j]);
1115 pulses[j] = tmp;
1116 psum += tmp;
1117 }
1118
1119 let mut coded_bands = end;
1120 loop {
1121 let j = coded_bands - 1;
1122 if j <= skip_start {
1123 total += skip_rsv;
1124 break;
1125 }
1126 let mut left = total - psum;
1127 let percoeff = left / (E_BANDS[coded_bands] - E_BANDS[start]) as i32;
1128 left -= (E_BANDS[coded_bands] - E_BANDS[start]) as i32 * percoeff;
1129 let rem = 0.max(left - (E_BANDS[j] - E_BANDS[start]) as i32);
1130 let band_width = (E_BANDS[coded_bands] - E_BANDS[j]) as i32;
1131 let mut band_bits = pulses[j] + percoeff * band_width + rem;
1132 if band_bits >= thresh[j].max(alloc_floor + (1 << BITRES)) {
1133 if mode.keep_band(j, band_bits, band_width, lm) {
1134 break;
1135 }
1136 psum += 1 << BITRES;
1137 band_bits -= 1 << BITRES;
1138 }
1139 psum -= pulses[j] + intensity_rsv;
1140 if intensity_rsv > 0 {
1141 intensity_rsv = LOG2_FRAC[j - start];
1142 }
1143 psum += intensity_rsv;
1144 if band_bits >= alloc_floor {
1145 psum += alloc_floor;
1146 pulses[j] = alloc_floor;
1147 } else {
1148 pulses[j] = 0;
1149 }
1150 coded_bands -= 1;
1151 }
1152
1153 let intensity = mode.code_intensity(start, coded_bands, intensity_rsv);
1154 if intensity <= start {
1155 total += dual_stereo_rsv;
1156 dual_stereo_rsv = 0;
1157 }
1158 let dual_stereo = mode.code_dual_stereo(dual_stereo_rsv);
1159
1160 let mut left = total - psum;
1161 let percoeff = left / (E_BANDS[coded_bands] - E_BANDS[start]) as i32;
1162 left -= (E_BANDS[coded_bands] - E_BANDS[start]) as i32 * percoeff;
1163 for j in start..coded_bands {
1164 pulses[j] += percoeff * (E_BANDS[j + 1] - E_BANDS[j]) as i32;
1165 }
1166 for j in start..coded_bands {
1167 let tmp = left.min((E_BANDS[j + 1] - E_BANDS[j]) as i32);
1168 pulses[j] += tmp;
1169 left -= tmp;
1170 }
1171
1172 let mut balance = 0i32;
1173 for j in start..coded_bands {
1174 let n0 = (E_BANDS[j + 1] - E_BANDS[j]) as i32;
1175 let n = n0 << lm;
1176 pulses[j] += balance;
1177 let mut excess;
1178 if n > 1 {
1179 excess = 0.max(pulses[j] - caps[j]);
1180 pulses[j] -= excess;
1181 let den = c as i32 + 0;
1182 let den = den * n + i32::from(c == 2 && n > 2 && !dual_stereo && j < intensity);
1183 let nc_log_n = den * (LOG_N[j] + log_m);
1184 let mut offset = (nc_log_n >> 1) - den * FINE_OFFSET;
1185 if n == 2 {
1186 offset += den << BITRES >> 2;
1187 }
1188 if pulses[j] + offset < (den * 2) << BITRES {
1189 offset += nc_log_n >> 2;
1190 } else if pulses[j] + offset < (den * 3) << BITRES {
1191 offset += nc_log_n >> 3;
1192 }
1193 let mut eb = 0.max((pulses[j] + offset + (den << (BITRES - 1))) / (den << BITRES));
1194 if c as i32 * eb > (pulses[j] >> BITRES) {
1195 eb = pulses[j] >> u32::from(stereo) >> BITRES;
1196 }
1197 eb = eb.min(MAX_FINE_BITS);
1198 fine_quant[j] = eb;
1199 fine_priority[j] = i32::from(eb * (den << BITRES) >= pulses[j] + offset);
1200 pulses[j] -= (c as i32 * eb) << BITRES;
1201 } else {
1202 excess = 0.max(pulses[j] - ((c as i32) << BITRES));
1203 pulses[j] -= excess;
1204 fine_quant[j] = 0;
1205 fine_priority[j] = 1;
1206 }
1207 if excess > 0 {
1208 let extra_fine =
1209 (excess >> (u32::from(stereo) + BITRES)).min(MAX_FINE_BITS - fine_quant[j]);
1210 fine_quant[j] += extra_fine;
1211 let extra_bits = (extra_fine * c as i32) << BITRES;
1212 fine_priority[j] = i32::from(extra_bits >= excess - balance);
1213 excess -= extra_bits;
1214 }
1215 balance = excess;
1216 }
1217 for j in coded_bands..end {
1218 fine_quant[j] = pulses[j] >> u32::from(stereo) >> BITRES;
1219 pulses[j] = 0;
1220 fine_priority[j] = i32::from(fine_quant[j] < 1);
1221 }
1222
1223 AllocationResult {
1224 coded_bands,
1225 intensity,
1226 dual_stereo,
1227 balance,
1228 }
1229}
1230
1231/// Facts about the last decoded frame, for diagnostics.
1232#[derive(Clone, Debug)]
1233pub struct CeltDecDiag {
1234 /// The frame was coded as CELT digital silence.
1235 pub silence: bool,
1236 /// Coarse energies used the intra-frame reset.
1237 pub intra: bool,
1238 /// Short-block (transient) frame as coded.
1239 pub transient: bool,
1240 /// Packet bits the range decoder saw for this frame.
1241 pub total_bits: i32,
1242 /// Decoded log2 band energies after fine bits, per channel (`2*NB_BANDS`).
1243 pub old_band_e: Vec<f32>,
1244 /// Time-frequency resolution change per band after `tf_select`.
1245 pub tf_res: Vec<i32>,
1246 /// Spreading decision as coded (0..3).
1247 pub spread: usize,
1248 /// Anti-collapse flag as coded.
1249 pub anti_collapse: bool,
1250 /// Allocation trim index as coded (0..10).
1251 pub alloc_trim: i32,
1252 /// Per-band allocated pulses after `compute_allocation`.
1253 pub pulses: Vec<i32>,
1254 /// Per-band fine-energy precision bits.
1255 pub fine_quant: Vec<i32>,
1256 /// Stereo intensity band (bands >= this collapse to mono).
1257 pub intensity: usize,
1258 /// Dual-stereo flag as coded.
1259 pub dual_stereo: bool,
1260 /// Highest band actually allocated pulses (`codedBands`).
1261 pub coded_bands: usize,
1262 /// Bit balance left after allocation, in 1/8-bit units.
1263 pub balance: i32,
1264 /// Decoded dynalloc band boosts (1/8-bit units).
1265 pub offsets: Vec<i32>,
1266}
1267
1268/// A CELT layer decoder, one per Opus stream.
1269#[derive(Clone, Debug)]
1270pub struct CeltDecoder {
1271 /// Channels this decoder outputs.
1272 channels: usize,
1273 /// Output decimation: 1 at 48 kHz, 2 at 24 kHz, and so on.
1274 downsample: usize,
1275 window: Vec<f32>,
1276 plans: Vec<ImdctPlan>,
1277 /// Synthesis history, `channels * DECODE_BUFFER`.
1278 decode_mem: Vec<f32>,
1279 /// MDCT overlap tail, `channels * OVERLAP`.
1280 overlap_mem: Vec<f32>,
1281 preemph_mem: [f32; 2],
1282 old_band_e: Vec<f32>,
1283 old_log_e: Vec<f32>,
1284 old_log_e2: Vec<f32>,
1285 background_log_e: Vec<f32>,
1286 postfilter_period: usize,
1287 postfilter_period_old: usize,
1288 postfilter_gain: f32,
1289 postfilter_gain_old: f32,
1290 postfilter_tapset: usize,
1291 postfilter_tapset_old: usize,
1292 /// The folding PRNG state, carried between frames.
1293 rng: u32,
1294 // Per-frame scratch, allocated once.
1295 x: Vec<f32>,
1296 freq: Vec<f32>,
1297 norm: Vec<f32>,
1298 lowband_scratch: Vec<f32>,
1299 hadamard_tmp: Vec<f32>,
1300 band_e: Vec<f32>,
1301 pulses: [i32; NB_BANDS],
1302 fine_quant: [i32; NB_BANDS],
1303 fine_priority: [i32; NB_BANDS],
1304 offsets: [i32; NB_BANDS],
1305 caps: [i32; NB_BANDS],
1306 tf_res: [i32; NB_BANDS],
1307 collapse_masks: [u8; 2 * NB_BANDS],
1308 iy: Vec<i32>,
1309 mdct_buf: Vec<f32>,
1310 diag: CeltDecDiag,
1311}
1312
1313impl CeltDecoder {
1314 /// A decoder producing `channels` channels at `48000/downsample` Hz.
1315 pub fn new(channels: usize, downsample: usize) -> CeltDecoder {
1316 assert!((1..=2).contains(&channels));
1317 let max_n = SHORT_MDCT * 8;
1318 CeltDecoder {
1319 channels,
1320 downsample,
1321 window: overlap_window(),
1322 plans: (0..4).map(|lm| ImdctPlan::new(SHORT_MDCT << lm)).collect(),
1323 decode_mem: vec![0.0; channels * DECODE_BUFFER],
1324 overlap_mem: vec![0.0; channels * OVERLAP],
1325 preemph_mem: [0.0; 2],
1326 old_band_e: vec![0.0; 2 * NB_BANDS],
1327 old_log_e: vec![-28.0; 2 * NB_BANDS],
1328 old_log_e2: vec![-28.0; 2 * NB_BANDS],
1329 background_log_e: vec![-28.0; 2 * NB_BANDS],
1330 postfilter_period: 0,
1331 postfilter_period_old: 0,
1332 postfilter_gain: 0.0,
1333 postfilter_gain_old: 0.0,
1334 postfilter_tapset: 0,
1335 postfilter_tapset_old: 0,
1336 rng: 0,
1337 x: vec![0.0; 2 * max_n],
1338 freq: vec![0.0; 2 * max_n],
1339 norm: vec![0.0; 2 * max_n],
1340 lowband_scratch: vec![0.0; max_n],
1341 hadamard_tmp: vec![0.0; max_n],
1342 band_e: vec![0.0; 2 * NB_BANDS],
1343 pulses: [0; NB_BANDS],
1344 fine_quant: [0; NB_BANDS],
1345 fine_priority: [0; NB_BANDS],
1346 offsets: [0; NB_BANDS],
1347 caps: [0; NB_BANDS],
1348 tf_res: [0; NB_BANDS],
1349 collapse_masks: [0; 2 * NB_BANDS],
1350 iy: vec![0; max_n],
1351 mdct_buf: vec![0.0; max_n + OVERLAP],
1352 diag: CeltDecDiag {
1353 silence: false,
1354 intra: false,
1355 transient: false,
1356 total_bits: 0,
1357 old_band_e: vec![0.0; 2 * NB_BANDS],
1358 tf_res: Vec::new(),
1359 spread: 0,
1360 anti_collapse: false,
1361 alloc_trim: 0,
1362 pulses: vec![0; NB_BANDS],
1363 fine_quant: vec![0; NB_BANDS],
1364 intensity: 0,
1365 dual_stereo: false,
1366 coded_bands: 0,
1367 balance: 0,
1368 offsets: vec![0; NB_BANDS],
1369 },
1370 }
1371 }
1372
1373 /// Drops all inter-frame state (after a seek, or on a mode switch).
1374 pub fn reset(&mut self) {
1375 self.decode_mem.fill(0.0);
1376 self.overlap_mem.fill(0.0);
1377 self.preemph_mem = [0.0; 2];
1378 self.old_band_e.fill(0.0);
1379 self.old_log_e.fill(-28.0);
1380 self.old_log_e2.fill(-28.0);
1381 self.background_log_e.fill(-28.0);
1382 self.postfilter_period = 0;
1383 self.postfilter_period_old = 0;
1384 self.postfilter_gain = 0.0;
1385 self.postfilter_gain_old = 0.0;
1386 self.postfilter_tapset = 0;
1387 self.postfilter_tapset_old = 0;
1388 self.rng = 0;
1389 }
1390
1391 /// The range decoder state after the last frame — the test vectors' oracle.
1392 pub fn rng(&self) -> u32 {
1393 self.rng
1394 }
1395
1396 /// Facts from the last decoded frame (diagnostic).
1397 pub fn last_diag(&self) -> &CeltDecDiag {
1398 &self.diag
1399 }
1400
1401 /// Decodes one CELT frame.
1402 ///
1403 /// `frame_size` is in 48 kHz samples; `start`/`end` bound the coded bands
1404 /// (17..21 for the CELT half of a hybrid frame); `stream_channels` is what
1405 /// the bitstream codes, which may be 1 while the decoder outputs 2.
1406 /// `out` receives `channels * frame_size / downsample` interleaved samples.
1407 #[allow(clippy::too_many_arguments)]
1408 pub fn decode(
1409 &mut self,
1410 dec: &mut RangeDecoder,
1411 out: &mut [f32],
1412 frame_size: usize,
1413 start: usize,
1414 end: usize,
1415 stream_channels: usize,
1416 ) -> Result<()> {
1417 let lm = match frame_size {
1418 120 => 0,
1419 240 => 1,
1420 480 => 2,
1421 960 => 3,
1422 _ => {
1423 return Err(Error::corrupt(format!(
1424 "celt: frame size {frame_size} is not 120, 240, 480 or 960"
1425 )));
1426 }
1427 };
1428 let m = 1usize << lm;
1429 let n = m * SHORT_MDCT;
1430 let cc = self.channels;
1431 let c = stream_channels;
1432 let eff_end = end.min(NB_BANDS);
1433 let len = dec.len();
1434 let total_bits = (len * 8) as i32;
1435
1436 // A mono stream fed to a stereo decoder inherits the louder history.
1437 if c == 1 {
1438 for i in 0..NB_BANDS {
1439 self.old_band_e[i] = self.old_band_e[i].max(self.old_band_e[NB_BANDS + i]);
1440 }
1441 }
1442
1443 for ch in 0..c {
1444 self.x[ch * n..ch * n + m * E_BANDS[start]].fill(0.0);
1445 self.x[ch * n + m * E_BANDS[eff_end]..(ch + 1) * n].fill(0.0);
1446 }
1447
1448 let mut tell = dec.tell() as i32;
1449 let silence = if tell >= total_bits {
1450 true
1451 } else if tell == 1 {
1452 dec.dec_bit_logp(15)
1453 } else {
1454 false
1455 };
1456 if silence {
1457 // Pretend the frame was fully consumed (Section 4.3).
1458 dec.skip_to_end();
1459 tell = total_bits;
1460 }
1461
1462 let mut postfilter_gain = 0.0f32;
1463 let mut postfilter_pitch = 0usize;
1464 let mut postfilter_tapset = 0usize;
1465 if start == 0 && tell + 16 <= total_bits {
1466 if dec.dec_bit_logp(1) {
1467 let octave = dec.dec_uint(6) as usize;
1468 postfilter_pitch = (16 << octave) + dec.dec_bits(4 + octave as u32) as usize - 1;
1469 let qg = dec.dec_bits(3);
1470 if dec.tell() as i32 + 2 <= total_bits {
1471 postfilter_tapset = dec.dec_icdf(&TAPSET_ICDF, 2);
1472 }
1473 postfilter_gain = 0.09375 * (qg + 1) as f32;
1474 }
1475 tell = dec.tell() as i32;
1476 }
1477
1478 let transient = if lm > 0 && tell + 3 <= total_bits {
1479 let t = dec.dec_bit_logp(3);
1480 tell = dec.tell() as i32;
1481 t
1482 } else {
1483 false
1484 };
1485 let short_blocks = if transient { m } else { 0 };
1486
1487 let intra = if tell + 3 <= total_bits {
1488 dec.dec_bit_logp(3)
1489 } else {
1490 false
1491 };
1492 self.unquant_coarse_energy(dec, start, end, intra, c, lm, len);
1493 self.tf_decode(dec, start, end, transient, lm, len);
1494
1495 tell = dec.tell() as i32;
1496 let spread = if tell + 4 <= total_bits {
1497 dec.dec_icdf(&SPREAD_ICDF, 5)
1498 } else {
1499 SPREAD_NORMAL
1500 };
1501
1502 // Per-band allocation ceiling.
1503 for i in 0..NB_BANDS {
1504 let bw = (E_BANDS[i + 1] - E_BANDS[i]) << lm;
1505 self.caps[i] =
1506 ((CACHE_CAPS[NB_BANDS * (2 * lm + c - 1) + i] as i32 + 64) * c as i32 * bw as i32)
1507 >> 2;
1508 }
1509
1510 // Band boosts (dynalloc).
1511 let mut dynalloc_logp = 6u32;
1512 let mut total_bits_frac = total_bits << BITRES;
1513 let mut tell_frac = dec.tell_frac() as i32;
1514 self.offsets.fill(0);
1515 for i in start..end {
1516 let width = ((c * (E_BANDS[i + 1] - E_BANDS[i])) << lm) as i32;
1517 let quanta = (width << BITRES).min((6 << BITRES).max(width));
1518 let mut loop_logp = dynalloc_logp;
1519 let mut boost = 0;
1520 while tell_frac + ((loop_logp as i32) << BITRES) < total_bits_frac
1521 && boost < self.caps[i]
1522 {
1523 let flag = dec.dec_bit_logp(loop_logp);
1524 tell_frac = dec.tell_frac() as i32;
1525 if !flag {
1526 break;
1527 }
1528 boost += quanta;
1529 total_bits_frac -= quanta;
1530 loop_logp = 1;
1531 }
1532 self.offsets[i] = boost;
1533 if boost > 0 {
1534 dynalloc_logp = dynalloc_logp.saturating_sub(1).max(2);
1535 }
1536 }
1537
1538 let alloc_trim = if tell_frac + (6 << BITRES) <= total_bits_frac {
1539 dec.dec_icdf(&TRIM_ICDF, 7) as i32
1540 } else {
1541 5
1542 };
1543
1544 let mut bits = ((len as i32 * 8) << BITRES) - dec.tell_frac() as i32 - 1;
1545 let anti_collapse_rsv = if transient && lm >= 2 && bits >= ((lm as i32 + 2) << BITRES) {
1546 1 << BITRES
1547 } else {
1548 0
1549 };
1550 bits -= anti_collapse_rsv;
1551
1552 let alloc = compute_allocation_decode(
1553 dec,
1554 start,
1555 end,
1556 alloc_trim,
1557 bits,
1558 c,
1559 lm,
1560 &self.offsets,
1561 &self.caps,
1562 &mut self.pulses,
1563 &mut self.fine_quant,
1564 &mut self.fine_priority,
1565 );
1566 let intensity = alloc.intensity;
1567 let dual_stereo = alloc.dual_stereo;
1568 let balance = alloc.balance;
1569 let coded_bands = alloc.coded_bands;
1570
1571 self.unquant_fine_energy(dec, start, end, c);
1572
1573 self.quant_all_bands(
1574 dec,
1575 start,
1576 end,
1577 short_blocks,
1578 spread,
1579 dual_stereo,
1580 intensity,
1581 (len as i32 * (8 << BITRES)) - anti_collapse_rsv,
1582 balance,
1583 lm,
1584 coded_bands,
1585 c,
1586 n,
1587 );
1588
1589 let anti_collapse_on = if anti_collapse_rsv > 0 {
1590 dec.dec_bits(1) != 0
1591 } else {
1592 false
1593 };
1594
1595 let bits_left = len as i32 * 8 - dec.tell() as i32;
1596 self.unquant_energy_finalise(dec, start, end, bits_left, c);
1597
1598 if anti_collapse_on {
1599 self.anti_collapse(lm, c, n, start, end);
1600 }
1601
1602 // log2 energy back to linear amplitude.
1603 for ch in 0..c {
1604 for (i, mean) in E_MEANS.iter().enumerate() {
1605 self.band_e[ch * NB_BANDS + i] = if i < start || i >= end {
1606 0.0
1607 } else {
1608 ((self.old_band_e[ch * NB_BANDS + i] + mean) as f64).exp2() as f32
1609 };
1610 }
1611 }
1612 if silence {
1613 self.band_e.fill(0.0);
1614 self.old_band_e.fill(-28.0);
1615 }
1616
1617 self.denormalise_bands(eff_end, c, m, n);
1618
1619 // Slide the synthesis history and run the inverse MDCT into it.
1620 for ch in 0..cc {
1621 let base = ch * DECODE_BUFFER;
1622 self.decode_mem
1623 .copy_within(base + n..base + DECODE_BUFFER, base);
1624 }
1625 for ch in 0..c {
1626 self.freq[ch * n..ch * n + m * E_BANDS[start]].fill(0.0);
1627 let bound = (m * E_BANDS[eff_end]).min(n / self.downsample);
1628 self.freq[ch * n + bound..(ch + 1) * n].fill(0.0);
1629 }
1630 if cc == 2 && c == 1 {
1631 let (a, b) = self.freq.split_at_mut(n);
1632 b[..n].copy_from_slice(&a[..n]);
1633 }
1634 if cc == 1 && c == 2 {
1635 for i in 0..n {
1636 self.freq[i] = 0.5 * (self.freq[i] + self.freq[n + i]);
1637 }
1638 }
1639 self.inverse_mdcts(short_blocks, lm, n, cc);
1640
1641 // Post-filter, then de-emphasis into the caller's buffer.
1642 self.postfilter_period = self.postfilter_period.max(MIN_PERIOD);
1643 self.postfilter_period_old = self.postfilter_period_old.max(MIN_PERIOD);
1644 for ch in 0..cc {
1645 let base = ch * DECODE_BUFFER + DECODE_BUFFER - n;
1646 self.comb_filter(
1647 base,
1648 SHORT_MDCT.min(n),
1649 self.postfilter_period_old,
1650 self.postfilter_period,
1651 self.postfilter_gain_old,
1652 self.postfilter_gain,
1653 self.postfilter_tapset_old,
1654 self.postfilter_tapset,
1655 true,
1656 );
1657 if lm != 0 {
1658 self.comb_filter(
1659 base + SHORT_MDCT,
1660 n - SHORT_MDCT,
1661 self.postfilter_period,
1662 postfilter_pitch.max(MIN_PERIOD),
1663 self.postfilter_gain,
1664 postfilter_gain,
1665 self.postfilter_tapset,
1666 postfilter_tapset,
1667 true,
1668 );
1669 }
1670 }
1671 self.postfilter_period_old = self.postfilter_period;
1672 self.postfilter_gain_old = self.postfilter_gain;
1673 self.postfilter_tapset_old = self.postfilter_tapset;
1674 self.postfilter_period = postfilter_pitch;
1675 self.postfilter_gain = postfilter_gain;
1676 self.postfilter_tapset = postfilter_tapset;
1677 if lm != 0 {
1678 self.postfilter_period_old = self.postfilter_period;
1679 self.postfilter_gain_old = self.postfilter_gain;
1680 self.postfilter_tapset_old = self.postfilter_tapset;
1681 }
1682
1683 // Energy history for the next frame's prediction and anti-collapse.
1684 if c == 1 {
1685 for i in 0..NB_BANDS {
1686 self.old_band_e[NB_BANDS + i] = self.old_band_e[i];
1687 }
1688 }
1689 if !transient {
1690 self.old_log_e2.copy_from_slice(&self.old_log_e);
1691 self.old_log_e.copy_from_slice(&self.old_band_e);
1692 for i in 0..2 * NB_BANDS {
1693 self.background_log_e[i] =
1694 (self.background_log_e[i] + m as f32 * 0.001).min(self.old_band_e[i]);
1695 }
1696 } else {
1697 for i in 0..2 * NB_BANDS {
1698 self.old_log_e[i] = self.old_log_e[i].min(self.old_band_e[i]);
1699 }
1700 }
1701 for ch in 0..2 {
1702 for i in (0..start).chain(end..NB_BANDS) {
1703 self.old_band_e[ch * NB_BANDS + i] = 0.0;
1704 self.old_log_e[ch * NB_BANDS + i] = -28.0;
1705 self.old_log_e2[ch * NB_BANDS + i] = -28.0;
1706 }
1707 }
1708 self.diag = CeltDecDiag {
1709 silence,
1710 intra,
1711 transient,
1712 total_bits,
1713 old_band_e: self.old_band_e.clone(),
1714 tf_res: self.tf_res.to_vec(),
1715 spread,
1716 anti_collapse: anti_collapse_on,
1717 alloc_trim,
1718 pulses: self.pulses.to_vec(),
1719 fine_quant: self.fine_quant.to_vec(),
1720 intensity,
1721 dual_stereo,
1722 coded_bands,
1723 balance,
1724 offsets: self.offsets.to_vec(),
1725 };
1726 self.rng = dec.range();
1727
1728 self.deemphasis(out, n, cc);
1729 Ok(())
1730 }
1731
1732 #[allow(clippy::too_many_arguments)]
1733 fn unquant_coarse_energy(
1734 &mut self,
1735 dec: &mut RangeDecoder,
1736 start: usize,
1737 end: usize,
1738 intra: bool,
1739 c: usize,
1740 lm: usize,
1741 len: usize,
1742 ) {
1743 let model = &E_PROB_MODEL[lm][usize::from(intra)];
1744 let (coef, beta) = if intra {
1745 (0.0, BETA_INTRA)
1746 } else {
1747 (PRED_COEF[lm], BETA_COEF[lm])
1748 };
1749 let budget = (len * 8) as i32;
1750 let mut prev = [0.0f32; 2];
1751 for i in start..end {
1752 for (ch, prev) in prev.iter_mut().enumerate().take(c) {
1753 let tell = dec.tell() as i32;
1754 let qi = if budget - tell >= 15 {
1755 let pi = 2 * i.min(20);
1756 laplace_decode(dec, (model[pi] as u32) << 7, (model[pi + 1] as i32) << 6)
1757 } else if budget - tell >= 2 {
1758 let qi = dec.dec_icdf(&SMALL_ENERGY_ICDF, 2) as i32;
1759 (qi >> 1) ^ -(qi & 1)
1760 } else if budget - tell >= 1 {
1761 -i32::from(dec.dec_bit_logp(1))
1762 } else {
1763 -1
1764 };
1765 let q = qi as f32;
1766 let old = &mut self.old_band_e[i + ch * NB_BANDS];
1767 *old = old.max(-9.0);
1768 *old = coef * *old + *prev + q;
1769 *prev += q - beta * q;
1770 }
1771 }
1772 }
1773
1774 fn unquant_fine_energy(&mut self, dec: &mut RangeDecoder, start: usize, end: usize, c: usize) {
1775 for i in start..end {
1776 if self.fine_quant[i] <= 0 {
1777 continue;
1778 }
1779 for ch in 0..c {
1780 let q2 = dec.dec_bits(self.fine_quant[i] as u32);
1781 let offset = (q2 as f32 + 0.5) / (1 << self.fine_quant[i]) as f32 - 0.5;
1782 self.old_band_e[i + ch * NB_BANDS] += offset;
1783 }
1784 }
1785 }
1786
1787 fn unquant_energy_finalise(
1788 &mut self,
1789 dec: &mut RangeDecoder,
1790 start: usize,
1791 end: usize,
1792 mut bits_left: i32,
1793 c: usize,
1794 ) {
1795 for prio in 0..2 {
1796 for i in start..end {
1797 if bits_left < c as i32 {
1798 break;
1799 }
1800 if self.fine_quant[i] >= MAX_FINE_BITS || self.fine_priority[i] != prio {
1801 continue;
1802 }
1803 for ch in 0..c {
1804 let q2 = dec.dec_bits(1);
1805 let offset = (q2 as f32 - 0.5) / (1 << (self.fine_quant[i] + 1)) as f32;
1806 self.old_band_e[i + ch * NB_BANDS] += offset;
1807 bits_left -= 1;
1808 }
1809 }
1810 }
1811 }
1812
1813 #[allow(clippy::too_many_arguments)]
1814 fn tf_decode(
1815 &mut self,
1816 dec: &mut RangeDecoder,
1817 start: usize,
1818 end: usize,
1819 transient: bool,
1820 lm: usize,
1821 len: usize,
1822 ) {
1823 let mut budget = (len * 8) as i32;
1824 let mut tell = dec.tell() as i32;
1825 let mut logp: u32 = if transient { 2 } else { 4 };
1826 let tf_select_rsv = lm > 0 && tell + (logp as i32) < budget;
1827 budget -= i32::from(tf_select_rsv);
1828 let mut curr = 0i32;
1829 let mut changed = false;
1830 for i in start..end {
1831 if tell + logp as i32 <= budget {
1832 curr ^= i32::from(dec.dec_bit_logp(logp));
1833 tell = dec.tell() as i32;
1834 changed |= curr != 0;
1835 }
1836 self.tf_res[i] = curr;
1837 logp = if transient { 4 } else { 5 };
1838 }
1839 let t = usize::from(transient);
1840 let ch = usize::from(changed);
1841 let mut tf_select = 0usize;
1842 if tf_select_rsv && TF_SELECT[lm][4 * t + ch] != TF_SELECT[lm][4 * t + 2 + ch] {
1843 tf_select = usize::from(dec.dec_bit_logp(1));
1844 }
1845 for i in start..end {
1846 self.tf_res[i] = TF_SELECT[lm][4 * t + 2 * tf_select + self.tf_res[i] as usize];
1847 }
1848 }
1849
1850 #[allow(clippy::too_many_arguments)]
1851 fn quant_all_bands(
1852 &mut self,
1853 dec: &mut RangeDecoder,
1854 start: usize,
1855 end: usize,
1856 short_blocks: usize,
1857 spread: usize,
1858 mut dual_stereo: bool,
1859 intensity: usize,
1860 total_bits: i32,
1861 mut balance: i32,
1862 lm: usize,
1863 coded_bands: usize,
1864 c: usize,
1865 n: usize,
1866 ) {
1867 let m = 1usize << lm;
1868 let blocks = if short_blocks != 0 { m } else { 1 };
1869 let norm_len = m * E_BANDS[NB_BANDS];
1870 let mut lowband_offset = 0usize;
1871 let mut update_lowband = true;
1872 self.collapse_masks.fill(0);
1873
1874 for i in start..end {
1875 let n_band = m * E_BANDS[i + 1] - m * E_BANDS[i];
1876 let tell = dec.tell_frac() as i32;
1877 if i != start {
1878 balance -= tell;
1879 }
1880 let mut remaining_bits = total_bits - tell - 1;
1881 let b = if i < coded_bands {
1882 let curr_balance = balance / 3.min(coded_bands - i) as i32;
1883 0.max(16383.min((remaining_bits + 1).min(self.pulses[i] + curr_balance)))
1884 } else {
1885 0
1886 };
1887
1888 if m * E_BANDS[i] >= m * E_BANDS[start] + n_band
1889 && (update_lowband || lowband_offset == 0)
1890 {
1891 lowband_offset = i;
1892 }
1893
1894 let tf_change = self.tf_res[i];
1895 // Which already-decoded bands this one may fold from, and whether
1896 // they had any pulses at all (the collapse mask).
1897 let (mut x_cm, mut y_cm);
1898 let mut effective_lowband: Option<usize> = None;
1899 if lowband_offset != 0 && (spread != SPREAD_AGGRESSIVE || blocks > 1 || tf_change < 0) {
1900 let low =
1901 (m * E_BANDS[start]).max((m * E_BANDS[lowband_offset]).saturating_sub(n_band));
1902 effective_lowband = Some(low);
1903 let mut fold_start = lowband_offset;
1904 loop {
1905 fold_start -= 1;
1906 if m * E_BANDS[fold_start] <= low {
1907 break;
1908 }
1909 }
1910 let mut fold_end = lowband_offset - 1;
1911 loop {
1912 fold_end += 1;
1913 if m * E_BANDS[fold_end] >= low + n_band {
1914 break;
1915 }
1916 }
1917 x_cm = 0;
1918 y_cm = 0;
1919 let mut fi = fold_start;
1920 loop {
1921 x_cm |= self.collapse_masks[fi * c] as u32;
1922 y_cm |= self.collapse_masks[fi * c + c - 1] as u32;
1923 fi += 1;
1924 if fi >= fold_end {
1925 break;
1926 }
1927 }
1928 } else {
1929 x_cm = (1u32 << blocks) - 1;
1930 y_cm = x_cm;
1931 }
1932
1933 if dual_stereo && i == intensity {
1934 // Switch off dual stereo to do intensity from here up.
1935 dual_stereo = false;
1936 for j in m * E_BANDS[start]..m * E_BANDS[i] {
1937 self.norm[j] = 0.5 * (self.norm[j] + self.norm[norm_len + j]);
1938 }
1939 }
1940
1941 let x_off = m * E_BANDS[i];
1942 let base = BandArgs {
1943 i,
1944 x: x_off,
1945 y: None,
1946 n: n_band,
1947 b,
1948 spread,
1949 blocks,
1950 intensity,
1951 tf_change,
1952 lowband: Lowband::None,
1953 level: 0,
1954 lm: lm as i32,
1955 lowband_out: Some(x_off),
1956 gain: 1.0,
1957 fill: 0,
1958 };
1959 if dual_stereo {
1960 x_cm = self.quant_band(
1961 dec,
1962 BandArgs {
1963 b: b / 2,
1964 lowband: effective_lowband.map_or(Lowband::None, Lowband::Norm),
1965 fill: x_cm,
1966 ..base
1967 },
1968 &mut remaining_bits,
1969 );
1970 y_cm = self.quant_band(
1971 dec,
1972 BandArgs {
1973 x: n + x_off,
1974 b: b / 2,
1975 lowband: effective_lowband
1976 .map_or(Lowband::None, |l| Lowband::Norm(norm_len + l)),
1977 lowband_out: Some(norm_len + x_off),
1978 fill: y_cm,
1979 ..base
1980 },
1981 &mut remaining_bits,
1982 );
1983 } else {
1984 x_cm = self.quant_band(
1985 dec,
1986 BandArgs {
1987 y: if c == 2 { Some(n + x_off) } else { None },
1988 lowband: effective_lowband.map_or(Lowband::None, Lowband::Norm),
1989 fill: x_cm | y_cm,
1990 ..base
1991 },
1992 &mut remaining_bits,
1993 );
1994 y_cm = x_cm;
1995 }
1996 self.collapse_masks[i * c] = x_cm as u8;
1997 self.collapse_masks[i * c + c - 1] = y_cm as u8;
1998 balance += self.pulses[i] + tell;
1999 // Keep folding from this band only while it has a bit per sample.
2000 update_lowband = b > (n_band as i32) << BITRES;
2001 }
2002 }
2003
2004 /// Decodes one band (Section 4.3.4), recursing for splits and for stereo.
2005 fn quant_band(&mut self, dec: &mut RangeDecoder, a: BandArgs, remaining_bits: &mut i32) -> u32 {
2006 let BandArgs {
2007 i,
2008 x,
2009 mut y,
2010 mut n,
2011 mut b,
2012 spread,
2013 mut blocks,
2014 intensity,
2015 mut tf_change,
2016 mut lowband,
2017 level,
2018 mut lm,
2019 lowband_out,
2020 gain,
2021 mut fill,
2022 } = a;
2023 let n0 = n;
2024 let mut n_b = n;
2025 let stereo = y.is_some();
2026 let mut split = stereo;
2027 let mut inv = false;
2028 let mut cm: u32 = 0;
2029 let mut time_divide = 0;
2030 let mut recombine = 0usize;
2031 let long_blocks = blocks == 1;
2032
2033 n_b /= blocks;
2034 let mut n_b0 = n_b;
2035 let mut b0 = blocks;
2036
2037 if n == 1 {
2038 // A single coefficient carries nothing but its sign.
2039 for offs in [Some(x), y].into_iter().flatten() {
2040 let mut sign = false;
2041 if *remaining_bits >= 1 << BITRES {
2042 sign = dec.dec_bits(1) != 0;
2043 *remaining_bits -= 1 << BITRES;
2044 }
2045 self.x[offs] = if sign { -1.0 } else { 1.0 };
2046 }
2047 if let Some(o) = lowband_out {
2048 self.norm[o] = self.x[x];
2049 }
2050 return 1;
2051 }
2052
2053 if !stereo && level == 0 {
2054 if tf_change > 0 {
2055 recombine = tf_change as usize;
2056 }
2057 // The folding source is about to be rewritten in place, so take a
2058 // copy first — the band it belongs to is still needed as decoded.
2059 if lowband != Lowband::None
2060 && (recombine > 0 || (n_b & 1) == 0 && tf_change < 0 || b0 > 1)
2061 {
2062 for j in 0..n {
2063 self.lowband_scratch[j] = self.lowband(lowband, j);
2064 }
2065 lowband = Lowband::Scratch(0);
2066 }
2067 for k in 0..recombine {
2068 const BIT_INTERLEAVE: [u8; 16] = [0, 1, 1, 1, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3];
2069 haar1(&mut self.x[x..], n >> k, 1 << k);
2070 if let Some(l) = self.lowband_mut(lowband) {
2071 haar1(l, n >> k, 1 << k);
2072 }
2073 fill = BIT_INTERLEAVE[(fill & 0xF) as usize] as u32
2074 | (BIT_INTERLEAVE[(fill >> 4) as usize] as u32) << 2;
2075 }
2076 blocks >>= recombine;
2077 n_b <<= recombine;
2078 // Increasing the time resolution.
2079 while (n_b & 1) == 0 && tf_change < 0 {
2080 haar1(&mut self.x[x..], n_b, blocks);
2081 if let Some(l) = self.lowband_mut(lowband) {
2082 haar1(l, n_b, blocks);
2083 }
2084 fill |= fill << blocks;
2085 blocks <<= 1;
2086 n_b >>= 1;
2087 time_divide += 1;
2088 tf_change += 1;
2089 }
2090 b0 = blocks;
2091 n_b0 = n_b;
2092 // Reorder the samples in time order instead of frequency order.
2093 if b0 > 1 {
2094 deinterleave_hadamard(
2095 &mut self.x[x..x + n],
2096 &mut self.hadamard_tmp,
2097 n_b >> recombine,
2098 b0 << recombine,
2099 long_blocks,
2100 );
2101 if lowband != Lowband::None {
2102 let mut tmp = core::mem::take(&mut self.hadamard_tmp);
2103 if let Some(l) = self.lowband_mut(lowband) {
2104 deinterleave_hadamard(
2105 &mut l[..n],
2106 tmp.as_mut_slice(),
2107 n_b >> recombine,
2108 b0 << recombine,
2109 long_blocks,
2110 );
2111 }
2112 self.hadamard_tmp = tmp;
2113 }
2114 }
2115 }
2116
2117 // Split the band when one codebook would need more than 32 bits.
2118 let cache_start = cache_index(i, lm);
2119 let cache0 = CACHE_BITS[cache_start] as usize;
2120 if !stereo && lm != -1 && b > CACHE_BITS[cache_start + cache0] as i32 + 12 && n > 2 {
2121 n >>= 1;
2122 y = Some(x + n);
2123 split = true;
2124 lm -= 1;
2125 if blocks == 1 {
2126 fill = (fill & 1) | (fill << 1);
2127 }
2128 blocks = (blocks + 1) >> 1;
2129 }
2130
2131 let mut mid = 0.0f32;
2132 if split {
2133 let pulse_cap = LOG_N[i] + lm * (1 << BITRES);
2134 let offset = (pulse_cap >> 1)
2135 - if stereo && n == 2 {
2136 QTHETA_OFFSET_TWOPHASE
2137 } else {
2138 QTHETA_OFFSET
2139 };
2140 let mut qn = compute_qn(n as i32, b, offset, pulse_cap, stereo);
2141 if stereo && i >= intensity {
2142 qn = 1;
2143 }
2144 let tell = dec.tell_frac() as i32;
2145 let mut itheta: i32 = 0;
2146 if qn != 1 {
2147 if stereo && n > 2 {
2148 // A step pdf: probability 3 up to itheta=qn/2, then 1.
2149 let p0 = 3i32;
2150 let x0 = qn / 2;
2151 let ft = p0 * (x0 + 1) + x0;
2152 let fs = dec.decode(ft as u32) as i32;
2153 let xv = if fs < (x0 + 1) * p0 {
2154 fs / p0
2155 } else {
2156 x0 + 1 + (fs - (x0 + 1) * p0)
2157 };
2158 let (fl, fh) = if xv <= x0 {
2159 (p0 * xv, p0 * (xv + 1))
2160 } else {
2161 ((xv - 1 - x0) + (x0 + 1) * p0, (xv - x0) + (x0 + 1) * p0)
2162 };
2163 dec.update(fl as u32, fh as u32, ft as u32);
2164 itheta = xv;
2165 } else if b0 > 1 || stereo {
2166 itheta = dec.dec_uint((qn + 1) as u32) as i32;
2167 } else {
2168 // Triangular pdf.
2169 let ft = ((qn >> 1) + 1) * ((qn >> 1) + 1);
2170 let fm = dec.decode(ft as u32) as i32;
2171 let (fl, fs);
2172 if fm < (((qn >> 1) * ((qn >> 1) + 1)) >> 1) {
2173 itheta = ((isqrt32(8 * fm as u32 + 1) - 1) >> 1) as i32;
2174 fs = itheta + 1;
2175 fl = (itheta * (itheta + 1)) >> 1;
2176 } else {
2177 itheta = (2 * (qn + 1) - isqrt32(8 * (ft - fm - 1) as u32 + 1) as i32) >> 1;
2178 fs = qn + 1 - itheta;
2179 fl = ft - (((qn + 1 - itheta) * (qn + 2 - itheta)) >> 1);
2180 }
2181 dec.update(fl as u32, (fl + fs) as u32, ft as u32);
2182 }
2183 itheta = (itheta * 16384) / qn;
2184 } else if stereo {
2185 inv = if b > 2 << BITRES && *remaining_bits > 2 << BITRES {
2186 dec.dec_bit_logp(2)
2187 } else {
2188 false
2189 };
2190 itheta = 0;
2191 }
2192 let qalloc = dec.tell_frac() as i32 - tell;
2193 b -= qalloc;
2194
2195 let orig_fill = fill;
2196 let (imid, iside, mut delta);
2197 if itheta == 0 {
2198 imid = 32767;
2199 iside = 0;
2200 fill &= (1 << blocks) - 1;
2201 delta = -16384;
2202 } else if itheta == 16384 {
2203 imid = 0;
2204 iside = 32767;
2205 fill &= ((1u32 << blocks) - 1) << blocks;
2206 delta = 16384;
2207 } else {
2208 imid = bitexact_cos(itheta as i16) as i32;
2209 iside = bitexact_cos((16384 - itheta) as i16) as i32;
2210 // The mid/side split that minimises the squared error.
2211 delta = frac_mul16(
2212 ((n as i32 - 1) << 7) as i16,
2213 bitexact_log2tan(iside, imid) as i16,
2214 );
2215 }
2216 mid = imid as f32 / 32768.0;
2217 let side = iside as f32 / 32768.0;
2218
2219 if n == 2 && stereo {
2220 // With two coefficients the side needs only a sign.
2221 let mut mbits = b;
2222 let mut sbits = 0;
2223 if itheta != 0 && itheta != 16384 {
2224 sbits = 1 << BITRES;
2225 }
2226 mbits -= sbits;
2227 let yy = y.unwrap();
2228 let swap = itheta > 8192;
2229 *remaining_bits -= qalloc + sbits;
2230 let (x2, y2) = if swap { (yy, x) } else { (x, yy) };
2231 let mut sign = 0i32;
2232 if sbits != 0 {
2233 sign = dec.dec_bits(1) as i32;
2234 }
2235 let sign = 1 - 2 * sign;
2236 cm = self.quant_band(
2237 dec,
2238 BandArgs {
2239 x: x2,
2240 y: None,
2241 n,
2242 b: mbits,
2243 blocks,
2244 tf_change,
2245 lowband,
2246 lm,
2247 fill: orig_fill,
2248 ..a
2249 },
2250 remaining_bits,
2251 );
2252 self.x[y2] = -(sign as f32) * self.x[x2 + 1];
2253 self.x[y2 + 1] = sign as f32 * self.x[x2];
2254 let x0 = self.x[x] * mid;
2255 let x1 = self.x[x + 1] * mid;
2256 let y0 = self.x[yy] * side;
2257 let y1 = self.x[yy + 1] * side;
2258 self.x[x] = x0 - y0;
2259 self.x[yy] = x0 + y0;
2260 self.x[x + 1] = x1 - y1;
2261 self.x[yy + 1] = x1 + y1;
2262 } else {
2263 // "Normal" split.
2264 if b0 > 1 && !stereo && (itheta & 0x3fff) != 0 {
2265 if itheta > 8192 {
2266 // Rough approximation for pre-echo masking.
2267 delta -= delta >> (4 - lm);
2268 } else {
2269 delta = 0.min(delta + ((n as i32) << BITRES >> (5 - lm)));
2270 }
2271 }
2272 let mut mbits = 0.max(b.min((b - delta) / 2));
2273 let mut sbits = b - mbits;
2274 *remaining_bits -= qalloc;
2275 let next_lowband2 = if lowband != Lowband::None && !stereo {
2276 lowband.offset(n)
2277 } else {
2278 Lowband::None
2279 };
2280 let next_lowband_out1 = if stereo { lowband_out } else { None };
2281 let next_level = if stereo { level } else { level + 1 };
2282 let mid_args = BandArgs {
2283 x,
2284 y: None,
2285 n,
2286 blocks,
2287 tf_change,
2288 lowband,
2289 level: next_level,
2290 lm,
2291 lowband_out: next_lowband_out1,
2292 gain: if stereo { 1.0 } else { gain * mid },
2293 fill,
2294 ..a
2295 };
2296 let side_args = BandArgs {
2297 x: y.unwrap(),
2298 y: None,
2299 n,
2300 blocks,
2301 tf_change,
2302 lowband: next_lowband2,
2303 level: next_level,
2304 lm,
2305 lowband_out: None,
2306 gain: gain * side,
2307 fill: fill >> blocks,
2308 ..a
2309 };
2310 // A mono split interleaves the two halves' collapse masks; a
2311 // stereo split keeps the side's mask in place.
2312 let shift = if stereo { 0 } else { b0 >> 1 };
2313 let mut rebalance = *remaining_bits;
2314 if mbits >= sbits {
2315 cm = self.quant_band(
2316 dec,
2317 BandArgs {
2318 b: mbits,
2319 ..mid_args
2320 },
2321 remaining_bits,
2322 );
2323 rebalance = mbits - (rebalance - *remaining_bits);
2324 if rebalance > 3 << BITRES && itheta != 0 {
2325 sbits += rebalance - (3 << BITRES);
2326 }
2327 cm |= self.quant_band(
2328 dec,
2329 BandArgs {
2330 b: sbits,
2331 ..side_args
2332 },
2333 remaining_bits,
2334 ) << shift;
2335 } else {
2336 cm = self.quant_band(
2337 dec,
2338 BandArgs {
2339 b: sbits,
2340 ..side_args
2341 },
2342 remaining_bits,
2343 ) << shift;
2344 rebalance = sbits - (rebalance - *remaining_bits);
2345 if rebalance > 3 << BITRES && itheta != 16384 {
2346 mbits += rebalance - (3 << BITRES);
2347 }
2348 cm |= self.quant_band(
2349 dec,
2350 BandArgs {
2351 b: mbits,
2352 ..mid_args
2353 },
2354 remaining_bits,
2355 );
2356 }
2357 }
2358 } else {
2359 // No split: straight PVQ, or folding when there are no pulses.
2360 let mut q = bits2pulses(i, lm, b);
2361 let mut curr_bits = pulses2bits(i, lm, q);
2362 *remaining_bits -= curr_bits;
2363 // Never bust the budget.
2364 while *remaining_bits < 0 && q > 0 {
2365 *remaining_bits += curr_bits;
2366 q -= 1;
2367 curr_bits = pulses2bits(i, lm, q);
2368 *remaining_bits -= curr_bits;
2369 }
2370 if q != 0 {
2371 let k = get_pulses(q) as usize;
2372 cm = self.alg_unquant(dec, x, n, k, spread, blocks, gain);
2373 } else {
2374 let cm_mask = (1u32 << blocks) - 1;
2375 fill &= cm_mask;
2376 if fill == 0 {
2377 self.x[x..x + n].fill(0.0);
2378 } else if lowband == Lowband::None {
2379 // Noise.
2380 for j in 0..n {
2381 self.rng = celt_lcg_rand(self.rng);
2382 self.x[x + j] = ((self.rng as i32) >> 20) as f32;
2383 }
2384 cm = cm_mask;
2385 renormalise(&mut self.x[x..x + n], gain);
2386 } else {
2387 // Folded spectrum, about 48 dB below the normal level.
2388 for j in 0..n {
2389 self.rng = celt_lcg_rand(self.rng);
2390 let tmp = if self.rng & 0x8000 != 0 {
2391 1.0 / 256.0
2392 } else {
2393 -1.0 / 256.0
2394 };
2395 self.x[x + j] = self.lowband(lowband, j) + tmp;
2396 }
2397 cm = fill;
2398 renormalise(&mut self.x[x..x + n], gain);
2399 }
2400 }
2401 }
2402
2403 // Undo the reorganisations, and pass the band on for later folding.
2404 if stereo {
2405 if n != 2 {
2406 stereo_merge(&mut self.x, x, y.unwrap(), mid, n);
2407 }
2408 if inv {
2409 for j in 0..n {
2410 self.x[y.unwrap() + j] = -self.x[y.unwrap() + j];
2411 }
2412 }
2413 } else if level == 0 {
2414 if b0 > 1 {
2415 interleave_hadamard(
2416 &mut self.x[x..x + n0],
2417 &mut self.hadamard_tmp,
2418 n_b >> recombine,
2419 b0 << recombine,
2420 long_blocks,
2421 );
2422 }
2423 n_b = n_b0;
2424 let mut bb = b0;
2425 for _ in 0..time_divide {
2426 bb >>= 1;
2427 n_b <<= 1;
2428 cm |= cm >> bb;
2429 haar1(&mut self.x[x..], n_b, bb);
2430 }
2431 for k in 0..recombine {
2432 const BIT_DEINTERLEAVE: [u8; 16] = [
2433 0x00, 0x03, 0x0C, 0x0F, 0x30, 0x33, 0x3C, 0x3F, 0xC0, 0xC3, 0xCC, 0xCF, 0xF0,
2434 0xF3, 0xFC, 0xFF,
2435 ];
2436 cm = BIT_DEINTERLEAVE[(cm & 0xF) as usize] as u32;
2437 haar1(&mut self.x[x..], n0 >> k, 1 << k);
2438 }
2439 bb <<= recombine;
2440 // Scale for use as a folding source.
2441 if let Some(o) = lowband_out {
2442 let nrm = (n0 as f32).sqrt();
2443 for j in 0..n0 {
2444 self.norm[o + j] = nrm * self.x[x + j];
2445 }
2446 }
2447 cm &= (1 << bb) - 1;
2448 }
2449 cm
2450 }
2451
2452 /// Reads one sample of the folding source.
2453 fn lowband(&self, lb: Lowband, j: usize) -> f32 {
2454 match lb {
2455 Lowband::None => 0.0,
2456 Lowband::Norm(l) => self.norm[l + j],
2457 Lowband::Scratch(o) => self.lowband_scratch[o + j],
2458 }
2459 }
2460
2461 /// The folding source as a mutable slice, for the in-place Haar passes.
2462 fn lowband_mut(&mut self, lb: Lowband) -> Option<&mut [f32]> {
2463 match lb {
2464 Lowband::None => None,
2465 Lowband::Norm(l) => Some(&mut self.norm[l..]),
2466 Lowband::Scratch(o) => Some(&mut self.lowband_scratch[o..]),
2467 }
2468 }
2469 #[allow(clippy::too_many_arguments)]
2470 fn alg_unquant(
2471 &mut self,
2472 dec: &mut RangeDecoder,
2473 x: usize,
2474 n: usize,
2475 k: usize,
2476 spread: usize,
2477 b_blocks: usize,
2478 gain: f32,
2479 ) -> u32 {
2480 decode_pulses(dec, n, k, &mut self.iy);
2481 let mut ryy = 0.0f32;
2482 for j in 0..n {
2483 ryy += (self.iy[j] * self.iy[j]) as f32;
2484 }
2485 let g = gain / ryy.sqrt();
2486 for j in 0..n {
2487 self.x[x + j] = g * self.iy[j] as f32;
2488 }
2489 exp_rotation(&mut self.x[x..x + n], n, -1, b_blocks, k, spread);
2490 // Collapse mask: which of the B short blocks got any pulse.
2491 if b_blocks <= 1 {
2492 return 1;
2493 }
2494 let n0 = n / b_blocks;
2495 let mut mask = 0u32;
2496 for bi in 0..b_blocks {
2497 for j in 0..n0 {
2498 mask |= u32::from(self.iy[bi * n0 + j] != 0) << bi;
2499 }
2500 }
2501 mask
2502 }
2503
2504 fn anti_collapse(&mut self, lm: usize, c: usize, size: usize, start: usize, end: usize) {
2505 for i in start..end {
2506 let n0 = E_BANDS[i + 1] - E_BANDS[i];
2507 let depth = (1 + self.pulses[i]) / (n0 << lm) as i32;
2508 let thresh = 0.5 * (-0.125 * depth as f32).exp2();
2509 let sqrt_1 = 1.0 / ((n0 << lm) as f32).sqrt();
2510 for ch in 0..c {
2511 let mut prev1 = self.old_log_e[ch * NB_BANDS + i];
2512 let mut prev2 = self.old_log_e2[ch * NB_BANDS + i];
2513 if c == 1 {
2514 prev1 = prev1.max(self.old_log_e[NB_BANDS + i]);
2515 prev2 = prev2.max(self.old_log_e2[NB_BANDS + i]);
2516 }
2517 let ediff = (self.old_band_e[ch * NB_BANDS + i] - prev1.min(prev2)).max(0.0);
2518 let mut r = 2.0 * (-ediff).exp2();
2519 if lm == 3 {
2520 r *= core::f32::consts::SQRT_2;
2521 }
2522 r = r.min(thresh) * sqrt_1;
2523 let base = ch * size + (E_BANDS[i] << lm);
2524 let mut renorm = false;
2525 for k in 0..(1usize << lm) {
2526 if self.collapse_masks[i * c + ch] & (1 << k) == 0 {
2527 for j in 0..n0 {
2528 self.rng = celt_lcg_rand(self.rng);
2529 self.x[base + (j << lm) + k] =
2530 if self.rng & 0x8000 != 0 { r } else { -r };
2531 }
2532 renorm = true;
2533 }
2534 }
2535 if renorm {
2536 let len = n0 << lm;
2537 renormalise(&mut self.x[base..base + len], 1.0);
2538 }
2539 }
2540 }
2541 }
2542
2543 fn denormalise_bands(&mut self, eff_end: usize, c: usize, m: usize, n: usize) {
2544 for ch in 0..c {
2545 for i in 0..eff_end {
2546 let g = self.band_e[i + ch * NB_BANDS];
2547 for j in m * E_BANDS[i]..m * E_BANDS[i + 1] {
2548 self.freq[ch * n + j] = self.x[ch * n + j] * g;
2549 }
2550 }
2551 for j in m * E_BANDS[eff_end]..n {
2552 self.freq[ch * n + j] = 0.0;
2553 }
2554 }
2555 }
2556
2557 fn inverse_mdcts(&mut self, short_blocks: usize, lm: usize, n: usize, cc: usize) {
2558 let (n2, blocks, plan_lm) = if short_blocks != 0 {
2559 (SHORT_MDCT, short_blocks, 0)
2560 } else {
2561 (n, 1, lm)
2562 };
2563 for ch in 0..cc {
2564 self.mdct_buf[..n + OVERLAP].fill(0.0);
2565 for b in 0..blocks {
2566 let spec_off = ch * n + b;
2567 let plan = &mut self.plans[plan_lm];
2568 plan.inverse(
2569 &self.freq[spec_off..],
2570 blocks,
2571 &self.window,
2572 &mut self.mdct_buf,
2573 n2 * b,
2574 );
2575 }
2576 let out_base = ch * DECODE_BUFFER + DECODE_BUFFER - n;
2577 let ov_base = ch * OVERLAP;
2578 for j in 0..OVERLAP {
2579 self.decode_mem[out_base + j] = self.mdct_buf[j] + self.overlap_mem[ov_base + j];
2580 }
2581 for j in OVERLAP..n {
2582 self.decode_mem[out_base + j] = self.mdct_buf[j];
2583 }
2584 for j in 0..OVERLAP {
2585 self.overlap_mem[ov_base + j] = self.mdct_buf[n + j];
2586 }
2587 }
2588 }
2589
2590 #[allow(clippy::too_many_arguments)]
2591 #[allow(clippy::too_many_arguments)]
2592 fn comb_filter(
2593 &mut self,
2594 base: usize,
2595 n: usize,
2596 t0: usize,
2597 t1: usize,
2598 g0: f32,
2599 g1: f32,
2600 tapset0: usize,
2601 tapset1: usize,
2602 _in_place: bool,
2603 ) {
2604 if g0 == 0.0 && g1 == 0.0 {
2605 return;
2606 }
2607 let g00 = g0 * POSTFILTER_GAINS[tapset0][0];
2608 let g01 = g0 * POSTFILTER_GAINS[tapset0][1];
2609 let g02 = g0 * POSTFILTER_GAINS[tapset0][2];
2610 let g10 = g1 * POSTFILTER_GAINS[tapset1][0];
2611 let g11 = g1 * POSTFILTER_GAINS[tapset1][1];
2612 let g12 = g1 * POSTFILTER_GAINS[tapset1][2];
2613 // The overlap region cross-fades between the old and new pitch.
2614 let ov = OVERLAP.min(n);
2615 for i in 0..ov {
2616 let f = self.window[i] * self.window[i];
2617 let x = |k: usize| self.decode_mem[base + i - k];
2618 let v = self.decode_mem[base + i]
2619 + (1.0 - f) * g00 * x(t0)
2620 + (1.0 - f) * g01 * (x(t0 + 1) + x(t0.wrapping_sub(1)))
2621 + (1.0 - f) * g02 * (x(t0 + 2) + x(t0.wrapping_sub(2)))
2622 + f * g10 * x(t1)
2623 + f * g11 * (x(t1 + 1) + x(t1.wrapping_sub(1)))
2624 + f * g12 * (x(t1 + 2) + x(t1.wrapping_sub(2)));
2625 self.decode_mem[base + i] = v;
2626 }
2627 for i in ov..n {
2628 let x = |k: usize| self.decode_mem[base + i - k];
2629 let v = self.decode_mem[base + i]
2630 + g10 * x(t1)
2631 + g11 * (x(t1 + 1) + x(t1.wrapping_sub(1)))
2632 + g12 * (x(t1 + 2) + x(t1.wrapping_sub(2)));
2633 self.decode_mem[base + i] = v;
2634 }
2635 }
2636
2637 fn deemphasis(&mut self, pcm: &mut [f32], n: usize, cc: usize) {
2638 for ch in 0..cc {
2639 let base = ch * DECODE_BUFFER + DECODE_BUFFER - n;
2640 let mut mem = self.preemph_mem[ch];
2641 let mut count = 0usize;
2642 let mut y = ch;
2643 for j in 0..n {
2644 let x = self.decode_mem[base + j];
2645 let tmp = x + mem;
2646 mem = PREEMPH * tmp;
2647 if count == 0 {
2648 pcm[y] = tmp / SIG_SCALE;
2649 }
2650 count += 1;
2651 if count == self.downsample {
2652 y += cc;
2653 count = 0;
2654 }
2655 }
2656 self.preemph_mem[ch] = mem;
2657 }
2658 }
2659}
2660
2661/// `ec_laplace_decode()`: the coarse-energy prediction error.
2662pub(crate) fn laplace_decode(dec: &mut RangeDecoder, fs0: u32, decay: i32) -> i32 {
2663 const MINP: u32 = 1;
2664 const NMIN: u32 = 16;
2665 let mut val = 0i32;
2666 let mut fs = fs0;
2667 let fm = dec.decode_bin(15);
2668 let mut fl = 0u32;
2669 if fm >= fs {
2670 val += 1;
2671 fl = fs;
2672 let ft = 32768 - MINP * (2 * NMIN) - fs0;
2673 fs = ((ft * (16384 - decay as u32)) >> 15) + MINP;
2674 while fs > MINP && fm >= fl + 2 * fs {
2675 fs *= 2;
2676 fl += fs;
2677 fs = (((fs - 2 * MINP) * decay as u32) >> 15) + MINP;
2678 val += 1;
2679 }
2680 if fs <= MINP {
2681 let di = (fm - fl) >> 1;
2682 val += di as i32;
2683 fl += 2 * di * MINP;
2684 }
2685 if fm < fl + fs {
2686 val = -val;
2687 } else {
2688 fl += fs;
2689 }
2690 }
2691 dec.update(fl, (fl + fs).min(32768), 32768);
2692 val
2693}
2694
2695/// `bitexact_cos()`: a cosine that must round identically everywhere, because
2696/// the bit allocation depends on it.
2697pub(crate) fn bitexact_cos(x: i16) -> i16 {
2698 let tmp = (4096 + (x as i32) * (x as i32)) >> 13;
2699 let mut x2 = tmp as i16;
2700 x2 = (32767 - x2 as i32
2701 + frac_mul16(
2702 x2,
2703 (-7651 + frac_mul16(x2, 8277 + frac_mul16(-626, x2) as i16)) as i16,
2704 )) as i16;
2705 1 + x2
2706}
2707
2708pub(crate) fn frac_mul16(a: i16, b: i16) -> i32 {
2709 (16384 + (a as i32) * (b as i32)) >> 15
2710}
2711
2712pub(crate) fn bitexact_log2tan(isin: i32, icos: i32) -> i32 {
2713 let lc = ilog(icos as u32);
2714 let ls = ilog(isin as u32);
2715 let isin = (isin << (15 - ls)) as i16;
2716 let icos = (icos << (15 - lc)) as i16;
2717 (ls - lc) * (1 << 11) + frac_mul16(isin, (frac_mul16(isin, -2597) + 7932) as i16)
2718 - frac_mul16(icos, (frac_mul16(icos, -2597) + 7932) as i16)
2719}
2720
2721pub(crate) fn compute_qn(n: i32, b: i32, offset: i32, pulse_cap: i32, stereo: bool) -> i32 {
2722 const EXP2_TABLE8: [i32; 8] = [16384, 17866, 19483, 21247, 23170, 25267, 27554, 30048];
2723 let mut n2 = 2 * n - 1;
2724 if stereo && n == 2 {
2725 n2 -= 1;
2726 }
2727 let mut qb = (b - pulse_cap - (4 << BITRES)).min((b + n2 * offset) / n2);
2728 qb = qb.min(8 << BITRES);
2729 if qb < (1 << BITRES >> 1) {
2730 1
2731 } else {
2732 let qn = EXP2_TABLE8[(qb & 0x7) as usize] >> (14 - (qb >> BITRES));
2733 (qn + 1) >> 1 << 1
2734 }
2735}
2736
2737pub(crate) fn get_pulses(i: i32) -> i32 {
2738 if i < 8 {
2739 i
2740 } else {
2741 (8 + (i & 7)) << ((i >> 3) - 1)
2742 }
2743}
2744
2745/// Longest CACHE_BITS row is far under this (the whole table is 392 bytes);
2746/// the fixed local window in [`bits2pulses`] lets the bisection compile
2747/// without a bounds check per access.
2748const CACHE_ROW_MAX: usize = 64;
2749
2750pub(crate) fn bits2pulses(band: usize, lm: i32, bits: i32) -> i32 {
2751 let base = cache_index(band, lm);
2752 let count = CACHE_BITS[base] as usize;
2753 // Statically decidable from the unchanged CACHE_BITS table (reviewer P3);
2754 // the copy below still panics if the table ever outgrew the window.
2755 debug_assert!(
2756 count < CACHE_ROW_MAX,
2757 "CACHE_BITS row overflows the fixed window"
2758 );
2759 let mut row = [0u8; CACHE_ROW_MAX];
2760 row[..=count].copy_from_slice(&CACHE_BITS[base..=base + count]);
2761 let mut lo = 0i32;
2762 let mut hi = count as i32;
2763 let bits = bits - 1;
2764 for _ in 0..6 {
2765 let mid = (lo + hi + 1) >> 1;
2766 if row[mid as usize] as i32 >= bits {
2767 hi = mid;
2768 } else {
2769 lo = mid;
2770 }
2771 }
2772 let lo_cost = if lo == 0 {
2773 -1
2774 } else {
2775 row[lo as usize] as i32
2776 };
2777 if bits - lo_cost <= row[hi as usize] as i32 - bits {
2778 lo
2779 } else {
2780 hi
2781 }
2782}
2783
2784pub(crate) fn pulses2bits(band: usize, lm: i32, pulses: i32) -> i32 {
2785 if pulses == 0 {
2786 return 0;
2787 }
2788 let base = cache_index(band, lm);
2789 CACHE_BITS[base + pulses as usize] as i32 + 1
2790}
2791
2792/// One level of the Haar transform, used for the time/frequency changes.
2793pub(crate) fn haar1(x: &mut [f32], n0: usize, stride: usize) {
2794 let n0 = n0 >> 1;
2795 const S: f32 = core::f32::consts::FRAC_1_SQRT_2;
2796 for i in 0..stride {
2797 for j in 0..n0 {
2798 let a = S * x[stride * 2 * j + i];
2799 let b = S * x[stride * (2 * j + 1) + i];
2800 x[stride * 2 * j + i] = a + b;
2801 x[stride * (2 * j + 1) + i] = a - b;
2802 }
2803 }
2804}
2805
2806pub(crate) fn deinterleave_hadamard(
2807 x: &mut [f32],
2808 tmp: &mut [f32],
2809 n0: usize,
2810 stride: usize,
2811 hadamard: bool,
2812) {
2813 let n = n0 * stride;
2814 let tmp = &mut tmp[..n];
2815 if hadamard {
2816 let order = &ORDERY[stride - 2..];
2817 for i in 0..stride {
2818 for j in 0..n0 {
2819 tmp[order[i] * n0 + j] = x[j * stride + i];
2820 }
2821 }
2822 } else {
2823 for i in 0..stride {
2824 for j in 0..n0 {
2825 tmp[i * n0 + j] = x[j * stride + i];
2826 }
2827 }
2828 }
2829 x[..n].copy_from_slice(tmp);
2830}
2831
2832fn interleave_hadamard(x: &mut [f32], tmp: &mut [f32], n0: usize, stride: usize, hadamard: bool) {
2833 let n = n0 * stride;
2834 let tmp = &mut tmp[..n];
2835 if hadamard {
2836 let order = &ORDERY[stride - 2..];
2837 for i in 0..stride {
2838 for j in 0..n0 {
2839 tmp[j * stride + i] = x[order[i] * n0 + j];
2840 }
2841 }
2842 } else {
2843 for i in 0..stride {
2844 for j in 0..n0 {
2845 tmp[j * stride + i] = x[i * n0 + j];
2846 }
2847 }
2848 }
2849 x[..n].copy_from_slice(tmp);
2850}
2851
2852/// Scales a vector to `gain` in the L2 sense.
2853fn renormalise(x: &mut [f32], gain: f32) {
2854 let mut e = 1e-15f32;
2855 for v in x.iter() {
2856 e += v * v;
2857 }
2858 let g = gain / e.sqrt();
2859 for v in x.iter_mut() {
2860 *v *= g;
2861 }
2862}
2863
2864/// Recombines the mid/side pair back into left/right (`stereo_merge`).
2865fn stereo_merge(buf: &mut [f32], x: usize, y: usize, mid: f32, n: usize) {
2866 let mut xp = 0.0f32;
2867 let mut side = 0.0f32;
2868 for j in 0..n {
2869 xp += buf[x + j] * buf[y + j];
2870 side += buf[y + j] * buf[y + j];
2871 }
2872 xp *= mid;
2873 let mid2 = mid;
2874 let el = mid2 * mid2 + side - 2.0 * xp;
2875 let er = mid2 * mid2 + side + 2.0 * xp;
2876 if er < 6e-4 || el < 6e-4 {
2877 for j in 0..n {
2878 buf[y + j] = buf[x + j];
2879 }
2880 return;
2881 }
2882 let lgain = 1.0 / el.sqrt();
2883 let rgain = 1.0 / er.sqrt();
2884 for j in 0..n {
2885 let l = mid * buf[x + j];
2886 let r = buf[y + j];
2887 buf[x + j] = lgain * (l - r);
2888 buf[y + j] = rgain * (l + r);
2889 }
2890}
2891
2892/// The spreading rotation (Section 4.3.4.3), applied in the decode direction.
2893pub(crate) fn exp_rotation(
2894 x: &mut [f32],
2895 len: usize,
2896 dir: i32,
2897 stride: usize,
2898 k: usize,
2899 spread: usize,
2900) {
2901 const SPREAD_FACTOR: [usize; 3] = [15, 10, 5];
2902 if 2 * k >= len || spread == SPREAD_NONE {
2903 return;
2904 }
2905 let factor = SPREAD_FACTOR[spread - 1];
2906 let gain = len as f32 / (len + factor * k) as f32;
2907 let theta = 0.5 * gain * gain;
2908 let c = (core::f32::consts::FRAC_PI_2 * theta).cos();
2909 let s = (core::f32::consts::FRAC_PI_2 * (1.0 - theta)).cos();
2910 let mut stride2 = 0usize;
2911 if len >= 8 * stride {
2912 stride2 = 1;
2913 while (stride2 * stride2 + stride2) * stride + (stride >> 2) < len {
2914 stride2 += 1;
2915 }
2916 }
2917 let sub = len / stride;
2918 for i in 0..stride {
2919 let seg = &mut x[i * sub..(i + 1) * sub];
2920 if dir < 0 {
2921 if stride2 != 0 {
2922 exp_rotation1(seg, sub, stride2, s, c);
2923 }
2924 exp_rotation1(seg, sub, 1, c, s);
2925 } else {
2926 exp_rotation1(seg, sub, 1, c, -s);
2927 if stride2 != 0 {
2928 exp_rotation1(seg, sub, stride2, s, -c);
2929 }
2930 }
2931 }
2932}
2933
2934fn exp_rotation1(x: &mut [f32], len: usize, stride: usize, c: f32, s: f32) {
2935 for i in 0..len.saturating_sub(stride) {
2936 let x1 = x[i];
2937 let x2 = x[i + stride];
2938 x[i + stride] = c * x2 + s * x1;
2939 x[i] = c * x1 - s * x2;
2940 }
2941 if len > 2 * stride {
2942 for i in (0..=len - 2 * stride - 1).rev() {
2943 let x1 = x[i];
2944 let x2 = x[i + stride];
2945 x[i + stride] = c * x2 + s * x1;
2946 x[i] = c * x1 - s * x2;
2947 }
2948 }
2949}
2950
2951#[cfg(test)]
2952mod tests {
2953 use super::*;
2954
2955 #[test]
2956 fn window_is_power_complementary() {
2957 // Princen-Bradley: w[n]^2 + w[L-1-n]^2 == 1, which is what makes the
2958 // overlap-add reconstruct exactly.
2959 let w = overlap_window();
2960 for i in 0..OVERLAP {
2961 let s = w[i] * w[i] + w[OVERLAP - 1 - i] * w[OVERLAP - 1 - i];
2962 assert!((s - 1.0).abs() < 1e-6, "w[{i}]^2 + w[..]^2 = {s}");
2963 }
2964 }
2965
2966 #[test]
2967 fn fft15_matches_a_direct_transform() {
2968 for &n in &[60usize, 120, 240, 480] {
2969 let mut re: Vec<f32> = (0..n).map(|i| ((i * 37 % 19) as f32) - 9.0).collect();
2970 let mut im: Vec<f32> = (0..n).map(|i| ((i * 11 % 7) as f32) - 3.0).collect();
2971 let (re0, im0) = (re.clone(), im.clone());
2972 let mut fft = Fft15::new(n);
2973 fft.inverse(&mut re, &mut im);
2974 for k in 0..n {
2975 let (mut sr, mut si) = (0.0f64, 0.0f64);
2976 for j in 0..n {
2977 let a = 2.0 * core::f64::consts::PI * (j * k % n) as f64 / n as f64;
2978 sr += re0[j] as f64 * a.cos() - im0[j] as f64 * a.sin();
2979 si += re0[j] as f64 * a.sin() + im0[j] as f64 * a.cos();
2980 }
2981 assert!(
2982 (sr - re[k] as f64).abs() < 1e-2 * n as f64,
2983 "n={n} k={k} re {sr} vs {}",
2984 re[k]
2985 );
2986 assert!(
2987 (si - im[k] as f64).abs() < 1e-2 * n as f64,
2988 "n={n} k={k} im"
2989 );
2990 }
2991 }
2992 }
2993
2994 /// The MDCT of a `2L` window, straight from the definition — the slow
2995 /// reference the fast inverse is checked against.
2996 fn direct_mdct(x: &[f32], l: usize) -> Vec<f32> {
2997 (0..l)
2998 .map(|k| {
2999 let mut sum = 0.0f64;
3000 for (n, &v) in x.iter().enumerate().take(2 * l) {
3001 let a = core::f64::consts::PI / l as f64
3002 * (n as f64 + 0.5 + l as f64 / 2.0)
3003 * (k as f64 + 0.5);
3004 sum += v as f64 * a.cos();
3005 }
3006 sum as f32
3007 })
3008 .collect()
3009 }
3010
3011 #[test]
3012 fn imdct_overlap_add_reconstructs_the_signal() {
3013 // Forward by definition, inverse through the FFT path, overlap-add at
3014 // hop L: the middle of the signal must come back. This pins down every
3015 // index, sign and window position in the inverse; the one free
3016 // parameter left is the overall gain, which the test reports.
3017 for &l in &[120usize, 240, 480] {
3018 let frames = 4;
3019 let total = (frames + 1) * l;
3020 let sig: Vec<f32> = (0..total)
3021 .map(|i| ((i * 7919 % 1000) as f32 / 500.0) - 1.0)
3022 .collect();
3023 // The 2L analysis window: zero, rise, ones, fall, zero.
3024 let w = overlap_window();
3025 let flat = (l - OVERLAP) / 2;
3026 let mut win = vec![0.0f32; 2 * l];
3027 for n in 0..l {
3028 win[n] = if n < flat {
3029 0.0
3030 } else if n < flat + OVERLAP {
3031 w[n - flat]
3032 } else {
3033 1.0
3034 };
3035 win[2 * l - 1 - n] = win[n];
3036 }
3037 let mut plan = ImdctPlan::new(l);
3038 let mut out = vec![0.0f32; total + 2 * l];
3039 for t in 0..frames {
3040 let start = t * l;
3041 let mut block = vec![0.0f32; 2 * l];
3042 for n in 0..2 * l {
3043 block[n] = win[n] * sig.get(start + n).copied().unwrap_or(0.0);
3044 }
3045 let spec = direct_mdct(&block, l);
3046 plan.inverse(&spec, 1, &w, &mut out, start + flat);
3047 }
3048 // Compare where two windows fully overlap.
3049 let lo = l + OVERLAP;
3050 let hi = frames * l - OVERLAP;
3051 let mut num = 0.0f64;
3052 let mut den = 0.0f64;
3053 for i in lo..hi {
3054 num += out[i] as f64 * sig[i] as f64;
3055 den += sig[i] as f64 * sig[i] as f64;
3056 }
3057 let gain = num / den;
3058 let mut err = 0.0f64;
3059 for i in lo..hi {
3060 let d = out[i] as f64 - gain * sig[i] as f64;
3061 err += d * d;
3062 }
3063 let rel = (err / den).sqrt();
3064 assert!(
3065 rel < 1e-3,
3066 "L={l}: overlap-add residual {rel} at gain {gain}"
3067 );
3068 // CELT puts the 2/N normalisation on the *forward* transform, so
3069 // this inverse is the plain sum and the loop above, whose forward
3070 // has no scaling at all, reconstructs at L/2.
3071 assert!(
3072 (gain - l as f64 / 2.0).abs() < 1e-3 * gain,
3073 "L={l}: gain {gain}, expected {}",
3074 l as f64 / 2.0
3075 );
3076 }
3077 }
3078
3079 #[test]
3080 fn pvq_index_round_trips_within_v() {
3081 // V(N,K) from the recursion in Section 4.3.4.2, checked against the
3082 // closed forms the RFC gives for small N, and the table against a
3083 // fresh runtime build of the same recurrence over the whole stored
3084 // triangle.
3085 assert_eq!(pvq_v(2, 1), 4);
3086 assert_eq!(pvq_v(2, 3), 12);
3087 assert_eq!(pvq_v(3, 2), 18);
3088 assert_eq!(pvq_v(4, 2), 32);
3089 // U(N,K) = U(N-1,K) + U(N,K-1) + U(N-1,K-1).
3090 for n in 3..8usize {
3091 for k in 2..8usize {
3092 let (v1, v2, v3, v) =
3093 (pvq_v(n - 1, k), pvq_v(n, k - 1), pvq_v(n - 1, k - 1), pvq_v(n, k));
3094 assert_eq!(v, v1.wrapping_add(v2).wrapping_add(v3), "V({n},{k})");
3095 }
3096 }
3097 // The table equals the runtime row-stepping everywhere it is stored:
3098 // rows 0..15, columns as laid out by PVQ_U_ROW.
3099 let mut u = vec![0u32; 400];
3100 for n in 0..=176usize {
3101 for k in 0..=176usize {
3102 let (lo, hi) = if n < k { (n, k) } else { (k, n) };
3103 if lo > 14 {
3104 continue;
3105 }
3106 let col_max = if lo < 14 {
3107 PVQ_U_ROW[lo + 1] - PVQ_U_ROW[lo] + lo
3108 } else {
3109 14
3110 };
3111 if hi > col_max || hi < 2 {
3112 // Outside the stored span, or a base row the row-stepping
3113 // never built (rows 0 and 1 are its seeds).
3114 continue;
3115 }
3116 // Runtime U via the old row-stepping, in wrapping arithmetic.
3117 u[0] = 0;
3118 u[1] = 1;
3119 for (j, slot) in u.iter_mut().enumerate().take(hi + 2).skip(2) {
3120 *slot = (2 * j - 1) as u32;
3121 }
3122 for _ in 2..hi {
3123 // unext over the slice u[1..lo+2] with ui0 = 1, exactly as
3124 // the row-stepping drove it.
3125 let mut ui0 = 1u32;
3126 for j in 2..lo + 2 {
3127 let ui1 = u[j].wrapping_add(u[j - 1]).wrapping_add(ui0);
3128 u[j - 1] = ui0;
3129 ui0 = ui1;
3130 }
3131 u[lo + 1] = ui0;
3132 }
3133 assert_eq!(pvq_u(hi, lo), u[lo], "U({hi},{lo})");
3134 }
3135 }
3136 }
3137}