forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB6828b15Tahinli3 months ago393 commits

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