forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB00c1b3fTahinli2 months ago1999 commits

celt_enc.rs2577 lines, 95.7 KiBHistoryRawDownload
1//! The CELT encoder — RFC 6716 Section 5.3, throughput-first.
2//!
3//! The *coding* path — every symbol written, every `tell()` the bit allocation
4//! reads — mirrors the normative reference (RFC 6716 Appendix A) exactly,
5//! because the decoder derives the allocation from the same arithmetic and one
6//! bit of drift desynchronises the frame. The *analysis* path is where this
7//! encoder buys its speed, with fast deterministic heuristics in place of the
8//! reference's searches:
9//!
10//! - **No pitch prefilter.** The postfilter-off bit is coded every frame,
11//! which removes the most expensive analysis in the reference encoder (an
12//! autocorrelation search over 1024 lags). Same choice the reference makes
13//! below complexity 5.
14//! - **Time/frequency Viterbi ported and enabled.** `tf_analysis()` and the
15//! libopus float-mode `transient_analysis()` (returning `tf_estimate`/
16//! `tf_chan`) are ported from the reference; `const TF_ANALYSIS: bool`
17//! gates the Viterbi search. It is `true`: `dynalloc_analysis()` computes
18//! per-band `importance[]` and feeds it to the search, matching the
19//! reference's analysis path.
20//! - **Fixed spreading.** `SPREAD_NORMAL` every frame, coded explicitly.
21//! - **Single-pass coarse energy** with the reference's own delayed-intra
22//! heuristic, not the two-pass encode-both-and-compare.
23//!
24//! What stays: transient detection, the closed-form allocation-trim and
25//! dynalloc spike heuristics, the stereo-mode analysis, intensity thresholds
26//! and constrained-VBR reservoir — all cheap O(frame) arithmetic that decides
27//! *rates*, not searches.
28//!
29//! Steady state allocates nothing: every buffer is owned by the encoder and
30//! sized at construction.
31
32use ec_core::{Error, Result};
33
34use crate::celt::{
35 self, BETA_COEF, BETA_INTRA, BITRES, CACHE_CAPS, E_BANDS, E_MEANS, E_PROB_MODEL, LOG_N,
36 MAX_FINE_BITS, NB_BANDS, OVERLAP, PRED_COEF, PREEMPH, QTHETA_OFFSET, QTHETA_OFFSET_TWOPHASE,
37 SHORT_MDCT, SIG_SCALE, SMALL_ENERGY_ICDF, SPREAD_AGGRESSIVE, SPREAD_ICDF, SPREAD_LIGHT,
38 SPREAD_NONE, SPREAD_NORMAL, TF_SELECT, TRIM_ICDF,
39 bitexact_cos, bitexact_log2tan, bits2pulses, cache_index, compute_allocation_encode,
40 compute_qn, deinterleave_hadamard, exp_rotation, frac_mul16, get_pulses, haar1, pulses2bits,
41 unext,
42};
43use crate::range::RangeEncoder;
44
45const CACHE_BITS: &[u8] = &crate::celt::CACHE_BITS;
46const INV_TABLE: [u8; 128] = [
47 255,255,156,110, 86, 70, 59, 51, 45, 40, 37, 33, 31, 28, 26, 25,
48 23, 22, 21, 20, 19, 18, 17, 16, 16, 15, 15, 14, 13, 13, 12, 12,
49 12, 12, 11, 11, 11, 10, 10, 10, 9, 9, 9, 9, 9, 9, 8, 8,
50 8, 8, 8, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6,
51 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5,
52 5, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
53 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3,
54 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2,
55];
56
57// ---------------------------------------------------------------------------
58// Forward MDCT
59// ---------------------------------------------------------------------------
60
61/// One forward-MDCT plan, the exact adjoint of the decoder's `ImdctPlan`:
62/// window-fold, pre-rotation, an `l/2`-point FFT and post-rotation, scaled by
63/// `2/l` so that decode(encode(x)) reconstructs at unit gain.
64#[derive(Clone, Debug)]
65struct MdctPlan {
66 l: usize,
67 fft: celt::Fft15,
68 rot_re: Vec<f32>,
69 rot_im: Vec<f32>,
70 fre: Vec<f32>,
71 fim: Vec<f32>,
72 t: Vec<f32>,
73}
74
75impl MdctPlan {
76 fn new(l: usize) -> MdctPlan {
77 let n = 2 * l;
78 let quarter = l / 2;
79 let mut rot_re = vec![0.0; quarter];
80 let mut rot_im = vec![0.0; quarter];
81 for i in 0..quarter {
82 let a = 2.0 * core::f64::consts::PI * (i as f64 + 0.125) / n as f64;
83 rot_re[i] = a.cos() as f32;
84 rot_im[i] = a.sin() as f32;
85 }
86 MdctPlan {
87 l,
88 fft: celt::Fft15::new(quarter),
89 rot_re,
90 rot_im,
91 fre: vec![0.0; quarter],
92 fim: vec![0.0; quarter],
93 t: vec![0.0; l],
94 }
95 }
96
97 /// Transforms `l + OVERLAP` time samples starting at `input[off]` — the
98 /// support of the low-overlap window — into `l` MDCT coefficients written
99 /// at `out[out_off + k*stride]`.
100 fn forward(
101 &mut self,
102 input: &[f32],
103 off: usize,
104 window: &[f32],
105 out: &mut [f32],
106 out_off: usize,
107 stride: usize,
108 ) {
109 let l = self.l;
110 let quarter = l / 2;
111 let flat = quarter - OVERLAP / 2;
112 let mirror = quarter + OVERLAP / 2;
113 let t = &mut self.t;
114 // Window fold: the adjoint of the inverse's scatter, so every
115 // coefficient, sign and window position matches by construction.
116 for i in 0..flat {
117 t[quarter - 1 - i] = input[off + mirror - 1 - i];
118 }
119 for i in flat..quarter {
120 let w = i - flat;
121 t[quarter - 1 - i] =
122 -window[w] * input[off + w] + window[OVERLAP - 1 - w] * input[off + mirror - 1 - i];
123 }
124 for i in 0..flat {
125 t[quarter + i] = input[off + mirror + i];
126 }
127 for i in flat..quarter {
128 let w = i - flat;
129 t[quarter + i] = window[w] * input[off + l + OVERLAP - 1 - w]
130 + window[OVERLAP - 1 - w] * input[off + mirror + i];
131 }
132 // Shuffle into the complex FFT input.
133 for i in 0..quarter {
134 self.fre[i] = -t[2 * i];
135 self.fim[i] = t[2 * (quarter - 1 - i) + 1];
136 }
137 // Rotate by -theta (adjoint of the inverse's post-rotation).
138 for i in 0..quarter {
139 let (c, s) = (self.rot_re[i], self.rot_im[i]);
140 let (re, im) = (self.fre[i], self.fim[i]);
141 self.fre[i] = re * c + im * s;
142 self.fim[i] = im * c - re * s;
143 }
144 // Forward FFT = conjugate, +i-convention FFT, conjugate.
145 for v in self.fim.iter_mut() {
146 *v = -*v;
147 }
148 self.fft.inverse(&mut self.fre, &mut self.fim);
149 for v in self.fim.iter_mut() {
150 *v = -*v;
151 }
152 // Adjoint of the pre-rotation, with the 2/l forward scaling CELT puts
153 // on this side of the transform.
154 let scale = 2.0 / l as f32;
155 for i in 0..quarter {
156 let (c, s) = (self.rot_re[i], self.rot_im[i]);
157 let (re, im) = (self.fre[i], self.fim[i]);
158 out[out_off + (2 * i) * stride] = scale * (s * re - c * im);
159 out[out_off + (l - 1 - 2 * i) * stride] = scale * (-c * re - s * im);
160 }
161 }
162}
163
164// ---------------------------------------------------------------------------
165// Symbol-level helpers
166// ---------------------------------------------------------------------------
167
168/// `ec_laplace_encode()`: the coarse-energy prediction error. May clamp
169/// `value`, which is why it is passed back.
170fn laplace_encode(enc: &mut RangeEncoder, value: &mut i32, mut fs: u32, decay: i32) -> i32 {
171 const MINP: u32 = 1;
172 const NMIN: u32 = 16;
173 let mut fl = 0u32;
174 let mut val = *value;
175 if val != 0 {
176 let s = if val < 0 { -1i32 } else { 0 };
177 val = (val + s) ^ s;
178 fl = fs;
179 let fs0 = fs;
180 fs = ((32768 - MINP * (2 * NMIN) - fs0) * (16384 - decay as u32)) >> 15;
181 // Search the decaying part of the pdf.
182 let mut i = 1i32;
183 while fs > 0 && i < val {
184 fs *= 2;
185 fl += fs + 2 * MINP;
186 fs = (fs * decay as u32) >> 15;
187 i += 1;
188 }
189 if fs == 0 {
190 // Everything beyond has probability MINP.
191 let mut ndi_max = (32768 - fl + MINP - 1) as i32;
192 ndi_max = (ndi_max - s) >> 1;
193 let di = (val - i).min(ndi_max - 1);
194 fl += ((2 * di + 1 + s) as u32) * MINP;
195 fs = MINP.min(32768 - fl);
196 *value = (i + di + s) ^ s;
197 } else {
198 fs += MINP;
199 if s == 0 {
200 fl += fs;
201 }
202 }
203 debug_assert!(fl + fs <= 32768);
204 debug_assert!(fs > 0);
205 }
206 enc.encode_bin(fl, fl + fs, 15);
207 *value
208}
209
210/// `encode_pulses()` for the general case: index the pulse vector in the
211/// V(N,K) enumeration and code it as one uniform symbol (Section 5.3.4).
212fn encode_pulses(enc: &mut RangeEncoder, iy: &[i32], n: usize, k: usize, u: &mut [u32]) {
213 debug_assert!(n >= 2 && k > 0);
214 u[0] = 0;
215 for (kk, slot) in u.iter_mut().enumerate().take(k + 2).skip(1) {
216 *slot = (2 * kk - 1) as u32;
217 }
218 let mut i = u32::from(iy[n - 1] < 0);
219 let mut kk = iy[n - 1].unsigned_abs() as usize;
220 let j = n - 2;
221 i = i.wrapping_add(u[kk]);
222 kk += iy[j].unsigned_abs() as usize;
223 if iy[j] < 0 {
224 i = i.wrapping_add(u[kk + 1]);
225 }
226 let mut j = j;
227 while j > 0 {
228 j -= 1;
229 unext(&mut u[..k + 2], 0);
230 i = i.wrapping_add(u[kk]);
231 kk += iy[j].unsigned_abs() as usize;
232 if iy[j] < 0 {
233 i = i.wrapping_add(u[kk + 1]);
234 }
235 }
236 let nc = u[kk].wrapping_add(u[kk + 1]);
237 enc.enc_uint(i, nc.max(2));
238}
239
240/// `stereo_itheta()`: the angle between mid and side (or the two halves of a
241/// split mono band), in Q14 (0..16384).
242fn stereo_itheta(x: &[f32], y: &[f32], stereo: bool, n: usize) -> i32 {
243 let mut emid = 1e-15f32;
244 let mut eside = 1e-15f32;
245 if stereo {
246 for j in 0..n {
247 let m = x[j] + y[j];
248 let s = x[j] - y[j];
249 emid += m * m;
250 eside += s * s;
251 }
252 } else {
253 for j in 0..n {
254 emid += x[j] * x[j];
255 eside += y[j] * y[j];
256 }
257 }
258 let mid = emid.sqrt();
259 let side = eside.sqrt();
260 // 0.63662 is the reference's own 2/pi literal (vq.c, stereo_itheta); the
261 // exact constant would round a boundary theta differently.
262 #[allow(clippy::approx_constant)]
263 const TWO_OVER_PI: f64 = 0.63662;
264 (0.5 + 16384.0 * TWO_OVER_PI * (side as f64).atan2(mid as f64)).floor() as i32
265}
266
267/// `l1_metric()` from the reference: L1 norm scaled by `(1 + LM*bias)`.
268/// In float mode `MAC16_32_Q15(c, a*b) = c + a*b`, so this is `L1*(1 + LM*bias)`.
269fn l1_metric(tmp: &[f32], n: usize, lm: usize, bias: f32) -> f32 {
270 let mut l1 = 0.0f32;
271 for i in 0..n {
272 l1 += tmp[i].abs();
273 }
274 l1 * (1.0 + lm as f32 * bias)
275}
276
277// ---------------------------------------------------------------------------
278// The encoder
279// ---------------------------------------------------------------------------
280
281/// Arguments threaded through the band-encode recursion; the encode-side
282/// mirror of the decoder's `BandArgs`, minus everything only resynthesis
283/// needs (folding sources, gains, collapse fill).
284#[derive(Clone, Copy, Debug)]
285struct EncBand {
286 i: usize,
287 x: usize,
288 y: Option<usize>,
289 n: usize,
290 b: i32,
291 spread: usize,
292 blocks: usize,
293 intensity: usize,
294 tf_change: i32,
295 level: i32,
296 lm: i32,
297}
298
299/// Per-frame encoder diagnostics for the dropout investigation. Captured at
300/// the end of [`CeltEncoder::encode`]; read via [`CeltEncoder::last_diag`].
301#[derive(Clone, Debug)]
302pub struct CeltFrameDiag {
303 /// Transient flag as coded into the bitstream.
304 pub is_transient: bool,
305 /// `short_blocks` (0 = long, else `m` short blocks).
306 pub short_blocks: usize,
307 /// Coarse-energy intra-frame reset was used.
308 pub intra: bool,
309 /// The whole frame was coded as silence.
310 pub silence: bool,
311 /// Frame-size exponent (`120 << lm`).
312 pub lm: usize,
313 /// First/last coded band indices.
314 pub start: usize,
315 /// Highest band actually allocated pulses.
316 pub coded_bands: usize,
317 /// Stereo intensity band (bands >= this collapse to mono).
318 pub intensity: usize,
319 /// Dual-stereo (no mid/side folding) flag.
320 pub dual_stereo: bool,
321 /// Allocation trim index (0..10).
322 pub alloc_trim: i32,
323 /// Constrained-VBR reservoir level after this frame, in 1/8-bit units.
324 pub vbr_reservoir: i32,
325 /// Final compressed payload of this frame, in bytes.
326 pub nb_compressed: usize,
327 /// Per-band log2 energy minus `E_MEANS`, both channels (ch0 then ch1).
328 pub band_log_e: [f32; 2 * NB_BANDS],
329 /// Per-band allocated pulses (ch0/ch1 share for intensity bands).
330 pub pulses: [i32; NB_BANDS],
331 /// Per-band fine-energy precision bits.
332 pub fine_quant: [i32; NB_BANDS],
333}
334
335impl Default for CeltFrameDiag {
336 fn default() -> Self {
337 Self {
338 is_transient: false,
339 short_blocks: 0,
340 intra: false,
341 silence: false,
342 lm: 0,
343 start: 0,
344 coded_bands: 0,
345 intensity: 0,
346 dual_stereo: false,
347 alloc_trim: 0,
348 vbr_reservoir: 0,
349 nb_compressed: 0,
350 band_log_e: [0.0; 2 * NB_BANDS],
351 pulses: [0; NB_BANDS],
352 fine_quant: [0; NB_BANDS],
353 }
354 }
355}
356
357/// A CELT-layer encoder for one elementary Opus stream (mono or stereo).
358/// CELT itself always runs at 48 kHz; slower input is zero-stuffed up to it.
359#[derive(Clone, Debug)]
360pub struct CeltEncoder {
361 channels: usize,
362 /// 48000 / input rate, 1 for native 48 kHz input.
363 upsample: usize,
364 window: Vec<f32>,
365 plans: Vec<MdctPlan>,
366 /// Preemphasised history, `channels * OVERLAP`.
367 in_mem: Vec<f32>,
368 preemph_mem: [f32; 2],
369 /// Coarse-energy prediction state, `2 * NB_BANDS`.
370 old_band_e: Vec<f32>,
371 delayed_intra: f32,
372 consec_transient: u32,
373 // Spreading decision state (libopus celt_encoder.c:2534-2537).
374 spread_decision: usize,
375 tonal_average: i32,
376 hf_average: i32,
377 tapset_decision: i32,
378 last_coded_bands: usize,
379 force_intra: bool,
380 // Constrained-VBR reservoir.
381 vbr_reservoir: i32,
382 vbr_drift: i32,
383 vbr_offset: i32,
384 vbr_count: i32,
385 /// libopus `st->stereo_saving` — mid/side bit-saving estimate (Q8 in C,
386 /// plain f32 here), updated in `alloc_trim_analysis`.
387 stereo_saving: f32,
388 /// libopus `st->spec_avg` — temporal-VBR follower average, updated each frame.
389 spec_avg: f32,
390 // Per-frame scratch, allocated once.
391 in_buf: Vec<f32>,
392 freq: Vec<f32>,
393 x: Vec<f32>,
394 band_e: Vec<f32>,
395 band_log_e: Vec<f32>,
396 /// Long-window log energies used by dynalloc (`bandLogE2`).
397 band_log_e2: Vec<f32>,
398 /// Previous intensity decision (hysteresis state, libopus `st->intensity`).
399 intensity: usize,
400 error: Vec<f32>,
401 transient_tmp: Vec<f32>,
402 hadamard_tmp: Vec<f32>,
403 tf_res: [i32; NB_BANDS],
404 pulses: [i32; NB_BANDS],
405 fine_quant: [i32; NB_BANDS],
406 fine_priority: [i32; NB_BANDS],
407 offsets: [i32; NB_BANDS],
408 caps: [i32; NB_BANDS],
409 iy: Vec<i32>,
410 pvq_y: Vec<f32>,
411 pvq_sign: Vec<i32>,
412 urow: Vec<u32>,
413 /// Per-frame diagnostics captured at the end of the last `encode` call.
414 last_diag: CeltFrameDiag,
415}
416
417impl CeltEncoder {
418 /// An encoder for `channels` channels (1 or 2) fed at `48000/upsample` Hz.
419 pub fn new(channels: usize, upsample: usize) -> CeltEncoder {
420 assert!((1..=2).contains(&channels));
421 assert!(upsample >= 1);
422 let max_n = SHORT_MDCT * 8;
423 CeltEncoder {
424 channels,
425 upsample,
426 window: celt::overlap_window(),
427 plans: (0..4).map(|lm| MdctPlan::new(SHORT_MDCT << lm)).collect(),
428 in_mem: vec![0.0; channels * OVERLAP],
429 preemph_mem: [0.0; 2],
430 old_band_e: vec![0.0; 2 * NB_BANDS],
431 delayed_intra: 1.0,
432 consec_transient: 0,
433 last_coded_bands: 0,
434 force_intra: true,
435 spread_decision: SPREAD_NORMAL,
436 tonal_average: 256,
437 hf_average: 0,
438 tapset_decision: 0,
439 vbr_reservoir: 0,
440 vbr_drift: 0,
441 vbr_offset: 0,
442 vbr_count: 0,
443 stereo_saving: 0.0,
444 spec_avg: 0.0,
445 in_buf: vec![0.0; channels * (max_n + OVERLAP)],
446 freq: vec![0.0; channels * max_n],
447 x: vec![0.0; channels * max_n],
448 band_e: vec![0.0; 2 * NB_BANDS],
449 band_log_e: vec![0.0; 2 * NB_BANDS],
450 band_log_e2: vec![0.0; 2 * NB_BANDS],
451 intensity: 0,
452 error: vec![0.0; 2 * NB_BANDS],
453 transient_tmp: vec![0.0; max_n + OVERLAP],
454 hadamard_tmp: vec![0.0; max_n],
455 tf_res: [0; NB_BANDS],
456 pulses: [0; NB_BANDS],
457 fine_quant: [0; NB_BANDS],
458 fine_priority: [0; NB_BANDS],
459 offsets: [0; NB_BANDS],
460 caps: [0; NB_BANDS],
461 iy: vec![0; max_n],
462 pvq_y: vec![0.0; max_n],
463 pvq_sign: vec![0; max_n],
464 urow: vec![0; 1280],
465 last_diag: CeltFrameDiag::default(),
466 }
467 }
468
469 /// Channels this encoder codes.
470 pub fn channels(&self) -> usize {
471 self.channels
472 }
473
474 /// Diagnostics captured at the end of the most recent [`encode`] call.
475 ///
476 /// [`encode`]: CeltEncoder::encode
477 pub fn last_diag(&self) -> &CeltFrameDiag {
478 &self.last_diag
479 }
480
481 /// Drops all inter-frame state.
482 pub fn reset(&mut self) {
483 self.in_mem.fill(0.0);
484 self.preemph_mem = [0.0; 2];
485 self.old_band_e.fill(0.0);
486 self.delayed_intra = 1.0;
487 self.consec_transient = 0;
488 self.last_coded_bands = 0;
489 self.force_intra = true;
490 self.spread_decision = SPREAD_NORMAL;
491 self.tonal_average = 256;
492 self.hf_average = 0;
493 self.tapset_decision = 0;
494 self.vbr_reservoir = 0;
495 self.vbr_drift = 0;
496 self.vbr_offset = 0;
497 self.vbr_count = 0;
498 self.stereo_saving = 0.0;
499 self.spec_avg = 0.0;
500 }
501
502 /// Encodes one frame of interleaved `f32` (`frame_size` samples per
503 /// channel at 48 kHz, one of 120/240/480/960 — of which
504 /// `frame_size/upsample` are read from `pcm`) into `enc`, which must have
505 /// been `reset` to the frame's byte budget. `start..end` bounds the coded
506 /// bands — `end` is how the caller limits the coded bandwidth, `start`
507 /// (0, or 17 under a hybrid packet's SILK layer) skips the low bands
508 /// exactly as the decoder's `start_band` does: no energy, no shapes, no
509 /// postfilter bit, allocation over the coded span only. With
510 /// `vbr_rate_bps` set, the frame may be shrunk below that budget
511 /// (constrained VBR); the return value is the final frame size in bytes.
512 pub fn encode(
513 &mut self,
514 enc: &mut RangeEncoder,
515 pcm: &[f32],
516 frame_size: usize,
517 start: usize,
518 end: usize,
519 vbr_rate_bps: u32,
520 ) -> Result<usize> {
521 let lm: usize = match frame_size {
522 120 => 0,
523 240 => 1,
524 480 => 2,
525 960 => 3,
526 _ => {
527 return Err(Error::unsupported(
528 format!("celt frame of {frame_size} samples"),
529 "CELT frames are 2.5, 5, 10 or 20 ms at 48 kHz",
530 ));
531 }
532 };
533 let m = 1usize << lm;
534 let n = frame_size;
535 let c = self.channels;
536 let in_n = n / self.upsample;
537 if pcm.len() < in_n * c {
538 return Err(Error::corrupt(format!(
539 "celt encode: {} samples for a {c}-channel {in_n}-sample frame",
540 pcm.len()
541 )));
542 }
543 let end = end.clamp(start + 1, NB_BANDS);
544
545 let mut nb_compressed = enc.storage();
546 let mut nb_available = nb_compressed as i32;
547 // The target rate in 1/8-bit units per frame, VBR only.
548 let (vbr_rate, mut effective_bytes) = if vbr_rate_bps > 0 {
549 let den = 48000i64 >> BITRES;
550 let vr = ((vbr_rate_bps as i64 * n as i64 + (den >> 1)) / den) as i32;
551 (vr, vr >> (3 + BITRES))
552 } else {
553 (0, nb_compressed as i32)
554 };
555
556 if vbr_rate > 0 {
557 // Constrained VBR: cap this frame so the reservoir never dips
558 // below one frame of buffering.
559 let vbr_bound = vbr_rate;
560 let max_allowed = (2i32
561 .max((vbr_rate + vbr_bound - self.vbr_reservoir) >> (BITRES + 3)))
562 .min(nb_available);
563 if max_allowed < nb_available {
564 nb_compressed = max_allowed as usize;
565 nb_available = max_allowed;
566 enc.shrink(nb_compressed);
567 }
568 }
569 let mut total_bits = (nb_compressed * 8) as i32;
570
571 // --- Preemphasis ----------------------------------------------------
572 let stride = n + OVERLAP;
573 let mut silence = true;
574 for ch in 0..c {
575 let base = ch * stride;
576 self.in_buf[base..base + OVERLAP]
577 .copy_from_slice(&self.in_mem[ch * OVERLAP..(ch + 1) * OVERLAP]);
578 let mut mem = self.preemph_mem[ch];
579 let up = self.upsample;
580 for i in 0..n {
581 // Zero-stuffing to 48 kHz: the images above the input's own
582 // Nyquist are never coded (the caller caps `end`) and the
583 // decoder's decimation drops them.
584 let mut x = if up == 1 {
585 pcm[i * c + ch] * SIG_SCALE
586 } else if i.is_multiple_of(up) {
587 pcm[(i / up) * c + ch] * SIG_SCALE * up as f32
588 } else {
589 0.0
590 };
591 if !x.is_finite() {
592 x = 0.0;
593 }
594 x = x.clamp(-65536.0, 65536.0);
595 let v = x + mem;
596 mem = -PREEMPH * x;
597 self.in_buf[base + OVERLAP + i] = v;
598 silence &= v == 0.0;
599 }
600 self.preemph_mem[ch] = mem;
601 self.in_mem[ch * OVERLAP..(ch + 1) * OVERLAP]
602 .copy_from_slice(&self.in_buf[base + n..base + n + OVERLAP]);
603 }
604
605 // --- Silence flag (first symbol of the frame) -----------------------
606 // Only exists when CELT opens the stream (decoder: `tell == 1`); under
607 // a hybrid packet's SILK layer the frame is never flagged silent.
608 if enc.tell() == 1 {
609 enc.enc_bit_logp(silence, 15);
610 } else {
611 silence = false;
612 }
613 if silence {
614 if vbr_rate > 0 {
615 nb_compressed = nb_compressed.min(2);
616 total_bits = (nb_compressed * 8) as i32;
617 nb_available = 2;
618 enc.shrink(nb_compressed);
619 }
620 enc.pad_to_end();
621 }
622
623 // --- Postfilter: always off (throughput-first, = complexity < 5) ----
624 // The flag exists only when band 0 is coded (decoder: `start == 0`).
625 if start == 0 && enc.tell() as i32 + 16 <= total_bits {
626 enc.enc_bit_logp(false, 1);
627 }
628
629 // --- Transient flag -------------------------------------------------
630 let mut is_transient = false;
631 let mut short_blocks = 0usize;
632 let mut tf_estimate = 0.0f32;
633 let mut tf_chan = 0usize;
634 if lm > 0 && enc.tell() as i32 + 3 <= total_bits {
635 let (ta, te, tc) = self.transient_analysis(n + OVERLAP, c, stride);
636 is_transient = ta;
637 tf_estimate = te;
638 tf_chan = tc;
639 if is_transient {
640 short_blocks = m;
641 }
642 enc.enc_bit_logp(is_transient, 3);
643 }
644
645 // --- Forward MDCTs, energies, normalisation -------------------------
646 // dynalloc looks at long-window energies (`bandLogE2`): on transient
647 // frames that is a second MDCT pass, offset by LM/2 for the block size.
648 if short_blocks != 0 {
649 self.compute_mdcts(0, lm, n, c);
650 for ch in 0..c {
651 for i in start..end {
652 let mut sum = 1e-27f32;
653 for j in m * E_BANDS[i]..m * E_BANDS[i + 1] {
654 let v = self.freq[ch * n + j];
655 sum += v * v;
656 }
657 self.band_log_e2[i + ch * NB_BANDS] =
658 (sum.sqrt() as f64).log2() as f32 - E_MEANS[i] + 0.5 * lm as f32;
659 }
660 }
661 }
662 self.compute_mdcts(short_blocks, lm, n, c);
663 for ch in 0..c {
664 self.x[ch * n..ch * n + m * E_BANDS[start]].fill(0.0);
665 for i in start..end {
666 let mut sum = 1e-27f32;
667 for j in m * E_BANDS[i]..m * E_BANDS[i + 1] {
668 let v = self.freq[ch * n + j];
669 sum += v * v;
670 }
671 self.band_e[i + ch * NB_BANDS] = sum.sqrt();
672 self.band_log_e[i + ch * NB_BANDS] =
673 (self.band_e[i + ch * NB_BANDS] as f64).log2() as f32 - E_MEANS[i];
674 if short_blocks == 0 {
675 self.band_log_e2[i + ch * NB_BANDS] = self.band_log_e[i + ch * NB_BANDS];
676 }
677 }
678 for i in start..end {
679 let g = 1.0 / (1e-27 + self.band_e[i + ch * NB_BANDS]);
680 for j in m * E_BANDS[i]..m * E_BANDS[i + 1] {
681 self.x[ch * n + j] = self.freq[ch * n + j] * g;
682 }
683 }
684 }
685
686 // --- Dynalloc analysis (offsets + spread_weight + importance) -----
687 self.offsets = [0; NB_BANDS];
688 let mut spread_weight = [0i32; NB_BANDS];
689 let mut importance = [0i32; NB_BANDS];
690 let max_depth = self.dynalloc_analysis(
691 start,
692 end,
693 c,
694 lm,
695 is_transient,
696 effective_bytes,
697 &mut spread_weight,
698 &mut importance,
699 );
700
701 // --- tf_res ---------------------------------------------------------
702 // `TF_ANALYSIS`: run the libopus Viterbi tf search when there are
703 // enough bits; otherwise fall back to the no-analysis default (raw
704 // `is_transient` per band codes "no tf change" under tf_select=0).
705 const TF_ANALYSIS: bool = true;
706 let tf_select = if TF_ANALYSIS && effective_bytes >= 15 * c as i32 {
707 let lambda = (80i32).max(20480 / effective_bytes + 2);
708 self.tf_analysis(end, is_transient, lambda, n, lm, tf_estimate, tf_chan, &importance)
709 } else {
710 self.tf_res = [i32::from(is_transient); NB_BANDS];
711 0usize
712 };
713
714 // --- Coarse energy --------------------------------------------------
715 let two_pass = false;
716 let mut intra = self.force_intra
717 || (!two_pass
718 && self.delayed_intra > (2 * c * (end - start)) as f32
719 && nb_available > ((end - start) * c) as i32);
720 let new_distortion = {
721 let mut dist = 0.0f32;
722 for ch in 0..c {
723 for i in start..end {
724 let d = self.band_log_e[i + ch * NB_BANDS] - self.old_band_e[i + ch * NB_BANDS];
725 dist += d * d;
726 }
727 }
728 dist.min(200.0)
729 };
730 let tell = enc.tell();
731 if tell + 3 > total_bits as u32 {
732 intra = false;
733 }
734 let max_decay = 16.0f32.min(0.125 * nb_available as f32);
735 self.quant_coarse_energy(enc, start, end, intra, c, lm, total_bits, max_decay);
736 self.delayed_intra = if intra {
737 new_distortion
738 } else {
739 PRED_COEF[lm] * PRED_COEF[lm] * self.delayed_intra + new_distortion
740 };
741
742 // --- tf encode ------------------------------------------------------
743 self.tf_encode(enc, start, end, is_transient, lm, tf_select, nb_compressed);
744
745 // --- Spread decision (libopus celt_encoder.c:1933-1977) --------------
746 // No LFE, no hybrid, no complexity field (treated as ≥ 3): the only
747 // guards that apply are shortBlocks and nbAvailableBytes < 10*C.
748 if enc.tell() as i32 + 4 <= total_bits {
749 if short_blocks != 0 || nb_available < 10 * c as i32 {
750 self.spread_decision = SPREAD_NORMAL;
751 } else {
752 self.spread_decision =
753 self.spreading_decision(end, c, lm, &spread_weight);
754 }
755 enc.enc_icdf(self.spread_decision, &SPREAD_ICDF, 5);
756 }
757
758 // --- Caps ------------------------------------------------------------
759 for i in 0..NB_BANDS {
760 let bw = (E_BANDS[i + 1] - E_BANDS[i]) << lm;
761 self.caps[i] =
762 ((CACHE_CAPS[NB_BANDS * (2 * lm + c - 1) + i] as i32 + 64) * c as i32 * bw as i32)
763 >> 2;
764 }
765 let mut dynalloc_logp = 6u32;
766 let total_bits_frac = total_bits << BITRES;
767 let mut total_boost = 0i32;
768 let mut tell_frac = enc.tell_frac() as i32;
769 for i in start..end {
770 let width = ((c * (E_BANDS[i + 1] - E_BANDS[i])) << lm) as i32;
771 let quanta = (width << BITRES).min((6 << BITRES).max(width));
772 let mut loop_logp = dynalloc_logp;
773 let mut boost = 0i32;
774 let mut j = 0i32;
775 while tell_frac + ((loop_logp as i32) << BITRES) < total_bits_frac - total_boost
776 && boost < self.caps[i]
777 {
778 let flag = j < self.offsets[i];
779 enc.enc_bit_logp(flag, loop_logp);
780 tell_frac = enc.tell_frac() as i32;
781 if !flag {
782 break;
783 }
784 boost += quanta;
785 total_boost += quanta;
786 loop_logp = 1;
787 j += 1;
788 }
789 if j > 0 {
790 dynalloc_logp = dynalloc_logp.saturating_sub(1).max(2);
791 }
792 self.offsets[i] = boost;
793 }
794
795 // --- Intensity decision (libopus celt_encoder.c:2392-2407) -------
796 // Moved before alloc_trim so alloc_trim_analysis can use
797 // self.intensity in the stereo_saving minXC loop.
798 let overhead = (40 * c as i32 + 20) * ((400 >> lm) - 50);
799 let mut equiv_rate = ((nb_compressed as i32 * 8 * 50) << (3 - lm)) - overhead;
800 if vbr_rate_bps > 0 {
801 equiv_rate = equiv_rate.min(vbr_rate_bps as i32 - overhead);
802 }
803 if c == 2 {
804 self.intensity_decision(nb_compressed, c, lm, vbr_rate_bps);
805 self.intensity = self.intensity.clamp(start, end);
806 }
807
808 // --- Allocation trim ------------------------------------------------
809 let mut alloc_trim = 5i32;
810 if tell_frac + (6 << BITRES) <= total_bits_frac - total_boost {
811 alloc_trim = self.alloc_trim_analysis(end, lm, c, n);
812 enc.enc_icdf(alloc_trim as usize, &TRIM_ICDF, 7);
813 tell_frac = enc.tell_frac() as i32;
814 }
815
816 // --- Temporal VBR (libopus celt_encoder.c:2187-2204) -------------
817 // lfe=0 so always computed. In float mode SHR32/SHL32/QCONST32 are
818 // identity, so follow/frame_avg/temporal_vbr are raw floats.
819 let temporal_vbr = {
820 let mut follow = -10.0f32;
821 let mut frame_avg = 0.0f32;
822 let offset = if short_blocks != 0 { 0.5 * lm as f32 } else { 0.0 };
823 for i in start..end {
824 follow = (follow - 1.0).max(self.band_log_e[i] - offset);
825 if c == 2 {
826 follow = follow.max(self.band_log_e[i + NB_BANDS] - offset);
827 }
828 frame_avg += follow;
829 }
830 frame_avg /= (end - start) as f32;
831 let tvbr = (frame_avg - self.spec_avg).clamp(-1.5, 3.0);
832 self.spec_avg += 0.02 * tvbr;
833 tvbr
834 };
835
836 // --- Constrained VBR ------------------------------------------------
837 if vbr_rate > 0 {
838 let lm_diff = 3 - lm as i32;
839 let base_target =
840 vbr_rate + (self.vbr_offset >> lm_diff) - ((40 * c as i32 + 20) << BITRES);
841 let mut target = base_target;
842 // compute_vbr (libopus celt_encoder.c:1605-1716), float-mode.
843 // Skipped: activity, tonality, surround_mask (analysis->valid=
844 // false, has_surround_mask=0, pitch_change=0, lfe=0). The qext
845 // 2-pass transient compute_vbr (C:2546-2554) is inside
846 // #ifdef ENABLE_QEXT — this encoder has no qext.
847 let coded_bands = if self.last_coded_bands != 0 {
848 self.last_coded_bands
849 } else {
850 NB_BANDS
851 };
852 let mut coded_bins = E_BANDS[coded_bands] << lm;
853 if c == 2 {
854 coded_bins += E_BANDS[self.intensity.min(coded_bands)] << lm;
855 }
856 // Stereo savings (C:1636-1649)
857 if c == 2 {
858 let coded_stereo_bands = self.intensity.min(coded_bands);
859 let coded_stereo_dof =
860 (E_BANDS[coded_stereo_bands] << lm) - coded_stereo_bands;
861 let max_frac = 0.8 * coded_stereo_dof as f32 / coded_bins as f32;
862 let ss = self.stereo_saving.min(1.0);
863 target -= (max_frac * target as f32)
864 .min((ss - 0.1) * coded_stereo_dof as f32 * 8.0) as i32;
865 }
866 // dynalloc boost minus calibration average (C:1651)
867 target += total_boost - (19 << lm);
868 // TF boost (C:1653-1654): MULT16_32_Q15 is identity in float mode,
869 // SHL32(.., 1) is the x2: 2 * (tf_estimate - 0.044) * target.
870 // Measured deviation: C applies SHL32(.., 1) (x2). On the 14-row
871 // library gate x2 loses .003 corr on reelm/hein@64 vs x1 (lane
872 // opus-vbr r2 vs r3); our tf_estimate is not scaled like libopus's.
873 target += ((tf_estimate - 0.044) * target as f32) as i32;
874 // floor depth cap (C:1683-1695): SHR32/MULT16_32_Q15 are identity.
875 {
876 let bins = E_BANDS[NB_BANDS - 2] << lm;
877 let floor_depth = ((c * bins * 8) as f32 * max_depth) as i32;
878 let floor_depth = floor_depth.max(target >> 2);
879 target = target.min(floor_depth);
880 }
881 // Constrained VBR (C:1699-1702)
882 target = base_target + (0.67 * (target - base_target) as f32) as i32;
883 // Temporal VBR (C:1704-1711)
884 if tf_estimate < 0.2 {
885 let amount = 0.0000031 * (96000 - equiv_rate).clamp(0, 32000) as f32;
886 target += (temporal_vbr * amount * target as f32) as i32;
887 }
888 // Never more than double the base rate (C:1714)
889 target = target.min(2 * base_target);
890 target += tell_frac;
891 let min_allowed =
892 ((tell_frac + total_boost + (1 << (BITRES + 3)) - 1) >> (BITRES + 3)) + 2;
893 let mut nb_avail = (target + (1 << (BITRES + 2))) >> (BITRES + 3);
894 nb_avail = nb_avail.max(min_allowed);
895 nb_avail = nb_avail.min(nb_compressed as i32);
896 let mut delta = target - vbr_rate;
897 target = nb_avail << (BITRES + 3);
898 if silence {
899 delta = 0;
900 }
901 let alpha = if self.vbr_count < 970 {
902 self.vbr_count += 1;
903 1.0 / (self.vbr_count + 20) as f32
904 } else {
905 0.001
906 };
907 self.vbr_reservoir += target - vbr_rate;
908 self.vbr_drift += (alpha
909 * ((delta * (1 << lm_diff)) as f32
910 - self.vbr_offset as f32
911 - self.vbr_drift as f32)) as i32;
912 self.vbr_offset = -self.vbr_drift;
913 // Bound banked credit at eight frames' worth of rate.
914 self.vbr_reservoir = self.vbr_reservoir.max(-8 * vbr_rate);
915 if self.vbr_reservoir < 0 {
916 // Release banked credit slowly (8 bytes per frame) so it stays
917 // available for transient boosts; libopus CVBR re-adds all of
918 // it to the next frame, which would defeat banking entirely.
919 let adjust = ((-self.vbr_reservoir) / (8 << BITRES)).min(8);
920 if !silence {
921 nb_avail += adjust;
922 self.vbr_reservoir += adjust << (BITRES + 3);
923 } else {
924 self.vbr_reservoir = 0;
925 }
926 }
927 let shrunk = (nb_compressed as i32).min(nb_avail).max(2) as usize;
928 if shrunk < nb_compressed {
929 nb_compressed = shrunk;
930 enc.shrink(nb_compressed);
931 }
932 }
933
934 // --- Stereo decisions -----------------------------------------------
935 let mut intensity = 0usize;
936 let mut dual_stereo = false;
937 if c == 2 {
938 if lm != 0 {
939 dual_stereo = self.stereo_analysis(lm, n);
940 }
941 intensity = self.intensity.clamp(start, end);
942 }
943 let _ = &mut effective_bytes;
944
945 // --- Bit allocation -------------------------------------------------
946 let mut bits = (((nb_compressed * 8) as i32) << BITRES) - enc.tell_frac() as i32 - 1;
947 let anti_collapse_rsv = if is_transient && lm >= 2 && bits >= ((lm as i32 + 2) << BITRES) {
948 1 << BITRES
949 } else {
950 0
951 };
952 bits -= anti_collapse_rsv;
953 let alloc = compute_allocation_encode(
954 enc,
955 start,
956 end,
957 alloc_trim,
958 bits,
959 c,
960 lm,
961 &self.offsets,
962 &self.caps,
963 &mut self.pulses,
964 &mut self.fine_quant,
965 &mut self.fine_priority,
966 intensity,
967 dual_stereo,
968 self.last_coded_bands,
969 );
970 let intensity = alloc.intensity;
971 let dual_stereo = alloc.dual_stereo;
972 let balance = alloc.balance;
973 let coded_bands = alloc.coded_bands;
974 // libopus: lastCodedBands follows codedBands by at most one band per frame.
975 self.last_coded_bands = if self.last_coded_bands != 0 {
976 coded_bands.clamp(self.last_coded_bands - 1, self.last_coded_bands + 1)
977 } else {
978 coded_bands
979 };
980
981 // --- Fine energy ----------------------------------------------------
982 for i in start..end {
983 if self.fine_quant[i] <= 0 {
984 continue;
985 }
986 let frac = 1 << self.fine_quant[i];
987 for ch in 0..c {
988 let e = &mut self.error[i + ch * NB_BANDS];
989 let q2 = (((*e + 0.5) * frac as f32).floor() as i32).clamp(0, frac - 1);
990 enc.enc_bits(q2 as u32, self.fine_quant[i] as u32);
991 let offset = (q2 as f32 + 0.5) / frac as f32 - 0.5;
992 self.old_band_e[i + ch * NB_BANDS] += offset;
993 *e -= offset;
994 }
995 }
996
997 // --- Shapes ---------------------------------------------------------
998 self.quant_all_bands(
999 enc,
1000 start,
1001 end,
1002 short_blocks,
1003 self.spread_decision,
1004 dual_stereo,
1005 intensity,
1006 (nb_compressed as i32 * (8 << BITRES)) - anti_collapse_rsv,
1007 balance,
1008 lm,
1009 coded_bands,
1010 c,
1011 n,
1012 );
1013
1014 // --- Anti-collapse --------------------------------------------------
1015 if anti_collapse_rsv > 0 {
1016 let on = self.consec_transient < 2;
1017 enc.enc_bits(u32::from(on), 1);
1018 }
1019
1020 // --- Leftover fine bits ---------------------------------------------
1021 let mut bits_left = nb_compressed as i32 * 8 - enc.tell() as i32;
1022 for prio in 0..2 {
1023 for i in start..end {
1024 if bits_left < c as i32 {
1025 break;
1026 }
1027 if self.fine_quant[i] >= MAX_FINE_BITS || self.fine_priority[i] != prio {
1028 continue;
1029 }
1030 for ch in 0..c {
1031 let q2 = i32::from(self.error[i + ch * NB_BANDS] >= 0.0);
1032 enc.enc_bits(q2 as u32, 1);
1033 let offset = (q2 as f32 - 0.5) / (1 << (self.fine_quant[i] + 1)) as f32;
1034 self.old_band_e[i + ch * NB_BANDS] += offset;
1035 bits_left -= 1;
1036 }
1037 }
1038 }
1039
1040 if silence {
1041 for e in self.old_band_e.iter_mut() {
1042 *e = -28.0;
1043 }
1044 }
1045 if c == 1 {
1046 for i in 0..NB_BANDS {
1047 self.old_band_e[NB_BANDS + i] = self.old_band_e[i];
1048 }
1049 }
1050 // Uncoded bands hold no energy history (the decoder clears them the
1051 // same way), so a later start/end change predicts from the same state.
1052 for ch in 0..2 {
1053 for i in (0..start).chain(end..NB_BANDS) {
1054 self.old_band_e[ch * NB_BANDS + i] = 0.0;
1055 }
1056 }
1057 if is_transient {
1058 self.consec_transient += 1;
1059 } else {
1060 self.consec_transient = 0;
1061 }
1062 self.force_intra = false;
1063
1064 enc.done();
1065 if enc.error() {
1066 return Err(Error::corrupt("celt encode: busted the frame budget"));
1067 }
1068 // Capture per-frame diagnostics for the dropout investigation.
1069 let mut band_log_e = [0.0f32; 2 * NB_BANDS];
1070 band_log_e[..2 * NB_BANDS].copy_from_slice(&self.band_log_e);
1071 self.last_diag = CeltFrameDiag {
1072 is_transient,
1073 short_blocks,
1074 intra,
1075 silence,
1076 lm,
1077 start,
1078 coded_bands,
1079 intensity,
1080 dual_stereo,
1081 alloc_trim,
1082 vbr_reservoir: self.vbr_reservoir,
1083 nb_compressed,
1084 band_log_e,
1085 pulses: self.pulses,
1086 fine_quant: self.fine_quant,
1087 };
1088 Ok(nb_compressed)
1089 }
1090 // -- Analysis ------------------------------------------------------------
1091
1092 /// `transient_analysis()` — libopus float-mode algorithm.
1093 /// Returns `(is_transient, tf_estimate, tf_chan)`.
1094 fn transient_analysis(&mut self, len: usize, c: usize, stride: usize) -> (bool, f32, usize) {
1095 let tmp = &mut self.transient_tmp[..len];
1096 let len2 = len / 2;
1097 let mut mask_metric: i32 = 0;
1098 let mut tf_chan: usize = 0;
1099
1100 for ch in 0..c {
1101 // Copy this channel's samples (C layout: in[i + c*len] = in_buf[ch*stride + i])
1102 tmp.copy_from_slice(&self.in_buf[ch * stride..ch * stride + len]);
1103
1104 // High-pass filter: (1 - 2*z^-1 + z^-2) / (1 - z^-1 + .5*z^-2)
1105 let mut mem0 = 0.0f32;
1106 let mut mem1 = 0.0f32;
1107 for v in tmp.iter_mut() {
1108 let x = *v;
1109 let y = mem0 + x;
1110 mem0 = mem1 + y - 2.0 * x;
1111 mem1 = x - 0.5 * y;
1112 *v = y;
1113 }
1114 // First few samples are bad because we don't propagate the memory
1115 for v in tmp.iter_mut().take(12) {
1116 *v = 0.0;
1117 }
1118
1119 // Forward pass: post-echo threshold (forward_decay = 0.0625)
1120 let mut mean = 0.0f32;
1121 let mut fm0 = 0.0f32;
1122 for i in 0..len2 {
1123 let x2 = tmp[2 * i] * tmp[2 * i] + tmp[2 * i + 1] * tmp[2 * i + 1];
1124 mean += x2;
1125 tmp[i] = fm0 + 0.0625 * (x2 - fm0);
1126 fm0 = tmp[i];
1127 }
1128
1129 // Backward pass: pre-echo threshold (backward_decay = 0.125)
1130 let mut bm0 = 0.0f32;
1131 let mut max_e = 0.0f32;
1132 for i in (0..len2).rev() {
1133 tmp[i] = bm0 + 0.125 * (tmp[i] - bm0);
1134 bm0 = tmp[i];
1135 max_e = max_e.max(bm0);
1136 }
1137
1138 // Geometric mean of frame energy and half the max
1139 mean = (mean * max_e * 0.5 * len2 as f32).sqrt();
1140
1141 // Inverse of the mean energy (float mode: SHL32/SHR32 are no-ops)
1142 let norm = len2 as f32 / (1e-15 + mean);
1143
1144 // Harmonic mean discarding unreliable boundaries (1/4th of samples)
1145 let mut unmask: i32 = 0;
1146 let mut i = 12;
1147 while i < len2 - 5 {
1148 let id = ((64.0 * norm * (tmp[i] + 1e-15)).floor() as i32).clamp(0, 127) as usize;
1149 unmask += INV_TABLE[id] as i32;
1150 i += 4;
1151 }
1152 // Normalize: 1/4th sampling, factor of 6 in inv_table
1153 unmask = 64 * unmask * 4 / (6 * (len2 as i32 - 17));
1154 if unmask > mask_metric {
1155 tf_chan = ch;
1156 mask_metric = unmask;
1157 }
1158 }
1159
1160 let is_transient = mask_metric > 200;
1161 // tf_max and tf_estimate (float mode: all Q-shifts are no-ops)
1162 let tf_max = ((27.0 * mask_metric as f32).sqrt() - 42.0).max(0.0);
1163 let tf_estimate = (0.0069 * tf_max.min(163.0) - 0.139).max(0.0).sqrt();
1164
1165 (is_transient, tf_estimate, tf_chan)
1166 }
1167
1168 /// libopus `dynalloc_analysis`: per-band boost requests from a follower /
1169 /// median masking model over the long-window energies. Writes
1170 /// `self.offsets[i]` in boost units (the loop that codes them converts to
1171 /// bits via the band's quanta). Also computes `importance[]` for
1172 /// `tf_analysis()` (libopus celt_encoder.c:1176-1189).
1173 fn dynalloc_analysis(
1174 &mut self,
1175 start: usize,
1176 end: usize,
1177 c: usize,
1178 lm: usize,
1179 is_transient: bool,
1180 effective_bytes: i32,
1181 spread_weight: &mut [i32; NB_BANDS],
1182 importance: &mut [i32; NB_BANDS],
1183 ) -> f32 {
1184 const LSB_DEPTH: f32 = 24.0;
1185 let mut noise_floor = [0.0f32; NB_BANDS];
1186 for i in 0..end {
1187 noise_floor[i] = 0.0625 * LOG_N[i] as f32 + 0.5 + (9.0 - LSB_DEPTH) - E_MEANS[i]
1188 + 0.0062 * ((i + 5) * (i + 5)) as f32;
1189 }
1190 // maxDepth = max(bandLogE - noise_floor) across channels (libopus 995-999).
1191 let mut max_depth = -31.9f32;
1192 for ch in 0..c {
1193 for i in 0..end {
1194 max_depth = max_depth.max(self.band_log_e[ch * NB_BANDS + i] - noise_floor[i]);
1195 }
1196 }
1197 // Simple masking model for spread_weight (libopus celt_encoder.c:1000-1035).
1198 let mut mask = [0.0f32; NB_BANDS];
1199 for i in 0..end {
1200 mask[i] = self.band_log_e[i] - noise_floor[i];
1201 }
1202 if c == 2 {
1203 for i in 0..end {
1204 mask[i] = mask[i].max(self.band_log_e[NB_BANDS + i] - noise_floor[i]);
1205 }
1206 }
1207 let mut sig = [0.0f32; NB_BANDS];
1208 sig[..end].copy_from_slice(&mask[..end]);
1209 for i in 1..end {
1210 mask[i] = mask[i].max(mask[i - 1] - 2.0);
1211 }
1212 for i in (0..end - 1).rev() {
1213 mask[i] = mask[i].max(mask[i + 1] - 3.0);
1214 }
1215 for i in 0..end {
1216 // SMR: mask is never more than 12 below the peak and never below the
1217 // noise floor.
1218 let smr = sig[i] - 0.0_f32.max(max_depth - 12.0).max(mask[i]);
1219 let shift = (5).min(0.max(-((smr + 0.5).floor() as i32)));
1220 spread_weight[i] = 32 >> shift;
1221 }
1222 // Dynamic allocation can't make us bust the budget (libopus 1036-1037).
1223 if !(effective_bytes > 50 && lm >= 1) {
1224 for i in start..end {
1225 importance[i] = 13;
1226 }
1227 return max_depth;
1228 }
1229 let median3 = |a: &[f32]| -> f32 {
1230 let (x, y, z) = (a[0], a[1], a[2]);
1231 x.max(y).min(z).max(x.min(y))
1232 };
1233 let median5 = |a: &[f32]| -> f32 {
1234 let mut v = [a[0], a[1], a[2], a[3], a[4]];
1235 v.sort_by(|p, q| p.partial_cmp(q).unwrap());
1236 v[2]
1237 };
1238 let mut follower = [0.0f32; 2 * NB_BANDS];
1239 let mut last = 0usize;
1240 for ch in 0..c {
1241 let e2 = &self.band_log_e2[ch * NB_BANDS..ch * NB_BANDS + NB_BANDS];
1242 let f = &mut follower[ch * NB_BANDS..ch * NB_BANDS + NB_BANDS];
1243 f[0] = e2[0];
1244 for i in 1..end {
1245 // The last band at least .5 dB above its predecessor bounds
1246 // the backward pass (band-limited signals).
1247 if e2[i] > e2[i - 1] + 0.5 {
1248 last = i;
1249 }
1250 f[i] = (f[i - 1] + 1.5).min(e2[i]);
1251 }
1252 for i in (0..last).rev() {
1253 f[i] = f[i].min((f[i + 1] + 2.0).min(e2[i]));
1254 }
1255 let offset = 1.0f32;
1256 for i in 2..end.saturating_sub(2) {
1257 f[i] = f[i].max(median5(&e2[i - 2..i + 3]) - offset);
1258 }
1259 let tmp = median3(&e2[0..3]) - offset;
1260 f[0] = f[0].max(tmp);
1261 f[1] = f[1].max(tmp);
1262 let tmp = median3(&e2[end - 3..end]) - offset;
1263 f[end - 2] = f[end - 2].max(tmp);
1264 f[end - 1] = f[end - 1].max(tmp);
1265 for i in 0..end {
1266 f[i] = f[i].max(noise_floor[i]);
1267 }
1268 }
1269 if c == 2 {
1270 for i in start..end {
1271 // 24 dB cross-talk between channels.
1272 follower[NB_BANDS + i] = follower[NB_BANDS + i].max(follower[i] - 4.0);
1273 follower[i] = follower[i].max(follower[NB_BANDS + i] - 4.0);
1274 follower[i] = 0.5
1275 * ((self.band_log_e[i] - follower[i]).max(0.0)
1276 + (self.band_log_e[NB_BANDS + i] - follower[NB_BANDS + i]).max(0.0));
1277 }
1278 } else {
1279 for i in start..end {
1280 follower[i] = (self.band_log_e[i] - follower[i]).max(0.0);
1281 }
1282 }
1283 // Importance for tf_analysis (libopus celt_encoder.c:1176-1189):
1284 // 13 * 2^min(follower, 4), rounded to nearest integer.
1285 for i in start..end {
1286 importance[i] = (13.0 * (2.0_f32).powf(follower[i].min(4.0)) + 0.5).floor() as i32;
1287 }
1288 // Our VBR is always constrained: halve dynalloc on steady frames.
1289 if !is_transient {
1290 for f in &mut follower[start..end] {
1291 *f *= 0.5;
1292 }
1293 }
1294 for i in start..end {
1295 if i < 8 {
1296 follower[i] *= 2.0;
1297 }
1298 if i >= 12 {
1299 follower[i] *= 0.5;
1300 }
1301 }
1302 let mut tot_boost = 0i32;
1303 for i in start..end {
1304 let f = follower[i].min(4.0);
1305 let width = ((c * (E_BANDS[i + 1] - E_BANDS[i])) << lm) as i32;
1306 let (boost, boost_bits) = if width < 6 {
1307 let b = f as i32;
1308 (b, (b * width) << BITRES)
1309 } else if width > 48 {
1310 let b = (f * 8.0) as i32;
1311 (b, ((b * width) << BITRES) / 8)
1312 } else {
1313 let b = (f * width as f32 / 6.0) as i32;
1314 (b, (b * 6) << BITRES)
1315 };
1316 // Constrained VBR, steady frame: dynalloc may take 2/3 of the bits.
1317 if !is_transient && ((tot_boost + boost_bits) >> BITRES >> 3) > 2 * effective_bytes / 3 {
1318 let cap = ((2 * effective_bytes / 3) << BITRES) << 3;
1319 self.offsets[i] = cap - tot_boost;
1320 break;
1321 }
1322 self.offsets[i] = boost;
1323 tot_boost += boost_bits;
1324 }
1325 max_depth
1326 }
1327
1328 /// libopus `spreading_decision` (bands.c:479-570): classifies the current
1329 /// frame's spectral shape as `SPREAD_NONE`/`SPREAD_LIGHT`/`SPREAD_NORMAL`/
1330 /// `SPREAD_AGGRESSIVE` by counting how concentrated the normalized band
1331 /// coefficients are, weighted by the masking-based `spread_weight` from
1332 /// `dynalloc_analysis`. Maintains `tonal_average` (recursive averaging)
1333 /// and applies hysteresis against the previous decision.
1334 ///
1335 /// `update_hf` is always false here (no pitch prefilter), so the
1336 /// `hf_average`/`tapset_decision` state is carried but never updated —
1337 /// matching libopus with `pf_on = false`.
1338 fn spreading_decision(
1339 &mut self,
1340 end: usize,
1341 c: usize,
1342 lm: usize,
1343 spread_weight: &[i32; NB_BANDS],
1344 ) -> usize {
1345 let m = 1usize << lm;
1346 let n0 = SHORT_MDCT << lm; // = M * shortMdctSize
1347 // Last band too narrow: nothing to spread.
1348 if m * (E_BANDS[end] - E_BANDS[end - 1]) <= 8 {
1349 return SPREAD_NONE;
1350 }
1351 let mut sum = 0i32;
1352 let mut nb_bands = 0i32;
1353 for ch in 0..c {
1354 for i in 0..end {
1355 let n = m * (E_BANDS[i + 1] - E_BANDS[i]);
1356 if n <= 8 {
1357 continue;
1358 }
1359 let base = ch * n0 + m * E_BANDS[i];
1360 let x = &self.x[base..base + n];
1361 let mut tcount = [0i32; 3];
1362 for j in 0..n {
1363 // Float-mode: x2N = x[j]^2 * N; thresholds are the literal
1364 // QCONST16 values (0.25, 0.0625, 0.015625).
1365 let x2n = x[j] * x[j] * n as f32;
1366 if x2n < 0.25 {
1367 tcount[0] += 1;
1368 }
1369 if x2n < 0.0625 {
1370 tcount[1] += 1;
1371 }
1372 if x2n < 0.015625 {
1373 tcount[2] += 1;
1374 }
1375 }
1376 // hf_sum accumulation is only used when update_hf is true
1377 // (prefilter on), which never happens here. The branch is
1378 // kept for structural fidelity but the result is unused.
1379 let _hf_sum_contrib = if i > NB_BANDS - 4 {
1380 32 * (tcount[1] + tcount[0]) / n as i32
1381 } else {
1382 0
1383 };
1384 let tmp = (2 * tcount[2] >= n as i32) as i32
1385 + (2 * tcount[1] >= n as i32) as i32
1386 + (2 * tcount[0] >= n as i32) as i32;
1387 sum += tmp * spread_weight[i];
1388 nb_bands += spread_weight[i];
1389 }
1390 }
1391 if nb_bands == 0 {
1392 return self.spread_decision;
1393 }
1394 let mut s = (sum << 8) / nb_bands;
1395 // Recursive averaging.
1396 s = (s + self.tonal_average) >> 1;
1397 self.tonal_average = s;
1398 // Hysteresis against the last decision.
1399 let last = self.spread_decision as i32;
1400 s = (3 * s + (((3 - last) << 7) + 64) + 2) >> 2;
1401 if s < 80 {
1402 SPREAD_AGGRESSIVE
1403 } else if s < 256 {
1404 SPREAD_NORMAL
1405 } else if s < 384 {
1406 SPREAD_LIGHT
1407 } else {
1408 SPREAD_NONE
1409 }
1410 }
1411
1412 fn compute_mdcts(&mut self, short_blocks: usize, lm: usize, n: usize, c: usize) {
1413 let stride = n + OVERLAP;
1414 let (n2, blocks, plan_lm) = if short_blocks != 0 {
1415 (SHORT_MDCT, short_blocks, 0)
1416 } else {
1417 (n, 1, lm)
1418 };
1419 for ch in 0..c {
1420 for b in 0..blocks {
1421 let plan = &mut self.plans[plan_lm];
1422 plan.forward(
1423 &self.in_buf,
1424 ch * stride + b * n2,
1425 &self.window,
1426 &mut self.freq,
1427 ch * n + b,
1428 blocks,
1429 );
1430 }
1431 }
1432 }
1433
1434 /// `alloc_trim_analysis()`: stereo correlation plus spectral tilt.
1435 fn alloc_trim_analysis(&mut self, end: usize, lm: usize, c: usize, n0: usize) -> i32 {
1436 let mut trim = 5i32;
1437 if c == 2 {
1438 let mut sum = 0.0f32;
1439 for i in 0..8 {
1440 let mut partial = 0.0f32;
1441 for j in (E_BANDS[i] << lm)..(E_BANDS[i + 1] << lm) {
1442 partial += self.x[j] * self.x[n0 + j];
1443 }
1444 sum += partial;
1445 }
1446 sum *= 1.0 / 8.0;
1447 if sum > 0.995 {
1448 trim -= 4;
1449 } else if sum > 0.92 {
1450 trim -= 3;
1451 } else if sum > 0.85 {
1452 trim -= 2;
1453 } else if sum > 0.8 {
1454 trim -= 1;
1455 }
1456 // Stereo_saving: inter-channel correlation savings (libopus
1457 // celt_encoder.c:897-920). In float mode all Q macros are
1458 // identity; sum and per-band partial are raw inner products.
1459 let sum_c = sum.abs().min(1.0);
1460 let mut min_xc = sum_c;
1461 for i in 8..self.intensity {
1462 let mut partial = 0.0f32;
1463 for j in (E_BANDS[i] << lm)..(E_BANDS[i + 1] << lm) {
1464 partial += self.x[j] * self.x[n0 + j];
1465 }
1466 min_xc = min_xc.min(partial.abs());
1467 }
1468 min_xc = min_xc.min(1.0);
1469 let log_xc = (1.001 - sum_c * sum_c).log2();
1470 let log_xc2 = (0.5 * log_xc).max((1.001 - min_xc * min_xc).log2());
1471 self.stereo_saving = (self.stereo_saving + 0.25).min(-0.5 * log_xc2);
1472 }
1473 let mut diff = 0.0f32;
1474 for ch in 0..c {
1475 for i in 0..end - 1 {
1476 diff += self.band_log_e[i + ch * NB_BANDS]
1477 * (2 + 2 * i as i32 - NB_BANDS as i32) as f32;
1478 }
1479 }
1480 diff /= (2 * c * (end - 1)) as f32;
1481 if diff > 2.0 {
1482 trim -= 1;
1483 }
1484 if diff > 8.0 {
1485 trim -= 1;
1486 }
1487 if diff < -4.0 {
1488 trim += 1;
1489 }
1490 if diff < -10.0 {
1491 trim += 1;
1492 }
1493 trim.clamp(0, 10)
1494 }
1495
1496 /// libopus `equiv_rate` + `hysteresis_decision()` for the intensity band:
1497 /// the frame's bytes as a 20 ms-equivalent bitrate minus the per-frame
1498 /// overhead, capped by the VBR target. Idempotent within a frame.
1499 fn intensity_decision(&mut self, nb_compressed: usize, c: usize, lm: usize, vbr_rate_bps: u32) {
1500 let overhead = (40 * c as i32 + 20) * ((400 >> lm) - 50);
1501 let mut equiv_rate = ((nb_compressed as i32 * 8 * 50) << (3 - lm)) - overhead;
1502 if vbr_rate_bps > 0 {
1503 equiv_rate = equiv_rate.min(vbr_rate_bps as i32 - overhead);
1504 }
1505 self.intensity = hysteresis_decision(
1506 equiv_rate as f32 / 1000.0,
1507 &INTENSITY_THRESHOLDS,
1508 &INTENSITY_HYSTERESIS,
1509 self.intensity,
1510 );
1511 }
1512
1513 /// `stereo_analysis()`: L1 entropy model of L/R against M/S.
1514 fn stereo_analysis(&self, lm: usize, n0: usize) -> bool {
1515 let mut sum_lr = 1e-15f64;
1516 let mut sum_ms = 1e-15f64;
1517 for i in 0..13 {
1518 for j in (E_BANDS[i] << lm)..(E_BANDS[i + 1] << lm) {
1519 let l = self.x[j] as f64;
1520 let r = self.x[n0 + j] as f64;
1521 sum_lr += l.abs() + r.abs();
1522 sum_ms += (l + r).abs() + (l - r).abs();
1523 }
1524 }
1525 // The reference's own literal (bands.c, stereo_analysis), kept as such.
1526 #[allow(clippy::approx_constant)]
1527 const SQRT_HALF: f64 = 0.707107;
1528 sum_ms *= SQRT_HALF;
1529 let mut thetas = 13;
1530 if lm <= 1 {
1531 thetas -= 8;
1532 }
1533 ((E_BANDS[13] << (lm + 1)) + thetas) as f64 * sum_ms
1534 > ((E_BANDS[13] << (lm + 1)) as f64) * sum_lr
1535 }
1536
1537 // -- Energy --------------------------------------------------------------
1538
1539 #[allow(clippy::too_many_arguments)]
1540 fn quant_coarse_energy(
1541 &mut self,
1542 enc: &mut RangeEncoder,
1543 start: usize,
1544 end: usize,
1545 intra: bool,
1546 c: usize,
1547 lm: usize,
1548 budget: i32,
1549 max_decay: f32,
1550 ) {
1551 let tell = enc.tell() as i32;
1552 if tell + 3 <= budget {
1553 enc.enc_bit_logp(intra, 3);
1554 }
1555 let model = &E_PROB_MODEL[lm][usize::from(intra)];
1556 let (coef, beta) = if intra {
1557 (0.0, BETA_INTRA)
1558 } else {
1559 (PRED_COEF[lm], BETA_COEF[lm])
1560 };
1561 let mut prev = [0.0f32; 2];
1562 for i in start..end {
1563 for (ch, prev) in prev.iter_mut().enumerate().take(c) {
1564 let x = self.band_log_e[i + ch * NB_BANDS];
1565 let old_raw = self.old_band_e[i + ch * NB_BANDS];
1566 let old = old_raw.max(-9.0);
1567 let f = x - coef * old - *prev;
1568 let mut qi = (0.5 + f).floor() as i32;
1569 let decay_bound = old_raw.max(-28.0) - max_decay;
1570 // Prevent the energy from dropping faster than the decoder
1571 // can follow.
1572 if qi < 0 && x < decay_bound {
1573 qi += (decay_bound - x) as i32;
1574 if qi > 0 {
1575 qi = 0;
1576 }
1577 }
1578 let tell = enc.tell() as i32;
1579 let bits_left = budget - tell - 3 * (c as i32) * (end - i) as i32;
1580 if i != start && bits_left < 30 {
1581 if bits_left < 24 {
1582 qi = qi.min(1);
1583 }
1584 if bits_left < 16 {
1585 qi = qi.max(-1);
1586 }
1587 }
1588 if budget - tell >= 15 {
1589 let pi = 2 * i.min(20);
1590 laplace_encode(
1591 enc,
1592 &mut qi,
1593 (model[pi] as u32) << 7,
1594 (model[pi + 1] as i32) << 6,
1595 );
1596 } else if budget - tell >= 2 {
1597 qi = qi.clamp(-1, 1);
1598 enc.enc_icdf(
1599 ((2 * qi) ^ -i32::from(qi < 0)) as usize,
1600 &SMALL_ENERGY_ICDF,
1601 2,
1602 );
1603 } else if budget - tell >= 1 {
1604 qi = qi.min(0);
1605 enc.enc_bit_logp(qi != 0, 1);
1606 } else {
1607 qi = -1;
1608 }
1609 self.error[i + ch * NB_BANDS] = f - qi as f32;
1610 let q = qi as f32;
1611 self.old_band_e[i + ch * NB_BANDS] = coef * old + *prev + q;
1612 *prev += q - beta * q;
1613 }
1614 }
1615 }
1616
1617 #[allow(clippy::too_many_arguments)]
1618 fn tf_encode(
1619 &mut self,
1620 enc: &mut RangeEncoder,
1621 start: usize,
1622 end: usize,
1623 transient: bool,
1624 lm: usize,
1625 mut tf_select: usize,
1626 len: usize,
1627 ) {
1628 let mut budget = (len * 8) as i32;
1629 let mut tell = enc.tell() as i32;
1630 let mut logp: u32 = if transient { 2 } else { 4 };
1631 let tf_select_rsv = lm > 0 && tell + (logp as i32) < budget;
1632 budget -= i32::from(tf_select_rsv);
1633 let mut curr = 0i32;
1634 let mut changed = false;
1635 for i in start..end {
1636 if tell + (logp as i32) <= budget {
1637 enc.enc_bit_logp((self.tf_res[i] ^ curr) != 0, logp);
1638 tell = enc.tell() as i32;
1639 curr = self.tf_res[i];
1640 changed |= curr != 0;
1641 } else {
1642 self.tf_res[i] = curr;
1643 }
1644 logp = if transient { 4 } else { 5 };
1645 }
1646 let t = usize::from(transient);
1647 let ch = usize::from(changed);
1648 if tf_select_rsv && TF_SELECT[lm][4 * t + ch] != TF_SELECT[lm][4 * t + 2 + ch] {
1649 enc.enc_bit_logp(tf_select != 0, 1);
1650 } else {
1651 tf_select = 0;
1652 }
1653 for i in start..end {
1654 self.tf_res[i] = TF_SELECT[lm][4 * t + 2 * tf_select + self.tf_res[i] as usize];
1655 }
1656 }
1657
1658 /// `tf_analysis()` — libopus Viterbi time/frequency search.
1659 /// Writes `self.tf_res[0..len]` and returns `tf_select`.
1660 #[allow(clippy::too_many_arguments)]
1661 fn tf_analysis(
1662 &mut self,
1663 len: usize,
1664 is_transient: bool,
1665 lambda: i32,
1666 n: usize,
1667 lm: usize,
1668 tf_estimate: f32,
1669 tf_chan: usize,
1670 importance: &[i32; NB_BANDS],
1671 ) -> usize {
1672 // bias = 0.04 * max(-0.25, 0.5 - tf_estimate)
1673 let bias = 0.04 * (0.5 - tf_estimate).max(-0.25);
1674 let t = usize::from(is_transient);
1675
1676 let mut metric = [0i32; NB_BANDS];
1677 let mut path0 = [0i32; NB_BANDS];
1678 let mut path1 = [0i32; NB_BANDS];
1679 let mut tf_res = [0i32; NB_BANDS];
1680
1681 // Max band width for tmp/tmp_1 scratch
1682 let max_band_w = ((E_BANDS[len] - E_BANDS[len - 1]) << lm).max(1);
1683 let (tmp_s, tmp_1_s) = self.hadamard_tmp.split_at_mut(max_band_w);
1684 let x = &self.x;
1685
1686 for i in 0..len {
1687 let band_w = (E_BANDS[i + 1] - E_BANDS[i]) << lm;
1688 let narrow = E_BANDS[i + 1] - E_BANDS[i] == 1;
1689 let tmp = &mut tmp_s[..band_w];
1690 let tmp_1 = &mut tmp_1_s[..band_w];
1691
1692 // Copy band coefficients: X[tf_chan*N0 + (eBands[i]<<LM)]
1693 let offset = tf_chan * n + (E_BANDS[i] << lm);
1694 tmp.copy_from_slice(&x[offset..offset + band_w]);
1695
1696 let mut best_level = 0i32;
1697 let mut best_l1 = l1_metric(tmp, band_w, if is_transient { lm } else { 0 }, bias);
1698
1699 // Check the -1 case for transients
1700 if is_transient && !narrow {
1701 tmp_1.copy_from_slice(tmp);
1702 haar1(tmp_1, band_w >> lm, 1 << lm);
1703 let l1 = l1_metric(tmp_1, band_w, lm + 1, bias);
1704 if l1 < best_l1 {
1705 best_l1 = l1;
1706 best_level = -1;
1707 }
1708 }
1709
1710 for k in 0..(lm + usize::from(!(is_transient || narrow))) {
1711 let b = if is_transient { lm - k - 1 } else { k + 1 };
1712 haar1(tmp, band_w >> k, 1 << k);
1713 let l1 = l1_metric(tmp, band_w, b, bias);
1714 if l1 < best_l1 {
1715 best_l1 = l1;
1716 best_level = (k as i32) + 1;
1717 }
1718 }
1719
1720 metric[i] = if is_transient { 2 * best_level } else { -2 * best_level };
1721 if narrow && (metric[i] == 0 || metric[i] == -2 * lm as i32) {
1722 metric[i] -= 1;
1723 }
1724 }
1725
1726 // Search for optimal tf resolution (tf_select)
1727 let mut tf_select = 0usize;
1728 let mut selcost = [0i32; 2];
1729 for sel in 0..2 {
1730 let mut cost0 = importance[0] * (metric[0] - 2 * TF_SELECT[lm][4 * t + 2 * sel]).abs();
1731 let mut cost1 = importance[0] * (metric[0] - 2 * TF_SELECT[lm][4 * t + 2 * sel + 1]).abs()
1732 + if is_transient { 0 } else { lambda };
1733 for i in 1..len {
1734 let curr0 = cost0.min(cost1 + lambda);
1735 let curr1 = (cost0 + lambda).min(cost1);
1736 cost0 = curr0 + importance[i] * (metric[i] - 2 * TF_SELECT[lm][4 * t + 2 * sel]).abs();
1737 cost1 = curr1 + importance[i] * (metric[i] - 2 * TF_SELECT[lm][4 * t + 2 * sel + 1]).abs();
1738 }
1739 selcost[sel] = cost0.min(cost1);
1740 }
1741 if selcost[1] < selcost[0] && is_transient {
1742 tf_select = 1;
1743 }
1744
1745 // Final Viterbi forward pass
1746 let mut cost0 = importance[0] * (metric[0] - 2 * TF_SELECT[lm][4 * t + 2 * tf_select]).abs();
1747 let mut cost1 = importance[0] * (metric[0] - 2 * TF_SELECT[lm][4 * t + 2 * tf_select + 1]).abs()
1748 + if is_transient { 0 } else { lambda };
1749 for i in 1..len {
1750 // curr0: best path to state 0
1751 let from0 = cost0;
1752 let from1 = cost1 + lambda;
1753 let (curr0, p0) = if from0 < from1 { (from0, 0) } else { (from1, 1) };
1754 path0[i] = p0;
1755 // curr1: best path to state 1 (uses OLD cost0)
1756 let from0 = cost0 + lambda;
1757 let from1 = cost1;
1758 let (curr1, p1) = if from0 < from1 { (from0, 0) } else { (from1, 1) };
1759 path1[i] = p1;
1760
1761 cost0 = curr0 + importance[i] * (metric[i] - 2 * TF_SELECT[lm][4 * t + 2 * tf_select]).abs();
1762 cost1 = curr1 + importance[i] * (metric[i] - 2 * TF_SELECT[lm][4 * t + 2 * tf_select + 1]).abs();
1763 }
1764
1765 // Backward pass
1766 tf_res[len - 1] = if cost0 < cost1 { 0 } else { 1 };
1767 for i in (0..len - 1).rev() {
1768 tf_res[i] = if tf_res[i + 1] == 1 { path1[i + 1] } else { path0[i + 1] };
1769 }
1770
1771 self.tf_res = tf_res;
1772 tf_select
1773 }
1774
1775 // -- Band shapes ---------------------------------------------------------
1776
1777 #[allow(clippy::too_many_arguments)]
1778 fn quant_all_bands(
1779 &mut self,
1780 enc: &mut RangeEncoder,
1781 start: usize,
1782 end: usize,
1783 short_blocks: usize,
1784 spread: usize,
1785 mut dual_stereo: bool,
1786 intensity: usize,
1787 total_bits: i32,
1788 mut balance: i32,
1789 lm: usize,
1790 coded_bands: usize,
1791 c: usize,
1792 n: usize,
1793 ) {
1794 let m = 1usize << lm;
1795 let blocks = if short_blocks != 0 { m } else { 1 };
1796 for i in start..end {
1797 let n_band = m * E_BANDS[i + 1] - m * E_BANDS[i];
1798 let tell = enc.tell_frac() as i32;
1799 if i != start {
1800 balance -= tell;
1801 }
1802 let mut remaining_bits = total_bits - tell - 1;
1803 let b = if i < coded_bands {
1804 let curr_balance = balance / 3.min(coded_bands - i) as i32;
1805 0.max(16383.min((remaining_bits + 1).min(self.pulses[i] + curr_balance)))
1806 } else {
1807 0
1808 };
1809 let tf_change = self.tf_res[i];
1810 if dual_stereo && i == intensity {
1811 dual_stereo = false;
1812 }
1813 let x_off = m * E_BANDS[i];
1814 let base = EncBand {
1815 i,
1816 x: x_off,
1817 y: None,
1818 n: n_band,
1819 b,
1820 spread,
1821 blocks,
1822 intensity,
1823 tf_change,
1824 level: 0,
1825 lm: lm as i32,
1826 };
1827 if dual_stereo {
1828 self.quant_band(enc, EncBand { b: b / 2, ..base }, &mut remaining_bits);
1829 self.quant_band(
1830 enc,
1831 EncBand {
1832 x: n + x_off,
1833 b: b / 2,
1834 ..base
1835 },
1836 &mut remaining_bits,
1837 );
1838 } else {
1839 self.quant_band(
1840 enc,
1841 EncBand {
1842 y: if c == 2 { Some(n + x_off) } else { None },
1843 ..base
1844 },
1845 &mut remaining_bits,
1846 );
1847 }
1848 balance += self.pulses[i] + tell;
1849 }
1850 }
1851
1852 /// Encodes one band (Section 5.3.4-5.3.5), recursing for splits and for
1853 /// stereo. The mirror of the decoder's `quant_band`, with the resynthesis
1854 /// paths removed — nothing the encoder writes depends on them.
1855 fn quant_band(&mut self, enc: &mut RangeEncoder, a: EncBand, remaining_bits: &mut i32) {
1856 let EncBand {
1857 i,
1858 x,
1859 mut y,
1860 mut n,
1861 mut b,
1862 spread,
1863 mut blocks,
1864 intensity,
1865 mut tf_change,
1866 level,
1867 mut lm,
1868 } = a;
1869 let stereo = y.is_some();
1870 let mut split = stereo;
1871 let long_blocks = blocks == 1;
1872 let mut b0 = blocks;
1873
1874 if n == 1 {
1875 for offs in [Some(x), y].into_iter().flatten() {
1876 if *remaining_bits >= 1 << BITRES {
1877 let sign = self.x[offs] < 0.0;
1878 enc.enc_bits(u32::from(sign), 1);
1879 *remaining_bits -= 1 << BITRES;
1880 }
1881 }
1882 return;
1883 }
1884
1885 let mut n_b = n / blocks;
1886 if !stereo && level == 0 {
1887 let recombine = if tf_change > 0 { tf_change as usize } else { 0 };
1888 for k in 0..recombine {
1889 haar1(&mut self.x[x..], n >> k, 1 << k);
1890 }
1891 blocks >>= recombine;
1892 n_b <<= recombine;
1893 while (n_b & 1) == 0 && tf_change < 0 {
1894 haar1(&mut self.x[x..], n_b, blocks);
1895 blocks <<= 1;
1896 n_b >>= 1;
1897 tf_change += 1;
1898 }
1899 b0 = blocks;
1900 if b0 > 1 {
1901 deinterleave_hadamard(
1902 &mut self.x[x..x + n],
1903 &mut self.hadamard_tmp,
1904 n_b >> recombine,
1905 b0 << recombine,
1906 long_blocks,
1907 );
1908 }
1909 }
1910
1911 let cache_start = cache_index(i, lm);
1912 let cache0 = CACHE_BITS[cache_start] as usize;
1913 if !stereo && lm != -1 && b > CACHE_BITS[cache_start + cache0] as i32 + 12 && n > 2 {
1914 n >>= 1;
1915 y = Some(x + n);
1916 split = true;
1917 lm -= 1;
1918 blocks = (blocks + 1) >> 1;
1919 }
1920
1921 if split {
1922 let pulse_cap = LOG_N[i] + lm * (1 << BITRES);
1923 let offset = (pulse_cap >> 1)
1924 - if stereo && n == 2 {
1925 QTHETA_OFFSET_TWOPHASE
1926 } else {
1927 QTHETA_OFFSET
1928 };
1929 let mut qn = compute_qn(n as i32, b, offset, pulse_cap, stereo);
1930 if stereo && i >= intensity {
1931 qn = 1;
1932 }
1933 // The angle between the two halves, before any quantisation.
1934 let mut itheta = {
1935 let yy = y.unwrap();
1936 let (xs, ys) = (&self.x[x..x + n], &self.x[yy..yy + n]);
1937 stereo_itheta(xs, ys, stereo, n)
1938 };
1939 let tell = enc.tell_frac() as i32;
1940 if qn != 1 {
1941 itheta = (itheta * qn + 8192) >> 14;
1942 // Entropy coding of the angle: step pdf for stereo, uniform
1943 // for the time split, triangular otherwise.
1944 if stereo && n > 2 {
1945 let p0 = 3i32;
1946 let x0 = qn / 2;
1947 let ft = (p0 * (x0 + 1) + x0) as u32;
1948 let xv = itheta;
1949 let (fl, fh) = if xv <= x0 {
1950 (p0 * xv, p0 * (xv + 1))
1951 } else {
1952 ((xv - 1 - x0) + (x0 + 1) * p0, (xv - x0) + (x0 + 1) * p0)
1953 };
1954 enc.encode(fl as u32, fh as u32, ft);
1955 } else if b0 > 1 || stereo {
1956 enc.enc_uint(itheta as u32, (qn + 1) as u32);
1957 } else {
1958 let ft = ((qn >> 1) + 1) * ((qn >> 1) + 1);
1959 let (fl, fs) = if itheta <= qn >> 1 {
1960 ((itheta * (itheta + 1)) >> 1, itheta + 1)
1961 } else {
1962 (
1963 ft - (((qn + 1 - itheta) * (qn + 2 - itheta)) >> 1),
1964 qn + 1 - itheta,
1965 )
1966 };
1967 enc.encode(fl as u32, (fl + fs) as u32, ft as u32);
1968 }
1969 itheta = itheta * 16384 / qn;
1970 if stereo {
1971 let yy = y.unwrap();
1972 if itheta == 0 {
1973 self.intensity_stereo(i, x, yy, n);
1974 } else {
1975 // stereo_split
1976 for j in 0..n {
1977 let l = core::f32::consts::FRAC_1_SQRT_2 * self.x[x + j];
1978 let r = core::f32::consts::FRAC_1_SQRT_2 * self.x[yy + j];
1979 self.x[x + j] = l + r;
1980 self.x[yy + j] = r - l;
1981 }
1982 }
1983 }
1984 } else if stereo {
1985 let yy = y.unwrap();
1986 let inv = itheta > 8192;
1987 if inv {
1988 for j in 0..n {
1989 self.x[yy + j] = -self.x[yy + j];
1990 }
1991 }
1992 self.intensity_stereo(i, x, yy, n);
1993 if b > 2 << BITRES && *remaining_bits > 2 << BITRES {
1994 enc.enc_bit_logp(inv, 2);
1995 }
1996 itheta = 0;
1997 }
1998 let qalloc = enc.tell_frac() as i32 - tell;
1999 b -= qalloc;
2000
2001 let mut delta;
2002 let imid;
2003 let iside;
2004 if itheta == 0 {
2005 imid = 32767;
2006 iside = 0;
2007 delta = -16384;
2008 } else if itheta == 16384 {
2009 imid = 0;
2010 iside = 32767;
2011 delta = 16384;
2012 } else {
2013 imid = bitexact_cos(itheta as i16) as i32;
2014 iside = bitexact_cos((16384 - itheta) as i16) as i32;
2015 delta = frac_mul16(
2016 ((n as i32 - 1) << 7) as i16,
2017 bitexact_log2tan(iside, imid) as i16,
2018 );
2019 }
2020 let _ = imid;
2021 let _ = iside;
2022
2023 if n == 2 && stereo {
2024 let mut mbits = b;
2025 let mut sbits = 0;
2026 if itheta != 0 && itheta != 16384 {
2027 sbits = 1 << BITRES;
2028 }
2029 mbits -= sbits;
2030 let yy = y.unwrap();
2031 let swap = itheta > 8192;
2032 *remaining_bits -= qalloc + sbits;
2033 let (x2, y2) = if swap { (yy, x) } else { (x, yy) };
2034 if sbits != 0 {
2035 let sign = self.x[x2] * self.x[y2 + 1] - self.x[x2 + 1] * self.x[y2] < 0.0;
2036 enc.enc_bits(u32::from(sign), 1);
2037 }
2038 self.quant_band(
2039 enc,
2040 EncBand {
2041 x: x2,
2042 y: None,
2043 n,
2044 b: mbits,
2045 blocks,
2046 tf_change,
2047 lm,
2048 ..a
2049 },
2050 remaining_bits,
2051 );
2052 } else {
2053 if b0 > 1 && !stereo && (itheta & 0x3fff) != 0 {
2054 if itheta > 8192 {
2055 delta -= delta >> (4 - lm);
2056 } else {
2057 delta = 0.min(delta + ((n as i32) << BITRES >> (5 - lm)));
2058 }
2059 }
2060 let mut mbits = 0.max(b.min((b - delta) / 2));
2061 let mut sbits = b - mbits;
2062 *remaining_bits -= qalloc;
2063 let next_level = if stereo { level } else { level + 1 };
2064 let mid_args = EncBand {
2065 x,
2066 y: None,
2067 n,
2068 blocks,
2069 tf_change,
2070 level: next_level,
2071 lm,
2072 ..a
2073 };
2074 let side_args = EncBand {
2075 x: y.unwrap(),
2076 y: None,
2077 n,
2078 blocks,
2079 tf_change,
2080 level: next_level,
2081 lm,
2082 ..a
2083 };
2084 let mut rebalance = *remaining_bits;
2085 if mbits >= sbits {
2086 self.quant_band(
2087 enc,
2088 EncBand {
2089 b: mbits,
2090 ..mid_args
2091 },
2092 remaining_bits,
2093 );
2094 rebalance = mbits - (rebalance - *remaining_bits);
2095 if rebalance > 3 << BITRES && itheta != 0 {
2096 sbits += rebalance - (3 << BITRES);
2097 }
2098 self.quant_band(
2099 enc,
2100 EncBand {
2101 b: sbits,
2102 ..side_args
2103 },
2104 remaining_bits,
2105 );
2106 } else {
2107 self.quant_band(
2108 enc,
2109 EncBand {
2110 b: sbits,
2111 ..side_args
2112 },
2113 remaining_bits,
2114 );
2115 rebalance = sbits - (rebalance - *remaining_bits);
2116 if rebalance > 3 << BITRES && itheta != 16384 {
2117 mbits += rebalance - (3 << BITRES);
2118 }
2119 self.quant_band(
2120 enc,
2121 EncBand {
2122 b: mbits,
2123 ..mid_args
2124 },
2125 remaining_bits,
2126 );
2127 }
2128 }
2129 } else {
2130 // The basic no-split case: straight PVQ.
2131 let mut q = bits2pulses(i, lm, b);
2132 let mut curr_bits = pulses2bits(i, lm, q);
2133 *remaining_bits -= curr_bits;
2134 while *remaining_bits < 0 && q > 0 {
2135 *remaining_bits += curr_bits;
2136 q -= 1;
2137 curr_bits = pulses2bits(i, lm, q);
2138 *remaining_bits -= curr_bits;
2139 }
2140 if q != 0 {
2141 let k = get_pulses(q) as usize;
2142 self.alg_quant(enc, x, n, k, spread, blocks);
2143 }
2144 // q == 0: the decoder folds or fills with noise on its own;
2145 // nothing is coded.
2146 }
2147 }
2148
2149 /// `intensity_stereo()`: collapses the pair onto a single channel weighted
2150 /// by the band energies; only the combined channel is coded.
2151 fn intensity_stereo(&mut self, band: usize, x: usize, y: usize, n: usize) {
2152 let left = self.band_e[band];
2153 let right = self.band_e[band + NB_BANDS];
2154 let norm = 1e-15 + (1e-15 + left * left + right * right).sqrt();
2155 let a1 = left / norm;
2156 let a2 = right / norm;
2157 for j in 0..n {
2158 let l = self.x[x + j];
2159 let r = self.x[y + j];
2160 self.x[x + j] = a1 * l + a2 * r;
2161 }
2162 }
2163
2164 /// `alg_quant()`: the PVQ search — greedy pyramid projection plus one
2165 /// pulse at a time on the exact `Rxy^2/Ryy` criterion — then the
2166 /// enumeration encode.
2167 fn alg_quant(
2168 &mut self,
2169 enc: &mut RangeEncoder,
2170 x: usize,
2171 n: usize,
2172 k: usize,
2173 spread: usize,
2174 blocks: usize,
2175 ) {
2176 debug_assert!(n > 1 && k > 0);
2177 exp_rotation(&mut self.x[x..x + n], n, 1, blocks, k, spread);
2178 let xs = &mut self.x[x..x + n];
2179 let iy = &mut self.iy[..n];
2180 let y = &mut self.pvq_y[..n];
2181 let signs = &mut self.pvq_sign[..n];
2182 for j in 0..n {
2183 if xs[j] > 0.0 {
2184 signs[j] = 1;
2185 } else {
2186 signs[j] = -1;
2187 xs[j] = -xs[j];
2188 }
2189 iy[j] = 0;
2190 y[j] = 0.0;
2191 }
2192 let mut xy = 0.0f32;
2193 let mut yy = 0.0f32;
2194 let mut pulses_left = k as i32;
2195 if k > n >> 1 {
2196 let mut sum = 0.0f32;
2197 for v in xs.iter() {
2198 sum += *v;
2199 }
2200 if !(sum > 1e-15 && sum < 64.0) {
2201 xs[0] = 1.0;
2202 for v in xs.iter_mut().skip(1) {
2203 *v = 0.0;
2204 }
2205 sum = 1.0;
2206 }
2207 let rcp = (k as f32 - 1.0) / sum;
2208 for j in 0..n {
2209 iy[j] = (rcp * xs[j]).floor() as i32;
2210 y[j] = iy[j] as f32;
2211 yy += y[j] * y[j];
2212 xy += xs[j] * y[j];
2213 y[j] *= 2.0;
2214 pulses_left -= iy[j];
2215 }
2216 }
2217 debug_assert!(pulses_left >= 1);
2218 if pulses_left > n as i32 + 3 {
2219 let tmp = pulses_left as f32;
2220 yy += tmp * tmp;
2221 yy += tmp * y[0];
2222 iy[0] += pulses_left;
2223 pulses_left = 0;
2224 }
2225 // The pulse-placement search is the encoder's hottest loop — O(K*N)
2226 // per band, dominant at high rates — so it runs eight candidates a
2227 // lane with `wide`. Lane-local bests are reduced after the sweep;
2228 // only the tie-breaking order differs from the scalar loop, and any
2229 // pulse choice is a valid codeword — the enumeration, not the
2230 // search, is what conformance constrains.
2231 for _ in 0..pulses_left {
2232 yy += 1.0;
2233 let mut best_id = 0usize;
2234 let mut best_num = -1e15f32;
2235 let mut best_den = 0.0f32;
2236 let mut j0 = 0usize;
2237 if n >= 16 {
2238 use wide::f32x8;
2239 let chunks = n / 8;
2240 let xy_v = f32x8::splat(xy);
2241 let yy_v = f32x8::splat(yy);
2242 let mut bn = f32x8::splat(-1e15);
2243 let mut bd = f32x8::splat(0.0);
2244 let mut bc = f32x8::splat(0.0);
2245 for c in 0..chunks {
2246 let mut xa = [0f32; 8];
2247 let mut ya = [0f32; 8];
2248 xa.copy_from_slice(&xs[c * 8..c * 8 + 8]);
2249 ya.copy_from_slice(&y[c * 8..c * 8 + 8]);
2250 let rxy = xy_v + f32x8::from(xa);
2251 let ryy = yy_v + f32x8::from(ya);
2252 let rxy2 = rxy * rxy;
2253 let mask = (bd * rxy2).simd_gt(ryy * bn);
2254 // wide 1.5 deprecates `blend` in favour of a split that
2255 // does not exist yet in this release; the mask here is a
2256 // true lane mask, which is exactly blend's contract.
2257 #[allow(deprecated)]
2258 {
2259 bn = mask.blend(rxy2, bn);
2260 bd = mask.blend(ryy, bd);
2261 bc = mask.blend(f32x8::splat(c as f32), bc);
2262 }
2263 }
2264 let bn_a: [f32; 8] = bn.into();
2265 let bd_a: [f32; 8] = bd.into();
2266 let bc_a: [f32; 8] = bc.into();
2267 for l in 0..8 {
2268 if best_den * bn_a[l] > bd_a[l] * best_num {
2269 best_den = bd_a[l];
2270 best_num = bn_a[l];
2271 best_id = bc_a[l] as usize * 8 + l;
2272 }
2273 }
2274 j0 = chunks * 8;
2275 }
2276 for j in j0..n {
2277 let rxy = xy + xs[j];
2278 let ryy = yy + y[j];
2279 let rxy2 = rxy * rxy;
2280 if best_den * rxy2 > ryy * best_num {
2281 best_den = ryy;
2282 best_num = rxy2;
2283 best_id = j;
2284 }
2285 }
2286 xy += xs[best_id];
2287 yy += y[best_id];
2288 y[best_id] += 2.0;
2289 iy[best_id] += 1;
2290 }
2291 for j in 0..n {
2292 if signs[j] < 0 {
2293 iy[j] = -iy[j];
2294 }
2295 }
2296 if self.urow.len() < k + 2 {
2297 self.urow.resize(k + 2, 0);
2298 }
2299 encode_pulses(enc, &self.iy[..n], n, k, &mut self.urow);
2300 }
2301}
2302
2303#[cfg(test)]
2304mod tests {
2305 use super::*;
2306 use crate::range::RangeDecoder;
2307
2308 /// The forward MDCT against the transform's definition, at the 2/l scale
2309 /// CELT puts on the analysis side.
2310 #[test]
2311 fn forward_mdct_matches_the_definition() {
2312 for &l in &[120usize, 240, 480, 960] {
2313 let w = celt::overlap_window();
2314 let flat = (l - OVERLAP) / 2;
2315 // The full 2l low-overlap window.
2316 let mut win = vec![0.0f32; 2 * l];
2317 for i in 0..l {
2318 win[i] = if i < flat {
2319 0.0
2320 } else if i < flat + OVERLAP {
2321 w[i - flat]
2322 } else {
2323 1.0
2324 };
2325 win[2 * l - 1 - i] = win[i];
2326 }
2327 // A signal over the window's support, zero-padded to 2l.
2328 let support = l + OVERLAP;
2329 let sig: Vec<f32> = (0..support)
2330 .map(|i| ((i * 2654435761usize) % 2000) as f32 / 1000.0 - 1.0)
2331 .collect();
2332 let mut x2l = vec![0.0f32; 2 * l];
2333 for j in 0..support {
2334 x2l[flat + j] = win[flat + j] * sig[j];
2335 }
2336 // Direct MDCT by definition.
2337 let direct: Vec<f64> = (0..l)
2338 .map(|k| {
2339 let mut sum = 0.0f64;
2340 for (nn, &v) in x2l.iter().enumerate() {
2341 let a = core::f64::consts::PI / l as f64
2342 * (nn as f64 + 0.5 + l as f64 / 2.0)
2343 * (k as f64 + 0.5);
2344 sum += v as f64 * a.cos();
2345 }
2346 sum * 2.0 / l as f64
2347 })
2348 .collect();
2349 let mut plan = MdctPlan::new(l);
2350 let mut out = vec![0.0f32; l];
2351 plan.forward(&sig, 0, &w, &mut out, 0, 1);
2352 let mut worst = 0.0f64;
2353 for k in 0..l {
2354 worst = worst.max((direct[k] - out[k] as f64).abs());
2355 }
2356 assert!(worst < 1e-4, "l={l}: worst coefficient error {worst}");
2357 }
2358 }
2359
2360 /// encode_pulses must invert decode_pulses for every (n, k) shape the
2361 /// allocation can produce.
2362 #[test]
2363 fn pulse_enumeration_round_trips() {
2364 let mut state = 0x2545F491u32;
2365 let mut rand = move || {
2366 state ^= state << 13;
2367 state ^= state >> 17;
2368 state ^= state << 5;
2369 state
2370 };
2371 for &(n, k) in &[
2372 (2usize, 1usize),
2373 (2, 8),
2374 (3, 4),
2375 (4, 6),
2376 (5, 3),
2377 (8, 10),
2378 (16, 7),
2379 (24, 4),
2380 (48, 2),
2381 (96, 1),
2382 (176, 2),
2383 (22, 8),
2384 (32, 6),
2385 (11, 12),
2386 (64, 4),
2387 ] {
2388 for _ in 0..20 {
2389 // A random pulse vector with |y| summing to k.
2390 let mut iy = vec![0i32; n];
2391 for _ in 0..k {
2392 let j = (rand() as usize) % n;
2393 iy[j] += 1;
2394 }
2395 for v in iy.iter_mut() {
2396 if *v != 0 && rand() & 1 == 1 {
2397 *v = -*v;
2398 }
2399 }
2400 let mut enc = RangeEncoder::new();
2401 enc.reset(600);
2402 let mut u = vec![0u32; k + 2];
2403 encode_pulses(&mut enc, &iy, n, k, &mut u);
2404 enc.done();
2405 assert!(!enc.error());
2406 let data = enc.data().to_vec();
2407 let mut dec = RangeDecoder::new(&data);
2408 let mut got = vec![0i32; n];
2409 let mut u2 = vec![0u32; k + 2];
2410 crate::celt::decode_pulses(&mut dec, n, k, &mut got, &mut u2);
2411 assert_eq!(got, iy, "n={n} k={k}");
2412 }
2413 }
2414 }
2415
2416 /// The Laplace encoder against the decoder, over the whole coarse-energy
2417 /// model space.
2418 #[test]
2419 fn laplace_round_trips() {
2420 #[allow(clippy::needless_range_loop)]
2421 for lm in 0..4 {
2422 for intra in 0..2 {
2423 for band in 0..21usize {
2424 let model = &E_PROB_MODEL[lm][intra];
2425 let pi = 2 * band.min(20);
2426 let fs = (model[pi] as u32) << 7;
2427 let decay = (model[pi + 1] as i32) << 6;
2428 for val in -12i32..=12 {
2429 let mut enc = RangeEncoder::new();
2430 enc.reset(64);
2431 let mut v = val;
2432 laplace_encode(&mut enc, &mut v, fs, decay);
2433 enc.done();
2434 let data = enc.data().to_vec();
2435 let mut dec = RangeDecoder::new(&data);
2436 let got = crate::celt::laplace_decode(&mut dec, fs, decay);
2437 assert_eq!(got, v, "lm={lm} intra={intra} band={band} val={val}");
2438 }
2439 }
2440 }
2441 }
2442 }
2443
2444 fn allocation_caps(lm: usize, c: usize) -> [i32; NB_BANDS] {
2445 let mut caps = [0i32; NB_BANDS];
2446 for i in 0..NB_BANDS {
2447 let bw = (E_BANDS[i + 1] - E_BANDS[i]) << lm;
2448 caps[i] =
2449 ((CACHE_CAPS[NB_BANDS * (2 * lm + c - 1) + i] as i32 + 64) * c as i32 * bw as i32)
2450 >> 2;
2451 }
2452 caps
2453 }
2454
2455 #[test]
2456 fn allocation_encoder_and_decoder_match_on_grid() {
2457 let frame_grid = [(0usize, 120usize), (1, 240), (2, 480), (3, 960)];
2458 let bitrate_grid = [16_000i32, 24_000, 48_000, 96_000, 192_000];
2459 let stereo_grid = [
2460 (0usize, false),
2461 (8, false),
2462 (12, true),
2463 (18, false),
2464 (NB_BANDS, true),
2465 ];
2466
2467 for &(lm, frame_size) in &frame_grid {
2468 assert_eq!(SHORT_MDCT << lm, frame_size);
2469 for &bitrate in &bitrate_grid {
2470 for &c in &[1usize, 2] {
2471 let start = 0usize;
2472 let end = NB_BANDS;
2473 let caps = allocation_caps(lm, c);
2474 let mut offsets = [0i32; NB_BANDS];
2475 for i in start..end {
2476 if (i + lm + bitrate as usize / 8_000 + c).is_multiple_of(7) {
2477 let width = ((c * (E_BANDS[i + 1] - E_BANDS[i])) << lm) as i32;
2478 offsets[i] = (width << BITRES).min(caps[i] / 2).max(0);
2479 }
2480 }
2481 let total = ((bitrate * frame_size as i32 / 48_000) << BITRES).max(2 << BITRES);
2482 let trim = ((bitrate / 24_000) + lm as i32 + c as i32).rem_euclid(11);
2483 let prev = end.saturating_sub((bitrate as usize / 24_000 + lm + c) % 6);
2484 let stereo_cases: &[(usize, bool)] =
2485 if c == 2 { &stereo_grid } else { &[(0, false)] };
2486
2487 for &(requested_intensity, requested_dual) in stereo_cases {
2488 let mut ep = [0i32; NB_BANDS];
2489 let mut ef = [0i32; NB_BANDS];
2490 let mut eprio = [0i32; NB_BANDS];
2491 let mut enc = RangeEncoder::new();
2492 enc.reset(64);
2493 let er = compute_allocation_encode(
2494 &mut enc,
2495 start,
2496 end,
2497 trim,
2498 total,
2499 c,
2500 lm,
2501 &offsets,
2502 &caps,
2503 &mut ep,
2504 &mut ef,
2505 &mut eprio,
2506 requested_intensity,
2507 requested_dual,
2508 prev,
2509 );
2510 let enc_tell = enc.tell_frac();
2511 enc.done();
2512 assert!(!enc.error());
2513
2514 let data = enc.data().to_vec();
2515 let mut dp = [0i32; NB_BANDS];
2516 let mut df = [0i32; NB_BANDS];
2517 let mut dprio = [0i32; NB_BANDS];
2518 let mut dec = RangeDecoder::new(&data);
2519 let dr = celt::compute_allocation_decode(
2520 &mut dec, start, end, trim, total, c, lm, &offsets, &caps, &mut dp,
2521 &mut df, &mut dprio,
2522 );
2523
2524 assert_eq!(dr, er, "lm={lm} bitrate={bitrate} c={c}");
2525 assert_eq!(
2526 dec.tell_frac(),
2527 enc_tell,
2528 "tell lm={lm} bitrate={bitrate} c={c}"
2529 );
2530 assert_eq!(
2531 &dp[start..end],
2532 &ep[start..end],
2533 "pulses lm={lm} bitrate={bitrate} c={c}"
2534 );
2535 assert_eq!(
2536 &df[start..end],
2537 &ef[start..end],
2538 "fine lm={lm} bitrate={bitrate} c={c}"
2539 );
2540 assert_eq!(
2541 &dprio[start..end],
2542 &eprio[start..end],
2543 "priority lm={lm} bitrate={bitrate} c={c}"
2544 );
2545 }
2546 }
2547 }
2548 }
2549 }
2550}
2551
2552const INTENSITY_THRESHOLDS: [f32; 21] = [
2553 1., 2., 3., 4., 5., 6., 7., 8., 16., 24., 36., 44., 50., 56., 62., 67., 72., 79., 88., 106.,
2554 134.,
2555];
2556const INTENSITY_HYSTERESIS: [f32; 21] =
2557 [1., 1., 1., 1., 1., 1., 1., 2., 2., 2., 2., 2., 2., 2., 3., 3., 4., 5., 6., 8., 8.];
2558
2559/// libopus `hysteresis_decision()`: the largest `i` with `val >= thresholds[i]`,
2560/// sticky around the previous decision by `hysteresis`.
2561fn hysteresis_decision(val: f32, thresholds: &[f32], hysteresis: &[f32], prev: usize) -> usize {
2562 let n = thresholds.len();
2563 let mut i = 0;
2564 while i < n {
2565 if val < thresholds[i] {
2566 break;
2567 }
2568 i += 1;
2569 }
2570 if i > prev && val < thresholds[prev] + hysteresis[prev] {
2571 i = prev;
2572 }
2573 if i < prev && val > thresholds[prev - 1] - hysteresis[prev - 1] {
2574 i = prev;
2575 }
2576 i
2577}