Skip to main content

rusty_opus/
celt.rs

1use crate::bands::{
2    SPREAD_NONE, SPREAD_NORMAL, compute_band_energies, denormalise_bands, haar1, log2amp,
3    normalise_bands, quant_all_bands, spreading_decision,
4};
5use crate::modes::{CeltMode, SPREAD_ICDF, TAPSET_ICDF, TF_SELECT_TABLE, TRIM_ICDF};
6use crate::quant_bands::{
7    quant_coarse_energy_advanced, quant_energy_finalise, quant_fine_energy, unquant_coarse_energy,
8    unquant_energy_finalise, unquant_fine_energy,
9};
10use crate::range_coder::RangeCoder;
11use crate::rate::{BITRES, clt_compute_allocation};
12
13#[cfg(target_arch = "aarch64")]
14use std::arch::aarch64::*;
15
16#[cfg(target_arch = "aarch64")]
17#[inline(always)]
18#[allow(unsafe_op_in_unsafe_fn)]
19unsafe fn sum_abs_neon(x: &[f32], n: usize) -> f32 {
20    let mut sum_vec = vdupq_n_f32(0.0);
21    let mut i = 0;
22
23    while i + 16 <= n {
24        let x0 = vld1q_f32(x.as_ptr().add(i));
25        let x1 = vld1q_f32(x.as_ptr().add(i + 4));
26        let x2 = vld1q_f32(x.as_ptr().add(i + 8));
27        let x3 = vld1q_f32(x.as_ptr().add(i + 12));
28
29        sum_vec = vfmaq_f32(sum_vec, vabsq_f32(x0), vdupq_n_f32(1.0));
30        sum_vec = vfmaq_f32(sum_vec, vabsq_f32(x1), vdupq_n_f32(1.0));
31        sum_vec = vfmaq_f32(sum_vec, vabsq_f32(x2), vdupq_n_f32(1.0));
32        sum_vec = vfmaq_f32(sum_vec, vabsq_f32(x3), vdupq_n_f32(1.0));
33
34        i += 16;
35    }
36
37    while i + 8 <= n {
38        let x0 = vld1q_f32(x.as_ptr().add(i));
39        let x1 = vld1q_f32(x.as_ptr().add(i + 4));
40        sum_vec = vfmaq_f32(sum_vec, vabsq_f32(x0), vdupq_n_f32(1.0));
41        sum_vec = vfmaq_f32(sum_vec, vabsq_f32(x1), vdupq_n_f32(1.0));
42        i += 8;
43    }
44
45    while i + 4 <= n {
46        let x0 = vld1q_f32(x.as_ptr().add(i));
47        sum_vec = vfmaq_f32(sum_vec, vabsq_f32(x0), vdupq_n_f32(1.0));
48        i += 4;
49    }
50
51    let mut sum = vaddvq_f32(sum_vec);
52
53    for j in i..n {
54        sum += x[j].abs();
55    }
56
57    sum
58}
59
60#[inline(always)]
61fn sum_abs(x: &[f32]) -> f32 {
62    #[cfg(target_arch = "x86_64")]
63    unsafe {
64        if std::arch::is_x86_feature_detected!("avx") {
65            return sum_abs_avx(x, x.len());
66        }
67    }
68    #[cfg(target_arch = "aarch64")]
69    unsafe {
70        sum_abs_neon(x, x.len())
71    }
72    #[cfg(not(target_arch = "aarch64"))]
73    {
74        x.iter().map(|&v| v.abs()).sum()
75    }
76}
77
78const MAX_FRAME_SIZE: usize = 2880;
79
80const DECODE_BUFFER_SIZE: usize = 3072;
81/// CELT packet-loss-concealment constants (celt_decoder.c).
82const PLC_LPC_ORDER: usize = 24;
83const PLC_PITCH_LAG_MAX: usize = 720;
84const PLC_PITCH_LAG_MIN: usize = 100;
85
86const INV_TABLE: [u8; 128] = [
87    255, 255, 156, 110, 86, 70, 59, 51, 45, 40, 37, 33, 31, 28, 26, 25, 23, 22, 21, 20, 19, 18, 17,
88    16, 16, 15, 15, 14, 13, 13, 12, 12, 12, 12, 11, 11, 11, 10, 10, 10, 9, 9, 9, 9, 9, 9, 8, 8, 8,
89    8, 8, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
90    5, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3, 3,
91    3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2,
92];
93
94const MAX_TRANSIENT_LEN: usize = 3000;
95
96#[derive(Debug, Clone, Copy)]
97pub struct AnalysisInfo {
98    pub valid: bool,
99    pub tonality: f32,
100    pub tonality_slope: f32,
101    pub noisiness: f32,
102    pub activity: f32,
103    pub music_prob: f32,
104    pub music_prob_min: f32,
105    pub music_prob_max: f32,
106    pub bandwidth: i32,
107    pub activity_probability: f32,
108    pub max_pitch_ratio: f32,
109    pub leak_boost: [u8; 19], // LEAK_BANDS = 19
110}
111
112impl Default for AnalysisInfo {
113    fn default() -> Self {
114        Self {
115            valid: false,
116            tonality: 0.0,
117            tonality_slope: 0.0,
118            noisiness: 0.0,
119            activity: 0.0,
120            music_prob: 0.0,
121            music_prob_min: 0.0,
122            music_prob_max: 0.0,
123            bandwidth: 0,
124            activity_probability: 0.0,
125            max_pitch_ratio: 1.0,
126            leak_boost: [0; 19],
127        }
128    }
129}
130
131#[allow(clippy::too_many_arguments)]
132fn transient_analysis(
133    input: &[f32],
134    len: usize,
135    channels: usize,
136    tf_estimate: &mut f32,
137    tf_chan: &mut usize,
138    allow_weak_transients: bool,
139    weak_transient: &mut bool,
140    _tone_freq: f32,
141    toneishness: f32,
142    tmp: &mut [f32],
143    tmp2: &mut [f32],
144) -> bool {
145    let _prof = crate::prof::scope(crate::prof::Stage::CeltTransient);
146    let mut mask_metric = 0.0f32;
147    let mut forward_decay = 0.0625f32;
148
149    *weak_transient = false;
150    if allow_weak_transients {
151        forward_decay = 0.03125f32;
152    }
153
154    let len2 = len / 2;
155    debug_assert!(len <= MAX_TRANSIENT_LEN);
156
157    for c in 0..channels {
158        let mut mem0 = 0.0f32;
159        let mut mem1 = 0.0f32;
160
161        for i in 0..len {
162            let x = input[c * len + i];
163            let y = mem0 + x;
164            let mem00 = mem0;
165            mem0 = mem0 - x + 0.5 * mem1;
166            mem1 = x - mem00;
167            tmp[i] = y;
168        }
169
170        tmp[..12].fill(0.0);
171
172        let mut mean = 0.0f32;
173        mem0 = 0.0f32;
174        for i in 0..len2 {
175            let x2 = (tmp[2 * i] * tmp[2 * i] + tmp[2 * i + 1] * tmp[2 * i + 1]) / 16.0;
176            mean += x2 / 4096.0;
177            mem0 = x2 + (1.0 - forward_decay) * mem0;
178            tmp2[i] = forward_decay * mem0;
179        }
180
181        mem0 = 0.0f32;
182        let mut max_e = 0.0f32;
183        for i in (0..len2).rev() {
184            mem0 = tmp2[i] + 0.875 * mem0;
185            tmp2[i] = 0.125 * mem0;
186            if tmp2[i] > max_e {
187                max_e = tmp2[i];
188            }
189        }
190
191        mean = (mean * max_e * 0.5 * (len2 as f32)).sqrt();
192        let norm = (len2 as f32) / (1e-10 + mean);
193
194        let mut unmask = 0.0f32;
195        for i in (12..(len2 - 5)).step_by(4) {
196            let id = (64.0 * norm * (tmp2[i] + 1e-10)).floor() as i32;
197            let id = id.clamp(0, 127) as usize;
198            unmask += INV_TABLE[id] as f32;
199        }
200
201        unmask = 64.0 * unmask * 4.0 / (6.0 * (len2 as f32 - 17.0));
202        if unmask > mask_metric {
203            *tf_chan = c;
204            mask_metric = unmask;
205        }
206    }
207
208    let mut is_transient = mask_metric > 200.0;
209
210    if toneishness > 0.98 && _tone_freq < 0.026 {
211        is_transient = false;
212        mask_metric = 0.0;
213    }
214
215    *tf_estimate = (mask_metric - 150.0).clamp(0.0, 1.0);
216
217    is_transient
218}
219
220fn l1_metric(tmp: &[f32], n: usize, lm: i32, bias: f32) -> f32 {
221    #[cfg(target_arch = "x86_64")]
222    unsafe {
223        if n >= 16 && std::arch::is_x86_feature_detected!("avx") {
224            return l1_metric_avx(tmp, n, lm, bias);
225        }
226    }
227    #[cfg(target_arch = "aarch64")]
228    {
229        if n >= 16 {
230            return unsafe { l1_metric_neon(tmp, n, lm, bias) };
231        }
232    }
233
234    let mut l1 = 0.0f32;
235    for &tv in tmp[..n].iter() {
236        l1 += tv.abs();
237    }
238    l1 + (lm as f32) * bias * l1
239}
240
241#[cfg(target_arch = "x86_64")]
242#[target_feature(enable = "avx")]
243unsafe fn sum_abs_avx(x: &[f32], n: usize) -> f32 {
244    use std::arch::x86_64::*;
245
246    let mut sum0 = _mm256_setzero_ps();
247    let mut sum1 = _mm256_setzero_ps();
248    let mut i = 0usize;
249    let sign_mask = _mm256_set1_ps(-0.0);
250
251    while i + 16 <= n {
252        let v0 = _mm256_loadu_ps(x.as_ptr().add(i));
253        let v1 = _mm256_loadu_ps(x.as_ptr().add(i + 8));
254        sum0 = _mm256_add_ps(sum0, _mm256_andnot_ps(sign_mask, v0));
255        sum1 = _mm256_add_ps(sum1, _mm256_andnot_ps(sign_mask, v1));
256        i += 16;
257    }
258
259    while i + 8 <= n {
260        let v = _mm256_loadu_ps(x.as_ptr().add(i));
261        sum0 = _mm256_add_ps(sum0, _mm256_andnot_ps(sign_mask, v));
262        i += 8;
263    }
264
265    let sum = _mm256_add_ps(sum0, sum1);
266    let hi = _mm256_extractf128_ps(sum, 1);
267    let lo = _mm256_castps256_ps128(sum);
268    let s4 = _mm_add_ps(lo, hi);
269    let t1 = _mm_movehl_ps(s4, s4);
270    let s2 = _mm_add_ps(s4, t1);
271    let t2 = _mm_shuffle_ps(s2, s2, 0x55);
272    let mut out = _mm_cvtss_f32(_mm_add_ss(s2, t2));
273
274    for j in i..n {
275        out += x[j].abs();
276    }
277
278    out
279}
280
281#[cfg(target_arch = "x86_64")]
282#[target_feature(enable = "avx")]
283unsafe fn l1_metric_avx(tmp: &[f32], n: usize, lm: i32, bias: f32) -> f32 {
284    let l1 = sum_abs_avx(tmp, n);
285    l1 + (lm as f32) * bias * l1
286}
287
288#[cfg(target_arch = "aarch64")]
289#[target_feature(enable = "neon")]
290unsafe fn l1_metric_neon(tmp: &[f32], n: usize, lm: i32, bias: f32) -> f32 {
291    unsafe {
292        let mut sum4 = vdupq_n_f32(0.0);
293        let mut i = 0;
294
295        while i + 15 < n {
296            let v0 = vld1q_f32(tmp.as_ptr().add(i));
297            let v1 = vld1q_f32(tmp.as_ptr().add(i + 4));
298            let v2 = vld1q_f32(tmp.as_ptr().add(i + 8));
299            let v3 = vld1q_f32(tmp.as_ptr().add(i + 12));
300
301            sum4 = vaddq_f32(sum4, vabsq_f32(v0));
302            sum4 = vaddq_f32(sum4, vabsq_f32(v1));
303            sum4 = vaddq_f32(sum4, vabsq_f32(v2));
304            sum4 = vaddq_f32(sum4, vabsq_f32(v3));
305
306            i += 16;
307        }
308
309        while i + 3 < n {
310            let v = vld1q_f32(tmp.as_ptr().add(i));
311            sum4 = vaddq_f32(sum4, vabsq_f32(v));
312            i += 4;
313        }
314
315        let sum2 = vpaddq_f32(sum4, sum4);
316        let sum1 = vpaddq_f32(sum2, sum2);
317        let mut l1 = vgetq_lane_f32(sum1, 0);
318
319        while i < n {
320            l1 += tmp[i].abs();
321            i += 1;
322        }
323
324        l1 + (lm as f32) * bias * l1
325    }
326}
327
328const MAX_NB_EBANDS: usize = 21;
329
330const MAX_TF_TMP: usize = 176;
331
332#[allow(clippy::too_many_arguments)]
333fn tf_analysis(
334    mode: &CeltMode,
335    len: usize,
336    is_transient: bool,
337    tf_res: &mut [i32],
338    lambda: i32,
339    x: &[f32],
340    n0: usize,
341    lm: i32,
342    tf_estimate: f32,
343    tf_chan: usize,
344    importance: &[f32],
345) -> i32 {
346    let _prof = crate::prof::scope(crate::prof::Stage::CeltTf);
347    debug_assert!(len <= MAX_NB_EBANDS);
348    let mut metric = [0i32; MAX_NB_EBANDS];
349    let mut tmp = [0.0f32; MAX_TF_TMP];
350    let mut tmp_1 = [0.0f32; MAX_TF_TMP];
351
352    let bias = 0.04 * (-0.25f32).max(0.5 - tf_estimate);
353
354    for (i, metric_i) in metric[..len].iter_mut().enumerate() {
355        let n = ((mode.e_bands[i + 1] - mode.e_bands[i]) as usize) << lm;
356        let narrow = (mode.e_bands[i + 1] - mode.e_bands[i]) == 1;
357        let offset = tf_chan * n0 + ((mode.e_bands[i] as usize) << lm);
358        tmp[..n].copy_from_slice(&x[offset..offset + n]);
359
360        let mut l1 = l1_metric(&tmp[..n], n, if is_transient { lm } else { 0 }, bias);
361        let mut best_l1 = l1;
362        let mut best_level = 0;
363
364        if is_transient && !narrow {
365            tmp_1[..n].copy_from_slice(&tmp[..n]);
366            haar1(&mut tmp_1[..n], n >> lm, 1 << lm);
367            l1 = l1_metric(&tmp_1[..n], n, lm + 1, bias);
368            if l1 < best_l1 {
369                best_l1 = l1;
370                best_level = -1;
371            }
372        }
373
374        for k in 0..(lm + if is_transient || narrow { 0 } else { 1 }) {
375            let b = if is_transient { lm - k - 1 } else { k + 1 };
376
377            haar1(&mut tmp[..n], n >> k, 1 << k);
378            l1 = l1_metric(&tmp[..n], n, b, bias);
379
380            if l1 < best_l1 {
381                best_l1 = l1;
382                best_level = k + 1;
383            }
384        }
385
386        if is_transient {
387            *metric_i = 2 * best_level;
388        } else {
389            *metric_i = -2 * best_level;
390        }
391
392        if narrow && (*metric_i == 0 || *metric_i == -2 * lm) {
393            *metric_i -= 1;
394        }
395    }
396
397    let mut tf_select = 0;
398    let mut selcost = [0.0f32; 2];
399
400    for sel in 0..2 {
401        let mut cost0 = importance[0]
402            * ((metric[0]
403                - 2 * TF_SELECT_TABLE[lm as usize][4 * (is_transient as usize) + 2 * sel] as i32)
404                as f32)
405                .abs();
406        let mut cost1 = importance[0]
407            * ((metric[0]
408                - 2 * TF_SELECT_TABLE[lm as usize][4 * (is_transient as usize) + 2 * sel + 1]
409                    as i32) as f32)
410                .abs()
411            + (if is_transient { 0.0 } else { lambda as f32 });
412
413        for i in 1..len {
414            let curr0 = cost0.min(cost1 + lambda as f32);
415            let curr1 = (cost0 + lambda as f32).min(cost1);
416            cost0 = curr0
417                + importance[i]
418                    * ((metric[i]
419                        - 2 * TF_SELECT_TABLE[lm as usize][4 * (is_transient as usize) + 2 * sel]
420                            as i32) as f32)
421                        .abs();
422            cost1 = curr1
423                + importance[i]
424                    * ((metric[i]
425                        - 2 * TF_SELECT_TABLE[lm as usize]
426                            [4 * (is_transient as usize) + 2 * sel + 1]
427                            as i32) as f32)
428                        .abs();
429        }
430        selcost[sel] = cost0.min(cost1);
431    }
432
433    // C: tf_select=1 is only allowed on transients (celt_encoder.c:108).
434    if selcost[1] < selcost[0] && is_transient {
435        tf_select = 1;
436    }
437
438    let mut cost0 = importance[0]
439        * ((metric[0]
440            - 2 * TF_SELECT_TABLE[lm as usize][4 * (is_transient as usize) + 2 * tf_select] as i32)
441            as f32)
442            .abs();
443    let mut cost1 = importance[0]
444        * ((metric[0]
445            - 2 * TF_SELECT_TABLE[lm as usize][4 * (is_transient as usize) + 2 * tf_select + 1]
446                as i32) as f32)
447            .abs()
448        + (if is_transient { 0.0 } else { lambda as f32 });
449
450    tf_res[0] = if cost0 < cost1 { 0 } else { 1 };
451
452    for i in 1..len {
453        let curr0 = cost0.min(cost1 + lambda as f32);
454        let curr1 = (cost0 + lambda as f32).min(cost1);
455        cost0 = curr0
456            + importance[i]
457                * ((metric[i]
458                    - 2 * TF_SELECT_TABLE[lm as usize][4 * (is_transient as usize) + 2 * tf_select]
459                        as i32) as f32)
460                    .abs();
461        cost1 = curr1
462            + importance[i]
463                * ((metric[i]
464                    - 2 * TF_SELECT_TABLE[lm as usize]
465                        [4 * (is_transient as usize) + 2 * tf_select + 1]
466                        as i32) as f32)
467                    .abs();
468        tf_res[i] = if cost0 < cost1 { 0 } else { 1 };
469    }
470
471    tf_select as i32
472}
473
474fn tf_encode(
475    start: usize,
476    end: usize,
477    is_transient: bool,
478    tf_res: &mut [i32],
479    lm: i32,
480    mut tf_select: i32,
481    rc: &mut RangeCoder,
482) -> i32 {
483    let mut curr = 0;
484    let mut tf_changed = 0;
485    let mut logp = if is_transient { 2 } else { 4 };
486    let mut budget = rc.storage as i32 * 8;
487    let mut tell = rc.tell();
488
489    let tf_select_rsv = if lm > 0 && tell + logp < budget { 1 } else { 0 };
490    budget -= tf_select_rsv;
491
492    for tf_res_i in tf_res[start..end].iter_mut() {
493        if tell + logp <= budget {
494            rc.encode_bit_logp(*tf_res_i ^ curr != 0, logp as u32);
495            tell = rc.tell();
496            curr = *tf_res_i;
497            tf_changed |= curr;
498        } else {
499            *tf_res_i = curr;
500        }
501        logp = if is_transient { 4 } else { 5 };
502    }
503
504    if tf_select_rsv != 0
505        && TF_SELECT_TABLE[lm as usize][4 * (is_transient as usize) + (tf_changed as usize)]
506            != TF_SELECT_TABLE[lm as usize][4 * (is_transient as usize) + 2 + (tf_changed as usize)]
507    {
508        rc.encode_bit_logp(tf_select != 0, 1);
509    } else {
510        tf_select = 0;
511    }
512
513    for tf_res_i in tf_res[start..end].iter_mut() {
514        *tf_res_i = TF_SELECT_TABLE[lm as usize]
515            [4 * (is_transient as usize) + 2 * (tf_select as usize) + (*tf_res_i as usize)]
516            as i32;
517    }
518
519    tf_changed
520}
521
522fn tf_decode(
523    start: usize,
524    end: usize,
525    is_transient: bool,
526    tf_res: &mut [i32],
527    lm: i32,
528    rc: &mut RangeCoder,
529) {
530    let mut curr = 0;
531    let mut tf_changed = 0;
532    let mut logp = if is_transient { 2 } else { 4 };
533    let budget = rc.storage as i32 * 8;
534    let mut tell = rc.tell();
535
536    let tf_select_rsv = if lm > 0 && tell + logp < budget { 1 } else { 0 };
537    let budget = budget - tf_select_rsv;
538
539    for tf_res_i in tf_res[start..end].iter_mut() {
540        if tell + logp <= budget {
541            curr ^= if rc.decode_bit_logp(logp as u32) {
542                1
543            } else {
544                0
545            };
546            tell = rc.tell();
547            tf_changed |= curr;
548        }
549        *tf_res_i = curr;
550        logp = if is_transient { 4 } else { 5 };
551    }
552
553    let mut tf_select = 0;
554    let _budget = budget + tf_select_rsv;
555    if tf_select_rsv > 0
556        && TF_SELECT_TABLE[lm as usize][4 * (is_transient as usize) + (tf_changed as usize)]
557            != TF_SELECT_TABLE[lm as usize][4 * (is_transient as usize) + 2 + (tf_changed as usize)]
558    {
559        tf_select = if rc.decode_bit_logp(1) { 1 } else { 0 };
560    }
561
562    for tf_res_i in tf_res[start..end].iter_mut() {
563        *tf_res_i = TF_SELECT_TABLE[lm as usize]
564            [4 * (is_transient as usize) + 2 * (tf_select as usize) + (*tf_res_i as usize)]
565            as i32;
566    }
567}
568
569fn stereo_analysis(m: &CeltMode, x: &[f32], lm: i32, n0: usize) -> bool {
570    let mut sum_lr = 1e-9f32;
571    let mut sum_ms = 1e-9f32;
572
573    for i in 0..13 {
574        let start = (m.e_bands[i] as usize) << lm;
575        let end = (m.e_bands[i + 1] as usize) << lm;
576        for j in start..end {
577            let l = x[j];
578            let r = x[n0 + j];
579            let m_val = l + r;
580            let s_val = l - r;
581            sum_lr += l.abs() + r.abs();
582            sum_ms += m_val.abs() + s_val.abs();
583        }
584    }
585
586    sum_ms *= std::f32::consts::FRAC_1_SQRT_2;
587    let mut thetas = 13;
588    if lm <= 1 {
589        thetas -= 8;
590    }
591
592    let left = (((m.e_bands[13] as usize) << (lm + 1)) + thetas) as f32 * sum_ms;
593    let right = ((m.e_bands[13] as usize) << (lm + 1)) as f32 * sum_lr;
594
595    left > right
596}
597
598const COMBFILTER_MINPERIOD: usize = 15;
599const COMBFILTER_MAXPERIOD: usize = 1024;
600
601const PREFILTER_GAINS: [[f32; 3]; 3] = [
602    [0.306_640_6, 0.217_041, 0.129_638_7],
603    [0.463_867_2, 0.268_066_4, 0.0],
604    [0.799_804_7, 0.100_097_7, 0.0],
605];
606
607#[allow(clippy::too_many_arguments)]
608fn comb_filter_const(
609    y: &mut [f32],
610    x: &[f32],
611    y_idx: usize,
612    x_idx: usize,
613    t: usize,
614    n: usize,
615    g10: f32,
616    g11: f32,
617    g12: f32,
618) {
619    #[cfg(target_arch = "aarch64")]
620    {
621        comb_filter_const_neon(y, x, y_idx, x_idx, t, n, g10, g11, g12);
622    }
623    #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
624    unsafe {
625        if std::arch::is_x86_feature_detected!("avx") {
626            comb_filter_const_avx(y, x, y_idx, x_idx, t, n, g10, g11, g12);
627            return;
628        }
629    }
630    #[cfg(all(target_arch = "x86_64", target_feature = "sse"))]
631    unsafe {
632        comb_filter_const_sse(y, x, y_idx, x_idx, t, n, g10, g11, g12);
633        #[allow(clippy::needless_return)]
634        return;
635    }
636    #[cfg(not(any(
637        target_arch = "aarch64",
638        all(target_arch = "x86_64", target_feature = "sse")
639    )))]
640    {
641        comb_filter_const_scalar(y, x, y_idx, x_idx, t, n, g10, g11, g12);
642    }
643}
644
645#[inline]
646#[allow(dead_code)]
647fn comb_filter_const_scalar(
648    y: &mut [f32],
649    x: &[f32],
650    y_idx: usize,
651    x_idx: usize,
652    t: usize,
653    n: usize,
654    g10: f32,
655    g11: f32,
656    g12: f32,
657) {
658    let mut x1;
659    let mut x2;
660    let mut x3;
661    let mut x4;
662    let mut x0;
663
664    x4 = x[x_idx - t - 2];
665    x3 = x[x_idx - t - 1];
666    x2 = x[x_idx - t];
667    x1 = x[x_idx - t + 1];
668
669    for i in 0..n {
670        x0 = x[x_idx + i - t + 2];
671        y[y_idx + i] = x[x_idx + i] + g10 * x2 + g11 * (x1 + x3) + g12 * (x0 + x4);
672        x4 = x3;
673        x3 = x2;
674        x2 = x1;
675        x1 = x0;
676    }
677}
678
679#[cfg(target_arch = "aarch64")]
680fn comb_filter_const_neon(
681    y: &mut [f32],
682    x: &[f32],
683    y_idx: usize,
684    x_idx: usize,
685    t: usize,
686    n: usize,
687    g10: f32,
688    g11: f32,
689    g12: f32,
690) {
691    unsafe { comb_filter_const_neon_impl(y, x, y_idx, x_idx, t, n, g10, g11, g12) }
692}
693
694#[cfg(target_arch = "aarch64")]
695#[inline(always)]
696#[allow(unsafe_op_in_unsafe_fn)]
697unsafe fn comb_filter_const_neon_impl(
698    y: &mut [f32],
699    x: &[f32],
700    y_idx: usize,
701    x_idx: usize,
702    t: usize,
703    n: usize,
704    g10: f32,
705    g11: f32,
706    g12: f32,
707) {
708    use std::arch::aarch64::*;
709
710    let g10v = vdupq_n_f32(g10);
711    let g11v = vdupq_n_f32(g11);
712    let g12v = vdupq_n_f32(g12);
713
714    let xbase = x.as_ptr().add(x_idx);
715    let ybase = y.as_mut_ptr().add(y_idx);
716
717    let mut x0v = vld1q_f32(xbase.sub(t + 2));
718
719    let mut i = 0;
720    while i + 4 <= n {
721        let x4v = vld1q_f32(xbase.add(i).sub(t - 2));
722
723        let x2v = vextq_f32(x0v, x4v, 2);
724
725        let x1v = vextq_f32(x0v, x4v, 1);
726
727        let x3v = vextq_f32(x0v, x4v, 3);
728
729        let xi = vld1q_f32(xbase.add(i));
730
731        let mut yi = xi;
732        yi = vfmaq_f32(yi, g10v, x2v);
733        yi = vfmaq_f32(yi, g11v, vaddq_f32(x1v, x3v));
734        yi = vfmaq_f32(yi, g12v, vaddq_f32(x4v, x0v));
735        vst1q_f32(ybase.add(i), yi);
736
737        x0v = x4v;
738        i += 4;
739    }
740
741    let x0v_arr: [f32; 4] = std::mem::transmute(x0v);
742    let mut sx4 = x0v_arr[0];
743    let mut sx3 = x0v_arr[1];
744    let mut sx2 = x0v_arr[2];
745    let mut sx1 = x0v_arr[3];
746
747    while i < n {
748        let sx0 = x[x_idx + i - t + 2];
749        y[y_idx + i] = x[x_idx + i] + g10 * sx2 + g11 * (sx1 + sx3) + g12 * (sx0 + sx4);
750        sx4 = sx3;
751        sx3 = sx2;
752        sx2 = sx1;
753        sx1 = sx0;
754        i += 1;
755    }
756}
757
758#[cfg(all(target_arch = "x86_64", target_feature = "sse"))]
759#[inline(always)]
760#[allow(unsafe_op_in_unsafe_fn)]
761unsafe fn comb_filter_const_sse(
762    y: &mut [f32],
763    x: &[f32],
764    y_idx: usize,
765    x_idx: usize,
766    t: usize,
767    n: usize,
768    g10: f32,
769    g11: f32,
770    g12: f32,
771) {
772    use std::arch::x86_64::*;
773
774    let g10v = _mm_set1_ps(g10);
775    let g11v = _mm_set1_ps(g11);
776    let g12v = _mm_set1_ps(g12);
777
778    let xbase = x.as_ptr().add(x_idx);
779    let ybase = y.as_mut_ptr().add(y_idx);
780    let mut x0v = _mm_loadu_ps(xbase.sub(t + 2));
781
782    let mut i = 0;
783    while i + 4 <= n {
784        let x4v = _mm_loadu_ps(xbase.add(i).sub(t - 2));
785
786        let x2v = _mm_shuffle_ps(x0v, x4v, 0x4e);
787
788        let x1v = _mm_shuffle_ps(x0v, x2v, 0x99);
789
790        let x3v = _mm_shuffle_ps(x2v, x4v, 0x99);
791
792        let xi = _mm_loadu_ps(xbase.add(i));
793
794        let mut yi = xi;
795        yi = _mm_add_ps(yi, _mm_mul_ps(g10v, x2v));
796        let yi2 = _mm_add_ps(
797            _mm_mul_ps(g11v, _mm_add_ps(x3v, x1v)),
798            _mm_mul_ps(g12v, _mm_add_ps(x4v, x0v)),
799        );
800        yi = _mm_add_ps(yi, yi2);
801        _mm_storeu_ps(ybase.add(i), yi);
802
803        x0v = x4v;
804        i += 4;
805    }
806
807    let x0v_arr: [f32; 4] = std::mem::transmute(x0v);
808    let mut sx4 = x0v_arr[0];
809    let mut sx3 = x0v_arr[1];
810    let mut sx2 = x0v_arr[2];
811    let mut sx1 = x0v_arr[3];
812
813    while i < n {
814        let sx0 = x[x_idx + i - t + 2];
815        y[y_idx + i] = x[x_idx + i] + g10 * sx2 + g11 * (sx1 + sx3) + g12 * (sx0 + sx4);
816        sx4 = sx3;
817        sx3 = sx2;
818        sx2 = sx1;
819        sx1 = sx0;
820        i += 1;
821    }
822}
823
824#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
825#[target_feature(enable = "avx,fma")]
826#[allow(unsafe_op_in_unsafe_fn)]
827unsafe fn comb_filter_const_avx(
828    y: &mut [f32],
829    x: &[f32],
830    y_idx: usize,
831    x_idx: usize,
832    t: usize,
833    n: usize,
834    g10: f32,
835    g11: f32,
836    g12: f32,
837) {
838    use std::arch::x86_64::*;
839
840    let g10v = _mm256_set1_ps(g10);
841    let g11v = _mm256_set1_ps(g11);
842    let g12v = _mm256_set1_ps(g12);
843
844    let xbase = x.as_ptr().add(x_idx);
845    let ybase = y.as_mut_ptr().add(y_idx);
846
847    let mut i = 0;
848
849    while i + 16 <= n {
850        let xi_a = _mm256_loadu_ps(xbase.add(i));
851        let x0_a = _mm256_loadu_ps(xbase.add(i).sub(t + 2));
852        let x4_a = _mm256_loadu_ps(xbase.add(i).sub(t - 2));
853
854        let x2_a = _mm256_loadu_ps(xbase.add(i).sub(t));
855        let x1x3_a = _mm256_add_ps(
856            _mm256_loadu_ps(xbase.add(i).sub(t + 1)),
857            _mm256_loadu_ps(xbase.add(i).sub(t - 1)),
858        );
859        let x0x4_a = _mm256_add_ps(x0_a, x4_a);
860
861        let mut yi_a = xi_a;
862        yi_a = _mm256_fmadd_ps(g10v, x2_a, yi_a);
863        yi_a = _mm256_fmadd_ps(g11v, x1x3_a, yi_a);
864        yi_a = _mm256_fmadd_ps(g12v, x0x4_a, yi_a);
865        _mm256_storeu_ps(ybase.add(i), yi_a);
866
867        let j = i + 8;
868        let xi_b = _mm256_loadu_ps(xbase.add(j));
869        let x0_b = _mm256_loadu_ps(xbase.add(j).sub(t + 2));
870        let x4_b = _mm256_loadu_ps(xbase.add(j).sub(t - 2));
871        let x2_b = _mm256_loadu_ps(xbase.add(j).sub(t));
872        let x1x3_b = _mm256_add_ps(
873            _mm256_loadu_ps(xbase.add(j).sub(t + 1)),
874            _mm256_loadu_ps(xbase.add(j).sub(t - 1)),
875        );
876        let x0x4_b = _mm256_add_ps(x0_b, x4_b);
877
878        let mut yi_b = xi_b;
879        yi_b = _mm256_fmadd_ps(g10v, x2_b, yi_b);
880        yi_b = _mm256_fmadd_ps(g11v, x1x3_b, yi_b);
881        yi_b = _mm256_fmadd_ps(g12v, x0x4_b, yi_b);
882        _mm256_storeu_ps(ybase.add(j), yi_b);
883
884        i += 16;
885    }
886
887    while i + 8 <= n {
888        let xi = _mm256_loadu_ps(xbase.add(i));
889        let x0 = _mm256_loadu_ps(xbase.add(i).sub(t + 2));
890        let x4 = _mm256_loadu_ps(xbase.add(i).sub(t - 2));
891        let x2 = _mm256_loadu_ps(xbase.add(i).sub(t));
892        let x1x3 = _mm256_add_ps(
893            _mm256_loadu_ps(xbase.add(i).sub(t + 1)),
894            _mm256_loadu_ps(xbase.add(i).sub(t - 1)),
895        );
896        let x0x4 = _mm256_add_ps(x0, x4);
897
898        let mut yi = xi;
899        yi = _mm256_fmadd_ps(g10v, x2, yi);
900        yi = _mm256_fmadd_ps(g11v, x1x3, yi);
901        yi = _mm256_fmadd_ps(g12v, x0x4, yi);
902        _mm256_storeu_ps(ybase.add(i), yi);
903
904        i += 8;
905    }
906
907    if i + 4 <= n {
908        comb_filter_const_sse_fma(y, x, y_idx + i, x_idx + i, t, n - i, g10, g11, g12);
909        return;
910    }
911
912    let mut sx4 = x[x_idx + i - t - 2];
913    let mut sx3 = x[x_idx + i - t - 1];
914    let mut sx2 = x[x_idx + i - t];
915    let mut sx1 = x[x_idx + i - t + 1];
916    while i < n {
917        let sx0 = x[x_idx + i - t + 2];
918        y[y_idx + i] = x[x_idx + i] + g10 * sx2 + g11 * (sx1 + sx3) + g12 * (sx0 + sx4);
919        sx4 = sx3;
920        sx3 = sx2;
921        sx2 = sx1;
922        sx1 = sx0;
923        i += 1;
924    }
925}
926
927#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
928#[target_feature(enable = "avx,fma")]
929#[allow(unsafe_op_in_unsafe_fn)]
930unsafe fn comb_filter_const_sse_fma(
931    y: &mut [f32],
932    x: &[f32],
933    y_idx: usize,
934    x_idx: usize,
935    t: usize,
936    n: usize,
937    g10: f32,
938    g11: f32,
939    g12: f32,
940) {
941    use std::arch::x86_64::*;
942
943    let g10v = _mm_set1_ps(g10);
944    let g11v = _mm_set1_ps(g11);
945    let g12v = _mm_set1_ps(g12);
946
947    let xbase = x.as_ptr().add(x_idx);
948    let ybase = y.as_mut_ptr().add(y_idx);
949    let mut x0v = _mm_loadu_ps(xbase.sub(t + 2));
950
951    let mut i = 0;
952    while i + 4 <= n {
953        let x4v = _mm_loadu_ps(xbase.add(i).sub(t - 2));
954        let x2v = _mm_shuffle_ps(x0v, x4v, 0x4e);
955        let x1v = _mm_shuffle_ps(x0v, x2v, 0x99);
956        let x3v = _mm_shuffle_ps(x2v, x4v, 0x99);
957        let xi = _mm_loadu_ps(xbase.add(i));
958
959        let mut yi = xi;
960        yi = _mm_fmadd_ps(g10v, x2v, yi);
961        yi = _mm_fmadd_ps(g11v, _mm_add_ps(x1v, x3v), yi);
962        yi = _mm_fmadd_ps(g12v, _mm_add_ps(x0v, x4v), yi);
963        _mm_storeu_ps(ybase.add(i), yi);
964
965        x0v = x4v;
966        i += 4;
967    }
968
969    let x0v_arr: [f32; 4] = std::mem::transmute(x0v);
970    let mut sx4 = x0v_arr[0];
971    let mut sx3 = x0v_arr[1];
972    let mut sx2 = x0v_arr[2];
973    let mut sx1 = x0v_arr[3];
974    while i < n {
975        let sx0 = x[x_idx + i - t + 2];
976        y[y_idx + i] = x[x_idx + i] + g10 * sx2 + g11 * (sx1 + sx3) + g12 * (sx0 + sx4);
977        sx4 = sx3;
978        sx3 = sx2;
979        sx2 = sx1;
980        sx1 = sx0;
981        i += 1;
982    }
983}
984
985#[allow(clippy::too_many_arguments)]
986fn comb_filter(
987    y: &mut [f32],
988    x: &[f32],
989    y_idx: usize,
990    x_idx: usize,
991    t0: usize,
992    t1: usize,
993    n: usize,
994    g0: f32,
995    g1: f32,
996    tapset0: i32,
997    tapset1: i32,
998    window: &[f32],
999    overlap: usize,
1000) {
1001    if g0 == 0.0 && g1 == 0.0 {
1002        if x_idx != y_idx || !std::ptr::eq(x.as_ptr(), y.as_ptr()) {
1003            y[y_idx..y_idx + n].copy_from_slice(&x[x_idx..x_idx + n]);
1004        }
1005        return;
1006    }
1007
1008    let t0 = t0.clamp(
1009        COMBFILTER_MINPERIOD,
1010        x_idx.saturating_sub(2).max(COMBFILTER_MINPERIOD),
1011    );
1012    let t1 = t1.clamp(
1013        COMBFILTER_MINPERIOD,
1014        x_idx.saturating_sub(2).max(COMBFILTER_MINPERIOD),
1015    );
1016
1017    let g00 = g0 * PREFILTER_GAINS[tapset0 as usize][0];
1018    let g01 = g0 * PREFILTER_GAINS[tapset0 as usize][1];
1019    let g02 = g0 * PREFILTER_GAINS[tapset0 as usize][2];
1020
1021    let g10 = g1 * PREFILTER_GAINS[tapset1 as usize][0];
1022    let g11 = g1 * PREFILTER_GAINS[tapset1 as usize][1];
1023    let g12 = g1 * PREFILTER_GAINS[tapset1 as usize][2];
1024
1025    let mut x1 = x[x_idx - t1 + 1];
1026    let mut x2 = x[x_idx - t1];
1027    let mut x3 = x[x_idx - t1 - 1];
1028    let mut x4 = x[x_idx - t1 - 2];
1029
1030    let mut inner_overlap = overlap;
1031    if g0 == g1 && t0 == t1 && tapset0 == tapset1 {
1032        inner_overlap = 0;
1033    }
1034
1035    let mut i = 0;
1036    while i < inner_overlap && i < n {
1037        let x0 = x[x_idx + i - t1 + 2];
1038        let f = window[i] * window[i];
1039        y[y_idx + i] = x[x_idx + i]
1040            + (1.0 - f)
1041                * (g00 * x[x_idx + i - t0]
1042                    + g01 * (x[x_idx + i - t0 + 1] + x[x_idx + i - t0 - 1])
1043                    + g02 * (x[x_idx + i - t0 + 2] + x[x_idx + i - t0 - 2]))
1044            + f * (g10 * x2 + g11 * (x1 + x3) + g12 * (x0 + x4));
1045
1046        x4 = x3;
1047        x3 = x2;
1048        x2 = x1;
1049        x1 = x0;
1050        i += 1;
1051    }
1052
1053    if i < n {
1054        if g1 == 0.0 {
1055            y[y_idx + i..y_idx + n].copy_from_slice(&x[x_idx + i..x_idx + n]);
1056        } else {
1057            comb_filter_const(y, x, y_idx + i, x_idx + i, t1, n - i, g10, g11, g12);
1058        }
1059    }
1060}
1061
1062/// In-place comb filter: buf[y_idx..y_idx+n] is both input and output.
1063/// Reference samples at buf[y_idx + i - T + offset] may already be filtered
1064/// if T < i, matching C libopus's in-place comb_filter(out, out, ...) behavior.
1065fn comb_filter_inplace(
1066    buf: &mut [f32],
1067    y_idx: usize,
1068    t0: usize,
1069    t1: usize,
1070    n: usize,
1071    g0: f32,
1072    g1: f32,
1073    tapset0: i32,
1074    tapset1: i32,
1075    window: &[f32],
1076    overlap: usize,
1077) {
1078    if g0 == 0.0 && g1 == 0.0 {
1079        // nothing to do; buf[y_idx..] already holds the input
1080        return;
1081    }
1082
1083    let t0 = t0.clamp(COMBFILTER_MINPERIOD, y_idx - 2);
1084    let t1 = t1.clamp(COMBFILTER_MINPERIOD, y_idx - 2);
1085
1086    let g00 = g0 * PREFILTER_GAINS[tapset0 as usize][0];
1087    let g01 = g0 * PREFILTER_GAINS[tapset0 as usize][1];
1088    let g02 = g0 * PREFILTER_GAINS[tapset0 as usize][2];
1089
1090    let g10 = g1 * PREFILTER_GAINS[tapset1 as usize][0];
1091    let g11 = g1 * PREFILTER_GAINS[tapset1 as usize][1];
1092    let g12 = g1 * PREFILTER_GAINS[tapset1 as usize][2];
1093
1094    let mut inner_overlap = overlap;
1095    if g0 == g1 && t0 == t1 && tapset0 == tapset1 {
1096        inner_overlap = 0;
1097    }
1098
1099    let mut i = 0;
1100    while i < inner_overlap && i < n {
1101        let idx = y_idx + i;
1102        let f = window[i] * window[i];
1103        let s = buf[idx]; // original input (not yet overwritten at idx)
1104        let r0 = buf[idx - t0];
1105        let r0p1 = buf[idx - t0 + 1];
1106        let r0m1 = buf[idx - t0 - 1];
1107        let r0p2 = buf[idx - t0 + 2];
1108        let r0m2 = buf[idx - t0 - 2];
1109        let r1 = buf[idx - t1];
1110        let r1p1 = buf[idx - t1 + 1];
1111        let r1m1 = buf[idx - t1 - 1];
1112        let r1p2 = buf[idx - t1 + 2];
1113        let r1m2 = buf[idx - t1 - 2];
1114        buf[idx] = s
1115            + (1.0 - f) * (g00 * r0 + g01 * (r0p1 + r0m1) + g02 * (r0p2 + r0m2))
1116            + f * (g10 * r1 + g11 * (r1p1 + r1m1) + g12 * (r1p2 + r1m2));
1117        i += 1;
1118    }
1119
1120    // Constant region: only new filter (t1, g1). The feedback delay t1 >=
1121    // COMBFILTER_MINPERIOD (15) >= 10, so an 8-wide vector at [idx, idx+8) never
1122    // reads its own writes: the batch's read span [idx-t1-2, idx-t1+9] is disjoint
1123    // from the write span [idx, idx+8) iff t1 >= 10 — the past outputs it reads are
1124    // already finalized, exactly as the scalar loop sees them.
1125    #[cfg(target_arch = "x86_64")]
1126    {
1127        if i + 8 <= n && t1 >= 10 && std::arch::is_x86_feature_detected!("avx2") {
1128            unsafe {
1129                i = comb_filter_const_avx2(buf, y_idx, i, n, t1, g10, g11, g12);
1130            }
1131        }
1132    }
1133    while i < n {
1134        let idx = y_idx + i;
1135        let s = buf[idx];
1136        let r1 = buf[idx - t1];
1137        let r1p1 = buf[idx - t1 + 1];
1138        let r1m1 = buf[idx - t1 - 1];
1139        let r1p2 = buf[idx - t1 + 2];
1140        let r1m2 = buf[idx - t1 - 2];
1141        buf[idx] = s + g10 * r1 + g11 * (r1p1 + r1m1) + g12 * (r1p2 + r1m2);
1142        i += 1;
1143    }
1144}
1145
1146/// AVX2 comb-filter constant region: 8 samples/iter, bit-exact vs the scalar
1147/// tail below. Uses separate mul+add (NOT FMA) in the scalar op order
1148/// `s + g10*r1 + g11*(r1p1+r1m1) + g12*(r1p2+r1m2)` so every rounding matches.
1149/// Requires `t1 >= 10` (the batch reads [idx-t1-2, idx-t1+9] stay clear of the
1150/// [idx, idx+8) writes). Returns the index `i` where the scalar tail resumes.
1151#[cfg(target_arch = "x86_64")]
1152#[target_feature(enable = "avx2")]
1153unsafe fn comb_filter_const_avx2(
1154    buf: &mut [f32],
1155    y_idx: usize,
1156    mut i: usize,
1157    n: usize,
1158    t1: usize,
1159    g10: f32,
1160    g11: f32,
1161    g12: f32,
1162) -> usize {
1163    use std::arch::x86_64::*;
1164    let vg10 = _mm256_set1_ps(g10);
1165    let vg11 = _mm256_set1_ps(g11);
1166    let vg12 = _mm256_set1_ps(g12);
1167    let p = buf.as_mut_ptr();
1168    while i + 8 <= n {
1169        let idx = y_idx + i;
1170        let base = idx - t1; // >= 2 (t1 <= idx-2, and idx >= y_idx >= t1+2)
1171        let s = _mm256_loadu_ps(p.add(idx));
1172        let r1 = _mm256_loadu_ps(p.add(base));
1173        let r1p1 = _mm256_loadu_ps(p.add(base + 1));
1174        let r1m1 = _mm256_loadu_ps(p.add(base - 1));
1175        let r1p2 = _mm256_loadu_ps(p.add(base + 2));
1176        let r1m2 = _mm256_loadu_ps(p.add(base - 2));
1177        let a = _mm256_add_ps(r1p1, r1m1);
1178        let b = _mm256_add_ps(r1p2, r1m2);
1179        // out = ((s + g10*r1) + g11*a) + g12*b  (left-to-right, two-rounding, no FMA)
1180        let mut out = _mm256_add_ps(s, _mm256_mul_ps(vg10, r1));
1181        out = _mm256_add_ps(out, _mm256_mul_ps(vg11, a));
1182        out = _mm256_add_ps(out, _mm256_mul_ps(vg12, b));
1183        _mm256_storeu_ps(p.add(idx), out);
1184        i += 8;
1185    }
1186    i
1187}
1188
1189fn run_prefilter(
1190    in_buf: &mut [f32],
1191    prefilter_mem: &mut [f32],
1192    prefilter_period: usize,
1193    prefilter_gain: f32,
1194    prefilter_tapset: i32,
1195    tapset_decision: i32,
1196    window: &[f32],
1197    channels: usize,
1198    frame_size: usize,
1199    overlap: usize,
1200
1201    pre: &mut [f32],
1202    pitch_buf: &mut [f32],
1203
1204    analysis: &AnalysisInfo,
1205    loss_rate: i32,
1206    nb_available_bytes: i32,
1207) -> (bool, f32, usize) {
1208    let _prof = crate::prof::scope(crate::prof::Stage::CeltPrefilter);
1209    let max_period = COMBFILTER_MAXPERIOD;
1210    let min_period = COMBFILTER_MINPERIOD;
1211    let buf_stride = frame_size + overlap;
1212    let pre_size = max_period + frame_size;
1213
1214    for c in 0..channels {
1215        pre[c * pre_size..c * pre_size + max_period]
1216            .copy_from_slice(&prefilter_mem[c * max_period..(c + 1) * max_period]);
1217        pre[c * pre_size + max_period..c * pre_size + pre_size].copy_from_slice(
1218            &in_buf[c * buf_stride + overlap..c * buf_stride + overlap + frame_size],
1219        );
1220    }
1221
1222    let pitch_buf_len = (max_period + frame_size) >> 1;
1223    {
1224        let pre_slices: Vec<&[f32]> = (0..channels)
1225            .map(|c| &pre[c * pre_size..c * pre_size + pre_size])
1226            .collect();
1227        crate::pitch::pitch_downsample(&pre_slices, pitch_buf, pitch_buf_len, channels, 2);
1228    }
1229
1230    let search_max = max_period - 3 * min_period;
1231    let pitch_result = crate::pitch::pitch_search(
1232        &pitch_buf[max_period >> 1..],
1233        pitch_buf,
1234        frame_size,
1235        search_max,
1236    );
1237    let mut pitch_index = (max_period - pitch_result).min(max_period - 2);
1238
1239    let gain1_raw = crate::pitch::remove_doubling(
1240        pitch_buf,
1241        max_period,
1242        min_period,
1243        frame_size,
1244        &mut pitch_index,
1245        prefilter_period,
1246        prefilter_gain,
1247    );
1248    let mut gain1 = gain1_raw * 0.7;
1249
1250    // Loss-rate ladder (matches celt_encoder.c: halve >2%, halve again >4%,
1251    // zero >8%).
1252    if loss_rate > 2 {
1253        gain1 *= 0.5;
1254    }
1255    if loss_rate > 4 {
1256        gain1 *= 0.5;
1257    }
1258    if loss_rate > 8 {
1259        gain1 = 0.0;
1260    }
1261
1262    // Apply max_pitch_ratio from analysis if available
1263    if analysis.valid {
1264        gain1 *= analysis.max_pitch_ratio;
1265    }
1266
1267    let mut pf_threshold = 0.2f32;
1268    if (pitch_index as i32 - prefilter_period as i32).unsigned_abs() as usize * 10 > pitch_index {
1269        pf_threshold += 0.2;
1270    }
1271    // Rate-based bumps (celt_encoder.c): the ~7 pf bits are not worth it on
1272    // starved frames.
1273    if nb_available_bytes < 25 {
1274        pf_threshold += 0.1;
1275    }
1276    if nb_available_bytes < 35 {
1277        pf_threshold += 0.1;
1278    }
1279    if prefilter_gain > 0.4 {
1280        pf_threshold -= 0.1;
1281    }
1282    if prefilter_gain > 0.55 {
1283        pf_threshold -= 0.1;
1284    }
1285    pf_threshold = pf_threshold.max(0.2);
1286
1287    let pf_on;
1288    if gain1 < pf_threshold {
1289        gain1 = 0.0;
1290        pf_on = false;
1291    } else {
1292        if (gain1 - prefilter_gain).abs() < 0.1 {
1293            gain1 = prefilter_gain;
1294        }
1295        let qg = ((gain1 * 32.0 / 3.0 + 0.5).floor() as i32 - 1).clamp(0, 7);
1296        gain1 = 0.09375 * (qg + 1) as f32;
1297        pf_on = true;
1298    }
1299
1300    // Standard Opus modes have shortMdctSize == overlap (120), so C's
1301    // `offset = mode->shortMdctSize - overlap` is always 0 here.
1302    let offset = 0usize;
1303    let prev_period = prefilter_period.clamp(COMBFILTER_MINPERIOD, max_period - 2);
1304
1305    for c in 0..channels {
1306        if offset > 0 {
1307            let pre_c = &pre[c * pre_size..];
1308            comb_filter(
1309                in_buf,
1310                pre_c,
1311                c * buf_stride + overlap,
1312                max_period,
1313                prev_period,
1314                prev_period,
1315                offset,
1316                -prefilter_gain,
1317                -prefilter_gain,
1318                prefilter_tapset,
1319                prefilter_tapset,
1320                window,
1321                0,
1322            );
1323        }
1324
1325        {
1326            let pre_c = &pre[c * pre_size..];
1327            comb_filter(
1328                in_buf,
1329                pre_c,
1330                c * buf_stride + overlap + offset,
1331                max_period + offset,
1332                prev_period,
1333                pitch_index,
1334                frame_size - offset,
1335                -prefilter_gain,
1336                -gain1,
1337                prefilter_tapset,
1338                tapset_decision,
1339                window,
1340                overlap,
1341            );
1342        }
1343    }
1344
1345    for c in 0..channels {
1346        if frame_size >= max_period {
1347            prefilter_mem[c * max_period..(c + 1) * max_period].copy_from_slice(
1348                &pre[c * pre_size + frame_size..c * pre_size + frame_size + max_period],
1349            );
1350        } else {
1351            let shift = max_period - frame_size;
1352            prefilter_mem.copy_within(
1353                c * max_period + frame_size..(c + 1) * max_period,
1354                c * max_period,
1355            );
1356            prefilter_mem[c * max_period + shift..(c + 1) * max_period].copy_from_slice(
1357                &pre[c * pre_size + max_period..c * pre_size + max_period + frame_size],
1358            );
1359        }
1360    }
1361
1362    (pf_on, gain1, pitch_index)
1363}
1364
1365const STRIDE_ACCESS_PAD: usize = crate::pvq::MAX_PVQ_N * 8;
1366
1367/// libopus celt_encoder.c `compute_vbr` (float build), minus the pieces that
1368/// need the tonality analysis / surround masking / LFE / temporal-VBR inputs we
1369/// don't compute (their boosts are quality refinements, not conformance).
1370/// All quantities in eighth-bits per frame.
1371#[allow(clippy::too_many_arguments)]
1372fn compute_vbr_target(
1373    mode: &CeltMode,
1374    base_target: i32,
1375    lm: i32,
1376    last_coded_bands: i32,
1377    channels: i32,
1378    intensity: i32,
1379    constrained_vbr: bool,
1380    stereo_saving: f32,
1381    tot_boost: i32,
1382    tf_estimate: f32,
1383    max_depth: f32,
1384) -> i32 {
1385    let nb_ebands = mode.nb_ebands as i32;
1386    let e_bands = mode.e_bands;
1387    let coded_bands = if last_coded_bands != 0 { last_coded_bands } else { nb_ebands };
1388    let mut coded_bins = (e_bands[coded_bands as usize] as i32) << lm;
1389    if channels == 2 {
1390        coded_bins += (e_bands[intensity.min(coded_bands) as usize] as i32) << lm;
1391    }
1392
1393    let mut target = base_target;
1394
1395    // Stereo savings.
1396    if channels == 2 {
1397        let coded_stereo_bands = intensity.min(coded_bands);
1398        let coded_stereo_dof =
1399            ((e_bands[coded_stereo_bands as usize] as i32) << lm) - coded_stereo_bands;
1400        // Maximum fraction of the bits we could save if the signal were mono.
1401        let max_frac = 0.8f32 * coded_stereo_dof as f32 / coded_bins as f32;
1402        let ss = stereo_saving.min(1.0);
1403        target -= ((max_frac * target as f32) as i32)
1404            .min((((ss - 0.1) * ((coded_stereo_dof << BITRES) as f32)) as i32).max(i32::MIN));
1405    }
1406    // Boost according to dynalloc (minus the average for calibration).
1407    target += tot_boost - (19 << lm);
1408    // Transient boost, compensating for the average.
1409    let tf_calibration = 0.044f32;
1410    target += (2.0 * (tf_estimate - tf_calibration) * target as f32) as i32;
1411
1412    // Don't allocate more than 8 bits above the "depth" of the signal.
1413    {
1414        let bins = (e_bands[nb_ebands as usize - 2] as i32) << lm;
1415        let mut floor_depth = ((channels * bins << BITRES) as f32 * max_depth) as i32;
1416        floor_depth = floor_depth.max(target >> 2);
1417        target = target.min(floor_depth);
1418    }
1419
1420    // Constrained VBR can't sustain large swings.
1421    if constrained_vbr {
1422        target = base_target + (0.67 * (target - base_target) as f32) as i32;
1423    }
1424
1425    // Never more than double the base rate.
1426    target.min(2 * base_target)
1427}
1428
1429pub struct CeltEncoder {
1430    mode: &'static CeltMode,
1431    channels: usize,
1432    pub complexity: i32,
1433    syn_mem: Vec<f32>,
1434    enc_decode_mem: Vec<f32>,
1435    old_band_e: Vec<f32>,
1436    preemph_mem: Vec<f32>,
1437    tonal_average: i32,
1438    hf_average: i32,
1439    tapset_decision: i32,
1440    spread_decision: i32,
1441    intensity: i32,
1442    last_coded_bands: i32,
1443    /// Input bit depth for the dynalloc noise floors (opus lsb_depth).
1444    pub lsb_depth: i32,
1445    /// VBR target in eighth-bits per frame (0 = hard CBR). libopus vbr_rate.
1446    pub vbr_rate: i32,
1447    /// Constrained VBR (libopus default): reservoir-limited drift around target.
1448    pub constrained_vbr: bool,
1449    vbr_reservoir: i32,
1450    vbr_drift: i32,
1451    vbr_offset: i32,
1452    vbr_count: i32,
1453    prefilter_mem: Vec<f32>,
1454    prefilter_period: usize,
1455    prefilter_gain: f32,
1456    prefilter_tapset: i32,
1457    old_band_e2: Vec<f32>,
1458    old_band_e3: Vec<f32>,
1459    last_band_log_e: Vec<f32>,
1460    delayed_intra: f32,
1461
1462    w_in_buf: Vec<f32>,
1463    w_freq: Vec<f32>,
1464    w_band_e: Vec<f32>,
1465    w_x: Vec<f32>,
1466    w_band_log_e: Vec<f32>,
1467    w_band_log_e2: Vec<f32>,
1468    w_error: Vec<f32>,
1469    w_tf_res: Vec<i32>,
1470    w_cap: Vec<i32>,
1471    w_offsets: Vec<i32>,
1472    w_pulses: Vec<i32>,
1473    w_ebits: Vec<i32>,
1474    w_fine_priority: Vec<i32>,
1475    w_collapse_masks: Vec<u32>,
1476    w_band_amp_synth: Vec<f32>,
1477    w_freq_synth: Vec<f32>,
1478    consec_transient: i32,
1479
1480    w_prefilter_pre: Vec<f32>,
1481    w_prefilter_pitch_buf: Vec<f32>,
1482
1483    w_transient_tmp: Vec<f32>,
1484    w_transient_tmp2: Vec<f32>,
1485
1486    pub(crate) analysis: AnalysisInfo,
1487    loss_rate: i32,
1488}
1489
1490const INTEN_THRESHOLDS: [i32; 21] = [
1491    1, 2, 3, 4, 5, 6, 7, 8, 16, 24, 36, 44, 50, 56, 62, 67, 72, 79, 88, 106, 134,
1492];
1493const INTEN_HYSTERESIS: [i32; 21] = [
1494    1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 5, 6, 8, 8,
1495];
1496
1497fn hysteresis_decision(val: i32, thresholds: &[i32], hysteresis: &[i32], prev: i32) -> i32 {
1498    let mut i = 0;
1499    while i < thresholds.len() {
1500        if val < thresholds[i] {
1501            break;
1502        }
1503        i += 1;
1504    }
1505    let mut res = i as i32;
1506    if res > prev && val < thresholds[prev as usize] + hysteresis[prev as usize] {
1507        res = prev;
1508    }
1509    if res < prev && res > 0 && val > thresholds[prev as usize - 1] - hysteresis[prev as usize - 1]
1510    {
1511        res = prev;
1512    }
1513    res
1514}
1515
1516#[allow(clippy::too_many_arguments)]
1517fn alloc_trim_analysis(
1518    mode: &CeltMode,
1519    x: &[f32],
1520    band_log_e: &[f32],
1521    end: usize,
1522    lm: i32,
1523    channels: usize,
1524    n0: usize,
1525    stereo_saving: &mut f32,
1526    tf_estimate: f32,
1527    intensity: i32,
1528    surround_trim: f32,
1529    equiv_rate: i32,
1530) -> i32 {
1531    let _prof = crate::prof::scope(crate::prof::Stage::CeltAlloc);
1532    let mut trim = 5.0f32;
1533    if equiv_rate < 64000 {
1534        trim = 4.0;
1535    } else if equiv_rate < 80000 {
1536        let frac = (equiv_rate - 64000) as f32 / 1024.0;
1537        trim = 4.0 + (1.0 / 16.0) * frac;
1538    }
1539
1540    if channels == 2 {
1541        let mut sum = 0.0f32;
1542        for i in 0..8 {
1543            let offset = (mode.e_bands[i] as usize) << lm;
1544            let n = ((mode.e_bands[i + 1] - mode.e_bands[i]) as usize) << lm;
1545            let mut partial = 0.0f32;
1546            for j in 0..n {
1547                partial += x[offset + j] * x[n0 + offset + j];
1548            }
1549            sum += partial;
1550        }
1551        sum = (sum / 8.0).abs().min(1.0);
1552        let mut min_xc = sum;
1553        for i in 8..intensity as usize {
1554            let offset = (mode.e_bands[i] as usize) << lm;
1555            let n = ((mode.e_bands[i + 1] - mode.e_bands[i]) as usize) << lm;
1556            let mut partial = 0.0f32;
1557            for j in 0..n {
1558                partial += x[offset + j] * x[n0 + offset + j];
1559            }
1560            min_xc = min_xc.min(partial.abs());
1561        }
1562        min_xc = min_xc.min(1.0);
1563
1564        let log_xc = (1.001 - sum * sum).log2();
1565        let log_xc2 = (log_xc * 0.5).max((1.001 - min_xc * min_xc).log2());
1566
1567        trim += (-4.0f32).max(0.75 * log_xc);
1568        *stereo_saving = (*stereo_saving + 0.25).min(-0.5 * log_xc2);
1569    }
1570
1571    let mut diff = 0.0f32;
1572    for c in 0..channels {
1573        for i in 0..end - 1 {
1574            diff += band_log_e[c * mode.nb_ebands + i] * (2 + 2 * i as i32 - end as i32) as f32;
1575        }
1576    }
1577    diff /= (channels * (end - 1)) as f32;
1578    trim -= (-2.0f32).max(2.0f32.min((diff + 1.0) / 6.0));
1579    trim -= surround_trim;
1580    trim -= 2.0 * tf_estimate;
1581
1582    // Stereo-music LF tilt (PEAQ-tuned, opt-out via env NO_STEREO_TRIM). Our
1583    // per-output analysis lands the trim slightly lower than is perceptually ideal
1584    // for coupled stereo music — tilting a little more toward LF (where our coding
1585    // is strongest) recovers ~0.03–0.10 ODG on stereo music across 64–192 kbps with
1586    // no regressions (a +2 tilt was stronger at mid rates but starved HF at 64k under
1587    // VBR rate overlap; +1 is the safe, monotonic choice). Mono is untouched, and
1588    // trim is transmitted so encoder/decoder stay in sync — fully conformant.
1589    let _ = equiv_rate;
1590    if channels == 2 && std::env::var("NO_STEREO_TRIM").is_err() {
1591        trim += 1.0;
1592    }
1593
1594    let trim_index = (trim + 0.5).floor() as i32;
1595    trim_index.clamp(0, 10)
1596}
1597
1598#[inline(always)]
1599fn median3(a: f32, b: f32, c: f32) -> f32 {
1600    let mut v = [a, b, c];
1601    v.sort_by(|x, y| x.partial_cmp(y).unwrap_or(std::cmp::Ordering::Equal));
1602    v[1]
1603}
1604
1605#[inline(always)]
1606fn median5(v: &[f32]) -> f32 {
1607    let mut x = [v[0], v[1], v[2], v[3], v[4]];
1608    x.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
1609    x[2]
1610}
1611
1612/// Full port of celt_encoder.c dynalloc_analysis: per-band boosts (offsets),
1613/// the tf importance weights, the spreading-decision SMR weights, and maxDepth
1614/// (the signal depth over the noise floor, used as the VBR ceiling). Consumes
1615/// the pre-transient band logs (band_log_e2) and the analysis leak_boost.
1616#[allow(clippy::too_many_arguments)]
1617fn dynalloc_analysis(
1618    mode: &CeltMode,
1619    band_log_e: &[f32],
1620    band_log_e2: &[f32],
1621    start: usize,
1622    end: usize,
1623    channels: usize,
1624    offsets: &mut [i32],
1625    lsb_depth: i32,
1626    is_transient: bool,
1627    vbr: bool,
1628    constrained_vbr: bool,
1629    lm: usize,
1630    effective_bytes: usize,
1631    analysis: &AnalysisInfo,
1632    importance: &mut [f32],
1633    spread_weight: &mut [i32],
1634) -> f32 {
1635    let _prof = crate::prof::scope(crate::prof::Stage::CeltAlloc);
1636    let nb = mode.nb_ebands;
1637    offsets.fill(0);
1638
1639    // Noise floor: eMeans, depth, band width (logN) and the preemphasis tilt
1640    // (~ square of the bark band index).
1641    let mut noise_floor = [0.0f32; MAX_NB_EBANDS];
1642    for i in 0..end {
1643        noise_floor[i] = 0.0625 * mode.log_n[i] as f32 + 0.5 + (9 - lsb_depth) as f32
1644            - mode.e_means[i]
1645            + 0.0062 * ((i + 5) * (i + 5)) as f32;
1646    }
1647    let mut max_depth = -31.9f32;
1648    for c in 0..channels {
1649        for i in 0..end {
1650            max_depth = max_depth.max(band_log_e[c * nb + i] - noise_floor[i]);
1651        }
1652    }
1653
1654    // Simple masking model for the spreading decision: ignore fully masked bands.
1655    {
1656        let mut mask = [0.0f32; MAX_NB_EBANDS];
1657        let mut sig = [0.0f32; MAX_NB_EBANDS];
1658        for i in 0..end {
1659            mask[i] = band_log_e[i] - noise_floor[i];
1660        }
1661        if channels == 2 {
1662            for i in 0..end {
1663                mask[i] = mask[i].max(band_log_e[nb + i] - noise_floor[i]);
1664            }
1665        }
1666        sig[..end].copy_from_slice(&mask[..end]);
1667        for i in 1..end {
1668            mask[i] = mask[i].max(mask[i - 1] - 2.0);
1669        }
1670        for i in (0..end.saturating_sub(1)).rev() {
1671            mask[i] = mask[i].max(mask[i + 1] - 3.0);
1672        }
1673        for i in 0..end {
1674            // SMR: mask never more than 72 dB below the peak, never below floor.
1675            let smr = sig[i] - (0.0f32.max(max_depth - 12.0)).max(mask[i]);
1676            let shift = 5.min(0.max(-((0.5 + smr).floor() as i32)));
1677            spread_weight[i] = 32 >> shift;
1678        }
1679    }
1680
1681    // Make sure dynamic allocation can't bust the budget.
1682    if effective_bytes > 50 && lm >= 1 {
1683        let mut follower = [0.0f32; 2 * MAX_NB_EBANDS];
1684        let mut last = 0usize;
1685        for c in 0..channels {
1686            let base = c * nb;
1687            follower[base] = band_log_e2[base];
1688            for i in 1..end {
1689                // The last band at least .5 dB higher than the previous one is
1690                // the last we'll consider (band-limited signals).
1691                if band_log_e2[base + i] > band_log_e2[base + i - 1] + 0.5 {
1692                    last = i;
1693                }
1694                follower[base + i] =
1695                    (follower[base + i - 1] + 1.5).min(band_log_e2[base + i]);
1696            }
1697            for i in (0..last).rev() {
1698                follower[base + i] = follower[base + i]
1699                    .min((follower[base + i + 1] + 2.0).min(band_log_e2[base + i]));
1700            }
1701
1702            // Median filter so dynalloc doesn't trigger unnecessarily.
1703            let offset = 1.0f32;
1704            if end >= 5 {
1705                for i in 2..end - 2 {
1706                    follower[base + i] = follower[base + i]
1707                        .max(median5(&band_log_e2[base + i - 2..base + i + 3]) - offset);
1708                }
1709            }
1710            if end >= 3 {
1711                let tmp = median3(
1712                    band_log_e2[base],
1713                    band_log_e2[base + 1],
1714                    band_log_e2[base + 2],
1715                ) - offset;
1716                follower[base] = follower[base].max(tmp);
1717                follower[base + 1] = follower[base + 1].max(tmp);
1718                let tmp = median3(
1719                    band_log_e2[base + end - 3],
1720                    band_log_e2[base + end - 2],
1721                    band_log_e2[base + end - 1],
1722                ) - offset;
1723                follower[base + end - 2] = follower[base + end - 2].max(tmp);
1724                follower[base + end - 1] = follower[base + end - 1].max(tmp);
1725            }
1726
1727            for i in 0..end {
1728                follower[base + i] = follower[base + i].max(noise_floor[i]);
1729            }
1730        }
1731        if channels == 2 {
1732            for i in start..end {
1733                // Consider 24 dB "cross-talk".
1734                follower[nb + i] = follower[nb + i].max(follower[i] - 4.0);
1735                follower[i] = follower[i].max(follower[nb + i] - 4.0);
1736                follower[i] = 0.5
1737                    * ((band_log_e[i] - follower[i]).max(0.0)
1738                        + (band_log_e[nb + i] - follower[nb + i]).max(0.0));
1739            }
1740        } else {
1741            for i in start..end {
1742                follower[i] = (band_log_e[i] - follower[i]).max(0.0);
1743            }
1744        }
1745        for i in start..end {
1746            importance[i] = (0.5 + 13.0 * (follower[i].min(4.0)).exp2()).floor();
1747        }
1748        // For non-transient CBR/CVBR frames, halve the dynalloc contribution.
1749        if (!vbr || constrained_vbr) && !is_transient {
1750            for f in follower.iter_mut().take(end).skip(start) {
1751                *f *= 0.5;
1752            }
1753        }
1754        for i in start..end {
1755            if i < 8 {
1756                follower[i] *= 2.0;
1757            }
1758            if i >= 12 {
1759                follower[i] *= 0.5;
1760            }
1761        }
1762        if analysis.valid {
1763            for i in start..end.min(19) {
1764                follower[i] += analysis.leak_boost[i] as f32 * (1.0 / 64.0);
1765            }
1766        }
1767        let mut tot_boost = 0i32;
1768        for i in start..end {
1769            follower[i] = follower[i].min(4.0);
1770
1771            let width =
1772                channels as i32 * (mode.e_bands[i + 1] - mode.e_bands[i]) as i32 * (1 << lm);
1773            let (boost, boost_bits) = if width < 6 {
1774                let b = follower[i] as i32;
1775                (b, (b * width) << BITRES)
1776            } else if width > 48 {
1777                let b = (follower[i] * 8.0) as i32;
1778                (b, ((b * width) << BITRES) / 8)
1779            } else {
1780                let b = (follower[i] * width as f32 / 6.0) as i32;
1781                (b, (b * 6) << BITRES)
1782            };
1783            // For CBR and non-transient CVBR frames, limit dynalloc to 2/3 of
1784            // the bits.
1785            if (!vbr || (constrained_vbr && !is_transient))
1786                && ((tot_boost + boost_bits) >> BITRES >> 3) > 2 * effective_bytes as i32 / 3
1787            {
1788                let cap = (2 * effective_bytes as i32 / 3) << BITRES << 3;
1789                offsets[i] = cap - tot_boost;
1790                break;
1791            } else {
1792                offsets[i] = boost;
1793                tot_boost += boost_bits;
1794            }
1795        }
1796    } else {
1797        for i in start..end {
1798            importance[i] = 13.0;
1799        }
1800    }
1801    max_depth
1802}
1803
1804impl CeltEncoder {
1805    pub fn new(mode: &'static CeltMode, channels: usize) -> Self {
1806        let overlap = mode.overlap;
1807        let channel_mem_size = 2048 + overlap;
1808        let syn_mem_size = channels * channel_mem_size;
1809        let nb_ebands = mode.nb_ebands;
1810        let nb_x_ch = nb_ebands * channels;
1811        let frame_x_ch = MAX_FRAME_SIZE * channels;
1812        let bufstride_x_ch = (MAX_FRAME_SIZE + overlap) * channels;
1813        Self {
1814            mode,
1815            channels,
1816            complexity: 9,
1817            syn_mem: vec![0.0; syn_mem_size],
1818            enc_decode_mem: vec![0.0; syn_mem_size],
1819            old_band_e: vec![0.0; nb_x_ch],
1820            preemph_mem: vec![0.0; channels],
1821            tonal_average: 256,
1822            hf_average: 0,
1823            tapset_decision: 0,
1824            spread_decision: SPREAD_NORMAL,
1825            intensity: 0,
1826            last_coded_bands: 0,
1827            lsb_depth: 24,
1828            vbr_rate: 0,
1829            constrained_vbr: true,
1830            vbr_reservoir: 0,
1831            vbr_drift: 0,
1832            vbr_offset: 0,
1833            vbr_count: 0,
1834            prefilter_mem: vec![0.0; channels * COMBFILTER_MAXPERIOD],
1835            prefilter_period: COMBFILTER_MINPERIOD,
1836            prefilter_gain: 0.0,
1837            prefilter_tapset: 0,
1838            old_band_e2: vec![0.0; nb_x_ch],
1839            old_band_e3: vec![0.0; nb_x_ch],
1840            last_band_log_e: vec![0.0; nb_x_ch],
1841            delayed_intra: 0.0,
1842
1843            w_in_buf: vec![0.0; bufstride_x_ch],
1844            w_freq: vec![0.0; frame_x_ch + 4],
1845            w_band_e: vec![0.0; nb_x_ch],
1846
1847            w_x: vec![0.0; frame_x_ch + STRIDE_ACCESS_PAD],
1848            w_band_log_e: vec![0.0; nb_x_ch],
1849            w_band_log_e2: vec![0.0; nb_x_ch],
1850            w_error: vec![0.0; nb_x_ch],
1851            w_tf_res: vec![0; nb_ebands],
1852            w_cap: vec![0; nb_ebands],
1853            w_offsets: vec![0; nb_ebands],
1854            w_pulses: vec![0; nb_ebands],
1855            w_ebits: vec![0; nb_x_ch],
1856            w_fine_priority: vec![0; nb_x_ch],
1857            w_collapse_masks: vec![0; nb_x_ch],
1858            w_band_amp_synth: vec![0.0; nb_x_ch],
1859            w_freq_synth: vec![0.0; frame_x_ch + 4],
1860
1861            w_prefilter_pre: vec![0.0; channels * (COMBFILTER_MAXPERIOD + MAX_FRAME_SIZE)],
1862            w_prefilter_pitch_buf: vec![0.0; (COMBFILTER_MAXPERIOD + MAX_FRAME_SIZE) >> 1],
1863            w_transient_tmp: vec![0.0; MAX_TRANSIENT_LEN],
1864            w_transient_tmp2: vec![0.0; MAX_TRANSIENT_LEN / 2],
1865            consec_transient: 0,
1866
1867            analysis: AnalysisInfo::default(),
1868            loss_rate: 0,
1869        }
1870    }
1871
1872    pub fn encode(&mut self, pcm: &[f32], frame_size: usize, rc: &mut RangeCoder) {
1873        self.encode_impl(pcm, frame_size, rc, 0, self.mode.nb_ebands, None)
1874    }
1875
1876    pub fn encode_with_start_band(
1877        &mut self,
1878        pcm: &[f32],
1879        frame_size: usize,
1880        rc: &mut RangeCoder,
1881        start_band: usize,
1882    ) {
1883        self.encode_impl(pcm, frame_size, rc, start_band, self.mode.nb_ebands, None)
1884    }
1885
1886    pub fn encode_with_budget(
1887        &mut self,
1888        pcm: &[f32],
1889        frame_size: usize,
1890        rc: &mut RangeCoder,
1891        start_band: usize,
1892        end_band: usize,
1893        total_bits: i32,
1894    ) {
1895        self.encode_impl(pcm, frame_size, rc, start_band, end_band, Some(total_bits))
1896    }
1897
1898    fn encode_impl(
1899        &mut self,
1900        pcm: &[f32],
1901        frame_size: usize,
1902        rc: &mut RangeCoder,
1903        start_band: usize,
1904        end_band: usize,
1905        explicit_total_bits: Option<i32>,
1906    ) {
1907        debug_assert!(end_band > start_band && end_band <= self.mode.nb_ebands);
1908        let mode = self.mode;
1909        let channels = self.channels;
1910        let nb_ebands = mode.nb_ebands;
1911        let overlap = mode.overlap;
1912        // Bits already in the coder at entry (the SILK part in hybrid mode) — used
1913        // by the VBR min-size guard so shrinking never truncates them.
1914        let tell0_frac = rc.tell_frac();
1915
1916        let mut lm = 0;
1917        while (mode.short_mdct_size << lm) != frame_size {
1918            lm += 1;
1919            if lm > mode.max_lm {
1920                break;
1921            }
1922        }
1923        if (mode.short_mdct_size << lm) != frame_size {
1924            lm = 0;
1925        }
1926
1927        let _prof_pre = crate::prof::scope(crate::prof::Stage::CeltPreemph);
1928        let syn_mem_size = 2048 + overlap;
1929        for c in 0..channels {
1930            let channel_offset = c * syn_mem_size;
1931
1932            self.syn_mem.copy_within(
1933                channel_offset + frame_size..channel_offset + syn_mem_size,
1934                channel_offset,
1935            );
1936
1937            let mut m = self.preemph_mem[c];
1938            let coef = mode.preemph[0];
1939            for i in 0..frame_size {
1940                let x = pcm[c * frame_size + i] * 32768.0;
1941                let val = x - m;
1942                self.syn_mem[channel_offset + syn_mem_size - frame_size + i] = val;
1943                m = x * coef;
1944            }
1945            self.preemph_mem[c] = m;
1946        }
1947
1948        let buf_stride = frame_size + overlap;
1949        let in_buf = &mut self.w_in_buf[..buf_stride * channels];
1950        for c in 0..channels {
1951            let channel_offset = c * syn_mem_size;
1952            let in_buf_offset = c * buf_stride;
1953
1954            let src_start = syn_mem_size - frame_size - overlap;
1955            in_buf[in_buf_offset..in_buf_offset + buf_stride].copy_from_slice(
1956                &self.syn_mem[channel_offset + src_start..channel_offset + syn_mem_size],
1957            );
1958        }
1959
1960        drop(_prof_pre);
1961
1962        // Encoder pitch prefilter (the inverse of the decoder postfilter).
1963        // Enable gate matches celt_encoder.c: enough bytes to be worth the ~7
1964        // bits, CELT-only (start_band == 0; the hybrid high band has no pf),
1965        // complexity >= 5. `CELT_PF_OFF` disables for A/B debugging.
1966        // (History: default-off until 2026-07-09 — the octave signalling was one
1967        // low for every pitch_index >= 31, so decoders reconstructed a garbage
1968        // period; fixed, sine round-trip 7.6 -> 45.7 dB.)
1969        let nb_available_bytes = (explicit_total_bits.unwrap_or((rc.buf.len() * 8) as i32) >> 3)
1970            - ((rc.tell() + 4) >> 3);
1971        let pf_enabled = start_band == 0
1972            && self.complexity >= 5
1973            && nb_available_bytes > 12 * channels as i32
1974            && std::env::var("CELT_PF_OFF").is_err();
1975        // Capture the tapset used for THIS frame's comb (C's `prefilter_tapset`
1976        // local): spreading_decision mutates self.tapset_decision later in the
1977        // frame, and the value applied+signalled here — not the mutated one —
1978        // must become next frame's "old" tapset.
1979        let prefilter_tapset = self.tapset_decision;
1980        let (pf_on, gain1, pitch_index) = if pf_enabled {
1981            run_prefilter(
1982                in_buf,
1983                &mut self.prefilter_mem,
1984                self.prefilter_period,
1985                self.prefilter_gain,
1986                self.prefilter_tapset,
1987                prefilter_tapset,
1988                mode.window,
1989                channels,
1990                frame_size,
1991                overlap,
1992                &mut self.w_prefilter_pre,
1993                &mut self.w_prefilter_pitch_buf,
1994                &self.analysis,
1995                self.loss_rate,
1996                nb_available_bytes,
1997            )
1998        } else {
1999            (false, 0.0f32, COMBFILTER_MINPERIOD)
2000        };
2001
2002        // Save the prefiltered overlap for the next frame.
2003        // In libopus, st->in_mem stores the overlap separately and run_prefilter
2004        // copies it to/from in[]. Here we emulate that by updating syn_mem with
2005        // the last overlap samples of in_buf (which were prefiltered in place).
2006        let syn_mem_size = 2048 + overlap;
2007        for c in 0..channels {
2008            let channel_offset = c * syn_mem_size;
2009            let in_buf_offset = c * buf_stride;
2010            self.syn_mem[channel_offset + syn_mem_size - overlap..channel_offset + syn_mem_size]
2011                .copy_from_slice(&in_buf[in_buf_offset + frame_size..in_buf_offset + buf_stride]);
2012        }
2013
2014        // Transient analysis runs on the PREFILTERED signal (celt_encoder.c
2015        // order) — the comb removes periodic energy so pitch pulses don't read
2016        // as transients.
2017        let mut tf_estimate = 0.0f32;
2018        let mut tf_chan = 0;
2019        let mut weak_transient = false;
2020        let is_transient = if self.complexity >= 1 {
2021            transient_analysis(
2022                in_buf,
2023                buf_stride,
2024                channels,
2025                &mut tf_estimate,
2026                &mut tf_chan,
2027                false,
2028                &mut weak_transient,
2029                0.0,
2030                0.0,
2031                &mut self.w_transient_tmp,
2032                &mut self.w_transient_tmp2,
2033            )
2034        } else {
2035            false
2036        };
2037
2038        let freq = &mut self.w_freq[..frame_size * channels];
2039        // The first MDCT pass is always LONG blocks: for non-transients it is
2040        // the coding transform; for transients it feeds bandLogE2 (the
2041        // pre-transient spectrum dynalloc smooths against, celt_encoder.c
2042        // secondMdct) and the short re-MDCT below produces the coding one.
2043        let (shift, b) = (mode.max_lm - lm, 1);
2044        let n = frame_size / b;
2045
2046        for c in 0..channels {
2047            let c_buf_offset = c * buf_stride;
2048
2049            if c == 0 && b == 1 && channels == 1 {
2050                let mut max_val = 0.0f32;
2051                let check_len = (frame_size + overlap).min(buf_stride);
2052                for j in 0..check_len {
2053                    max_val = max_val.max(in_buf[c_buf_offset + j].abs());
2054                }
2055            }
2056
2057            for i in 0..b {
2058                mode.mdct.forward(
2059                    &in_buf[c_buf_offset + i * n..],
2060                    &mut freq[c * frame_size + i..],
2061                    mode.window,
2062                    overlap,
2063                    shift,
2064                    b,
2065                );
2066            }
2067        }
2068
2069        let band_e = &mut self.w_band_e[..nb_ebands * channels];
2070        band_e.fill(0.0);
2071        compute_band_energies(mode, freq, band_e, end_band, channels, lm);
2072
2073        let x_pad_end = (frame_size * channels + STRIDE_ACCESS_PAD).min(self.w_x.len());
2074        let x = &mut self.w_x[..x_pad_end];
2075        normalise_bands(
2076            mode,
2077            freq,
2078            x,
2079            band_e,
2080            end_band,
2081            channels,
2082            (1 << lm) as usize,
2083        );
2084
2085        if channels == 1 {
2086            let _ = freq[0];
2087        }
2088
2089        let total_bits = explicit_total_bits.unwrap_or_else(|| (rc.buf.len() * 8) as i32);
2090        self.w_error[..nb_ebands * channels].fill(0.0);
2091        let error = &mut self.w_error[..nb_ebands * channels];
2092
2093        let tell = rc.tell();
2094        let silence = false;
2095        if tell == 1 {
2096            rc.encode_bit_logp(silence, 15);
2097        }
2098
2099        if start_band == 0 && !silence && rc.tell() + 16 <= total_bits {
2100            rc.encode_bit_logp(pf_on, 1);
2101            if pf_on {
2102                let qg = (gain1 / 0.09375 - 1.0 + 0.5).floor() as i32;
2103                let qg = qg.clamp(0, 7);
2104                let pi = (pitch_index + 1) as u32;
2105                // octave = EC_ILOG(pi) - 5 (EC_ILOG = 32 - clz, the BIT COUNT of
2106                // pi, not floor(log2)). The old `31 - clz` was one octave low for
2107                // every pi >= 32, overflowing the 4+octave residual field -> the
2108                // decoder reconstructed a garbage period (the prefilter's AM/PM
2109                // sideband bug). pi >= MINPERIOD+1 = 16 keeps this >= 0.
2110                let octave = 32 - pi.leading_zeros() - 5;
2111                rc.enc_uint(octave, 6);
2112                rc.enc_bits(pi - (16 << octave), 4 + octave);
2113                rc.enc_bits(qg as u32, 3);
2114                rc.encode_icdf(prefilter_tapset, &TAPSET_ICDF, 2);
2115            }
2116        }
2117
2118        let mut short_blocks = false;
2119        if lm > 0 && rc.tell() + 3 <= total_bits {
2120            rc.encode_bit_logp(is_transient, 3);
2121            if is_transient {
2122                short_blocks = true;
2123            }
2124        }
2125
2126        // bandLogE2: the long-MDCT logs + 0.5*LM when we re-MDCT short
2127        // (celt_encoder.c secondMdct); else a copy of the final logs (set after
2128        // the final amp2log2 below).
2129        let mut second_mdct_logs = false;
2130        if short_blocks && self.complexity >= 8 {
2131            let band_log_e2 = &mut self.w_band_log_e2[..nb_ebands * channels];
2132            band_log_e2.fill(-14.0);
2133            crate::bands::amp2log2(mode, 0, end_band, band_e, band_log_e2, channels);
2134            for v in band_log_e2.iter_mut() {
2135                *v += 0.5 * lm as f32;
2136            }
2137            second_mdct_logs = true;
2138        }
2139        if short_blocks {
2140            let b = 1 << lm;
2141            let n = frame_size / b;
2142            for c in 0..channels {
2143                let c_offset = c * buf_stride;
2144                for i in 0..b {
2145                    mode.mdct.forward(
2146                        &in_buf[c_offset + i * n..c_offset + buf_stride],
2147                        &mut freq[c * frame_size + i..],
2148                        mode.window,
2149                        overlap,
2150                        mode.max_lm,
2151                        b,
2152                    );
2153                }
2154            }
2155
2156            compute_band_energies(mode, freq, band_e, end_band, channels, lm);
2157            normalise_bands(
2158                mode,
2159                freq,
2160                x,
2161                band_e,
2162                end_band,
2163                channels,
2164                (1 << lm) as usize,
2165            );
2166        }
2167
2168        // Final band logs come AFTER the (possibly short) coding MDCT — C order
2169        // (celt_encoder.c:1742). C computes real logs for ALL bands below end
2170        // (amp2Log2 effEnd==end), incl. below start in hybrid: dynalloc's noise
2171        // floor and the spreading mask read them.
2172        let band_log_e = &mut self.w_band_log_e[..nb_ebands * channels];
2173        band_log_e.fill(-14.0);
2174        crate::bands::amp2log2(mode, 0, end_band, band_e, band_log_e, channels);
2175        if !second_mdct_logs {
2176            self.w_band_log_e2[..nb_ebands * channels].copy_from_slice(band_log_e);
2177        }
2178
2179        let intra_ener = if self.complexity >= 4 {
2180            false
2181        } else {
2182            self.old_band_e[..nb_ebands * channels]
2183                .iter()
2184                .all(|&e| e <= -27.0)
2185        };
2186        quant_coarse_energy_advanced(
2187            mode,
2188            start_band,
2189            end_band,
2190            end_band,
2191            band_log_e,
2192            &mut self.old_band_e,
2193            total_bits as u32,
2194            error,
2195            rc,
2196            channels,
2197            lm,
2198            (total_bits / 8) as usize,
2199            is_transient || intra_ener,
2200            &mut self.delayed_intra,
2201            self.complexity >= 4,
2202            0,
2203            false,
2204        );
2205        // Dynalloc analysis runs BEFORE tf (celt_encoder.c order): its
2206        // importance[] weights the tf Viterbi costs and spread_weight[] feeds
2207        // the spreading decision. The boost FLAGS are still written later, in
2208        // bitstream order.
2209        let effective_bytes = ((total_bits / 8) as usize).max(1);
2210        let mut importance = [13.0f32; MAX_NB_EBANDS];
2211        let mut spread_weight = [32i32; MAX_NB_EBANDS];
2212        self.w_offsets[..nb_ebands].fill(0);
2213        let max_depth = {
2214            let band_log_e2 = &self.w_band_log_e2[..nb_ebands * channels];
2215            dynalloc_analysis(
2216                mode,
2217                band_log_e,
2218                band_log_e2,
2219                start_band,
2220                end_band,
2221                channels,
2222                &mut self.w_offsets[..nb_ebands],
2223                self.lsb_depth,
2224                is_transient,
2225                self.vbr_rate > 0,
2226                self.constrained_vbr,
2227                lm,
2228                effective_bytes,
2229                &self.analysis,
2230                &mut importance,
2231                &mut spread_weight,
2232            )
2233        };
2234
2235        self.w_tf_res[..nb_ebands].fill(0);
2236        let tf_res = &mut self.w_tf_res[..nb_ebands];
2237        let lambda = 80.max(20480 / effective_bytes + 2) as i32;
2238
2239        let tf_select = if self.complexity >= 2 && effective_bytes >= 15 * channels {
2240            tf_analysis(
2241                mode,
2242                end_band,
2243                is_transient,
2244                tf_res,
2245                lambda,
2246                x,
2247                frame_size,
2248                lm as i32,
2249                tf_estimate,
2250                tf_chan,
2251                &importance,
2252            )
2253        } else {
2254            0
2255        };
2256        tf_encode(
2257            start_band,
2258            end_band,
2259            is_transient,
2260            tf_res,
2261            lm as i32,
2262            tf_select,
2263            rc,
2264        );
2265
2266        let mut dual_stereo_val = if channels == 2 {
2267            stereo_analysis(mode, x, lm as i32, frame_size) as i32
2268        } else {
2269            0
2270        };
2271
2272        let mut stereo_saving = 0.0f32;
2273        let equiv_rate = (total_bits * 48000) / frame_size as i32;
2274        if channels == 2 {
2275            self.intensity = hysteresis_decision(
2276                equiv_rate / 1000,
2277                &INTEN_THRESHOLDS,
2278                &INTEN_HYSTERESIS,
2279                self.intensity,
2280            );
2281            // Clamp to [start, end], NOT [0, nb_ebands] (celt_encoder.c:2034).
2282            // clt_compute_allocation codes `intensity - start` in a field of
2283            // width `end + 1 - start`; a value below start (which happens in
2284            // stereo HYBRID, start_band = 17) underflowed that field and
2285            // desynced the range coder on the first stereo-hybrid frame.
2286            self.intensity = self.intensity.clamp(start_band as i32, end_band as i32);
2287        }
2288
2289        if self.complexity == 0 {
2290            self.spread_decision = SPREAD_NONE;
2291            if rc.tell() + 4 <= total_bits {
2292                rc.encode_icdf(self.spread_decision, &SPREAD_ICDF, 5);
2293            }
2294        } else if rc.tell() + 4 <= total_bits {
2295            if is_transient || self.complexity < 3 || effective_bytes < 10 * channels {
2296                self.spread_decision = SPREAD_NORMAL;
2297            } else {
2298                let update_hf = lm == mode.max_lm;
2299                self.spread_decision = spreading_decision(
2300                    mode,
2301                    x,
2302                    &mut self.tonal_average,
2303                    self.spread_decision,
2304                    &mut self.hf_average,
2305                    &mut self.tapset_decision,
2306                    update_hf,
2307                    end_band,
2308                    channels,
2309                    (1 << lm) as usize,
2310                    &spread_weight,
2311                );
2312            }
2313            rc.encode_icdf(self.spread_decision, &SPREAD_ICDF, 5);
2314        } else {
2315            self.spread_decision = SPREAD_NORMAL;
2316        }
2317
2318        self.w_cap[..nb_ebands].fill(0);
2319        let cap = &mut self.w_cap[..nb_ebands];
2320        for (i, cap_i) in cap.iter_mut().enumerate() {
2321            let n = (mode.e_bands[i + 1] - mode.e_bands[i]) << lm;
2322            *cap_i = ((mode.cache.caps[nb_ebands * (2 * lm + channels - 1) + i] as i32 + 64)
2323                * channels as i32
2324                * n as i32)
2325                >> 2;
2326        }
2327
2328        let offsets = &mut self.w_offsets[..nb_ebands];
2329
2330        let mut dynalloc_logp = 6i32;
2331        let total_bits_bitres = total_bits << BITRES;
2332        let mut total_boost = 0i32;
2333        let mut tell_frac = rc.tell_frac();
2334
2335        for i in start_band..end_band {
2336            let width =
2337                channels as i32 * (mode.e_bands[i + 1] - mode.e_bands[i]) as i32 * (1 << lm);
2338            let quanta = (width << BITRES).min((6 << BITRES).max(width));
2339            let mut dynalloc_loop_logp = dynalloc_logp;
2340            let mut boost = 0i32;
2341            let mut j = 0i32;
2342
2343            while tell_frac + (dynalloc_loop_logp << BITRES) < total_bits_bitres - total_boost
2344                && boost < cap[i]
2345            {
2346                let flag = j < offsets[i];
2347                rc.encode_bit_logp(flag, dynalloc_loop_logp as u32);
2348                tell_frac = rc.tell_frac();
2349                if !flag {
2350                    break;
2351                }
2352                boost += quanta;
2353                total_boost += quanta;
2354                dynalloc_loop_logp = 1;
2355                j += 1;
2356            }
2357
2358            if j > 0 {
2359                dynalloc_logp = 2.max(dynalloc_logp - 1);
2360            }
2361            offsets[i] = boost;
2362        }
2363
2364        let alloc_trim = alloc_trim_analysis(
2365            mode,
2366            x,
2367            band_log_e,
2368            end_band,
2369            lm as i32,
2370            channels,
2371            frame_size,
2372            &mut stereo_saving,
2373            tf_estimate,
2374            self.intensity,
2375            0.0,
2376            equiv_rate,
2377        );
2378        // libopus celt_encoder.c: alloc_trim is 5 UNLESS there is room to code the
2379        // analysis value — the decoder falls back to 5 when the trim isn't coded,
2380        // so the encoder MUST use 5 in the allocation math too. Keeping the
2381        // analysis trim here made trim_offset (hence the allocation) differ from
2382        // every conformant decoder on tight-budget frames (e.g. 24 kbps hybrid),
2383        // desyncing the range coder on ~1% of packets.
2384        let alloc_trim = if rc.tell_frac() + (6 << BITRES) <= total_bits_bitres - total_boost {
2385            rc.encode_icdf(alloc_trim, &TRIM_ICDF, 7);
2386            alloc_trim
2387        } else {
2388            5
2389        };
2390
2391        // ---- VBR: pick this frame's size and shrink the coder to it ----
2392        // (libopus celt_encoder.c `if (vbr_rate>0)`; runs between the trim and the
2393        // allocation so the allocator sees the final budget.)
2394        let total_bits = if self.vbr_rate > 0 {
2395            let hybrid = start_band != 0;
2396            let lm_diff = mode.max_lm as i32 - lm as i32;
2397            let vbr_rate = self.vbr_rate;
2398            let mut base_target = if hybrid {
2399                0.max(vbr_rate - ((9 * channels as i32 + 4) << BITRES))
2400            } else {
2401                vbr_rate - ((40 * channels as i32 + 20) << BITRES)
2402            };
2403            if self.constrained_vbr {
2404                base_target += self.vbr_offset >> lm_diff;
2405            }
2406            let mut target = if hybrid {
2407                // (libopus also nudges by the SILK quantization offset; we don't
2408                // track silk_info yet — quality refinement, not conformance.)
2409                let mut t = base_target;
2410                t += ((tf_estimate - 0.25) * (50 << BITRES) as f32) as i32;
2411                if tf_estimate > 0.7 {
2412                    t = t.max(50 << BITRES);
2413                }
2414                t
2415            } else {
2416                compute_vbr_target(
2417                    mode,
2418                    base_target,
2419                    lm as i32,
2420                    self.last_coded_bands,
2421                    channels as i32,
2422                    self.intensity,
2423                    self.constrained_vbr,
2424                    stereo_saving,
2425                    total_boost,
2426                    tf_estimate,
2427                    max_depth,
2428                )
2429            };
2430            let tell = rc.tell_frac();
2431            target += tell;
2432            // Never shrink below what's already coded (+2 bytes of margin); in
2433            // hybrid, keep >=37 bits after the SILK part so the redundancy
2434            // signalling space assumed by every decoder still exists.
2435            let mut min_allowed =
2436                ((tell + total_boost + (1 << (BITRES + 3)) - 1) >> (BITRES + 3)) + 2;
2437            if hybrid {
2438                min_allowed = min_allowed.max(
2439                    (tell0_frac + (37 << BITRES) + total_boost + (1 << (BITRES + 3)) - 1)
2440                        >> (BITRES + 3),
2441                );
2442            }
2443            let cap_bytes = (total_bits / 8).min(1275 >> (3 - lm as i32));
2444            let mut nb_available = (target + (1 << (BITRES + 2))) >> (BITRES + 3);
2445            nb_available = nb_available.max(min_allowed).min(cap_bytes);
2446
2447            // Reservoir/drift tracking (constrained VBR).
2448            let delta = target - vbr_rate;
2449            let target_q = nb_available << (BITRES + 3);
2450            if self.vbr_count < 970 {
2451                self.vbr_count += 1;
2452            }
2453            let alpha = if self.vbr_count < 970 {
2454                1.0f32 / (self.vbr_count as f32 + 20.0)
2455            } else {
2456                0.001f32
2457            };
2458            if self.constrained_vbr {
2459                self.vbr_reservoir += target_q - vbr_rate;
2460                self.vbr_drift += (alpha
2461                    * ((delta * (1 << lm_diff)) - self.vbr_offset - self.vbr_drift) as f32)
2462                    as i32;
2463                self.vbr_offset = -self.vbr_drift;
2464                if self.vbr_reservoir < 0 {
2465                    let adjust = (-self.vbr_reservoir) / (8 << BITRES);
2466                    nb_available += adjust;
2467                    self.vbr_reservoir = 0;
2468                }
2469            }
2470            let nb_compressed = cap_bytes.min(nb_available).max(2);
2471            rc.shrink(nb_compressed as u32);
2472            nb_compressed * 8
2473        } else {
2474            total_bits
2475        };
2476
2477        let mut intensity = self.intensity;
2478        self.w_pulses[..nb_ebands].fill(0);
2479        let pulses = &mut self.w_pulses[..nb_ebands];
2480
2481        let stereo = channels > 1;
2482        let ebands_stereo = if stereo {
2483            nb_ebands * channels
2484        } else {
2485            nb_ebands
2486        };
2487        self.w_fine_priority[..ebands_stereo].fill(0);
2488        let fine_priority = &mut self.w_fine_priority[..ebands_stereo];
2489        self.w_ebits[..ebands_stereo].fill(0);
2490        let ebits = &mut self.w_ebits[..ebands_stereo];
2491        let mut balance = 0;
2492
2493        // The anti-collapse bit reservation must be subtracted from the allocation
2494        // budget BEFORE compute_allocation (libopus celt_encoder.c: `total_bits -=
2495        // anti_collapse_rsv` precedes it) — the decoder reserves it there too.
2496        // Computing it only afterwards (as this code used to) let the encoder
2497        // allocate 1<<BITRES more than the decoder assumes on transient LM>=2
2498        // frames -> band budgets differ from band `start` -> range desync on
2499        // exactly those frames (caught by opus_demo -d's per-packet range check).
2500        // Same formula as the decoder for exact symmetry.
2501        let anti_collapse_rsv = if is_transient && lm >= 2 {
2502            let remaining = (total_bits << BITRES) - rc.tell_frac() - 1;
2503            if remaining >= ((lm as i32 + 2) << BITRES) {
2504                1i32 << BITRES
2505            } else {
2506                0
2507            }
2508        } else {
2509            0
2510        };
2511
2512        // signalBandwidth: end-1 by CHOICE (C uses the analysis bandwidth,
2513        // celt_encoder.c:2174, to let the allocator skip top bands — but that
2514        // narrowing loses ~0.7 ODG on music even with leak_boost live, and
2515        // libopus's own narrowed scores lose to our full-band ones). PEAQ-gated
2516        // out twice; do not re-enable without a corpus win.
2517        let signal_bandwidth = end_band as i32 - 1;
2518        let _ = equiv_rate;
2519
2520        self.last_coded_bands = clt_compute_allocation(
2521            mode,
2522            start_band,
2523            end_band,
2524            offsets,
2525            cap,
2526            alloc_trim,
2527            &mut intensity,
2528            &mut dual_stereo_val,
2529            (total_bits << BITRES) - rc.tell_frac() - 1 - anti_collapse_rsv,
2530            &mut balance,
2531            pulses,
2532            ebits,
2533            fine_priority,
2534            channels as i32,
2535            lm as i32,
2536            rc,
2537            true,
2538            0,
2539            signal_bandwidth,
2540        );
2541
2542        quant_fine_energy(
2543            mode,
2544            start_band,
2545            end_band,
2546            &mut self.old_band_e,
2547            error,
2548            ebits,
2549            rc,
2550            channels,
2551        );
2552
2553        self.w_collapse_masks[..nb_ebands * channels].fill(0);
2554        let collapse_masks = &mut self.w_collapse_masks[..nb_ebands * channels];
2555        let (x_split, y_split) = x.split_at_mut(frame_size);
2556        let y_opt = if channels == 2 { Some(y_split) } else { None };
2557
2558        let mut dual_stereo = dual_stereo_val != 0;
2559
2560        let theta_rdo = channels == 2 && !dual_stereo && self.complexity >= 8;
2561        let resynth = theta_rdo;
2562
2563        quant_all_bands(
2564            true,
2565            mode,
2566            start_band,
2567            end_band,
2568            x_split,
2569            y_opt,
2570            collapse_masks,
2571            band_e,
2572            pulses,
2573            short_blocks,
2574            self.spread_decision,
2575            &mut dual_stereo,
2576            intensity as usize,
2577            tf_res,
2578            (total_bits << BITRES) - anti_collapse_rsv,
2579            &mut balance,
2580            rc,
2581            lm as i32,
2582            self.last_coded_bands,
2583            resynth,
2584            false,
2585            &mut 0u32,
2586        );
2587
2588        if anti_collapse_rsv > 0 {
2589            let anti_collapse_on = if self.consec_transient < 2 {
2590                1u32
2591            } else {
2592                0u32
2593            };
2594            rc.enc_bits(anti_collapse_on, 1);
2595        }
2596
2597        quant_energy_finalise(
2598            mode,
2599            start_band,
2600            end_band,
2601            &mut self.old_band_e,
2602            error,
2603            ebits,
2604            fine_priority,
2605            total_bits - rc.tell(),
2606            rc,
2607            channels,
2608        );
2609
2610        if resynth {
2611            let _prof = crate::prof::scope(crate::prof::Stage::CeltSynth);
2612            let band_amp_synth = &mut self.w_band_amp_synth[..nb_ebands * channels];
2613            log2amp(mode, nb_ebands, band_amp_synth, &self.old_band_e, channels);
2614            self.w_freq_synth[..frame_size * channels].fill(0.0);
2615            let freq_synth = &mut self.w_freq_synth[..frame_size * channels];
2616            denormalise_bands(
2617                mode,
2618                x,
2619                freq_synth,
2620                band_amp_synth,
2621                start_band,
2622                end_band,
2623                channels,
2624                (1 << lm) as usize,
2625            );
2626            let (syn_shift, syn_b) = if is_transient {
2627                (mode.max_lm, 1 << lm)
2628            } else {
2629                (mode.max_lm - lm, 1)
2630            };
2631            let syn_n = frame_size / syn_b;
2632            let decode_buf_size = 2048;
2633
2634            for c in 0..channels {
2635                let co = c * syn_mem_size;
2636                self.enc_decode_mem
2637                    .copy_within(co + frame_size..co + decode_buf_size + overlap, co);
2638            }
2639
2640            for c in 0..channels {
2641                let co = c * syn_mem_size;
2642                let out_syn_idx = decode_buf_size - frame_size;
2643                for bi in 0..syn_b {
2644                    let syn_stride = if is_transient {
2645                        mode.short_mdct_size
2646                    } else {
2647                        syn_n
2648                    };
2649                    mode.mdct.backward(
2650                        &freq_synth[c * frame_size + bi..],
2651                        &mut self.enc_decode_mem[co + out_syn_idx + bi * syn_stride..],
2652                        mode.window,
2653                        overlap,
2654                        syn_shift,
2655                        syn_b,
2656                    );
2657                }
2658            }
2659        }
2660
2661        self.last_band_log_e.copy_from_slice(&self.old_band_e);
2662
2663        if !is_transient {
2664            self.old_band_e3.copy_from_slice(&self.old_band_e2);
2665            self.old_band_e2.copy_from_slice(&self.old_band_e);
2666        } else {
2667            for i in 0..channels * nb_ebands {
2668                self.old_band_e2[i] = self.old_band_e2[i].min(self.old_band_e[i]);
2669            }
2670        }
2671
2672        // "In case start or end were to change" (celt_encoder.c:2301): zero the
2673        // coarse-energy state outside [start, end) and floor the log history —
2674        // the decoder does the same every frame, and a later frame with a wider
2675        // end must predict those bands from the SAME (zeroed) base.
2676        for c in 0..channels {
2677            for i in 0..start_band {
2678                self.old_band_e[c * nb_ebands + i] = 0.0;
2679                self.old_band_e2[c * nb_ebands + i] = -28.0;
2680                self.old_band_e3[c * nb_ebands + i] = -28.0;
2681            }
2682            for i in end_band..nb_ebands {
2683                self.old_band_e[c * nb_ebands + i] = 0.0;
2684                self.old_band_e2[c * nb_ebands + i] = -28.0;
2685                self.old_band_e3[c * nb_ebands + i] = -28.0;
2686            }
2687        }
2688
2689        rc.pad_to_bits(total_bits);
2690
2691        if pf_on {
2692            self.prefilter_period = pitch_index;
2693            self.prefilter_gain = gain1;
2694        } else {
2695            self.prefilter_period = COMBFILTER_MINPERIOD;
2696            self.prefilter_gain = 0.0;
2697        }
2698        self.prefilter_tapset = prefilter_tapset;
2699
2700        if is_transient {
2701            self.consec_transient += 1;
2702        } else {
2703            self.consec_transient = 0;
2704        }
2705    }
2706}
2707
2708pub struct CeltDecoder {
2709    mode: &'static CeltMode,
2710    channels: usize,
2711    // Bitstream (coded) channels C; normally == channels (CC). A mono packet in a
2712    // stereo decoder sets this to 1 (C=1, CC=2) so the CELT inter-frame state stays
2713    // one continuous chain across mono<->stereo switches, matching libopus.
2714    stream_channels: usize,
2715    decode_mem: Vec<f32>,
2716    old_band_e: Vec<f32>,
2717    preemph_mem: Vec<f32>,
2718    prefilter_mem: Vec<f32>,
2719    prefilter_period: usize,
2720    prefilter_period_old: usize,
2721    prefilter_gain: f32,
2722    prefilter_gain_old: f32,
2723    prefilter_tapset: i32,
2724    prefilter_tapset_old: i32,
2725    old_band_e2: Vec<f32>,
2726    old_band_e3: Vec<f32>,
2727    rng: u32,
2728    /// Consecutive-loss counter for packet-loss concealment (celt_decode_lost).
2729    loss_count: u32,
2730    /// Pitch lag from the first lost frame, reused across a loss burst.
2731    last_pitch_index: i32,
2732    /// LPC coefficients (per channel, PLC_LPC_ORDER) computed at the first loss
2733    /// and reused for the rest of the burst (pitch-based PLC).
2734    plc_lpc: Vec<f32>,
2735
2736    w_tf_res: Vec<i32>,
2737    w_cap: Vec<i32>,
2738    w_offsets: Vec<i32>,
2739    w_pulses: Vec<i32>,
2740    w_ebits: Vec<i32>,
2741    w_fine_priority: Vec<i32>,
2742    w_x: Vec<f32>,
2743    w_collapse_masks: Vec<u32>,
2744    w_freq: Vec<f32>,
2745    w_band_amp: Vec<f32>,
2746    w_pcm_frame: Vec<f32>,
2747    w_post: Vec<f32>,
2748}
2749
2750impl CeltDecoder {
2751    pub fn new(mode: &'static CeltMode, channels: usize) -> Self {
2752        let overlap = mode.overlap;
2753        let nb_ebands = mode.nb_ebands;
2754        let nb_x_ch = nb_ebands * channels;
2755        let dec_frame_x_ch = DECODE_BUFFER_SIZE * channels;
2756        Self {
2757            mode,
2758            channels,
2759            stream_channels: channels,
2760            decode_mem: vec![0.0; channels * (DECODE_BUFFER_SIZE + overlap)],
2761            // libopus: oldBandE inits to 0 (OPUS_CLEAR); only oldLogE/oldLogE2 get
2762            // the -28 "very quiet" floor. Do NOT init old_band_e to -28 (it is the
2763            // coarse-energy prediction state; -28 makes the first frames too quiet).
2764            old_band_e: vec![0.0; nb_x_ch],
2765            preemph_mem: vec![0.0; channels],
2766            prefilter_mem: vec![0.0; channels * COMBFILTER_MAXPERIOD],
2767            prefilter_period: COMBFILTER_MINPERIOD,
2768            prefilter_period_old: COMBFILTER_MINPERIOD,
2769            prefilter_gain: 0.0,
2770            prefilter_gain_old: 0.0,
2771            prefilter_tapset: 0,
2772            prefilter_tapset_old: 0,
2773            // oldLogE / oldLogE2 in libopus: init -QCONST16(28,DB_SHIFT).
2774            old_band_e2: vec![-28.0; nb_x_ch],
2775            old_band_e3: vec![-28.0; nb_x_ch],
2776            rng: 0,
2777            loss_count: 0,
2778            last_pitch_index: 0,
2779            plc_lpc: vec![0.0; channels * PLC_LPC_ORDER],
2780
2781            w_tf_res: vec![0; nb_ebands],
2782            w_cap: vec![0; nb_ebands],
2783            w_offsets: vec![0; nb_ebands],
2784            w_pulses: vec![0; nb_ebands],
2785            w_ebits: vec![0; nb_x_ch],
2786            w_fine_priority: vec![0; nb_x_ch],
2787
2788            w_x: vec![0.0; dec_frame_x_ch + STRIDE_ACCESS_PAD],
2789            w_collapse_masks: vec![0; nb_x_ch],
2790            w_freq: vec![0.0; dec_frame_x_ch + 4], // +4: NEON backward pre-rotation reads up to 3 elements past n2
2791            w_band_amp: vec![0.0; nb_x_ch],
2792            w_pcm_frame: vec![0.0; DECODE_BUFFER_SIZE],
2793            w_post: vec![0.0; DECODE_BUFFER_SIZE + COMBFILTER_MAXPERIOD],
2794        }
2795    }
2796
2797    /// Seed this decoder's inter-frame state from another decoder (typically the
2798    /// auxiliary mono decoder), replicating its channel 0 into every channel of
2799    /// self. Used at a mono->stereo switch so the primary stereo CeltDecoder's
2800    /// overlap/energy/prefilter state is continuous with the preceding mono
2801    /// packets (which libopus keeps in one continuous decoder) — without this the
2802    /// first stereo frame's MDCT overlap-add starts from silence.
2803    pub fn seed_from(&mut self, src: &CeltDecoder) {
2804        let overlap = self.mode.overlap;
2805        let nb = self.mode.nb_ebands;
2806        let per_dm = DECODE_BUFFER_SIZE + overlap;
2807        let src_ch = src.channels.max(1);
2808        for c in 0..self.channels {
2809            let sc = c.min(src_ch - 1);
2810            self.decode_mem[c * per_dm..(c + 1) * per_dm]
2811                .copy_from_slice(&src.decode_mem[sc * per_dm..(sc + 1) * per_dm]);
2812            self.old_band_e[c * nb..(c + 1) * nb]
2813                .copy_from_slice(&src.old_band_e[sc * nb..(sc + 1) * nb]);
2814            self.old_band_e2[c * nb..(c + 1) * nb]
2815                .copy_from_slice(&src.old_band_e2[sc * nb..(sc + 1) * nb]);
2816            self.old_band_e3[c * nb..(c + 1) * nb]
2817                .copy_from_slice(&src.old_band_e3[sc * nb..(sc + 1) * nb]);
2818            self.preemph_mem[c] = src.preemph_mem[sc];
2819            self.prefilter_mem[c * COMBFILTER_MAXPERIOD..(c + 1) * COMBFILTER_MAXPERIOD]
2820                .copy_from_slice(
2821                    &src.prefilter_mem[sc * COMBFILTER_MAXPERIOD..(sc + 1) * COMBFILTER_MAXPERIOD],
2822                );
2823        }
2824        self.prefilter_period = src.prefilter_period;
2825        self.prefilter_period_old = src.prefilter_period_old;
2826        self.prefilter_gain = src.prefilter_gain;
2827        self.prefilter_gain_old = src.prefilter_gain_old;
2828        self.prefilter_tapset = src.prefilter_tapset;
2829        self.prefilter_tapset_old = src.prefilter_tapset_old;
2830        self.rng = src.rng;
2831    }
2832
2833    /// Channels coded in the next packet's bitstream (1 for a mono packet decoded
2834    /// by a stereo decoder — keeps 2-channel state continuous across switches).
2835    pub fn set_stream_channels(&mut self, sc: usize) {
2836        self.stream_channels = sc.clamp(1, self.channels);
2837    }
2838
2839    /// libopus OPUS_RESET_STATE for the decoder: clear everything from rng onward,
2840    /// then oldLogE/oldLogE2 = -28 (oldBandE stays 0).
2841    pub fn reset(&mut self) {
2842        self.decode_mem.fill(0.0);
2843        self.old_band_e.fill(0.0);
2844        self.old_band_e2.fill(-28.0);
2845        self.old_band_e3.fill(-28.0);
2846        self.preemph_mem.fill(0.0);
2847        self.prefilter_mem.fill(0.0);
2848        self.prefilter_period = COMBFILTER_MINPERIOD;
2849        self.prefilter_period_old = COMBFILTER_MINPERIOD;
2850        self.prefilter_gain = 0.0;
2851        self.prefilter_gain_old = 0.0;
2852        self.prefilter_tapset = 0;
2853        self.prefilter_tapset_old = 0;
2854        self.rng = 0;
2855    }
2856
2857    pub fn decode(&mut self, compressed: &[u8], frame_size: usize, pcm: &mut [f32]) -> usize {
2858        self.decode_impl(compressed, frame_size, pcm, 0, self.mode.nb_ebands)
2859    }
2860
2861    pub fn decode_with_start_band(
2862        &mut self,
2863        compressed: &[u8],
2864        frame_size: usize,
2865        pcm: &mut [f32],
2866        start_band: usize,
2867    ) -> usize {
2868        self.decode_impl(compressed, frame_size, pcm, start_band, self.mode.nb_ebands)
2869    }
2870
2871    pub fn decode_from_range_coder(
2872        &mut self,
2873        rc: &mut RangeCoder,
2874        total_bits: i32,
2875        frame_size: usize,
2876        pcm: &mut [f32],
2877        start_band: usize,
2878    ) -> usize {
2879        self.decode_impl_from_rc(
2880            rc,
2881            total_bits,
2882            frame_size,
2883            pcm,
2884            start_band,
2885            self.mode.nb_ebands,
2886        )
2887    }
2888
2889    pub fn decode_from_range_coder_with_band_range(
2890        &mut self,
2891        rc: &mut RangeCoder,
2892        total_bits: i32,
2893        frame_size: usize,
2894        pcm: &mut [f32],
2895        start_band: usize,
2896        end_band: usize,
2897    ) -> usize {
2898        self.decode_impl_from_rc(rc, total_bits, frame_size, pcm, start_band, end_band)
2899    }
2900
2901    fn decode_impl(
2902        &mut self,
2903        compressed: &[u8],
2904        frame_size: usize,
2905        pcm: &mut [f32],
2906        start_band: usize,
2907        end_band: usize,
2908    ) -> usize {
2909        let total_bits = (compressed.len() * 8) as i32;
2910        let mut rc = RangeCoder::new_decoder(compressed);
2911        self.decode_impl_from_rc(&mut rc, total_bits, frame_size, pcm, start_band, end_band)
2912    }
2913
2914    fn decode_impl_from_rc(
2915        &mut self,
2916        rc: &mut RangeCoder,
2917        total_bits: i32,
2918        frame_size: usize,
2919        pcm: &mut [f32],
2920        start_band: usize,
2921        end_band: usize,
2922    ) -> usize {
2923        let mode = self.mode;
2924        // CC = state/output channels; C (=`channels`) = channels coded in the
2925        // bitstream. Mono packet in a stereo decoder: C=1, CC=2 — energy/allocation/
2926        // bands/denormalise all use C; synthesis writes CC output channels reading
2927        // the single decoded channel.
2928        let cc = self.channels;
2929        let channels = self.stream_channels.clamp(1, cc);
2930        let nb_ebands = mode.nb_ebands;
2931        let end_band = end_band.min(nb_ebands).max(start_band);
2932        let overlap = mode.overlap;
2933
2934        let mut lm = 0;
2935        while (mode.short_mdct_size << lm) != frame_size {
2936            lm += 1;
2937            if lm > mode.max_lm {
2938                break;
2939            }
2940        }
2941        if (mode.short_mdct_size << lm) != frame_size {
2942            lm = 0;
2943        }
2944
2945        // libopus celt_decoder.c:953: `if (C==1) oldBandE[i]=MAX(oldBandE[i],
2946        // oldBandE[nbEBands+i])` before the coarse-energy decode — a mono packet in
2947        // a stereo decoder predicts its single channel from the MAX of both
2948        // channels' previous energy. (Only meaningful on the first mono frame after
2949        // stereo; after every mono frame ch0 is replicated to ch1 at frame end.)
2950        if channels == 1 && cc == 2 {
2951            for i in 0..nb_ebands {
2952                self.old_band_e[i] = self.old_band_e[i].max(self.old_band_e[nb_ebands + i]);
2953            }
2954        }
2955
2956        let tell = rc.tell();
2957        let mut silence = false;
2958        if tell >= total_bits {
2959            silence = true;
2960        } else if tell == 1 {
2961            silence = rc.decode_bit_logp(15);
2962        }
2963        if silence {
2964            // libopus: "Pretend we've read all the remaining bits" — every
2965            // downstream budget check then skips its entropy reads naturally, the
2966            // whole pipeline still runs (decode_mem shift, overlap fade-out via a
2967            // zeroed spectrum, postfilter/deemph, frame-end energy bookkeeping).
2968            // The old early-return left the decoder state one frame stale and the
2969            // energy prediction hot -> the next loud frame decoded ~2^15 too loud
2970            // and railed the output.
2971            rc.nbits_total += total_bits - rc.tell();
2972        }
2973
2974        let mut pf_on = false;
2975        let mut pitch_index = COMBFILTER_MINPERIOD;
2976        let mut gain1 = 0.0f32;
2977        let mut prefilter_tapset = 0;
2978
2979        if start_band == 0 && !silence && rc.tell() + 16 <= total_bits {
2980            pf_on = rc.decode_bit_logp(1);
2981            if pf_on {
2982                let octave = rc.dec_uint(6);
2983                pitch_index = ((16 << octave) + rc.dec_bits(4 + octave)) as usize - 1;
2984                let qg = rc.dec_bits(3);
2985                if rc.tell() + 2 <= total_bits {
2986                    prefilter_tapset = rc.decode_icdf(&TAPSET_ICDF, 2) as usize;
2987                }
2988                gain1 = 0.09375 * (qg as f32 + 1.0);
2989            }
2990        }
2991        if start_band != 0 {
2992            self.prefilter_gain = 0.0;
2993        }
2994
2995        let mut is_transient = false;
2996        if lm > 0 && rc.tell() + 3 <= total_bits {
2997            is_transient = rc.decode_bit_logp(3);
2998        }
2999        let short_blocks = is_transient;
3000
3001        let intra_ener = if rc.tell() + 3 <= total_bits {
3002            rc.decode_bit_logp(3)
3003        } else {
3004            false
3005        };
3006
3007        unquant_coarse_energy(
3008            mode,
3009            start_band,
3010            end_band,
3011            &mut self.old_band_e,
3012            intra_ener,
3013            rc,
3014            channels,
3015            lm,
3016        );
3017        self.w_tf_res[..nb_ebands].fill(0);
3018        let tf_res = &mut self.w_tf_res[..nb_ebands];
3019        tf_decode(start_band, end_band, is_transient, tf_res, lm as i32, rc);
3020
3021        let spread_decision = if rc.tell() + 4 <= total_bits {
3022            rc.decode_icdf(&SPREAD_ICDF, 5)
3023        } else {
3024            SPREAD_NORMAL
3025        };
3026
3027        self.w_cap[..nb_ebands].fill(0);
3028        let cap = &mut self.w_cap[..nb_ebands];
3029        for (i, cap_i) in cap.iter_mut().enumerate() {
3030            let n = (mode.e_bands[i + 1] - mode.e_bands[i]) << lm;
3031            *cap_i = ((mode.cache.caps[nb_ebands * (2 * lm + channels - 1) + i] as i32 + 64)
3032                * channels as i32
3033                * n as i32)
3034                >> 2;
3035        }
3036
3037        self.w_offsets[..nb_ebands].fill(0);
3038        let offsets = &mut self.w_offsets[..nb_ebands];
3039        let mut dynalloc_logp = 6i32;
3040        let mut total_bits_bitres = total_bits << BITRES;
3041        let mut tell_frac = rc.tell_frac();
3042        for i in start_band..end_band {
3043            let width =
3044                channels as i32 * (mode.e_bands[i + 1] - mode.e_bands[i]) as i32 * (1 << lm);
3045            let quanta = (width << BITRES).min((6i32 << BITRES).max(width));
3046            let mut dynalloc_loop_logp = dynalloc_logp;
3047            let mut boost = 0i32;
3048            while tell_frac + (dynalloc_loop_logp << BITRES) < total_bits_bitres && boost < cap[i] {
3049                let flag = rc.decode_bit_logp(dynalloc_loop_logp as u32);
3050                tell_frac = rc.tell_frac();
3051                if !flag {
3052                    break;
3053                }
3054                boost += quanta;
3055                total_bits_bitres -= quanta;
3056                dynalloc_loop_logp = 1;
3057            }
3058            offsets[i] = boost;
3059            if boost > 0 {
3060                dynalloc_logp = dynalloc_logp.max(2) - 1;
3061                dynalloc_logp = dynalloc_logp.max(2);
3062            }
3063        }
3064
3065        let alloc_trim = if rc.tell_frac() + (6 << BITRES) <= total_bits_bitres {
3066            rc.decode_icdf(&TRIM_ICDF, 7)
3067        } else {
3068            5
3069        };
3070        let anti_collapse_rsv = if is_transient && lm >= 2 {
3071            let remaining = (total_bits << BITRES) - rc.tell_frac() - 1;
3072            if remaining >= ((lm as i32 + 2) << BITRES) {
3073                1i32 << BITRES
3074            } else {
3075                0
3076            }
3077        } else {
3078            0
3079        };
3080
3081        let mut intensity = 0;
3082        let mut dual_stereo_val = if channels == 2 { 1 } else { 0 };
3083        let mut balance = 0;
3084        self.w_pulses[..nb_ebands].fill(0);
3085        let pulses = &mut self.w_pulses[..nb_ebands];
3086
3087        let ebands_stereo = if channels > 1 {
3088            nb_ebands * channels
3089        } else {
3090            nb_ebands
3091        };
3092        self.w_fine_priority[..ebands_stereo].fill(0);
3093        let fine_priority = &mut self.w_fine_priority[..ebands_stereo];
3094        self.w_ebits[..ebands_stereo].fill(0);
3095        let ebits = &mut self.w_ebits[..ebands_stereo];
3096
3097        let alloc_bits = (total_bits << BITRES) - rc.tell_frac() - 1 - anti_collapse_rsv;
3098        let coded_bands = clt_compute_allocation(
3099            mode,
3100            start_band,
3101            end_band,
3102            offsets,
3103            cap,
3104            alloc_trim,
3105            &mut intensity,
3106            &mut dual_stereo_val,
3107            alloc_bits,
3108            &mut balance,
3109            pulses,
3110            ebits,
3111            fine_priority,
3112            channels as i32,
3113            lm as i32,
3114            rc,
3115            false,
3116            0,
3117            end_band as i32 - 1,
3118        );
3119
3120        unquant_fine_energy(
3121            mode,
3122            start_band,
3123            end_band,
3124            &mut self.old_band_e,
3125            ebits,
3126            rc,
3127            channels,
3128        );
3129
3130        if frame_size > DECODE_BUFFER_SIZE + overlap {
3131            return 0;
3132        }
3133
3134        self.w_x[..frame_size * channels].fill(0.0);
3135
3136        let x_pad_end = (frame_size * channels + STRIDE_ACCESS_PAD).min(self.w_x.len());
3137        let x = &mut self.w_x[..x_pad_end];
3138        self.w_collapse_masks[..nb_ebands * channels].fill(0);
3139        let collapse_masks = &mut self.w_collapse_masks[..nb_ebands * channels];
3140
3141        let (x_split, y_split) = x.split_at_mut(frame_size);
3142        let y_opt = if channels == 2 { Some(y_split) } else { None };
3143
3144        let mut dual_stereo = dual_stereo_val != 0;
3145        self.w_band_amp[..nb_ebands * channels].fill(0.0);
3146        let band_amp = &mut self.w_band_amp[..nb_ebands * channels];
3147        log2amp(mode, nb_ebands, band_amp, &self.old_band_e, channels);
3148        quant_all_bands(
3149            false,
3150            mode,
3151            start_band,
3152            end_band,
3153            x_split,
3154            y_opt,
3155            collapse_masks,
3156            band_amp,
3157            pulses,
3158            short_blocks,
3159            spread_decision,
3160            &mut dual_stereo,
3161            intensity as usize,
3162            tf_res,
3163            (total_bits << BITRES) - anti_collapse_rsv,
3164            &mut balance,
3165            rc,
3166            lm as i32,
3167            coded_bands,
3168            true,
3169            false,
3170            &mut self.rng,
3171        );
3172        // Trace X values for comparison with C decoder
3173        let mut anti_collapse_on = false;
3174        if anti_collapse_rsv > 0 {
3175            anti_collapse_on = rc.dec_bits(1) != 0;
3176        }
3177
3178        unquant_energy_finalise(
3179            mode,
3180            start_band,
3181            end_band,
3182            &mut self.old_band_e,
3183            ebits,
3184            fine_priority,
3185            total_bits - rc.tell(),
3186            rc,
3187            channels,
3188        );
3189        if anti_collapse_on {
3190            // libopus passes `end`, not nbEBands: for narrower bandwidths (e.g.
3191            // SWB end=19) anti-collapsing the uncoded bands would burn PRNG draws
3192            // and desync the noise-fill seed for every subsequent frame.
3193            self.rng = crate::bands::anti_collapse(
3194                mode,
3195                x,
3196                collapse_masks,
3197                lm as i32,
3198                channels,
3199                frame_size,
3200                start_band,
3201                end_band,
3202                &self.old_band_e,
3203                &self.old_band_e2,
3204                &self.old_band_e3,
3205                pulses,
3206                self.rng,
3207            );
3208        }
3209
3210        // libopus celt_decoder.c:1107: silence floors the coded channels' energy to
3211        // -28 (so the next frame's inter prediction starts from "very quiet") and
3212        // renders a zero spectrum — the frame's output is just the MDCT overlap
3213        // fade-out of the previous frame.
3214        if silence {
3215            for i in 0..channels * nb_ebands {
3216                self.old_band_e[i] = -28.0;
3217            }
3218        }
3219
3220        // Recompute band_amp after unquant_energy_finalise, which adjusts old_band_e.
3221        // (Mirrors the encoder's resynth path: log2amp is called after quant_energy_finalise.)
3222        log2amp(mode, nb_ebands, band_amp, &self.old_band_e, channels);
3223        self.w_freq[..frame_size * channels].fill(0.0);
3224        let freq = &mut self.w_freq[..frame_size * channels];
3225        if !silence {
3226            denormalise_bands(
3227                mode,
3228                x,
3229                freq,
3230                band_amp,
3231                start_band,
3232                end_band,
3233                channels,
3234                (1 << lm) as usize,
3235            );
3236        }
3237        // Always trace freq and band_amp for comparison
3238
3239        let (shift, b) = if short_blocks {
3240            (mode.max_lm, 1 << lm)
3241        } else {
3242            (mode.max_lm - lm, 1)
3243        };
3244        let n = frame_size / b;
3245
3246        for c in 0..cc {
3247            // A mono packet (C=1) in a stereo decoder (CC=2) renders its single
3248            // decoded channel into both outputs: re-run the iMDCT reading channel
3249            // 0's freq (fc clamps to C-1). Re-synthesis (not a decode_mem copy) is
3250            // required so the per-channel postfilter/deemph below run exactly once
3251            // each; denormalise_bands leaves freq unmodified so this is exact.
3252            let fc = c.min(channels - 1);
3253            let channel_mem_offset = c * (DECODE_BUFFER_SIZE + overlap);
3254
3255            let mem_size = DECODE_BUFFER_SIZE + overlap;
3256            self.decode_mem.copy_within(
3257                channel_mem_offset + frame_size..channel_mem_offset + mem_size,
3258                channel_mem_offset,
3259            );
3260
3261            let out_syn_idx = DECODE_BUFFER_SIZE - frame_size;
3262
3263            for i in 0..b {
3264                let block_freq_idx = fc * frame_size + i;
3265                // Stride between short-block MDCT outputs is short_mdct_size (not n).
3266                // In libopus: out_syn[c] + NB*b, where NB = mode->shortMdctSize.
3267                // For non-transient b=1, i*n == 0 either way.
3268                let block_stride = if short_blocks {
3269                    mode.short_mdct_size
3270                } else {
3271                    n
3272                };
3273                let block_out_idx = channel_mem_offset + out_syn_idx + i * block_stride;
3274                let available_len = self.decode_mem.len() - block_out_idx;
3275                if available_len < n + overlap {
3276                    panic!(
3277                        "MDCT backward buffer too small: need {}, have {} (out_syn_idx={}, n={}, overlap={})",
3278                        n + overlap,
3279                        available_len,
3280                        out_syn_idx,
3281                        n,
3282                        overlap
3283                    );
3284                }
3285                self.mode.mdct.backward(
3286                    &freq[block_freq_idx..],
3287                    &mut self.decode_mem[block_out_idx..],
3288                    mode.window,
3289                    overlap,
3290                    shift,
3291                    b,
3292                );
3293            }
3294
3295            const SIG_SAT: f32 = 536870911.0;
3296            for i in 0..frame_size {
3297                let v = &mut self.decode_mem[channel_mem_offset + out_syn_idx + i];
3298                *v = v.clamp(-SIG_SAT, SIG_SAT);
3299            }
3300
3301            self.w_pcm_frame[..frame_size].fill(0.0);
3302            let pcm_frame = &mut self.w_pcm_frame[..frame_size];
3303
3304            pcm_frame.copy_from_slice(
3305                &self.decode_mem[channel_mem_offset + out_syn_idx
3306                    ..channel_mem_offset + out_syn_idx + frame_size],
3307            );
3308            if pf_on || self.prefilter_gain > 0.0 || self.prefilter_gain_old > 0.0 {
3309                // Set up w_post = [prefilter_mem | pcm_frame] for history access.
3310                // We apply combfilter in-place on w_post[COMBFILTER_MAXPERIOD..] so that
3311                // later samples can reference already-filtered earlier samples, matching C's
3312                // in-place comb_filter behavior.
3313                self.w_post[..COMBFILTER_MAXPERIOD].copy_from_slice(
3314                    &self.prefilter_mem[c * COMBFILTER_MAXPERIOD..(c + 1) * COMBFILTER_MAXPERIOD],
3315                );
3316                self.w_post[COMBFILTER_MAXPERIOD..COMBFILTER_MAXPERIOD + frame_size]
3317                    .copy_from_slice(pcm_frame);
3318
3319                let short_n = mode.short_mdct_size;
3320                // Call 1: first short_n samples, transition old→current params
3321                // Apply in-place on w_post[COMBFILTER_MAXPERIOD..], output overwrites input
3322                comb_filter_inplace(
3323                    &mut self.w_post,
3324                    COMBFILTER_MAXPERIOD,
3325                    self.prefilter_period_old,
3326                    self.prefilter_period,
3327                    short_n,
3328                    self.prefilter_gain_old,
3329                    self.prefilter_gain,
3330                    self.prefilter_tapset_old,
3331                    self.prefilter_tapset,
3332                    mode.window,
3333                    overlap,
3334                );
3335                if lm != 0 {
3336                    // Call 2: remaining N-short_n samples, transition current→new params
3337                    comb_filter_inplace(
3338                        &mut self.w_post,
3339                        COMBFILTER_MAXPERIOD + short_n,
3340                        self.prefilter_period,
3341                        pitch_index,
3342                        frame_size - short_n,
3343                        self.prefilter_gain,
3344                        gain1,
3345                        self.prefilter_tapset,
3346                        prefilter_tapset as i32,
3347                        mode.window,
3348                        overlap,
3349                    );
3350                }
3351
3352                pcm_frame.copy_from_slice(
3353                    &self.w_post[COMBFILTER_MAXPERIOD..COMBFILTER_MAXPERIOD + frame_size],
3354                );
3355
3356                self.decode_mem[channel_mem_offset + out_syn_idx
3357                    ..channel_mem_offset + out_syn_idx + frame_size]
3358                    .copy_from_slice(pcm_frame);
3359            }
3360            let mut new_mem = [0.0f32; COMBFILTER_MAXPERIOD];
3361            if frame_size >= COMBFILTER_MAXPERIOD {
3362                new_mem.copy_from_slice(&pcm_frame[frame_size - COMBFILTER_MAXPERIOD..frame_size]);
3363            } else {
3364                new_mem[..COMBFILTER_MAXPERIOD - frame_size].copy_from_slice(
3365                    &self.prefilter_mem
3366                        [c * COMBFILTER_MAXPERIOD + frame_size..(c + 1) * COMBFILTER_MAXPERIOD],
3367                );
3368                new_mem[COMBFILTER_MAXPERIOD - frame_size..].copy_from_slice(pcm_frame);
3369            }
3370            self.prefilter_mem[c * COMBFILTER_MAXPERIOD..(c + 1) * COMBFILTER_MAXPERIOD]
3371                .copy_from_slice(&new_mem);
3372
3373            let coef = mode.preemph[0];
3374            let mut m = self.preemph_mem[c];
3375            const VERY_SMALL: f32 = 1e-30f32;
3376            for i in 0..frame_size {
3377                let x = pcm_frame[i];
3378                let val = (x + VERY_SMALL + m).clamp(-SIG_SAT, SIG_SAT);
3379                pcm[c * frame_size + i] = val * (1.0 / 32768.0);
3380                m = val * coef;
3381            }
3382            self.preemph_mem[c] = m;
3383        }
3384
3385        self.prefilter_period_old = self.prefilter_period;
3386        self.prefilter_gain_old = self.prefilter_gain;
3387        self.prefilter_tapset_old = self.prefilter_tapset;
3388
3389        if pf_on {
3390            self.prefilter_period = pitch_index;
3391            self.prefilter_gain = gain1;
3392            self.prefilter_tapset = prefilter_tapset as i32;
3393        } else {
3394            self.prefilter_period = COMBFILTER_MINPERIOD;
3395            self.prefilter_gain = 0.0;
3396            self.prefilter_tapset = 0;
3397        }
3398
3399        if lm > 0 {
3400            self.prefilter_period_old = self.prefilter_period;
3401            self.prefilter_gain_old = self.prefilter_gain;
3402            self.prefilter_tapset_old = self.prefilter_tapset;
3403        }
3404
3405        // libopus celt_decoder.c:1140: after a mono frame in a stereo decoder,
3406        // replicate channel 0's coarse energy to channel 1 — this keeps ch1's
3407        // prediction state current through mono runs (and is what makes the
3408        // pre-decode MAX-merge a first-frame-only event).
3409        if channels == 1 && cc == 2 {
3410            let (ch0, ch1) = self.old_band_e.split_at_mut(nb_ebands);
3411            ch1[..nb_ebands].copy_from_slice(&ch0[..nb_ebands]);
3412        }
3413
3414        // oldLogE/oldLogE2 updates run over ALL state channels (2*nbEBands in
3415        // libopus), not just the coded ones.
3416        if !is_transient {
3417            self.old_band_e3.copy_from_slice(&self.old_band_e2);
3418            self.old_band_e2.copy_from_slice(&self.old_band_e);
3419        } else {
3420            for i in 0..cc * nb_ebands {
3421                self.old_band_e2[i] = self.old_band_e2[i].min(self.old_band_e[i]);
3422            }
3423        }
3424
3425        // "In case start or end were to change" (celt_decoder.c:1162-1174): zero
3426        // the coarse energy outside [start, end) and floor the log history, for
3427        // BOTH state channels. Matters for hybrid (start=17) and narrower
3428        // bandwidths (end<21) mixing with full-band frames in one stream.
3429        for c in 0..cc {
3430            for i in 0..start_band {
3431                self.old_band_e[c * nb_ebands + i] = 0.0;
3432                self.old_band_e2[c * nb_ebands + i] = -28.0;
3433                self.old_band_e3[c * nb_ebands + i] = -28.0;
3434            }
3435            for i in end_band..nb_ebands {
3436                self.old_band_e[c * nb_ebands + i] = 0.0;
3437                self.old_band_e2[c * nb_ebands + i] = -28.0;
3438                self.old_band_e3[c * nb_ebands + i] = -28.0;
3439            }
3440        }
3441
3442        self.rng = rc.rng;
3443        self.loss_count = 0;
3444
3445        frame_size
3446    }
3447
3448    /// Packet-loss concealment for a lost CELT frame — a port of libopus
3449    /// `celt_decode_lost` (celt_decoder.c). For the first few losses of a burst
3450    /// it uses the pitch-based branch (LPC-whitened excitation extrapolated at
3451    /// the last pitch period, resynthesized through the LPC filter — good for
3452    /// tonal/music content); once the burst runs long (`loss_count >= 5`) it
3453    /// falls back to the noise-based branch (spectrally-shaped, energy-decayed
3454    /// random excitation). Both fill the decode buffer, then this deemphasises
3455    /// to `pcm` (interleaved, /32768). Real attenuating audio instead of silence.
3456    pub fn conceal_lost(&mut self, frame_size: usize, pcm: &mut [f32]) {
3457        let n = frame_size;
3458        // start==0 for CELT-only; noise-based only once the burst is long.
3459        if self.loss_count >= 5 {
3460            self.conceal_fill_noise(n);
3461        } else {
3462            self.conceal_fill_pitch(n);
3463        }
3464
3465        // Deemphasise the concealed frame (decode_mem out_syn) to interleaved pcm.
3466        let mode = self.mode;
3467        let c = self.channels;
3468        let overlap = mode.overlap;
3469        let mem_size = DECODE_BUFFER_SIZE + overlap;
3470        let out_syn_idx = DECODE_BUFFER_SIZE - n;
3471        const SIG_SAT: f32 = 536870911.0;
3472        const VERY_SMALL: f32 = 1e-30f32;
3473        let coef = mode.preemph[0];
3474        for ch in 0..c {
3475            let out = ch * mem_size + out_syn_idx;
3476            let mut m = self.preemph_mem[ch];
3477            for i in 0..n {
3478                let x = self.decode_mem[out + i];
3479                let val = (x + VERY_SMALL + m).clamp(-SIG_SAT, SIG_SAT);
3480                pcm[i * c + ch] = val * (1.0 / 32768.0);
3481                m = val * coef;
3482            }
3483            self.preemph_mem[ch] = m;
3484        }
3485
3486        self.prefilter_period_old = self.prefilter_period;
3487        self.prefilter_gain_old = self.prefilter_gain;
3488        self.prefilter_period = COMBFILTER_MINPERIOD;
3489        self.prefilter_gain = 0.0;
3490        self.loss_count += 1;
3491    }
3492
3493    /// Noise-based concealment branch (celt_decode_lost, `noise_based`): fill the
3494    /// decode buffer's out_syn region with an energy-decayed random spectrum.
3495    fn conceal_fill_noise(&mut self, n: usize) {
3496        let mode = self.mode;
3497        let nb_ebands = mode.nb_ebands;
3498        let overlap = mode.overlap;
3499        let c = self.channels;
3500        let start = 0usize;
3501        let end = nb_ebands;
3502        let eff_end = end.min(mode.eff_ebands);
3503        let mem_size = DECODE_BUFFER_SIZE + overlap;
3504
3505        let mut lm = 0usize;
3506        while (mode.short_mdct_size << lm) != n && lm < mode.max_lm {
3507            lm += 1;
3508        }
3509
3510        let decay = if self.loss_count == 0 { 1.5f32 } else { 0.5f32 };
3511        for ch in 0..c {
3512            for i in start..end {
3513                let e = &mut self.old_band_e[ch * nb_ebands + i];
3514                *e = (*e - decay).max(-28.0);
3515            }
3516        }
3517
3518        let mut seed = self.rng;
3519        self.w_x[..n * c].fill(0.0);
3520        for ch in 0..c {
3521            for i in start..eff_end {
3522                let boffs = n * ch + ((mode.e_bands[i] as usize) << lm);
3523                let blen = ((mode.e_bands[i + 1] - mode.e_bands[i]) as usize) << lm;
3524                for j in 0..blen {
3525                    seed = crate::bands::celt_lcg_rand(seed);
3526                    self.w_x[boffs + j] = ((seed as i32) >> 20) as f32;
3527                }
3528                crate::bands::renormalise_vector(&mut self.w_x[boffs..boffs + blen], blen, 1.0);
3529            }
3530        }
3531        self.rng = seed;
3532
3533        for ch in 0..c {
3534            let base = ch * mem_size;
3535            self.decode_mem
3536                .copy_within(base + n..base + DECODE_BUFFER_SIZE + overlap / 2, base);
3537        }
3538
3539        self.w_band_amp[..nb_ebands * c].fill(0.0);
3540        let band_amp = &mut self.w_band_amp[..nb_ebands * c];
3541        log2amp(mode, nb_ebands, band_amp, &self.old_band_e, c);
3542        self.w_freq[..n * c].fill(0.0);
3543        let freq = &mut self.w_freq[..n * c];
3544        denormalise_bands(mode, &self.w_x, freq, band_amp, start, end, c, 1usize << lm);
3545
3546        let shift = mode.max_lm - lm;
3547        let out_syn_idx = DECODE_BUFFER_SIZE - n;
3548        const SIG_SAT: f32 = 536870911.0;
3549        for ch in 0..c {
3550            let out = ch * mem_size + out_syn_idx;
3551            self.mode.mdct.backward(
3552                &freq[ch * n..],
3553                &mut self.decode_mem[out..],
3554                mode.window,
3555                overlap,
3556                shift,
3557                1,
3558            );
3559            for i in 0..n {
3560                let v = &mut self.decode_mem[out + i];
3561                *v = v.clamp(-SIG_SAT, SIG_SAT);
3562            }
3563        }
3564    }
3565
3566    /// Pitch-based concealment branch (celt_decode_lost, pitch-based): extrapolate
3567    /// the LPC-whitened excitation at the last pitch period with per-period decay,
3568    /// resynthesize through the LPC filter, then TDAC-fold the overlap.
3569    fn conceal_fill_pitch(&mut self, n: usize) {
3570        let mode = self.mode;
3571        let overlap = mode.overlap;
3572        let c = self.channels;
3573        let mem_size = DECODE_BUFFER_SIZE + overlap;
3574        const MAX_PERIOD: usize = COMBFILTER_MAXPERIOD;
3575        let ord = PLC_LPC_ORDER;
3576        let out_syn_idx = DECODE_BUFFER_SIZE - n;
3577        const SIG_SAT: f32 = 536870911.0;
3578        let window = mode.window;
3579
3580        // Pitch lag: search on the first loss, reuse across the burst.
3581        let mut fade = 1.0f32;
3582        if self.loss_count == 0 {
3583            let mut lp = vec![0.0f32; DECODE_BUFFER_SIZE >> 1];
3584            let slices: Vec<&[f32]> = (0..c)
3585                .map(|ch| &self.decode_mem[ch * mem_size..ch * mem_size + DECODE_BUFFER_SIZE])
3586                .collect();
3587            crate::pitch::pitch_downsample(&slices, &mut lp, DECODE_BUFFER_SIZE >> 1, c, 2);
3588            let pr = crate::pitch::pitch_search(
3589                &lp[PLC_PITCH_LAG_MAX >> 1..],
3590                &lp,
3591                DECODE_BUFFER_SIZE - PLC_PITCH_LAG_MAX,
3592                PLC_PITCH_LAG_MAX - PLC_PITCH_LAG_MIN,
3593            );
3594            self.last_pitch_index = (PLC_PITCH_LAG_MAX - pr) as i32;
3595        } else {
3596            fade = 0.8;
3597        }
3598        let pitch_index = (self.last_pitch_index.max(1) as usize).min(MAX_PERIOD - 1);
3599        let exc_length = (2 * pitch_index).min(MAX_PERIOD);
3600
3601        let mut etmp = vec![0.0f32; overlap];
3602        for ch in 0..c {
3603            let base = ch * mem_size;
3604            // exc[k] = exc_buf[ord + k] for k in -ord..MAX_PERIOD.
3605            let mut exc_buf = vec![0.0f32; MAX_PERIOD + ord];
3606            for (i, v) in exc_buf.iter_mut().enumerate() {
3607                *v = self.decode_mem[base + DECODE_BUFFER_SIZE - MAX_PERIOD - ord + i];
3608            }
3609            if self.loss_count == 0 {
3610                let mut ac = vec![0.0f32; ord + 1];
3611                crate::celt_lpc::autocorr(
3612                    &exc_buf[ord..ord + MAX_PERIOD],
3613                    &mut ac,
3614                    Some(window),
3615                    overlap,
3616                    ord,
3617                    MAX_PERIOD,
3618                );
3619                ac[0] *= 1.0001; // -40 dB noise floor
3620                for i in 1..=ord {
3621                    ac[i] -= ac[i] * (0.008 * 0.008) * (i * i) as f32; // lag windowing
3622                }
3623                let mut lc = vec![0.0f32; ord];
3624                crate::celt_lpc::lpc(&mut lc, &ac, ord);
3625                self.plc_lpc[ch * ord..ch * ord + ord].copy_from_slice(&lc);
3626            }
3627            let lc: Vec<f32> = self.plc_lpc[ch * ord..ch * ord + ord].to_vec();
3628
3629            // Whiten the last exc_length excitation samples (celt_fir with history
3630            // — pass the ord preceding samples and read outputs at [ord..]).
3631            {
3632                let x = &exc_buf[MAX_PERIOD - exc_length..];
3633                let mut y = vec![0.0f32; ord + exc_length];
3634                crate::celt_lpc::celt_fir(x, &lc, &mut y, ord + exc_length, ord);
3635                for i in 0..exc_length {
3636                    exc_buf[ord + MAX_PERIOD - exc_length + i] = y[ord + i];
3637                }
3638            }
3639
3640            // Decay factor from the excitation energy ratio (avoid adding energy).
3641            let decay_length = exc_length >> 1;
3642            let mut e1 = 1.0f32;
3643            let mut e2 = 1.0f32;
3644            for i in 0..decay_length {
3645                let a = exc_buf[ord + MAX_PERIOD - decay_length + i];
3646                e1 += a * a;
3647                let b = exc_buf[ord + MAX_PERIOD - 2 * decay_length + i];
3648                e2 += b * b;
3649            }
3650            e1 = e1.min(e2);
3651            let decay = (e1 / e2).sqrt();
3652
3653            // Shift decode buffer one frame left.
3654            self.decode_mem
3655                .copy_within(base + n..base + DECODE_BUFFER_SIZE, base);
3656
3657            // Extrapolate at period `pitch_index`, attenuating each period.
3658            let extrapolation_offset = MAX_PERIOD - pitch_index;
3659            let extrapolation_len = n + overlap;
3660            let mut atten = fade * decay;
3661            let mut j = 0usize;
3662            let mut s1 = 0.0f32;
3663            for i in 0..extrapolation_len {
3664                if j >= pitch_index {
3665                    j -= pitch_index;
3666                    atten *= decay;
3667                }
3668                self.decode_mem[base + out_syn_idx + i] =
3669                    atten * exc_buf[ord + extrapolation_offset + j];
3670                let tmp = self.decode_mem
3671                    [base + (DECODE_BUFFER_SIZE - MAX_PERIOD - n) + extrapolation_offset + j];
3672                s1 += tmp * tmp;
3673                j += 1;
3674            }
3675
3676            // Resynthesize: excitation -> signal through the LPC synthesis filter.
3677            let mut lpc_mem = [0.0f32; PLC_LPC_ORDER];
3678            for (i, v) in lpc_mem.iter_mut().enumerate().take(ord) {
3679                *v = self.decode_mem[base + DECODE_BUFFER_SIZE - n - 1 - i];
3680            }
3681            let extrap: Vec<f32> = self.decode_mem
3682                [base + out_syn_idx..base + out_syn_idx + extrapolation_len]
3683                .to_vec();
3684            crate::celt_lpc::celt_iir(
3685                &extrap,
3686                &lc,
3687                &mut self.decode_mem[base + out_syn_idx..base + out_syn_idx + extrapolation_len],
3688                extrapolation_len,
3689                ord,
3690                &mut lpc_mem[..ord],
3691            );
3692            for i in 0..extrapolation_len {
3693                let v = &mut self.decode_mem[base + out_syn_idx + i];
3694                *v = v.clamp(-SIG_SAT, SIG_SAT);
3695            }
3696
3697            // Explosion / NaN guard (the !(S1 > .2*S2) test also catches IIR NaNs).
3698            let mut s2 = 0.0f32;
3699            for i in 0..extrapolation_len {
3700                let t = self.decode_mem[base + out_syn_idx + i];
3701                s2 += t * t;
3702            }
3703            if !(s1 > 0.2 * s2) {
3704                for i in 0..extrapolation_len {
3705                    self.decode_mem[base + out_syn_idx + i] = 0.0;
3706                }
3707            } else if s1 < s2 {
3708                let ratio = ((s1 + 1.0) / (s2 + 1.0)).sqrt();
3709                for i in 0..overlap {
3710                    let g = 1.0 - window[i] * (1.0 - ratio);
3711                    self.decode_mem[base + out_syn_idx + i] *= g;
3712                }
3713                for i in overlap..extrapolation_len {
3714                    self.decode_mem[base + out_syn_idx + i] *= ratio;
3715                }
3716            }
3717
3718            // Re-apply the postfilter to the overlap, then TDAC-fold so the
3719            // concealed audio blends with the next frame's MDCT.
3720            comb_filter(
3721                &mut etmp,
3722                &self.decode_mem,
3723                0,
3724                base + DECODE_BUFFER_SIZE,
3725                self.prefilter_period,
3726                self.prefilter_period,
3727                overlap,
3728                -self.prefilter_gain,
3729                -self.prefilter_gain,
3730                self.prefilter_tapset,
3731                self.prefilter_tapset,
3732                window,
3733                0,
3734            );
3735            for i in 0..overlap / 2 {
3736                self.decode_mem[base + DECODE_BUFFER_SIZE + i] =
3737                    window[i] * etmp[overlap - 1 - i] + window[overlap - 1 - i] * etmp[i];
3738            }
3739        }
3740    }
3741}
3742
3743#[cfg(test)]
3744mod tests {
3745    use super::*;
3746    use crate::{modes, range_coder::RangeCoder};
3747
3748    // Regression test: directly drive CeltEncoder with an invalid frame_size=48,
3749    // bypassing the OpusEncoder::encode() validation layer.
3750    //
3751    // This reproduces the crash that was reported against opus-rs 0.1.19 when
3752    // G.729-decoded PCM (8 kHz) reached the 48 kHz Opus encoder without correct
3753    // resampling, producing a 48-sample frame instead of 480.
3754    //
3755    // Root cause: the lm-search in encode_impl finds no valid match for frame_size=48
3756    // (valid sizes are 120, 240, 480, 960) and silently falls back to lm=0.
3757    // With lm=0 and shift=max_lm=3: n=1920>>3=240, n2=120, overlap2=60.
3758    // The in_buf slice has only frame_size+overlap=168 elements, but forward()
3759    // requires input.len() >= n2+overlap2 = 180, so it panics immediately.
3760    // In opus-rs 0.1.19 this assertion was absent and the crash reached the MDCT
3761    // output write: "index out of bounds: the len is 48 but the index is 119".
3762    //
3763    // Either way: the call panics, confirming the crash path is real.
3764    // The fix in OpusEncoder::encode() returns Err before reaching CeltEncoder.
3765    #[test]
3766    #[should_panic]
3767    fn test_celt_frame_size_48_panics_confirms_crash_path() {
3768        let mode = modes::default_mode();
3769        let mut enc = CeltEncoder::new(mode, 1);
3770        // frame_size=48: lm-search fails, falls back to lm=0.
3771        // forward() will panic — either on the input-size assertion (0.1.21+) or
3772        // on the output write (0.1.19): "len is 48 but the index is 119".
3773        let pcm = vec![0.0f32; 48 + mode.overlap]; // supply ≥ frame_size samples
3774        let mut rc = RangeCoder::new_encoder(100);
3775        enc.encode_with_budget(&pcm, 48, &mut rc, 0, 21, 800);
3776    }
3777
3778    // Prefilter/postfilter inversion, MDCT bypassed: run the real run_prefilter
3779    // per frame (with the real signalling quantization of gain/period), feed the
3780    // FILTERED stream straight into the decoder's postfilter sequence (call 1
3781    // old->current over shortMdctSize, call 2 current->new with the crossfade),
3782    // honoring the 120-sample MDCT delay. If the encoder applies exactly what it
3783    // signals with the timing the decoder inverts, the round trip is ~identity.
3784    #[test]
3785    fn prefilter_postfilter_inversion() {
3786        let mode = modes::default_mode();
3787        let n = 960usize;
3788        let overlap = mode.overlap; // 120
3789        let short_n = mode.short_mdct_size; // 120
3790        let frames = 100usize;
3791        let max_period = COMBFILTER_MAXPERIOD;
3792
3793        // Signal designed to TOGGLE the prefilter: alternating strongly periodic
3794        // stretches (varying pitch) and noise bursts.
3795        let total = frames * n;
3796        let mut x = vec![0.0f32; total];
3797        let mut rng = 0x12345678u32;
3798        let mut next = || {
3799            rng = rng.wrapping_mul(1664525).wrapping_add(1013904223);
3800            (rng >> 8) as f32 / (1 << 24) as f32 - 0.5
3801        };
3802        for (t, v) in x.iter_mut().enumerate() {
3803            let seg = t / (n * 10);
3804            let phase = t as f32;
3805            *v = match seg % 4 {
3806                0 => (phase * std::f32::consts::TAU / 147.0).sin() * 8000.0, // ~326 Hz
3807                1 => next() * 6000.0,
3808                2 => {
3809                    ((phase * std::f32::consts::TAU / 89.0).sin()
3810                        + 0.5 * (phase * std::f32::consts::TAU / 44.5).sin())
3811                        * 7000.0
3812                }
3813                _ => (phase * std::f32::consts::TAU / 480.0).sin() * 5000.0, // 100 Hz
3814            };
3815        }
3816
3817        // ---- encoder side ----
3818        let mut pre = vec![0.0f32; max_period + n];
3819        let mut pitch_buf = vec![0.0f32; (max_period + n) >> 1];
3820        let mut prefilter_mem = vec![0.0f32; max_period];
3821        let mut in_mem = vec![0.0f32; overlap];
3822        let (mut prev_t, mut prev_g) = (COMBFILTER_MINPERIOD, 0.0f32);
3823        let analysis = AnalysisInfo::default();
3824        let mut filtered = vec![0.0f32; total];
3825        let mut params = Vec::new(); // (pf_on, T, g) per frame
3826        let mut in_buf = vec![0.0f32; n + overlap];
3827        for k in 0..frames {
3828            in_buf[..overlap].copy_from_slice(&in_mem);
3829            in_buf[overlap..].copy_from_slice(&x[k * n..(k + 1) * n]);
3830            let (pf_on, g1, t1) = run_prefilter(
3831                &mut in_buf,
3832                &mut prefilter_mem,
3833                prev_t,
3834                prev_g,
3835                0, // prefilter_tapset (old)
3836                0, // tapset_decision (new)
3837                mode.window,
3838                1,
3839                n,
3840                overlap,
3841                &mut pre,
3842                &mut pitch_buf,
3843                &analysis,
3844                0,
3845                159,
3846            );
3847            filtered[k * n..(k + 1) * n].copy_from_slice(&in_buf[overlap..]);
3848            in_mem.copy_from_slice(&in_buf[n..]);
3849            params.push((pf_on, t1, g1));
3850            // encoder end-of-frame state update
3851            prev_t = if pf_on { t1 } else { COMBFILTER_MINPERIOD };
3852            prev_g = if pf_on { g1 } else { 0.0 };
3853        }
3854
3855        // ---- decoder side (postfilter only), 120-sample MDCT delay ----
3856        let mut delayed = vec![0.0f32; total];
3857        delayed[short_n..].copy_from_slice(&filtered[..total - short_n]);
3858        let mut w = vec![0.0f32; max_period + n];
3859        let mut post_mem = vec![0.0f32; max_period];
3860        let (mut d_t_old, mut d_g_old) = (COMBFILTER_MINPERIOD, 0.0f32);
3861        let (mut d_t, mut d_g) = (COMBFILTER_MINPERIOD, 0.0f32);
3862        let mut out = vec![0.0f32; total];
3863        for k in 0..frames {
3864            let (pf_on, sig_t, sig_g) = params[k];
3865            let (gain1, pitch_index) = if pf_on {
3866                (sig_g, sig_t)
3867            } else {
3868                (0.0, COMBFILTER_MINPERIOD)
3869            };
3870            w[..max_period].copy_from_slice(&post_mem);
3871            w[max_period..].copy_from_slice(&delayed[k * n..(k + 1) * n]);
3872            if pf_on || d_g > 0.0 || d_g_old > 0.0 {
3873                comb_filter_inplace(
3874                    &mut w, max_period, d_t_old, d_t, short_n, d_g_old, d_g, 0, 0, mode.window,
3875                    overlap,
3876                );
3877                comb_filter_inplace(
3878                    &mut w,
3879                    max_period + short_n,
3880                    d_t,
3881                    pitch_index,
3882                    n - short_n,
3883                    d_g,
3884                    gain1,
3885                    0,
3886                    0,
3887                    mode.window,
3888                    overlap,
3889                );
3890            }
3891            out[k * n..(k + 1) * n].copy_from_slice(&w[max_period..]);
3892            post_mem.copy_from_slice(&w[n..]);
3893            // decoder end-of-frame chain, then the lm > 0 override
3894            if pf_on {
3895                d_t = pitch_index;
3896                d_g = gain1;
3897            } else {
3898                d_t = COMBFILTER_MINPERIOD;
3899                d_g = 0.0;
3900            }
3901            d_t_old = d_t;
3902            d_g_old = d_g;
3903        }
3904
3905        // ---- compare out (delayed by short_n) against x ----
3906        let m = total - 2 * n;
3907        let mut se = 0.0f64;
3908        let mut sx = 0.0f64;
3909        for t in n..m {
3910            let e = (out[t + short_n] - x[t]) as f64;
3911            se += e * e;
3912            sx += (x[t] as f64) * (x[t] as f64);
3913        }
3914        let snr = 10.0 * (sx / se.max(1e-30)).log10();
3915        let engaged = params.iter().filter(|p| p.0).count();
3916        assert!(
3917            engaged > frames / 4,
3918            "prefilter never engaged ({engaged}/{frames}) — test signal too weak"
3919        );
3920        assert!(
3921            snr > 90.0,
3922            "prefilter/postfilter round trip not transparent: SNR={snr:.1} dB (engaged {engaged}/{frames})"
3923        );
3924    }
3925}