forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB00c1b3fTahinli2 months ago1999 commits

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