forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

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