ec-opus: CELT encoder replaced by a port of the libopus 1.6 float encoder (celt_flp: celt_encoder.c, bands, vq, quant_bands, pitch, MDCT/FFT); every Opus packet now byte-identical to libopus 1.6 across VoIP/Audio/LowDelay, mono/stereo, CBR/VBR, FEC on/off, 8-128 kb/s, 2.5-60 ms frames (CELT-only, hybrid, SILK, mode switches, redundancy)
Browse files at this commite84467678af472c83966325ec66cfc8f46083dc1Parent: e7e591420 changed files +7926 -4641
- crates/ec-opus/src/analysis.rs +25 -24
- crates/ec-opus/src/celt.rs +56 -22
- crates/ec-opus/src/celt_enc.rs +0 -3120
- crates/ec-opus/src/celt_flp/bands.rs +1234 -0
- crates/ec-opus/src/celt_flp/enc.rs +1389 -0
- crates/ec-opus/src/celt_flp/enc_an.rs +843 -0
- crates/ec-opus/src/celt_flp/fft.rs +268 -0
- crates/ec-opus/src/celt_flp/mod.rs +81 -0
- crates/ec-opus/src/celt_flp/pitch.rs +569 -0
- crates/ec-opus/src/celt_flp/quant_bands.rs +358 -0
- crates/ec-opus/src/celt_flp/tables.rs +2501 -0
- crates/ec-opus/src/celt_flp/vq.rs +250 -0
- crates/ec-opus/src/encoder.rs +312 -220
- crates/ec-opus/src/lib.rs +1 -2
- crates/ec-opus/src/range.rs +5 -0
- crates/ec-opus/src/silk.rs +1 -1
- crates/ec-opus/src/silk_flp/encode.rs +11 -6
- crates/ec-opus/src/silk_flp/opus.rs +2 -0
- crates/ec-opus/src/stack_budget.rs +18 -33
- crates/ec-opus/tests/conformance.rs +2 -1213
crates/ec-opus/src/analysis.rsmodified+25 -24
| @@ -28,7 +28,6 @@ | |||
| 28 | //! `st->Fs >= 16000` guard arranges; below that `AnalysisInfo::valid` stays | 28 | //! `st->Fs >= 16000` guard arranges; below that `AnalysisInfo::valid` stays |
| 29 | //! false and every consumer takes its no-analysis branch. | 29 | //! false and every consumer takes its no-analysis branch. |
| 30 | 30 | ||
| 31 | -use crate::celt::Fft15; | ||
| 32 | 31 | ||
| 33 | /// Number of past frames the band-energy history keeps (`NB_FRAMES`). | 32 | /// Number of past frames the band-energy history keeps (`NB_FRAMES`). |
| 34 | const NB_FRAMES: usize = 8; | 33 | const NB_FRAMES: usize = 8; |
| @@ -59,6 +58,12 @@ const WEIGHTS_SCALE: f32 = 1.0 / 128.0; | |||
| 59 | /// libopus's truncated `1.442695` (log2(e)), kept verbatim for bit-exact band energies. | 58 | /// libopus's truncated `1.442695` (log2(e)), kept verbatim for bit-exact band energies. |
| 60 | #[allow(clippy::approx_constant)] | 59 | #[allow(clippy::approx_constant)] |
| 61 | const LIBOPUS_LOG2_E: f32 = 1.442_695; | 60 | const LIBOPUS_LOG2_E: f32 = 1.442_695; |
| 61 | +const SIG_SCALE: f32 = 32768.0; | ||
| 62 | +const HALF_OVER_PI: f32 = (0.5f64 / core::f64::consts::PI) as f32; | ||
| 63 | + | ||
| 64 | +fn ln_f64(x: f32) -> f32 { | ||
| 65 | + f64::from(x).ln() as f32 | ||
| 66 | +} | ||
| 62 | 67 | ||
| 63 | /// Tonality band edges in 480-point FFT bins (`tbands`). | 68 | /// Tonality band edges in 480-point FFT bins (`tbands`). |
| 64 | const TBANDS: [usize; NB_TBANDS + 1] = [ | 69 | const TBANDS: [usize; NB_TBANDS + 1] = [ |
| @@ -256,7 +261,6 @@ pub(crate) struct TonalityAnalysis { | |||
| 256 | fs: u32, | 261 | fs: u32, |
| 257 | /// False for rates libopus never analyses (below 16 kHz). | 262 | /// False for rates libopus never analyses (below 16 kHz). |
| 258 | enabled: bool, | 263 | enabled: bool, |
| 259 | - fft: Fft15, | ||
| 260 | angle: Vec<f32>, | 264 | angle: Vec<f32>, |
| 261 | d_angle: Vec<f32>, | 265 | d_angle: Vec<f32>, |
| 262 | d2_angle: Vec<f32>, | 266 | d2_angle: Vec<f32>, |
| @@ -302,7 +306,6 @@ impl TonalityAnalysis { | |||
| 302 | TonalityAnalysis { | 306 | TonalityAnalysis { |
| 303 | fs: sample_rate, | 307 | fs: sample_rate, |
| 304 | enabled: matches!(sample_rate, 16000 | 24000 | 48000), | 308 | enabled: matches!(sample_rate, 16000 | 24000 | 48000), |
| 305 | - fft: Fft15::new(N), | ||
| 306 | angle: vec![0.0; N2], | 309 | angle: vec![0.0; N2], |
| 307 | d_angle: vec![0.0; N2], | 310 | d_angle: vec![0.0; N2], |
| 308 | d2_angle: vec![0.0; N2], | 311 | d2_angle: vec![0.0; N2], |
| @@ -342,10 +345,7 @@ impl TonalityAnalysis { | |||
| 342 | 345 | ||
| 343 | /// Clears every non-reusable field — libopus `tonality_analysis_reset()`. | 346 | /// Clears every non-reusable field — libopus `tonality_analysis_reset()`. |
| 344 | pub(crate) fn reset(&mut self) { | 347 | pub(crate) fn reset(&mut self) { |
| 345 | - let fs = self.fs; | 348 | + *self = TonalityAnalysis::new(self.fs); |
| 346 | - let fft = std::mem::replace(&mut self.fft, Fft15::new(15)); | ||
| 347 | - *self = TonalityAnalysis::new(fs); | ||
| 348 | - self.fft = fft; | ||
| 349 | } | 349 | } |
| 350 | 350 | ||
| 351 | /// libopus `run_analysis()`: consumes one API frame of interleaved input | 351 | /// libopus `run_analysis()`: consumes one API frame of interleaved input |
| @@ -410,6 +410,7 @@ impl TonalityAnalysis { | |||
| 410 | for c in 1..channels { | 410 | for c in 1..channels { |
| 411 | acc += pcm[base + c]; | 411 | acc += pcm[base + c]; |
| 412 | } | 412 | } |
| 413 | + let acc = acc.clamp(-2.0, 2.0); | ||
| 413 | *t = if channels == 2 { 0.5 * acc } else { acc }; | 414 | *t = if channels == 2 { 0.5 * acc } else { acc }; |
| 414 | } | 415 | } |
| 415 | let mut st = self.downmix_state; | 416 | let mut st = self.downmix_state; |
| @@ -480,7 +481,8 @@ impl TonalityAnalysis { | |||
| 480 | self.write_pos -= DETECT_SIZE; | 481 | self.write_pos -= DETECT_SIZE; |
| 481 | } | 482 | } |
| 482 | 483 | ||
| 483 | - let is_silence = self.inmem.iter().all(|&v| v == 0.0); | 484 | + let max_abs = self.inmem.iter().fold(0.0f32, |m, &v| m.max(v.abs())); |
| 485 | + let is_silence = max_abs * 32768.0 <= 1.0 / (1u32 << lsb_depth) as f32; | ||
| 484 | 486 | ||
| 485 | let mut re = std::mem::take(&mut self.fft_re); | 487 | let mut re = std::mem::take(&mut self.fft_re); |
| 486 | let mut im = std::mem::take(&mut self.fft_im); | 488 | let mut im = std::mem::take(&mut self.fft_im); |
| @@ -509,16 +511,15 @@ impl TonalityAnalysis { | |||
| 509 | self.fft_im = im; | 511 | self.fft_im = im; |
| 510 | return; | 512 | return; |
| 511 | } | 513 | } |
| 512 | - // libopus takes `opus_fft` (forward, scaled by 1/N); ours is the | 514 | + let st = &crate::celt_flp::tables::FFT_STATES[0]; |
| 513 | - // unscaled conjugate transform, so conjugate in and out and scale. | 515 | + let mut fout = [[0.0f32; 2]; N]; |
| 514 | - for v in im.iter_mut() { | 516 | + for i in 0..N { |
| 515 | - *v = -*v; | 517 | + fout[st.bitrev[i] as usize] = [re[i] * st.scale, im[i] * st.scale]; |
| 516 | } | 518 | } |
| 517 | - self.fft.inverse(&mut re, &mut im); | 519 | + crate::celt_flp::fft::opus_fft_impl(st, &mut fout); |
| 518 | - let s = 1.0 / N as f32; | ||
| 519 | for i in 0..N { | 520 | for i in 0..N { |
| 520 | - re[i] *= s; | 521 | + re[i] = fout[i][0]; |
| 521 | - im[i] *= -s; | 522 | + im[i] = fout[i][1]; |
| 522 | } | 523 | } |
| 523 | if re[0].is_nan() { | 524 | if re[0].is_nan() { |
| 524 | self.info[write].valid = false; | 525 | self.info[write].valid = false; |
| @@ -537,11 +538,11 @@ impl TonalityAnalysis { | |||
| 537 | let x2r = im[i] + im[N - i]; | 538 | let x2r = im[i] + im[N - i]; |
| 538 | let x2i = re[N - i] - re[i]; | 539 | let x2i = re[N - i] - re[i]; |
| 539 | 540 | ||
| 540 | - let angle = (0.5 / core::f32::consts::PI) * fast_atan2f(x1i, x1r); | 541 | + let angle = HALF_OVER_PI * fast_atan2f(x1i * SIG_SCALE, x1r * SIG_SCALE); |
| 541 | let d_angle = angle - self.angle[i]; | 542 | let d_angle = angle - self.angle[i]; |
| 542 | let d2_angle = d_angle - self.d_angle[i]; | 543 | let d2_angle = d_angle - self.d_angle[i]; |
| 543 | 544 | ||
| 544 | - let angle2 = (0.5 / core::f32::consts::PI) * fast_atan2f(x2i, x2r); | 545 | + let angle2 = HALF_OVER_PI * fast_atan2f(x2i * SIG_SCALE, x2r * SIG_SCALE); |
| 545 | let d_angle2 = angle2 - angle; | 546 | let d_angle2 = angle2 - angle; |
| 546 | let d2_angle2 = d_angle2 - d_angle; | 547 | let d2_angle2 = d_angle2 - d_angle; |
| 547 | 548 | ||
| @@ -594,7 +595,7 @@ impl TonalityAnalysis { | |||
| 594 | for i in 1..4 { | 595 | for i in 1..4 { |
| 595 | e += bin_e(&re, &im, i); | 596 | e += bin_e(&re, &im, i); |
| 596 | } | 597 | } |
| 597 | - band_log2[0] = 0.5 * LIBOPUS_LOG2_E * (e + 1e-10).ln(); | 598 | + band_log2[0] = 0.5 * LIBOPUS_LOG2_E * ln_f64(e + 1e-10); |
| 598 | } | 599 | } |
| 599 | let mut band_tonality = [0.0f32; NB_TBANDS]; | 600 | let mut band_tonality = [0.0f32; NB_TBANDS]; |
| 600 | let mut slope = 0.0f32; | 601 | let mut slope = 0.0f32; |
| @@ -618,8 +619,8 @@ impl TonalityAnalysis { | |||
| 618 | self.e[self.e_count][b] = e; | 619 | self.e[self.e_count][b] = e; |
| 619 | frame_noisiness += ne / (1e-15 + e); | 620 | frame_noisiness += ne / (1e-15 + e); |
| 620 | frame_loudness += (e + 1e-10).sqrt(); | 621 | frame_loudness += (e + 1e-10).sqrt(); |
| 621 | - log_e[b] = (e + 1e-10).ln(); | 622 | + log_e[b] = ln_f64(e + 1e-10); |
| 622 | - band_log2[b + 1] = 0.5 * LIBOPUS_LOG2_E * (e + 1e-10).ln(); | 623 | + band_log2[b + 1] = 0.5 * LIBOPUS_LOG2_E * ln_f64(e + 1e-10); |
| 623 | self.log_e[self.e_count][b] = log_e[b]; | 624 | self.log_e[self.e_count][b] = log_e[b]; |
| 624 | if self.count == 0 { | 625 | if self.count == 0 { |
| 625 | self.high_e[b] = log_e[b]; | 626 | self.high_e[b] = log_e[b]; |
| @@ -647,7 +648,7 @@ impl TonalityAnalysis { | |||
| 647 | l1 += self.e[i][b].sqrt(); | 648 | l1 += self.e[i][b].sqrt(); |
| 648 | l2 += self.e[i][b]; | 649 | l2 += self.e[i][b]; |
| 649 | } | 650 | } |
| 650 | - let mut stationarity = 0.99f32.min(l1 / (1e-15 + NB_FRAMES as f32 * l2).sqrt()); | 651 | + let mut stationarity = 0.99f32.min(l1 / (1e-15 + f64::from(NB_FRAMES as f32 * l2)).sqrt() as f32); |
| 651 | stationarity *= stationarity; | 652 | stationarity *= stationarity; |
| 652 | stationarity *= stationarity; | 653 | stationarity *= stationarity; |
| 653 | frame_stationarity += stationarity; | 654 | frame_stationarity += stationarity; |
| @@ -680,7 +681,7 @@ impl TonalityAnalysis { | |||
| 680 | for b in 0..NB_TBANDS + 1 { | 681 | for b in 0..NB_TBANDS + 1 { |
| 681 | let boost = (leakage_to[b] - band_log2[b]).max(0.0) | 682 | let boost = (leakage_to[b] - band_log2[b]).max(0.0) |
| 682 | + (band_log2[b] - (leakage_from[b] + LEAKAGE_OFFSET)).max(0.0); | 683 | + (band_log2[b] - (leakage_from[b] + LEAKAGE_OFFSET)).max(0.0); |
| 683 | - leak_boost[b] = (0.5 + 64.0 * boost).floor().min(255.0) as u8; | 684 | + leak_boost[b] = (0.5 + f64::from(64.0 * boost)).floor().min(255.0) as u8; |
| 684 | } | 685 | } |
| 685 | 686 | ||
| 686 | let mut spec_variability = 0.0f32; | 687 | let mut spec_variability = 0.0f32; |
| @@ -756,7 +757,7 @@ impl TonalityAnalysis { | |||
| 756 | if self.count <= 2 { | 757 | if self.count <= 2 { |
| 757 | bandwidth = 20; | 758 | bandwidth = 20; |
| 758 | } | 759 | } |
| 759 | - frame_loudness = 20.0 * frame_loudness.log10(); | 760 | + frame_loudness = 20.0 * f64::from(frame_loudness).log10() as f32; |
| 760 | self.e_tracker = (self.e_tracker - 0.003).max(frame_loudness); | 761 | self.e_tracker = (self.e_tracker - 0.003).max(frame_loudness); |
| 761 | self.low_e_count *= 1.0 - alpha_e; | 762 | self.low_e_count *= 1.0 - alpha_e; |
| 762 | if frame_loudness < self.e_tracker - 30.0 { | 763 | if frame_loudness < self.e_tracker - 30.0 { |
crates/ec-opus/src/celt.rsmodified+56 -22
| @@ -263,7 +263,6 @@ pub(crate) const PREEMPH: f32 = 0.850_006_1; | |||
| 263 | pub(crate) const SIG_SCALE: f32 = 32768.0; | 263 | pub(crate) const SIG_SCALE: f32 = 32768.0; |
| 264 | 264 | ||
| 265 | pub(crate) const SPREAD_NONE: usize = 0; | 265 | pub(crate) const SPREAD_NONE: usize = 0; |
| 266 | -pub(crate) const SPREAD_LIGHT: usize = 1; | ||
| 267 | pub(crate) const SPREAD_NORMAL: usize = 2; | 266 | pub(crate) const SPREAD_NORMAL: usize = 2; |
| 268 | pub(crate) const SPREAD_AGGRESSIVE: usize = 3; | 267 | pub(crate) const SPREAD_AGGRESSIVE: usize = 3; |
| 269 | 268 | ||
| @@ -663,7 +662,9 @@ const fn compute_pvq_u() -> [u32; PVQ_U_LEN] { | |||
| 663 | while a < 15 { | 662 | while a < 15 { |
| 664 | let mut b = 1; | 663 | let mut b = 1; |
| 665 | while b < 177 { | 664 | while b < 177 { |
| 666 | - uu[a][b] = uu[a - 1][b].wrapping_add(uu[a][b - 1]).wrapping_add(uu[a - 1][b - 1]); | 665 | + uu[a][b] = uu[a - 1][b] |
| 666 | + .wrapping_add(uu[a][b - 1]) | ||
| 667 | + .wrapping_add(uu[a - 1][b - 1]); | ||
| 667 | b += 1; | 668 | b += 1; |
| 668 | } | 669 | } |
| 669 | a += 1; | 670 | a += 1; |
| @@ -842,20 +843,36 @@ enum AllocationMode<'a, 'b> { | |||
| 842 | intensity: usize, | 843 | intensity: usize, |
| 843 | dual_stereo: bool, | 844 | dual_stereo: bool, |
| 844 | prev_coded_bands: usize, | 845 | prev_coded_bands: usize, |
| 846 | + signal_bandwidth: usize, | ||
| 845 | }, | 847 | }, |
| 846 | } | 848 | } |
| 847 | 849 | ||
| 848 | impl AllocationMode<'_, '_> { | 850 | impl AllocationMode<'_, '_> { |
| 849 | - fn keep_band(&mut self, j: usize, band_bits: i32, band_width: i32, lm: usize) -> bool { | 851 | + fn keep_band( |
| 852 | + &mut self, | ||
| 853 | + j: usize, | ||
| 854 | + band_bits: i32, | ||
| 855 | + band_width: i32, | ||
| 856 | + lm: usize, | ||
| 857 | + start: usize, | ||
| 858 | + coded_bands: usize, | ||
| 859 | + ) -> bool { | ||
| 850 | match self { | 860 | match self { |
| 851 | AllocationMode::Decode(dec) => dec.dec_bit_logp(1), | 861 | AllocationMode::Decode(dec) => dec.dec_bit_logp(1), |
| 852 | AllocationMode::Encode { | 862 | AllocationMode::Encode { |
| 853 | enc, | 863 | enc, |
| 854 | prev_coded_bands, | 864 | prev_coded_bands, |
| 865 | + signal_bandwidth, | ||
| 855 | .. | 866 | .. |
| 856 | } => { | 867 | } => { |
| 857 | - let hysteresis = if j < *prev_coded_bands { 7 } else { 9 }; | 868 | + let depth_threshold = if coded_bands > 17 { |
| 858 | - let stay = band_bits > ((hysteresis * band_width) << lm << BITRES) >> 4; | 869 | + if j < *prev_coded_bands { 7 } else { 9 } |
| 870 | + } else { | ||
| 871 | + 0 | ||
| 872 | + }; | ||
| 873 | + let stay = coded_bands <= start + 2 | ||
| 874 | + || (band_bits > ((depth_threshold * band_width) << lm << BITRES) >> 4 | ||
| 875 | + && j <= *signal_bandwidth); | ||
| 859 | enc.enc_bit_logp(stay, 1); | 876 | enc.enc_bit_logp(stay, 1); |
| 860 | stay | 877 | stay |
| 861 | } | 878 | } |
| @@ -959,6 +976,7 @@ pub(crate) fn compute_allocation_encode( | |||
| 959 | intensity: usize, | 976 | intensity: usize, |
| 960 | dual_stereo: bool, | 977 | dual_stereo: bool, |
| 961 | prev_coded_bands: usize, | 978 | prev_coded_bands: usize, |
| 979 | + signal_bandwidth: usize, | ||
| 962 | ) -> AllocationResult { | 980 | ) -> AllocationResult { |
| 963 | compute_allocation_shared( | 981 | compute_allocation_shared( |
| 964 | AllocationMode::Encode { | 982 | AllocationMode::Encode { |
| @@ -966,6 +984,7 @@ pub(crate) fn compute_allocation_encode( | |||
| 966 | intensity, | 984 | intensity, |
| 967 | dual_stereo, | 985 | dual_stereo, |
| 968 | prev_coded_bands, | 986 | prev_coded_bands, |
| 987 | + signal_bandwidth, | ||
| 969 | }, | 988 | }, |
| 970 | start, | 989 | start, |
| 971 | end, | 990 | end, |
| @@ -1140,7 +1159,7 @@ fn compute_allocation_shared( | |||
| 1140 | let band_width = (E_BANDS[coded_bands] - E_BANDS[j]) as i32; | 1159 | let band_width = (E_BANDS[coded_bands] - E_BANDS[j]) as i32; |
| 1141 | let mut band_bits = pulses[j] + percoeff * band_width + rem; | 1160 | let mut band_bits = pulses[j] + percoeff * band_width + rem; |
| 1142 | if band_bits >= thresh[j].max(alloc_floor + (1 << BITRES)) { | 1161 | if band_bits >= thresh[j].max(alloc_floor + (1 << BITRES)) { |
| 1143 | - if mode.keep_band(j, band_bits, band_width, lm) { | 1162 | + if mode.keep_band(j, band_bits, band_width, lm, start, coded_bands) { |
| 1144 | break; | 1163 | break; |
| 1145 | } | 1164 | } |
| 1146 | psum += 1 << BITRES; | 1165 | psum += 1 << BITRES; |
| @@ -1645,7 +1664,11 @@ impl CeltDecoder { | |||
| 1645 | // RFC 8251 Section 8: cap the log2 energy at 32 so the amplitude | 1664 | // RFC 8251 Section 8: cap the log2 energy at 32 so the amplitude |
| 1646 | // stays finite (libopus `log2Amp`, `MIN32(QCONST32(32.f, 16), lg)`). | 1665 | // stays finite (libopus `log2Amp`, `MIN32(QCONST32(32.f, 16), lg)`). |
| 1647 | let lg = (self.old_band_e[ch * NB_BANDS + i] + mean) as f64; | 1666 | let lg = (self.old_band_e[ch * NB_BANDS + i] + mean) as f64; |
| 1648 | - let lg = if self.legacy_rfc6716 { lg } else { lg.min(32.0) }; | 1667 | + let lg = if self.legacy_rfc6716 { |
| 1668 | + lg | ||
| 1669 | + } else { | ||
| 1670 | + lg.min(32.0) | ||
| 1671 | + }; | ||
| 1649 | lg.exp2() as f32 | 1672 | lg.exp2() as f32 |
| 1650 | }; | 1673 | }; |
| 1651 | } | 1674 | } |
| @@ -1868,13 +1891,13 @@ impl CeltDecoder { | |||
| 1868 | budget -= i32::from(tf_select_rsv); | 1891 | budget -= i32::from(tf_select_rsv); |
| 1869 | let mut curr = 0i32; | 1892 | let mut curr = 0i32; |
| 1870 | let mut changed = false; | 1893 | let mut changed = false; |
| 1871 | - for i in start..end { | 1894 | + for tf in self.tf_res.iter_mut().take(end).skip(start) { |
| 1872 | if tell + logp as i32 <= budget { | 1895 | if tell + logp as i32 <= budget { |
| 1873 | curr ^= i32::from(dec.dec_bit_logp(logp)); | 1896 | curr ^= i32::from(dec.dec_bit_logp(logp)); |
| 1874 | tell = dec.tell() as i32; | 1897 | tell = dec.tell() as i32; |
| 1875 | changed |= curr != 0; | 1898 | changed |= curr != 0; |
| 1876 | } | 1899 | } |
| 1877 | - self.tf_res[i] = curr; | 1900 | + *tf = curr; |
| 1878 | logp = if transient { 4 } else { 5 }; | 1901 | logp = if transient { 4 } else { 5 }; |
| 1879 | } | 1902 | } |
| 1880 | let t = usize::from(transient); | 1903 | let t = usize::from(transient); |
| @@ -1941,7 +1964,8 @@ impl CeltDecoder { | |||
| 1941 | let n2 = m * (E_BANDS[start + 2] - E_BANDS[start + 1]); | 1964 | let n2 = m * (E_BANDS[start + 2] - E_BANDS[start + 1]); |
| 1942 | let offset = m * E_BANDS[start]; | 1965 | let offset = m * E_BANDS[start]; |
| 1943 | if n2 > n1 && n2 <= 2 * n1 { | 1966 | if n2 > n1 && n2 <= 2 * n1 { |
| 1944 | - self.norm.copy_within(offset + 2 * n1 - n2..offset + n1, offset + n1); | 1967 | + self.norm |
| 1968 | + .copy_within(offset + 2 * n1 - n2..offset + n1, offset + n1); | ||
| 1945 | if c == 2 { | 1969 | if c == 2 { |
| 1946 | let o2 = norm_len + offset; | 1970 | let o2 = norm_len + offset; |
| 1947 | self.norm.copy_within(o2 + 2 * n1 - n2..o2 + n1, o2 + n1); | 1971 | self.norm.copy_within(o2 + 2 * n1 - n2..o2 + n1, o2 + n1); |
| @@ -2062,7 +2086,12 @@ impl CeltDecoder { | |||
| 2062 | } | 2086 | } |
| 2063 | 2087 | ||
| 2064 | /// Decodes one band (Section 4.3.4), recursing for splits and for stereo. | 2088 | /// Decodes one band (Section 4.3.4), recursing for splits and for stereo. |
| 2065 | - fn quant_band(&mut self, dec: &mut RangeDecoder, a: BandArgs, remaining_bits: &mut i32) -> Result<u32> { | 2089 | + fn quant_band( |
| 2090 | + &mut self, | ||
| 2091 | + dec: &mut RangeDecoder, | ||
| 2092 | + a: BandArgs, | ||
| 2093 | + remaining_bits: &mut i32, | ||
| 2094 | + ) -> Result<u32> { | ||
| 2066 | let BandArgs { | 2095 | let BandArgs { |
| 2067 | i, | 2096 | i, |
| 2068 | x, | 2097 | x, |
| @@ -2463,7 +2492,13 @@ impl CeltDecoder { | |||
| 2463 | // Undo the reorganisations, and pass the band on for later folding. | 2492 | // Undo the reorganisations, and pass the band on for later folding. |
| 2464 | if stereo { | 2493 | if stereo { |
| 2465 | if n != 2 { | 2494 | if n != 2 { |
| 2466 | - stereo_merge(&mut self.x, x, y.ok_or_else(|| Error::corrupt(INV_SIDE))?, mid, n); | 2495 | + stereo_merge( |
| 2496 | + &mut self.x, | ||
| 2497 | + x, | ||
| 2498 | + y.ok_or_else(|| Error::corrupt(INV_SIDE))?, | ||
| 2499 | + mid, | ||
| 2500 | + n, | ||
| 2501 | + ); | ||
| 2467 | } | 2502 | } |
| 2468 | if inv { | 2503 | if inv { |
| 2469 | let ys = y.ok_or_else(|| Error::corrupt(INV_SIDE))?; | 2504 | let ys = y.ok_or_else(|| Error::corrupt(INV_SIDE))?; |
| @@ -2540,8 +2575,8 @@ impl CeltDecoder { | |||
| 2540 | ) -> u32 { | 2575 | ) -> u32 { |
| 2541 | decode_pulses(dec, n, k, &mut self.iy); | 2576 | decode_pulses(dec, n, k, &mut self.iy); |
| 2542 | let mut ryy = 0.0f32; | 2577 | let mut ryy = 0.0f32; |
| 2543 | - for j in 0..n { | 2578 | + for &v in &self.iy[..n] { |
| 2544 | - ryy += (self.iy[j] * self.iy[j]) as f32; | 2579 | + ryy += (v * v) as f32; |
| 2545 | } | 2580 | } |
| 2546 | let g = gain / ryy.sqrt(); | 2581 | let g = gain / ryy.sqrt(); |
| 2547 | for j in 0..n { | 2582 | for j in 0..n { |
| @@ -2648,7 +2683,6 @@ impl CeltDecoder { | |||
| 2648 | } | 2683 | } |
| 2649 | } | 2684 | } |
| 2650 | 2685 | ||
| 2651 | - #[allow(clippy::too_many_arguments)] | ||
| 2652 | #[allow(clippy::too_many_arguments)] | 2686 | #[allow(clippy::too_many_arguments)] |
| 2653 | fn comb_filter( | 2687 | fn comb_filter( |
| 2654 | &mut self, | 2688 | &mut self, |
| @@ -3084,11 +3118,7 @@ pub(crate) fn bits2pulses(band: usize, lm: i32, bits: i32) -> i32 { | |||
| 3084 | lo = mid; | 3118 | lo = mid; |
| 3085 | } | 3119 | } |
| 3086 | } | 3120 | } |
| 3087 | - let lo_cost = if lo == 0 { | 3121 | + let lo_cost = if lo == 0 { -1 } else { row[lo as usize] as i32 }; |
| 3088 | - -1 | ||
| 3089 | - } else { | ||
| 3090 | - row[lo as usize] as i32 | ||
| 3091 | - }; | ||
| 3092 | if bits - lo_cost <= row[hi as usize] as i32 - bits { | 3122 | if bits - lo_cost <= row[hi as usize] as i32 - bits { |
| 3093 | lo | 3123 | lo |
| 3094 | } else { | 3124 | } else { |
| @@ -3404,8 +3434,12 @@ mod tests { | |||
| 3404 | // U(N,K) = U(N-1,K) + U(N,K-1) + U(N-1,K-1). | 3434 | // U(N,K) = U(N-1,K) + U(N,K-1) + U(N-1,K-1). |
| 3405 | for n in 3..8usize { | 3435 | for n in 3..8usize { |
| 3406 | for k in 2..8usize { | 3436 | for k in 2..8usize { |
| 3407 | - let (v1, v2, v3, v) = | 3437 | + let (v1, v2, v3, v) = ( |
| 3408 | - (pvq_v(n - 1, k), pvq_v(n, k - 1), pvq_v(n - 1, k - 1), pvq_v(n, k)); | 3438 | + pvq_v(n - 1, k), |
| 3439 | + pvq_v(n, k - 1), | ||
| 3440 | + pvq_v(n - 1, k - 1), | ||
| 3441 | + pvq_v(n, k), | ||
| 3442 | + ); | ||
| 3409 | assert_eq!(v, v1.wrapping_add(v2).wrapping_add(v3), "V({n},{k})"); | 3443 | assert_eq!(v, v1.wrapping_add(v2).wrapping_add(v3), "V({n},{k})"); |
| 3410 | } | 3444 | } |
| 3411 | } | 3445 | } |
crates/ec-opus/src/celt_enc.rsdeleted+0 -3120
Diff too large; view file
| @@ -1,3120 +0,0 @@ | |||
| 1 | -//! The CELT encoder — RFC 6716 Section 5.3, throughput-first. | ||
| 2 | -//! | ||
| 3 | -//! The *coding* path — every symbol written, every `tell()` the bit allocation | ||
| 4 | -//! reads — mirrors the normative reference (RFC 6716 Appendix A) exactly, | ||
| 5 | -//! because the decoder derives the allocation from the same arithmetic and one | ||
| 6 | -//! bit of drift desynchronises the frame. The *analysis* path is where this | ||
| 7 | -//! encoder buys its speed, with fast deterministic heuristics in place of the | ||
| 8 | -//! reference's searches: | ||
| 9 | -//! | ||
| 10 | -//! - **No pitch prefilter.** The postfilter-off bit is coded every frame, | ||
| 11 | -//! which removes the most expensive analysis in the reference encoder (an | ||
| 12 | -//! autocorrelation search over 1024 lags). Same choice the reference makes | ||
| 13 | -//! below complexity 5. | ||
| 14 | -//! - **Time/frequency Viterbi ported and enabled.** `tf_analysis()` and the | ||
| 15 | -//! libopus float-mode `transient_analysis()` (returning `tf_estimate`/ | ||
| 16 | -//! `tf_chan`) are ported from the reference; `const TF_ANALYSIS: bool` | ||
| 17 | -//! gates the Viterbi search. It is `true`: `dynalloc_analysis()` computes | ||
| 18 | -//! per-band `importance[]` and feeds it to the search, matching the | ||
| 19 | -//! reference's analysis path. | ||
| 20 | -//! - **Fixed spreading.** `SPREAD_NORMAL` every frame, coded explicitly. | ||
| 21 | -//! - **Coarse energy**: the reference's two-pass encode-both-and-compare is | ||
| 22 | -//! ported (`TWO_PASS_COARSE_ENERGY`) but ships off — it measured mixed on | ||
| 23 | -//! the library gate's err_ratio; the delayed-intra heuristic decides. | ||
| 24 | -//! | ||
| 25 | -//! What stays: transient detection, the closed-form allocation-trim and | ||
| 26 | -//! dynalloc spike heuristics, the stereo-mode analysis, intensity thresholds | ||
| 27 | -//! and constrained-VBR reservoir — all cheap O(frame) arithmetic that decides | ||
| 28 | -//! *rates*, not searches. | ||
| 29 | -//! | ||
| 30 | -//! Steady state allocates nothing: every buffer is owned by the encoder and | ||
| 31 | -//! sized at construction. | ||
| 32 | - | ||
| 33 | -use ec_core::{Error, Result}; | ||
| 34 | - | ||
| 35 | -use crate::analysis::AnalysisInfo; | ||
| 36 | -use crate::celt::{ | ||
| 37 | - self, BETA_COEF, BETA_INTRA, BITRES, CACHE_CAPS, E_BANDS, E_MEANS, E_PROB_MODEL, LOG_N, | ||
| 38 | - MAX_FINE_BITS, NB_BANDS, OVERLAP, PRED_COEF, PREEMPH, QTHETA_OFFSET, QTHETA_OFFSET_TWOPHASE, | ||
| 39 | - SHORT_MDCT, SIG_SCALE, SMALL_ENERGY_ICDF, SPREAD_AGGRESSIVE, SPREAD_ICDF, SPREAD_LIGHT, | ||
| 40 | - SPREAD_NONE, SPREAD_NORMAL, TF_SELECT, TRIM_ICDF, bitexact_cos, bitexact_log2tan, bits2pulses, | ||
| 41 | - cache_index, compute_allocation_encode, compute_qn, deinterleave_hadamard, exp_rotation, | ||
| 42 | - frac_mul16, get_pulses, haar1, pulses2bits, | ||
| 43 | -}; | ||
| 44 | -use crate::range::RangeEncoder; | ||
| 45 | - | ||
| 46 | -/// `EC_OPUS_TRIM13` override of the continuous allocation trim. | ||
| 47 | -fn trim13_env() -> Option<bool> { | ||
| 48 | - static P: std::sync::OnceLock<Option<bool>> = std::sync::OnceLock::new(); | ||
| 49 | - *P.get_or_init(|| std::env::var("EC_OPUS_TRIM13").ok().map(|v| v != "0")) | ||
| 50 | -} | ||
| 51 | - | ||
| 52 | -/// TF-boost sweep knobs (lane opustr2): `k * (tf_estimate - off) * target`, | ||
| 53 | -/// optionally applied only on frames the transient analysis flagged (other | ||
| 54 | -/// frames keep the shipped k=1). Read once from the environment; | ||
| 55 | -/// `EC_OPUS_TF_K` / `EC_OPUS_TF_OFF` / `EC_OPUS_TF_GATE=transient` / | ||
| 56 | -/// `EC_OPUS_TF_THRESH` (k applies only from that `tf_estimate` up). | ||
| 57 | -fn tf_boost_params() -> (f32, f32, bool, f32) { | ||
| 58 | - static P: std::sync::OnceLock<(f32, f32, bool, f32)> = std::sync::OnceLock::new(); | ||
| 59 | - *P.get_or_init(|| { | ||
| 60 | - let f = |name: &str, dflt: f32| { | ||
| 61 | - std::env::var(name) | ||
| 62 | - .ok() | ||
| 63 | - .and_then(|v| v.parse().ok()) | ||
| 64 | - .unwrap_or(dflt) | ||
| 65 | - }; | ||
| 66 | - let gate = std::env::var("EC_OPUS_TF_GATE") | ||
| 67 | - .map(|v| v == "transient") | ||
| 68 | - .unwrap_or(false); | ||
| 69 | - ( | ||
| 70 | - f("EC_OPUS_TF_K", 1.0), | ||
| 71 | - f("EC_OPUS_TF_OFF", 0.044), | ||
| 72 | - gate, | ||
| 73 | - f("EC_OPUS_TF_THRESH", 0.0), | ||
| 74 | - ) | ||
| 75 | - }) | ||
| 76 | -} | ||
| 77 | - | ||
| 78 | -/// Which consumers of the [`crate::analysis`] tonality analysis are live. | ||
| 79 | -/// | ||
| 80 | -/// The analysis itself runs whenever `EC_OPUS_ANALYSIS` is not `0`; each | ||
| 81 | -/// downstream term was measured on the 12-row library gate on its own, so | ||
| 82 | -/// each keeps its own switch (`1`/`0`) around the shipped default: | ||
| 83 | -/// `EC_OPUS_TRIM_TONAL` (`alloc_trim`'s `tonality_slope` term), | ||
| 84 | -/// `EC_OPUS_TRIM13` (the continuous 1.3 trim the term belongs to), | ||
| 85 | -/// `EC_OPUS_VBR_TONAL` (`compute_vbr`'s tonality boost) and | ||
| 86 | -/// `EC_OPUS_VBR_ACT` (`compute_vbr`'s low-activity cut), | ||
| 87 | -/// `EC_OPUS_LEAK` (`dynalloc_analysis`'s per-band leakage boost) and | ||
| 88 | -/// `EC_OPUS_BW_DETECT` (the detected bandwidth lowering the coded one). | ||
| 89 | -/// | ||
| 90 | -/// MEASURED (lane opustonal, four detached 12-row library-gate runs against | ||
| 91 | -/// the shipped rows `lanes/opus-opustr2-r1.sweep.txt`). The analysis itself is | ||
| 92 | -/// byte-neutral -- no consumer reads it unless its own switch is on -- and | ||
| 93 | -/// **every consumer arm is rejected by the KEEP rule**, so all three default | ||
| 94 | -/// off. err_ratio, better rows first, blocking rows named: | ||
| 95 | -/// | ||
| 96 | -/// | arm | better | blocking | | ||
| 97 | -/// |---|---|---| | ||
| 98 | -/// | 1.3 trim + tonality term (`-r1`) | nik@64 .708→.647, reelo@64 1.510→1.071, reelo@96 .940→.898, reell@96 4.499→2.458, dl8a .552/.374→.512/.336 | nik@96 .985→1.006, her@64 1.103→1.109, her@96 1.051→1.085, reell@64 2.697→2.872 | | ||
| 99 | -/// | vbr tonality + activity (`-r2`) | hein@64 .853→.327, hein@96 .528→.426, nik@64 →.672, dl8a@64 →.541 | nik@96 →1.061, reelo@96 →1.165, her@64 →1.104, her@96 →1.060, dl8a@96 →.414 | | ||
| 100 | -/// | vbr activity alone (`-r3`) | hein@64 →.430, hein@96 →.408, nik@64 →.657, dl8a@64 →.511 | nik@96 →.990, her@64 →1.104, her@96 →1.071, dl8a@96 →.382 | | ||
| 101 | -/// | `EC_OPUS_BW_DETECT` (`opusmode -r1`) | -- | -- (byte-identical: `analysis.bandwidth` is 20 on every valid frame of every gate source, so the clamp never fires) | | ||
| 102 | -/// | `EC_OPUS_LEAK` (`opusmode -r2`) | -- | nik@64 .708→.709, nik@96 .985→.986, her@96 1.051→1.052 (the rest identical) | | ||
| 103 | -/// | `EC_OPUS_BW_DETECT` + `EC_OPUS_VBR_ACT` + `EC_OPUS_TF_K=1.25` (`opusmode -r3`) | reell@96 4.499→2.516, reell@64 2.697→1.440, hein@64 .853→.470, hein@96 .528→.404, dl8a@96 .374→.315, dl8a@64 →.535, nik@64 →.651, **nik@96 .985→.957**, reelo@96 →.928, reelo@64 →1.509 | her@96 1.051→1.071, her@64 1.103→1.104 | | ||
| 104 | -/// | all four + `EC_OPUS_ALIGN=1` (`-r4`) | reell@64 →1.865, reell@96 →3.986, reelo@64 →1.123, reelo@96 →.891, her@64 →.952 | nik@64 →1.014, nik@96 →1.842, her@96 →1.217, dl8a →1.162/.988, hein →.971/1.514 | | ||
| 105 | -/// | ||
| 106 | -/// `corr_ours` is never worse by more than .0005 on any unaligned arm (it is | ||
| 107 | -/// *better* on every row of `-r2`/`-r3`), so corr is not what rejects them. | ||
| 108 | -/// The `alloc_trim` term is small by construction -- `tonality_slope` averages | ||
| 109 | -/// -.09 (speech) to -.17 (music), so the term is ±.08 of a trim step and | ||
| 110 | -/// rounds away entirely on the shipped discrete ladder, which is why no | ||
| 111 | -/// discrete-ladder arm was run. The activity cut is the nearest miss ever | ||
| 112 | -/// measured on this gate for a speech source (hein halves) and is blocked by | ||
| 113 | -/// her@96 +.020 and nik@96 +.005 -- the same two rows that have blocked the | ||
| 114 | -/// The combined arm (`opusmode -r3`) is the first arm ever measured on this | ||
| 115 | -/// gate that moves a blocking row the right way: nik@96 .985→.957. It is | ||
| 116 | -/// **rejected by the per-row KEEP rule** (her@96 +.020, her@64 +.001) and | ||
| 117 | -/// **passes the aggregate rule** (geometric-mean err_ratio 1.0218→0.8378, | ||
| 118 | -/// -18.0%; worst row her@96 +1.9%, under the 5% bound; `corr_ours` within | ||
| 119 | -/// .0001 on every row). Which rule ships is the user's call; the default is | ||
| 120 | -/// off either way. Aligned, the analysis moves reell/reelo/her@64 a long way but leaves | ||
| 121 | -/// the aligned blocking set (nik, her@96, dl8a, hein) exactly where the | ||
| 122 | -/// analysis-free aligned arms left it, so the alignment default stays off. | ||
| 123 | -pub(crate) fn analysis_params() -> (bool, bool, bool, bool, bool, bool) { | ||
| 124 | - static P: std::sync::OnceLock<(bool, bool, bool, bool, bool, bool)> = | ||
| 125 | - std::sync::OnceLock::new(); | ||
| 126 | - *P.get_or_init(|| { | ||
| 127 | - let b = |name: &str, dflt: bool| std::env::var(name).map(|v| v != "0").unwrap_or(dflt); | ||
| 128 | - let trim = b("EC_OPUS_TRIM_TONAL", true); | ||
| 129 | - let vbr_tonal = b("EC_OPUS_VBR_TONAL", false); | ||
| 130 | - let vbr_act = b("EC_OPUS_VBR_ACT", false); | ||
| 131 | - // The analysis costs ~25% of the encoder (5.1 384k: 126x -> 100x | ||
| 132 | - // realtime), so it only runs when something reads it: any consumer | ||
| 133 | - // switch, an explicit `EC_OPUS_ANALYSIS=1`, or | ||
| 134 | - // `Encoder::set_analysis(true)` for the diagnostics. | ||
| 135 | - let leak = b("EC_OPUS_LEAK", true); | ||
| 136 | - let bw = b("EC_OPUS_BW_DETECT", false); | ||
| 137 | - let any = trim || vbr_tonal || vbr_act || leak || bw; | ||
| 138 | - ( | ||
| 139 | - b("EC_OPUS_ANALYSIS", any), | ||
| 140 | - trim, | ||
| 141 | - vbr_tonal, | ||
| 142 | - vbr_act, | ||
| 143 | - leak, | ||
| 144 | - bw, | ||
| 145 | - ) | ||
| 146 | - }) | ||
| 147 | -} | ||
| 148 | - | ||
| 149 | -const CACHE_BITS: &[u8] = &crate::celt::CACHE_BITS; | ||
| 150 | -const INV_TABLE: [u8; 128] = [ | ||
| 151 | - 255, 255, 156, 110, 86, 70, 59, 51, 45, 40, 37, 33, 31, 28, 26, 25, 23, 22, 21, 20, 19, 18, 17, | ||
| 152 | - 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, | ||
| 153 | - 8, 8, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, | ||
| 154 | - 5, 5, 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, 3, 3, 3, | ||
| 155 | - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, | ||
| 156 | -]; | ||
| 157 | - | ||
| 158 | -// --------------------------------------------------------------------------- | ||
| 159 | -// Forward MDCT | ||
| 160 | -// --------------------------------------------------------------------------- | ||
| 161 | - | ||
| 162 | -/// One forward-MDCT plan, the exact adjoint of the decoder's `ImdctPlan`: | ||
| 163 | -/// window-fold, pre-rotation, an `l/2`-point FFT and post-rotation, scaled by | ||
| 164 | -/// `2/l` so that decode(encode(x)) reconstructs at unit gain. | ||
| 165 | -/// libopus `opus_encoder.c`'s `delay_compensation = Fs/250`: how far behind | ||
| 166 | -/// the API frame the CELT analysis window sits, in 48 kHz samples. | ||
| 167 | -const CELT_DELAY_48K: usize = 192; | ||
| 168 | - | ||
| 169 | -#[derive(Clone, Debug)] | ||
| 170 | -struct MdctPlan { | ||
| 171 | - l: usize, | ||
| 172 | - fft: celt::Fft15, | ||
| 173 | - rot_re: Vec<f32>, | ||
| 174 | - rot_im: Vec<f32>, | ||
| 175 | - fre: Vec<f32>, | ||
| 176 | - fim: Vec<f32>, | ||
| 177 | - t: Vec<f32>, | ||
| 178 | -} | ||
| 179 | - | ||
| 180 | -impl MdctPlan { | ||
| 181 | - fn new(l: usize) -> MdctPlan { | ||
| 182 | - let n = 2 * l; | ||
| 183 | - let quarter = l / 2; | ||
| 184 | - let mut rot_re = vec![0.0; quarter]; | ||
| 185 | - let mut rot_im = vec![0.0; quarter]; | ||
| 186 | - for i in 0..quarter { | ||
| 187 | - let a = 2.0 * core::f64::consts::PI * (i as f64 + 0.125) / n as f64; | ||
| 188 | - rot_re[i] = a.cos() as f32; | ||
| 189 | - rot_im[i] = a.sin() as f32; | ||
| 190 | - } | ||
| 191 | - MdctPlan { | ||
| 192 | - l, | ||
| 193 | - fft: celt::Fft15::new(quarter), | ||
| 194 | - rot_re, | ||
| 195 | - rot_im, | ||
| 196 | - fre: vec![0.0; quarter], | ||
| 197 | - fim: vec![0.0; quarter], | ||
| 198 | - t: vec![0.0; l], | ||
| 199 | - } | ||
| 200 | - } | ||
| 201 | - | ||
| 202 | - /// Transforms `l + OVERLAP` time samples starting at `input[off]` — the | ||
| 203 | - /// support of the low-overlap window — into `l` MDCT coefficients written | ||
| 204 | - /// at `out[out_off + k*stride]`. | ||
| 205 | - fn forward( | ||
| 206 | - &mut self, | ||
| 207 | - input: &[f32], | ||
| 208 | - off: usize, | ||
| 209 | - window: &[f32], | ||
| 210 | - out: &mut [f32], | ||
| 211 | - out_off: usize, | ||
| 212 | - stride: usize, | ||
| 213 | - ) { | ||
| 214 | - let l = self.l; | ||
| 215 | - let quarter = l / 2; | ||
| 216 | - let flat = quarter - OVERLAP / 2; | ||
| 217 | - let mirror = quarter + OVERLAP / 2; | ||
| 218 | - let t = &mut self.t; | ||
| 219 | - // Window fold: the adjoint of the inverse's scatter, so every | ||
| 220 | - // coefficient, sign and window position matches by construction. | ||
| 221 | - for i in 0..flat { | ||
| 222 | - t[quarter - 1 - i] = input[off + mirror - 1 - i]; | ||
| 223 | - } | ||
| 224 | - for i in flat..quarter { | ||
| 225 | - let w = i - flat; | ||
| 226 | - t[quarter - 1 - i] = | ||
| 227 | - -window[w] * input[off + w] + window[OVERLAP - 1 - w] * input[off + mirror - 1 - i]; | ||
| 228 | - } | ||
| 229 | - for i in 0..flat { | ||
| 230 | - t[quarter + i] = input[off + mirror + i]; | ||
| 231 | - } | ||
| 232 | - for i in flat..quarter { | ||
| 233 | - let w = i - flat; | ||
| 234 | - t[quarter + i] = window[w] * input[off + l + OVERLAP - 1 - w] | ||
| 235 | - + window[OVERLAP - 1 - w] * input[off + mirror + i]; | ||
| 236 | - } | ||
| 237 | - // Shuffle into the complex FFT input. | ||
| 238 | - for i in 0..quarter { | ||
| 239 | - self.fre[i] = -t[2 * i]; | ||
| 240 | - self.fim[i] = t[2 * (quarter - 1 - i) + 1]; | ||
| 241 | - } | ||
| 242 | - // Rotate by -theta (adjoint of the inverse's post-rotation). | ||
| 243 | - for i in 0..quarter { | ||
| 244 | - let (c, s) = (self.rot_re[i], self.rot_im[i]); | ||
| 245 | - let (re, im) = (self.fre[i], self.fim[i]); | ||
| 246 | - self.fre[i] = re * c + im * s; | ||
| 247 | - self.fim[i] = im * c - re * s; | ||
| 248 | - } | ||
| 249 | - // Forward FFT = conjugate, +i-convention FFT, conjugate. | ||
| 250 | - for v in self.fim.iter_mut() { | ||
| 251 | - *v = -*v; | ||
| 252 | - } | ||
| 253 | - self.fft.inverse(&mut self.fre, &mut self.fim); | ||
| 254 | - for v in self.fim.iter_mut() { | ||
| 255 | - *v = -*v; | ||
| 256 | - } | ||
| 257 | - // Adjoint of the pre-rotation, with the 2/l forward scaling CELT puts | ||
| 258 | - // on this side of the transform. | ||
| 259 | - let scale = 2.0 / l as f32; | ||
| 260 | - for i in 0..quarter { | ||
| 261 | - let (c, s) = (self.rot_re[i], self.rot_im[i]); | ||
| 262 | - let (re, im) = (self.fre[i], self.fim[i]); | ||
| 263 | - out[out_off + (2 * i) * stride] = scale * (s * re - c * im); | ||
| 264 | - out[out_off + (l - 1 - 2 * i) * stride] = scale * (-c * re - s * im); | ||
| 265 | - } | ||
| 266 | - } | ||
| 267 | -} | ||
| 268 | - | ||
| 269 | -// --------------------------------------------------------------------------- | ||
| 270 | -// Symbol-level helpers | ||
| 271 | -// --------------------------------------------------------------------------- | ||
| 272 | - | ||
| 273 | -/// `ec_laplace_encode()`: the coarse-energy prediction error. May clamp | ||
| 274 | -/// `value`, which is why it is passed back. | ||
| 275 | -fn laplace_encode(enc: &mut RangeEncoder, value: &mut i32, mut fs: u32, decay: i32) -> i32 { | ||
| 276 | - const MINP: u32 = 1; | ||
| 277 | - const NMIN: u32 = 16; | ||
| 278 | - let mut fl = 0u32; | ||
| 279 | - let mut val = *value; | ||
| 280 | - if val != 0 { | ||
| 281 | - let s = if val < 0 { -1i32 } else { 0 }; | ||
| 282 | - val = (val + s) ^ s; | ||
| 283 | - fl = fs; | ||
| 284 | - let fs0 = fs; | ||
| 285 | - fs = ((32768 - MINP * (2 * NMIN) - fs0) * (16384 - decay as u32)) >> 15; | ||
| 286 | - // Search the decaying part of the pdf. | ||
| 287 | - let mut i = 1i32; | ||
| 288 | - while fs > 0 && i < val { | ||
| 289 | - fs *= 2; | ||
| 290 | - fl += fs + 2 * MINP; | ||
| 291 | - fs = (fs * decay as u32) >> 15; | ||
| 292 | - i += 1; | ||
| 293 | - } | ||
| 294 | - if fs == 0 { | ||
| 295 | - // Everything beyond has probability MINP. | ||
| 296 | - let mut ndi_max = (32768 - fl + MINP - 1) as i32; | ||
| 297 | - ndi_max = (ndi_max - s) >> 1; | ||
| 298 | - let di = (val - i).min(ndi_max - 1); | ||
| 299 | - fl += ((2 * di + 1 + s) as u32) * MINP; | ||
| 300 | - fs = MINP.min(32768 - fl); | ||
| 301 | - *value = (i + di + s) ^ s; | ||
| 302 | - } else { | ||
| 303 | - fs += MINP; | ||
| 304 | - if s == 0 { | ||
| 305 | - fl += fs; | ||
| 306 | - } | ||
| 307 | - } | ||
| 308 | - debug_assert!(fl + fs <= 32768); | ||
| 309 | - debug_assert!(fs > 0); | ||
| 310 | - } | ||
| 311 | - enc.encode_bin(fl, fl + fs, 15); | ||
| 312 | - *value | ||
| 313 | -} | ||
| 314 | - | ||
| 315 | -/// `encode_pulses()` for the general case: index the pulse vector in the | ||
| 316 | -/// V(N,K) enumeration and code it as one uniform symbol (Section 5.3.4). | ||
| 317 | -fn encode_pulses(enc: &mut RangeEncoder, iy: &[i32], n: usize, k: usize) { | ||
| 318 | - debug_assert!(n >= 2 && k > 0); | ||
| 319 | - let mut j = n - 1; | ||
| 320 | - let mut i = u32::from(iy[j] < 0); | ||
| 321 | - let mut kk = iy[j].unsigned_abs() as usize; | ||
| 322 | - while j > 0 { | ||
| 323 | - j -= 1; | ||
| 324 | - // The row the reference stepping left in place at this dimension is | ||
| 325 | - // `U(n - j, .)`; read it from the table instead. | ||
| 326 | - i = i.wrapping_add(celt::pvq_u(n - j, kk)); | ||
| 327 | - kk += iy[j].unsigned_abs() as usize; | ||
| 328 | - if iy[j] < 0 { | ||
| 329 | - i = i.wrapping_add(celt::pvq_u(n - j, kk + 1)); | ||
| 330 | - } | ||
| 331 | - } | ||
| 332 | - let nc = celt::pvq_v(n, kk); | ||
| 333 | - enc.enc_uint(i, nc.max(2)); | ||
| 334 | -} | ||
| 335 | - | ||
| 336 | -/// `stereo_itheta()`: the angle between mid and side (or the two halves of a | ||
| 337 | -/// split mono band), in Q14 (0..16384). | ||
| 338 | -fn stereo_itheta(x: &[f32], y: &[f32], stereo: bool, n: usize) -> i32 { | ||
| 339 | - let mut emid = 1e-15f32; | ||
| 340 | - let mut eside = 1e-15f32; | ||
| 341 | - if stereo { | ||
| 342 | - for j in 0..n { | ||
| 343 | - let m = x[j] + y[j]; | ||
| 344 | - let s = x[j] - y[j]; | ||
| 345 | - emid += m * m; | ||
| 346 | - eside += s * s; | ||
| 347 | - } | ||
| 348 | - } else { | ||
| 349 | - for j in 0..n { | ||
| 350 | - emid += x[j] * x[j]; | ||
| 351 | - eside += y[j] * y[j]; | ||
| 352 | - } | ||
| 353 | - } | ||
| 354 | - let mid = emid.sqrt(); | ||
| 355 | - let side = eside.sqrt(); | ||
| 356 | - // 0.63662 is the reference's own 2/pi literal (vq.c, stereo_itheta); the | ||
| 357 | - // exact constant would round a boundary theta differently. The angle is | ||
| 358 | - // the reference float build's `fast_atan2f` (the rational approximation | ||
| 359 | - // the tonality features share), which also keeps libm's `atan2` out of | ||
| 360 | - // the per-band loop. | ||
| 361 | - #[allow(clippy::approx_constant)] | ||
| 362 | - const TWO_OVER_PI: f32 = 0.63662; | ||
| 363 | - (TWO_OVER_PI * 16384.0 * crate::analysis::fast_atan2f(side, mid) + 0.5).floor() as i32 | ||
| 364 | -} | ||
| 365 | - | ||
| 366 | -/// `l1_metric()` from the reference: L1 norm scaled by `(1 + LM*bias)`. | ||
| 367 | -/// In float mode `MAC16_32_Q15(c, a*b) = c + a*b`, so this is `L1*(1 + LM*bias)`. | ||
| 368 | -fn l1_metric(tmp: &[f32], n: usize, lm: usize, bias: f32) -> f32 { | ||
| 369 | - let mut l1 = 0.0f32; | ||
| 370 | - for v in &tmp[..n] { | ||
| 371 | - l1 += v.abs(); | ||
| 372 | - } | ||
| 373 | - l1 * (1.0 + lm as f32 * bias) | ||
| 374 | -} | ||
| 375 | - | ||
| 376 | -// --------------------------------------------------------------------------- | ||
| 377 | -// The encoder | ||
| 378 | -// --------------------------------------------------------------------------- | ||
| 379 | - | ||
| 380 | -/// Arguments threaded through the band-encode recursion; the encode-side | ||
| 381 | -/// mirror of the decoder's `BandArgs`, minus everything only resynthesis | ||
| 382 | -/// needs (folding sources, gains, collapse fill). | ||
| 383 | -#[derive(Clone, Copy, Debug)] | ||
| 384 | -struct EncBand { | ||
| 385 | - i: usize, | ||
| 386 | - x: usize, | ||
| 387 | - y: Option<usize>, | ||
| 388 | - n: usize, | ||
| 389 | - b: i32, | ||
| 390 | - spread: usize, | ||
| 391 | - blocks: usize, | ||
| 392 | - intensity: usize, | ||
| 393 | - tf_change: i32, | ||
| 394 | - level: i32, | ||
| 395 | - lm: i32, | ||
| 396 | -} | ||
| 397 | - | ||
| 398 | -/// Per-frame encoder diagnostics for the dropout investigation. Captured at | ||
| 399 | -/// the end of `CeltEncoder::encode`; read via [`CeltEncoder::last_diag`]. | ||
| 400 | -#[derive(Clone, Debug)] | ||
| 401 | -pub struct CeltFrameDiag { | ||
| 402 | - /// Transient flag as coded into the bitstream. | ||
| 403 | - pub is_transient: bool, | ||
| 404 | - /// `short_blocks` (0 = long, else `m` short blocks). | ||
| 405 | - pub short_blocks: usize, | ||
| 406 | - /// Coarse-energy intra-frame reset was used. | ||
| 407 | - pub intra: bool, | ||
| 408 | - /// The whole frame was coded as silence. | ||
| 409 | - pub silence: bool, | ||
| 410 | - /// Frame-size exponent (`120 << lm`). | ||
| 411 | - pub lm: usize, | ||
| 412 | - /// First/last coded band indices. | ||
| 413 | - pub start: usize, | ||
| 414 | - /// Highest band actually allocated pulses. | ||
| 415 | - pub coded_bands: usize, | ||
| 416 | - /// Stereo intensity band (bands >= this collapse to mono). | ||
| 417 | - pub intensity: usize, | ||
| 418 | - /// Dual-stereo (no mid/side folding) flag. | ||
| 419 | - pub dual_stereo: bool, | ||
| 420 | - /// Allocation trim index (0..10). | ||
| 421 | - pub alloc_trim: i32, | ||
| 422 | - /// Constrained-VBR reservoir level after this frame, in 1/8-bit units. | ||
| 423 | - pub vbr_reservoir: i32, | ||
| 424 | - /// Final compressed payload of this frame, in bytes. | ||
| 425 | - pub nb_compressed: usize, | ||
| 426 | - /// Per-band log2 energy minus `E_MEANS`, both channels (ch0 then ch1). | ||
| 427 | - pub band_log_e: [f32; 2 * NB_BANDS], | ||
| 428 | - /// Per-band allocated pulses (ch0/ch1 share for intensity bands). | ||
| 429 | - pub pulses: [i32; NB_BANDS], | ||
| 430 | - /// Per-band fine-energy precision bits. | ||
| 431 | - pub fine_quant: [i32; NB_BANDS], | ||
| 432 | - /// Whether the tonality analysis produced a usable window for this frame. | ||
| 433 | - pub analysis_valid: bool, | ||
| 434 | - /// `AnalysisInfo::music_prob` — 0 is speech, 1 is music. | ||
| 435 | - pub music_prob: f32, | ||
| 436 | - /// `AnalysisInfo::tonality`. | ||
| 437 | - pub tonality: f32, | ||
| 438 | - /// `AnalysisInfo::tonality_slope`, `alloc_trim`'s input. | ||
| 439 | - pub tonality_slope: f32, | ||
| 440 | - /// `AnalysisInfo::activity`, `compute_vbr`'s input. | ||
| 441 | - pub activity: f32, | ||
| 442 | - /// `AnalysisInfo::bandwidth`, the detected bandwidth band index. | ||
| 443 | - pub analysis_bandwidth: i32, | ||
| 444 | -} | ||
| 445 | - | ||
| 446 | -impl Default for CeltFrameDiag { | ||
| 447 | - fn default() -> Self { | ||
| 448 | - Self { | ||
| 449 | - is_transient: false, | ||
| 450 | - short_blocks: 0, | ||
| 451 | - intra: false, | ||
| 452 | - silence: false, | ||
| 453 | - lm: 0, | ||
| 454 | - start: 0, | ||
| 455 | - coded_bands: 0, | ||
| 456 | - intensity: 0, | ||
| 457 | - dual_stereo: false, | ||
| 458 | - alloc_trim: 0, | ||
| 459 | - vbr_reservoir: 0, | ||
| 460 | - nb_compressed: 0, | ||
| 461 | - band_log_e: [0.0; 2 * NB_BANDS], | ||
| 462 | - pulses: [0; NB_BANDS], | ||
| 463 | - fine_quant: [0; NB_BANDS], | ||
| 464 | - analysis_valid: false, | ||
| 465 | - music_prob: 0.0, | ||
| 466 | - tonality: 0.0, | ||
| 467 | - tonality_slope: 0.0, | ||
| 468 | - activity: 0.0, | ||
| 469 | - analysis_bandwidth: 0, | ||
| 470 | - } | ||
| 471 | - } | ||
| 472 | -} | ||
| 473 | - | ||
| 474 | -/// A CELT-layer encoder for one elementary Opus stream (mono or stereo). | ||
| 475 | -/// CELT itself always runs at 48 kHz; slower input is zero-stuffed up to it. | ||
| 476 | -#[derive(Clone, Debug)] | ||
| 477 | -pub struct CeltEncoder { | ||
| 478 | - channels: usize, | ||
| 479 | - stream_channels: usize, | ||
| 480 | - constrained_vbr: bool, | ||
| 481 | - silk_offset: i32, | ||
| 482 | - /// 48000 / input rate, 1 for native 48 kHz input. | ||
| 483 | - upsample: usize, | ||
| 484 | - window: Vec<f32>, | ||
| 485 | - plans: Vec<MdctPlan>, | ||
| 486 | - /// Preemphasised history, `channels * OVERLAP`. | ||
| 487 | - in_mem: Vec<f32>, | ||
| 488 | - /// libopus `opus_encoder.c`'s `delay_buffer`: the CELT layer is fed the | ||
| 489 | - /// input delayed by `delay_compensation = Fs/250` (192 samples at 48 kHz), | ||
| 490 | - /// so its analysis window sits 4 ms behind the API frame. Interleaved, | ||
| 491 | - /// `CELT_DELAY_48K / upsample` samples per channel. | ||
| 492 | - delay_buf: Vec<f32>, | ||
| 493 | - /// Whether that delay is applied at all — see | ||
| 494 | - /// [`crate::Encoder::set_libopus_input_alignment`] for why it ships off. | ||
| 495 | - align_input: bool, | ||
| 496 | - preemph_mem: [f32; 2], | ||
| 497 | - /// Coarse-energy prediction state, `2 * NB_BANDS`. | ||
| 498 | - old_band_e: Vec<f32>, | ||
| 499 | - delayed_intra: f32, | ||
| 500 | - consec_transient: u32, | ||
| 501 | - // Spreading decision state (libopus celt_encoder.c:2534-2537). | ||
| 502 | - spread_decision: usize, | ||
| 503 | - tonal_average: i32, | ||
| 504 | - hf_average: i32, | ||
| 505 | - tapset_decision: i32, | ||
| 506 | - last_coded_bands: usize, | ||
| 507 | - force_intra: bool, | ||
| 508 | - // Constrained-VBR reservoir. | ||
| 509 | - vbr_reservoir: i32, | ||
| 510 | - vbr_drift: i32, | ||
| 511 | - vbr_offset: i32, | ||
| 512 | - vbr_count: i32, | ||
| 513 | - /// libopus `st->stereo_saving` — mid/side bit-saving estimate (Q8 in C, | ||
| 514 | - /// plain f32 here), updated in `alloc_trim_analysis`. | ||
| 515 | - stereo_saving: f32, | ||
| 516 | - /// libopus `st->spec_avg` — temporal-VBR follower average, updated each frame. | ||
| 517 | - spec_avg: f32, | ||
| 518 | - // Per-frame scratch, allocated once. | ||
| 519 | - in_buf: Vec<f32>, | ||
| 520 | - freq: Vec<f32>, | ||
| 521 | - x: Vec<f32>, | ||
| 522 | - band_e: Vec<f32>, | ||
| 523 | - band_log_e: Vec<f32>, | ||
| 524 | - /// Long-window log energies used by dynalloc (`bandLogE2`). | ||
| 525 | - band_log_e2: Vec<f32>, | ||
| 526 | - /// Coarse-energy two-pass scratch: state before the first pass, and the | ||
| 527 | - /// intra pass's results while the inter pass overwrites the live arrays. | ||
| 528 | - old_e_save: Vec<f32>, | ||
| 529 | - old_e_intra: Vec<f32>, | ||
| 530 | - error_intra: Vec<f32>, | ||
| 531 | - /// Bytes the intra pass wrote, kept while the inter pass is tried. | ||
| 532 | - coarse_bytes: Vec<u8>, | ||
| 533 | - /// Previous intensity decision (hysteresis state, libopus `st->intensity`). | ||
| 534 | - intensity: usize, | ||
| 535 | - error: Vec<f32>, | ||
| 536 | - transient_tmp: Vec<f32>, | ||
| 537 | - hadamard_tmp: Vec<f32>, | ||
| 538 | - tf_res: [i32; NB_BANDS], | ||
| 539 | - pulses: [i32; NB_BANDS], | ||
| 540 | - fine_quant: [i32; NB_BANDS], | ||
| 541 | - fine_priority: [i32; NB_BANDS], | ||
| 542 | - offsets: [i32; NB_BANDS], | ||
| 543 | - caps: [i32; NB_BANDS], | ||
| 544 | - iy: Vec<i32>, | ||
| 545 | - pvq_y: Vec<f32>, | ||
| 546 | - pvq_sign: Vec<i32>, | ||
| 547 | - /// Per-frame diagnostics captured at the end of the last `encode` call. | ||
| 548 | - last_diag: CeltFrameDiag, | ||
| 549 | - /// libopus `st->analysis`'s per-frame output, handed in by | ||
| 550 | - /// [`crate::Encoder`] (which owns the estimator and runs it once per API | ||
| 551 | - /// frame, libopus's order); the `valid == false` default when the | ||
| 552 | - /// analysis is off. | ||
| 553 | - info: AnalysisInfo, | ||
| 554 | -} | ||
| 555 | - | ||
| 556 | -impl CeltEncoder { | ||
| 557 | - /// An encoder for `channels` channels (1 or 2) fed at `48000/upsample` Hz. | ||
| 558 | - pub fn new(channels: usize, upsample: usize) -> CeltEncoder { | ||
| 559 | - assert!((1..=2).contains(&channels)); | ||
| 560 | - assert!(upsample >= 1); | ||
| 561 | - let max_n = SHORT_MDCT * 8; | ||
| 562 | - CeltEncoder { | ||
| 563 | - channels, | ||
| 564 | - stream_channels: channels, | ||
| 565 | - constrained_vbr: true, | ||
| 566 | - silk_offset: 0, | ||
| 567 | - upsample, | ||
| 568 | - window: celt::overlap_window(), | ||
| 569 | - plans: (0..4).map(|lm| MdctPlan::new(SHORT_MDCT << lm)).collect(), | ||
| 570 | - in_mem: vec![0.0; channels * OVERLAP], | ||
| 571 | - delay_buf: vec![0.0; channels * CELT_DELAY_48K], | ||
| 572 | - align_input: false, | ||
| 573 | - preemph_mem: [0.0; 2], | ||
| 574 | - old_band_e: vec![0.0; 2 * NB_BANDS], | ||
| 575 | - delayed_intra: 1.0, | ||
| 576 | - consec_transient: 0, | ||
| 577 | - last_coded_bands: 0, | ||
| 578 | - force_intra: true, | ||
| 579 | - spread_decision: SPREAD_NORMAL, | ||
| 580 | - tonal_average: 256, | ||
| 581 | - hf_average: 0, | ||
| 582 | - tapset_decision: 0, | ||
| 583 | - vbr_reservoir: 0, | ||
| 584 | - vbr_drift: 0, | ||
| 585 | - vbr_offset: 0, | ||
| 586 | - vbr_count: 0, | ||
| 587 | - stereo_saving: 0.0, | ||
| 588 | - spec_avg: 0.0, | ||
| 589 | - in_buf: vec![0.0; channels * (max_n + OVERLAP)], | ||
| 590 | - freq: vec![0.0; channels * max_n], | ||
| 591 | - x: vec![0.0; channels * max_n], | ||
| 592 | - band_e: vec![0.0; 2 * NB_BANDS], | ||
| 593 | - band_log_e: vec![0.0; 2 * NB_BANDS], | ||
| 594 | - band_log_e2: vec![0.0; 2 * NB_BANDS], | ||
| 595 | - old_e_save: vec![0.0; 2 * NB_BANDS], | ||
| 596 | - old_e_intra: vec![0.0; 2 * NB_BANDS], | ||
| 597 | - error_intra: vec![0.0; 2 * NB_BANDS], | ||
| 598 | - coarse_bytes: Vec::with_capacity(1275), | ||
| 599 | - intensity: 0, | ||
| 600 | - error: vec![0.0; 2 * NB_BANDS], | ||
| 601 | - transient_tmp: vec![0.0; max_n + OVERLAP], | ||
| 602 | - hadamard_tmp: vec![0.0; max_n], | ||
| 603 | - tf_res: [0; NB_BANDS], | ||
| 604 | - pulses: [0; NB_BANDS], | ||
| 605 | - fine_quant: [0; NB_BANDS], | ||
| 606 | - fine_priority: [0; NB_BANDS], | ||
| 607 | - offsets: [0; NB_BANDS], | ||
| 608 | - caps: [0; NB_BANDS], | ||
| 609 | - iy: vec![0; max_n], | ||
| 610 | - pvq_y: vec![0.0; max_n], | ||
| 611 | - pvq_sign: vec![0; max_n], | ||
| 612 | - last_diag: CeltFrameDiag::default(), | ||
| 613 | - info: AnalysisInfo::default(), | ||
| 614 | - } | ||
| 615 | - } | ||
| 616 | - | ||
| 617 | - /// Channels this encoder codes. | ||
| 618 | - pub fn channels(&self) -> usize { | ||
| 619 | - self.channels | ||
| 620 | - } | ||
| 621 | - | ||
| 622 | - pub(crate) fn set_stream_channels(&mut self, c: usize) { | ||
| 623 | - self.stream_channels = c.clamp(1, self.channels); | ||
| 624 | - } | ||
| 625 | - | ||
| 626 | - pub(crate) fn set_prediction(&mut self, level: u8) { | ||
| 627 | - self.force_intra = level == 0; | ||
| 628 | - } | ||
| 629 | - | ||
| 630 | - pub(crate) fn set_constrained_vbr(&mut self, on: bool) { | ||
| 631 | - self.constrained_vbr = on; | ||
| 632 | - } | ||
| 633 | - | ||
| 634 | - pub(crate) fn set_silk_offset(&mut self, offset: i32) { | ||
| 635 | - self.silk_offset = offset; | ||
| 636 | - } | ||
| 637 | - | ||
| 638 | - pub(crate) fn window(&self) -> &[f32] { | ||
| 639 | - &self.window | ||
| 640 | - } | ||
| 641 | - | ||
| 642 | - /// Diagnostics captured at the end of the most recent `encode` call. | ||
| 643 | - pub fn last_diag(&self) -> &CeltFrameDiag { | ||
| 644 | - &self.last_diag | ||
| 645 | - } | ||
| 646 | - | ||
| 647 | - /// Feeds the layer the input delayed by `CELT_DELAY_48K`, as libopus | ||
| 648 | - /// does; see [`crate::Encoder::set_libopus_input_alignment`]. | ||
| 649 | - pub fn set_align_input(&mut self, on: bool) { | ||
| 650 | - self.align_input = on; | ||
| 651 | - } | ||
| 652 | - | ||
| 653 | - /// Drops all inter-frame state. | ||
| 654 | - pub fn reset(&mut self) { | ||
| 655 | - self.in_mem.fill(0.0); | ||
| 656 | - self.delay_buf.fill(0.0); | ||
| 657 | - self.preemph_mem = [0.0; 2]; | ||
| 658 | - self.old_band_e.fill(0.0); | ||
| 659 | - self.delayed_intra = 1.0; | ||
| 660 | - self.consec_transient = 0; | ||
| 661 | - self.last_coded_bands = 0; | ||
| 662 | - self.force_intra = true; | ||
| 663 | - self.spread_decision = SPREAD_NORMAL; | ||
| 664 | - self.tonal_average = 256; | ||
| 665 | - self.hf_average = 0; | ||
| 666 | - self.tapset_decision = 0; | ||
| 667 | - self.vbr_reservoir = 0; | ||
| 668 | - self.vbr_drift = 0; | ||
| 669 | - self.vbr_offset = 0; | ||
| 670 | - self.vbr_count = 0; | ||
| 671 | - self.stereo_saving = 0.0; | ||
| 672 | - self.spec_avg = 0.0; | ||
| 673 | - self.info = AnalysisInfo::default(); | ||
| 674 | - } | ||
| 675 | - | ||
| 676 | - /// Encodes one frame of interleaved `f32` (`frame_size` samples per | ||
| 677 | - /// channel at 48 kHz, one of 120/240/480/960 — of which | ||
| 678 | - /// `frame_size/upsample` are read from `pcm`) into `enc`, which must have | ||
| 679 | - /// been `reset` to the frame's byte budget. `start..end` bounds the coded | ||
| 680 | - /// bands — `end` is how the caller limits the coded bandwidth, `start` | ||
| 681 | - /// (0, or 17 under a hybrid packet's SILK layer) skips the low bands | ||
| 682 | - /// exactly as the decoder's `start_band` does: no energy, no shapes, no | ||
| 683 | - /// postfilter bit, allocation over the coded span only. With | ||
| 684 | - /// `vbr_rate_bps` set, the frame may be shrunk below that budget | ||
| 685 | - /// (constrained VBR); the return value is the final frame size in bytes. | ||
| 686 | - // The encoder entry point takes the per-frame knobs the caller owns, one argument each. | ||
| 687 | - #[allow(clippy::too_many_arguments)] | ||
| 688 | - pub(crate) fn encode( | ||
| 689 | - &mut self, | ||
| 690 | - enc: &mut RangeEncoder, | ||
| 691 | - pcm: &[f32], | ||
| 692 | - frame_size: usize, | ||
| 693 | - start: usize, | ||
| 694 | - end: usize, | ||
| 695 | - vbr_rate_bps: u32, | ||
| 696 | - info: &AnalysisInfo, | ||
| 697 | - ) -> Result<usize> { | ||
| 698 | - let lm: usize = match frame_size { | ||
| 699 | - 120 => 0, | ||
| 700 | - 240 => 1, | ||
| 701 | - 480 => 2, | ||
| 702 | - 960 => 3, | ||
| 703 | - _ => { | ||
| 704 | - return Err(Error::unsupported( | ||
| 705 | - format!("celt frame of {frame_size} samples"), | ||
| 706 | - "CELT frames are 2.5, 5, 10 or 20 ms at 48 kHz", | ||
| 707 | - )); | ||
| 708 | - } | ||
| 709 | - }; | ||
| 710 | - let m = 1usize << lm; | ||
| 711 | - let n = frame_size; | ||
| 712 | - let cc = self.channels; | ||
| 713 | - let c = self.stream_channels; | ||
| 714 | - let in_n = n / self.upsample; | ||
| 715 | - if pcm.len() < in_n * cc { | ||
| 716 | - return Err(Error::corrupt(format!( | ||
| 717 | - "celt encode: {} samples for a {cc}-channel {in_n}-sample frame", | ||
| 718 | - pcm.len() | ||
| 719 | - ))); | ||
| 720 | - } | ||
| 721 | - let tell0_frac = enc.tell_frac() as i32; | ||
| 722 | - let end = end.clamp(start + 1, NB_BANDS); | ||
| 723 | - | ||
| 724 | - // libopus `opus_encode_native` runs the tonality analysis on the raw | ||
| 725 | - // API frame before the mode decision, so the estimator lives in | ||
| 726 | - // `Encoder` and its result is handed down here. | ||
| 727 | - self.info = *info; | ||
| 728 | - | ||
| 729 | - let mut nb_compressed = enc.storage(); | ||
| 730 | - let mut nb_available = nb_compressed as i32; | ||
| 731 | - // The target rate in 1/8-bit units per frame, VBR only. | ||
| 732 | - let (vbr_rate, mut effective_bytes) = if vbr_rate_bps > 0 { | ||
| 733 | - let den = 48000i64 >> BITRES; | ||
| 734 | - let vr = ((vbr_rate_bps as i64 * n as i64 + (den >> 1)) / den) as i32; | ||
| 735 | - (vr, vr >> (3 + BITRES)) | ||
| 736 | - } else { | ||
| 737 | - (0, nb_compressed as i32) | ||
| 738 | - }; | ||
| 739 | - | ||
| 740 | - if vbr_rate > 0 && self.constrained_vbr { | ||
| 741 | - // Constrained VBR: cap this frame so the reservoir never dips | ||
| 742 | - // below one frame of buffering. | ||
| 743 | - let vbr_bound = vbr_rate; | ||
| 744 | - let floor = if enc.tell() == 1 { 2i32 } else { 0 }; | ||
| 745 | - let max_allowed = (floor | ||
| 746 | - .max((vbr_rate + vbr_bound - self.vbr_reservoir) >> (BITRES + 3))) | ||
| 747 | - .min(nb_available); | ||
| 748 | - if max_allowed < nb_available { | ||
| 749 | - nb_compressed = max_allowed as usize; | ||
| 750 | - nb_available = max_allowed; | ||
| 751 | - enc.shrink(nb_compressed); | ||
| 752 | - } | ||
| 753 | - } | ||
| 754 | - let mut total_bits = (nb_compressed * 8) as i32; | ||
| 755 | - | ||
| 756 | - // --- Preemphasis ---------------------------------------------------- | ||
| 757 | - let stride = n + OVERLAP; | ||
| 758 | - let mut silence = true; | ||
| 759 | - let mut delay = std::mem::take(&mut self.delay_buf); | ||
| 760 | - let mut next_delay = [0.0f32; 2 * CELT_DELAY_48K]; | ||
| 761 | - for ch in 0..cc { | ||
| 762 | - let base = ch * stride; | ||
| 763 | - self.in_buf[base..base + OVERLAP] | ||
| 764 | - .copy_from_slice(&self.in_mem[ch * OVERLAP..(ch + 1) * OVERLAP]); | ||
| 765 | - let mut mem = self.preemph_mem[ch]; | ||
| 766 | - let up = self.upsample; | ||
| 767 | - // `src(j)`: input sample `j` of the delayed stream libopus's CELT | ||
| 768 | - // layer sees -- the `d` samples held over from the previous call | ||
| 769 | - // first, then this frame's. | ||
| 770 | - let dd = CELT_DELAY_48K / up; | ||
| 771 | - let d = if self.align_input { dd } else { 0 }; | ||
| 772 | - let src = |j: usize| { | ||
| 773 | - if j < d { | ||
| 774 | - delay[j * cc + ch] | ||
| 775 | - } else { | ||
| 776 | - pcm[(j - d) * cc + ch] | ||
| 777 | - } | ||
| 778 | - }; | ||
| 779 | - for i in 0..n { | ||
| 780 | - // Zero-stuffing to 48 kHz: the images above the input's own | ||
| 781 | - // Nyquist are never coded (the caller caps `end`) and the | ||
| 782 | - // decoder's decimation drops them. | ||
| 783 | - let mut x = if up == 1 { | ||
| 784 | - src(i) * SIG_SCALE | ||
| 785 | - } else if i.is_multiple_of(up) { | ||
| 786 | - src(i / up) * SIG_SCALE * up as f32 | ||
| 787 | - } else { | ||
| 788 | - 0.0 | ||
| 789 | - }; | ||
| 790 | - if !x.is_finite() { | ||
| 791 | - x = 0.0; | ||
| 792 | - } | ||
| 793 | - x = x.clamp(-65536.0, 65536.0); | ||
| 794 | - let v = x + mem; | ||
| 795 | - mem = -PREEMPH * x; | ||
| 796 | - self.in_buf[base + OVERLAP + i] = v; | ||
| 797 | - silence &= v == 0.0; | ||
| 798 | - } | ||
| 799 | - self.preemph_mem[ch] = mem; | ||
| 800 | - for k in 0..dd { | ||
| 801 | - let j = in_n + k; | ||
| 802 | - next_delay[k * cc + ch] = if j < dd { | ||
| 803 | - delay[j * cc + ch] | ||
| 804 | - } else { | ||
| 805 | - pcm[(j - dd) * cc + ch] | ||
| 806 | - }; | ||
| 807 | - } | ||
| 808 | - self.in_mem[ch * OVERLAP..(ch + 1) * OVERLAP] | ||
| 809 | - .copy_from_slice(&self.in_buf[base + n..base + n + OVERLAP]); | ||
| 810 | - } | ||
| 811 | - delay[..cc * (CELT_DELAY_48K / self.upsample)] | ||
| 812 | - .copy_from_slice(&next_delay[..cc * (CELT_DELAY_48K / self.upsample)]); | ||
| 813 | - self.delay_buf = delay; | ||
| 814 | - | ||
| 815 | - // --- Silence flag (first symbol of the frame) ----------------------- | ||
| 816 | - // Only exists when CELT opens the stream (decoder: `tell == 1`); under | ||
| 817 | - // a hybrid packet's SILK layer the frame is never flagged silent. | ||
| 818 | - if enc.tell() == 1 { | ||
| 819 | - enc.enc_bit_logp(silence, 15); | ||
| 820 | - } else { | ||
| 821 | - silence = false; | ||
| 822 | - } | ||
| 823 | - if silence { | ||
| 824 | - if vbr_rate > 0 { | ||
| 825 | - nb_compressed = nb_compressed.min(2); | ||
| 826 | - total_bits = (nb_compressed * 8) as i32; | ||
| 827 | - nb_available = 2; | ||
| 828 | - enc.shrink(nb_compressed); | ||
| 829 | - } | ||
| 830 | - enc.pad_to_end(); | ||
| 831 | - } | ||
| 832 | - | ||
| 833 | - // --- Postfilter: always off (throughput-first, = complexity < 5) ---- | ||
| 834 | - // The flag exists only when band 0 is coded (decoder: `start == 0`). | ||
| 835 | - if start == 0 && enc.tell() as i32 + 16 <= total_bits { | ||
| 836 | - enc.enc_bit_logp(false, 1); | ||
| 837 | - } | ||
| 838 | - | ||
| 839 | - // --- Transient flag ------------------------------------------------- | ||
| 840 | - let mut is_transient = false; | ||
| 841 | - let mut short_blocks = 0usize; | ||
| 842 | - let mut tf_estimate = 0.0f32; | ||
| 843 | - let mut tf_chan = 0usize; | ||
| 844 | - if lm > 0 && enc.tell() as i32 + 3 <= total_bits { | ||
| 845 | - let (ta, te, tc) = self.transient_analysis(n + OVERLAP, cc, stride); | ||
| 846 | - is_transient = ta; | ||
| 847 | - tf_estimate = te; | ||
| 848 | - tf_chan = if cc == 2 && c == 1 { 0 } else { tc }; | ||
| 849 | - if is_transient { | ||
| 850 | - short_blocks = m; | ||
| 851 | - } | ||
| 852 | - enc.enc_bit_logp(is_transient, 3); | ||
| 853 | - } | ||
| 854 | - | ||
| 855 | - // --- Forward MDCTs, energies, normalisation ------------------------- | ||
| 856 | - // dynalloc looks at long-window energies (`bandLogE2`): on transient | ||
| 857 | - // frames that is a second MDCT pass, offset by LM/2 for the block size. | ||
| 858 | - if short_blocks != 0 { | ||
| 859 | - self.compute_mdcts(0, lm, n, cc, c); | ||
| 860 | - for ch in 0..c { | ||
| 861 | - for i in start..end { | ||
| 862 | - let mut sum = 1e-27f32; | ||
| 863 | - for j in m * E_BANDS[i]..m * E_BANDS[i + 1] { | ||
| 864 | - let v = self.freq[ch * n + j]; | ||
| 865 | - sum += v * v; | ||
| 866 | - } | ||
| 867 | - self.band_log_e2[i + ch * NB_BANDS] = | ||
| 868 | - (sum.sqrt() as f64).log2() as f32 - E_MEANS[i] + 0.5 * lm as f32; | ||
| 869 | - } | ||
| 870 | - } | ||
| 871 | - } | ||
| 872 | - self.compute_mdcts(short_blocks, lm, n, cc, c); | ||
| 873 | - for ch in 0..c { | ||
| 874 | - self.x[ch * n..ch * n + m * E_BANDS[start]].fill(0.0); | ||
| 875 | - for i in start..end { | ||
| 876 | - let mut sum = 1e-27f32; | ||
| 877 | - for j in m * E_BANDS[i]..m * E_BANDS[i + 1] { | ||
| 878 | - let v = self.freq[ch * n + j]; | ||
| 879 | - sum += v * v; | ||
| 880 | - } | ||
| 881 | - self.band_e[i + ch * NB_BANDS] = sum.sqrt(); | ||
| 882 | - self.band_log_e[i + ch * NB_BANDS] = | ||
| 883 | - (self.band_e[i + ch * NB_BANDS] as f64).log2() as f32 - E_MEANS[i]; | ||
| 884 | - if short_blocks == 0 { | ||
| 885 | - self.band_log_e2[i + ch * NB_BANDS] = self.band_log_e[i + ch * NB_BANDS]; | ||
| 886 | - } | ||
| 887 | - } | ||
| 888 | - for i in start..end { | ||
| 889 | - let g = 1.0 / (1e-27 + self.band_e[i + ch * NB_BANDS]); | ||
| 890 | - for j in m * E_BANDS[i]..m * E_BANDS[i + 1] { | ||
| 891 | - self.x[ch * n + j] = self.freq[ch * n + j] * g; | ||
| 892 | - } | ||
| 893 | - } | ||
| 894 | - } | ||
| 895 | - | ||
| 896 | - if std::env::var_os("EC_OPUS_X_DEBUG").is_some() { | ||
| 897 | - let f: Vec<String> = self.in_buf[OVERLAP..OVERLAP + 16] | ||
| 898 | - .iter() | ||
| 899 | - .map(|v| format!("{v:.5}")) | ||
| 900 | - .collect(); | ||
| 901 | - let e: f64 = self.in_buf[..n + OVERLAP] | ||
| 902 | - .iter() | ||
| 903 | - .map(|v| *v as f64 * *v as f64) | ||
| 904 | - .sum(); | ||
| 905 | - let ovl: Vec<String> = self.in_buf[..4].iter().map(|v| format!("{v:.5}")).collect(); | ||
| 906 | - eprintln!("XPRE {} | E {e:.6e} ovl {}", f.join(" "), ovl.join(" ")); | ||
| 907 | - let fr: Vec<String> = self.freq[..16].iter().map(|v| format!("{v:.5}")).collect(); | ||
| 908 | - let be: Vec<String> = self.band_e[..8].iter().map(|v| format!("{v:.5}")).collect(); | ||
| 909 | - let bl: Vec<String> = self.band_log_e[..8] | ||
| 910 | - .iter() | ||
| 911 | - .map(|v| format!("{v:.5}")) | ||
| 912 | - .collect(); | ||
| 913 | - eprintln!( | ||
| 914 | - "XMDCT sb {short_blocks} {} | bandE {} | bandLogE {}", | ||
| 915 | - fr.join(" "), | ||
| 916 | - be.join(" "), | ||
| 917 | - bl.join(" ") | ||
| 918 | - ); | ||
| 919 | - let sx: f64 = self.x[..n].iter().map(|v| v.abs() as f64).sum(); | ||
| 920 | - let x0: Vec<String> = self.x[..8].iter().map(|v| format!("{v:.5}")).collect(); | ||
| 921 | - eprintln!("XNORM sumX {sx:.5} X0..8 {}", x0.join(" ")); | ||
| 922 | - } | ||
| 923 | - | ||
| 924 | - // --- Dynalloc analysis (offsets + spread_weight + importance) ----- | ||
| 925 | - self.offsets = [0; NB_BANDS]; | ||
| 926 | - let mut spread_weight = [0i32; NB_BANDS]; | ||
| 927 | - let mut importance = [0i32; NB_BANDS]; | ||
| 928 | - let max_depth = self.dynalloc_analysis( | ||
| 929 | - start, | ||
| 930 | - end, | ||
| 931 | - c, | ||
| 932 | - lm, | ||
| 933 | - is_transient, | ||
| 934 | - effective_bytes, | ||
| 935 | - &mut spread_weight, | ||
| 936 | - &mut importance, | ||
| 937 | - ); | ||
| 938 | - | ||
| 939 | - // --- tf_res --------------------------------------------------------- | ||
| 940 | - // `TF_ANALYSIS`: run the libopus Viterbi tf search when there are | ||
| 941 | - // enough bits; otherwise fall back to the no-analysis default (raw | ||
| 942 | - // `is_transient` per band codes "no tf change" under tf_select=0). | ||
| 943 | - const TF_ANALYSIS: bool = true; | ||
| 944 | - let tf_select = if TF_ANALYSIS && effective_bytes >= 15 * c as i32 { | ||
| 945 | - let lambda = (80i32).max(20480 / effective_bytes + 2); | ||
| 946 | - self.tf_analysis( | ||
| 947 | - end, | ||
| 948 | - is_transient, | ||
| 949 | - lambda, | ||
| 950 | - n, | ||
| 951 | - lm, | ||
| 952 | - tf_estimate, | ||
| 953 | - tf_chan, | ||
| 954 | - &importance, | ||
| 955 | - ) | ||
| 956 | - } else { | ||
| 957 | - self.tf_res = [i32::from(is_transient); NB_BANDS]; | ||
| 958 | - 0usize | ||
| 959 | - }; | ||
| 960 | - | ||
| 961 | - // --- Coarse energy -------------------------------------------------- | ||
| 962 | - // libopus runs the two-pass coarse-energy search at complexity >= 4. | ||
| 963 | - // MEASURED OFF (lane opus64, 12-row library gate vs libopus): it moves | ||
| 964 | - // err_ratio 6 rows better / 4 worse (nik@96 .982->.990, reelo@64 | ||
| 965 | - // 1.510->1.581, her@64 1.102->1.135, her@96 1.052->1.059; nik@64 | ||
| 966 | - // .708->.703, reelo@96 .940->.872, dl8a .551/.374->.503/.346, hein | ||
| 967 | - // .855/.528->.771/.419), corr within +.0001 everywhere. The KEEP rule | ||
| 968 | - // is "err_ratio not worse on every row", so the search ships off. | ||
| 969 | - // `EC_OPUS_TWO_PASS=1` re-arms it for a sweep (lane opusx2 r2). | ||
| 970 | - const TWO_PASS_COARSE_ENERGY: bool = false; | ||
| 971 | - let mut two_pass = TWO_PASS_COARSE_ENERGY || std::env::var_os("EC_OPUS_TWO_PASS").is_some(); | ||
| 972 | - let mut intra = self.force_intra | ||
| 973 | - || (!two_pass | ||
| 974 | - && self.delayed_intra > (2 * c * (end - start)) as f32 | ||
| 975 | - && nb_available > ((end - start) * c) as i32); | ||
| 976 | - let new_distortion = { | ||
| 977 | - let mut dist = 0.0f32; | ||
| 978 | - for ch in 0..c { | ||
| 979 | - for i in start..end { | ||
| 980 | - let d = self.band_log_e[i + ch * NB_BANDS] - self.old_band_e[i + ch * NB_BANDS]; | ||
| 981 | - dist += d * d; | ||
| 982 | - } | ||
| 983 | - } | ||
| 984 | - dist.min(200.0) | ||
| 985 | - }; | ||
| 986 | - let tell = enc.tell(); | ||
| 987 | - if tell + 3 > total_bits as u32 { | ||
| 988 | - intra = false; | ||
| 989 | - two_pass = false; | ||
| 990 | - } | ||
| 991 | - let max_decay = 16.0f32.min(0.125 * nb_available as f32); | ||
| 992 | - if two_pass || intra { | ||
| 993 | - intra = self.quant_coarse_energy(enc, start, end, intra, c, lm, total_bits, max_decay); | ||
| 994 | - } else { | ||
| 995 | - self.quant_coarse_energy_impl(enc, start, end, intra, c, lm, total_bits, max_decay); | ||
| 996 | - } | ||
| 997 | - self.delayed_intra = if intra { | ||
| 998 | - new_distortion | ||
| 999 | - } else { | ||
| 1000 | - PRED_COEF[lm] * PRED_COEF[lm] * self.delayed_intra + new_distortion | ||
| 1001 | - }; | ||
| 1002 | - | ||
| 1003 | - // --- tf encode ------------------------------------------------------ | ||
| 1004 | - self.tf_encode(enc, start, end, is_transient, lm, tf_select, nb_compressed); | ||
| 1005 | - | ||
| 1006 | - // --- Spread decision (libopus celt_encoder.c:1933-1977) -------------- | ||
| 1007 | - // No LFE, no hybrid, no complexity field (treated as ≥ 3): the only | ||
| 1008 | - // guards that apply are shortBlocks and nbAvailableBytes < 10*C. | ||
| 1009 | - if enc.tell() as i32 + 4 <= total_bits { | ||
| 1010 | - if short_blocks != 0 || nb_available < 10 * c as i32 { | ||
| 1011 | - self.spread_decision = SPREAD_NORMAL; | ||
| 1012 | - } else { | ||
| 1013 | - self.spread_decision = self.spreading_decision(end, c, lm, &spread_weight); | ||
| 1014 | - } | ||
| 1015 | - enc.enc_icdf(self.spread_decision, &SPREAD_ICDF, 5); | ||
| 1016 | - } | ||
| 1017 | - | ||
| 1018 | - // --- Caps ------------------------------------------------------------ | ||
| 1019 | - for i in 0..NB_BANDS { | ||
| 1020 | - let bw = (E_BANDS[i + 1] - E_BANDS[i]) << lm; | ||
| 1021 | - self.caps[i] = | ||
| 1022 | - ((CACHE_CAPS[NB_BANDS * (2 * lm + c - 1) + i] as i32 + 64) * c as i32 * bw as i32) | ||
| 1023 | - >> 2; | ||
| 1024 | - } | ||
| 1025 | - let mut dynalloc_logp = 6u32; | ||
| 1026 | - let total_bits_frac = total_bits << BITRES; | ||
| 1027 | - let mut total_boost = 0i32; | ||
| 1028 | - let mut tell_frac = enc.tell_frac() as i32; | ||
| 1029 | - for i in start..end { | ||
| 1030 | - let width = ((c * (E_BANDS[i + 1] - E_BANDS[i])) << lm) as i32; | ||
| 1031 | - let quanta = (width << BITRES).min((6 << BITRES).max(width)); | ||
| 1032 | - let mut loop_logp = dynalloc_logp; | ||
| 1033 | - let mut boost = 0i32; | ||
| 1034 | - let mut j = 0i32; | ||
| 1035 | - while tell_frac + ((loop_logp as i32) << BITRES) < total_bits_frac - total_boost | ||
| 1036 | - && boost < self.caps[i] | ||
| 1037 | - { | ||
| 1038 | - let flag = j < self.offsets[i]; | ||
| 1039 | - enc.enc_bit_logp(flag, loop_logp); | ||
| 1040 | - tell_frac = enc.tell_frac() as i32; | ||
| 1041 | - if !flag { | ||
| 1042 | - break; | ||
| 1043 | - } | ||
| 1044 | - boost += quanta; | ||
| 1045 | - total_boost += quanta; | ||
| 1046 | - loop_logp = 1; | ||
| 1047 | - j += 1; | ||
| 1048 | - } | ||
| 1049 | - if j > 0 { | ||
| 1050 | - dynalloc_logp = dynalloc_logp.saturating_sub(1).max(2); | ||
| 1051 | - } | ||
| 1052 | - self.offsets[i] = boost; | ||
| 1053 | - } | ||
| 1054 | - | ||
| 1055 | - // --- Intensity decision (libopus celt_encoder.c:2392-2407) ------- | ||
| 1056 | - // Moved before alloc_trim so alloc_trim_analysis can use | ||
| 1057 | - // self.intensity in the stereo_saving minXC loop. | ||
| 1058 | - let overhead = (40 * c as i32 + 20) * ((400 >> lm) - 50); | ||
| 1059 | - let mut equiv_rate = ((nb_compressed as i32 * 8 * 50) << (3 - lm)) - overhead; | ||
| 1060 | - if vbr_rate_bps > 0 { | ||
| 1061 | - equiv_rate = equiv_rate.min(vbr_rate_bps as i32 - overhead); | ||
| 1062 | - } | ||
| 1063 | - if c == 2 { | ||
| 1064 | - self.intensity_decision(nb_compressed, c, lm, vbr_rate_bps); | ||
| 1065 | - self.intensity = self.intensity.clamp(start, end); | ||
| 1066 | - } | ||
| 1067 | - | ||
| 1068 | - // --- Allocation trim ------------------------------------------------ | ||
| 1069 | - let mut alloc_trim = 5i32; | ||
| 1070 | - if tell_frac + (6 << BITRES) <= total_bits_frac - total_boost { | ||
| 1071 | - alloc_trim = self.alloc_trim_analysis(end, lm, c, n, tf_estimate); | ||
| 1072 | - enc.enc_icdf(alloc_trim as usize, &TRIM_ICDF, 7); | ||
| 1073 | - tell_frac = enc.tell_frac() as i32; | ||
| 1074 | - } | ||
| 1075 | - | ||
| 1076 | - // --- Temporal VBR (libopus celt_encoder.c:2187-2204) ------------- | ||
| 1077 | - // lfe=0 so always computed. In float mode SHR32/SHL32/QCONST32 are | ||
| 1078 | - // identity, so follow/frame_avg/temporal_vbr are raw floats. | ||
| 1079 | - let temporal_vbr = { | ||
| 1080 | - let mut follow = -10.0f32; | ||
| 1081 | - let mut frame_avg = 0.0f32; | ||
| 1082 | - let offset = if short_blocks != 0 { | ||
| 1083 | - 0.5 * lm as f32 | ||
| 1084 | - } else { | ||
| 1085 | - 0.0 | ||
| 1086 | - }; | ||
| 1087 | - for i in start..end { | ||
| 1088 | - follow = (follow - 1.0).max(self.band_log_e[i] - offset); | ||
| 1089 | - if c == 2 { | ||
| 1090 | - follow = follow.max(self.band_log_e[i + NB_BANDS] - offset); | ||
| 1091 | - } | ||
| 1092 | - frame_avg += follow; | ||
| 1093 | - } | ||
| 1094 | - frame_avg /= (end - start) as f32; | ||
| 1095 | - let tvbr = (frame_avg - self.spec_avg).clamp(-1.5, 3.0); | ||
| 1096 | - self.spec_avg += 0.02 * tvbr; | ||
| 1097 | - tvbr | ||
| 1098 | - }; | ||
| 1099 | - | ||
| 1100 | - // --- Constrained VBR ------------------------------------------------ | ||
| 1101 | - if vbr_rate > 0 { | ||
| 1102 | - let lm_diff = 3 - lm as i32; | ||
| 1103 | - let hybrid = start != 0; | ||
| 1104 | - let offset_term = if self.constrained_vbr { | ||
| 1105 | - self.vbr_offset >> lm_diff | ||
| 1106 | - } else { | ||
| 1107 | - 0 | ||
| 1108 | - }; | ||
| 1109 | - let base_target = if hybrid { | ||
| 1110 | - (vbr_rate - ((9 * c as i32 + 4) << BITRES)).max(0) + offset_term | ||
| 1111 | - } else { | ||
| 1112 | - vbr_rate + offset_term - ((40 * c as i32 + 20) << BITRES) | ||
| 1113 | - }; | ||
| 1114 | - let mut target = base_target; | ||
| 1115 | - if hybrid { | ||
| 1116 | - let shift = 3 - lm as i32; | ||
| 1117 | - if self.silk_offset < 100 { | ||
| 1118 | - target += (12 << BITRES) >> shift; | ||
| 1119 | - } | ||
| 1120 | - if self.silk_offset > 100 { | ||
| 1121 | - target -= (18 << BITRES) >> shift; | ||
| 1122 | - } | ||
| 1123 | - target += ((tf_estimate - 0.25) * (50 << BITRES) as f32) as i32; | ||
| 1124 | - if tf_estimate > 0.7 { | ||
| 1125 | - target = target.max(50 << BITRES); | ||
| 1126 | - } | ||
| 1127 | - } else { | ||
| 1128 | - let (_, _, vbr_tonal, vbr_act, _, _) = analysis_params(); | ||
| 1129 | - // compute_vbr (libopus celt_encoder.c:1605-1716), float-mode. | ||
| 1130 | - // Skipped: activity, tonality, surround_mask (analysis->valid= | ||
| 1131 | - // false, has_surround_mask=0, pitch_change=0, lfe=0). The qext | ||
| 1132 | - // 2-pass transient compute_vbr (C:2546-2554) is inside | ||
| 1133 | - // #ifdef ENABLE_QEXT — this encoder has no qext. | ||
| 1134 | - let coded_bands = if self.last_coded_bands != 0 { | ||
| 1135 | - self.last_coded_bands | ||
| 1136 | - } else { | ||
| 1137 | - NB_BANDS | ||
| 1138 | - }; | ||
| 1139 | - let mut coded_bins = E_BANDS[coded_bands] << lm; | ||
| 1140 | - if c == 2 { | ||
| 1141 | - coded_bins += E_BANDS[self.intensity.min(coded_bands)] << lm; | ||
| 1142 | - } | ||
| 1143 | - // Low-activity cut (C:1632-1633). REJECTED on the 12-row gate | ||
| 1144 | - // (lane opustonal r2/r3): halves hein's err_ratio but costs | ||
| 1145 | - // her@96 +.020 and nik@96 +.005 -- see `analysis_params`. | ||
| 1146 | - if vbr_act && self.info.valid && self.info.activity < 0.4 { | ||
| 1147 | - target -= ((coded_bins << BITRES) as f32 * (0.4 - self.info.activity)) as i32; | ||
| 1148 | - } | ||
| 1149 | - // Stereo savings (C:1636-1649) | ||
| 1150 | - if c == 2 { | ||
| 1151 | - let coded_stereo_bands = self.intensity.min(coded_bands); | ||
| 1152 | - let coded_stereo_dof = (E_BANDS[coded_stereo_bands] << lm) - coded_stereo_bands; | ||
| 1153 | - let max_frac = 0.8 * coded_stereo_dof as f32 / coded_bins as f32; | ||
| 1154 | - let ss = self.stereo_saving.min(1.0); | ||
| 1155 | - target -= (max_frac * target as f32) | ||
| 1156 | - .min((ss - 0.1) * coded_stereo_dof as f32 * 8.0) | ||
| 1157 | - as i32; | ||
| 1158 | - } | ||
| 1159 | - // dynalloc boost minus calibration average (C:1651) | ||
| 1160 | - target += total_boost - (19 << lm); | ||
| 1161 | - // TF boost (C:1653-1654): MULT16_32_Q15 is identity in float mode, | ||
| 1162 | - // SHL32(.., 1) is the x2 and tf_calibration is .04 at a fixed frame | ||
| 1163 | - // size. MEASURED TWICE (lane opus-vbr r2/r3 on the old 14-row gate, | ||
| 1164 | - // lane opustr r2 on the 12-row one): the x2 costs .0030 corr on | ||
| 1165 | - // hein@64 and .0014 on hein@96 and pushes 5 err_ratio rows the | ||
| 1166 | - // wrong way, so the x1 stand-in stays. The reelm rows that carried | ||
| 1167 | - // the first rejection are gone; hein reproduced it exactly. | ||
| 1168 | - // SWEPT WHOLE (lane opustr2, 12 detached gate runs, r1 = this | ||
| 1169 | - // default reproducing the base rows exactly; the gate is | ||
| 1170 | - // deterministic, so every delta below is real, not run noise). | ||
| 1171 | - // err_ratio deltas vs r1, worst rows only: | ||
| 1172 | - // k=2 off=.04 her@96 +.021 hein@96 +.067, hein corr | ||
| 1173 | - // -.0024 (r2) | ||
| 1174 | - // k=1.5 off=.04/.06/.08 reelo@96 +.09 her@96 +.019, hein corr | ||
| 1175 | - // -.0012 -- the offset is inert (r3,7,6) | ||
| 1176 | - // k=2 off=.04 transient reelo@96 +.095 dl8a@96 +.040 (r4) | ||
| 1177 | - // k=1.5 off=.04 transient hein@64 +.026 her@96 +.020 (r5) | ||
| 1178 | - // k=2 tfe>=.6 / >=.35 nik@96 +.042/+.060 hein@96 +.075 (r9,10) | ||
| 1179 | - // k=1.25 tfe>=.6 / >=.35 hein@64 +.090 / dl8a@96 +.065 (r11,12) | ||
| 1180 | - // k=1.25 off=.044 her@64 +.001 her@96 +.021 ONLY, corr | ||
| 1181 | - // worst -.0005 (hein@64), and reell@64 | ||
| 1182 | - // 2.697->1.440, reell@96 4.499->2.516, | ||
| 1183 | - // hein@64 .853->.302, nik@64 .708->.643, | ||
| 1184 | - // dl8a@96 .374->.315 (r8) | ||
| 1185 | - // r8 is the nearest miss ever measured on this term and still | ||
| 1186 | - // fails the keep rule on her@96, so the x1 stand-in stays. Every | ||
| 1187 | - // variant that moves reell also costs her@96 ~+.02, and the reell gain | ||
| 1188 | - // comes entirely from frames with tf_estimate >= 0.6 (r11 keeps the | ||
| 1189 | - // full reell win) -- so her@96's loss lives on the same frames and | ||
| 1190 | - // no content gate built from `tf_estimate` or the transient flag | ||
| 1191 | - // can separate them. Upgrade path: libopus gates this boost with | ||
| 1192 | - // its tonality analysis (`analysis->valid`, music_prob), which this | ||
| 1193 | - // encoder does not run at all. Sweeps: lanes/opus-opustr2-r*.sweep.txt. | ||
| 1194 | - // SWEPT (lane opustr2): k/offset/gate come from `tf_boost_params()`; | ||
| 1195 | - // the defaults (k=1, off=.044, gate=all) are the shipped point and | ||
| 1196 | - // reproduce the line above byte for byte. | ||
| 1197 | - { | ||
| 1198 | - let (k, off, gate_transient, thresh) = tf_boost_params(); | ||
| 1199 | - let fires = (!gate_transient || is_transient) && tf_estimate >= thresh; | ||
| 1200 | - let k_eff = if fires { k } else { 1.0 }; | ||
| 1201 | - target += (k_eff * (tf_estimate - off) * target as f32) as i32; | ||
| 1202 | - } | ||
| 1203 | - // Tonality boost (C:1658-1669), compensating for the average. | ||
| 1204 | - // REJECTED on the 12-row gate (lane opustonal r2): it is what | ||
| 1205 | - // pushes reelo@96 .940->1.165 -- see `analysis_params`. | ||
| 1206 | - // `pitch_change` is 0 here (no prefilter), so its term is absent. | ||
| 1207 | - if vbr_tonal && self.info.valid { | ||
| 1208 | - let tonal = (self.info.tonality - 0.15).max(0.0) - 0.12; | ||
| 1209 | - target += ((coded_bins << BITRES) as f32 * 1.2 * tonal) as i32; | ||
| 1210 | - } | ||
| 1211 | - // floor depth cap (C:1683-1695): SHR32/MULT16_32_Q15 are identity. | ||
| 1212 | - { | ||
| 1213 | - let bins = E_BANDS[NB_BANDS - 2] << lm; | ||
| 1214 | - let floor_depth = ((c * bins * 8) as f32 * max_depth) as i32; | ||
| 1215 | - let floor_depth = floor_depth.max(target >> 2); | ||
| 1216 | - target = target.min(floor_depth); | ||
| 1217 | - } | ||
| 1218 | - // Constrained VBR (C:1699-1702) | ||
| 1219 | - target = base_target + (0.67 * (target - base_target) as f32) as i32; | ||
| 1220 | - // Temporal VBR (C:1704-1711) | ||
| 1221 | - if tf_estimate < 0.2 { | ||
| 1222 | - let amount = 0.0000031 * (96000 - equiv_rate).clamp(0, 32000) as f32; | ||
| 1223 | - target += (temporal_vbr * amount * target as f32) as i32; | ||
| 1224 | - } | ||
| 1225 | - // Never more than double the base rate (C:1714) | ||
| 1226 | - target = target.min(2 * base_target); | ||
| 1227 | - } | ||
| 1228 | - target += tell_frac; | ||
| 1229 | - let mut min_allowed = | ||
| 1230 | - ((tell_frac + total_boost + (1 << (BITRES + 3)) - 1) >> (BITRES + 3)) + 2; | ||
| 1231 | - if hybrid { | ||
| 1232 | - min_allowed = min_allowed.max( | ||
| 1233 | - (tell0_frac + (37 << BITRES) + total_boost + (1 << (BITRES + 3)) - 1) | ||
| 1234 | - >> (BITRES + 3), | ||
| 1235 | - ); | ||
| 1236 | - } | ||
| 1237 | - let mut nb_avail = (target + (1 << (BITRES + 2))) >> (BITRES + 3); | ||
| 1238 | - nb_avail = nb_avail.max(min_allowed); | ||
| 1239 | - nb_avail = nb_avail.min(nb_compressed as i32); | ||
| 1240 | - let mut delta = target - vbr_rate; | ||
| 1241 | - target = nb_avail << (BITRES + 3); | ||
| 1242 | - if silence { | ||
| 1243 | - delta = 0; | ||
| 1244 | - if hybrid { | ||
| 1245 | - nb_avail = 2; | ||
| 1246 | - target = (2 * 8) << BITRES; | ||
| 1247 | - } | ||
| 1248 | - } | ||
| 1249 | - let alpha = if self.vbr_count < 970 { | ||
| 1250 | - self.vbr_count += 1; | ||
| 1251 | - 1.0 / (self.vbr_count + 20) as f32 | ||
| 1252 | - } else { | ||
| 1253 | - 0.001 | ||
| 1254 | - }; | ||
| 1255 | - if self.constrained_vbr { | ||
| 1256 | - self.vbr_reservoir += target - vbr_rate; | ||
| 1257 | - self.vbr_drift += (alpha | ||
| 1258 | - * ((delta * (1 << lm_diff)) as f32 | ||
| 1259 | - - self.vbr_offset as f32 | ||
| 1260 | - - self.vbr_drift as f32)) as i32; | ||
| 1261 | - self.vbr_offset = -self.vbr_drift; | ||
| 1262 | - if hybrid { | ||
| 1263 | - if self.vbr_reservoir < 0 { | ||
| 1264 | - let adjust = (-self.vbr_reservoir) / (8 << BITRES); | ||
| 1265 | - if !silence { | ||
| 1266 | - nb_avail += adjust; | ||
| 1267 | - } | ||
| 1268 | - self.vbr_reservoir = 0; | ||
| 1269 | - } | ||
| 1270 | - } else { | ||
| 1271 | - // Bound banked credit at eight frames' worth of rate. | ||
| 1272 | - self.vbr_reservoir = self.vbr_reservoir.max(-8 * vbr_rate); | ||
| 1273 | - if self.vbr_reservoir < 0 { | ||
| 1274 | - // Release banked credit slowly (8 bytes per frame) so it stays | ||
| 1275 | - // available for transient boosts; libopus CVBR re-adds all of | ||
| 1276 | - // it to the next frame, which would defeat banking entirely. | ||
| 1277 | - // MEASURED (lane opustr r3, `lanes/opus-opustr-r3.sweep.txt`): | ||
| 1278 | - // restoring the libopus uncapped one-frame release on its own | ||
| 1279 | - // is neutral-to-worse -- 3 rows better, 5 worse (dl8a@96 | ||
| 1280 | - // .374->.415, hein@96 .528->.555, her@96 1.051->1.064) and | ||
| 1281 | - // hein@64 corr -.0008. The drip stays. | ||
| 1282 | - let adjust = ((-self.vbr_reservoir) / (8 << BITRES)).min(8); | ||
| 1283 | - if !silence { | ||
| 1284 | - nb_avail += adjust; | ||
| 1285 | - self.vbr_reservoir += adjust << (BITRES + 3); | ||
| 1286 | - } else { | ||
| 1287 | - self.vbr_reservoir = 0; | ||
| 1288 | - } | ||
| 1289 | - } | ||
| 1290 | - } | ||
| 1291 | - } | ||
| 1292 | - let floor = if hybrid { 0 } else { 2 }; | ||
| 1293 | - let shrunk = (nb_compressed as i32).min(nb_avail).max(floor) as usize; | ||
| 1294 | - if shrunk < nb_compressed { | ||
| 1295 | - nb_compressed = shrunk; | ||
| 1296 | - enc.shrink(nb_compressed); | ||
| 1297 | - } | ||
| 1298 | - } | ||
| 1299 | - | ||
| 1300 | - // --- Stereo decisions ----------------------------------------------- | ||
| 1301 | - let mut intensity = 0usize; | ||
| 1302 | - let mut dual_stereo = false; | ||
| 1303 | - if c == 2 { | ||
| 1304 | - if lm != 0 { | ||
| 1305 | - dual_stereo = self.stereo_analysis(lm, n); | ||
| 1306 | - } | ||
| 1307 | - intensity = self.intensity.clamp(start, end); | ||
| 1308 | - } | ||
| 1309 | - let _ = &mut effective_bytes; | ||
| 1310 | - | ||
| 1311 | - // --- Bit allocation ------------------------------------------------- | ||
| 1312 | - let mut bits = (((nb_compressed * 8) as i32) << BITRES) - enc.tell_frac() as i32 - 1; | ||
| 1313 | - let anti_collapse_rsv = if is_transient && lm >= 2 && bits >= ((lm as i32 + 2) << BITRES) { | ||
| 1314 | - 1 << BITRES | ||
| 1315 | - } else { | ||
| 1316 | - 0 | ||
| 1317 | - }; | ||
| 1318 | - bits -= anti_collapse_rsv; | ||
| 1319 | - let alloc = compute_allocation_encode( | ||
| 1320 | - enc, | ||
| 1321 | - start, | ||
| 1322 | - end, | ||
| 1323 | - alloc_trim, | ||
| 1324 | - bits, | ||
| 1325 | - c, | ||
| 1326 | - lm, | ||
| 1327 | - &self.offsets, | ||
| 1328 | - &self.caps, | ||
| 1329 | - &mut self.pulses, | ||
| 1330 | - &mut self.fine_quant, | ||
| 1331 | - &mut self.fine_priority, | ||
| 1332 | - intensity, | ||
| 1333 | - dual_stereo, | ||
| 1334 | - self.last_coded_bands, | ||
| 1335 | - ); | ||
| 1336 | - let intensity = alloc.intensity; | ||
| 1337 | - let dual_stereo = alloc.dual_stereo; | ||
| 1338 | - let balance = alloc.balance; | ||
| 1339 | - let coded_bands = alloc.coded_bands; | ||
| 1340 | - // libopus: lastCodedBands follows codedBands by at most one band per frame. | ||
| 1341 | - self.last_coded_bands = if self.last_coded_bands != 0 { | ||
| 1342 | - coded_bands.clamp(self.last_coded_bands - 1, self.last_coded_bands + 1) | ||
| 1343 | - } else { | ||
| 1344 | - coded_bands | ||
| 1345 | - }; | ||
| 1346 | - | ||
| 1347 | - // --- Fine energy ---------------------------------------------------- | ||
| 1348 | - for i in start..end { | ||
| 1349 | - if self.fine_quant[i] <= 0 { | ||
| 1350 | - continue; | ||
| 1351 | - } | ||
| 1352 | - let frac = 1 << self.fine_quant[i]; | ||
| 1353 | - for ch in 0..c { | ||
| 1354 | - let e = &mut self.error[i + ch * NB_BANDS]; | ||
| 1355 | - let q2 = (((*e + 0.5) * frac as f32).floor() as i32).clamp(0, frac - 1); | ||
| 1356 | - enc.enc_bits(q2 as u32, self.fine_quant[i] as u32); | ||
| 1357 | - let offset = (q2 as f32 + 0.5) / frac as f32 - 0.5; | ||
| 1358 | - self.old_band_e[i + ch * NB_BANDS] += offset; | ||
| 1359 | - *e -= offset; | ||
| 1360 | - } | ||
| 1361 | - } | ||
| 1362 | - | ||
| 1363 | - // --- Shapes --------------------------------------------------------- | ||
| 1364 | - self.quant_all_bands( | ||
| 1365 | - enc, | ||
| 1366 | - start, | ||
| 1367 | - end, | ||
| 1368 | - short_blocks, | ||
| 1369 | - self.spread_decision, | ||
| 1370 | - dual_stereo, | ||
| 1371 | - intensity, | ||
| 1372 | - (nb_compressed as i32 * (8 << BITRES)) - anti_collapse_rsv, | ||
| 1373 | - balance, | ||
| 1374 | - lm, | ||
| 1375 | - coded_bands, | ||
| 1376 | - c, | ||
| 1377 | - n, | ||
| 1378 | - ); | ||
| 1379 | - | ||
| 1380 | - // --- Anti-collapse -------------------------------------------------- | ||
| 1381 | - if anti_collapse_rsv > 0 { | ||
| 1382 | - let on = self.consec_transient < 2; | ||
| 1383 | - enc.enc_bits(u32::from(on), 1); | ||
| 1384 | - } | ||
| 1385 | - | ||
| 1386 | - // --- Leftover fine bits --------------------------------------------- | ||
| 1387 | - let mut bits_left = nb_compressed as i32 * 8 - enc.tell() as i32; | ||
| 1388 | - for prio in 0..2 { | ||
| 1389 | - for i in start..end { | ||
| 1390 | - if bits_left < c as i32 { | ||
| 1391 | - break; | ||
| 1392 | - } | ||
| 1393 | - if self.fine_quant[i] >= MAX_FINE_BITS || self.fine_priority[i] != prio { | ||
| 1394 | - continue; | ||
| 1395 | - } | ||
| 1396 | - for ch in 0..c { | ||
| 1397 | - let q2 = i32::from(self.error[i + ch * NB_BANDS] >= 0.0); | ||
| 1398 | - enc.enc_bits(q2 as u32, 1); | ||
| 1399 | - let offset = (q2 as f32 - 0.5) / (1 << (self.fine_quant[i] + 1)) as f32; | ||
| 1400 | - self.old_band_e[i + ch * NB_BANDS] += offset; | ||
| 1401 | - bits_left -= 1; | ||
| 1402 | - } | ||
| 1403 | - } | ||
| 1404 | - } | ||
| 1405 | - | ||
| 1406 | - if silence { | ||
| 1407 | - for e in self.old_band_e.iter_mut() { | ||
| 1408 | - *e = -28.0; | ||
| 1409 | - } | ||
| 1410 | - } | ||
| 1411 | - if c == 1 { | ||
| 1412 | - for i in 0..NB_BANDS { | ||
| 1413 | - self.old_band_e[NB_BANDS + i] = self.old_band_e[i]; | ||
| 1414 | - } | ||
| 1415 | - } | ||
| 1416 | - // Uncoded bands hold no energy history (the decoder clears them the | ||
| 1417 | - // same way), so a later start/end change predicts from the same state. | ||
| 1418 | - for ch in 0..2 { | ||
| 1419 | - for i in (0..start).chain(end..NB_BANDS) { | ||
| 1420 | - self.old_band_e[ch * NB_BANDS + i] = 0.0; | ||
| 1421 | - } | ||
| 1422 | - } | ||
| 1423 | - if is_transient { | ||
| 1424 | - self.consec_transient += 1; | ||
| 1425 | - } else { | ||
| 1426 | - self.consec_transient = 0; | ||
| 1427 | - } | ||
| 1428 | - self.force_intra = false; | ||
| 1429 | - | ||
| 1430 | - enc.done(); | ||
| 1431 | - if enc.error() { | ||
| 1432 | - return Err(Error::corrupt("celt encode: busted the frame budget")); | ||
| 1433 | - } | ||
| 1434 | - // Capture per-frame diagnostics for the dropout investigation. | ||
| 1435 | - let mut band_log_e = [0.0f32; 2 * NB_BANDS]; | ||
| 1436 | - band_log_e[..2 * NB_BANDS].copy_from_slice(&self.band_log_e); | ||
| 1437 | - self.last_diag = CeltFrameDiag { | ||
| 1438 | - is_transient, | ||
| 1439 | - short_blocks, | ||
| 1440 | - intra, | ||
| 1441 | - silence, | ||
| 1442 | - lm, | ||
| 1443 | - start, | ||
| 1444 | - coded_bands, | ||
| 1445 | - intensity, | ||
| 1446 | - dual_stereo, | ||
| 1447 | - alloc_trim, | ||
| 1448 | - vbr_reservoir: self.vbr_reservoir, | ||
| 1449 | - nb_compressed, | ||
| 1450 | - band_log_e, | ||
| 1451 | - pulses: self.pulses, | ||
| 1452 | - fine_quant: self.fine_quant, | ||
| 1453 | - analysis_valid: self.info.valid, | ||
| 1454 | - music_prob: self.info.music_prob, | ||
| 1455 | - tonality: self.info.tonality, | ||
| 1456 | - tonality_slope: self.info.tonality_slope, | ||
| 1457 | - activity: self.info.activity, | ||
| 1458 | - analysis_bandwidth: self.info.bandwidth, | ||
| 1459 | - }; | ||
| 1460 | - Ok(nb_compressed) | ||
| 1461 | - } | ||
| 1462 | - // -- Analysis ------------------------------------------------------------ | ||
| 1463 | - | ||
| 1464 | - /// `transient_analysis()` — libopus float-mode algorithm. | ||
| 1465 | - /// Returns `(is_transient, tf_estimate, tf_chan)`. | ||
| 1466 | - fn transient_analysis(&mut self, len: usize, c: usize, stride: usize) -> (bool, f32, usize) { | ||
| 1467 | - let tmp = &mut self.transient_tmp[..len]; | ||
| 1468 | - let len2 = len / 2; | ||
| 1469 | - let mut mask_metric: i32 = 0; | ||
| 1470 | - let mut tf_chan: usize = 0; | ||
| 1471 | - | ||
| 1472 | - for ch in 0..c { | ||
| 1473 | - // Copy this channel's samples (C layout: in[i + c*len] = in_buf[ch*stride + i]) | ||
| 1474 | - tmp.copy_from_slice(&self.in_buf[ch * stride..ch * stride + len]); | ||
| 1475 | - | ||
| 1476 | - // High-pass filter: (1 - 2*z^-1 + z^-2) / (1 - z^-1 + .5*z^-2) | ||
| 1477 | - let mut mem0 = 0.0f32; | ||
| 1478 | - let mut mem1 = 0.0f32; | ||
| 1479 | - for v in tmp.iter_mut() { | ||
| 1480 | - let x = *v; | ||
| 1481 | - let y = mem0 + x; | ||
| 1482 | - mem0 = mem1 + y - 2.0 * x; | ||
| 1483 | - mem1 = x - 0.5 * y; | ||
| 1484 | - *v = y; | ||
| 1485 | - } | ||
| 1486 | - // First few samples are bad because we don't propagate the memory | ||
| 1487 | - for v in tmp.iter_mut().take(12) { | ||
| 1488 | - *v = 0.0; | ||
| 1489 | - } | ||
| 1490 | - | ||
| 1491 | - // Forward pass: post-echo threshold (forward_decay = 0.0625) | ||
| 1492 | - let mut mean = 0.0f32; | ||
| 1493 | - let mut fm0 = 0.0f32; | ||
| 1494 | - for i in 0..len2 { | ||
| 1495 | - let x2 = tmp[2 * i] * tmp[2 * i] + tmp[2 * i + 1] * tmp[2 * i + 1]; | ||
| 1496 | - mean += x2; | ||
| 1497 | - tmp[i] = fm0 + 0.0625 * (x2 - fm0); | ||
| 1498 | - fm0 = tmp[i]; | ||
| 1499 | - } | ||
| 1500 | - | ||
| 1501 | - // Backward pass: pre-echo threshold (backward_decay = 0.125) | ||
| 1502 | - let mut bm0 = 0.0f32; | ||
| 1503 | - let mut max_e = 0.0f32; | ||
| 1504 | - for i in (0..len2).rev() { | ||
| 1505 | - tmp[i] = bm0 + 0.125 * (tmp[i] - bm0); | ||
| 1506 | - bm0 = tmp[i]; | ||
| 1507 | - max_e = max_e.max(bm0); | ||
| 1508 | - } | ||
| 1509 | - | ||
| 1510 | - // Geometric mean of frame energy and half the max | ||
| 1511 | - mean = (mean * max_e * 0.5 * len2 as f32).sqrt(); | ||
| 1512 | - | ||
| 1513 | - // Inverse of the mean energy (float mode: SHL32/SHR32 are no-ops) | ||
| 1514 | - let norm = len2 as f32 / (1e-15 + mean); | ||
| 1515 | - | ||
| 1516 | - // Harmonic mean discarding unreliable boundaries (1/4th of samples) | ||
| 1517 | - let mut unmask: i32 = 0; | ||
| 1518 | - let mut i = 12; | ||
| 1519 | - while i < len2 - 5 { | ||
| 1520 | - let id = ((64.0 * norm * (tmp[i] + 1e-15)).floor() as i32).clamp(0, 127) as usize; | ||
| 1521 | - unmask += INV_TABLE[id] as i32; | ||
| 1522 | - i += 4; | ||
| 1523 | - } | ||
| 1524 | - // Normalize: 1/4th sampling, factor of 6 in inv_table | ||
| 1525 | - unmask = 64 * unmask * 4 / (6 * (len2 as i32 - 17)); | ||
| 1526 | - if unmask > mask_metric { | ||
| 1527 | - tf_chan = ch; | ||
| 1528 | - mask_metric = unmask; | ||
| 1529 | - } | ||
| 1530 | - } | ||
| 1531 | - | ||
| 1532 | - let is_transient = mask_metric > 200; | ||
| 1533 | - // tf_max and tf_estimate (float mode: all Q-shifts are no-ops) | ||
| 1534 | - let tf_max = ((27.0 * mask_metric as f32).sqrt() - 42.0).max(0.0); | ||
| 1535 | - let tf_estimate = (0.0069 * tf_max.min(163.0) - 0.139).max(0.0).sqrt(); | ||
| 1536 | - | ||
| 1537 | - (is_transient, tf_estimate, tf_chan) | ||
| 1538 | - } | ||
| 1539 | - | ||
| 1540 | - /// libopus `dynalloc_analysis`: per-band boost requests from a follower / | ||
| 1541 | - /// median masking model over the long-window energies. Writes | ||
| 1542 | - /// `self.offsets[i]` in boost units (the loop that codes them converts to | ||
| 1543 | - /// bits via the band's quanta). Also computes `importance[]` for | ||
| 1544 | - /// `tf_analysis()` (libopus celt_encoder.c:1176-1189). | ||
| 1545 | - // Mirrors libopus's dynalloc_analysis() signature; the inputs stay separate. | ||
| 1546 | - #[allow(clippy::too_many_arguments)] | ||
| 1547 | - fn dynalloc_analysis( | ||
| 1548 | - &mut self, | ||
| 1549 | - start: usize, | ||
| 1550 | - end: usize, | ||
| 1551 | - c: usize, | ||
| 1552 | - lm: usize, | ||
| 1553 | - is_transient: bool, | ||
| 1554 | - effective_bytes: i32, | ||
| 1555 | - spread_weight: &mut [i32; NB_BANDS], | ||
| 1556 | - importance: &mut [i32; NB_BANDS], | ||
| 1557 | - ) -> f32 { | ||
| 1558 | - const LSB_DEPTH: f32 = 24.0; | ||
| 1559 | - let mut noise_floor = [0.0f32; NB_BANDS]; | ||
| 1560 | - for i in 0..end { | ||
| 1561 | - noise_floor[i] = 0.0625 * LOG_N[i] as f32 + 0.5 + (9.0 - LSB_DEPTH) - E_MEANS[i] | ||
| 1562 | - + 0.0062 * ((i + 5) * (i + 5)) as f32; | ||
| 1563 | - } | ||
| 1564 | - // maxDepth = max(bandLogE - noise_floor) across channels (libopus 995-999). | ||
| 1565 | - let mut max_depth = -31.9f32; | ||
| 1566 | - for ch in 0..c { | ||
| 1567 | - // Parallel arrays are indexed by band or bin, as in libopus. | ||
| 1568 | - #[allow(clippy::needless_range_loop)] | ||
| 1569 | - for i in 0..end { | ||
| 1570 | - max_depth = max_depth.max(self.band_log_e[ch * NB_BANDS + i] - noise_floor[i]); | ||
| 1571 | - } | ||
| 1572 | - } | ||
| 1573 | - // Simple masking model for spread_weight (libopus celt_encoder.c:1000-1035). | ||
| 1574 | - let mut mask = [0.0f32; NB_BANDS]; | ||
| 1575 | - for i in 0..end { | ||
| 1576 | - mask[i] = self.band_log_e[i] - noise_floor[i]; | ||
| 1577 | - } | ||
| 1578 | - if c == 2 { | ||
| 1579 | - for i in 0..end { | ||
| 1580 | - mask[i] = mask[i].max(self.band_log_e[NB_BANDS + i] - noise_floor[i]); | ||
| 1581 | - } | ||
| 1582 | - } | ||
| 1583 | - let mut sig = [0.0f32; NB_BANDS]; | ||
| 1584 | - sig[..end].copy_from_slice(&mask[..end]); | ||
| 1585 | - for i in 1..end { | ||
| 1586 | - mask[i] = mask[i].max(mask[i - 1] - 2.0); | ||
| 1587 | - } | ||
| 1588 | - for i in (0..end - 1).rev() { | ||
| 1589 | - mask[i] = mask[i].max(mask[i + 1] - 3.0); | ||
| 1590 | - } | ||
| 1591 | - for i in 0..end { | ||
| 1592 | - // SMR: mask is never more than 12 below the peak and never below the | ||
| 1593 | - // noise floor. | ||
| 1594 | - let smr = sig[i] - 0.0_f32.max(max_depth - 12.0).max(mask[i]); | ||
| 1595 | - let shift = (5).min(0.max(-((smr + 0.5).floor() as i32))); | ||
| 1596 | - spread_weight[i] = 32 >> shift; | ||
| 1597 | - } | ||
| 1598 | - // Dynamic allocation can't make us bust the budget (libopus 1036-1037). | ||
| 1599 | - if !(effective_bytes > 50 && lm >= 1) { | ||
| 1600 | - // Parallel arrays are indexed by band or bin, as in libopus. | ||
| 1601 | - #[allow(clippy::needless_range_loop)] | ||
| 1602 | - for i in start..end { | ||
| 1603 | - importance[i] = 13; | ||
| 1604 | - } | ||
| 1605 | - return max_depth; | ||
| 1606 | - } | ||
| 1607 | - let median3 = |a: &[f32]| -> f32 { | ||
| 1608 | - let (x, y, z) = (a[0], a[1], a[2]); | ||
| 1609 | - x.max(y).min(z).max(x.min(y)) | ||
| 1610 | - }; | ||
| 1611 | - let median5 = |a: &[f32]| -> f32 { | ||
| 1612 | - let mut v = [a[0], a[1], a[2], a[3], a[4]]; | ||
| 1613 | - v.sort_by(|p, q| p.partial_cmp(q).unwrap()); | ||
| 1614 | - v[2] | ||
| 1615 | - }; | ||
| 1616 | - let mut follower = [0.0f32; 2 * NB_BANDS]; | ||
| 1617 | - let mut last = 0usize; | ||
| 1618 | - for ch in 0..c { | ||
| 1619 | - let e2 = &self.band_log_e2[ch * NB_BANDS..ch * NB_BANDS + NB_BANDS]; | ||
| 1620 | - let f = &mut follower[ch * NB_BANDS..ch * NB_BANDS + NB_BANDS]; | ||
| 1621 | - f[0] = e2[0]; | ||
| 1622 | - for i in 1..end { | ||
| 1623 | - // The last band at least .5 dB above its predecessor bounds | ||
| 1624 | - // the backward pass (band-limited signals). | ||
| 1625 | - if e2[i] > e2[i - 1] + 0.5 { | ||
| 1626 | - last = i; | ||
| 1627 | - } | ||
| 1628 | - f[i] = (f[i - 1] + 1.5).min(e2[i]); | ||
| 1629 | - } | ||
| 1630 | - for i in (0..last).rev() { | ||
| 1631 | - f[i] = f[i].min((f[i + 1] + 2.0).min(e2[i])); | ||
| 1632 | - } | ||
| 1633 | - let offset = 1.0f32; | ||
| 1634 | - for i in 2..end.saturating_sub(2) { | ||
| 1635 | - f[i] = f[i].max(median5(&e2[i - 2..i + 3]) - offset); | ||
| 1636 | - } | ||
| 1637 | - let tmp = median3(&e2[0..3]) - offset; | ||
| 1638 | - f[0] = f[0].max(tmp); | ||
| 1639 | - f[1] = f[1].max(tmp); | ||
| 1640 | - let tmp = median3(&e2[end - 3..end]) - offset; | ||
| 1641 | - f[end - 2] = f[end - 2].max(tmp); | ||
| 1642 | - f[end - 1] = f[end - 1].max(tmp); | ||
| 1643 | - for i in 0..end { | ||
| 1644 | - f[i] = f[i].max(noise_floor[i]); | ||
| 1645 | - } | ||
| 1646 | - } | ||
| 1647 | - if c == 2 { | ||
| 1648 | - for i in start..end { | ||
| 1649 | - // 24 dB cross-talk between channels. | ||
| 1650 | - follower[NB_BANDS + i] = follower[NB_BANDS + i].max(follower[i] - 4.0); | ||
| 1651 | - follower[i] = follower[i].max(follower[NB_BANDS + i] - 4.0); | ||
| 1652 | - follower[i] = 0.5 | ||
| 1653 | - * ((self.band_log_e[i] - follower[i]).max(0.0) | ||
| 1654 | - + (self.band_log_e[NB_BANDS + i] - follower[NB_BANDS + i]).max(0.0)); | ||
| 1655 | - } | ||
| 1656 | - } else { | ||
| 1657 | - // Parallel arrays are indexed by band or bin, as in libopus. | ||
| 1658 | - #[allow(clippy::needless_range_loop)] | ||
| 1659 | - for i in start..end { | ||
| 1660 | - follower[i] = (self.band_log_e[i] - follower[i]).max(0.0); | ||
| 1661 | - } | ||
| 1662 | - } | ||
| 1663 | - // Importance for tf_analysis (libopus celt_encoder.c:1176-1189): | ||
| 1664 | - // 13 * 2^min(follower, 4), rounded to nearest integer. | ||
| 1665 | - for i in start..end { | ||
| 1666 | - importance[i] = (13.0 * (2.0_f32).powf(follower[i].min(4.0)) + 0.5).floor() as i32; | ||
| 1667 | - } | ||
| 1668 | - // Our VBR is always constrained: halve dynalloc on steady frames. | ||
| 1669 | - if !is_transient { | ||
| 1670 | - for f in &mut follower[start..end] { | ||
| 1671 | - *f *= 0.5; | ||
| 1672 | - } | ||
| 1673 | - } | ||
| 1674 | - // Parallel arrays are indexed by band or bin, as in libopus. | ||
| 1675 | - #[allow(clippy::needless_range_loop)] | ||
| 1676 | - for i in start..end { | ||
| 1677 | - if i < 8 { | ||
| 1678 | - follower[i] *= 2.0; | ||
| 1679 | - } | ||
| 1680 | - if i >= 12 { | ||
| 1681 | - follower[i] *= 0.5; | ||
| 1682 | - } | ||
| 1683 | - } | ||
| 1684 | - // libopus `celt_encoder.c:1226-1230`: the analysis's per-band | ||
| 1685 | - // leakage boost, in 1/64 dB units, on top of the follower. | ||
| 1686 | - if analysis_params().4 && self.info.valid { | ||
| 1687 | - // Parallel arrays are indexed by band or bin, as in libopus. | ||
| 1688 | - #[allow(clippy::needless_range_loop)] | ||
| 1689 | - for i in start..crate::analysis::LEAK_BANDS.min(end) { | ||
| 1690 | - follower[i] += f32::from(self.info.leak_boost[i]) / 64.0; | ||
| 1691 | - } | ||
| 1692 | - } | ||
| 1693 | - let mut tot_boost = 0i32; | ||
| 1694 | - for i in start..end { | ||
| 1695 | - let f = follower[i].min(4.0); | ||
| 1696 | - let width = ((c * (E_BANDS[i + 1] - E_BANDS[i])) << lm) as i32; | ||
| 1697 | - let (boost, boost_bits) = if width < 6 { | ||
| 1698 | - let b = f as i32; | ||
| 1699 | - (b, (b * width) << BITRES) | ||
| 1700 | - } else if width > 48 { | ||
| 1701 | - let b = (f * 8.0) as i32; | ||
| 1702 | - (b, ((b * width) << BITRES) / 8) | ||
| 1703 | - } else { | ||
| 1704 | - let b = (f * width as f32 / 6.0) as i32; | ||
| 1705 | - (b, (b * 6) << BITRES) | ||
| 1706 | - }; | ||
| 1707 | - // Constrained VBR, steady frame: dynalloc may take 2/3 of the bits. | ||
| 1708 | - if !is_transient && ((tot_boost + boost_bits) >> BITRES >> 3) > 2 * effective_bytes / 3 | ||
| 1709 | - { | ||
| 1710 | - let cap = ((2 * effective_bytes / 3) << BITRES) << 3; | ||
| 1711 | - self.offsets[i] = cap - tot_boost; | ||
| 1712 | - break; | ||
| 1713 | - } | ||
| 1714 | - self.offsets[i] = boost; | ||
| 1715 | - tot_boost += boost_bits; | ||
| 1716 | - } | ||
| 1717 | - max_depth | ||
| 1718 | - } | ||
| 1719 | - | ||
| 1720 | - /// libopus `spreading_decision` (bands.c:479-570): classifies the current | ||
| 1721 | - /// frame's spectral shape as `SPREAD_NONE`/`SPREAD_LIGHT`/`SPREAD_NORMAL`/ | ||
| 1722 | - /// `SPREAD_AGGRESSIVE` by counting how concentrated the normalized band | ||
| 1723 | - /// coefficients are, weighted by the masking-based `spread_weight` from | ||
| 1724 | - /// `dynalloc_analysis`. Maintains `tonal_average` (recursive averaging) | ||
| 1725 | - /// and applies hysteresis against the previous decision. | ||
| 1726 | - /// | ||
| 1727 | - /// `update_hf` is always false here (no pitch prefilter), so the | ||
| 1728 | - /// `hf_average`/`tapset_decision` state is carried but never updated — | ||
| 1729 | - /// matching libopus with `pf_on = false`. | ||
| 1730 | - fn spreading_decision( | ||
| 1731 | - &mut self, | ||
| 1732 | - end: usize, | ||
| 1733 | - c: usize, | ||
| 1734 | - lm: usize, | ||
| 1735 | - spread_weight: &[i32; NB_BANDS], | ||
| 1736 | - ) -> usize { | ||
| 1737 | - let m = 1usize << lm; | ||
| 1738 | - let n0 = SHORT_MDCT << lm; // = M * shortMdctSize | ||
| 1739 | - // Last band too narrow: nothing to spread. | ||
| 1740 | - if m * (E_BANDS[end] - E_BANDS[end - 1]) <= 8 { | ||
| 1741 | - return SPREAD_NONE; | ||
| 1742 | - } | ||
| 1743 | - let mut sum = 0i32; | ||
| 1744 | - let mut nb_bands = 0i32; | ||
| 1745 | - for ch in 0..c { | ||
| 1746 | - for i in 0..end { | ||
| 1747 | - let n = m * (E_BANDS[i + 1] - E_BANDS[i]); | ||
| 1748 | - if n <= 8 { | ||
| 1749 | - continue; | ||
| 1750 | - } | ||
| 1751 | - let base = ch * n0 + m * E_BANDS[i]; | ||
| 1752 | - let x = &self.x[base..base + n]; | ||
| 1753 | - let mut tcount = [0i32; 3]; | ||
| 1754 | - // Parallel arrays are indexed by band or bin, as in libopus. | ||
| 1755 | - #[allow(clippy::needless_range_loop)] | ||
| 1756 | - for j in 0..n { | ||
| 1757 | - // Float-mode: x2N = x[j]^2 * N; thresholds are the literal | ||
| 1758 | - // QCONST16 values (0.25, 0.0625, 0.015625). | ||
| 1759 | - let x2n = x[j] * x[j] * n as f32; | ||
| 1760 | - if x2n < 0.25 { | ||
| 1761 | - tcount[0] += 1; | ||
| 1762 | - } | ||
| 1763 | - if x2n < 0.0625 { | ||
| 1764 | - tcount[1] += 1; | ||
| 1765 | - } | ||
| 1766 | - if x2n < 0.015625 { | ||
| 1767 | - tcount[2] += 1; | ||
| 1768 | - } | ||
| 1769 | - } | ||
| 1770 | - // hf_sum accumulation is only used when update_hf is true | ||
| 1771 | - // (prefilter on), which never happens here. The branch is | ||
| 1772 | - // kept for structural fidelity but the result is unused. | ||
| 1773 | - let _hf_sum_contrib = if i > NB_BANDS - 4 { | ||
| 1774 | - 32 * (tcount[1] + tcount[0]) / n as i32 | ||
| 1775 | - } else { | ||
| 1776 | - 0 | ||
| 1777 | - }; | ||
| 1778 | - let tmp = (2 * tcount[2] >= n as i32) as i32 | ||
| 1779 | - + (2 * tcount[1] >= n as i32) as i32 | ||
| 1780 | - + (2 * tcount[0] >= n as i32) as i32; | ||
| 1781 | - sum += tmp * spread_weight[i]; | ||
| 1782 | - nb_bands += spread_weight[i]; | ||
| 1783 | - } | ||
| 1784 | - } | ||
| 1785 | - if nb_bands == 0 { | ||
| 1786 | - return self.spread_decision; | ||
| 1787 | - } | ||
| 1788 | - let mut s = (sum << 8) / nb_bands; | ||
| 1789 | - // Recursive averaging. | ||
| 1790 | - s = (s + self.tonal_average) >> 1; | ||
| 1791 | - self.tonal_average = s; | ||
| 1792 | - // Hysteresis against the last decision. | ||
| 1793 | - let last = self.spread_decision as i32; | ||
| 1794 | - s = (3 * s + (((3 - last) << 7) + 64) + 2) >> 2; | ||
| 1795 | - if s < 80 { | ||
| 1796 | - SPREAD_AGGRESSIVE | ||
| 1797 | - } else if s < 256 { | ||
| 1798 | - SPREAD_NORMAL | ||
| 1799 | - } else if s < 384 { | ||
| 1800 | - SPREAD_LIGHT | ||
| 1801 | - } else { | ||
| 1802 | - SPREAD_NONE | ||
| 1803 | - } | ||
| 1804 | - } | ||
| 1805 | - | ||
| 1806 | - fn compute_mdcts(&mut self, short_blocks: usize, lm: usize, n: usize, cc: usize, c: usize) { | ||
| 1807 | - let stride = n + OVERLAP; | ||
| 1808 | - let (n2, blocks, plan_lm) = if short_blocks != 0 { | ||
| 1809 | - (SHORT_MDCT, short_blocks, 0) | ||
| 1810 | - } else { | ||
| 1811 | - (n, 1, lm) | ||
| 1812 | - }; | ||
| 1813 | - for ch in 0..cc { | ||
| 1814 | - for b in 0..blocks { | ||
| 1815 | - let plan = &mut self.plans[plan_lm]; | ||
| 1816 | - plan.forward( | ||
| 1817 | - &self.in_buf, | ||
| 1818 | - ch * stride + b * n2, | ||
| 1819 | - &self.window, | ||
| 1820 | - &mut self.freq, | ||
| 1821 | - ch * n + b, | ||
| 1822 | - blocks, | ||
| 1823 | - ); | ||
| 1824 | - } | ||
| 1825 | - } | ||
| 1826 | - if cc == 2 && c == 1 { | ||
| 1827 | - for i in 0..n { | ||
| 1828 | - self.freq[i] = 0.5 * self.freq[i] + 0.5 * self.freq[n + i]; | ||
| 1829 | - } | ||
| 1830 | - } | ||
| 1831 | - } | ||
| 1832 | - | ||
| 1833 | - /// `alloc_trim_analysis()`: stereo correlation plus spectral tilt. | ||
| 1834 | - /// | ||
| 1835 | - /// This is the pre-1.1 libopus discrete ladder, not the continuous 1.3 | ||
| 1836 | - /// form. MEASURED (lane opustr r1, `lanes/opus-opustr-r1.sweep.txt`): the | ||
| 1837 | - /// whole 1.3 float function -- `trim += max(-4, .75*log2(1.001-sum^2))`, | ||
| 1838 | - /// `trim -= clamp(-2, 2, (diff+1)/6)` with `diff /= C*(end-1)`, and the | ||
| 1839 | - /// transient term `trim -= 2*tf_estimate` -- moves the 12-row library gate | ||
| 1840 | - /// 5 rows better / 4 worse on err_ratio (reelo@64 1.510->1.049, reell@96 | ||
| 1841 | - /// 4.499->2.458, nik@64 .708->.648, dl8a .552/.374->.487/.336; against | ||
| 1842 | - /// reell@64 2.697->2.872, her@96 1.051->1.085, nik@96 .985->1.006, her@64 | ||
| 1843 | - /// 1.103->1.109) and costs corr on every row (nik@64 .9887->.9878, | ||
| 1844 | - /// dl8a@64 .9889->.9879). The KEEP rule rejects it; this is the third | ||
| 1845 | - /// rejection of the same port (see `lanes/opus-trim-r2.{A,B}.sweep.txt`). | ||
| 1846 | - /// Do not re-port it without a fix for the transient rows first. | ||
| 1847 | - /// | ||
| 1848 | - /// `EC_OPUS_TRIM13=1` selects the continuous 1.3 form instead, for the | ||
| 1849 | - /// re-sweep on the aligned (delayed) spectrum the discrete ladder was | ||
| 1850 | - /// never measured against. | ||
| 1851 | - fn alloc_trim_analysis( | ||
| 1852 | - &mut self, | ||
| 1853 | - end: usize, | ||
| 1854 | - lm: usize, | ||
| 1855 | - c: usize, | ||
| 1856 | - n0: usize, | ||
| 1857 | - tf_estimate: f32, | ||
| 1858 | - ) -> i32 { | ||
| 1859 | - // Continuous (libopus 1.3+) trim; `EC_OPUS_TRIM13=0` restores the old discrete ladder. | ||
| 1860 | - let cont = !matches!(trim13_env(), Some(false)); | ||
| 1861 | - let mut trim_f = 5.0f32; | ||
| 1862 | - let mut trim = 5i32; | ||
| 1863 | - if c == 2 { | ||
| 1864 | - let mut sum = 0.0f32; | ||
| 1865 | - for i in 0..8 { | ||
| 1866 | - let mut partial = 0.0f32; | ||
| 1867 | - for j in (E_BANDS[i] << lm)..(E_BANDS[i + 1] << lm) { | ||
| 1868 | - partial += self.x[j] * self.x[n0 + j]; | ||
| 1869 | - } | ||
| 1870 | - sum += partial; | ||
| 1871 | - } | ||
| 1872 | - sum *= 1.0 / 8.0; | ||
| 1873 | - if cont { | ||
| 1874 | - let sum_c = sum.abs().min(1.0); | ||
| 1875 | - trim_f += (0.75 * (1.001 - sum_c * sum_c).log2()).max(-4.0); | ||
| 1876 | - } | ||
| 1877 | - if sum > 0.995 { | ||
| 1878 | - trim -= 4; | ||
| 1879 | - } else if sum > 0.92 { | ||
| 1880 | - trim -= 3; | ||
| 1881 | - } else if sum > 0.85 { | ||
| 1882 | - trim -= 2; | ||
| 1883 | - } else if sum > 0.8 { | ||
| 1884 | - trim -= 1; | ||
| 1885 | - } | ||
| 1886 | - // Stereo_saving: inter-channel correlation savings (libopus | ||
| 1887 | - // celt_encoder.c:897-920). In float mode all Q macros are | ||
| 1888 | - // identity; sum and per-band partial are raw inner products. | ||
| 1889 | - let sum_c = sum.abs().min(1.0); | ||
| 1890 | - let mut min_xc = sum_c; | ||
| 1891 | - for i in 8..self.intensity { | ||
| 1892 | - let mut partial = 0.0f32; | ||
| 1893 | - for j in (E_BANDS[i] << lm)..(E_BANDS[i + 1] << lm) { | ||
| 1894 | - partial += self.x[j] * self.x[n0 + j]; | ||
| 1895 | - } | ||
| 1896 | - min_xc = min_xc.min(partial.abs()); | ||
| 1897 | - } | ||
| 1898 | - min_xc = min_xc.min(1.0); | ||
| 1899 | - let log_xc = (1.001 - sum_c * sum_c).log2(); | ||
| 1900 | - let log_xc2 = (0.5 * log_xc).max((1.001 - min_xc * min_xc).log2()); | ||
| 1901 | - self.stereo_saving = (self.stereo_saving + 0.25).min(-0.5 * log_xc2); | ||
| 1902 | - } | ||
| 1903 | - let mut diff = 0.0f32; | ||
| 1904 | - for ch in 0..c { | ||
| 1905 | - for i in 0..end - 1 { | ||
| 1906 | - diff += self.band_log_e[i + ch * NB_BANDS] | ||
| 1907 | - * (2 + 2 * i as i32 - NB_BANDS as i32) as f32; | ||
| 1908 | - } | ||
| 1909 | - } | ||
| 1910 | - // libopus's `analysis->valid` term (celt_encoder.c:935-939): a tonal | ||
| 1911 | - // spectrum wants a lower trim. It is only defined on the continuous | ||
| 1912 | - // 1.3 trim; on the discrete ladder it can only be applied rounded, | ||
| 1913 | - // where it is inert (|term| <= .08). REJECTED with the 1.3 trim it | ||
| 1914 | - // belongs to -- see `analysis_params`, lane opustonal r1. | ||
| 1915 | - let tonal_trim = if analysis_params().1 && self.info.valid { | ||
| 1916 | - (2.0 * (self.info.tonality_slope + 0.05)).clamp(-2.0, 2.0) | ||
| 1917 | - } else { | ||
| 1918 | - 0.0 | ||
| 1919 | - }; | ||
| 1920 | - if cont { | ||
| 1921 | - // libopus divides the same sum by `C*(end-1)`; the ladder above | ||
| 1922 | - // carries an extra factor of two in its thresholds. | ||
| 1923 | - let diff = diff / (c * (end - 1)) as f32; | ||
| 1924 | - trim_f -= ((diff + 1.0) / 6.0).clamp(-2.0, 2.0); | ||
| 1925 | - trim_f -= 2.0 * tf_estimate; | ||
| 1926 | - trim_f -= tonal_trim; | ||
| 1927 | - return (trim_f + 0.5).floor().clamp(0.0, 10.0) as i32; | ||
| 1928 | - } | ||
| 1929 | - trim -= tonal_trim.round_ties_even() as i32; | ||
| 1930 | - diff /= (2 * c * (end - 1)) as f32; | ||
| 1931 | - if diff > 2.0 { | ||
| 1932 | - trim -= 1; | ||
| 1933 | - } | ||
| 1934 | - if diff > 8.0 { | ||
| 1935 | - trim -= 1; | ||
| 1936 | - } | ||
| 1937 | - if diff < -4.0 { | ||
| 1938 | - trim += 1; | ||
| 1939 | - } | ||
| 1940 | - if diff < -10.0 { | ||
| 1941 | - trim += 1; | ||
| 1942 | - } | ||
| 1943 | - trim.clamp(0, 10) | ||
| 1944 | - } | ||
| 1945 | - | ||
| 1946 | - /// libopus `equiv_rate` + `hysteresis_decision()` for the intensity band: | ||
| 1947 | - /// the frame's bytes as a 20 ms-equivalent bitrate minus the per-frame | ||
| 1948 | - /// overhead, capped by the VBR target. Idempotent within a frame. | ||
| 1949 | - fn intensity_decision(&mut self, nb_compressed: usize, c: usize, lm: usize, vbr_rate_bps: u32) { | ||
| 1950 | - let overhead = (40 * c as i32 + 20) * ((400 >> lm) - 50); | ||
| 1951 | - let mut equiv_rate = ((nb_compressed as i32 * 8 * 50) << (3 - lm)) - overhead; | ||
| 1952 | - if vbr_rate_bps > 0 { | ||
| 1953 | - equiv_rate = equiv_rate.min(vbr_rate_bps as i32 - overhead); | ||
| 1954 | - } | ||
| 1955 | - self.intensity = hysteresis_decision( | ||
| 1956 | - equiv_rate as f32 / 1000.0, | ||
| 1957 | - &INTENSITY_THRESHOLDS, | ||
| 1958 | - &INTENSITY_HYSTERESIS, | ||
| 1959 | - self.intensity, | ||
| 1960 | - ); | ||
| 1961 | - } | ||
| 1962 | - | ||
| 1963 | - /// `stereo_analysis()`: L1 entropy model of L/R against M/S. | ||
| 1964 | - fn stereo_analysis(&self, lm: usize, n0: usize) -> bool { | ||
| 1965 | - let mut sum_lr = 1e-15f64; | ||
| 1966 | - let mut sum_ms = 1e-15f64; | ||
| 1967 | - for i in 0..13 { | ||
| 1968 | - for j in (E_BANDS[i] << lm)..(E_BANDS[i + 1] << lm) { | ||
| 1969 | - let l = self.x[j] as f64; | ||
| 1970 | - let r = self.x[n0 + j] as f64; | ||
| 1971 | - sum_lr += l.abs() + r.abs(); | ||
| 1972 | - sum_ms += (l + r).abs() + (l - r).abs(); | ||
| 1973 | - } | ||
| 1974 | - } | ||
| 1975 | - // The reference's own literal (bands.c, stereo_analysis), kept as such. | ||
| 1976 | - #[allow(clippy::approx_constant)] | ||
| 1977 | - const SQRT_HALF: f64 = 0.707107; | ||
| 1978 | - sum_ms *= SQRT_HALF; | ||
| 1979 | - let mut thetas = 13; | ||
| 1980 | - if lm <= 1 { | ||
| 1981 | - thetas -= 8; | ||
| 1982 | - } | ||
| 1983 | - ((E_BANDS[13] << (lm + 1)) + thetas) as f64 * sum_ms | ||
| 1984 | - > ((E_BANDS[13] << (lm + 1)) as f64) * sum_lr | ||
| 1985 | - } | ||
| 1986 | - | ||
| 1987 | - // -- Energy -------------------------------------------------------------- | ||
| 1988 | - | ||
| 1989 | - #[allow(clippy::too_many_arguments)] | ||
| 1990 | - /// libopus `quant_coarse_energy_impl()`: codes one pass of coarse energy | ||
| 1991 | - /// with the given intra setting and returns its *badness* — the total | ||
| 1992 | - /// clamping the bit budget forced on the quantised deltas, which the | ||
| 1993 | - /// two-pass search in [`CeltEncoder::quant_coarse_energy`] minimises. | ||
| 1994 | - fn quant_coarse_energy_impl( | ||
| 1995 | - &mut self, | ||
| 1996 | - enc: &mut RangeEncoder, | ||
| 1997 | - start: usize, | ||
| 1998 | - end: usize, | ||
| 1999 | - intra: bool, | ||
| 2000 | - c: usize, | ||
crates/ec-opus/src/celt_flp/bands.rsadded+1234 -0
| @@ -0,0 +1,1234 @@ | |||
| 1 | +use super::vq::{alg_quant, renormalise_vector, stereo_itheta}; | ||
| 2 | +use super::{EPSILON, LOG_N, SHORT_MDCT, celt_rsqrt, celt_sqrt}; | ||
| 3 | +use crate::celt::{ | ||
| 4 | + BITRES, CACHE_BITS, E_BANDS, NB_BANDS, QTHETA_OFFSET, QTHETA_OFFSET_TWOPHASE, | ||
| 5 | + SPREAD_AGGRESSIVE, SPREAD_NONE, bitexact_cos, bitexact_log2tan, bits2pulses, cache_index, | ||
| 6 | + compute_qn, frac_mul16, get_pulses, pulses2bits, | ||
| 7 | +}; | ||
| 8 | +use crate::range::RangeEncoder; | ||
| 9 | + | ||
| 10 | +const BR: i32 = BITRES as i32; | ||
| 11 | +const MAX_BAND: usize = 176; | ||
| 12 | +const MAX_NORM: usize = 2 * 960; | ||
| 13 | +const MAX_BYTES: usize = 1275; | ||
| 14 | +const C70: f32 = 0.70710678; | ||
| 15 | +const ORDERY: [usize; 30] = [ | ||
| 16 | + 1, 0, 3, 0, 2, 1, 7, 0, 4, 3, 6, 1, 5, 2, 15, 0, 8, 7, 12, 3, 11, 4, 14, 1, 9, 6, 13, 2, 10, 5, | ||
| 17 | +]; | ||
| 18 | +const BIT_INTERLEAVE: [u8; 16] = [0, 1, 1, 1, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3]; | ||
| 19 | +const BIT_DEINTERLEAVE: [u8; 16] = [ | ||
| 20 | + 0x00, 0x03, 0x0C, 0x0F, 0x30, 0x33, 0x3C, 0x3F, 0xC0, 0xC3, 0xCC, 0xCF, 0xF0, 0xF3, 0xFC, 0xFF, | ||
| 21 | +]; | ||
| 22 | + | ||
| 23 | +#[derive(Clone, Copy)] | ||
| 24 | +struct BandCtx<'a> { | ||
| 25 | + resynth: bool, | ||
| 26 | + i: usize, | ||
| 27 | + intensity: usize, | ||
| 28 | + spread: i32, | ||
| 29 | + tf_change: i32, | ||
| 30 | + remaining_bits: i32, | ||
| 31 | + band_e: &'a [f32], | ||
| 32 | + seed: u32, | ||
| 33 | + theta_round: i32, | ||
| 34 | + disable_inv: bool, | ||
| 35 | + avoid_split_noise: bool, | ||
| 36 | +} | ||
| 37 | + | ||
| 38 | +struct SplitCtx { | ||
| 39 | + inv: bool, | ||
| 40 | + imid: i32, | ||
| 41 | + iside: i32, | ||
| 42 | + delta: i32, | ||
| 43 | + itheta: i32, | ||
| 44 | + qalloc: i32, | ||
| 45 | +} | ||
| 46 | + | ||
| 47 | +fn lcg_rand(seed: u32) -> u32 { | ||
| 48 | + seed.wrapping_mul(1664525).wrapping_add(1013904223) | ||
| 49 | +} | ||
| 50 | + | ||
| 51 | +fn inner(a: &[f32], b: &[f32]) -> f32 { | ||
| 52 | + let mut s = 0.0f32; | ||
| 53 | + for (p, q) in a.iter().zip(b) { | ||
| 54 | + s += p * q; | ||
| 55 | + } | ||
| 56 | + s | ||
| 57 | +} | ||
| 58 | + | ||
| 59 | +/// `hysteresis_decision`; the count `N` is `thresholds.len()`. | ||
| 60 | +pub(crate) fn hysteresis_decision( | ||
| 61 | + val: f32, | ||
| 62 | + thresholds: &[f32], | ||
| 63 | + hysteresis: &[f32], | ||
| 64 | + prev: i32, | ||
| 65 | +) -> i32 { | ||
| 66 | + let mut i = thresholds | ||
| 67 | + .iter() | ||
| 68 | + .position(|&t| val < t) | ||
| 69 | + .unwrap_or(thresholds.len()) as i32; | ||
| 70 | + if i > prev && val < thresholds[prev as usize] + hysteresis[prev as usize] { | ||
| 71 | + i = prev; | ||
| 72 | + } | ||
| 73 | + if i < prev && val > thresholds[(prev - 1) as usize] - hysteresis[(prev - 1) as usize] { | ||
| 74 | + i = prev; | ||
| 75 | + } | ||
| 76 | + i | ||
| 77 | +} | ||
| 78 | + | ||
| 79 | +/// `compute_band_energies`; `x` is C `X` (`c * (N << lm)` frequency bins as C lays them out), `band_e` is `c * 21`. | ||
| 80 | +pub(crate) fn compute_band_energies( | ||
| 81 | + x: &[f32], | ||
| 82 | + band_e: &mut [f32], | ||
| 83 | + end: usize, | ||
| 84 | + c: usize, | ||
| 85 | + lm: usize, | ||
| 86 | +) { | ||
| 87 | + let n = SHORT_MDCT << lm; | ||
| 88 | + for ch in 0..c { | ||
| 89 | + for i in 0..end { | ||
| 90 | + let lo = ch * n + (E_BANDS[i] << lm); | ||
| 91 | + let len = (E_BANDS[i + 1] - E_BANDS[i]) << lm; | ||
| 92 | + let s = &x[lo..lo + len]; | ||
| 93 | + let sum = 1e-27f32 + inner(s, s); | ||
| 94 | + band_e[i + ch * NB_BANDS] = celt_sqrt(sum); | ||
| 95 | + } | ||
| 96 | + } | ||
| 97 | +} | ||
| 98 | + | ||
| 99 | +/// `normalise_bands`; `m` is C `M` (`1 << lm`). | ||
| 100 | +pub(crate) fn normalise_bands( | ||
| 101 | + freq: &[f32], | ||
| 102 | + x: &mut [f32], | ||
| 103 | + band_e: &[f32], | ||
| 104 | + end: usize, | ||
| 105 | + c: usize, | ||
| 106 | + m: usize, | ||
| 107 | +) { | ||
| 108 | + let n = m * SHORT_MDCT; | ||
| 109 | + for ch in 0..c { | ||
| 110 | + for i in 0..end { | ||
| 111 | + let g = 1.0f32 / (1e-27f32 + band_e[i + ch * NB_BANDS]); | ||
| 112 | + for j in m * E_BANDS[i]..m * E_BANDS[i + 1] { | ||
| 113 | + x[j + ch * n] = freq[j + ch * n] * g; | ||
| 114 | + } | ||
| 115 | + } | ||
| 116 | + } | ||
| 117 | +} | ||
| 118 | + | ||
| 119 | +/// `spreading_decision`; returns the decision. | ||
| 120 | +pub(crate) fn spreading_decision( | ||
| 121 | + x: &[f32], | ||
| 122 | + average: &mut i32, | ||
| 123 | + last_decision: i32, | ||
| 124 | + hf_average: &mut i32, | ||
| 125 | + tapset_decision: &mut i32, | ||
| 126 | + update_hf: bool, | ||
| 127 | + end: usize, | ||
| 128 | + c: usize, | ||
| 129 | + m: usize, | ||
| 130 | + spread_weight: &[i32], | ||
| 131 | +) -> i32 { | ||
| 132 | + let n0 = m * SHORT_MDCT; | ||
| 133 | + let mut sum: i32 = 0; | ||
| 134 | + let mut nb_bands: i32 = 0; | ||
| 135 | + let mut hf_sum: i32 = 0; | ||
| 136 | + if m * (E_BANDS[end] - E_BANDS[end - 1]) <= 8 { | ||
| 137 | + return SPREAD_NONE as i32; | ||
| 138 | + } | ||
| 139 | + for ch in 0..c { | ||
| 140 | + for i in 0..end { | ||
| 141 | + let mut tcount = [0i32; 3]; | ||
| 142 | + let base = m * E_BANDS[i] + ch * n0; | ||
| 143 | + let n = (m * (E_BANDS[i + 1] - E_BANDS[i])) as i32; | ||
| 144 | + if n <= 8 { | ||
| 145 | + continue; | ||
| 146 | + } | ||
| 147 | + for j in 0..n as usize { | ||
| 148 | + let v = x[base + j]; | ||
| 149 | + let x2n = (v * v) * n as f32; | ||
| 150 | + if x2n < 0.25 { | ||
| 151 | + tcount[0] += 1; | ||
| 152 | + } | ||
| 153 | + if x2n < 0.0625 { | ||
| 154 | + tcount[1] += 1; | ||
| 155 | + } | ||
| 156 | + if x2n < 0.015625 { | ||
| 157 | + tcount[2] += 1; | ||
| 158 | + } | ||
| 159 | + } | ||
| 160 | + if i + 4 > NB_BANDS { | ||
| 161 | + hf_sum += 32 * (tcount[1] + tcount[0]) / n; | ||
| 162 | + } | ||
| 163 | + let tmp = (2 * tcount[2] >= n) as i32 | ||
| 164 | + + (2 * tcount[1] >= n) as i32 | ||
| 165 | + + (2 * tcount[0] >= n) as i32; | ||
| 166 | + sum += tmp * spread_weight[i]; | ||
| 167 | + nb_bands += spread_weight[i]; | ||
| 168 | + } | ||
| 169 | + } | ||
| 170 | + if update_hf { | ||
| 171 | + if hf_sum != 0 { | ||
| 172 | + hf_sum /= c as i32 * (4 - NB_BANDS as i32 + end as i32); | ||
| 173 | + } | ||
| 174 | + *hf_average = (*hf_average + hf_sum) >> 1; | ||
| 175 | + hf_sum = *hf_average; | ||
| 176 | + if *tapset_decision == 2 { | ||
| 177 | + hf_sum += 4; | ||
| 178 | + } else if *tapset_decision == 0 { | ||
| 179 | + hf_sum -= 4; | ||
| 180 | + } | ||
| 181 | + *tapset_decision = if hf_sum > 22 { | ||
| 182 | + 2 | ||
| 183 | + } else if hf_sum > 18 { | ||
| 184 | + 1 | ||
| 185 | + } else { | ||
| 186 | + 0 | ||
| 187 | + }; | ||
| 188 | + } | ||
| 189 | + sum = (sum << 8) / nb_bands; | ||
| 190 | + sum = (sum + *average) >> 1; | ||
| 191 | + *average = sum; | ||
| 192 | + sum = (3 * sum + (((3 - last_decision) << 7) + 64) + 2) >> 2; | ||
| 193 | + if sum < 80 { | ||
| 194 | + SPREAD_AGGRESSIVE as i32 | ||
| 195 | + } else if sum < 256 { | ||
| 196 | + 2 | ||
| 197 | + } else if sum < 384 { | ||
| 198 | + 1 | ||
| 199 | + } else { | ||
| 200 | + SPREAD_NONE as i32 | ||
| 201 | + } | ||
| 202 | +} | ||
| 203 | + | ||
| 204 | +fn deinterleave_hadamard(x: &mut [f32], n0: usize, stride: usize, hadamard: bool) { | ||
| 205 | + let n = n0 * stride; | ||
| 206 | + let mut tmp_buf = [0f32; MAX_BAND]; | ||
| 207 | + let tmp = &mut tmp_buf[..n]; | ||
| 208 | + if hadamard { | ||
| 209 | + let ordery = &ORDERY[stride - 2..]; | ||
| 210 | + for i in 0..stride { | ||
| 211 | + for j in 0..n0 { | ||
| 212 | + tmp[ordery[i] * n0 + j] = x[j * stride + i]; | ||
| 213 | + } | ||
| 214 | + } | ||
| 215 | + } else { | ||
| 216 | + for i in 0..stride { | ||
| 217 | + for j in 0..n0 { | ||
| 218 | + tmp[i * n0 + j] = x[j * stride + i]; | ||
| 219 | + } | ||
| 220 | + } | ||
| 221 | + } | ||
| 222 | + x[..n].copy_from_slice(tmp); | ||
| 223 | +} | ||
| 224 | + | ||
| 225 | +fn interleave_hadamard(x: &mut [f32], n0: usize, stride: usize, hadamard: bool) { | ||
| 226 | + let n = n0 * stride; | ||
| 227 | + let mut tmp_buf = [0f32; MAX_BAND]; | ||
| 228 | + let tmp = &mut tmp_buf[..n]; | ||
| 229 | + if hadamard { | ||
| 230 | + let ordery = &ORDERY[stride - 2..]; | ||
| 231 | + for i in 0..stride { | ||
| 232 | + for j in 0..n0 { | ||
| 233 | + tmp[j * stride + i] = x[ordery[i] * n0 + j]; | ||
| 234 | + } | ||
| 235 | + } | ||
| 236 | + } else { | ||
| 237 | + for i in 0..stride { | ||
| 238 | + for j in 0..n0 { | ||
| 239 | + tmp[j * stride + i] = x[i * n0 + j]; | ||
| 240 | + } | ||
| 241 | + } | ||
| 242 | + } | ||
| 243 | + x[..n].copy_from_slice(tmp); | ||
| 244 | +} | ||
| 245 | + | ||
| 246 | +fn haar1(x: &mut [f32], n0: usize, stride: usize) { | ||
| 247 | + let n0 = n0 >> 1; | ||
| 248 | + for i in 0..stride { | ||
| 249 | + for j in 0..n0 { | ||
| 250 | + let tmp1 = C70 * x[stride * 2 * j + i]; | ||
| 251 | + let tmp2 = C70 * x[stride * (2 * j + 1) + i]; | ||
| 252 | + x[stride * 2 * j + i] = tmp1 + tmp2; | ||
| 253 | + x[stride * (2 * j + 1) + i] = tmp1 - tmp2; | ||
| 254 | + } | ||
| 255 | + } | ||
| 256 | +} | ||
| 257 | + | ||
| 258 | +fn compute_channel_weights(ex: f32, ey: f32) -> [f32; 2] { | ||
| 259 | + let min_e = if ex < ey { ex } else { ey }; | ||
| 260 | + [ex + min_e / 3.0, ey + min_e / 3.0] | ||
| 261 | +} | ||
| 262 | + | ||
| 263 | +fn intensity_stereo(x: &mut [f32], y: &[f32], band_e: &[f32], i: usize, n: usize) { | ||
| 264 | + let left = band_e[i]; | ||
| 265 | + let right = band_e[i + NB_BANDS]; | ||
| 266 | + let norm = EPSILON + celt_sqrt(EPSILON + left * left + right * right); | ||
| 267 | + let a1 = left / norm; | ||
| 268 | + let a2 = right / norm; | ||
| 269 | + for j in 0..n { | ||
| 270 | + x[j] = a1 * x[j] + a2 * y[j]; | ||
| 271 | + } | ||
| 272 | +} | ||
| 273 | + | ||
| 274 | +fn stereo_split(x: &mut [f32], y: &mut [f32], n: usize) { | ||
| 275 | + for j in 0..n { | ||
| 276 | + let l = C70 * x[j]; | ||
| 277 | + let r = C70 * y[j]; | ||
| 278 | + x[j] = l + r; | ||
| 279 | + y[j] = r - l; | ||
| 280 | + } | ||
| 281 | +} | ||
| 282 | + | ||
| 283 | +fn stereo_merge(x: &mut [f32], y: &mut [f32], mid: f32, n: usize) { | ||
| 284 | + let mut xp = inner(&y[..n], &x[..n]); | ||
| 285 | + let side = inner(&y[..n], &y[..n]); | ||
| 286 | + xp *= mid; | ||
| 287 | + let el = mid * mid + side - 2.0 * xp; | ||
| 288 | + let er = mid * mid + side + 2.0 * xp; | ||
| 289 | + if er < 6e-4f32 || el < 6e-4f32 { | ||
| 290 | + y[..n].copy_from_slice(&x[..n]); | ||
| 291 | + return; | ||
| 292 | + } | ||
| 293 | + let lgain = celt_rsqrt(el); | ||
| 294 | + let rgain = celt_rsqrt(er); | ||
| 295 | + for j in 0..n { | ||
| 296 | + let l = mid * x[j]; | ||
| 297 | + let r = y[j]; | ||
| 298 | + x[j] = lgain * (l - r); | ||
| 299 | + y[j] = rgain * (l + r); | ||
| 300 | + } | ||
| 301 | +} | ||
| 302 | + | ||
| 303 | +fn special_hybrid_folding( | ||
| 304 | + norm: &mut [f32], | ||
| 305 | + norm2: &mut [f32], | ||
| 306 | + start: usize, | ||
| 307 | + m: usize, | ||
| 308 | + dual_stereo: bool, | ||
| 309 | +) { | ||
| 310 | + let n1 = m * (E_BANDS[start + 1] - E_BANDS[start]); | ||
| 311 | + let n2 = m * (E_BANDS[start + 2] - E_BANDS[start + 1]); | ||
| 312 | + norm.copy_within(2 * n1 - n2..n1, n1); | ||
| 313 | + if dual_stereo { | ||
| 314 | + norm2.copy_within(2 * n1 - n2..n1, n1); | ||
| 315 | + } | ||
| 316 | +} | ||
| 317 | + | ||
| 318 | +fn cache_top(band: usize, lm: i32) -> i32 { | ||
| 319 | + let base = cache_index(band, lm); | ||
| 320 | + CACHE_BITS[base + CACHE_BITS[base] as usize] as i32 | ||
| 321 | +} | ||
| 322 | + | ||
| 323 | +fn theta_delta(n: i32, imid: i32, iside: i32) -> i32 { | ||
| 324 | + frac_mul16(((n - 1) << 7) as i16, bitexact_log2tan(iside, imid) as i16) | ||
| 325 | +} | ||
| 326 | + | ||
| 327 | +fn compute_theta( | ||
| 328 | + ctx: &mut BandCtx, | ||
| 329 | + enc: &mut RangeEncoder, | ||
| 330 | + x: &mut [f32], | ||
| 331 | + y: &mut [f32], | ||
| 332 | + n: usize, | ||
| 333 | + b: &mut i32, | ||
| 334 | + bb: i32, | ||
| 335 | + b0: i32, | ||
| 336 | + lm: i32, | ||
| 337 | + stereo: bool, | ||
| 338 | + fill: &mut i32, | ||
| 339 | +) -> SplitCtx { | ||
| 340 | + let i = ctx.i; | ||
| 341 | + let ni = n as i32; | ||
| 342 | + let pulse_cap = LOG_N[i] + lm * (1 << BR); | ||
| 343 | + let offset = (pulse_cap >> 1) | ||
| 344 | + - if stereo && n == 2 { | ||
| 345 | + QTHETA_OFFSET_TWOPHASE | ||
| 346 | + } else { | ||
| 347 | + QTHETA_OFFSET | ||
| 348 | + }; | ||
| 349 | + let mut qn = compute_qn(ni, *b, offset, pulse_cap, stereo); | ||
| 350 | + if stereo && i >= ctx.intensity { | ||
| 351 | + qn = 1; | ||
| 352 | + } | ||
| 353 | + let mut itheta = stereo_itheta(x, y, stereo, n) >> 16; | ||
| 354 | + let tell = enc.tell_frac() as i32; | ||
| 355 | + let mut inv = false; | ||
| 356 | + if qn != 1 { | ||
| 357 | + if !stereo || ctx.theta_round == 0 { | ||
| 358 | + itheta = (itheta * qn + 8192) >> 14; | ||
| 359 | + if !stereo && ctx.avoid_split_noise && itheta > 0 && itheta < qn { | ||
| 360 | + let unquantized = itheta * 16384 / qn; | ||
| 361 | + let imid = bitexact_cos(unquantized as i16) as i32; | ||
| 362 | + let iside = bitexact_cos((16384 - unquantized) as i16) as i32; | ||
| 363 | + let delta = theta_delta(ni, imid, iside); | ||
| 364 | + if delta > *b { | ||
| 365 | + itheta = qn; | ||
| 366 | + } else if delta < -*b { | ||
| 367 | + itheta = 0; | ||
| 368 | + } | ||
| 369 | + } | ||
| 370 | + } else { | ||
| 371 | + let bias = if itheta > 8192 { | ||
| 372 | + 32767 / qn | ||
| 373 | + } else { | ||
| 374 | + -32767 / qn | ||
| 375 | + }; | ||
| 376 | + let down = (qn - 1).min(((itheta * qn + bias) >> 14).max(0)); | ||
| 377 | + itheta = if ctx.theta_round < 0 { down } else { down + 1 }; | ||
| 378 | + } | ||
| 379 | + if stereo && n > 2 { | ||
| 380 | + let p0 = 3; | ||
| 381 | + let x0 = qn / 2; | ||
| 382 | + let ft = p0 * (x0 + 1) + x0; | ||
| 383 | + let (fl, fh) = if itheta <= x0 { | ||
| 384 | + (p0 * itheta, p0 * (itheta + 1)) | ||
| 385 | + } else { | ||
| 386 | + ( | ||
| 387 | + (itheta - 1 - x0) + (x0 + 1) * p0, | ||
| 388 | + (itheta - x0) + (x0 + 1) * p0, | ||
| 389 | + ) | ||
| 390 | + }; | ||
| 391 | + enc.encode(fl as u32, fh as u32, ft as u32); | ||
| 392 | + } else if b0 > 1 || stereo { | ||
| 393 | + enc.enc_uint(itheta as u32, (qn + 1) as u32); | ||
| 394 | + } else { | ||
| 395 | + let ft = ((qn >> 1) + 1) * ((qn >> 1) + 1); | ||
| 396 | + let fs = if itheta <= (qn >> 1) { | ||
| 397 | + itheta + 1 | ||
| 398 | + } else { | ||
| 399 | + qn + 1 - itheta | ||
| 400 | + }; | ||
| 401 | + let fl = if itheta <= (qn >> 1) { | ||
| 402 | + (itheta * (itheta + 1)) >> 1 | ||
| 403 | + } else { | ||
| 404 | + ft - (((qn + 1 - itheta) * (qn + 2 - itheta)) >> 1) | ||
| 405 | + }; | ||
| 406 | + enc.encode(fl as u32, (fl + fs) as u32, ft as u32); | ||
| 407 | + } | ||
| 408 | + itheta = itheta * 16384 / qn; | ||
| 409 | + if stereo { | ||
| 410 | + if itheta == 0 { | ||
| 411 | + intensity_stereo(x, y, ctx.band_e, i, n); | ||
| 412 | + } else { | ||
| 413 | + stereo_split(x, y, n); | ||
| 414 | + } | ||
| 415 | + } | ||
| 416 | + } else if stereo { | ||
| 417 | + inv = itheta > 8192 && !ctx.disable_inv; | ||
| 418 | + if inv { | ||
| 419 | + for v in y[..n].iter_mut() { | ||
| 420 | + *v = -*v; | ||
| 421 | + } | ||
| 422 | + } | ||
| 423 | + intensity_stereo(x, y, ctx.band_e, i, n); | ||
| 424 | + if *b > 2 << BR && ctx.remaining_bits > 2 << BR { | ||
| 425 | + enc.enc_bit_logp(inv, 2); | ||
| 426 | + } else { | ||
| 427 | + inv = false; | ||
| 428 | + } | ||
| 429 | + if ctx.disable_inv { | ||
| 430 | + inv = false; | ||
| 431 | + } | ||
| 432 | + itheta = 0; | ||
| 433 | + } | ||
| 434 | + let qalloc = enc.tell_frac() as i32 - tell; | ||
| 435 | + *b -= qalloc; | ||
| 436 | + | ||
| 437 | + let (imid, iside, delta) = if itheta == 0 { | ||
| 438 | + *fill &= (1 << bb) - 1; | ||
| 439 | + (32767, 0, -16384) | ||
| 440 | + } else if itheta == 16384 { | ||
| 441 | + *fill &= ((1 << bb) - 1) << bb; | ||
| 442 | + (0, 32767, 16384) | ||
| 443 | + } else { | ||
| 444 | + let imid = bitexact_cos(itheta as i16) as i32; | ||
| 445 | + let iside = bitexact_cos((16384 - itheta) as i16) as i32; | ||
| 446 | + (imid, iside, theta_delta(ni, imid, iside)) | ||
| 447 | + }; | ||
| 448 | + SplitCtx { | ||
| 449 | + inv, | ||
| 450 | + imid, | ||
| 451 | + iside, | ||
| 452 | + delta, | ||
| 453 | + itheta, | ||
| 454 | + qalloc, | ||
| 455 | + } | ||
| 456 | +} | ||
| 457 | + | ||
| 458 | +fn n1_channel(ctx: &mut BandCtx, enc: &mut RangeEncoder, v: &mut f32) { | ||
| 459 | + let mut sign = false; | ||
| 460 | + if ctx.remaining_bits >= 1 << BR { | ||
| 461 | + sign = *v < 0.0; | ||
| 462 | + enc.enc_bits(sign as u32, 1); | ||
| 463 | + ctx.remaining_bits -= 1 << BR; | ||
| 464 | + } | ||
| 465 | + if ctx.resynth { | ||
| 466 | + *v = if sign { -1.0 } else { 1.0 }; | ||
| 467 | + } | ||
| 468 | +} | ||
| 469 | + | ||
| 470 | +fn quant_band_n1( | ||
| 471 | + ctx: &mut BandCtx, | ||
| 472 | + enc: &mut RangeEncoder, | ||
| 473 | + x: &mut [f32], | ||
| 474 | + y: Option<&mut [f32]>, | ||
| 475 | + lowband_out: Option<&mut [f32]>, | ||
| 476 | +) -> u32 { | ||
| 477 | + n1_channel(ctx, enc, &mut x[0]); | ||
| 478 | + if let Some(y) = y { | ||
| 479 | + n1_channel(ctx, enc, &mut y[0]); | ||
| 480 | + } | ||
| 481 | + if let Some(out) = lowband_out { | ||
| 482 | + out[0] = x[0]; | ||
| 483 | + } | ||
| 484 | + 1 | ||
| 485 | +} | ||
| 486 | + | ||
| 487 | +fn quant_partition( | ||
| 488 | + ctx: &mut BandCtx, | ||
| 489 | + enc: &mut RangeEncoder, | ||
| 490 | + x: &mut [f32], | ||
| 491 | + n: usize, | ||
| 492 | + b: i32, | ||
| 493 | + bb: i32, | ||
| 494 | + lowband: Option<&mut [f32]>, | ||
| 495 | + lm: i32, | ||
| 496 | + gain: f32, | ||
| 497 | + fill: i32, | ||
| 498 | +) -> u32 { | ||
| 499 | + let i = ctx.i; | ||
| 500 | + let b0 = bb; | ||
| 501 | + let mut n = n; | ||
| 502 | + let mut b = b; | ||
| 503 | + let mut bb = bb; | ||
| 504 | + let mut lm = lm; | ||
| 505 | + let mut fill = fill; | ||
| 506 | + if lm != -1 && b > cache_top(i, lm) + 12 && n > 2 { | ||
| 507 | + n >>= 1; | ||
| 508 | + lm -= 1; | ||
| 509 | + if bb == 1 { | ||
| 510 | + fill = (fill & 1) | (fill << 1); | ||
| 511 | + } | ||
| 512 | + bb = (bb + 1) >> 1; | ||
| 513 | + let (xa, ya) = x[..2 * n].split_at_mut(n); | ||
| 514 | + let sc = compute_theta(ctx, enc, xa, ya, n, &mut b, bb, b0, lm, false, &mut fill); | ||
| 515 | + let mid = (1.0f32 / 32768.0) * sc.imid as f32; | ||
| 516 | + let side = (1.0f32 / 32768.0) * sc.iside as f32; | ||
| 517 | + let itheta = sc.itheta; | ||
| 518 | + let mut delta = sc.delta; | ||
| 519 | + if b0 > 1 && (itheta & 0x3fff) != 0 { | ||
| 520 | + if itheta > 8192 { | ||
| 521 | + delta -= delta >> (4 - lm); | ||
| 522 | + } else { | ||
| 523 | + delta = (delta + (((n as i32) << BR) >> (5 - lm))).min(0); | ||
| 524 | + } | ||
| 525 | + } | ||
| 526 | + let mut mbits = 0.max(b.min((b - delta) / 2)); | ||
| 527 | + let mut sbits = b - mbits; | ||
| 528 | + ctx.remaining_bits -= sc.qalloc; | ||
| 529 | + let rem_before = ctx.remaining_bits; | ||
| 530 | + let (lb1, lb2) = match lowband { | ||
| 531 | + Some(lb) => { | ||
| 532 | + let (p, q) = lb.split_at_mut(n); | ||
| 533 | + (Some(p), Some(q)) | ||
| 534 | + } | ||
| 535 | + None => (None, None), | ||
| 536 | + }; | ||
| 537 | + if mbits >= sbits { | ||
| 538 | + let c1 = quant_partition(ctx, enc, xa, n, mbits, bb, lb1, lm, gain * mid, fill); | ||
| 539 | + let rb = mbits - (rem_before - ctx.remaining_bits); | ||
| 540 | + if rb > 3 << BR && itheta != 0 { | ||
| 541 | + sbits += rb - (3 << BR); | ||
| 542 | + } | ||
| 543 | + c1 | (quant_partition(ctx, enc, ya, n, sbits, bb, lb2, lm, gain * side, fill >> bb) | ||
| 544 | + << (b0 >> 1)) | ||
| 545 | + } else { | ||
| 546 | + let c1 = quant_partition(ctx, enc, ya, n, sbits, bb, lb2, lm, gain * side, fill >> bb) | ||
| 547 | + << (b0 >> 1); | ||
| 548 | + let rb = sbits - (rem_before - ctx.remaining_bits); | ||
| 549 | + if rb > 3 << BR && itheta != 16384 { | ||
| 550 | + mbits += rb - (3 << BR); | ||
| 551 | + } | ||
| 552 | + c1 | quant_partition(ctx, enc, xa, n, mbits, bb, lb1, lm, gain * mid, fill) | ||
| 553 | + } | ||
| 554 | + } else { | ||
| 555 | + let mut q = bits2pulses(i, lm, b); | ||
| 556 | + let mut curr_bits = pulses2bits(i, lm, q); | ||
| 557 | + ctx.remaining_bits -= curr_bits; | ||
| 558 | + while ctx.remaining_bits < 0 && q > 0 { | ||
| 559 | + ctx.remaining_bits += curr_bits; | ||
| 560 | + q -= 1; | ||
| 561 | + curr_bits = pulses2bits(i, lm, q); | ||
| 562 | + ctx.remaining_bits -= curr_bits; | ||
| 563 | + } | ||
| 564 | + if q != 0 { | ||
| 565 | + let k = get_pulses(q); | ||
| 566 | + alg_quant(x, n, k, ctx.spread, bb, enc, gain, ctx.resynth) | ||
| 567 | + } else if ctx.resynth { | ||
| 568 | + let cm_mask: u32 = (1u32 << bb) - 1; | ||
| 569 | + fill &= cm_mask as i32; | ||
| 570 | + if fill == 0 { | ||
| 571 | + x[..n].fill(0.0); | ||
| 572 | + 0 | ||
| 573 | + } else { | ||
| 574 | + let cm = match lowband { | ||
| 575 | + None => { | ||
| 576 | + for v in x[..n].iter_mut() { | ||
| 577 | + ctx.seed = lcg_rand(ctx.seed); | ||
| 578 | + *v = ((ctx.seed as i32) >> 20) as f32; | ||
| 579 | + } | ||
| 580 | + cm_mask | ||
| 581 | + } | ||
| 582 | + Some(lb) => { | ||
| 583 | + for j in 0..n { | ||
| 584 | + ctx.seed = lcg_rand(ctx.seed); | ||
| 585 | + let tmp = 1.0f32 / 256.0; | ||
| 586 | + let tmp = if ctx.seed & 0x8000 != 0 { tmp } else { -tmp }; | ||
| 587 | + x[j] = lb[j] + tmp; | ||
| 588 | + } | ||
| 589 | + fill as u32 | ||
| 590 | + } | ||
| 591 | + }; | ||
| 592 | + renormalise_vector(x, n, gain); | ||
| 593 | + cm | ||
| 594 | + } | ||
| 595 | + } else { | ||
| 596 | + 0 | ||
| 597 | + } | ||
| 598 | + } | ||
| 599 | +} | ||
| 600 | + | ||
| 601 | +fn opt_scratch(on: bool, buf: &mut [f32]) -> Option<&mut [f32]> { | ||
| 602 | + if on { Some(buf) } else { None } | ||
| 603 | +} | ||
| 604 | + | ||
| 605 | +fn quant_band( | ||
| 606 | + ctx: &mut BandCtx, | ||
| 607 | + enc: &mut RangeEncoder, | ||
| 608 | + x: &mut [f32], | ||
| 609 | + n: usize, | ||
| 610 | + b: i32, | ||
| 611 | + bb: i32, | ||
| 612 | + lowband: Option<&mut [f32]>, | ||
| 613 | + lm: i32, | ||
| 614 | + lowband_out: Option<&mut [f32]>, | ||
| 615 | + gain: f32, | ||
| 616 | + lowband_scratch: Option<&mut [f32]>, | ||
| 617 | + fill: i32, | ||
| 618 | +) -> u32 { | ||
| 619 | + if n == 1 { | ||
| 620 | + return quant_band_n1(ctx, enc, x, None, lowband_out); | ||
| 621 | + } | ||
| 622 | + let n0 = n; | ||
| 623 | + let b0_long = bb; | ||
| 624 | + let long_blocks = b0_long == 1; | ||
| 625 | + let mut bb = bb; | ||
| 626 | + let mut fill = fill; | ||
| 627 | + let mut n_b = (n as i32) / bb; | ||
| 628 | + let mut tf_change = ctx.tf_change; | ||
| 629 | + let recombine = if tf_change > 0 { tf_change } else { 0 }; | ||
| 630 | + let copy = recombine != 0 || ((n_b & 1) == 0 && tf_change < 0) || b0_long > 1; | ||
| 631 | + let mut lowband = match (lowband, lowband_scratch) { | ||
| 632 | + (Some(lb), Some(sc)) if copy => { | ||
| 633 | + sc[..n].copy_from_slice(&lb[..n]); | ||
| 634 | + Some(sc) | ||
| 635 | + } | ||
| 636 | + (lb, _) => lb, | ||
| 637 | + }; | ||
| 638 | + for k in 0..recombine as usize { | ||
| 639 | + haar1(x, n0 >> k, 1 << k); | ||
| 640 | + if let Some(lb) = lowband.as_deref_mut() { | ||
| 641 | + haar1(lb, n0 >> k, 1 << k); | ||
| 642 | + } | ||
| 643 | + fill = BIT_INTERLEAVE[(fill & 0xF) as usize] as i32 | ||
| 644 | + | ((BIT_INTERLEAVE[(fill >> 4) as usize] as i32) << 2); | ||
| 645 | + } | ||
| 646 | + bb >>= recombine; | ||
| 647 | + n_b <<= recombine; | ||
| 648 | + let mut time_divide = 0; | ||
| 649 | + while (n_b & 1) == 0 && tf_change < 0 { | ||
| 650 | + haar1(x, n_b as usize, bb as usize); | ||
| 651 | + if let Some(lb) = lowband.as_deref_mut() { | ||
| 652 | + haar1(lb, n_b as usize, bb as usize); | ||
| 653 | + } | ||
| 654 | + fill |= fill << bb; | ||
| 655 | + bb <<= 1; | ||
| 656 | + n_b >>= 1; | ||
| 657 | + time_divide += 1; | ||
| 658 | + tf_change += 1; | ||
| 659 | + } | ||
| 660 | + let b0 = bb; | ||
| 661 | + let n_b0 = n_b; | ||
| 662 | + if b0 > 1 { | ||
| 663 | + deinterleave_hadamard( | ||
| 664 | + x, | ||
| 665 | + (n_b >> recombine) as usize, | ||
| 666 | + (b0 << recombine) as usize, | ||
| 667 | + long_blocks, | ||
| 668 | + ); | ||
| 669 | + if let Some(lb) = lowband.as_deref_mut() { | ||
| 670 | + deinterleave_hadamard( | ||
| 671 | + lb, | ||
| 672 | + (n_b >> recombine) as usize, | ||
| 673 | + (b0 << recombine) as usize, | ||
| 674 | + long_blocks, | ||
| 675 | + ); | ||
| 676 | + } | ||
| 677 | + } | ||
| 678 | + let mut cm = quant_partition(ctx, enc, x, n, b, bb, lowband, lm, gain, fill); | ||
| 679 | + if ctx.resynth { | ||
| 680 | + if b0 > 1 { | ||
| 681 | + interleave_hadamard( | ||
| 682 | + x, | ||
| 683 | + (n_b >> recombine) as usize, | ||
| 684 | + (b0 << recombine) as usize, | ||
| 685 | + long_blocks, | ||
| 686 | + ); | ||
| 687 | + } | ||
| 688 | + n_b = n_b0; | ||
| 689 | + bb = b0; | ||
| 690 | + for _ in 0..time_divide { | ||
| 691 | + bb >>= 1; | ||
| 692 | + n_b <<= 1; | ||
| 693 | + cm |= cm >> bb; | ||
| 694 | + haar1(x, n_b as usize, bb as usize); | ||
| 695 | + } | ||
| 696 | + for k in 0..recombine as usize { | ||
| 697 | + cm = BIT_DEINTERLEAVE[cm as usize] as u32; | ||
| 698 | + haar1(x, n0 >> k, 1 << k); | ||
| 699 | + } | ||
| 700 | + bb <<= recombine; | ||
| 701 | + if let Some(out) = lowband_out { | ||
| 702 | + let nn = celt_sqrt(n0 as f32); | ||
| 703 | + for j in 0..n0 { | ||
| 704 | + out[j] = nn * x[j]; | ||
| 705 | + } | ||
| 706 | + } | ||
| 707 | + cm &= (1u32 << bb) - 1; | ||
| 708 | + } | ||
| 709 | + cm | ||
| 710 | +} | ||
| 711 | + | ||
| 712 | +fn quant_band_stereo( | ||
| 713 | + ctx: &mut BandCtx, | ||
| 714 | + enc: &mut RangeEncoder, | ||
| 715 | + x: &mut [f32], | ||
| 716 | + y: &mut [f32], | ||
| 717 | + n: usize, | ||
| 718 | + b: i32, | ||
| 719 | + bb: i32, | ||
| 720 | + lowband: Option<&mut [f32]>, | ||
| 721 | + lm: i32, | ||
| 722 | + lowband_out: Option<&mut [f32]>, | ||
| 723 | + lowband_scratch: Option<&mut [f32]>, | ||
| 724 | + fill: i32, | ||
| 725 | +) -> u32 { | ||
| 726 | + if n == 1 { | ||
| 727 | + return quant_band_n1(ctx, enc, x, Some(y), lowband_out); | ||
| 728 | + } | ||
| 729 | + let i = ctx.i; | ||
| 730 | + let nb = NB_BANDS; | ||
| 731 | + let orig_fill = fill; | ||
| 732 | + if ctx.band_e[i] < 1e-10 || ctx.band_e[nb + i] < 1e-10 { | ||
| 733 | + if ctx.band_e[i] > ctx.band_e[nb + i] { | ||
| 734 | + y[..n].copy_from_slice(&x[..n]); | ||
| 735 | + } else { | ||
| 736 | + x[..n].copy_from_slice(&y[..n]); | ||
| 737 | + } | ||
| 738 | + } | ||
| 739 | + let mut fill = fill; | ||
| 740 | + let mut bm = b; | ||
| 741 | + let sc = compute_theta(ctx, enc, x, y, n, &mut bm, bb, bb, lm, true, &mut fill); | ||
| 742 | + let mid = (1.0f32 / 32768.0) * sc.imid as f32; | ||
| 743 | + let side = (1.0f32 / 32768.0) * sc.iside as f32; | ||
| 744 | + let cm = if n == 2 { | ||
| 745 | + let mut mbits = bm; | ||
| 746 | + let mut sbits = 0; | ||
| 747 | + if sc.itheta != 0 && sc.itheta != 16384 { | ||
| 748 | + sbits = 1 << BR; | ||
| 749 | + } | ||
| 750 | + mbits -= sbits; | ||
| 751 | + let c = sc.itheta > 8192; | ||
| 752 | + ctx.remaining_bits -= sc.qalloc + sbits; | ||
| 753 | + let (x2, y2): (&mut [f32], &mut [f32]) = if c { | ||
| 754 | + (&mut *y, &mut *x) | ||
| 755 | + } else { | ||
| 756 | + (&mut *x, &mut *y) | ||
| 757 | + }; | ||
| 758 | + let mut sign = 0i32; | ||
| 759 | + if sbits != 0 { | ||
| 760 | + sign = (x2[0] * y2[1] - x2[1] * y2[0] < 0.0) as i32; | ||
| 761 | + enc.enc_bits(sign as u32, 1); | ||
| 762 | + } | ||
| 763 | + let sign = 1 - 2 * sign; | ||
| 764 | + let cm = quant_band( | ||
| 765 | + ctx, | ||
| 766 | + enc, | ||
| 767 | + x2, | ||
| 768 | + 2, | ||
| 769 | + mbits, | ||
| 770 | + bb, | ||
| 771 | + lowband, | ||
| 772 | + lm, | ||
| 773 | + lowband_out, | ||
| 774 | + 1.0, | ||
| 775 | + lowband_scratch, | ||
| 776 | + orig_fill, | ||
| 777 | + ); | ||
| 778 | + y2[0] = (-sign) as f32 * x2[1]; | ||
| 779 | + y2[1] = sign as f32 * x2[0]; | ||
| 780 | + cm | ||
| 781 | + } else { | ||
| 782 | + let mut mbits = 0.max(bm.min((bm - sc.delta) / 2)); | ||
| 783 | + let mut sbits = bm - mbits; | ||
| 784 | + ctx.remaining_bits -= sc.qalloc; | ||
| 785 | + let rem_before = ctx.remaining_bits; | ||
| 786 | + if mbits >= sbits { | ||
| 787 | + let c1 = quant_band( | ||
| 788 | + ctx, | ||
| 789 | + enc, | ||
| 790 | + x, | ||
| 791 | + n, | ||
| 792 | + mbits, | ||
| 793 | + bb, | ||
| 794 | + lowband, | ||
| 795 | + lm, | ||
| 796 | + lowband_out, | ||
| 797 | + 1.0, | ||
| 798 | + lowband_scratch, | ||
| 799 | + fill, | ||
| 800 | + ); | ||
| 801 | + let rb = mbits - (rem_before - ctx.remaining_bits); | ||
| 802 | + if rb > 3 << BR && sc.itheta != 0 { | ||
| 803 | + sbits += rb - (3 << BR); | ||
| 804 | + } | ||
| 805 | + c1 | quant_band( | ||
| 806 | + ctx, | ||
| 807 | + enc, | ||
| 808 | + y, | ||
| 809 | + n, | ||
| 810 | + sbits, | ||
| 811 | + bb, | ||
| 812 | + None, | ||
| 813 | + lm, | ||
| 814 | + None, | ||
| 815 | + side, | ||
| 816 | + None, | ||
| 817 | + fill >> bb, | ||
| 818 | + ) | ||
| 819 | + } else { | ||
| 820 | + let c1 = quant_band( | ||
| 821 | + ctx, | ||
| 822 | + enc, | ||
| 823 | + y, | ||
| 824 | + n, | ||
| 825 | + sbits, | ||
| 826 | + bb, | ||
| 827 | + None, | ||
| 828 | + lm, | ||
| 829 | + None, | ||
| 830 | + side, | ||
| 831 | + None, | ||
| 832 | + fill >> bb, | ||
| 833 | + ); | ||
| 834 | + let rb = sbits - (rem_before - ctx.remaining_bits); | ||
| 835 | + if rb > 3 << BR && sc.itheta != 16384 { | ||
| 836 | + mbits += rb - (3 << BR); | ||
| 837 | + } | ||
| 838 | + c1 | quant_band( | ||
| 839 | + ctx, | ||
| 840 | + enc, | ||
| 841 | + x, | ||
| 842 | + n, | ||
| 843 | + mbits, | ||
| 844 | + bb, | ||
| 845 | + lowband, | ||
| 846 | + lm, | ||
| 847 | + lowband_out, | ||
| 848 | + 1.0, | ||
| 849 | + lowband_scratch, | ||
| 850 | + fill, | ||
| 851 | + ) | ||
| 852 | + } | ||
| 853 | + }; | ||
| 854 | + if ctx.resynth { | ||
| 855 | + if n == 2 { | ||
| 856 | + x[0] *= mid; | ||
| 857 | + x[1] *= mid; | ||
| 858 | + y[0] *= side; | ||
| 859 | + y[1] *= side; | ||
| 860 | + let tmp = x[0]; | ||
| 861 | + x[0] = tmp - y[0]; | ||
| 862 | + y[0] += tmp; | ||
| 863 | + let tmp = x[1]; | ||
| 864 | + x[1] = tmp - y[1]; | ||
| 865 | + y[1] += tmp; | ||
| 866 | + } else { | ||
| 867 | + stereo_merge(x, y, mid, n); | ||
| 868 | + } | ||
| 869 | + if sc.inv { | ||
| 870 | + for v in y[..n].iter_mut() { | ||
| 871 | + *v = -*v; | ||
| 872 | + } | ||
| 873 | + } | ||
| 874 | + } | ||
| 875 | + cm | ||
| 876 | +} | ||
| 877 | + | ||
| 878 | +fn store(buf: &mut [f32], off: usize, v: Option<&[f32]>) { | ||
| 879 | + if let Some(v) = v { | ||
| 880 | + buf[off..off + v.len()].copy_from_slice(v); | ||
| 881 | + } | ||
| 882 | +} | ||
| 883 | + | ||
| 884 | +fn lowband_copy<'a>( | ||
| 885 | + buf: &'a mut [f32; MAX_BAND], | ||
| 886 | + norm: &[f32], | ||
| 887 | + e: Option<usize>, | ||
| 888 | + nu: usize, | ||
| 889 | +) -> Option<&'a mut [f32]> { | ||
| 890 | + let e = e?; | ||
| 891 | + buf[..nu].copy_from_slice(&norm[e..e + nu]); | ||
| 892 | + Some(&mut buf[..nu]) | ||
| 893 | +} | ||
| 894 | + | ||
| 895 | +/// `quant_all_bands` with `encode = 1` (no QEXT); `y` is C `Y` (None for mono). | ||
| 896 | +pub(crate) fn quant_all_bands( | ||
| 897 | + start: usize, | ||
| 898 | + end: usize, | ||
| 899 | + x: &mut [f32], | ||
| 900 | + y: Option<&mut [f32]>, | ||
| 901 | + collapse_masks: &mut [u8], | ||
| 902 | + band_e: &[f32], | ||
| 903 | + pulses: &[i32], | ||
| 904 | + short_blocks: bool, | ||
| 905 | + spread: i32, | ||
| 906 | + dual_stereo: bool, | ||
| 907 | + intensity: usize, | ||
| 908 | + tf_res: &[i32], | ||
| 909 | + total_bits: i32, | ||
| 910 | + balance: i32, | ||
| 911 | + enc: &mut RangeEncoder, | ||
| 912 | + lm: usize, | ||
| 913 | + coded_bands: usize, | ||
| 914 | + seed: &mut u32, | ||
| 915 | + complexity: i32, | ||
| 916 | + disable_inv: bool, | ||
| 917 | +) { | ||
| 918 | + let mut y = y; | ||
| 919 | + let mut dual_stereo = dual_stereo; | ||
| 920 | + let mut balance = balance; | ||
| 921 | + let c = if y.is_some() { 2 } else { 1 }; | ||
| 922 | + let theta_rdo = y.is_some() && !dual_stereo && complexity >= 8; | ||
| 923 | + let resynth = theta_rdo; | ||
| 924 | + let m = 1usize << lm; | ||
| 925 | + let lm = lm as i32; | ||
| 926 | + let b_full = if short_blocks { m as i32 } else { 1 }; | ||
| 927 | + let eb = |k: usize| (m * E_BANDS[k]) as i32; | ||
| 928 | + let norm_offset = eb(start); | ||
| 929 | + let norm_len = (eb(NB_BANDS - 1) - norm_offset) as usize; | ||
| 930 | + let mut norm_buf = [0f32; MAX_NORM]; | ||
| 931 | + let mut norm2_buf = [0f32; MAX_NORM]; | ||
| 932 | + let norm = &mut norm_buf[..norm_len]; | ||
| 933 | + let norm2 = &mut norm2_buf[..norm_len]; | ||
| 934 | + let scratch_len = if resynth { | ||
| 935 | + m * (E_BANDS[NB_BANDS] - E_BANDS[NB_BANDS - 1]) | ||
| 936 | + } else { | ||
| 937 | + 0 | ||
| 938 | + }; | ||
| 939 | + let mut scratch_buf = [0f32; MAX_BAND]; | ||
| 940 | + let scratch = &mut scratch_buf[..scratch_len]; | ||
| 941 | + let mut lowband_offset = 0usize; | ||
| 942 | + let mut update_lowband = true; | ||
| 943 | + let mut ctx = BandCtx { | ||
| 944 | + resynth, | ||
| 945 | + i: start, | ||
| 946 | + intensity, | ||
| 947 | + spread, | ||
| 948 | + tf_change: 0, | ||
| 949 | + remaining_bits: 0, | ||
| 950 | + band_e, | ||
| 951 | + seed: *seed, | ||
| 952 | + theta_round: 0, | ||
| 953 | + disable_inv, | ||
| 954 | + avoid_split_noise: b_full > 1, | ||
| 955 | + }; | ||
| 956 | + | ||
| 957 | + for i in start..end { | ||
| 958 | + ctx.i = i; | ||
| 959 | + let last = i + 1 == end; | ||
| 960 | + let lo = eb(i); | ||
| 961 | + let n = eb(i + 1) - lo; | ||
| 962 | + let nu = n as usize; | ||
| 963 | + let lo_u = lo as usize; | ||
| 964 | + let out_off = (lo - norm_offset) as usize; | ||
| 965 | + let tell = enc.tell_frac() as i32; | ||
| 966 | + if i != start { | ||
| 967 | + balance -= tell; | ||
| 968 | + } | ||
| 969 | + let remaining_bits = total_bits - tell - 1; | ||
| 970 | + ctx.remaining_bits = remaining_bits; | ||
| 971 | + let b = if i < coded_bands { | ||
| 972 | + let curr_balance = balance / ((coded_bands - i) as i32).min(3); | ||
| 973 | + (remaining_bits + 1) | ||
| 974 | + .min(pulses[i] + curr_balance) | ||
| 975 | + .clamp(0, 16383) | ||
| 976 | + } else { | ||
| 977 | + 0 | ||
| 978 | + }; | ||
| 979 | + if resynth | ||
| 980 | + && (lo - n >= norm_offset || i == start + 1) | ||
| 981 | + && (update_lowband || lowband_offset == 0) | ||
| 982 | + { | ||
| 983 | + lowband_offset = i; | ||
| 984 | + } | ||
| 985 | + if i == start + 1 { | ||
| 986 | + special_hybrid_folding(norm, norm2, start, m, dual_stereo); | ||
| 987 | + } | ||
| 988 | + let tf_change = tf_res[i]; | ||
| 989 | + ctx.tf_change = tf_change; | ||
| 990 | + | ||
| 991 | + let mut effective_lowband: Option<usize> = None; | ||
| 992 | + let (mut x_cm, mut y_cm): (u32, u32) = if lowband_offset != 0 | ||
| 993 | + && (spread != SPREAD_AGGRESSIVE as i32 || b_full > 1 || tf_change < 0) | ||
| 994 | + { | ||
| 995 | + let eff = (eb(lowband_offset) - norm_offset - n).max(0); | ||
| 996 | + effective_lowband = Some(eff as usize); | ||
| 997 | + let mut fold_start = lowband_offset; | ||
| 998 | + loop { | ||
| 999 | + fold_start -= 1; | ||
| 1000 | + if eb(fold_start) <= eff + norm_offset { | ||
| 1001 | + break; | ||
| 1002 | + } | ||
| 1003 | + } | ||
| 1004 | + let mut fold_end = lowband_offset - 1; | ||
| 1005 | + loop { | ||
| 1006 | + fold_end += 1; | ||
| 1007 | + if !(fold_end < i && eb(fold_end) < eff + norm_offset + n) { | ||
| 1008 | + break; | ||
| 1009 | + } | ||
| 1010 | + } | ||
| 1011 | + let mut xc = 0u32; | ||
| 1012 | + let mut yc = 0u32; | ||
| 1013 | + let mut fi = fold_start; | ||
| 1014 | + loop { | ||
| 1015 | + xc |= collapse_masks[fi * c] as u32; | ||
| 1016 | + yc |= collapse_masks[fi * c + c - 1] as u32; | ||
| 1017 | + fi += 1; | ||
| 1018 | + if fi >= fold_end { | ||
| 1019 | + break; | ||
| 1020 | + } | ||
| 1021 | + } | ||
| 1022 | + (xc, yc) | ||
| 1023 | + } else { | ||
| 1024 | + let all = (1u32 << b_full) - 1; | ||
| 1025 | + (all, all) | ||
| 1026 | + }; | ||
| 1027 | + | ||
| 1028 | + if dual_stereo && i == intensity { | ||
| 1029 | + dual_stereo = false; | ||
| 1030 | + if resynth { | ||
| 1031 | + for j in 0..(eb(i) - norm_offset) as usize { | ||
| 1032 | + norm[j] = 0.5f32 * (norm[j] + norm2[j]); | ||
| 1033 | + } | ||
| 1034 | + } | ||
| 1035 | + } | ||
| 1036 | + | ||
| 1037 | + let xb = &mut x[lo_u..lo_u + nu]; | ||
| 1038 | + let yb = y.as_deref_mut().map(|yy| &mut yy[lo_u..lo_u + nu]); | ||
| 1039 | + match yb { | ||
| 1040 | + None => { | ||
| 1041 | + let mut lb_buf = [0f32; MAX_BAND]; | ||
| 1042 | + let mut lbo_buf = [0f32; MAX_BAND]; | ||
| 1043 | + let lb = lowband_copy(&mut lb_buf, norm, effective_lowband, nu); | ||
| 1044 | + let mut lbo = if last { None } else { Some(&mut lbo_buf[..nu]) }; | ||
| 1045 | + x_cm = quant_band( | ||
| 1046 | + &mut ctx, | ||
| 1047 | + enc, | ||
| 1048 | + xb, | ||
| 1049 | + nu, | ||
| 1050 | + b, | ||
| 1051 | + b_full, | ||
| 1052 | + lb, | ||
| 1053 | + lm, | ||
| 1054 | + lbo.as_deref_mut(), | ||
| 1055 | + 1.0, | ||
| 1056 | + opt_scratch(resynth, scratch), | ||
| 1057 | + (x_cm | y_cm) as i32, | ||
| 1058 | + ); | ||
| 1059 | + store(norm, out_off, lbo.as_deref()); | ||
| 1060 | + y_cm = x_cm; | ||
| 1061 | + } | ||
| 1062 | + Some(yb) => { | ||
| 1063 | + if dual_stereo { | ||
| 1064 | + let mut lb_buf = [0f32; MAX_BAND]; | ||
| 1065 | + let mut lbo_buf = [0f32; MAX_BAND]; | ||
| 1066 | + let mut lb2_buf = [0f32; MAX_BAND]; | ||
| 1067 | + let mut lbo2_buf = [0f32; MAX_BAND]; | ||
| 1068 | + let lb = lowband_copy(&mut lb_buf, norm, effective_lowband, nu); | ||
| 1069 | + let mut lbo = if last { None } else { Some(&mut lbo_buf[..nu]) }; | ||
| 1070 | + x_cm = quant_band( | ||
| 1071 | + &mut ctx, | ||
| 1072 | + enc, | ||
| 1073 | + xb, | ||
| 1074 | + nu, | ||
| 1075 | + b / 2, | ||
| 1076 | + b_full, | ||
| 1077 | + lb, | ||
| 1078 | + lm, | ||
| 1079 | + lbo.as_deref_mut(), | ||
| 1080 | + 1.0, | ||
| 1081 | + None, | ||
| 1082 | + x_cm as i32, | ||
| 1083 | + ); | ||
| 1084 | + store(norm, out_off, lbo.as_deref()); | ||
| 1085 | + let lb2 = lowband_copy(&mut lb2_buf, norm2, effective_lowband, nu); | ||
| 1086 | + let mut lbo2 = if last { | ||
| 1087 | + None | ||
| 1088 | + } else { | ||
| 1089 | + Some(&mut lbo2_buf[..nu]) | ||
| 1090 | + }; | ||
| 1091 | + y_cm = quant_band( | ||
| 1092 | + &mut ctx, | ||
| 1093 | + enc, | ||
| 1094 | + yb, | ||
| 1095 | + nu, | ||
| 1096 | + b / 2, | ||
| 1097 | + b_full, | ||
| 1098 | + lb2, | ||
| 1099 | + lm, | ||
| 1100 | + lbo2.as_deref_mut(), | ||
| 1101 | + 1.0, | ||
| 1102 | + None, | ||
| 1103 | + y_cm as i32, | ||
| 1104 | + ); | ||
| 1105 | + store(norm2, out_off, lbo2.as_deref()); | ||
| 1106 | + } else if theta_rdo && i < intensity { | ||
| 1107 | + let w = compute_channel_weights(band_e[i], band_e[i + NB_BANDS]); | ||
| 1108 | + let cm_in = x_cm | y_cm; | ||
| 1109 | + let ec_save = enc.snapshot(); | ||
| 1110 | + let offs = enc.front_offs(); | ||
| 1111 | + let ctx_save = ctx; | ||
| 1112 | + let mut x_save_buf = [0f32; MAX_BAND]; | ||
| 1113 | + let mut y_save_buf = [0f32; MAX_BAND]; | ||
| 1114 | + x_save_buf[..nu].copy_from_slice(xb); | ||
| 1115 | + y_save_buf[..nu].copy_from_slice(yb); | ||
| 1116 | + let x_save = &x_save_buf[..nu]; | ||
| 1117 | + let y_save = &y_save_buf[..nu]; | ||
| 1118 | + | ||
| 1119 | + ctx.theta_round = -1; | ||
| 1120 | + let mut lb_buf = [0f32; MAX_BAND]; | ||
| 1121 | + let mut lbo_buf = [0f32; MAX_BAND]; | ||
| 1122 | + let lb = lowband_copy(&mut lb_buf, norm, effective_lowband, nu); | ||
| 1123 | + let mut lbo = if last { None } else { Some(&mut lbo_buf[..nu]) }; | ||
| 1124 | + x_cm = quant_band_stereo( | ||
| 1125 | + &mut ctx, | ||
| 1126 | + enc, | ||
| 1127 | + xb, | ||
| 1128 | + yb, | ||
| 1129 | + nu, | ||
| 1130 | + b, | ||
| 1131 | + b_full, | ||
| 1132 | + lb, | ||
| 1133 | + lm, | ||
| 1134 | + lbo.as_deref_mut(), | ||
| 1135 | + opt_scratch(resynth, scratch), | ||
| 1136 | + cm_in as i32, | ||
| 1137 | + ); | ||
| 1138 | + store(norm, out_off, lbo.as_deref()); | ||
| 1139 | + let dist0 = w[0] * inner(x_save, xb) + w[1] * inner(y_save, yb); | ||
| 1140 | + | ||
| 1141 | + let cm2 = x_cm; | ||
| 1142 | + let ec_save2 = enc.snapshot(); | ||
| 1143 | + let ctx_save2 = ctx; | ||
| 1144 | + let mut x_save2_buf = [0f32; MAX_BAND]; | ||
| 1145 | + let mut y_save2_buf = [0f32; MAX_BAND]; | ||
| 1146 | + x_save2_buf[..nu].copy_from_slice(xb); | ||
| 1147 | + y_save2_buf[..nu].copy_from_slice(yb); | ||
| 1148 | + let x_save2 = &x_save2_buf[..nu]; | ||
| 1149 | + let y_save2 = &y_save2_buf[..nu]; | ||
| 1150 | + let mut norm_save2_buf = [0f32; MAX_BAND]; | ||
| 1151 | + if !last { | ||
| 1152 | + norm_save2_buf[..nu].copy_from_slice(&norm[out_off..out_off + nu]); | ||
| 1153 | + } | ||
| 1154 | + let bytes_len = enc.data().len() - offs; | ||
| 1155 | + let mut bytes_save_buf = [0u8; MAX_BYTES]; | ||
| 1156 | + bytes_save_buf[..bytes_len].copy_from_slice(&enc.data()[offs..]); | ||
| 1157 | + let bytes_save = &bytes_save_buf[..bytes_len]; | ||
| 1158 | + | ||
| 1159 | + enc.restore(&ec_save); | ||
| 1160 | + ctx = ctx_save; | ||
| 1161 | + xb.copy_from_slice(x_save); | ||
| 1162 | + yb.copy_from_slice(y_save); | ||
| 1163 | + if i == start + 1 { | ||
| 1164 | + special_hybrid_folding(norm, norm2, start, m, dual_stereo); | ||
| 1165 | + } | ||
| 1166 | + | ||
| 1167 | + ctx.theta_round = 1; | ||
| 1168 | + let mut lb_buf = [0f32; MAX_BAND]; | ||
| 1169 | + let mut lbo_buf = [0f32; MAX_BAND]; | ||
| 1170 | + let lb = lowband_copy(&mut lb_buf, norm, effective_lowband, nu); | ||
| 1171 | + let mut lbo = if last { None } else { Some(&mut lbo_buf[..nu]) }; | ||
| 1172 | + x_cm = quant_band_stereo( | ||
| 1173 | + &mut ctx, | ||
| 1174 | + enc, | ||
| 1175 | + xb, | ||
| 1176 | + yb, | ||
| 1177 | + nu, | ||
| 1178 | + b, | ||
| 1179 | + b_full, | ||
| 1180 | + lb, | ||
| 1181 | + lm, | ||
| 1182 | + lbo.as_deref_mut(), | ||
| 1183 | + opt_scratch(resynth, scratch), | ||
| 1184 | + cm_in as i32, | ||
| 1185 | + ); | ||
| 1186 | + store(norm, out_off, lbo.as_deref()); | ||
| 1187 | + let dist1 = w[0] * inner(x_save, xb) + w[1] * inner(y_save, yb); | ||
| 1188 | + | ||
| 1189 | + if dist0 >= dist1 { | ||
| 1190 | + x_cm = cm2; | ||
| 1191 | + enc.restore(&ec_save2); | ||
| 1192 | + ctx = ctx_save2; | ||
| 1193 | + xb.copy_from_slice(x_save2); | ||
| 1194 | + yb.copy_from_slice(y_save2); | ||
| 1195 | + if !last { | ||
| 1196 | + norm[out_off..out_off + nu].copy_from_slice(&norm_save2_buf[..nu]); | ||
| 1197 | + } | ||
| 1198 | + enc.front_write(offs, bytes_save); | ||
| 1199 | + } | ||
| 1200 | + y_cm = x_cm; | ||
| 1201 | + } else { | ||
| 1202 | + ctx.theta_round = 0; | ||
| 1203 | + let mut lb_buf = [0f32; MAX_BAND]; | ||
| 1204 | + let mut lbo_buf = [0f32; MAX_BAND]; | ||
| 1205 | + let lb = lowband_copy(&mut lb_buf, norm, effective_lowband, nu); | ||
| 1206 | + let mut lbo = if last { None } else { Some(&mut lbo_buf[..nu]) }; | ||
| 1207 | + x_cm = quant_band_stereo( | ||
| 1208 | + &mut ctx, | ||
| 1209 | + enc, | ||
| 1210 | + xb, | ||
| 1211 | + yb, | ||
| 1212 | + nu, | ||
| 1213 | + b, | ||
| 1214 | + b_full, | ||
| 1215 | + lb, | ||
| 1216 | + lm, | ||
| 1217 | + lbo.as_deref_mut(), | ||
| 1218 | + opt_scratch(resynth, scratch), | ||
| 1219 | + (x_cm | y_cm) as i32, | ||
| 1220 | + ); | ||
| 1221 | + store(norm, out_off, lbo.as_deref()); | ||
| 1222 | + y_cm = x_cm; | ||
| 1223 | + } | ||
| 1224 | + } | ||
| 1225 | + } | ||
| 1226 | + | ||
| 1227 | + collapse_masks[i * c] = x_cm as u8; | ||
| 1228 | + collapse_masks[i * c + c - 1] = y_cm as u8; | ||
| 1229 | + balance += pulses[i] + tell; | ||
| 1230 | + update_lowband = b > (n << BR); | ||
| 1231 | + ctx.avoid_split_noise = false; | ||
| 1232 | + } | ||
| 1233 | + *seed = ctx.seed; | ||
| 1234 | +} | ||
crates/ec-opus/src/celt_flp/enc.rsadded+1389 -0
| @@ -0,0 +1,1389 @@ | |||
| 1 | +use crate::analysis::{AnalysisInfo, LEAK_BANDS}; | ||
| 2 | +use crate::celt::{ | ||
| 3 | + CACHE_CAPS, SPREAD_AGGRESSIVE, SPREAD_ICDF, SPREAD_NONE, SPREAD_NORMAL, TRIM_ICDF, | ||
| 4 | + compute_allocation_encode, ilog, | ||
| 5 | +}; | ||
| 6 | +use crate::range::RangeEncoder; | ||
| 7 | + | ||
| 8 | +use super::bands::{ | ||
| 9 | + compute_band_energies, hysteresis_decision, normalise_bands, quant_all_bands, | ||
| 10 | + spreading_decision, | ||
| 11 | +}; | ||
| 12 | +use super::enc_an::{ | ||
| 13 | + alloc_trim_analysis, compute_vbr, dynalloc_analysis, patch_transient_decision, stereo_analysis, | ||
| 14 | + tf_analysis, tf_encode, tone_detect, transient_analysis, | ||
| 15 | +}; | ||
| 16 | +use super::fft::clt_mdct_forward; | ||
| 17 | +use super::pitch::{comb_filter, pitch_downsample, pitch_search, remove_doubling}; | ||
| 18 | +use super::quant_bands::{amp2log2, quant_coarse_energy, quant_energy_finalise, quant_fine_energy}; | ||
| 19 | +use super::tables::WINDOW120; | ||
| 20 | +use super::{BITRES, E_BANDS}; | ||
| 21 | +use super::{ | ||
| 22 | + COMBFILTER_MAXPERIOD, COMBFILTER_MINPERIOD, EPSILON, MAX_LM, NB_BANDS, OVERLAP, PI, SHORT_MDCT, | ||
| 23 | + celt_rcp, | ||
| 24 | +}; | ||
| 25 | + | ||
| 26 | +const BR: i32 = BITRES as i32; | ||
| 27 | +const NB: usize = NB_BANDS; | ||
| 28 | +const PACKET_SIZE_CAP: i32 = 1275; | ||
| 29 | +const TAPSET_ICDF: [u8; 3] = [2, 1, 0]; | ||
| 30 | +const INTENSITY_THRESHOLDS: [f32; NB_BANDS] = [ | ||
| 31 | + 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 16.0, 24.0, 36.0, 44.0, 50.0, 56.0, 62.0, 67.0, 72.0, | ||
| 32 | + 79.0, 88.0, 106.0, 134.0, | ||
| 33 | +]; | ||
| 34 | +const INTENSITY_HYSTERESIS: [f32; NB_BANDS] = [ | ||
| 35 | + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 3.0, 3.0, 4.0, 5.0, 6.0, | ||
| 36 | + 8.0, 8.0, | ||
| 37 | +]; | ||
| 38 | +const CH_MAX: usize = 2; | ||
| 39 | +const N_MAX: usize = 960; | ||
| 40 | +const PRE_LEN: usize = CH_MAX * (N_MAX + COMBFILTER_MAXPERIOD); | ||
| 41 | +const PITCH_BUF_LEN: usize = (N_MAX + COMBFILTER_MAXPERIOD) >> 1; | ||
| 42 | +const INPUT_LEN: usize = CH_MAX * (N_MAX + OVERLAP); | ||
| 43 | +const FREQ_LEN: usize = CH_MAX * N_MAX; | ||
| 44 | +const BAND_LEN: usize = CH_MAX * NB; | ||
| 45 | + | ||
| 46 | +/// libopus `OPUS_BITRATE_MAX`. | ||
| 47 | +pub(crate) const BITRATE_MAX: i32 = -1; | ||
| 48 | + | ||
| 49 | +/// libopus `OpusCustomEncoder` for the static 48 kHz / 960 mode (float, no QEXT). | ||
| 50 | +#[derive(Clone, Debug)] | ||
| 51 | +pub(crate) struct CeltEnc { | ||
| 52 | + channels: usize, | ||
| 53 | + stream_channels: usize, | ||
| 54 | + upsample: usize, | ||
| 55 | + start: usize, | ||
| 56 | + end: usize, | ||
| 57 | + bitrate: i32, | ||
| 58 | + vbr: bool, | ||
| 59 | + constrained_vbr: bool, | ||
| 60 | + loss_rate: i32, | ||
| 61 | + lsb_depth: i32, | ||
| 62 | + lfe: bool, | ||
| 63 | + disable_inv: bool, | ||
| 64 | + disable_pf: bool, | ||
| 65 | + force_intra: bool, | ||
| 66 | + complexity: i32, | ||
| 67 | + clip: bool, | ||
| 68 | + rng: u32, | ||
| 69 | + spread_decision: i32, | ||
| 70 | + delayed_intra: f32, | ||
| 71 | + tonal_average: i32, | ||
| 72 | + last_coded_bands: usize, | ||
| 73 | + hf_average: i32, | ||
| 74 | + tapset_decision: i32, | ||
| 75 | + prefilter_period: i32, | ||
| 76 | + prefilter_gain: f32, | ||
| 77 | + prefilter_tapset: i32, | ||
| 78 | + consec_transient: i32, | ||
| 79 | + analysis: AnalysisInfo, | ||
| 80 | + silk_signal_type: i32, | ||
| 81 | + silk_offset: i32, | ||
| 82 | + preemph_mem_e: [f32; 2], | ||
| 83 | + vbr_reservoir: i32, | ||
| 84 | + vbr_drift: i32, | ||
| 85 | + vbr_offset: i32, | ||
| 86 | + vbr_count: i32, | ||
| 87 | + overlap_max: f32, | ||
| 88 | + stereo_saving: f32, | ||
| 89 | + intensity: usize, | ||
| 90 | + spec_avg: f32, | ||
| 91 | + in_mem: Vec<f32>, | ||
| 92 | + prefilter_mem: Vec<f32>, | ||
| 93 | + old_band_e: Vec<f32>, | ||
| 94 | + old_log_e: Vec<f32>, | ||
| 95 | + old_log_e2: Vec<f32>, | ||
| 96 | + energy_error: Vec<f32>, | ||
| 97 | +} | ||
| 98 | + | ||
| 99 | +fn zero_analysis() -> AnalysisInfo { | ||
| 100 | + AnalysisInfo { | ||
| 101 | + valid: false, | ||
| 102 | + tonality: 0.0, | ||
| 103 | + tonality_slope: 0.0, | ||
| 104 | + noisiness: 0.0, | ||
| 105 | + activity: 0.0, | ||
| 106 | + music_prob: 0.0, | ||
| 107 | + music_prob_min: 0.0, | ||
| 108 | + music_prob_max: 0.0, | ||
| 109 | + activity_probability: 0.0, | ||
| 110 | + max_pitch_ratio: 0.0, | ||
| 111 | + bandwidth: 0, | ||
| 112 | + leak_boost: [0; LEAK_BANDS], | ||
| 113 | + } | ||
| 114 | +} | ||
| 115 | + | ||
| 116 | +fn max32(a: f32, b: f32) -> f32 { | ||
| 117 | + if a > b { a } else { b } | ||
| 118 | +} | ||
| 119 | + | ||
| 120 | +fn min32(a: f32, b: f32) -> f32 { | ||
| 121 | + if a < b { a } else { b } | ||
| 122 | +} | ||
| 123 | + | ||
| 124 | +fn maxabs(x: &[f32]) -> f32 { | ||
| 125 | + let mut maxval = 0.0f32; | ||
| 126 | + let mut minval = 0.0f32; | ||
| 127 | + for &v in x { | ||
| 128 | + maxval = max32(maxval, v); | ||
| 129 | + minval = min32(minval, v); | ||
| 130 | + } | ||
| 131 | + max32(maxval, -minval) | ||
| 132 | +} | ||
| 133 | + | ||
| 134 | +fn bitrate_to_bits(bitrate: i32, fs: i32, frame_size: i32) -> i32 { | ||
| 135 | + bitrate * 6 / (6 * fs / frame_size) | ||
| 136 | +} | ||
| 137 | + | ||
| 138 | +fn init_caps(lm: usize, c: usize) -> [i32; NB_BANDS] { | ||
| 139 | + let mut cap = [0i32; NB_BANDS]; | ||
| 140 | + for i in 0..NB_BANDS { | ||
| 141 | + let n = ((E_BANDS[i + 1] - E_BANDS[i]) << lm) as i32; | ||
| 142 | + cap[i] = ((CACHE_CAPS[NB_BANDS * (2 * lm + c - 1) + i] as i32 + 64) * c as i32 * n) >> 2; | ||
| 143 | + } | ||
| 144 | + cap | ||
| 145 | +} | ||
| 146 | + | ||
| 147 | +/// `compute_mdcts`: `short_blocks == 0` means long blocks. | ||
| 148 | +fn compute_mdcts( | ||
| 149 | + short_blocks: usize, | ||
| 150 | + input: &[f32], | ||
| 151 | + out: &mut [f32], | ||
| 152 | + c: usize, | ||
| 153 | + cc: usize, | ||
| 154 | + lm: usize, | ||
| 155 | + upsample: usize, | ||
| 156 | +) { | ||
| 157 | + let (b, nn, shift) = if short_blocks != 0 { | ||
| 158 | + (short_blocks, SHORT_MDCT, MAX_LM) | ||
| 159 | + } else { | ||
| 160 | + (1, SHORT_MDCT << lm, MAX_LM - lm) | ||
| 161 | + }; | ||
| 162 | + for ch in 0..cc { | ||
| 163 | + for blk in 0..b { | ||
| 164 | + let in_off = ch * (b * nn + OVERLAP) + blk * nn; | ||
| 165 | + let out_off = blk + ch * nn * b; | ||
| 166 | + clt_mdct_forward(&input[in_off..], &mut out[out_off..], OVERLAP, shift, b); | ||
| 167 | + } | ||
| 168 | + } | ||
| 169 | + if cc == 2 && c == 1 { | ||
| 170 | + for i in 0..b * nn { | ||
| 171 | + out[i] = 0.5f32 * out[i] + 0.5f32 * out[b * nn + i]; | ||
| 172 | + } | ||
| 173 | + } | ||
| 174 | + if upsample != 1 { | ||
| 175 | + for ch in 0..c { | ||
| 176 | + let bound = b * nn / upsample; | ||
| 177 | + for i in 0..bound { | ||
| 178 | + out[ch * b * nn + i] *= upsample as f32; | ||
| 179 | + } | ||
| 180 | + out[ch * b * nn + bound..ch * b * nn + b * nn].fill(0.0); | ||
| 181 | + } | ||
| 182 | + } | ||
| 183 | +} | ||
| 184 | + | ||
| 185 | +/// `celt_preemphasis` for the static mode, where `coef[1] == 0` so only the | ||
| 186 | +/// single-pole branch is live. | ||
| 187 | +fn celt_preemphasis( | ||
| 188 | + pcm: &[f32], | ||
| 189 | + inp: &mut [f32], | ||
| 190 | + n: usize, | ||
| 191 | + cc: usize, | ||
| 192 | + upsample: usize, | ||
| 193 | + coef0: f32, | ||
| 194 | + mem: &mut f32, | ||
| 195 | + clip: bool, | ||
| 196 | +) { | ||
| 197 | + let nu = n / upsample; | ||
| 198 | + if upsample != 1 { | ||
| 199 | + inp[..n].fill(0.0); | ||
| 200 | + } | ||
| 201 | + for i in 0..nu { | ||
| 202 | + inp[i * upsample] = 32768.0f32 * pcm[cc * i]; | ||
| 203 | + } | ||
| 204 | + if clip { | ||
| 205 | + for i in 0..nu { | ||
| 206 | + inp[i * upsample] = max32(-65536.0, min32(65536.0, inp[i * upsample])); | ||
| 207 | + } | ||
| 208 | + } | ||
| 209 | + let mut m = *mem; | ||
| 210 | + for i in 0..n { | ||
| 211 | + let x = inp[i]; | ||
| 212 | + inp[i] = x - m; | ||
| 213 | + m = coef0 * x; | ||
| 214 | + } | ||
| 215 | + *mem = m; | ||
| 216 | +} | ||
| 217 | + | ||
| 218 | +impl CeltEnc { | ||
| 219 | + /// `celt_encoder_init(st, 48000 / upsample, channels)`. | ||
| 220 | + pub(crate) fn new(channels: usize, upsample: usize) -> CeltEnc { | ||
| 221 | + let mut st = CeltEnc { | ||
| 222 | + channels, | ||
| 223 | + stream_channels: channels, | ||
| 224 | + upsample, | ||
| 225 | + start: 0, | ||
| 226 | + end: NB_BANDS, | ||
| 227 | + bitrate: BITRATE_MAX, | ||
| 228 | + vbr: false, | ||
| 229 | + constrained_vbr: true, | ||
| 230 | + loss_rate: 0, | ||
| 231 | + lsb_depth: 24, | ||
| 232 | + lfe: false, | ||
| 233 | + disable_inv: false, | ||
| 234 | + disable_pf: false, | ||
| 235 | + force_intra: false, | ||
| 236 | + complexity: 5, | ||
| 237 | + clip: true, | ||
| 238 | + rng: 0, | ||
| 239 | + spread_decision: 0, | ||
| 240 | + delayed_intra: 0.0, | ||
| 241 | + tonal_average: 0, | ||
| 242 | + last_coded_bands: 0, | ||
| 243 | + hf_average: 0, | ||
| 244 | + tapset_decision: 0, | ||
| 245 | + prefilter_period: 0, | ||
| 246 | + prefilter_gain: 0.0, | ||
| 247 | + prefilter_tapset: 0, | ||
| 248 | + consec_transient: 0, | ||
| 249 | + analysis: zero_analysis(), | ||
| 250 | + silk_signal_type: 0, | ||
| 251 | + silk_offset: 0, | ||
| 252 | + preemph_mem_e: [0.0; 2], | ||
| 253 | + vbr_reservoir: 0, | ||
| 254 | + vbr_drift: 0, | ||
| 255 | + vbr_offset: 0, | ||
| 256 | + vbr_count: 0, | ||
| 257 | + overlap_max: 0.0, | ||
| 258 | + stereo_saving: 0.0, | ||
| 259 | + intensity: 0, | ||
| 260 | + spec_avg: 0.0, | ||
| 261 | + in_mem: vec![0.0; channels * OVERLAP], | ||
| 262 | + prefilter_mem: vec![0.0; channels * COMBFILTER_MAXPERIOD], | ||
| 263 | + old_band_e: vec![0.0; channels * NB_BANDS], | ||
| 264 | + old_log_e: vec![0.0; channels * NB_BANDS], | ||
| 265 | + old_log_e2: vec![0.0; channels * NB_BANDS], | ||
| 266 | + energy_error: vec![0.0; channels * NB_BANDS], | ||
| 267 | + }; | ||
| 268 | + st.reset(); | ||
| 269 | + st | ||
| 270 | + } | ||
| 271 | + | ||
| 272 | + /// `OPUS_RESET_STATE`. | ||
| 273 | + pub(crate) fn reset(&mut self) { | ||
| 274 | + self.rng = 0; | ||
| 275 | + self.spread_decision = SPREAD_NORMAL as i32; | ||
| 276 | + self.delayed_intra = 1.0; | ||
| 277 | + self.tonal_average = 256; | ||
| 278 | + self.last_coded_bands = 0; | ||
| 279 | + self.hf_average = 0; | ||
| 280 | + self.tapset_decision = 0; | ||
| 281 | + self.prefilter_period = 0; | ||
| 282 | + self.prefilter_gain = 0.0; | ||
| 283 | + self.prefilter_tapset = 0; | ||
| 284 | + self.consec_transient = 0; | ||
| 285 | + self.analysis = zero_analysis(); | ||
| 286 | + self.silk_signal_type = 0; | ||
| 287 | + self.silk_offset = 0; | ||
| 288 | + self.preemph_mem_e = [0.0; 2]; | ||
| 289 | + self.vbr_reservoir = 0; | ||
| 290 | + self.vbr_drift = 0; | ||
| 291 | + self.vbr_offset = 0; | ||
| 292 | + self.vbr_count = 0; | ||
| 293 | + self.overlap_max = 0.0; | ||
| 294 | + self.stereo_saving = 0.0; | ||
| 295 | + self.intensity = 0; | ||
| 296 | + self.spec_avg = 0.0; | ||
| 297 | + self.in_mem.fill(0.0); | ||
| 298 | + self.prefilter_mem.fill(0.0); | ||
| 299 | + self.old_band_e.fill(0.0); | ||
| 300 | + self.energy_error.fill(0.0); | ||
| 301 | + self.old_log_e.fill(-28.0); | ||
| 302 | + self.old_log_e2.fill(-28.0); | ||
| 303 | + } | ||
| 304 | + | ||
| 305 | + /// `run_prefilter`: returns `(pf_on, pitch, gain, qgain)`. `prefilter_mem` is | ||
| 306 | + /// the caller-taken `st->prefilter_mem`. | ||
| 307 | + #[allow(clippy::too_many_arguments)] | ||
| 308 | + fn run_prefilter( | ||
| 309 | + &mut self, | ||
| 310 | + input: &mut [f32], | ||
| 311 | + prefilter_mem: &mut [f32], | ||
| 312 | + cc: usize, | ||
| 313 | + n: usize, | ||
| 314 | + prefilter_tapset: i32, | ||
| 315 | + enabled: bool, | ||
| 316 | + tf_estimate: f32, | ||
| 317 | + nb_available_bytes: i32, | ||
| 318 | + analysis: &AnalysisInfo, | ||
| 319 | + tone_freq: f32, | ||
| 320 | + toneishness: f32, | ||
| 321 | + ) -> (bool, i32, f32, i32) { | ||
| 322 | + let max_period = COMBFILTER_MAXPERIOD; | ||
| 323 | + let min_period = COMBFILTER_MINPERIOD; | ||
| 324 | + let overlap = OVERLAP; | ||
| 325 | + let window: &[f32] = &WINDOW120; | ||
| 326 | + let pre_stride = n + max_period; | ||
| 327 | + let mut pre_buf = [0.0f32; PRE_LEN]; | ||
| 328 | + let pre = &mut pre_buf[..cc * pre_stride]; | ||
| 329 | + for ch in 0..cc { | ||
| 330 | + pre[ch * pre_stride..ch * pre_stride + max_period] | ||
| 331 | + .copy_from_slice(&prefilter_mem[ch * max_period..(ch + 1) * max_period]); | ||
| 332 | + let base = ch * pre_stride + max_period; | ||
| 333 | + pre[base..base + n].copy_from_slice( | ||
| 334 | + &input[ch * (n + overlap) + overlap..ch * (n + overlap) + overlap + n], | ||
| 335 | + ); | ||
| 336 | + } | ||
| 337 | + | ||
| 338 | + let mut pitch_index: i32; | ||
| 339 | + let mut gain1: f32; | ||
| 340 | + let mut tone_freq = tone_freq; | ||
| 341 | + if enabled && toneishness > 0.99f32 { | ||
| 342 | + let mut multiple: i32 = 1; | ||
| 343 | + if tone_freq >= 3.1416f32 { | ||
| 344 | + tone_freq = 3.141593f32 - tone_freq; | ||
| 345 | + } | ||
| 346 | + while tone_freq >= multiple as f32 * 0.39f32 { | ||
| 347 | + multiple += 1; | ||
| 348 | + } | ||
| 349 | + if tone_freq > 0.006148f32 { | ||
| 350 | + let v = (0.5f64 + 2.0f64 * PI * multiple as f64 / tone_freq as f64).floor() as i32; | ||
| 351 | + pitch_index = v.min(COMBFILTER_MAXPERIOD as i32 - 2); | ||
| 352 | + } else { | ||
| 353 | + pitch_index = COMBFILTER_MINPERIOD as i32; | ||
| 354 | + } | ||
| 355 | + gain1 = 0.75; | ||
| 356 | + } else if enabled && self.complexity >= 5 { | ||
| 357 | + let mut pitch_buf_arr = [0.0f32; PITCH_BUF_LEN]; | ||
| 358 | + let pitch_buf = &mut pitch_buf_arr[..(max_period + n) >> 1]; | ||
| 359 | + { | ||
| 360 | + let chans: [&[f32]; CH_MAX] = [&pre[..pre_stride], &pre[pre_stride..]]; | ||
| 361 | + pitch_downsample(&chans[..cc], pitch_buf, (max_period + n) >> 1, 2); | ||
| 362 | + } | ||
| 363 | + pitch_index = pitch_search( | ||
| 364 | + &pitch_buf[max_period >> 1..], | ||
| 365 | + pitch_buf, | ||
| 366 | + n, | ||
| 367 | + max_period - 3 * min_period, | ||
| 368 | + ); | ||
| 369 | + pitch_index = max_period as i32 - pitch_index; | ||
| 370 | + gain1 = remove_doubling( | ||
| 371 | + pitch_buf, | ||
| 372 | + max_period as i32, | ||
| 373 | + min_period as i32, | ||
| 374 | + n as i32, | ||
| 375 | + &mut pitch_index, | ||
| 376 | + self.prefilter_period, | ||
| 377 | + self.prefilter_gain, | ||
| 378 | + ); | ||
| 379 | + if pitch_index > max_period as i32 - 2 { | ||
| 380 | + pitch_index = max_period as i32 - 2; | ||
| 381 | + } | ||
| 382 | + gain1 *= 0.7f32; | ||
| 383 | + if self.loss_rate > 2 { | ||
| 384 | + gain1 *= 0.5; | ||
| 385 | + } | ||
| 386 | + if self.loss_rate > 4 { | ||
| 387 | + gain1 *= 0.5; | ||
| 388 | + } | ||
| 389 | + if self.loss_rate > 8 { | ||
| 390 | + gain1 = 0.0; | ||
| 391 | + } | ||
| 392 | + } else { | ||
| 393 | + gain1 = 0.0; | ||
| 394 | + pitch_index = COMBFILTER_MINPERIOD as i32; | ||
| 395 | + } | ||
| 396 | + if analysis.valid { | ||
| 397 | + gain1 *= analysis.max_pitch_ratio; | ||
| 398 | + } | ||
| 399 | + | ||
| 400 | + let mut pf_threshold: f32 = 0.2; | ||
| 401 | + if (pitch_index - self.prefilter_period).abs() * 10 > pitch_index { | ||
| 402 | + pf_threshold += 0.2; | ||
| 403 | + if tf_estimate > 0.98f32 { | ||
| 404 | + gain1 = 0.0; | ||
| 405 | + } | ||
| 406 | + } | ||
| 407 | + if nb_available_bytes < 25 { | ||
| 408 | + pf_threshold += 0.1; | ||
| 409 | + } | ||
| 410 | + if nb_available_bytes < 35 { | ||
| 411 | + pf_threshold += 0.1; | ||
| 412 | + } | ||
| 413 | + if self.prefilter_gain > 0.4f32 { | ||
| 414 | + pf_threshold -= 0.1; | ||
| 415 | + } | ||
| 416 | + if self.prefilter_gain > 0.55f32 { | ||
| 417 | + pf_threshold -= 0.1; | ||
| 418 | + } | ||
| 419 | + pf_threshold = max32(pf_threshold, 0.2); | ||
| 420 | + | ||
| 421 | + let mut pf_on: bool; | ||
| 422 | + let mut qg: i32; | ||
| 423 | + if gain1 < pf_threshold { | ||
| 424 | + gain1 = 0.0; | ||
| 425 | + pf_on = false; | ||
| 426 | + qg = 0; | ||
| 427 | + } else { | ||
| 428 | + if (gain1 - self.prefilter_gain).abs() < 0.1f32 { | ||
| 429 | + gain1 = self.prefilter_gain; | ||
| 430 | + } | ||
| 431 | + qg = ((0.5f32 + gain1 * 32.0 / 3.0) as f64).floor() as i32 - 1; | ||
| 432 | + qg = qg.clamp(0, 7); | ||
| 433 | + gain1 = 0.09375f32 * (qg + 1) as f32; | ||
| 434 | + pf_on = true; | ||
| 435 | + } | ||
| 436 | + | ||
| 437 | + let offset = SHORT_MDCT - overlap; | ||
| 438 | + let mut before = [0.0f32; 2]; | ||
| 439 | + let mut after = [0.0f32; 2]; | ||
| 440 | + for ch in 0..cc { | ||
| 441 | + self.prefilter_period = self.prefilter_period.max(COMBFILTER_MINPERIOD as i32); | ||
| 442 | + let in_base = ch * (n + overlap); | ||
| 443 | + let pre_base = ch * pre_stride; | ||
| 444 | + input[in_base..in_base + overlap] | ||
| 445 | + .copy_from_slice(&self.in_mem[ch * overlap..(ch + 1) * overlap]); | ||
| 446 | + for i in 0..n { | ||
| 447 | + before[ch] += input[in_base + overlap + i].abs(); | ||
| 448 | + } | ||
| 449 | + if offset != 0 { | ||
| 450 | + comb_filter( | ||
| 451 | + &mut input[in_base + overlap..], | ||
| 452 | + pre, | ||
| 453 | + pre_base + max_period, | ||
| 454 | + self.prefilter_period, | ||
| 455 | + self.prefilter_period, | ||
| 456 | + offset, | ||
| 457 | + -self.prefilter_gain, | ||
| 458 | + -self.prefilter_gain, | ||
| 459 | + self.prefilter_tapset, | ||
| 460 | + self.prefilter_tapset, | ||
| 461 | + &[], | ||
| 462 | + 0, | ||
| 463 | + ); | ||
| 464 | + } | ||
| 465 | + comb_filter( | ||
| 466 | + &mut input[in_base + overlap + offset..], | ||
| 467 | + pre, | ||
| 468 | + pre_base + max_period + offset, | ||
| 469 | + self.prefilter_period, | ||
| 470 | + pitch_index, | ||
| 471 | + n - offset, | ||
| 472 | + -self.prefilter_gain, | ||
| 473 | + -gain1, | ||
| 474 | + self.prefilter_tapset, | ||
| 475 | + prefilter_tapset, | ||
| 476 | + window, | ||
| 477 | + overlap, | ||
| 478 | + ); | ||
| 479 | + for i in 0..n { | ||
| 480 | + after[ch] += input[in_base + overlap + i].abs(); | ||
| 481 | + } | ||
| 482 | + } | ||
| 483 | + | ||
| 484 | + let mut cancel_pitch = false; | ||
| 485 | + if cc == 2 { | ||
| 486 | + let thresh0 = (0.25f32 * gain1) * before[0] + 0.01f32 * before[1]; | ||
| 487 | + let thresh1 = (0.25f32 * gain1) * before[1] + 0.01f32 * before[0]; | ||
| 488 | + if after[0] - before[0] > thresh0 || after[1] - before[1] > thresh1 { | ||
| 489 | + cancel_pitch = true; | ||
| 490 | + } | ||
| 491 | + if before[0] - after[0] < thresh0 && before[1] - after[1] < thresh1 { | ||
| 492 | + cancel_pitch = true; | ||
| 493 | + } | ||
| 494 | + } else if after[0] > before[0] { | ||
| 495 | + cancel_pitch = true; | ||
| 496 | + } | ||
| 497 | + if cancel_pitch { | ||
| 498 | + for ch in 0..cc { | ||
| 499 | + let in_base = ch * (n + overlap); | ||
| 500 | + let pre_base = ch * pre_stride; | ||
| 501 | + input[in_base + overlap..in_base + overlap + n] | ||
| 502 | + .copy_from_slice(&pre[pre_base + max_period..pre_base + max_period + n]); | ||
| 503 | + comb_filter( | ||
| 504 | + &mut input[in_base + overlap + offset..], | ||
| 505 | + pre, | ||
| 506 | + pre_base + max_period + offset, | ||
| 507 | + self.prefilter_period, | ||
| 508 | + pitch_index, | ||
| 509 | + overlap, | ||
| 510 | + -self.prefilter_gain, | ||
| 511 | + 0.0, | ||
| 512 | + self.prefilter_tapset, | ||
| 513 | + prefilter_tapset, | ||
| 514 | + window, | ||
| 515 | + overlap, | ||
| 516 | + ); | ||
| 517 | + } | ||
| 518 | + gain1 = 0.0; | ||
| 519 | + pf_on = false; | ||
| 520 | + qg = 0; | ||
| 521 | + } | ||
| 522 | + | ||
| 523 | + for ch in 0..cc { | ||
| 524 | + let in_base = ch * (n + overlap); | ||
| 525 | + let pre_base = ch * pre_stride; | ||
| 526 | + let mem_base = ch * max_period; | ||
| 527 | + self.in_mem[ch * overlap..(ch + 1) * overlap] | ||
| 528 | + .copy_from_slice(&input[in_base + n..in_base + n + overlap]); | ||
| 529 | + if n > max_period { | ||
| 530 | + prefilter_mem[mem_base..mem_base + max_period] | ||
| 531 | + .copy_from_slice(&pre[pre_base + n..pre_base + n + max_period]); | ||
| 532 | + } else { | ||
| 533 | + prefilter_mem.copy_within(mem_base + n..mem_base + max_period, mem_base); | ||
| 534 | + prefilter_mem[mem_base + max_period - n..mem_base + max_period] | ||
| 535 | + .copy_from_slice(&pre[pre_base + max_period..pre_base + max_period + n]); | ||
| 536 | + } | ||
| 537 | + } | ||
| 538 | + | ||
| 539 | + (pf_on, pitch_index, gain1, qg) | ||
| 540 | + } | ||
| 541 | + | ||
| 542 | + /// `celt_encode_with_ec`: `pcm` holds `frame_size * channels` samples at the API rate. | ||
| 543 | + /// With `own == true` C's `enc == NULL` path: `enc` is reset to | ||
| 544 | + /// `nb_compressed_bytes` here. Returns the byte count (C's return value). | ||
| 545 | + pub(crate) fn encode( | ||
| 546 | + &mut self, | ||
| 547 | + pcm: &[f32], | ||
| 548 | + frame_size: usize, | ||
| 549 | + nb_compressed_bytes: usize, | ||
| 550 | + enc: &mut RangeEncoder, | ||
| 551 | + own: bool, | ||
| 552 | + ) -> i32 { | ||
| 553 | + if nb_compressed_bytes < 2 { | ||
| 554 | + return -1; | ||
| 555 | + } | ||
| 556 | + let cc = self.channels; | ||
| 557 | + let c = self.stream_channels; | ||
| 558 | + let up = self.upsample; | ||
| 559 | + let start = self.start; | ||
| 560 | + let end = self.end; | ||
| 561 | + let hybrid = start != 0; | ||
| 562 | + let analysis = self.analysis; | ||
| 563 | + let fs = 48000i32; | ||
| 564 | + let frame_size = frame_size * up; | ||
| 565 | + let mut lm = 0usize; | ||
| 566 | + while lm <= MAX_LM && (SHORT_MDCT << lm) != frame_size { | ||
| 567 | + lm += 1; | ||
| 568 | + } | ||
| 569 | + if lm > MAX_LM { | ||
| 570 | + return -1; | ||
| 571 | + } | ||
| 572 | + let lm_i = lm as i32; | ||
| 573 | + let c_i = c as i32; | ||
| 574 | + let m = 1usize << lm; | ||
| 575 | + let n = m * SHORT_MDCT; | ||
| 576 | + let eff_end = end.min(NB); | ||
| 577 | + | ||
| 578 | + let mut tell: i32; | ||
| 579 | + let tell0_frac: i32; | ||
| 580 | + let nb_filled: i32; | ||
| 581 | + if own { | ||
| 582 | + tell0_frac = 1; | ||
| 583 | + tell = 1; | ||
| 584 | + nb_filled = 0; | ||
| 585 | + } else { | ||
| 586 | + tell0_frac = enc.tell_frac() as i32; | ||
| 587 | + tell = enc.tell() as i32; | ||
| 588 | + nb_filled = (tell + 4) >> 3; | ||
| 589 | + } | ||
| 590 | + | ||
| 591 | + let mut nb = (nb_compressed_bytes as i32).min(PACKET_SIZE_CAP); | ||
| 592 | + let vbr_rate: i32; | ||
| 593 | + let mut effective_bytes: i32; | ||
| 594 | + if self.vbr && self.bitrate != BITRATE_MAX { | ||
| 595 | + vbr_rate = bitrate_to_bits(self.bitrate, fs, frame_size as i32) << BR; | ||
| 596 | + effective_bytes = vbr_rate >> (3 + BR); | ||
| 597 | + } else { | ||
| 598 | + vbr_rate = 0; | ||
| 599 | + let mut tmp = self.bitrate.wrapping_mul(frame_size as i32); | ||
| 600 | + if tell > 1 { | ||
| 601 | + tmp = tmp.wrapping_add(tell.wrapping_mul(fs)); | ||
| 602 | + } | ||
| 603 | + if self.bitrate != BITRATE_MAX { | ||
| 604 | + nb = 2.max(nb.min((tmp + 4 * fs) / (8 * fs))); | ||
| 605 | + if !own { | ||
| 606 | + enc.shrink(nb as usize); | ||
| 607 | + } | ||
| 608 | + } | ||
| 609 | + effective_bytes = nb - nb_filled; | ||
| 610 | + } | ||
| 611 | + let mut nb_avail = nb - nb_filled; | ||
| 612 | + let mut equiv_rate = ((nb * 8 * 50) << (3 - lm_i)) - (40 * c_i + 20) * ((400 >> lm_i) - 50); | ||
| 613 | + if self.bitrate != BITRATE_MAX { | ||
| 614 | + equiv_rate = equiv_rate.min(self.bitrate - (40 * c_i + 20) * ((400 >> lm_i) - 50)); | ||
| 615 | + } | ||
| 616 | + | ||
| 617 | + if own { | ||
| 618 | + enc.reset(nb as usize); | ||
| 619 | + } | ||
| 620 | + | ||
| 621 | + if vbr_rate > 0 && self.constrained_vbr { | ||
| 622 | + let vbr_bound = vbr_rate; | ||
| 623 | + let floor = if tell == 1 { 2 } else { 0 }; | ||
| 624 | + let max_allowed = floor | ||
| 625 | + .max((vbr_rate + vbr_bound - self.vbr_reservoir) >> (BR + 3)) | ||
| 626 | + .min(nb_avail); | ||
| 627 | + if max_allowed < nb_avail { | ||
| 628 | + nb = nb_filled + max_allowed; | ||
| 629 | + nb_avail = max_allowed; | ||
| 630 | + enc.shrink(nb as usize); | ||
| 631 | + } | ||
| 632 | + } | ||
| 633 | + let mut total_bits = nb * 8; | ||
| 634 | + | ||
| 635 | + let mut input_buf = [0.0f32; INPUT_LEN]; | ||
| 636 | + let input = &mut input_buf[..cc * (n + OVERLAP)]; | ||
| 637 | + let pcm_split = cc * (n - OVERLAP) / up; | ||
| 638 | + let mut sample_max = max32(self.overlap_max, maxabs(&pcm[..pcm_split])); | ||
| 639 | + self.overlap_max = maxabs(&pcm[pcm_split..pcm_split + cc * OVERLAP / up]); | ||
| 640 | + sample_max = max32(sample_max, self.overlap_max); | ||
| 641 | + let mut silence = sample_max <= 1.0f32 / ((1i32 << self.lsb_depth) as f32); | ||
| 642 | + | ||
| 643 | + if tell == 1 { | ||
| 644 | + enc.enc_bit_logp(silence, 15); | ||
| 645 | + } else { | ||
| 646 | + silence = false; | ||
| 647 | + } | ||
| 648 | + if silence { | ||
| 649 | + if vbr_rate > 0 { | ||
| 650 | + nb = nb.min(nb_filled + 2); | ||
| 651 | + effective_bytes = nb; | ||
| 652 | + total_bits = nb * 8; | ||
| 653 | + nb_avail = 2; | ||
| 654 | + enc.shrink(nb as usize); | ||
| 655 | + } | ||
| 656 | + let before = enc.tell() as i32; | ||
| 657 | + tell = nb * 8; | ||
| 658 | + enc.add_tell(tell - before); | ||
| 659 | + } | ||
| 660 | + | ||
| 661 | + for ch in 0..cc { | ||
| 662 | + let need_clip = self.clip && sample_max > 65536.0; | ||
| 663 | + let in_base = ch * (n + OVERLAP); | ||
| 664 | + celt_preemphasis( | ||
| 665 | + &pcm[ch..], | ||
| 666 | + &mut input[in_base + OVERLAP..], | ||
| 667 | + n, | ||
| 668 | + cc, | ||
| 669 | + up, | ||
| 670 | + 0.85000610f32, | ||
| 671 | + &mut self.preemph_mem_e[ch], | ||
| 672 | + need_clip, | ||
| 673 | + ); | ||
| 674 | + let src = (ch + 1) * COMBFILTER_MAXPERIOD - OVERLAP; | ||
| 675 | + input[in_base..in_base + OVERLAP] | ||
| 676 | + .copy_from_slice(&self.prefilter_mem[src..src + OVERLAP]); | ||
| 677 | + } | ||
| 678 | + | ||
| 679 | + let mut toneishness: f32 = 0.0; | ||
| 680 | + let tone_freq = tone_detect(input, cc, n + OVERLAP, &mut toneishness, fs); | ||
| 681 | + let mut is_transient = false; | ||
| 682 | + let mut short_blocks = 0usize; | ||
| 683 | + let mut tf_estimate: f32 = 0.0; | ||
| 684 | + let mut tf_chan: usize = 0; | ||
| 685 | + let mut weak_transient = false; | ||
| 686 | + let mut transient_got_disabled = false; | ||
| 687 | + if self.complexity >= 1 && !self.lfe { | ||
| 688 | + let allow_weak_transients = | ||
| 689 | + hybrid && effective_bytes < 15 && self.silk_signal_type != 2; | ||
| 690 | + is_transient = transient_analysis( | ||
| 691 | + input, | ||
| 692 | + n + OVERLAP, | ||
| 693 | + cc, | ||
| 694 | + &mut tf_estimate, | ||
| 695 | + &mut tf_chan, | ||
| 696 | + allow_weak_transients, | ||
| 697 | + &mut weak_transient, | ||
| 698 | + tone_freq, | ||
| 699 | + toneishness, | ||
| 700 | + ); | ||
| 701 | + } | ||
| 702 | + toneishness = min32(toneishness, 1.0 - tf_estimate); | ||
| 703 | + | ||
| 704 | + let mut pitch_index: i32; | ||
| 705 | + let gain1: f32; | ||
| 706 | + let prefilter_tapset: i32; | ||
| 707 | + let pf_on: bool; | ||
| 708 | + let mut pitch_change = false; | ||
| 709 | + { | ||
| 710 | + let enabled = ((self.lfe && nb_avail > 3) || nb_avail > 12 * c_i) | ||
| 711 | + && !hybrid | ||
| 712 | + && !silence | ||
| 713 | + && tell + 16 <= total_bits | ||
| 714 | + && !self.disable_pf; | ||
| 715 | + prefilter_tapset = self.tapset_decision; | ||
| 716 | + let mut prefilter_mem = std::mem::take(&mut self.prefilter_mem); | ||
| 717 | + let (on, pi, g, qg) = self.run_prefilter( | ||
| 718 | + input, | ||
| 719 | + &mut prefilter_mem, | ||
| 720 | + cc, | ||
| 721 | + n, | ||
| 722 | + prefilter_tapset, | ||
| 723 | + enabled, | ||
| 724 | + tf_estimate, | ||
| 725 | + nb_avail, | ||
| 726 | + &analysis, | ||
| 727 | + tone_freq, | ||
| 728 | + toneishness, | ||
| 729 | + ); | ||
| 730 | + self.prefilter_mem = prefilter_mem; | ||
| 731 | + pf_on = on; | ||
| 732 | + pitch_index = pi; | ||
| 733 | + gain1 = g; | ||
| 734 | + if (gain1 > 0.4f32 || self.prefilter_gain > 0.4f32) | ||
| 735 | + && (!analysis.valid || (analysis.tonality as f64) > 0.3) | ||
| 736 | + && ((pitch_index as f64) > 1.26 * (self.prefilter_period as f64) | ||
| 737 | + || (pitch_index as f64) < 0.79 * (self.prefilter_period as f64)) | ||
| 738 | + { | ||
| 739 | + pitch_change = true; | ||
| 740 | + } | ||
| 741 | + if !pf_on { | ||
| 742 | + if !hybrid && tell + 16 <= total_bits { | ||
| 743 | + enc.enc_bit_logp(false, 1); | ||
| 744 | + } | ||
| 745 | + } else { | ||
| 746 | + enc.enc_bit_logp(true, 1); | ||
| 747 | + pitch_index += 1; | ||
| 748 | + let octave = ilog(pitch_index as u32) - 5; | ||
| 749 | + enc.enc_uint(octave as u32, 6); | ||
| 750 | + enc.enc_bits((pitch_index - (16 << octave)) as u32, (4 + octave) as u32); | ||
| 751 | + pitch_index -= 1; | ||
| 752 | + enc.enc_bits(qg as u32, 3); | ||
| 753 | + enc.enc_icdf(prefilter_tapset as usize, &TAPSET_ICDF, 2); | ||
| 754 | + } | ||
| 755 | + } | ||
| 756 | + if lm > 0 && (enc.tell() as i32) + 3 <= total_bits { | ||
| 757 | + if is_transient { | ||
| 758 | + short_blocks = m; | ||
| 759 | + } | ||
| 760 | + } else { | ||
| 761 | + is_transient = false; | ||
| 762 | + transient_got_disabled = true; | ||
| 763 | + } | ||
| 764 | + | ||
| 765 | + let mut freq_buf = [0.0f32; FREQ_LEN]; | ||
| 766 | + let freq = &mut freq_buf[..cc * n]; | ||
| 767 | + let mut band_e_buf = [0.0f32; BAND_LEN]; | ||
| 768 | + let band_e = &mut band_e_buf[..cc * NB]; | ||
| 769 | + let mut band_log_e_buf = [0.0f32; BAND_LEN]; | ||
| 770 | + let band_log_e = &mut band_log_e_buf[..cc * NB]; | ||
| 771 | + let mut band_log_e2_buf = [0.0f32; BAND_LEN]; | ||
| 772 | + let band_log_e2 = &mut band_log_e2_buf[..c * NB]; | ||
| 773 | + | ||
| 774 | + let second_mdct = short_blocks != 0 && self.complexity >= 8; | ||
| 775 | + if second_mdct { | ||
| 776 | + compute_mdcts(0, input, freq, c, cc, lm, up); | ||
| 777 | + compute_band_energies(freq, band_e, eff_end, c, lm); | ||
| 778 | + amp2log2(eff_end, end, band_e, band_log_e2, c); | ||
| 779 | + for ch in 0..c { | ||
| 780 | + for i in 0..end { | ||
| 781 | + band_log_e2[NB * ch + i] += 0.5f32 * lm as f32; | ||
| 782 | + } | ||
| 783 | + } | ||
| 784 | + } | ||
| 785 | + | ||
| 786 | + compute_mdcts(short_blocks, input, freq, c, cc, lm, up); | ||
| 787 | + if cc == 2 && c == 1 { | ||
| 788 | + tf_chan = 0; | ||
| 789 | + } | ||
| 790 | + compute_band_energies(freq, band_e, eff_end, c, lm); | ||
| 791 | + if self.lfe { | ||
| 792 | + for i in 2..end { | ||
| 793 | + band_e[i] = min32(band_e[i], 1e-4f32 * band_e[0]); | ||
| 794 | + band_e[i] = max32(band_e[i], EPSILON); | ||
| 795 | + } | ||
| 796 | + } | ||
| 797 | + amp2log2(eff_end, end, band_e, band_log_e, c); | ||
| 798 | + | ||
| 799 | + let surround_buf = [0.0f32; BAND_LEN]; | ||
| 800 | + let surround_dynalloc = &surround_buf[..cc * NB]; | ||
| 801 | + let mut temporal_vbr: f32 = 0.0; | ||
| 802 | + if !self.lfe { | ||
| 803 | + let mut follow: f32 = -10.0; | ||
| 804 | + let mut frame_avg: f32 = 0.0; | ||
| 805 | + let offset: f32 = if short_blocks != 0 { | ||
| 806 | + 0.5f32 * lm as f32 | ||
| 807 | + } else { | ||
| 808 | + 0.0 | ||
| 809 | + }; | ||
| 810 | + for i in start..end { | ||
| 811 | + follow = max32(follow - 1.0, band_log_e[i] - offset); | ||
| 812 | + if c == 2 { | ||
| 813 | + follow = max32(follow, band_log_e[i + NB] - offset); | ||
| 814 | + } | ||
| 815 | + frame_avg += follow; | ||
| 816 | + } | ||
| 817 | + frame_avg /= (end as i32 - start as i32) as f32; | ||
| 818 | + temporal_vbr = frame_avg - self.spec_avg; | ||
| 819 | + temporal_vbr = min32(3.0, max32(-1.5, temporal_vbr)); | ||
| 820 | + self.spec_avg += 0.02f32 * temporal_vbr; | ||
| 821 | + } | ||
| 822 | + | ||
| 823 | + if !second_mdct { | ||
| 824 | + band_log_e2[..c * NB].copy_from_slice(&band_log_e[..c * NB]); | ||
| 825 | + } | ||
| 826 | + | ||
| 827 | + if lm > 0 | ||
| 828 | + && (enc.tell() as i32) + 3 <= total_bits | ||
| 829 | + && !is_transient | ||
| 830 | + && self.complexity >= 5 | ||
| 831 | + && !self.lfe | ||
| 832 | + && !hybrid | ||
| 833 | + && patch_transient_decision(band_log_e, &self.old_band_e, start, end, c) | ||
| 834 | + { | ||
| 835 | + is_transient = true; | ||
| 836 | + short_blocks = m; | ||
| 837 | + compute_mdcts(short_blocks, input, freq, c, cc, lm, up); | ||
| 838 | + compute_band_energies(freq, band_e, eff_end, c, lm); | ||
| 839 | + amp2log2(eff_end, end, band_e, band_log_e, c); | ||
| 840 | + for ch in 0..c { | ||
| 841 | + for i in 0..end { | ||
| 842 | + band_log_e2[NB * ch + i] += 0.5f32 * lm as f32; | ||
| 843 | + } | ||
| 844 | + } | ||
| 845 | + tf_estimate = 0.2f32; | ||
| 846 | + } | ||
| 847 | + | ||
| 848 | + if lm > 0 && (enc.tell() as i32) + 3 <= total_bits { | ||
| 849 | + enc.enc_bit_logp(is_transient, 3); | ||
| 850 | + } | ||
| 851 | + | ||
| 852 | + let mut x_buf = [0.0f32; FREQ_LEN]; | ||
| 853 | + let x = &mut x_buf[..c * n]; | ||
| 854 | + normalise_bands(freq, x, band_e, eff_end, c, m); | ||
| 855 | + | ||
| 856 | + let enable_tf_analysis = effective_bytes >= 15 * c_i | ||
| 857 | + && !hybrid | ||
| 858 | + && self.complexity >= 2 | ||
| 859 | + && !self.lfe | ||
| 860 | + && toneishness < 0.98f32; | ||
| 861 | + | ||
| 862 | + let mut offsets = [0i32; NB]; | ||
| 863 | + let mut importance = [0i32; NB]; | ||
| 864 | + let mut spread_weight = [0i32; NB]; | ||
| 865 | + let mut tot_boost: i32 = 0; | ||
| 866 | + let max_depth = dynalloc_analysis( | ||
| 867 | + band_log_e, | ||
| 868 | + band_log_e2, | ||
| 869 | + &self.old_band_e, | ||
| 870 | + start, | ||
| 871 | + end, | ||
| 872 | + c, | ||
| 873 | + &mut offsets, | ||
| 874 | + self.lsb_depth, | ||
| 875 | + is_transient, | ||
| 876 | + self.vbr, | ||
| 877 | + self.constrained_vbr, | ||
| 878 | + lm, | ||
| 879 | + effective_bytes, | ||
| 880 | + &mut tot_boost, | ||
| 881 | + self.lfe, | ||
| 882 | + surround_dynalloc, | ||
| 883 | + &analysis, | ||
| 884 | + &mut importance, | ||
| 885 | + &mut spread_weight, | ||
| 886 | + tone_freq, | ||
| 887 | + toneishness, | ||
| 888 | + ); | ||
| 889 | + | ||
| 890 | + let mut tf_res = [0i32; NB]; | ||
| 891 | + | ||
| 892 | + let tf_select: i32; | ||
| 893 | + if enable_tf_analysis { | ||
| 894 | + let lambda = 80.max(20480 / effective_bytes + 2); | ||
| 895 | + tf_select = tf_analysis( | ||
| 896 | + eff_end, | ||
| 897 | + is_transient, | ||
| 898 | + &mut tf_res, | ||
| 899 | + lambda, | ||
| 900 | + x, | ||
| 901 | + n, | ||
| 902 | + lm, | ||
| 903 | + tf_estimate, | ||
| 904 | + tf_chan, | ||
| 905 | + &importance, | ||
| 906 | + ); | ||
| 907 | + for i in eff_end..end { | ||
| 908 | + tf_res[i] = tf_res[eff_end - 1]; | ||
| 909 | + } | ||
| 910 | + } else if hybrid && weak_transient { | ||
| 911 | + for i in 0..end { | ||
| 912 | + tf_res[i] = 1; | ||
| 913 | + } | ||
| 914 | + tf_select = 0; | ||
| 915 | + } else if hybrid && effective_bytes < 15 && self.silk_signal_type != 2 { | ||
| 916 | + for i in 0..end { | ||
| 917 | + tf_res[i] = 0; | ||
| 918 | + } | ||
| 919 | + tf_select = is_transient as i32; | ||
| 920 | + } else { | ||
| 921 | + for i in 0..end { | ||
| 922 | + tf_res[i] = is_transient as i32; | ||
| 923 | + } | ||
| 924 | + tf_select = 0; | ||
| 925 | + } | ||
| 926 | + | ||
| 927 | + let mut error_buf = [0.0f32; BAND_LEN]; | ||
| 928 | + let error = &mut error_buf[..c * NB]; | ||
| 929 | + for ch in 0..c { | ||
| 930 | + for i in start..end { | ||
| 931 | + let idx = i + ch * NB; | ||
| 932 | + if (band_log_e[idx] - self.old_band_e[idx]).abs() < 2.0f32 { | ||
| 933 | + band_log_e[idx] -= 0.25f32 * self.energy_error[idx]; | ||
| 934 | + } | ||
| 935 | + } | ||
| 936 | + } | ||
| 937 | + quant_coarse_energy( | ||
| 938 | + start, | ||
| 939 | + end, | ||
| 940 | + eff_end, | ||
| 941 | + band_log_e, | ||
| 942 | + &mut self.old_band_e, | ||
| 943 | + total_bits as u32, | ||
| 944 | + error, | ||
| 945 | + enc, | ||
| 946 | + c, | ||
| 947 | + lm, | ||
| 948 | + nb_avail, | ||
| 949 | + self.force_intra, | ||
| 950 | + &mut self.delayed_intra, | ||
| 951 | + self.complexity >= 4, | ||
| 952 | + self.loss_rate, | ||
| 953 | + self.lfe, | ||
| 954 | + ); | ||
| 955 | + | ||
| 956 | + tf_encode(start, end, is_transient, &mut tf_res, lm, tf_select, enc); | ||
| 957 | + | ||
| 958 | + if (enc.tell() as i32) + 4 <= total_bits { | ||
| 959 | + if self.lfe { | ||
| 960 | + self.tapset_decision = 0; | ||
| 961 | + self.spread_decision = SPREAD_NORMAL as i32; | ||
| 962 | + } else if hybrid { | ||
| 963 | + if self.complexity == 0 { | ||
| 964 | + self.spread_decision = SPREAD_NONE as i32; | ||
| 965 | + } else if is_transient { | ||
| 966 | + self.spread_decision = SPREAD_NORMAL as i32; | ||
| 967 | + } else { | ||
| 968 | + self.spread_decision = SPREAD_AGGRESSIVE as i32; | ||
| 969 | + } | ||
| 970 | + } else if short_blocks != 0 || self.complexity < 3 || nb_avail < 10 * c_i { | ||
| 971 | + if self.complexity == 0 { | ||
| 972 | + self.spread_decision = SPREAD_NONE as i32; | ||
| 973 | + } else { | ||
| 974 | + self.spread_decision = SPREAD_NORMAL as i32; | ||
| 975 | + } | ||
| 976 | + } else { | ||
| 977 | + self.spread_decision = spreading_decision( | ||
| 978 | + x, | ||
| 979 | + &mut self.tonal_average, | ||
| 980 | + self.spread_decision, | ||
| 981 | + &mut self.hf_average, | ||
| 982 | + &mut self.tapset_decision, | ||
| 983 | + pf_on && short_blocks == 0, | ||
| 984 | + eff_end, | ||
| 985 | + c, | ||
| 986 | + m, | ||
| 987 | + &spread_weight, | ||
| 988 | + ); | ||
| 989 | + } | ||
| 990 | + enc.enc_icdf(self.spread_decision as usize, &SPREAD_ICDF, 5); | ||
| 991 | + } else { | ||
| 992 | + self.spread_decision = SPREAD_NORMAL as i32; | ||
| 993 | + } | ||
| 994 | + | ||
| 995 | + if self.lfe { | ||
| 996 | + offsets[0] = 8.min(effective_bytes / 3); | ||
| 997 | + } | ||
| 998 | + let cap = init_caps(lm, c); | ||
| 999 | + | ||
| 1000 | + let mut dynalloc_logp: i32 = 6; | ||
| 1001 | + total_bits <<= BR; | ||
| 1002 | + let mut total_boost: i32 = 0; | ||
| 1003 | + tell = enc.tell_frac() as i32; | ||
| 1004 | + for i in start..end { | ||
| 1005 | + let width = (c_i * (E_BANDS[i + 1] - E_BANDS[i]) as i32) << lm_i; | ||
| 1006 | + let quanta = (width << BR).min((6 << BR).max(width)); | ||
| 1007 | + let mut dynalloc_loop_logp = dynalloc_logp; | ||
| 1008 | + let mut boost: i32 = 0; | ||
| 1009 | + let mut j: i32 = 0; | ||
| 1010 | + while tell + (dynalloc_loop_logp << BR) < total_bits - total_boost && boost < cap[i] { | ||
| 1011 | + let flag = j < offsets[i]; | ||
| 1012 | + enc.enc_bit_logp(flag, dynalloc_loop_logp as u32); | ||
| 1013 | + tell = enc.tell_frac() as i32; | ||
| 1014 | + if !flag { | ||
| 1015 | + break; | ||
| 1016 | + } | ||
| 1017 | + boost += quanta; | ||
| 1018 | + total_boost += quanta; | ||
| 1019 | + dynalloc_loop_logp = 1; | ||
| 1020 | + j += 1; | ||
| 1021 | + } | ||
| 1022 | + if j != 0 { | ||
| 1023 | + dynalloc_logp = 2.max(dynalloc_logp - 1); | ||
| 1024 | + } | ||
| 1025 | + offsets[i] = boost; | ||
| 1026 | + } | ||
| 1027 | + | ||
| 1028 | + let mut dual_stereo = false; | ||
| 1029 | + if c == 2 { | ||
| 1030 | + if lm != 0 { | ||
| 1031 | + dual_stereo = stereo_analysis(x, lm, n); | ||
| 1032 | + } | ||
| 1033 | + let v = hysteresis_decision( | ||
| 1034 | + (equiv_rate / 1000) as f32, | ||
| 1035 | + &INTENSITY_THRESHOLDS, | ||
| 1036 | + &INTENSITY_HYSTERESIS, | ||
| 1037 | + self.intensity as i32, | ||
| 1038 | + ); | ||
| 1039 | + let v = (start as i32).max(v); | ||
| 1040 | + let v = (end as i32).min(v); | ||
| 1041 | + self.intensity = v as usize; | ||
| 1042 | + } | ||
| 1043 | + | ||
| 1044 | + let mut alloc_trim: i32 = 5; | ||
| 1045 | + if tell + (6 << BR) <= total_bits - total_boost { | ||
| 1046 | + if start > 0 || self.lfe { | ||
| 1047 | + self.stereo_saving = 0.0; | ||
| 1048 | + alloc_trim = 5; | ||
| 1049 | + } else { | ||
| 1050 | + alloc_trim = alloc_trim_analysis( | ||
| 1051 | + x, | ||
| 1052 | + band_log_e, | ||
| 1053 | + end, | ||
| 1054 | + lm, | ||
| 1055 | + c, | ||
| 1056 | + n, | ||
| 1057 | + &analysis, | ||
| 1058 | + &mut self.stereo_saving, | ||
| 1059 | + tf_estimate, | ||
| 1060 | + self.intensity, | ||
| 1061 | + 0.0, | ||
| 1062 | + equiv_rate, | ||
| 1063 | + ); | ||
| 1064 | + } | ||
| 1065 | + enc.enc_icdf(alloc_trim as usize, &TRIM_ICDF, 7); | ||
| 1066 | + tell = enc.tell_frac() as i32; | ||
| 1067 | + } | ||
| 1068 | + | ||
| 1069 | + let mut min_allowed = ((tell + total_boost + (1 << (BR + 3)) - 1) >> (BR + 3)) + 2; | ||
| 1070 | + if hybrid { | ||
| 1071 | + min_allowed = min_allowed | ||
| 1072 | + .max((tell0_frac + (37 << BR) + total_boost + (1 << (BR + 3)) - 1) >> (BR + 3)); | ||
| 1073 | + } | ||
| 1074 | + | ||
| 1075 | + if vbr_rate > 0 { | ||
| 1076 | + let lm_diff = MAX_LM as i32 - lm_i; | ||
| 1077 | + nb = nb.min(PACKET_SIZE_CAP >> (3 - lm_i)); | ||
| 1078 | + let mut base_target = if !hybrid { | ||
| 1079 | + vbr_rate - ((40 * c_i + 20) << BR) | ||
| 1080 | + } else { | ||
| 1081 | + 0.max(vbr_rate - ((9 * c_i + 4) << BR)) | ||
| 1082 | + }; | ||
| 1083 | + if self.constrained_vbr { | ||
| 1084 | + base_target += self.vbr_offset >> lm_diff; | ||
| 1085 | + } | ||
| 1086 | + let target = if !hybrid { | ||
| 1087 | + compute_vbr( | ||
| 1088 | + &analysis, | ||
| 1089 | + base_target, | ||
| 1090 | + lm, | ||
| 1091 | + equiv_rate, | ||
| 1092 | + self.last_coded_bands, | ||
| 1093 | + c, | ||
| 1094 | + self.intensity, | ||
| 1095 | + self.constrained_vbr, | ||
| 1096 | + self.stereo_saving, | ||
| 1097 | + tot_boost, | ||
| 1098 | + tf_estimate, | ||
| 1099 | + pitch_change, | ||
| 1100 | + max_depth, | ||
| 1101 | + self.lfe, | ||
| 1102 | + false, | ||
| 1103 | + 0.0, | ||
| 1104 | + temporal_vbr, | ||
| 1105 | + ) | ||
| 1106 | + } else { | ||
| 1107 | + let mut t = base_target; | ||
| 1108 | + if self.silk_offset < 100 { | ||
| 1109 | + t += (12 << BR) >> (3 - lm_i); | ||
| 1110 | + } | ||
| 1111 | + if self.silk_offset > 100 { | ||
| 1112 | + t -= (18 << BR) >> (3 - lm_i); | ||
| 1113 | + } | ||
| 1114 | + t += ((tf_estimate - 0.25f32) * ((50 << BR) as f32)) as i32; | ||
| 1115 | + if tf_estimate > 0.7f32 { | ||
| 1116 | + t = t.max(50 << BR); | ||
| 1117 | + } | ||
| 1118 | + t | ||
| 1119 | + }; | ||
| 1120 | + let target = target + tell; | ||
| 1121 | + | ||
| 1122 | + nb_avail = (target + (1 << (BR + 2))) >> (BR + 3); | ||
| 1123 | + nb_avail = min_allowed.max(nb_avail); | ||
| 1124 | + nb_avail = nb.min(nb_avail); | ||
| 1125 | + | ||
| 1126 | + let mut delta = target - vbr_rate; | ||
| 1127 | + let mut target_bits = nb_avail << (BR + 3); | ||
| 1128 | + | ||
| 1129 | + if silence { | ||
| 1130 | + nb_avail = 2; | ||
| 1131 | + target_bits = (2 * 8) << BR; | ||
| 1132 | + delta = 0; | ||
| 1133 | + } | ||
| 1134 | + | ||
| 1135 | + let alpha: f32 = if self.vbr_count < 970 { | ||
| 1136 | + self.vbr_count += 1; | ||
| 1137 | + celt_rcp((self.vbr_count + 20) as f32) | ||
| 1138 | + } else { | ||
| 1139 | + 0.001f32 | ||
| 1140 | + }; | ||
| 1141 | + if self.constrained_vbr { | ||
| 1142 | + self.vbr_reservoir += target_bits - vbr_rate; | ||
| 1143 | + let d = delta * (1 << lm_diff) - self.vbr_offset - self.vbr_drift; | ||
| 1144 | + self.vbr_drift += (alpha * d as f32) as i32; | ||
| 1145 | + self.vbr_offset = -self.vbr_drift; | ||
| 1146 | + } | ||
| 1147 | + if self.constrained_vbr && self.vbr_reservoir < 0 { | ||
| 1148 | + let adjust = (-self.vbr_reservoir) / (8 << BR); | ||
| 1149 | + if !silence { | ||
| 1150 | + nb_avail += adjust; | ||
| 1151 | + } | ||
| 1152 | + self.vbr_reservoir = 0; | ||
| 1153 | + } | ||
| 1154 | + nb = nb.min(nb_avail); | ||
| 1155 | + enc.shrink(nb as usize); | ||
| 1156 | + } | ||
| 1157 | + | ||
| 1158 | + let mut bits = ((nb * 8) << BR) - (enc.tell_frac() as i32) - 1; | ||
| 1159 | + let anti_collapse_rsv = if is_transient && lm >= 2 && bits >= ((lm_i + 2) << BR) { | ||
| 1160 | + 1 << BR | ||
| 1161 | + } else { | ||
| 1162 | + 0 | ||
| 1163 | + }; | ||
| 1164 | + bits -= anti_collapse_rsv; | ||
| 1165 | + | ||
| 1166 | + let mut pulses = [0i32; NB]; | ||
| 1167 | + let mut fine_quant = [0i32; NB]; | ||
| 1168 | + let mut fine_priority = [0i32; NB]; | ||
| 1169 | + let mut signal_bandwidth = end - 1; | ||
| 1170 | + if analysis.valid { | ||
| 1171 | + let min_bandwidth = if equiv_rate < 32000 * c_i { | ||
| 1172 | + 13 | ||
| 1173 | + } else if equiv_rate < 48000 * c_i { | ||
| 1174 | + 16 | ||
| 1175 | + } else if equiv_rate < 60000 * c_i { | ||
| 1176 | + 18 | ||
| 1177 | + } else if equiv_rate < 80000 * c_i { | ||
| 1178 | + 19 | ||
| 1179 | + } else { | ||
| 1180 | + 20 | ||
| 1181 | + }; | ||
| 1182 | + signal_bandwidth = (analysis.bandwidth.max(min_bandwidth)) as usize; | ||
| 1183 | + } | ||
| 1184 | + if self.lfe { | ||
| 1185 | + signal_bandwidth = 1; | ||
| 1186 | + } | ||
| 1187 | + let alloc = compute_allocation_encode( | ||
| 1188 | + enc, | ||
| 1189 | + start, | ||
| 1190 | + end, | ||
| 1191 | + alloc_trim, | ||
| 1192 | + bits, | ||
| 1193 | + c, | ||
| 1194 | + lm, | ||
| 1195 | + &offsets, | ||
| 1196 | + &cap, | ||
| 1197 | + &mut pulses, | ||
| 1198 | + &mut fine_quant, | ||
| 1199 | + &mut fine_priority, | ||
| 1200 | + self.intensity, | ||
| 1201 | + dual_stereo, | ||
| 1202 | + self.last_coded_bands, | ||
| 1203 | + signal_bandwidth, | ||
| 1204 | + ); | ||
| 1205 | + self.intensity = alloc.intensity; | ||
| 1206 | + dual_stereo = alloc.dual_stereo; | ||
| 1207 | + let balance = alloc.balance; | ||
| 1208 | + let coded_bands = alloc.coded_bands; | ||
| 1209 | + | ||
| 1210 | + if self.last_coded_bands != 0 { | ||
| 1211 | + self.last_coded_bands = | ||
| 1212 | + (self.last_coded_bands + 1).min((self.last_coded_bands - 1).max(coded_bands)); | ||
| 1213 | + } else { | ||
| 1214 | + self.last_coded_bands = coded_bands; | ||
| 1215 | + } | ||
| 1216 | + | ||
| 1217 | + quant_fine_energy(start, end, &mut self.old_band_e, error, &fine_quant, enc, c); | ||
| 1218 | + self.energy_error.fill(0.0); | ||
| 1219 | + | ||
| 1220 | + let mut collapse_buf = [0u8; BAND_LEN]; | ||
| 1221 | + let collapse_masks = &mut collapse_buf[..c * NB]; | ||
| 1222 | + { | ||
| 1223 | + let (x0, x1) = x.split_at_mut(n); | ||
| 1224 | + let y = if c == 2 { Some(x1) } else { None }; | ||
| 1225 | + quant_all_bands( | ||
| 1226 | + start, | ||
| 1227 | + end, | ||
| 1228 | + x0, | ||
| 1229 | + y, | ||
| 1230 | + collapse_masks, | ||
| 1231 | + band_e, | ||
| 1232 | + &pulses, | ||
| 1233 | + short_blocks != 0, | ||
| 1234 | + self.spread_decision, | ||
| 1235 | + dual_stereo, | ||
| 1236 | + self.intensity, | ||
| 1237 | + &tf_res, | ||
| 1238 | + nb * (8 << BR) - anti_collapse_rsv, | ||
| 1239 | + balance, | ||
| 1240 | + enc, | ||
| 1241 | + lm, | ||
| 1242 | + coded_bands, | ||
| 1243 | + &mut self.rng, | ||
| 1244 | + self.complexity, | ||
| 1245 | + self.disable_inv, | ||
| 1246 | + ); | ||
| 1247 | + } | ||
| 1248 | + | ||
| 1249 | + if anti_collapse_rsv > 0 { | ||
| 1250 | + let anti_collapse_on = self.consec_transient < 2; | ||
| 1251 | + enc.enc_bits(anti_collapse_on as u32, 1); | ||
| 1252 | + } | ||
| 1253 | + quant_energy_finalise( | ||
| 1254 | + start, | ||
| 1255 | + end, | ||
| 1256 | + &mut self.old_band_e, | ||
| 1257 | + error, | ||
| 1258 | + &fine_quant, | ||
| 1259 | + &fine_priority, | ||
| 1260 | + nb * 8 - enc.tell() as i32, | ||
| 1261 | + enc, | ||
| 1262 | + c, | ||
| 1263 | + ); | ||
| 1264 | + for ch in 0..c { | ||
| 1265 | + for i in start..end { | ||
| 1266 | + let idx = i + ch * NB; | ||
| 1267 | + self.energy_error[idx] = max32(-0.5, min32(0.5, error[idx])); | ||
| 1268 | + } | ||
| 1269 | + } | ||
| 1270 | + if silence { | ||
| 1271 | + self.old_band_e[..c * NB].fill(-28.0); | ||
| 1272 | + } | ||
| 1273 | + | ||
| 1274 | + self.prefilter_period = pitch_index; | ||
| 1275 | + self.prefilter_gain = gain1; | ||
| 1276 | + self.prefilter_tapset = prefilter_tapset; | ||
| 1277 | + | ||
| 1278 | + if cc == 2 && c == 1 { | ||
| 1279 | + self.old_band_e.copy_within(0..NB, NB); | ||
| 1280 | + } | ||
| 1281 | + | ||
| 1282 | + if !is_transient { | ||
| 1283 | + self.old_log_e2.copy_from_slice(&self.old_log_e); | ||
| 1284 | + self.old_log_e.copy_from_slice(&self.old_band_e); | ||
| 1285 | + } else { | ||
| 1286 | + for i in 0..cc * NB { | ||
| 1287 | + self.old_log_e[i] = min32(self.old_log_e[i], self.old_band_e[i]); | ||
| 1288 | + } | ||
| 1289 | + } | ||
| 1290 | + for ch in 0..cc { | ||
| 1291 | + for i in 0..start { | ||
| 1292 | + self.old_band_e[ch * NB + i] = 0.0; | ||
| 1293 | + self.old_log_e[ch * NB + i] = -28.0; | ||
| 1294 | + self.old_log_e2[ch * NB + i] = -28.0; | ||
| 1295 | + } | ||
| 1296 | + for i in end..NB { | ||
| 1297 | + self.old_band_e[ch * NB + i] = 0.0; | ||
| 1298 | + self.old_log_e[ch * NB + i] = -28.0; | ||
| 1299 | + self.old_log_e2[ch * NB + i] = -28.0; | ||
| 1300 | + } | ||
| 1301 | + } | ||
| 1302 | + | ||
| 1303 | + if is_transient || transient_got_disabled { | ||
| 1304 | + self.consec_transient += 1; | ||
| 1305 | + } else { | ||
| 1306 | + self.consec_transient = 0; | ||
| 1307 | + } | ||
| 1308 | + self.rng = enc.range(); | ||
| 1309 | + | ||
| 1310 | + enc.done(); | ||
| 1311 | + if enc.error() { | ||
| 1312 | + return -3; | ||
| 1313 | + } | ||
| 1314 | + nb | ||
| 1315 | + } | ||
| 1316 | + | ||
| 1317 | + /// `CELT_SET_START_BAND`. | ||
| 1318 | + pub(crate) fn set_start_band(&mut self, v: usize) { | ||
| 1319 | + if v < NB_BANDS { | ||
| 1320 | + self.start = v; | ||
| 1321 | + } | ||
| 1322 | + } | ||
| 1323 | + /// `CELT_SET_END_BAND`. | ||
| 1324 | + pub(crate) fn set_end_band(&mut self, v: usize) { | ||
| 1325 | + if (1..=NB_BANDS).contains(&v) { | ||
| 1326 | + self.end = v; | ||
| 1327 | + } | ||
| 1328 | + } | ||
| 1329 | + /// `CELT_SET_CHANNELS`. | ||
| 1330 | + pub(crate) fn set_stream_channels(&mut self, v: usize) { | ||
| 1331 | + if (1..=2).contains(&v) { | ||
| 1332 | + self.stream_channels = v; | ||
| 1333 | + } | ||
| 1334 | + } | ||
| 1335 | + /// `OPUS_SET_VBR`. | ||
| 1336 | + pub(crate) fn set_vbr(&mut self, v: bool) { | ||
| 1337 | + self.vbr = v; | ||
| 1338 | + } | ||
| 1339 | + /// `OPUS_SET_VBR_CONSTRAINT`. | ||
| 1340 | + pub(crate) fn set_vbr_constraint(&mut self, v: bool) { | ||
| 1341 | + self.constrained_vbr = v; | ||
| 1342 | + } | ||
| 1343 | + /// `OPUS_SET_BITRATE` (`BITRATE_MAX` allowed). | ||
| 1344 | + pub(crate) fn set_bitrate(&mut self, v: i32) { | ||
| 1345 | + if v <= 500 && v != BITRATE_MAX { | ||
| 1346 | + return; | ||
| 1347 | + } | ||
| 1348 | + self.bitrate = v.min(750000 * self.channels as i32); | ||
| 1349 | + } | ||
| 1350 | + /// `CELT_SET_PREDICTION`. | ||
| 1351 | + pub(crate) fn set_prediction(&mut self, v: i32) { | ||
| 1352 | + if !(0..=2).contains(&v) { | ||
| 1353 | + return; | ||
| 1354 | + } | ||
| 1355 | + self.disable_pf = v <= 1; | ||
| 1356 | + self.force_intra = v == 0; | ||
| 1357 | + } | ||
| 1358 | + /// `OPUS_SET_COMPLEXITY`. | ||
| 1359 | + pub(crate) fn set_complexity(&mut self, v: i32) { | ||
| 1360 | + if (0..=10).contains(&v) { | ||
| 1361 | + self.complexity = v; | ||
| 1362 | + } | ||
| 1363 | + } | ||
| 1364 | + /// `OPUS_SET_PACKET_LOSS_PERC`. | ||
| 1365 | + pub(crate) fn set_loss_rate(&mut self, v: i32) { | ||
| 1366 | + if (0..=100).contains(&v) { | ||
| 1367 | + self.loss_rate = v; | ||
| 1368 | + } | ||
| 1369 | + } | ||
| 1370 | + /// `OPUS_SET_LSB_DEPTH`. | ||
| 1371 | + pub(crate) fn set_lsb_depth(&mut self, v: i32) { | ||
| 1372 | + if (8..=24).contains(&v) { | ||
| 1373 | + self.lsb_depth = v; | ||
| 1374 | + } | ||
| 1375 | + } | ||
| 1376 | + /// `CELT_SET_ANALYSIS`. | ||
| 1377 | + pub(crate) fn set_analysis(&mut self, v: &AnalysisInfo) { | ||
| 1378 | + self.analysis = *v; | ||
| 1379 | + } | ||
| 1380 | + /// `CELT_SET_SILK_INFO`. | ||
| 1381 | + pub(crate) fn set_silk_info(&mut self, signal_type: i32, offset: i32) { | ||
| 1382 | + self.silk_signal_type = signal_type; | ||
| 1383 | + self.silk_offset = offset; | ||
| 1384 | + } | ||
| 1385 | + /// `OPUS_GET_FINAL_RANGE`. | ||
| 1386 | + pub(crate) fn final_range(&self) -> u32 { | ||
| 1387 | + self.rng | ||
| 1388 | + } | ||
| 1389 | +} | ||
crates/ec-opus/src/celt_flp/enc_an.rsadded+843 -0
| @@ -0,0 +1,843 @@ | |||
| 1 | +use super::{EPSILON, MAX_LM, OVERLAP, PI, celt_exp2, celt_log2}; | ||
| 2 | +use crate::analysis::{AnalysisInfo, LEAK_BANDS}; | ||
| 3 | +use crate::celt::{BITRES, E_BANDS, E_MEANS, LOG_N, NB_BANDS, TF_SELECT}; | ||
| 4 | +use crate::range::RangeEncoder; | ||
| 5 | + | ||
| 6 | +const MAX_FRAME: usize = 960; | ||
| 7 | +const ANALYSIS_MAX_LEN: usize = MAX_FRAME + OVERLAP; | ||
| 8 | +const TF_TMP_MAX: usize = 100 << MAX_LM; | ||
| 9 | + | ||
| 10 | +fn min_f(a: f32, b: f32) -> f32 { | ||
| 11 | + if a < b { a } else { b } | ||
| 12 | +} | ||
| 13 | + | ||
| 14 | +fn max_f(a: f32, b: f32) -> f32 { | ||
| 15 | + if a > b { a } else { b } | ||
| 16 | +} | ||
| 17 | + | ||
| 18 | +fn inner_prod(x: &[f32], y: &[f32]) -> f32 { | ||
| 19 | + let mut xy = 0f32; | ||
| 20 | + for i in 0..x.len() { | ||
| 21 | + xy += x[i] * y[i]; | ||
| 22 | + } | ||
| 23 | + xy | ||
| 24 | +} | ||
| 25 | + | ||
| 26 | +fn haar1(x: &mut [f32], n0: usize, stride: usize) { | ||
| 27 | + let n0 = n0 >> 1; | ||
| 28 | + for i in 0..stride { | ||
| 29 | + for j in 0..n0 { | ||
| 30 | + let tmp1 = 0.70710678f32 * x[stride * 2 * j + i]; | ||
| 31 | + let tmp2 = 0.70710678f32 * x[stride * (2 * j + 1) + i]; | ||
| 32 | + x[stride * 2 * j + i] = tmp1 + tmp2; | ||
| 33 | + x[stride * (2 * j + 1) + i] = tmp1 - tmp2; | ||
| 34 | + } | ||
| 35 | + } | ||
| 36 | +} | ||
| 37 | + | ||
| 38 | +const INV_TABLE: [u8; 128] = [ | ||
| 39 | + 255, 255, 156, 110, 86, 70, 59, 51, 45, 40, 37, 33, 31, 28, 26, 25, 23, 22, 21, 20, 19, 18, 17, | ||
| 40 | + 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, | ||
| 41 | + 8, 8, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, | ||
| 42 | + 5, 5, 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, 3, 3, 3, | ||
| 43 | + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, | ||
| 44 | +]; | ||
| 45 | + | ||
| 46 | +/// `transient_analysis`; `input` is C `in` (`c * len`), returns `is_transient`. | ||
| 47 | +pub(crate) fn transient_analysis( | ||
| 48 | + input: &[f32], | ||
| 49 | + len: usize, | ||
| 50 | + c: usize, | ||
| 51 | + tf_estimate: &mut f32, | ||
| 52 | + tf_chan: &mut usize, | ||
| 53 | + allow_weak_transients: bool, | ||
| 54 | + weak_transient: &mut bool, | ||
| 55 | + tone_freq: f32, | ||
| 56 | + toneishness: f32, | ||
| 57 | +) -> bool { | ||
| 58 | + let forward_decay: f32 = if allow_weak_transients { | ||
| 59 | + 0.03125 | ||
| 60 | + } else { | ||
| 61 | + 0.0625 | ||
| 62 | + }; | ||
| 63 | + let len2 = len / 2; | ||
| 64 | + let mut tmp_buf = [0f32; ANALYSIS_MAX_LEN]; | ||
| 65 | + let tmp = &mut tmp_buf[..len]; | ||
| 66 | + let mut mask_metric: i32 = 0; | ||
| 67 | + *weak_transient = false; | ||
| 68 | + for ch in 0..c { | ||
| 69 | + let mut mem0: f32 = 0.0; | ||
| 70 | + let mut mem1: f32 = 0.0; | ||
| 71 | + for i in 0..len { | ||
| 72 | + let x = input[i + ch * len]; | ||
| 73 | + let y = mem0 + x; | ||
| 74 | + let mem00 = mem0; | ||
| 75 | + mem0 = mem0 - x + 0.5f32 * mem1; | ||
| 76 | + mem1 = x - mem00; | ||
| 77 | + tmp[i] = y; | ||
| 78 | + } | ||
| 79 | + for v in tmp.iter_mut().take(12) { | ||
| 80 | + *v = 0.0; | ||
| 81 | + } | ||
| 82 | + let mut mean: f32 = 0.0; | ||
| 83 | + mem0 = 0.0; | ||
| 84 | + for i in 0..len2 { | ||
| 85 | + let x2 = tmp[2 * i] * tmp[2 * i] + tmp[2 * i + 1] * tmp[2 * i + 1]; | ||
| 86 | + mean += x2; | ||
| 87 | + mem0 = x2 + (1.0f32 - forward_decay) * mem0; | ||
| 88 | + tmp[i] = forward_decay * mem0; | ||
| 89 | + } | ||
| 90 | + mem0 = 0.0; | ||
| 91 | + let mut max_e: f32 = 0.0; | ||
| 92 | + for i in (0..len2).rev() { | ||
| 93 | + mem0 = tmp[i] + 0.875f32 * mem0; | ||
| 94 | + tmp[i] = 0.125f32 * mem0; | ||
| 95 | + max_e = max_f(max_e, 0.125f32 * mem0); | ||
| 96 | + } | ||
| 97 | + let arg: f64 = ((mean * max_e) as f64 * 0.5) * len2 as f64; | ||
| 98 | + mean = arg.sqrt() as f32; | ||
| 99 | + let norm: f32 = len2 as f32 / (EPSILON + mean); | ||
| 100 | + let mut unmask: i32 = 0; | ||
| 101 | + let mut i = 12usize; | ||
| 102 | + while i + 5 < len2 { | ||
| 103 | + let v = ((64.0f32 * norm) * (tmp[i] + EPSILON)).floor(); | ||
| 104 | + let id = max_f(0.0, min_f(127.0, v)) as usize; | ||
| 105 | + unmask += INV_TABLE[id] as i32; | ||
| 106 | + i += 4; | ||
| 107 | + } | ||
| 108 | + unmask = (64 * unmask * 4) | ||
| 109 | + .checked_div(6 * (len2 as i32 - 17)) | ||
| 110 | + .unwrap_or(0); | ||
| 111 | + if unmask > mask_metric { | ||
| 112 | + *tf_chan = ch; | ||
| 113 | + mask_metric = unmask; | ||
| 114 | + } | ||
| 115 | + } | ||
| 116 | + let mut is_transient = mask_metric > 200; | ||
| 117 | + if toneishness > 0.98f32 && tone_freq < 0.026f32 { | ||
| 118 | + is_transient = false; | ||
| 119 | + mask_metric = 0; | ||
| 120 | + } | ||
| 121 | + if allow_weak_transients && is_transient && mask_metric < 600 { | ||
| 122 | + is_transient = false; | ||
| 123 | + *weak_transient = true; | ||
| 124 | + } | ||
| 125 | + let tf_max = max_f( | ||
| 126 | + 0.0, | ||
| 127 | + ((27i32.wrapping_mul(mask_metric)) as f64).sqrt() as f32 - 42.0, | ||
| 128 | + ); | ||
| 129 | + let p = 0.0069f64 as f32 * min_f(163.0, tf_max); | ||
| 130 | + let d = p as f64 - 0.139; | ||
| 131 | + let d = if 0.0 > d { 0.0 } else { d }; | ||
| 132 | + *tf_estimate = d.sqrt() as f32; | ||
| 133 | + is_transient | ||
| 134 | +} | ||
| 135 | + | ||
| 136 | +/// `patch_transient_decision`. | ||
| 137 | +pub(crate) fn patch_transient_decision( | ||
| 138 | + new_e: &[f32], | ||
| 139 | + old_e: &[f32], | ||
| 140 | + start: usize, | ||
| 141 | + end: usize, | ||
| 142 | + c: usize, | ||
| 143 | +) -> bool { | ||
| 144 | + let nb = NB_BANDS; | ||
| 145 | + let mut spread_old = [0f32; 26]; | ||
| 146 | + if c == 1 { | ||
| 147 | + spread_old[start] = old_e[start]; | ||
| 148 | + for i in start + 1..end { | ||
| 149 | + spread_old[i] = max_f(spread_old[i - 1] - 1.0, old_e[i]); | ||
| 150 | + } | ||
| 151 | + } else { | ||
| 152 | + spread_old[start] = max_f(old_e[start], old_e[start + nb]); | ||
| 153 | + for i in start + 1..end { | ||
| 154 | + spread_old[i] = max_f(spread_old[i - 1] - 1.0, max_f(old_e[i], old_e[i + nb])); | ||
| 155 | + } | ||
| 156 | + } | ||
| 157 | + let mut i = end as i32 - 2; | ||
| 158 | + while i >= start as i32 { | ||
| 159 | + let iu = i as usize; | ||
| 160 | + spread_old[iu] = max_f(spread_old[iu], spread_old[iu + 1] - 1.0); | ||
| 161 | + i -= 1; | ||
| 162 | + } | ||
| 163 | + let mut mean_diff: f32 = 0.0; | ||
| 164 | + for ch in 0..c { | ||
| 165 | + for i in start.max(2)..end.saturating_sub(1) { | ||
| 166 | + let x1 = max_f(0.0, new_e[i + ch * nb]); | ||
| 167 | + let x2 = max_f(0.0, spread_old[i]); | ||
| 168 | + mean_diff += max_f(0.0, x1 - x2); | ||
| 169 | + } | ||
| 170 | + } | ||
| 171 | + let den = c as i32 * (end as i32 - 1 - start.max(2) as i32); | ||
| 172 | + mean_diff /= den as f32; | ||
| 173 | + mean_diff > 1.0 | ||
| 174 | +} | ||
| 175 | + | ||
| 176 | +fn l1_metric(tmp: &[f32], n: usize, lm: i32, bias: f32) -> f32 { | ||
| 177 | + let mut l1 = 0f32; | ||
| 178 | + for i in 0..n { | ||
| 179 | + l1 += tmp[i].abs(); | ||
| 180 | + } | ||
| 181 | + l1 + (lm as f32 * bias) * l1 | ||
| 182 | +} | ||
| 183 | + | ||
| 184 | +/// `tf_analysis`; returns `tf_select`. | ||
| 185 | +pub(crate) fn tf_analysis( | ||
| 186 | + len: usize, | ||
| 187 | + is_transient: bool, | ||
| 188 | + tf_res: &mut [i32], | ||
| 189 | + lambda: i32, | ||
| 190 | + x: &[f32], | ||
| 191 | + n0: usize, | ||
| 192 | + lm: usize, | ||
| 193 | + tf_estimate: f32, | ||
| 194 | + tf_chan: usize, | ||
| 195 | + importance: &[i32], | ||
| 196 | +) -> i32 { | ||
| 197 | + let is_t = is_transient as usize; | ||
| 198 | + let bias = 0.04f32 * max_f(-0.25f32, 0.5f32 - tf_estimate); | ||
| 199 | + let tmp_len = (E_BANDS[len] - E_BANDS[len - 1]) << lm; | ||
| 200 | + let mut metric_buf = [0i32; NB_BANDS]; | ||
| 201 | + let mut tmp_buf = [0f32; TF_TMP_MAX]; | ||
| 202 | + let mut tmp_1_buf = [0f32; TF_TMP_MAX]; | ||
| 203 | + let mut path0_buf = [0i32; NB_BANDS]; | ||
| 204 | + let mut path1_buf = [0i32; NB_BANDS]; | ||
| 205 | + let metric = &mut metric_buf[..len]; | ||
| 206 | + let tmp = &mut tmp_buf[..tmp_len]; | ||
| 207 | + let tmp_1 = &mut tmp_1_buf[..tmp_len]; | ||
| 208 | + let path0 = &mut path0_buf[..len]; | ||
| 209 | + let path1 = &mut path1_buf[..len]; | ||
| 210 | + for i in 0..len { | ||
| 211 | + let width = E_BANDS[i + 1] - E_BANDS[i]; | ||
| 212 | + let n = width << lm; | ||
| 213 | + let narrow = width == 1; | ||
| 214 | + let base = tf_chan * n0 + (E_BANDS[i] << lm); | ||
| 215 | + tmp[..n].copy_from_slice(&x[base..base + n]); | ||
| 216 | + let mut l1 = l1_metric(&tmp[..n], n, if is_transient { lm as i32 } else { 0 }, bias); | ||
| 217 | + let mut best_l1 = l1; | ||
| 218 | + let mut best_level: i32 = 0; | ||
| 219 | + if is_transient && !narrow { | ||
| 220 | + tmp_1[..n].copy_from_slice(&tmp[..n]); | ||
| 221 | + haar1(&mut tmp_1[..n], n >> lm, 1 << lm); | ||
| 222 | + l1 = l1_metric(&tmp_1[..n], n, lm as i32 + 1, bias); | ||
| 223 | + if l1 < best_l1 { | ||
| 224 | + best_l1 = l1; | ||
| 225 | + best_level = -1; | ||
| 226 | + } | ||
| 227 | + } | ||
| 228 | + let kmax = lm + !(is_transient || narrow) as usize; | ||
| 229 | + for k in 0..kmax { | ||
| 230 | + let b = if is_transient { lm - k - 1 } else { k + 1 }; | ||
| 231 | + haar1(&mut tmp[..n], n >> k, 1 << k); | ||
| 232 | + l1 = l1_metric(&tmp[..n], n, b as i32, bias); | ||
| 233 | + if l1 < best_l1 { | ||
| 234 | + best_l1 = l1; | ||
| 235 | + best_level = k as i32 + 1; | ||
| 236 | + } | ||
| 237 | + } | ||
| 238 | + metric[i] = if is_transient { | ||
| 239 | + 2 * best_level | ||
| 240 | + } else { | ||
| 241 | + -2 * best_level | ||
| 242 | + }; | ||
| 243 | + if narrow && (metric[i] == 0 || metric[i] == -2 * lm as i32) { | ||
| 244 | + metric[i] -= 1; | ||
| 245 | + } | ||
| 246 | + } | ||
| 247 | + let tbl = |idx: usize| TF_SELECT[lm][idx]; | ||
| 248 | + let mut selcost = [0i32; 2]; | ||
| 249 | + for sel in 0..2 { | ||
| 250 | + let s0 = 4 * is_t + 2 * sel; | ||
| 251 | + let s1 = s0 + 1; | ||
| 252 | + let mut cost0 = importance[0] * (metric[0] - 2 * tbl(s0)).abs(); | ||
| 253 | + let mut cost1 = | ||
| 254 | + importance[0] * (metric[0] - 2 * tbl(s1)).abs() + if is_transient { 0 } else { lambda }; | ||
| 255 | + for i in 1..len { | ||
| 256 | + let curr0 = min_i(cost0, cost1 + lambda); | ||
| 257 | + let curr1 = min_i(cost0 + lambda, cost1); | ||
| 258 | + cost0 = curr0 + importance[i] * (metric[i] - 2 * tbl(s0)).abs(); | ||
| 259 | + cost1 = curr1 + importance[i] * (metric[i] - 2 * tbl(s1)).abs(); | ||
| 260 | + } | ||
| 261 | + selcost[sel] = min_i(cost0, cost1); | ||
| 262 | + } | ||
| 263 | + let mut tf_select = 0i32; | ||
| 264 | + if selcost[1] < selcost[0] && is_transient { | ||
| 265 | + tf_select = 1; | ||
| 266 | + } | ||
| 267 | + let s0 = 4 * is_t + 2 * tf_select as usize; | ||
| 268 | + let s1 = s0 + 1; | ||
| 269 | + let mut cost0 = importance[0] * (metric[0] - 2 * tbl(s0)).abs(); | ||
| 270 | + let mut cost1 = | ||
| 271 | + importance[0] * (metric[0] - 2 * tbl(s1)).abs() + if is_transient { 0 } else { lambda }; | ||
| 272 | + for i in 1..len { | ||
| 273 | + let from0 = cost0; | ||
| 274 | + let from1 = cost1 + lambda; | ||
| 275 | + let (curr0, p0) = if from0 < from1 { | ||
| 276 | + (from0, 0) | ||
| 277 | + } else { | ||
| 278 | + (from1, 1) | ||
| 279 | + }; | ||
| 280 | + let from0 = cost0 + lambda; | ||
| 281 | + let from1 = cost1; | ||
| 282 | + let (curr1, p1) = if from0 < from1 { | ||
| 283 | + (from0, 0) | ||
| 284 | + } else { | ||
| 285 | + (from1, 1) | ||
| 286 | + }; | ||
| 287 | + path0[i] = p0; | ||
| 288 | + path1[i] = p1; | ||
| 289 | + cost0 = curr0 + importance[i] * (metric[i] - 2 * tbl(s0)).abs(); | ||
| 290 | + cost1 = curr1 + importance[i] * (metric[i] - 2 * tbl(s1)).abs(); | ||
| 291 | + } | ||
| 292 | + tf_res[len - 1] = if cost0 < cost1 { 0 } else { 1 }; | ||
| 293 | + for i in (0..len - 1).rev() { | ||
| 294 | + tf_res[i] = if tf_res[i + 1] == 1 { | ||
| 295 | + path1[i + 1] | ||
| 296 | + } else { | ||
| 297 | + path0[i + 1] | ||
| 298 | + }; | ||
| 299 | + } | ||
| 300 | + tf_select | ||
| 301 | +} | ||
| 302 | + | ||
| 303 | +fn min_i(a: i32, b: i32) -> i32 { | ||
| 304 | + if a < b { a } else { b } | ||
| 305 | +} | ||
| 306 | + | ||
| 307 | +/// `tf_encode`. | ||
| 308 | +pub(crate) fn tf_encode( | ||
| 309 | + start: usize, | ||
| 310 | + end: usize, | ||
| 311 | + is_transient: bool, | ||
| 312 | + tf_res: &mut [i32], | ||
| 313 | + lm: usize, | ||
| 314 | + tf_select: i32, | ||
| 315 | + enc: &mut RangeEncoder, | ||
| 316 | +) { | ||
| 317 | + let is_t = is_transient as usize; | ||
| 318 | + let mut budget = enc.storage() as u32 * 8; | ||
| 319 | + let mut tell = enc.tell(); | ||
| 320 | + let mut logp: u32 = if is_transient { 2 } else { 4 }; | ||
| 321 | + let tf_select_rsv = (lm > 0 && tell + logp < budget) as u32; | ||
| 322 | + budget = budget.wrapping_sub(tf_select_rsv); | ||
| 323 | + let mut curr = 0i32; | ||
| 324 | + let mut tf_changed = 0i32; | ||
| 325 | + for i in start..end { | ||
| 326 | + if tell + logp <= budget { | ||
| 327 | + enc.enc_bit_logp((tf_res[i] ^ curr) != 0, logp); | ||
| 328 | + tell = enc.tell(); | ||
| 329 | + curr = tf_res[i]; | ||
| 330 | + tf_changed |= curr; | ||
| 331 | + } else { | ||
| 332 | + tf_res[i] = curr; | ||
| 333 | + } | ||
| 334 | + logp = if is_transient { 4 } else { 5 }; | ||
| 335 | + } | ||
| 336 | + let mut tf_select = tf_select; | ||
| 337 | + if tf_select_rsv != 0 | ||
| 338 | + && TF_SELECT[lm][4 * is_t + tf_changed as usize] | ||
| 339 | + != TF_SELECT[lm][4 * is_t + 2 + tf_changed as usize] | ||
| 340 | + { | ||
| 341 | + enc.enc_bit_logp(tf_select != 0, 1); | ||
| 342 | + } else { | ||
| 343 | + tf_select = 0; | ||
| 344 | + } | ||
| 345 | + for i in start..end { | ||
| 346 | + tf_res[i] = TF_SELECT[lm][4 * is_t + 2 * tf_select as usize + tf_res[i] as usize]; | ||
| 347 | + } | ||
| 348 | +} | ||
| 349 | + | ||
| 350 | +/// `alloc_trim_analysis`. | ||
| 351 | +pub(crate) fn alloc_trim_analysis( | ||
| 352 | + x: &[f32], | ||
| 353 | + band_log_e: &[f32], | ||
| 354 | + end: usize, | ||
| 355 | + lm: usize, | ||
| 356 | + c: usize, | ||
| 357 | + n0: usize, | ||
| 358 | + analysis: &AnalysisInfo, | ||
| 359 | + stereo_saving: &mut f32, | ||
| 360 | + tf_estimate: f32, | ||
| 361 | + intensity: usize, | ||
| 362 | + surround_trim: f32, | ||
| 363 | + equiv_rate: i32, | ||
| 364 | +) -> i32 { | ||
| 365 | + let mut trim: f32 = 5.0; | ||
| 366 | + if equiv_rate < 64000 { | ||
| 367 | + trim = 4.0; | ||
| 368 | + } else if equiv_rate < 80000 { | ||
| 369 | + let frac = (equiv_rate - 64000) >> 10; | ||
| 370 | + trim = 4.0 + (1.0f32 / 16.0f32) * frac as f32; | ||
| 371 | + } | ||
| 372 | + if c == 2 { | ||
| 373 | + let mut sum: f32 = 0.0; | ||
| 374 | + for i in 0..8 { | ||
| 375 | + let lo = E_BANDS[i] << lm; | ||
| 376 | + let n = (E_BANDS[i + 1] - E_BANDS[i]) << lm; | ||
| 377 | + let partial = inner_prod(&x[lo..lo + n], &x[n0 + lo..n0 + lo + n]); | ||
| 378 | + sum += partial; | ||
| 379 | + } | ||
| 380 | + sum *= 0.125f32; | ||
| 381 | + sum = min_f(1.0, sum.abs()); | ||
| 382 | + let mut min_xc = sum; | ||
| 383 | + for i in 8..intensity { | ||
| 384 | + let lo = E_BANDS[i] << lm; | ||
| 385 | + let n = (E_BANDS[i + 1] - E_BANDS[i]) << lm; | ||
| 386 | + let partial = inner_prod(&x[lo..lo + n], &x[n0 + lo..n0 + lo + n]); | ||
| 387 | + min_xc = min_f(min_xc, partial.abs()); | ||
| 388 | + } | ||
| 389 | + min_xc = min_f(1.0, min_xc.abs()); | ||
| 390 | + let log_xc = celt_log2(1.001f32 - sum * sum); | ||
| 391 | + let log_xc2 = max_f(0.5f32 * log_xc, celt_log2(1.001f32 - min_xc * min_xc)); | ||
| 392 | + trim += max_f(-4.0, 0.75f32 * log_xc); | ||
| 393 | + *stereo_saving = min_f(*stereo_saving + 0.25, -(0.5f32 * log_xc2)); | ||
| 394 | + } | ||
| 395 | + let mut diff: f32 = 0.0; | ||
| 396 | + for ch in 0..c { | ||
| 397 | + for i in 0..end - 1 { | ||
| 398 | + diff += band_log_e[i + ch * NB_BANDS] * (2 + 2 * i as i32 - end as i32) as f32; | ||
| 399 | + } | ||
| 400 | + } | ||
| 401 | + diff /= (c as i32 * (end as i32 - 1)) as f32; | ||
| 402 | + let t = (diff + 1.0) / 6.0; | ||
| 403 | + trim -= max_f(-2.0, min_f(2.0, t)); | ||
| 404 | + trim -= surround_trim; | ||
| 405 | + trim -= 2.0 * tf_estimate; | ||
| 406 | + if analysis.valid { | ||
| 407 | + trim -= max_f( | ||
| 408 | + -2.0, | ||
| 409 | + min_f(2.0, 2.0f32 * (analysis.tonality_slope + 0.05f32)), | ||
| 410 | + ); | ||
| 411 | + } | ||
| 412 | + let trim_index = ((0.5f32 + trim) as f64).floor() as i32; | ||
| 413 | + trim_index.clamp(0, 10) | ||
| 414 | +} | ||
| 415 | + | ||
| 416 | +/// `stereo_analysis`; returns `dual_stereo`. | ||
| 417 | +pub(crate) fn stereo_analysis(x: &[f32], lm: usize, n0: usize) -> bool { | ||
| 418 | + let mut sum_lr = EPSILON; | ||
| 419 | + let mut sum_ms = EPSILON; | ||
| 420 | + for i in 0..13 { | ||
| 421 | + for j in (E_BANDS[i] << lm)..(E_BANDS[i + 1] << lm) { | ||
| 422 | + let l = x[j]; | ||
| 423 | + let r = x[n0 + j]; | ||
| 424 | + let m = l + r; | ||
| 425 | + let s = l - r; | ||
| 426 | + sum_lr += l.abs() + r.abs(); | ||
| 427 | + sum_ms += m.abs() + s.abs(); | ||
| 428 | + } | ||
| 429 | + } | ||
| 430 | + sum_ms *= 0.707107f32; | ||
| 431 | + let mut thetas: i32 = 13; | ||
| 432 | + if lm <= 1 { | ||
| 433 | + thetas -= 8; | ||
| 434 | + } | ||
| 435 | + let lhs = ((E_BANDS[13] << (lm + 1)) as i32 + thetas) as f32 * sum_ms; | ||
| 436 | + let rhs = (E_BANDS[13] << (lm + 1)) as f32 * sum_lr; | ||
| 437 | + lhs > rhs | ||
| 438 | +} | ||
| 439 | + | ||
| 440 | +fn median_of_5(x: &[f32]) -> f32 { | ||
| 441 | + let t2 = x[2]; | ||
| 442 | + let (mut t0, mut t1) = if x[0] > x[1] { | ||
| 443 | + (x[1], x[0]) | ||
| 444 | + } else { | ||
| 445 | + (x[0], x[1]) | ||
| 446 | + }; | ||
| 447 | + let (mut t3, mut t4) = if x[3] > x[4] { | ||
| 448 | + (x[4], x[3]) | ||
| 449 | + } else { | ||
| 450 | + (x[3], x[4]) | ||
| 451 | + }; | ||
| 452 | + if t0 > t3 { | ||
| 453 | + std::mem::swap(&mut t0, &mut t3); | ||
| 454 | + std::mem::swap(&mut t1, &mut t4); | ||
| 455 | + } | ||
| 456 | + if t2 > t1 { | ||
| 457 | + if t1 < t3 { | ||
| 458 | + min_f(t2, t3) | ||
| 459 | + } else { | ||
| 460 | + min_f(t4, t1) | ||
| 461 | + } | ||
| 462 | + } else if t2 < t3 { | ||
| 463 | + min_f(t1, t3) | ||
| 464 | + } else { | ||
| 465 | + min_f(t2, t4) | ||
| 466 | + } | ||
| 467 | +} | ||
| 468 | + | ||
| 469 | +fn median_of_3(x: &[f32]) -> f32 { | ||
| 470 | + let (t0, t1) = if x[0] > x[1] { | ||
| 471 | + (x[1], x[0]) | ||
| 472 | + } else { | ||
| 473 | + (x[0], x[1]) | ||
| 474 | + }; | ||
| 475 | + let t2 = x[2]; | ||
| 476 | + if t1 < t2 { | ||
| 477 | + t1 | ||
| 478 | + } else if t0 < t2 { | ||
| 479 | + t2 | ||
| 480 | + } else { | ||
| 481 | + t0 | ||
| 482 | + } | ||
| 483 | +} | ||
| 484 | + | ||
| 485 | +/// `dynalloc_analysis` (no QEXT); returns `maxDepth`. | ||
| 486 | +pub(crate) fn dynalloc_analysis( | ||
| 487 | + band_log_e: &[f32], | ||
| 488 | + band_log_e2: &[f32], | ||
| 489 | + old_band_e: &[f32], | ||
| 490 | + start: usize, | ||
| 491 | + end: usize, | ||
| 492 | + c: usize, | ||
| 493 | + offsets: &mut [i32], | ||
| 494 | + lsb_depth: i32, | ||
| 495 | + is_transient: bool, | ||
| 496 | + vbr: bool, | ||
| 497 | + constrained_vbr: bool, | ||
| 498 | + lm: usize, | ||
| 499 | + effective_bytes: i32, | ||
| 500 | + tot_boost: &mut i32, | ||
| 501 | + lfe: bool, | ||
| 502 | + surround_dynalloc: &[f32], | ||
| 503 | + analysis: &AnalysisInfo, | ||
| 504 | + importance: &mut [i32], | ||
| 505 | + spread_weight: &mut [i32], | ||
| 506 | + tone_freq: f32, | ||
| 507 | + toneishness: f32, | ||
| 508 | +) -> f32 { | ||
| 509 | + let nb = NB_BANDS; | ||
| 510 | + let mut tb: i32 = 0; | ||
| 511 | + let mut max_depth: f32 = -31.9; | ||
| 512 | + let mut follower = [0f32; 2 * NB_BANDS]; | ||
| 513 | + let mut noise_floor = [0f32; NB_BANDS]; | ||
| 514 | + let mut band_log_e3 = [0f32; NB_BANDS]; | ||
| 515 | + for v in offsets.iter_mut().take(nb) { | ||
| 516 | + *v = 0; | ||
| 517 | + } | ||
| 518 | + for i in 0..end { | ||
| 519 | + noise_floor[i] = 0.0625f32 * LOG_N[i] as f32 + 0.5 + (9 - lsb_depth) as f32 - E_MEANS[i] | ||
| 520 | + + 0.0062f32 * (i + 5) as f32 * (i + 5) as f32; | ||
| 521 | + } | ||
| 522 | + for ch in 0..c { | ||
| 523 | + for i in 0..end { | ||
| 524 | + max_depth = max_f(max_depth, band_log_e[ch * nb + i] - noise_floor[i]); | ||
| 525 | + } | ||
| 526 | + } | ||
| 527 | + let mut mask = [0f32; NB_BANDS]; | ||
| 528 | + let mut sig = [0f32; NB_BANDS]; | ||
| 529 | + for i in 0..end { | ||
| 530 | + mask[i] = band_log_e[i] - noise_floor[i]; | ||
| 531 | + } | ||
| 532 | + if c == 2 { | ||
| 533 | + for i in 0..end { | ||
| 534 | + mask[i] = max_f(mask[i], band_log_e[nb + i] - noise_floor[i]); | ||
| 535 | + } | ||
| 536 | + } | ||
| 537 | + sig[..end].copy_from_slice(&mask[..end]); | ||
| 538 | + for i in 1..end { | ||
| 539 | + mask[i] = max_f(mask[i], mask[i - 1] - 2.0); | ||
| 540 | + } | ||
| 541 | + for i in (0..end.saturating_sub(1)).rev() { | ||
| 542 | + mask[i] = max_f(mask[i], mask[i + 1] - 3.0); | ||
| 543 | + } | ||
| 544 | + for i in 0..end { | ||
| 545 | + let smr = sig[i] - max_f(max_f(0.0, max_depth - 12.0), mask[i]); | ||
| 546 | + let fl = ((0.5f32 + smr) as f64).floor() as i32; | ||
| 547 | + let shift = 5.min(0.max(fl.wrapping_neg())); | ||
| 548 | + spread_weight[i] = 32 >> shift; | ||
| 549 | + } | ||
| 550 | + if effective_bytes >= 30 + 5 * lm as i32 && !lfe { | ||
| 551 | + let mut last = 0usize; | ||
| 552 | + for ch in 0..c { | ||
| 553 | + band_log_e3[..end].copy_from_slice(&band_log_e2[ch * nb..ch * nb + end]); | ||
| 554 | + if lm == 0 { | ||
| 555 | + for i in 0..end.min(8) { | ||
| 556 | + band_log_e3[i] = max_f(band_log_e2[ch * nb + i], old_band_e[ch * nb + i]); | ||
| 557 | + } | ||
| 558 | + } | ||
| 559 | + let fb = ch * nb; | ||
| 560 | + follower[fb] = band_log_e3[0]; | ||
| 561 | + for i in 1..end { | ||
| 562 | + if band_log_e3[i] > band_log_e3[i - 1] + 0.5 { | ||
| 563 | + last = i; | ||
| 564 | + } | ||
| 565 | + follower[fb + i] = min_f(follower[fb + i - 1] + 1.5, band_log_e3[i]); | ||
| 566 | + } | ||
| 567 | + for i in (0..last).rev() { | ||
| 568 | + follower[fb + i] = min_f( | ||
| 569 | + follower[fb + i], | ||
| 570 | + min_f(follower[fb + i + 1] + 2.0, band_log_e3[i]), | ||
| 571 | + ); | ||
| 572 | + } | ||
| 573 | + let offset = 1.0f32; | ||
| 574 | + for i in 2..end.saturating_sub(2) { | ||
| 575 | + follower[fb + i] = max_f( | ||
| 576 | + follower[fb + i], | ||
| 577 | + median_of_5(&band_log_e3[i - 2..]) - offset, | ||
| 578 | + ); | ||
| 579 | + } | ||
| 580 | + let tmp = median_of_3(&band_log_e3[..]) - offset; | ||
| 581 | + follower[fb] = max_f(follower[fb], tmp); | ||
| 582 | + follower[fb + 1] = max_f(follower[fb + 1], tmp); | ||
| 583 | + let tmp = median_of_3(&band_log_e3[end - 3..]) - offset; | ||
| 584 | + follower[fb + end - 2] = max_f(follower[fb + end - 2], tmp); | ||
| 585 | + follower[fb + end - 1] = max_f(follower[fb + end - 1], tmp); | ||
| 586 | + for i in 0..end { | ||
| 587 | + follower[fb + i] = max_f(follower[fb + i], noise_floor[i]); | ||
| 588 | + } | ||
| 589 | + } | ||
| 590 | + if c == 2 { | ||
| 591 | + for i in start..end { | ||
| 592 | + follower[nb + i] = max_f(follower[nb + i], follower[i] - 4.0); | ||
| 593 | + follower[i] = max_f(follower[i], follower[nb + i] - 4.0); | ||
| 594 | + follower[i] = 0.5f32 | ||
| 595 | + * (max_f(0.0, band_log_e[i] - follower[i]) | ||
| 596 | + + max_f(0.0, band_log_e[nb + i] - follower[nb + i])); | ||
| 597 | + } | ||
| 598 | + } else { | ||
| 599 | + for i in start..end { | ||
| 600 | + follower[i] = max_f(0.0, band_log_e[i] - follower[i]); | ||
| 601 | + } | ||
| 602 | + } | ||
| 603 | + for i in start..end { | ||
| 604 | + follower[i] = max_f(follower[i], surround_dynalloc[i]); | ||
| 605 | + } | ||
| 606 | + for i in start..end { | ||
| 607 | + importance[i] = | ||
| 608 | + ((0.5f32 + 13.0f32 * celt_exp2(min_f(follower[i], 4.0))) as f64).floor() as i32; | ||
| 609 | + } | ||
| 610 | + if (!vbr || constrained_vbr) && !is_transient { | ||
| 611 | + for i in start..end { | ||
| 612 | + follower[i] *= 0.5f32; | ||
| 613 | + } | ||
| 614 | + } | ||
| 615 | + for i in start..end { | ||
| 616 | + if i < 8 { | ||
| 617 | + follower[i] *= 2.0; | ||
| 618 | + } | ||
| 619 | + if i >= 12 { | ||
| 620 | + follower[i] *= 0.5f32; | ||
| 621 | + } | ||
| 622 | + } | ||
| 623 | + if toneishness > 0.98f32 { | ||
| 624 | + let freq_bin = (0.5f64 + ((tone_freq * 120.0f32) as f64) / PI).floor() as i32; | ||
| 625 | + for i in start..end { | ||
| 626 | + let lo = E_BANDS[i] as i32; | ||
| 627 | + let hi = E_BANDS[i + 1] as i32; | ||
| 628 | + if freq_bin >= lo && freq_bin <= hi { | ||
| 629 | + follower[i] += 2.0; | ||
| 630 | + } | ||
| 631 | + if freq_bin >= lo - 1 && freq_bin <= hi + 1 { | ||
| 632 | + follower[i] += 1.0; | ||
| 633 | + } | ||
| 634 | + if freq_bin >= lo - 2 && freq_bin <= hi + 2 { | ||
| 635 | + follower[i] += 1.0; | ||
| 636 | + } | ||
| 637 | + if freq_bin >= lo - 3 && freq_bin <= hi + 3 { | ||
| 638 | + follower[i] += 0.5; | ||
| 639 | + } | ||
| 640 | + } | ||
| 641 | + if freq_bin >= E_BANDS[end] as i32 { | ||
| 642 | + follower[end - 1] += 2.0; | ||
| 643 | + follower[end - 2] += 1.0; | ||
| 644 | + } | ||
| 645 | + } | ||
| 646 | + if analysis.valid { | ||
| 647 | + for i in start..end.min(LEAK_BANDS) { | ||
| 648 | + follower[i] += (1.0f32 / 64.0f32) * analysis.leak_boost[i] as f32; | ||
| 649 | + } | ||
| 650 | + } | ||
| 651 | + if effective_bytes > 320 { | ||
| 652 | + follower[0] += min_f(1.5, 1e-3f32 * (effective_bytes - 320) as f32); | ||
| 653 | + } | ||
| 654 | + for i in start..end { | ||
| 655 | + follower[i] = min_f(follower[i], 4.0); | ||
| 656 | + let width = ((c as i32) * (E_BANDS[i + 1] - E_BANDS[i]) as i32) << lm; | ||
| 657 | + let (boost, boost_bits) = if width < 6 { | ||
| 658 | + let boost = follower[i] as i32; | ||
| 659 | + (boost, (boost * width) << BITRES) | ||
| 660 | + } else if width > 48 { | ||
| 661 | + let boost = (follower[i] * 8.0) as i32; | ||
| 662 | + (boost, ((boost * width) << BITRES) / 8) | ||
| 663 | + } else { | ||
| 664 | + let boost = (follower[i] * width as f32 / 6.0) as i32; | ||
| 665 | + (boost, (boost * 6) << BITRES) | ||
| 666 | + }; | ||
| 667 | + if (!vbr || (constrained_vbr && !is_transient)) | ||
| 668 | + && ((tb + boost_bits) >> BITRES >> 3) > 2 * effective_bytes / 3 | ||
| 669 | + { | ||
| 670 | + let cap = ((2 * effective_bytes / 3) << BITRES) << 3; | ||
| 671 | + offsets[i] = cap - tb; | ||
| 672 | + tb = cap; | ||
| 673 | + break; | ||
| 674 | + } else { | ||
| 675 | + offsets[i] = boost; | ||
| 676 | + tb += boost_bits; | ||
| 677 | + } | ||
| 678 | + } | ||
| 679 | + } else { | ||
| 680 | + for i in start..end { | ||
| 681 | + importance[i] = 13; | ||
| 682 | + } | ||
| 683 | + } | ||
| 684 | + *tot_boost = tb; | ||
| 685 | + max_depth | ||
| 686 | +} | ||
| 687 | + | ||
| 688 | +/// `tone_detect`; returns `tone_freq`. | ||
| 689 | +pub(crate) fn tone_detect( | ||
| 690 | + input: &[f32], | ||
| 691 | + cc: usize, | ||
| 692 | + n: usize, | ||
| 693 | + toneishness: &mut f32, | ||
| 694 | + fs: i32, | ||
| 695 | +) -> f32 { | ||
| 696 | + let mut delay: usize = 1; | ||
| 697 | + let mut x_buf = [0f32; ANALYSIS_MAX_LEN]; | ||
| 698 | + let x = &mut x_buf[..n]; | ||
| 699 | + if cc == 2 { | ||
| 700 | + for i in 0..n { | ||
| 701 | + x[i] = input[i] + input[i + n]; | ||
| 702 | + } | ||
| 703 | + } else { | ||
| 704 | + x.copy_from_slice(&input[..n]); | ||
| 705 | + } | ||
| 706 | + let mut lpc = [0f32; 2]; | ||
| 707 | + let mut fail = tone_lpc(x, n, delay, &mut lpc); | ||
| 708 | + while delay <= (fs / 3000) as usize && (fail || (lpc[0] > 1.0 && lpc[1] < 0.0)) { | ||
| 709 | + delay *= 2; | ||
| 710 | + fail = tone_lpc(x, n, delay, &mut lpc); | ||
| 711 | + } | ||
| 712 | + let check = (lpc[0] * lpc[0]) as f64 + 3.999999f64 * lpc[1] as f64; | ||
| 713 | + if !fail && check < 0.0 { | ||
| 714 | + *toneishness = -lpc[1]; | ||
| 715 | + ((((0.5f32 * lpc[0]) as f64).acos()) / delay as f64) as f32 | ||
| 716 | + } else { | ||
| 717 | + *toneishness = 0.0; | ||
| 718 | + -1.0 | ||
| 719 | + } | ||
| 720 | +} | ||
| 721 | + | ||
| 722 | +fn tone_lpc(x: &[f32], len: usize, delay: usize, lpc: &mut [f32; 2]) -> bool { | ||
| 723 | + let mut r00 = 0f32; | ||
| 724 | + let mut r01 = 0f32; | ||
| 725 | + let mut r02 = 0f32; | ||
| 726 | + for i in 0..len - 2 * delay { | ||
| 727 | + r00 += x[i] * x[i]; | ||
| 728 | + r01 += x[i] * x[i + delay]; | ||
| 729 | + r02 += x[i] * x[i + 2 * delay]; | ||
| 730 | + } | ||
| 731 | + let mut edges = 0f32; | ||
| 732 | + for i in 0..delay { | ||
| 733 | + edges += x[len + i - 2 * delay] * x[len + i - 2 * delay] - x[i] * x[i]; | ||
| 734 | + } | ||
| 735 | + let r11 = r00 + edges; | ||
| 736 | + edges = 0.0; | ||
| 737 | + for i in 0..delay { | ||
| 738 | + edges += x[len + i - delay] * x[len + i - delay] - x[i + delay] * x[i + delay]; | ||
| 739 | + } | ||
| 740 | + let r22 = r11 + edges; | ||
| 741 | + edges = 0.0; | ||
| 742 | + for i in 0..delay { | ||
| 743 | + edges += x[len + i - 2 * delay] * x[len + i - delay] - x[i] * x[i + delay]; | ||
| 744 | + } | ||
| 745 | + let r12 = r01 + edges; | ||
| 746 | + let (r00, r01, r11, r02, r12) = (r00 + r22, r01 + r12, 2.0 * r11, 2.0 * r02, r12 + r01); | ||
| 747 | + let den = r00 * r11 - r01 * r01; | ||
| 748 | + if den < 0.001f32 * (r00 * r11) { | ||
| 749 | + return true; | ||
| 750 | + } | ||
| 751 | + let num1 = r02 * r11 - r01 * r12; | ||
| 752 | + lpc[1] = if num1 >= den { | ||
| 753 | + 1.0 | ||
| 754 | + } else if num1 <= -den { | ||
| 755 | + -1.0 | ||
| 756 | + } else { | ||
| 757 | + num1 / den | ||
| 758 | + }; | ||
| 759 | + let num0 = r00 * r12 - r02 * r01; | ||
| 760 | + lpc[0] = if 0.5f32 * num0 >= den { | ||
| 761 | + 1.999999 | ||
| 762 | + } else if 0.5f32 * num0 <= -den { | ||
| 763 | + -1.999999 | ||
| 764 | + } else { | ||
| 765 | + num0 / den | ||
| 766 | + }; | ||
| 767 | + false | ||
| 768 | +} | ||
| 769 | + | ||
| 770 | +/// `compute_vbr` (no QEXT); returns the target in 1/8 bits. | ||
| 771 | +pub(crate) fn compute_vbr( | ||
| 772 | + analysis: &AnalysisInfo, | ||
| 773 | + base_target: i32, | ||
| 774 | + lm: usize, | ||
| 775 | + bitrate: i32, | ||
| 776 | + last_coded_bands: usize, | ||
| 777 | + c: usize, | ||
| 778 | + intensity: usize, | ||
| 779 | + constrained_vbr: bool, | ||
| 780 | + stereo_saving: f32, | ||
| 781 | + tot_boost: i32, | ||
| 782 | + tf_estimate: f32, | ||
| 783 | + pitch_change: bool, | ||
| 784 | + max_depth: f32, | ||
| 785 | + lfe: bool, | ||
| 786 | + has_surround_mask: bool, | ||
| 787 | + surround_masking: f32, | ||
| 788 | + temporal_vbr: f32, | ||
| 789 | +) -> i32 { | ||
| 790 | + let coded_bands = if last_coded_bands != 0 { | ||
| 791 | + last_coded_bands | ||
| 792 | + } else { | ||
| 793 | + NB_BANDS | ||
| 794 | + }; | ||
| 795 | + let mut coded_bins = (E_BANDS[coded_bands] << lm) as i32; | ||
| 796 | + if c == 2 { | ||
| 797 | + coded_bins += (E_BANDS[intensity.min(coded_bands)] << lm) as i32; | ||
| 798 | + } | ||
| 799 | + let mut target = base_target; | ||
| 800 | + if analysis.valid && (analysis.activity as f64) < 0.4 { | ||
| 801 | + target -= ((coded_bins << BITRES) as f32 * (0.4f32 - analysis.activity)) as i32; | ||
| 802 | + } | ||
| 803 | + let mut stereo_saving = stereo_saving; | ||
| 804 | + if c == 2 { | ||
| 805 | + let coded_stereo_bands = intensity.min(coded_bands); | ||
| 806 | + let coded_stereo_dof = ((E_BANDS[coded_stereo_bands] << lm) - coded_stereo_bands) as i32; | ||
| 807 | + let max_frac = (0.8f32 * coded_stereo_dof as f32) / coded_bins as f32; | ||
| 808 | + stereo_saving = min_f(stereo_saving, 1.0); | ||
| 809 | + let saving = min_f( | ||
| 810 | + max_frac * target as f32, | ||
| 811 | + (stereo_saving - 0.1f32) * ((coded_stereo_dof << BITRES) as f32), | ||
| 812 | + ); | ||
| 813 | + target -= saving as i32; | ||
| 814 | + } | ||
| 815 | + target += tot_boost - (19 << lm); | ||
| 816 | + let tf_calibration = 0.044f32; | ||
| 817 | + target += ((tf_estimate - tf_calibration) * target as f32) as i32; | ||
| 818 | + if analysis.valid && !lfe { | ||
| 819 | + let tonal: f32 = max_f(0.0, analysis.tonality - 0.15) - 0.12; | ||
| 820 | + let mut tonal_target = target + ((coded_bins << BITRES) as f32 * 1.2f32 * tonal) as i32; | ||
| 821 | + if pitch_change { | ||
| 822 | + tonal_target += ((coded_bins << BITRES) as f32 * 0.8f32) as i32; | ||
| 823 | + } | ||
| 824 | + target = tonal_target; | ||
| 825 | + } | ||
| 826 | + if has_surround_mask && !lfe { | ||
| 827 | + let surround_target = target + (surround_masking * (coded_bins << BITRES) as f32) as i32; | ||
| 828 | + target = (target / 4).max(surround_target); | ||
| 829 | + } | ||
| 830 | + let bins = (E_BANDS[NB_BANDS - 2] << lm) as i32; | ||
| 831 | + let mut floor_depth = ((((c as i32) * bins) << BITRES) as f32 * max_depth) as i32; | ||
| 832 | + floor_depth = floor_depth.max(target >> 2); | ||
| 833 | + target = target.min(floor_depth); | ||
| 834 | + if (!has_surround_mask || lfe) && constrained_vbr { | ||
| 835 | + target = base_target + ((target - base_target) as f32 * 0.67f32) as i32; | ||
| 836 | + } | ||
| 837 | + if !has_surround_mask && tf_estimate < 0.2f32 { | ||
| 838 | + let amount = 0.0000031f32 * (96000 - bitrate).clamp(0, 32000) as f32; | ||
| 839 | + let tvbr_factor = temporal_vbr * amount; | ||
| 840 | + target += (tvbr_factor * target as f32) as i32; | ||
| 841 | + } | ||
| 842 | + target.min(2 * base_target) | ||
| 843 | +} | ||
crates/ec-opus/src/celt_flp/fft.rsadded+268 -0
| @@ -0,0 +1,268 @@ | |||
| 1 | +use super::tables::{self, FftState}; | ||
| 2 | + | ||
| 3 | +type Cpx = [f32; 2]; | ||
| 4 | + | ||
| 5 | +const MAX_N2: usize = 960; | ||
| 6 | +const MAX_N4: usize = 480; | ||
| 7 | + | ||
| 8 | +fn cmul(a: Cpx, b: Cpx) -> Cpx { | ||
| 9 | + [a[0] * b[0] - a[1] * b[1], a[0] * b[1] + a[1] * b[0]] | ||
| 10 | +} | ||
| 11 | + | ||
| 12 | +fn cadd(a: Cpx, b: Cpx) -> Cpx { | ||
| 13 | + [a[0] + b[0], a[1] + b[1]] | ||
| 14 | +} | ||
| 15 | + | ||
| 16 | +fn csub(a: Cpx, b: Cpx) -> Cpx { | ||
| 17 | + [a[0] - b[0], a[1] - b[1]] | ||
| 18 | +} | ||
| 19 | + | ||
| 20 | +fn kf_bfly2(fout: &mut [Cpx], n: usize) { | ||
| 21 | + const TW: f32 = 0.7071067812; | ||
| 22 | + for i in 0..n { | ||
| 23 | + let b = 8 * i; | ||
| 24 | + let t = fout[b + 4]; | ||
| 25 | + fout[b + 4] = csub(fout[b], t); | ||
| 26 | + fout[b] = cadd(fout[b], t); | ||
| 27 | + | ||
| 28 | + let f5 = fout[b + 5]; | ||
| 29 | + let t = [(f5[0] + f5[1]) * TW, (f5[1] - f5[0]) * TW]; | ||
| 30 | + fout[b + 5] = csub(fout[b + 1], t); | ||
| 31 | + fout[b + 1] = cadd(fout[b + 1], t); | ||
| 32 | + | ||
| 33 | + let f6 = fout[b + 6]; | ||
| 34 | + let t = [f6[1], -f6[0]]; | ||
| 35 | + fout[b + 6] = csub(fout[b + 2], t); | ||
| 36 | + fout[b + 2] = cadd(fout[b + 2], t); | ||
| 37 | + | ||
| 38 | + let f7 = fout[b + 7]; | ||
| 39 | + let t = [(f7[1] - f7[0]) * TW, (-(f7[1] + f7[0])) * TW]; | ||
| 40 | + fout[b + 7] = csub(fout[b + 3], t); | ||
| 41 | + fout[b + 3] = cadd(fout[b + 3], t); | ||
| 42 | + } | ||
| 43 | +} | ||
| 44 | + | ||
| 45 | +fn kf_bfly4(fout: &mut [Cpx], fstride: usize, m: usize, n: usize, mm: usize) { | ||
| 46 | + let tw = &tables::FFT_TWIDDLES; | ||
| 47 | + if m == 1 { | ||
| 48 | + for i in 0..n { | ||
| 49 | + let b = 4 * i; | ||
| 50 | + let s0 = csub(fout[b], fout[b + 2]); | ||
| 51 | + fout[b] = cadd(fout[b], fout[b + 2]); | ||
| 52 | + let s1 = cadd(fout[b + 1], fout[b + 3]); | ||
| 53 | + fout[b + 2] = csub(fout[b], s1); | ||
| 54 | + fout[b] = cadd(fout[b], s1); | ||
| 55 | + let s1 = csub(fout[b + 1], fout[b + 3]); | ||
| 56 | + fout[b + 1] = [s0[0] + s1[1], s0[1] - s1[0]]; | ||
| 57 | + fout[b + 3] = [s0[0] - s1[1], s0[1] + s1[0]]; | ||
| 58 | + } | ||
| 59 | + return; | ||
| 60 | + } | ||
| 61 | + let m2 = 2 * m; | ||
| 62 | + let m3 = 3 * m; | ||
| 63 | + for i in 0..n { | ||
| 64 | + for j in 0..m { | ||
| 65 | + let f = i * mm + j; | ||
| 66 | + let s0 = cmul(fout[f + m], tw[j * fstride]); | ||
| 67 | + let s1 = cmul(fout[f + m2], tw[j * 2 * fstride]); | ||
| 68 | + let s2 = cmul(fout[f + m3], tw[j * 3 * fstride]); | ||
| 69 | + | ||
| 70 | + let s5 = csub(fout[f], s1); | ||
| 71 | + fout[f] = cadd(fout[f], s1); | ||
| 72 | + let s3 = cadd(s0, s2); | ||
| 73 | + let s4 = csub(s0, s2); | ||
| 74 | + fout[f + m2] = csub(fout[f], s3); | ||
| 75 | + fout[f] = cadd(fout[f], s3); | ||
| 76 | + | ||
| 77 | + fout[f + m] = [s5[0] + s4[1], s5[1] - s4[0]]; | ||
| 78 | + fout[f + m3] = [s5[0] - s4[1], s5[1] + s4[0]]; | ||
| 79 | + } | ||
| 80 | + } | ||
| 81 | +} | ||
| 82 | + | ||
| 83 | +fn kf_bfly3(fout: &mut [Cpx], fstride: usize, m: usize, n: usize, mm: usize) { | ||
| 84 | + let tw = &tables::FFT_TWIDDLES; | ||
| 85 | + let m2 = 2 * m; | ||
| 86 | + let epi3 = tw[fstride * m]; | ||
| 87 | + for i in 0..n { | ||
| 88 | + for j in 0..m { | ||
| 89 | + let f = i * mm + j; | ||
| 90 | + let s1 = cmul(fout[f + m], tw[j * fstride]); | ||
| 91 | + let s2 = cmul(fout[f + m2], tw[j * 2 * fstride]); | ||
| 92 | + | ||
| 93 | + let s3 = cadd(s1, s2); | ||
| 94 | + let mut s0 = csub(s1, s2); | ||
| 95 | + | ||
| 96 | + fout[f + m] = [fout[f][0] - s3[0] * 0.5, fout[f][1] - s3[1] * 0.5]; | ||
| 97 | + | ||
| 98 | + s0 = [s0[0] * epi3[1], s0[1] * epi3[1]]; | ||
| 99 | + | ||
| 100 | + fout[f] = cadd(fout[f], s3); | ||
| 101 | + | ||
| 102 | + fout[f + m2] = [fout[f + m][0] + s0[1], fout[f + m][1] - s0[0]]; | ||
| 103 | + fout[f + m] = [fout[f + m][0] - s0[1], fout[f + m][1] + s0[0]]; | ||
| 104 | + } | ||
| 105 | + } | ||
| 106 | +} | ||
| 107 | + | ||
| 108 | +fn kf_bfly5(fout: &mut [Cpx], fstride: usize, m: usize, n: usize, mm: usize) { | ||
| 109 | + let tw = &tables::FFT_TWIDDLES; | ||
| 110 | + let ya = tw[fstride * m]; | ||
| 111 | + let yb = tw[fstride * 2 * m]; | ||
| 112 | + for i in 0..n { | ||
| 113 | + let base = i * mm; | ||
| 114 | + for u in 0..m { | ||
| 115 | + let f0 = base + u; | ||
| 116 | + let f1 = f0 + m; | ||
| 117 | + let f2 = f0 + 2 * m; | ||
| 118 | + let f3 = f0 + 3 * m; | ||
| 119 | + let f4 = f0 + 4 * m; | ||
| 120 | + | ||
| 121 | + let s0 = fout[f0]; | ||
| 122 | + let s1 = cmul(fout[f1], tw[u * fstride]); | ||
| 123 | + let s2 = cmul(fout[f2], tw[2 * u * fstride]); | ||
| 124 | + let s3 = cmul(fout[f3], tw[3 * u * fstride]); | ||
| 125 | + let s4 = cmul(fout[f4], tw[4 * u * fstride]); | ||
| 126 | + | ||
| 127 | + let s7 = cadd(s1, s4); | ||
| 128 | + let s10 = csub(s1, s4); | ||
| 129 | + let s8 = cadd(s2, s3); | ||
| 130 | + let s9 = csub(s2, s3); | ||
| 131 | + | ||
| 132 | + fout[f0] = [fout[f0][0] + (s7[0] + s8[0]), fout[f0][1] + (s7[1] + s8[1])]; | ||
| 133 | + | ||
| 134 | + let s5 = [ | ||
| 135 | + s0[0] + (s7[0] * ya[0] + s8[0] * yb[0]), | ||
| 136 | + s0[1] + (s7[1] * ya[0] + s8[1] * yb[0]), | ||
| 137 | + ]; | ||
| 138 | + | ||
| 139 | + let s6 = [ | ||
| 140 | + s10[1] * ya[1] + s9[1] * yb[1], | ||
| 141 | + -(s10[0] * ya[1] + s9[0] * yb[1]), | ||
| 142 | + ]; | ||
| 143 | + | ||
| 144 | + fout[f1] = csub(s5, s6); | ||
| 145 | + fout[f4] = cadd(s5, s6); | ||
| 146 | + | ||
| 147 | + let s11 = [ | ||
| 148 | + s0[0] + (s7[0] * yb[0] + s8[0] * ya[0]), | ||
| 149 | + s0[1] + (s7[1] * yb[0] + s8[1] * ya[0]), | ||
| 150 | + ]; | ||
| 151 | + let s12 = [ | ||
| 152 | + s9[1] * ya[1] - s10[1] * yb[1], | ||
| 153 | + s10[0] * yb[1] - s9[0] * ya[1], | ||
| 154 | + ]; | ||
| 155 | + | ||
| 156 | + fout[f2] = cadd(s11, s12); | ||
| 157 | + fout[f3] = csub(s11, s12); | ||
| 158 | + } | ||
| 159 | + } | ||
| 160 | +} | ||
| 161 | + | ||
| 162 | +/// `opus_fft_impl` (float, in place on `fout`). | ||
| 163 | +pub(crate) fn opus_fft_impl(st: &FftState, fout: &mut [[f32; 2]]) { | ||
| 164 | + let shift = if st.shift > 0 { st.shift as usize } else { 0 }; | ||
| 165 | + let mut fstride = [0usize; 9]; | ||
| 166 | + fstride[0] = 1; | ||
| 167 | + let mut l = 0usize; | ||
| 168 | + loop { | ||
| 169 | + let p = st.factors[2 * l] as usize; | ||
| 170 | + let m = st.factors[2 * l + 1]; | ||
| 171 | + fstride[l + 1] = fstride[l] * p; | ||
| 172 | + l += 1; | ||
| 173 | + if m == 1 { | ||
| 174 | + break; | ||
| 175 | + } | ||
| 176 | + } | ||
| 177 | + let mut m = st.factors[2 * l - 1] as usize; | ||
| 178 | + for i in (0..l).rev() { | ||
| 179 | + let m2 = if i != 0 { | ||
| 180 | + st.factors[2 * i - 1] as usize | ||
| 181 | + } else { | ||
| 182 | + 1 | ||
| 183 | + }; | ||
| 184 | + match st.factors[2 * i] { | ||
| 185 | + 2 => kf_bfly2(fout, fstride[i]), | ||
| 186 | + 4 => kf_bfly4(fout, fstride[i] << shift, m, fstride[i], m2), | ||
| 187 | + 3 => kf_bfly3(fout, fstride[i] << shift, m, fstride[i], m2), | ||
| 188 | + 5 => kf_bfly5(fout, fstride[i] << shift, m, fstride[i], m2), | ||
| 189 | + _ => {} | ||
| 190 | + } | ||
| 191 | + m = m2; | ||
| 192 | + } | ||
| 193 | +} | ||
| 194 | + | ||
| 195 | +/// `clt_mdct_forward_c` for the static 1920-point lookup; `input` is C `in`, | ||
| 196 | +/// output goes to `out[k * stride]`. | ||
| 197 | +pub(crate) fn clt_mdct_forward( | ||
| 198 | + input: &[f32], | ||
| 199 | + out: &mut [f32], | ||
| 200 | + overlap: usize, | ||
| 201 | + shift: usize, | ||
| 202 | + stride: usize, | ||
| 203 | +) { | ||
| 204 | + let st = &tables::FFT_STATES[shift]; | ||
| 205 | + let window = &tables::WINDOW120; | ||
| 206 | + let trig_tab = &tables::MDCT_TWIDDLES; | ||
| 207 | + let scale = st.scale; | ||
| 208 | + | ||
| 209 | + let mut n = 1920usize; | ||
| 210 | + let mut trig = 0usize; | ||
| 211 | + for _ in 0..shift { | ||
| 212 | + n >>= 1; | ||
| 213 | + trig += n; | ||
| 214 | + } | ||
| 215 | + let n2 = n >> 1; | ||
| 216 | + let n4 = n >> 2; | ||
| 217 | + | ||
| 218 | + let h = overlap >> 1; | ||
| 219 | + let mut f_buf = [0f32; MAX_N2]; | ||
| 220 | + let mut f2_buf = [[0f32; 2]; MAX_N4]; | ||
| 221 | + let f = &mut f_buf[..n2]; | ||
| 222 | + let f2 = &mut f2_buf[..n4]; | ||
| 223 | + | ||
| 224 | + let fold_end = (overlap + 3) >> 2; | ||
| 225 | + let tail_start = n4 - fold_end; | ||
| 226 | + for i in 0..n4 { | ||
| 227 | + let x1 = h + 2 * i; | ||
| 228 | + let x2 = n2 - 1 + h - 2 * i; | ||
| 229 | + let yp = 2 * i; | ||
| 230 | + if i < fold_end { | ||
| 231 | + let w1 = h + 2 * i; | ||
| 232 | + let w2 = h - 1 - 2 * i; | ||
| 233 | + f[yp] = input[x1 + n2] * window[w2] + input[x2] * window[w1]; | ||
| 234 | + f[yp + 1] = input[x1] * window[w1] - input[x2 - n2] * window[w2]; | ||
| 235 | + } else if i < tail_start { | ||
| 236 | + f[yp] = input[x2]; | ||
| 237 | + f[yp + 1] = input[x1]; | ||
| 238 | + } else { | ||
| 239 | + let k = i - tail_start; | ||
| 240 | + let w1 = 2 * k; | ||
| 241 | + let w2 = overlap - 1 - 2 * k; | ||
| 242 | + f[yp] = -(input[x1 - n2] * window[w1]) + input[x2] * window[w2]; | ||
| 243 | + f[yp + 1] = input[x1] * window[w2] + input[x2 + n2] * window[w1]; | ||
| 244 | + } | ||
| 245 | + } | ||
| 246 | + | ||
| 247 | + for i in 0..n4 { | ||
| 248 | + let t0 = trig_tab[trig + 2 * i]; | ||
| 249 | + let t1 = trig_tab[trig + 2 * i + 1]; | ||
| 250 | + let re = f[2 * i]; | ||
| 251 | + let im = f[2 * i + 1]; | ||
| 252 | + let yr = re * t1 - im * t0; | ||
| 253 | + let yi = im * t1 + re * t0; | ||
| 254 | + f2[st.bitrev[i] as usize] = [yr * scale, yi * scale]; | ||
| 255 | + } | ||
| 256 | + | ||
| 257 | + opus_fft_impl(st, f2); | ||
| 258 | + | ||
| 259 | + for i in 0..n4 { | ||
| 260 | + let t0 = trig_tab[trig + 2 * i]; | ||
| 261 | + let t1 = trig_tab[trig + 2 * i + 1]; | ||
| 262 | + let fp = f2[i]; | ||
| 263 | + let yr = fp[1] * t0 - fp[0] * t1; | ||
| 264 | + let yi = fp[0] * t0 + fp[1] * t1; | ||
| 265 | + out[2 * i * stride] = yr; | ||
| 266 | + out[(n2 - 1 - 2 * i) * stride] = yi; | ||
| 267 | + } | ||
| 268 | +} | ||
crates/ec-opus/src/celt_flp/mod.rsadded+81 -0
| @@ -0,0 +1,81 @@ | |||
| 1 | +#![allow( | ||
| 2 | + clippy::needless_range_loop, | ||
| 3 | + clippy::too_many_arguments, | ||
| 4 | + clippy::manual_memcpy, | ||
| 5 | + clippy::explicit_counter_loop, | ||
| 6 | + clippy::excessive_precision, | ||
| 7 | + clippy::approx_constant | ||
| 8 | +)] | ||
| 9 | + | ||
| 10 | +pub(crate) mod bands; | ||
| 11 | +pub(crate) mod enc; | ||
| 12 | +pub(crate) mod enc_an; | ||
| 13 | +pub(crate) mod fft; | ||
| 14 | +pub(crate) mod pitch; | ||
| 15 | +pub(crate) mod quant_bands; | ||
| 16 | +pub(crate) mod tables; | ||
| 17 | +pub(crate) mod vq; | ||
| 18 | + | ||
| 19 | +pub(crate) use crate::celt::{BITRES, E_BANDS, LOG_N, NB_BANDS}; | ||
| 20 | + | ||
| 21 | +pub(crate) const OVERLAP: usize = 120; | ||
| 22 | +pub(crate) const COMBFILTER_MAXPERIOD: usize = 1024; | ||
| 23 | +pub(crate) const COMBFILTER_MINPERIOD: usize = 15; | ||
| 24 | +pub(crate) const SHORT_MDCT: usize = 120; | ||
| 25 | +pub(crate) const MAX_LM: usize = 3; | ||
| 26 | +pub(crate) const PI: f64 = std::f64::consts::PI; | ||
| 27 | +pub(crate) const EPSILON: f32 = 1e-15; | ||
| 28 | + | ||
| 29 | +pub(crate) fn celt_sqrt(x: f32) -> f32 { | ||
| 30 | + (x as f64).sqrt() as f32 | ||
| 31 | +} | ||
| 32 | + | ||
| 33 | +pub(crate) fn celt_rsqrt(x: f32) -> f32 { | ||
| 34 | + 1.0 / celt_sqrt(x) | ||
| 35 | +} | ||
| 36 | + | ||
| 37 | +pub(crate) fn celt_rcp(x: f32) -> f32 { | ||
| 38 | + 1.0 / x | ||
| 39 | +} | ||
| 40 | + | ||
| 41 | +pub(crate) fn celt_log2(x: f32) -> f32 { | ||
| 42 | + (1.442695040888963387f64 * (x as f64).ln()) as f32 | ||
| 43 | +} | ||
| 44 | + | ||
| 45 | +pub(crate) fn celt_exp2(x: f32) -> f32 { | ||
| 46 | + (0.6931471805599453094f64 * x as f64).exp() as f32 | ||
| 47 | +} | ||
| 48 | + | ||
| 49 | +pub(crate) fn celt_cos_norm(x: f32) -> f32 { | ||
| 50 | + ((0.5f32 as f64 * PI) * x as f64).cos() as f32 | ||
| 51 | +} | ||
| 52 | + | ||
| 53 | +pub(crate) fn celt_atan_norm(x: f32) -> f32 { | ||
| 54 | + const ATAN2_2_OVER_PI: f32 = 0.636619772367581; | ||
| 55 | + const A03: f32 = -3.3331659436225891113281250000e-01; | ||
| 56 | + const A05: f32 = 1.99627041816711425781250000000e-01; | ||
| 57 | + const A07: f32 = -1.3976582884788513183593750000e-01; | ||
| 58 | + const A09: f32 = 9.79423448443412780761718750000e-02; | ||
| 59 | + const A11: f32 = -5.7773590087890625000000000000e-02; | ||
| 60 | + const A13: f32 = 2.30401363223791122436523437500e-02; | ||
| 61 | + const A15: f32 = -4.3554059229791164398193359375e-03; | ||
| 62 | + let x_sq = x * x; | ||
| 63 | + ATAN2_2_OVER_PI | ||
| 64 | + * (x + x | ||
| 65 | + * x_sq | ||
| 66 | + * (A03 | ||
| 67 | + + x_sq | ||
| 68 | + * (A05 | ||
| 69 | + + x_sq * (A07 + x_sq * (A09 + x_sq * (A11 + x_sq * (A13 + x_sq * A15))))))) | ||
| 70 | +} | ||
| 71 | + | ||
| 72 | +pub(crate) fn celt_atan2p_norm(y: f32, x: f32) -> f32 { | ||
| 73 | + if x * x + y * y < 1e-18 { | ||
| 74 | + return 0.0; | ||
| 75 | + } | ||
| 76 | + if y < x { | ||
| 77 | + celt_atan_norm(y / x) | ||
| 78 | + } else { | ||
| 79 | + 1.0 - celt_atan_norm(x / y) | ||
| 80 | + } | ||
| 81 | +} | ||
crates/ec-opus/src/celt_flp/pitch.rsadded+569 -0
| @@ -0,0 +1,569 @@ | |||
| 1 | +use super::{COMBFILTER_MINPERIOD, celt_sqrt}; | ||
| 2 | + | ||
| 3 | +const SECOND_CHECK: [i32; 16] = [0, 0, 3, 2, 3, 2, 5, 2, 3, 2, 3, 2, 5, 2, 3, 2]; | ||
| 4 | + | ||
| 5 | +const MAX_PERIOD: usize = 1024; | ||
| 6 | +const MAX_FRAME: usize = 960; | ||
| 7 | +const MAX_DOWN: usize = (MAX_PERIOD + MAX_FRAME) >> 1; | ||
| 8 | +const MAX_LAG: usize = MAX_PERIOD + MAX_FRAME; | ||
| 9 | +const MAX_YY_LOOKUP: usize = (MAX_PERIOD >> 1) + 1; | ||
| 10 | + | ||
| 11 | +const COMB_GAINS: [[f32; 3]; 3] = [ | ||
| 12 | + [0.3066406250, 0.2170410156, 0.1296386719], | ||
| 13 | + [0.4638671875, 0.2680664062, 0.0], | ||
| 14 | + [0.7998046875, 0.1000976562, 0.0], | ||
| 15 | +]; | ||
| 16 | + | ||
| 17 | +fn max_f(a: f32, b: f32) -> f32 { | ||
| 18 | + if a > b { a } else { b } | ||
| 19 | +} | ||
| 20 | + | ||
| 21 | +fn half32(x: f32) -> f32 { | ||
| 22 | + 0.5f32 * x | ||
| 23 | +} | ||
| 24 | + | ||
| 25 | +fn half16(x: f32) -> f32 { | ||
| 26 | + 0.5f32 * x | ||
| 27 | +} | ||
| 28 | + | ||
| 29 | +fn xcorr_kernel(x: &[f32], y: &[f32], sum: &mut [f32; 4], len: usize) { | ||
| 30 | + let len = len as isize; | ||
| 31 | + let mut xi = 0usize; | ||
| 32 | + let mut yi = 3usize; | ||
| 33 | + let mut y0 = y[0]; | ||
| 34 | + let mut y1 = y[1]; | ||
| 35 | + let mut y2 = y[2]; | ||
| 36 | + let mut y3 = 0.0f32; | ||
| 37 | + let mut j: isize = 0; | ||
| 38 | + while j < len - 3 { | ||
| 39 | + let tmp = x[xi]; | ||
| 40 | + xi += 1; | ||
| 41 | + y3 = y[yi]; | ||
| 42 | + yi += 1; | ||
| 43 | + sum[0] += tmp * y0; | ||
| 44 | + sum[1] += tmp * y1; | ||
| 45 | + sum[2] += tmp * y2; | ||
| 46 | + sum[3] += tmp * y3; | ||
| 47 | + let tmp = x[xi]; | ||
| 48 | + xi += 1; | ||
| 49 | + y0 = y[yi]; | ||
| 50 | + yi += 1; | ||
| 51 | + sum[0] += tmp * y1; | ||
| 52 | + sum[1] += tmp * y2; | ||
| 53 | + sum[2] += tmp * y3; | ||
| 54 | + sum[3] += tmp * y0; | ||
| 55 | + let tmp = x[xi]; | ||
| 56 | + xi += 1; | ||
| 57 | + y1 = y[yi]; | ||
| 58 | + yi += 1; | ||
| 59 | + sum[0] += tmp * y2; | ||
| 60 | + sum[1] += tmp * y3; | ||
| 61 | + sum[2] += tmp * y0; | ||
| 62 | + sum[3] += tmp * y1; | ||
| 63 | + let tmp = x[xi]; | ||
| 64 | + xi += 1; | ||
| 65 | + y2 = y[yi]; | ||
| 66 | + yi += 1; | ||
| 67 | + sum[0] += tmp * y3; | ||
| 68 | + sum[1] += tmp * y0; | ||
| 69 | + sum[2] += tmp * y1; | ||
| 70 | + sum[3] += tmp * y2; | ||
| 71 | + j += 4; | ||
| 72 | + } | ||
| 73 | + let c = j < len; | ||
| 74 | + j += 1; | ||
| 75 | + if c { | ||
| 76 | + let tmp = x[xi]; | ||
| 77 | + xi += 1; | ||
| 78 | + y3 = y[yi]; | ||
| 79 | + yi += 1; | ||
| 80 | + sum[0] += tmp * y0; | ||
| 81 | + sum[1] += tmp * y1; | ||
| 82 | + sum[2] += tmp * y2; | ||
| 83 | + sum[3] += tmp * y3; | ||
| 84 | + } | ||
| 85 | + let c = j < len; | ||
| 86 | + j += 1; | ||
| 87 | + if c { | ||
| 88 | + let tmp = x[xi]; | ||
| 89 | + xi += 1; | ||
| 90 | + y0 = y[yi]; | ||
| 91 | + yi += 1; | ||
| 92 | + sum[0] += tmp * y1; | ||
| 93 | + sum[1] += tmp * y2; | ||
| 94 | + sum[2] += tmp * y3; | ||
| 95 | + sum[3] += tmp * y0; | ||
| 96 | + } | ||
| 97 | + if j < len { | ||
| 98 | + let tmp = x[xi]; | ||
| 99 | + y1 = y[yi]; | ||
| 100 | + sum[0] += tmp * y2; | ||
| 101 | + sum[1] += tmp * y3; | ||
| 102 | + sum[2] += tmp * y0; | ||
| 103 | + sum[3] += tmp * y1; | ||
| 104 | + } | ||
| 105 | +} | ||
| 106 | + | ||
| 107 | +fn celt_pitch_xcorr(x: &[f32], y: &[f32], xcorr: &mut [f32], len: usize, max_pitch: usize) { | ||
| 108 | + let mut i = 0usize; | ||
| 109 | + while i + 4 <= max_pitch { | ||
| 110 | + let mut sum = [0f32; 4]; | ||
| 111 | + xcorr_kernel(x, &y[i..], &mut sum, len); | ||
| 112 | + xcorr[i..i + 4].copy_from_slice(&sum); | ||
| 113 | + i += 4; | ||
| 114 | + } | ||
| 115 | + while i < max_pitch { | ||
| 116 | + xcorr[i] = celt_inner_prod(x, &y[i..], len); | ||
| 117 | + i += 1; | ||
| 118 | + } | ||
| 119 | +} | ||
| 120 | + | ||
| 121 | +fn dual_inner_prod(x: &[f32], y01: &[f32], y02: &[f32], n: usize) -> (f32, f32) { | ||
| 122 | + let mut xy01 = 0f32; | ||
| 123 | + let mut xy02 = 0f32; | ||
| 124 | + for i in 0..n { | ||
| 125 | + xy01 += x[i] * y01[i]; | ||
| 126 | + xy02 += x[i] * y02[i]; | ||
| 127 | + } | ||
| 128 | + (xy01, xy02) | ||
| 129 | +} | ||
| 130 | + | ||
| 131 | +fn celt_fir5(x: &mut [f32], num: &[f32], n: usize) { | ||
| 132 | + let (num0, num1, num2, num3, num4) = (num[0], num[1], num[2], num[3], num[4]); | ||
| 133 | + let (mut mem0, mut mem1, mut mem2, mut mem3, mut mem4) = (0f32, 0f32, 0f32, 0f32, 0f32); | ||
| 134 | + for xi in x.iter_mut().take(n) { | ||
| 135 | + let mut sum = *xi; | ||
| 136 | + sum += num0 * mem0; | ||
| 137 | + sum += num1 * mem1; | ||
| 138 | + sum += num2 * mem2; | ||
| 139 | + sum += num3 * mem3; | ||
| 140 | + sum += num4 * mem4; | ||
| 141 | + mem4 = mem3; | ||
| 142 | + mem3 = mem2; | ||
| 143 | + mem2 = mem1; | ||
| 144 | + mem1 = mem0; | ||
| 145 | + mem0 = *xi; | ||
| 146 | + *xi = sum; | ||
| 147 | + } | ||
| 148 | +} | ||
| 149 | + | ||
| 150 | +fn celt_lpc(lpc: &mut [f32], ac: &[f32], p: usize) { | ||
| 151 | + for v in lpc.iter_mut().take(p) { | ||
| 152 | + *v = 0.0; | ||
| 153 | + } | ||
| 154 | + let mut error = ac[0]; | ||
| 155 | + if ac[0] > 1e-10f32 { | ||
| 156 | + for i in 0..p { | ||
| 157 | + let mut rr = 0f32; | ||
| 158 | + for j in 0..i { | ||
| 159 | + rr += lpc[j] * ac[i - j]; | ||
| 160 | + } | ||
| 161 | + rr += ac[i + 1]; | ||
| 162 | + let r = -(rr / error); | ||
| 163 | + lpc[i] = r; | ||
| 164 | + for j in 0..((i + 1) >> 1) { | ||
| 165 | + let tmp1 = lpc[j]; | ||
| 166 | + let tmp2 = lpc[i - 1 - j]; | ||
| 167 | + lpc[j] = tmp1 + r * tmp2; | ||
| 168 | + lpc[i - 1 - j] = tmp2 + r * tmp1; | ||
| 169 | + } | ||
| 170 | + error = error - r * r * error; | ||
| 171 | + if error <= 0.001f32 * ac[0] { | ||
| 172 | + break; | ||
| 173 | + } | ||
| 174 | + } | ||
| 175 | + } | ||
| 176 | +} | ||
| 177 | + | ||
| 178 | +fn celt_autocorr( | ||
| 179 | + x: &[f32], | ||
| 180 | + ac: &mut [f32], | ||
| 181 | + window: Option<&[f32]>, | ||
| 182 | + overlap: usize, | ||
| 183 | + lag: usize, | ||
| 184 | + n: usize, | ||
| 185 | +) { | ||
| 186 | + let mut xx_buf = [0f32; MAX_DOWN]; | ||
| 187 | + let xx = &mut xx_buf[..n]; | ||
| 188 | + xx.copy_from_slice(&x[..n]); | ||
| 189 | + if let Some(w) = window { | ||
| 190 | + for i in 0..overlap { | ||
| 191 | + xx[i] = x[i] * w[i]; | ||
| 192 | + xx[n - i - 1] = x[n - i - 1] * w[i]; | ||
| 193 | + } | ||
| 194 | + } | ||
| 195 | + let fast_n = n - lag; | ||
| 196 | + celt_pitch_xcorr(xx, xx, ac, fast_n, lag + 1); | ||
| 197 | + for k in 0..=lag { | ||
| 198 | + let mut d = 0f32; | ||
| 199 | + for i in (k + fast_n)..n { | ||
| 200 | + d += xx[i] * xx[i - k]; | ||
| 201 | + } | ||
| 202 | + ac[k] += d; | ||
| 203 | + } | ||
| 204 | +} | ||
| 205 | + | ||
| 206 | +/// `pitch_downsample`; `x[c]` is C `x[c]` (one slice per channel). | ||
| 207 | +pub(crate) fn pitch_downsample(x: &[&[f32]], x_lp: &mut [f32], len: usize, factor: usize) { | ||
| 208 | + let offset = factor / 2; | ||
| 209 | + let mut ac = [0f32; 5]; | ||
| 210 | + let mut tmp = 1.0f32; | ||
| 211 | + let mut lpc = [0f32; 4]; | ||
| 212 | + let mut lpc2 = [0f32; 5]; | ||
| 213 | + let c1 = 0.8f32; | ||
| 214 | + for i in 1..len { | ||
| 215 | + x_lp[i] = 0.25f32 * x[0][factor * i - offset] | ||
| 216 | + + 0.25f32 * x[0][factor * i + offset] | ||
| 217 | + + 0.5f32 * x[0][factor * i]; | ||
| 218 | + } | ||
| 219 | + x_lp[0] = 0.25f32 * x[0][offset] + 0.5f32 * x[0][0]; | ||
| 220 | + if x.len() == 2 { | ||
| 221 | + for i in 1..len { | ||
| 222 | + x_lp[i] += 0.25f32 * x[1][factor * i - offset] | ||
| 223 | + + 0.25f32 * x[1][factor * i + offset] | ||
| 224 | + + 0.5f32 * x[1][factor * i]; | ||
| 225 | + } | ||
| 226 | + x_lp[0] += 0.25f32 * x[1][offset] + 0.5f32 * x[1][0]; | ||
| 227 | + } | ||
| 228 | + celt_autocorr(&x_lp[..len], &mut ac, None, 0, 4, len); | ||
| 229 | + ac[0] *= 1.0001f32; | ||
| 230 | + for i in 1..=4 { | ||
| 231 | + let t = 0.008f32 * (i as f32); | ||
| 232 | + ac[i] -= ac[i] * t * t; | ||
| 233 | + } | ||
| 234 | + celt_lpc(&mut lpc, &ac, 4); | ||
| 235 | + for i in 0..4 { | ||
| 236 | + tmp *= 0.9f32; | ||
| 237 | + lpc[i] *= tmp; | ||
| 238 | + } | ||
| 239 | + lpc2[0] = lpc[0] + 0.8f32; | ||
| 240 | + lpc2[1] = lpc[1] + c1 * lpc[0]; | ||
| 241 | + lpc2[2] = lpc[2] + c1 * lpc[1]; | ||
| 242 | + lpc2[3] = lpc[3] + c1 * lpc[2]; | ||
| 243 | + lpc2[4] = c1 * lpc[3]; | ||
| 244 | + celt_fir5(x_lp, &lpc2, len); | ||
| 245 | +} | ||
| 246 | + | ||
| 247 | +fn find_best_pitch( | ||
| 248 | + xcorr: &[f32], | ||
| 249 | + y: &[f32], | ||
| 250 | + len: usize, | ||
| 251 | + max_pitch: usize, | ||
| 252 | + best_pitch: &mut [i32; 2], | ||
| 253 | +) { | ||
| 254 | + let mut syy = 1.0f32; | ||
| 255 | + let mut best_num = [-1.0f32; 2]; | ||
| 256 | + let mut best_den = [0.0f32; 2]; | ||
| 257 | + best_pitch[0] = 0; | ||
| 258 | + best_pitch[1] = 1; | ||
| 259 | + for j in 0..len { | ||
| 260 | + syy += y[j] * y[j]; | ||
| 261 | + } | ||
| 262 | + for i in 0..max_pitch { | ||
| 263 | + if xcorr[i] > 0.0 { | ||
| 264 | + let mut xcorr16 = xcorr[i]; | ||
| 265 | + xcorr16 *= 1e-12f32; | ||
| 266 | + let num = xcorr16 * xcorr16; | ||
| 267 | + if num * best_den[1] > best_num[1] * syy { | ||
| 268 | + if num * best_den[0] > best_num[0] * syy { | ||
| 269 | + best_num[1] = best_num[0]; | ||
| 270 | + best_den[1] = best_den[0]; | ||
| 271 | + best_pitch[1] = best_pitch[0]; | ||
| 272 | + best_num[0] = num; | ||
| 273 | + best_den[0] = syy; | ||
| 274 | + best_pitch[0] = i as i32; | ||
| 275 | + } else { | ||
| 276 | + best_num[1] = num; | ||
| 277 | + best_den[1] = syy; | ||
| 278 | + best_pitch[1] = i as i32; | ||
| 279 | + } | ||
| 280 | + } | ||
| 281 | + } | ||
| 282 | + syy += y[i + len] * y[i + len] - y[i] * y[i]; | ||
| 283 | + syy = max_f(1.0, syy); | ||
| 284 | + } | ||
| 285 | +} | ||
| 286 | + | ||
| 287 | +/// `pitch_search`; returns C `*pitch`. | ||
| 288 | +pub(crate) fn pitch_search(x_lp: &[f32], y: &[f32], len: usize, max_pitch: usize) -> i32 { | ||
| 289 | + let lag = len + max_pitch; | ||
| 290 | + let mut x_lp4_buf = [0f32; MAX_FRAME >> 2]; | ||
| 291 | + let mut y_lp4_buf = [0f32; MAX_LAG >> 2]; | ||
| 292 | + let mut xcorr_buf = [0f32; MAX_PERIOD >> 1]; | ||
| 293 | + let x_lp4 = &mut x_lp4_buf[..len >> 2]; | ||
| 294 | + let y_lp4 = &mut y_lp4_buf[..lag >> 2]; | ||
| 295 | + let xcorr = &mut xcorr_buf[..max_pitch >> 1]; | ||
| 296 | + for j in 0..len >> 2 { | ||
| 297 | + x_lp4[j] = x_lp[2 * j]; | ||
| 298 | + } | ||
| 299 | + for j in 0..lag >> 2 { | ||
| 300 | + y_lp4[j] = y[2 * j]; | ||
| 301 | + } | ||
| 302 | + celt_pitch_xcorr(x_lp4, y_lp4, xcorr, len >> 2, max_pitch >> 2); | ||
| 303 | + let mut best_pitch = [0i32; 2]; | ||
| 304 | + find_best_pitch(xcorr, y_lp4, len >> 2, max_pitch >> 2, &mut best_pitch); | ||
| 305 | + for i in 0..max_pitch >> 1 { | ||
| 306 | + xcorr[i] = 0.0; | ||
| 307 | + let ii = i as i32; | ||
| 308 | + if (ii - 2 * best_pitch[0]).abs() > 2 && (ii - 2 * best_pitch[1]).abs() > 2 { | ||
| 309 | + continue; | ||
| 310 | + } | ||
| 311 | + let sum = celt_inner_prod(x_lp, &y[i..], len >> 1); | ||
| 312 | + xcorr[i] = if -1.0f32 > sum { -1.0f32 } else { sum }; | ||
| 313 | + } | ||
| 314 | + find_best_pitch(xcorr, y, len >> 1, max_pitch >> 1, &mut best_pitch); | ||
| 315 | + let bp = best_pitch[0]; | ||
| 316 | + let offset = if bp > 0 && bp < (max_pitch as i32 >> 1) - 1 { | ||
| 317 | + let b_idx = bp as usize; | ||
| 318 | + let a = xcorr[b_idx - 1]; | ||
| 319 | + let b = xcorr[b_idx]; | ||
| 320 | + let c = xcorr[b_idx + 1]; | ||
| 321 | + if (c - a) > 0.7f32 * (b - a) { | ||
| 322 | + 1 | ||
| 323 | + } else if (a - c) > 0.7f32 * (b - c) { | ||
| 324 | + -1 | ||
| 325 | + } else { | ||
| 326 | + 0 | ||
| 327 | + } | ||
| 328 | + } else { | ||
| 329 | + 0 | ||
| 330 | + }; | ||
| 331 | + 2 * bp - offset | ||
| 332 | +} | ||
| 333 | + | ||
| 334 | +fn compute_pitch_gain(xy: f32, xx: f32, yy: f32) -> f32 { | ||
| 335 | + xy / celt_sqrt(1.0 + xx * yy) | ||
| 336 | +} | ||
| 337 | + | ||
| 338 | +/// `remove_doubling`; `x` is C `x` (before its internal `x += maxperiod`). | ||
| 339 | +pub(crate) fn remove_doubling( | ||
| 340 | + x: &[f32], | ||
| 341 | + maxperiod: i32, | ||
| 342 | + minperiod: i32, | ||
| 343 | + n: i32, | ||
| 344 | + t0: &mut i32, | ||
| 345 | + prev_period: i32, | ||
| 346 | + prev_gain: f32, | ||
| 347 | +) -> f32 { | ||
| 348 | + let minperiod0 = minperiod; | ||
| 349 | + let maxperiod = maxperiod / 2; | ||
| 350 | + let minperiod = minperiod / 2; | ||
| 351 | + *t0 /= 2; | ||
| 352 | + let prev_period = prev_period / 2; | ||
| 353 | + let n = n / 2; | ||
| 354 | + let nn = n as usize; | ||
| 355 | + let base = maxperiod as isize; | ||
| 356 | + let at = |d: isize| (base + d) as usize; | ||
| 357 | + if *t0 >= maxperiod { | ||
| 358 | + *t0 = maxperiod - 1; | ||
| 359 | + } | ||
| 360 | + let t0v = *t0; | ||
| 361 | + let (xx, xy) = dual_inner_prod(&x[at(0)..], &x[at(0)..], &x[at(-(t0v as isize))..], nn); | ||
| 362 | + let mut yy_lookup_buf = [0f32; MAX_YY_LOOKUP]; | ||
| 363 | + let yy_lookup = &mut yy_lookup_buf[..(maxperiod + 1) as usize]; | ||
| 364 | + yy_lookup[0] = xx; | ||
| 365 | + let mut yy = xx; | ||
| 366 | + for i in 1..=maxperiod as isize { | ||
| 367 | + let a = x[at(-i)]; | ||
| 368 | + let b = x[at(n as isize - i)]; | ||
| 369 | + yy = yy + a * a - b * b; | ||
| 370 | + yy_lookup[i as usize] = max_f(0.0, yy); | ||
| 371 | + } | ||
| 372 | + let mut t = t0v; | ||
| 373 | + let mut best_xy = xy; | ||
| 374 | + let mut best_yy = yy_lookup[t0v as usize]; | ||
| 375 | + let mut g = compute_pitch_gain(xy, xx, best_yy); | ||
| 376 | + let g0 = g; | ||
| 377 | + for k in 2..=15 { | ||
| 378 | + let t1 = (2 * t0v + k) / (2 * k); | ||
| 379 | + if t1 < minperiod { | ||
| 380 | + break; | ||
| 381 | + } | ||
| 382 | + let t1b = if k == 2 { | ||
| 383 | + if t1 + t0v > maxperiod { t0v } else { t0v + t1 } | ||
| 384 | + } else { | ||
| 385 | + (2 * SECOND_CHECK[k as usize] * t0v + k) / (2 * k) | ||
| 386 | + }; | ||
| 387 | + let (xy_a, xy2) = dual_inner_prod( | ||
| 388 | + &x[at(0)..], | ||
| 389 | + &x[at(-(t1 as isize))..], | ||
| 390 | + &x[at(-(t1b as isize))..], | ||
| 391 | + nn, | ||
| 392 | + ); | ||
| 393 | + let xy_k = half32(xy_a + xy2); | ||
| 394 | + let yy_k = half32(yy_lookup[t1 as usize] + yy_lookup[t1b as usize]); | ||
| 395 | + let g1 = compute_pitch_gain(xy_k, xx, yy_k); | ||
| 396 | + let cont = if (t1 - prev_period).abs() <= 1 { | ||
| 397 | + prev_gain | ||
| 398 | + } else if (t1 - prev_period).abs() <= 2 && 5 * k * k < t0v { | ||
| 399 | + half16(prev_gain) | ||
| 400 | + } else { | ||
| 401 | + 0.0 | ||
| 402 | + }; | ||
| 403 | + let mut thresh = max_f(0.3f32, 0.7f32 * g0 - cont); | ||
| 404 | + if t1 < 3 * minperiod { | ||
| 405 | + thresh = max_f(0.4f32, 0.85f32 * g0 - cont); | ||
| 406 | + } else if t1 < 2 * minperiod { | ||
| 407 | + thresh = max_f(0.5f32, 0.9f32 * g0 - cont); | ||
| 408 | + } | ||
| 409 | + if g1 > thresh { | ||
| 410 | + best_xy = xy_k; | ||
| 411 | + best_yy = yy_k; | ||
| 412 | + t = t1; | ||
| 413 | + g = g1; | ||
| 414 | + } | ||
| 415 | + } | ||
| 416 | + if t < minperiod * 2 { | ||
| 417 | + let t1 = t * 5 / 8; | ||
| 418 | + let t2 = t * 6 / 8; | ||
| 419 | + let (xy_a, xy2) = dual_inner_prod( | ||
| 420 | + &x[at(0)..], | ||
| 421 | + &x[at(-(t1 as isize))..], | ||
| 422 | + &x[at(-(t2 as isize))..], | ||
| 423 | + nn, | ||
| 424 | + ); | ||
| 425 | + let g1 = compute_pitch_gain(xy_a, xx, yy_lookup[t1 as usize]); | ||
| 426 | + let g2 = compute_pitch_gain(xy2, xx, yy_lookup[t2 as usize]); | ||
| 427 | + if g1 >= g || g2 >= g { | ||
| 428 | + g = 0.0; | ||
| 429 | + } | ||
| 430 | + } | ||
| 431 | + best_xy = max_f(0.0, best_xy); | ||
| 432 | + let mut pg = if best_yy <= best_xy { | ||
| 433 | + 1.0f32 | ||
| 434 | + } else { | ||
| 435 | + best_xy / (best_yy + 1.0) | ||
| 436 | + }; | ||
| 437 | + let mut xcorr = [0f32; 3]; | ||
| 438 | + for k in 0..3 { | ||
| 439 | + let off = at(-(t as isize) - k as isize + 1); | ||
| 440 | + xcorr[k] = celt_inner_prod(&x[at(0)..], &x[off..], nn); | ||
| 441 | + } | ||
| 442 | + let offset = if (xcorr[2] - xcorr[0]) > 0.7f32 * (xcorr[1] - xcorr[0]) { | ||
| 443 | + 1 | ||
| 444 | + } else if (xcorr[0] - xcorr[2]) > 0.7f32 * (xcorr[1] - xcorr[2]) { | ||
| 445 | + -1 | ||
| 446 | + } else { | ||
| 447 | + 0 | ||
| 448 | + }; | ||
| 449 | + if pg > g { | ||
| 450 | + pg = g; | ||
| 451 | + } | ||
| 452 | + *t0 = 2 * t + offset; | ||
| 453 | + if *t0 < minperiod0 { | ||
| 454 | + *t0 = minperiod0; | ||
| 455 | + } | ||
| 456 | + pg | ||
| 457 | +} | ||
| 458 | + | ||
| 459 | +/// `comb_filter` (celt.c, float, no QEXT) with distinct buffers: C `y` is | ||
| 460 | +/// `y[0..n]`, C `x[i]` is `x[x_off + i]` (read down to `x_off - T - 2`). | ||
| 461 | +pub(crate) fn comb_filter( | ||
| 462 | + y: &mut [f32], | ||
| 463 | + x: &[f32], | ||
| 464 | + x_off: usize, | ||
| 465 | + t0: i32, | ||
| 466 | + t1: i32, | ||
| 467 | + n: usize, | ||
| 468 | + g0: f32, | ||
| 469 | + g1: f32, | ||
| 470 | + tapset0: i32, | ||
| 471 | + tapset1: i32, | ||
| 472 | + window: &[f32], | ||
| 473 | + overlap: usize, | ||
| 474 | +) { | ||
| 475 | + if g0 == 0.0 && g1 == 0.0 { | ||
| 476 | + y[..n].copy_from_slice(&x[x_off..x_off + n]); | ||
| 477 | + return; | ||
| 478 | + } | ||
| 479 | + let t0 = t0.max(COMBFILTER_MINPERIOD as i32) as isize; | ||
| 480 | + let t1 = t1.max(COMBFILTER_MINPERIOD as i32) as isize; | ||
| 481 | + let ts0 = tapset0 as usize; | ||
| 482 | + let ts1 = tapset1 as usize; | ||
| 483 | + let g00 = g0 * COMB_GAINS[ts0][0]; | ||
| 484 | + let g01 = g0 * COMB_GAINS[ts0][1]; | ||
| 485 | + let g02 = g0 * COMB_GAINS[ts0][2]; | ||
| 486 | + let g10 = g1 * COMB_GAINS[ts1][0]; | ||
| 487 | + let g11 = g1 * COMB_GAINS[ts1][1]; | ||
| 488 | + let g12 = g1 * COMB_GAINS[ts1][2]; | ||
| 489 | + let p = |d: isize| (x_off as isize + d) as usize; | ||
| 490 | + let mut x1 = x[p(-t1 + 1)]; | ||
| 491 | + let mut x2 = x[p(-t1)]; | ||
| 492 | + let mut x3 = x[p(-t1 - 1)]; | ||
| 493 | + let mut x4 = x[p(-t1 - 2)]; | ||
| 494 | + let mut overlap = overlap; | ||
| 495 | + if g0 == g1 && t0 == t1 && tapset0 == tapset1 { | ||
| 496 | + overlap = 0; | ||
| 497 | + } | ||
| 498 | + for i in 0..overlap { | ||
| 499 | + let ii = i as isize; | ||
| 500 | + let x0 = x[p(ii - t1 + 2)]; | ||
| 501 | + let f = window[i] * window[i]; | ||
| 502 | + let a0 = (1.0f32 - f) * g00; | ||
| 503 | + let a1 = (1.0f32 - f) * g01; | ||
| 504 | + let a2 = (1.0f32 - f) * g02; | ||
| 505 | + let b0 = f * g10; | ||
| 506 | + let b1 = f * g11; | ||
| 507 | + let b2 = f * g12; | ||
| 508 | + y[i] = x[p(ii)] | ||
| 509 | + + a0 * x[p(ii - t0)] | ||
| 510 | + + a1 * (x[p(ii - t0 + 1)] + x[p(ii - t0 - 1)]) | ||
| 511 | + + a2 * (x[p(ii - t0 + 2)] + x[p(ii - t0 - 2)]) | ||
| 512 | + + b0 * x2 | ||
| 513 | + + b1 * (x1 + x3) | ||
| 514 | + + b2 * (x0 + x4); | ||
| 515 | + x4 = x3; | ||
| 516 | + x3 = x2; | ||
| 517 | + x2 = x1; | ||
| 518 | + x1 = x0; | ||
| 519 | + } | ||
| 520 | + if g1 == 0.0 { | ||
| 521 | + y[overlap..n].copy_from_slice(&x[x_off + overlap..x_off + n]); | ||
| 522 | + return; | ||
| 523 | + } | ||
| 524 | + comb_filter_const( | ||
| 525 | + &mut y[overlap..], | ||
| 526 | + x, | ||
| 527 | + x_off + overlap, | ||
| 528 | + t1, | ||
| 529 | + n - overlap, | ||
| 530 | + g10, | ||
| 531 | + g11, | ||
| 532 | + g12, | ||
| 533 | + ); | ||
| 534 | +} | ||
| 535 | + | ||
| 536 | +fn comb_filter_const( | ||
| 537 | + y: &mut [f32], | ||
| 538 | + x: &[f32], | ||
| 539 | + x_off: usize, | ||
| 540 | + t: isize, | ||
| 541 | + n: usize, | ||
| 542 | + g10: f32, | ||
| 543 | + g11: f32, | ||
| 544 | + g12: f32, | ||
| 545 | +) { | ||
| 546 | + let p = |d: isize| (x_off as isize + d) as usize; | ||
| 547 | + let mut x4 = x[p(-t - 2)]; | ||
| 548 | + let mut x3 = x[p(-t - 1)]; | ||
| 549 | + let mut x2 = x[p(-t)]; | ||
| 550 | + let mut x1 = x[p(-t + 1)]; | ||
| 551 | + for i in 0..n { | ||
| 552 | + let ii = i as isize; | ||
| 553 | + let x0 = x[p(ii - t + 2)]; | ||
| 554 | + y[i] = x[p(ii)] + g10 * x2 + g11 * (x1 + x3) + g12 * (x0 + x4); | ||
| 555 | + x4 = x3; | ||
| 556 | + x3 = x2; | ||
| 557 | + x2 = x1; | ||
| 558 | + x1 = x0; | ||
| 559 | + } | ||
| 560 | +} | ||
| 561 | + | ||
| 562 | +/// `celt_inner_prod_c`. | ||
| 563 | +pub(crate) fn celt_inner_prod(x: &[f32], y: &[f32], n: usize) -> f32 { | ||
| 564 | + let mut xy = 0f32; | ||
| 565 | + for i in 0..n { | ||
| 566 | + xy += x[i] * y[i]; | ||
| 567 | + } | ||
| 568 | + xy | ||
| 569 | +} | ||
crates/ec-opus/src/celt_flp/quant_bands.rsadded+358 -0
| @@ -0,0 +1,358 @@ | |||
| 1 | +use super::celt_log2; | ||
| 2 | +use crate::celt::{ | ||
| 3 | + BETA_COEF, BETA_INTRA, E_MEANS, E_PROB_MODEL, MAX_FINE_BITS, NB_BANDS, PRED_COEF, | ||
| 4 | + SMALL_ENERGY_ICDF, | ||
| 5 | +}; | ||
| 6 | +use crate::range::RangeEncoder; | ||
| 7 | + | ||
| 8 | +const LAPLACE_MINP: u32 = 1; | ||
| 9 | +const LAPLACE_NMIN: u32 = 16; | ||
| 10 | +const MAX_FRAME_BYTES: usize = 1275; | ||
| 11 | + | ||
| 12 | +fn laplace_get_freq1(fs0: u32, decay: i32) -> u32 { | ||
| 13 | + let ft = 32768 - LAPLACE_MINP * (2 * LAPLACE_NMIN) - fs0; | ||
| 14 | + ft.wrapping_mul((16384 - decay) as u32) >> 15 | ||
| 15 | +} | ||
| 16 | + | ||
| 17 | +fn laplace_encode(enc: &mut RangeEncoder, value: &mut i32, fs: u32, decay: i32) { | ||
| 18 | + let mut fs = fs; | ||
| 19 | + let mut fl: u32 = 0; | ||
| 20 | + let mut val = *value; | ||
| 21 | + if val != 0 { | ||
| 22 | + let s: i32 = -((val < 0) as i32); | ||
| 23 | + val = (val + s) ^ s; | ||
| 24 | + fl = fs; | ||
| 25 | + fs = laplace_get_freq1(fs, decay); | ||
| 26 | + let mut i: i32 = 1; | ||
| 27 | + while fs > 0 && i < val { | ||
| 28 | + fs *= 2; | ||
| 29 | + fl += fs + 2 * LAPLACE_MINP; | ||
| 30 | + fs = (fs * decay as u32) >> 15; | ||
| 31 | + i += 1; | ||
| 32 | + } | ||
| 33 | + if fs == 0 { | ||
| 34 | + let ndi_max = | ||
| 35 | + ((32768u32.wrapping_sub(fl).wrapping_add(LAPLACE_MINP - 1)) as i32 - s) >> 1; | ||
| 36 | + let di = (val - i).min(ndi_max - 1); | ||
| 37 | + fl = fl.wrapping_add((2 * di + 1 + s) as u32 * LAPLACE_MINP); | ||
| 38 | + fs = LAPLACE_MINP.min(32768u32.wrapping_sub(fl)); | ||
| 39 | + *value = (i + di + s) ^ s; | ||
| 40 | + } else { | ||
| 41 | + fs += LAPLACE_MINP; | ||
| 42 | + if s == 0 { | ||
| 43 | + fl += fs; | ||
| 44 | + } | ||
| 45 | + } | ||
| 46 | + } | ||
| 47 | + enc.encode_bin(fl, fl + fs, 15); | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +fn loss_distortion( | ||
| 51 | + e_bands: &[f32], | ||
| 52 | + old_e_bands: &[f32], | ||
| 53 | + start: usize, | ||
| 54 | + end: usize, | ||
| 55 | + c: usize, | ||
| 56 | +) -> f32 { | ||
| 57 | + let mut dist = 0f32; | ||
| 58 | + for ch in 0..c { | ||
| 59 | + for i in start..end { | ||
| 60 | + let d = e_bands[i + ch * NB_BANDS] - old_e_bands[i + ch * NB_BANDS]; | ||
| 61 | + dist += d * d; | ||
| 62 | + } | ||
| 63 | + } | ||
| 64 | + if 200.0 < dist { 200.0 } else { dist } | ||
| 65 | +} | ||
| 66 | + | ||
| 67 | +fn quant_coarse_energy_impl( | ||
| 68 | + start: usize, | ||
| 69 | + end: usize, | ||
| 70 | + e_bands: &[f32], | ||
| 71 | + old_e_bands: &mut [f32], | ||
| 72 | + budget: i32, | ||
| 73 | + mut tell: i32, | ||
| 74 | + prob_model: &[u8; 42], | ||
| 75 | + error: &mut [f32], | ||
| 76 | + enc: &mut RangeEncoder, | ||
| 77 | + c: usize, | ||
| 78 | + lm: usize, | ||
| 79 | + intra: bool, | ||
| 80 | + max_decay: f32, | ||
| 81 | + lfe: bool, | ||
| 82 | +) -> i32 { | ||
| 83 | + let mut badness = 0i32; | ||
| 84 | + let mut prev = [0f32; 2]; | ||
| 85 | + if tell + 3 <= budget { | ||
| 86 | + enc.enc_bit_logp(intra, 3); | ||
| 87 | + } | ||
| 88 | + let (coef, beta) = if intra { | ||
| 89 | + (0f32, BETA_INTRA) | ||
| 90 | + } else { | ||
| 91 | + (PRED_COEF[lm], BETA_COEF[lm]) | ||
| 92 | + }; | ||
| 93 | + for i in start..end { | ||
| 94 | + for ch in 0..c { | ||
| 95 | + let idx = i + ch * NB_BANDS; | ||
| 96 | + let x = e_bands[idx]; | ||
| 97 | + let old_e = if -9.0f32 > old_e_bands[idx] { | ||
| 98 | + -9.0f32 | ||
| 99 | + } else { | ||
| 100 | + old_e_bands[idx] | ||
| 101 | + }; | ||
| 102 | + let f = x - coef * old_e - prev[ch]; | ||
| 103 | + let mut qi = ((0.5f32 + f) as f64).floor() as i32; | ||
| 104 | + let raw_old = if -28.0f32 > old_e_bands[idx] { | ||
| 105 | + -28.0f32 | ||
| 106 | + } else { | ||
| 107 | + old_e_bands[idx] | ||
| 108 | + }; | ||
| 109 | + let decay_bound = raw_old - max_decay; | ||
| 110 | + if qi < 0 && x < decay_bound { | ||
| 111 | + qi += (decay_bound - x) as i32; | ||
| 112 | + if qi > 0 { | ||
| 113 | + qi = 0; | ||
| 114 | + } | ||
| 115 | + } | ||
| 116 | + let qi0 = qi; | ||
| 117 | + tell = enc.tell() as i32; | ||
| 118 | + let bits_left = budget - tell - 3 * c as i32 * (end - i) as i32; | ||
| 119 | + if i != start && bits_left < 30 { | ||
| 120 | + if bits_left < 24 { | ||
| 121 | + qi = qi.min(1); | ||
| 122 | + } | ||
| 123 | + if bits_left < 16 { | ||
| 124 | + qi = qi.max(-1); | ||
| 125 | + } | ||
| 126 | + } | ||
| 127 | + if lfe && i >= 2 { | ||
| 128 | + qi = qi.min(0); | ||
| 129 | + } | ||
| 130 | + if budget - tell >= 15 { | ||
| 131 | + let pi = 2 * i.min(20); | ||
| 132 | + laplace_encode( | ||
| 133 | + enc, | ||
| 134 | + &mut qi, | ||
| 135 | + (prob_model[pi] as u32) << 7, | ||
| 136 | + (prob_model[pi + 1] as i32) << 6, | ||
| 137 | + ); | ||
| 138 | + } else if budget - tell >= 2 { | ||
| 139 | + qi = qi.clamp(-1, 1); | ||
| 140 | + let k = (2 * qi) ^ if qi < 0 { -1 } else { 0 }; | ||
| 141 | + enc.enc_icdf(k as usize, &SMALL_ENERGY_ICDF, 2); | ||
| 142 | + } else if budget - tell >= 1 { | ||
| 143 | + qi = qi.min(0); | ||
| 144 | + enc.enc_bit_logp(qi != 0, 1); | ||
| 145 | + } else { | ||
| 146 | + qi = -1; | ||
| 147 | + } | ||
| 148 | + error[idx] = f - qi as f32; | ||
| 149 | + badness += (qi0 - qi).abs(); | ||
| 150 | + let q = qi as f32; | ||
| 151 | + old_e_bands[idx] = coef * old_e + prev[ch] + q; | ||
| 152 | + prev[ch] = prev[ch] + q - beta * q; | ||
| 153 | + } | ||
| 154 | + } | ||
| 155 | + if lfe { 0 } else { badness } | ||
| 156 | +} | ||
| 157 | + | ||
| 158 | +/// `quant_coarse_energy`. | ||
| 159 | +pub(crate) fn quant_coarse_energy( | ||
| 160 | + start: usize, | ||
| 161 | + end: usize, | ||
| 162 | + eff_end: usize, | ||
| 163 | + e_bands: &[f32], | ||
| 164 | + old_e_bands: &mut [f32], | ||
| 165 | + budget: u32, | ||
| 166 | + error: &mut [f32], | ||
| 167 | + enc: &mut RangeEncoder, | ||
| 168 | + c: usize, | ||
| 169 | + lm: usize, | ||
| 170 | + nb_available_bytes: i32, | ||
| 171 | + force_intra: bool, | ||
| 172 | + delayed_intra: &mut f32, | ||
| 173 | + two_pass: bool, | ||
| 174 | + loss_rate: i32, | ||
| 175 | + lfe: bool, | ||
| 176 | +) { | ||
| 177 | + let n = c * NB_BANDS; | ||
| 178 | + let mut two_pass = two_pass; | ||
| 179 | + let mut intra = force_intra | ||
| 180 | + || (!two_pass | ||
| 181 | + && *delayed_intra > (2 * c * (end - start)) as f32 | ||
| 182 | + && nb_available_bytes > ((end - start) * c) as i32); | ||
| 183 | + let intra_bias = | ||
| 184 | + ((budget as f32 * *delayed_intra * loss_rate as f32) / (c * 512) as f32) as i32; | ||
| 185 | + let new_distortion = loss_distortion(e_bands, old_e_bands, start, eff_end, c); | ||
| 186 | + | ||
| 187 | + let tell = enc.tell(); | ||
| 188 | + if tell + 3 > budget { | ||
| 189 | + two_pass = false; | ||
| 190 | + intra = false; | ||
| 191 | + } | ||
| 192 | + | ||
| 193 | + let mut max_decay = 16f32; | ||
| 194 | + if end - start > 10 { | ||
| 195 | + let v = 0.125f32 * nb_available_bytes as f32; | ||
| 196 | + max_decay = if max_decay < v { max_decay } else { v }; | ||
| 197 | + } | ||
| 198 | + if lfe { | ||
| 199 | + max_decay = 3.0; | ||
| 200 | + } | ||
| 201 | + | ||
| 202 | + let start_state = enc.snapshot(); | ||
| 203 | + let nstart = enc.front_offs(); | ||
| 204 | + let mut old_intra = [0f32; 2 * NB_BANDS]; | ||
| 205 | + let mut err_intra = [0f32; 2 * NB_BANDS]; | ||
| 206 | + old_intra[..n].copy_from_slice(&old_e_bands[..n]); | ||
| 207 | + | ||
| 208 | + let mut badness1 = 0; | ||
| 209 | + if two_pass || intra { | ||
| 210 | + badness1 = quant_coarse_energy_impl( | ||
| 211 | + start, | ||
| 212 | + end, | ||
| 213 | + e_bands, | ||
| 214 | + &mut old_intra, | ||
| 215 | + budget as i32, | ||
| 216 | + tell as i32, | ||
| 217 | + &E_PROB_MODEL[lm][1], | ||
| 218 | + &mut err_intra, | ||
| 219 | + enc, | ||
| 220 | + c, | ||
| 221 | + lm, | ||
| 222 | + true, | ||
| 223 | + max_decay, | ||
| 224 | + lfe, | ||
| 225 | + ); | ||
| 226 | + } | ||
| 227 | + | ||
| 228 | + if !intra { | ||
| 229 | + let tell_intra = enc.tell_frac() as i32; | ||
| 230 | + let intra_state = enc.snapshot(); | ||
| 231 | + let nintra = enc.front_offs(); | ||
| 232 | + let intra_len = nintra - nstart; | ||
| 233 | + let mut intra_bits = [0u8; MAX_FRAME_BYTES]; | ||
| 234 | + intra_bits[..intra_len].copy_from_slice(&enc.front()[nstart..nintra]); | ||
| 235 | + | ||
| 236 | + enc.restore(&start_state); | ||
| 237 | + let badness2 = quant_coarse_energy_impl( | ||
| 238 | + start, | ||
| 239 | + end, | ||
| 240 | + e_bands, | ||
| 241 | + old_e_bands, | ||
| 242 | + budget as i32, | ||
| 243 | + tell as i32, | ||
| 244 | + &E_PROB_MODEL[lm][0], | ||
| 245 | + error, | ||
| 246 | + enc, | ||
| 247 | + c, | ||
| 248 | + lm, | ||
| 249 | + false, | ||
| 250 | + max_decay, | ||
| 251 | + lfe, | ||
| 252 | + ); | ||
| 253 | + | ||
| 254 | + if two_pass | ||
| 255 | + && (badness1 < badness2 | ||
| 256 | + || (badness1 == badness2 && enc.tell_frac() as i32 + intra_bias > tell_intra)) | ||
| 257 | + { | ||
| 258 | + enc.restore(&intra_state); | ||
| 259 | + enc.front_write(nstart, &intra_bits[..intra_len]); | ||
| 260 | + old_e_bands[..n].copy_from_slice(&old_intra[..n]); | ||
| 261 | + error[..n].copy_from_slice(&err_intra[..n]); | ||
| 262 | + intra = true; | ||
| 263 | + } | ||
| 264 | + } else { | ||
| 265 | + old_e_bands[..n].copy_from_slice(&old_intra[..n]); | ||
| 266 | + error[..n].copy_from_slice(&err_intra[..n]); | ||
| 267 | + } | ||
| 268 | + | ||
| 269 | + if intra { | ||
| 270 | + *delayed_intra = new_distortion; | ||
| 271 | + } else { | ||
| 272 | + *delayed_intra = PRED_COEF[lm] * PRED_COEF[lm] * *delayed_intra + new_distortion; | ||
| 273 | + } | ||
| 274 | +} | ||
| 275 | + | ||
| 276 | +/// `quant_fine_energy` as celt_encode_with_ec calls it without QEXT (`prev_quant` NULL). | ||
| 277 | +pub(crate) fn quant_fine_energy( | ||
| 278 | + start: usize, | ||
| 279 | + end: usize, | ||
| 280 | + old_e_bands: &mut [f32], | ||
| 281 | + error: &mut [f32], | ||
| 282 | + fine_quant: &[i32], | ||
| 283 | + enc: &mut RangeEncoder, | ||
| 284 | + c: usize, | ||
| 285 | +) { | ||
| 286 | + for i in start..end { | ||
| 287 | + let fq = fine_quant[i]; | ||
| 288 | + if fq <= 0 { | ||
| 289 | + continue; | ||
| 290 | + } | ||
| 291 | + if enc.tell() as i32 + c as i32 * fq > enc.storage() as i32 * 8 { | ||
| 292 | + continue; | ||
| 293 | + } | ||
| 294 | + let extra = 1i32 << fq; | ||
| 295 | + for ch in 0..c { | ||
| 296 | + let idx = i + ch * NB_BANDS; | ||
| 297 | + let q2 = (((error[idx] + 0.5f32) * extra as f32) as f64).floor() as i32; | ||
| 298 | + let q2 = q2.min(extra - 1).max(0); | ||
| 299 | + enc.enc_bits(q2 as u32, fq as u32); | ||
| 300 | + let offset = (q2 as f32 + 0.5) * (1 << (14 - fq)) as f32 * (1.0f32 / 16384.0) - 0.5; | ||
| 301 | + old_e_bands[idx] += offset; | ||
| 302 | + error[idx] -= offset; | ||
| 303 | + } | ||
| 304 | + } | ||
| 305 | +} | ||
| 306 | + | ||
| 307 | +/// `quant_energy_finalise`. | ||
| 308 | +pub(crate) fn quant_energy_finalise( | ||
| 309 | + start: usize, | ||
| 310 | + end: usize, | ||
| 311 | + old_e_bands: &mut [f32], | ||
| 312 | + error: &mut [f32], | ||
| 313 | + fine_quant: &[i32], | ||
| 314 | + fine_priority: &[i32], | ||
| 315 | + bits_left: i32, | ||
| 316 | + enc: &mut RangeEncoder, | ||
| 317 | + c: usize, | ||
| 318 | +) { | ||
| 319 | + let mut bits_left = bits_left; | ||
| 320 | + for prio in 0..2 { | ||
| 321 | + for i in start..end { | ||
| 322 | + if bits_left < c as i32 { | ||
| 323 | + break; | ||
| 324 | + } | ||
| 325 | + if fine_quant[i] >= MAX_FINE_BITS || fine_priority[i] != prio { | ||
| 326 | + continue; | ||
| 327 | + } | ||
| 328 | + for ch in 0..c { | ||
| 329 | + let idx = i + ch * NB_BANDS; | ||
| 330 | + let q2: u32 = if error[idx] < 0.0 { 0 } else { 1 }; | ||
| 331 | + enc.enc_bits(q2, 1); | ||
| 332 | + let offset = | ||
| 333 | + (q2 as f32 - 0.5) * (1 << (14 - fine_quant[i] - 1)) as f32 * (1.0f32 / 16384.0); | ||
| 334 | + old_e_bands[idx] += offset; | ||
| 335 | + error[idx] -= offset; | ||
| 336 | + bits_left -= 1; | ||
| 337 | + } | ||
| 338 | + } | ||
| 339 | + } | ||
| 340 | +} | ||
| 341 | + | ||
| 342 | +/// `amp2Log2`; `band_e`/`band_log_e` are `c * 21`. | ||
| 343 | +pub(crate) fn amp2log2( | ||
| 344 | + eff_end: usize, | ||
| 345 | + end: usize, | ||
| 346 | + band_e: &[f32], | ||
| 347 | + band_log_e: &mut [f32], | ||
| 348 | + c: usize, | ||
| 349 | +) { | ||
| 350 | + for ch in 0..c { | ||
| 351 | + for i in 0..eff_end { | ||
| 352 | + band_log_e[i + ch * NB_BANDS] = celt_log2(band_e[i + ch * NB_BANDS]) - E_MEANS[i]; | ||
| 353 | + } | ||
| 354 | + for i in eff_end..end { | ||
| 355 | + band_log_e[ch * NB_BANDS + i] = -14.0; | ||
| 356 | + } | ||
| 357 | + } | ||
| 358 | +} | ||
crates/ec-opus/src/celt_flp/tables.rsadded+2501 -0
Diff too large; view file
| @@ -0,0 +1,2501 @@ | |||
| 1 | +/// One `kiss_fft_state` of the static 48 kHz mode (nfft 480, 240, 120, 60). | ||
| 2 | +pub(crate) struct FftState { | ||
| 3 | + pub(crate) scale: f32, | ||
| 4 | + pub(crate) shift: i32, | ||
| 5 | + pub(crate) factors: [i16; 16], | ||
| 6 | + pub(crate) bitrev: &'static [i16], | ||
| 7 | +} | ||
| 8 | + | ||
| 9 | +/// `window120`. | ||
| 10 | +pub(crate) static WINDOW120: [f32; 120] = [ | ||
| 11 | + 6.7286966e-05, | ||
| 12 | + 0.00060551348, | ||
| 13 | + 0.0016815970, | ||
| 14 | + 0.0032947962, | ||
| 15 | + 0.0054439943, | ||
| 16 | + 0.0081276923, | ||
| 17 | + 0.011344001, | ||
| 18 | + 0.015090633, | ||
| 19 | + 0.019364886, | ||
| 20 | + 0.024163635, | ||
| 21 | + 0.029483315, | ||
| 22 | + 0.035319905, | ||
| 23 | + 0.041668911, | ||
| 24 | + 0.048525347, | ||
| 25 | + 0.055883718, | ||
| 26 | + 0.063737999, | ||
| 27 | + 0.072081616, | ||
| 28 | + 0.080907428, | ||
| 29 | + 0.090207705, | ||
| 30 | + 0.099974111, | ||
| 31 | + 0.11019769, | ||
| 32 | + 0.12086883, | ||
| 33 | + 0.13197729, | ||
| 34 | + 0.14351214, | ||
| 35 | + 0.15546177, | ||
| 36 | + 0.16781389, | ||
| 37 | + 0.18055550, | ||
| 38 | + 0.19367290, | ||
| 39 | + 0.20715171, | ||
| 40 | + 0.22097682, | ||
| 41 | + 0.23513243, | ||
| 42 | + 0.24960208, | ||
| 43 | + 0.26436860, | ||
| 44 | + 0.27941419, | ||
| 45 | + 0.29472040, | ||
| 46 | + 0.31026818, | ||
| 47 | + 0.32603788, | ||
| 48 | + 0.34200931, | ||
| 49 | + 0.35816177, | ||
| 50 | + 0.37447407, | ||
| 51 | + 0.39092462, | ||
| 52 | + 0.40749142, | ||
| 53 | + 0.42415215, | ||
| 54 | + 0.44088423, | ||
| 55 | + 0.45766484, | ||
| 56 | + 0.47447104, | ||
| 57 | + 0.49127978, | ||
| 58 | + 0.50806798, | ||
| 59 | + 0.52481261, | ||
| 60 | + 0.54149077, | ||
| 61 | + 0.55807973, | ||
| 62 | + 0.57455701, | ||
| 63 | + 0.59090049, | ||
| 64 | + 0.60708841, | ||
| 65 | + 0.62309951, | ||
| 66 | + 0.63891306, | ||
| 67 | + 0.65450896, | ||
| 68 | + 0.66986776, | ||
| 69 | + 0.68497077, | ||
| 70 | + 0.69980010, | ||
| 71 | + 0.71433873, | ||
| 72 | + 0.72857055, | ||
| 73 | + 0.74248043, | ||
| 74 | + 0.75605425, | ||
| 75 | + 0.76927895, | ||
| 76 | + 0.78214257, | ||
| 77 | + 0.79463430, | ||
| 78 | + 0.80674445, | ||
| 79 | + 0.81846456, | ||
| 80 | + 0.82978733, | ||
| 81 | + 0.84070669, | ||
| 82 | + 0.85121779, | ||
| 83 | + 0.86131698, | ||
| 84 | + 0.87100183, | ||
| 85 | + 0.88027111, | ||
| 86 | + 0.88912479, | ||
| 87 | + 0.89756398, | ||
| 88 | + 0.90559094, | ||
| 89 | + 0.91320904, | ||
| 90 | + 0.92042270, | ||
| 91 | + 0.92723738, | ||
| 92 | + 0.93365955, | ||
| 93 | + 0.93969656, | ||
| 94 | + 0.94535671, | ||
| 95 | + 0.95064907, | ||
| 96 | + 0.95558353, | ||
| 97 | + 0.96017067, | ||
| 98 | + 0.96442171, | ||
| 99 | + 0.96834849, | ||
| 100 | + 0.97196334, | ||
| 101 | + 0.97527906, | ||
| 102 | + 0.97830883, | ||
| 103 | + 0.98106616, | ||
| 104 | + 0.98356480, | ||
| 105 | + 0.98581869, | ||
| 106 | + 0.98784191, | ||
| 107 | + 0.98964856, | ||
| 108 | + 0.99125274, | ||
| 109 | + 0.99266849, | ||
| 110 | + 0.99390969, | ||
| 111 | + 0.99499004, | ||
| 112 | + 0.99592297, | ||
| 113 | + 0.99672162, | ||
| 114 | + 0.99739874, | ||
| 115 | + 0.99796667, | ||
| 116 | + 0.99843728, | ||
| 117 | + 0.99882195, | ||
| 118 | + 0.99913147, | ||
| 119 | + 0.99937606, | ||
| 120 | + 0.99956527, | ||
| 121 | + 0.99970802, | ||
| 122 | + 0.99981248, | ||
| 123 | + 0.99988613, | ||
| 124 | + 0.99993565, | ||
| 125 | + 0.99996697, | ||
| 126 | + 0.99998518, | ||
| 127 | + 0.99999457, | ||
| 128 | + 0.99999859, | ||
| 129 | + 0.99999982, | ||
| 130 | + 1.0000000, | ||
| 131 | +]; | ||
| 132 | +/// `fft_twiddles48000_960`. | ||
| 133 | +pub(crate) static FFT_TWIDDLES: [[f32; 2]; 480] = [ | ||
| 134 | + [1.0000000, -0.0000000], | ||
| 135 | + [0.99991433, -0.013089596], | ||
| 136 | + [0.99965732, -0.026176948], | ||
| 137 | + [0.99922904, -0.039259816], | ||
| 138 | + [0.99862953, -0.052335956], | ||
| 139 | + [0.99785892, -0.065403129], | ||
| 140 | + [0.99691733, -0.078459096], | ||
| 141 | + [0.99580493, -0.091501619], | ||
| 142 | + [0.99452190, -0.10452846], | ||
| 143 | + [0.99306846, -0.11753740], | ||
| 144 | + [0.99144486, -0.13052619], | ||
| 145 | + [0.98965139, -0.14349262], | ||
| 146 | + [0.98768834, -0.15643447], | ||
| 147 | + [0.98555606, -0.16934950], | ||
| 148 | + [0.98325491, -0.18223553], | ||
| 149 | + [0.98078528, -0.19509032], | ||
| 150 | + [0.97814760, -0.20791169], | ||
| 151 | + [0.97534232, -0.22069744], | ||
| 152 | + [0.97236992, -0.23344536], | ||
| 153 | + [0.96923091, -0.24615329], | ||
| 154 | + [0.96592583, -0.25881905], | ||
| 155 | + [0.96245524, -0.27144045], | ||
| 156 | + [0.95881973, -0.28401534], | ||
| 157 | + [0.95501994, -0.29654157], | ||
| 158 | + [0.95105652, -0.30901699], | ||
| 159 | + [0.94693013, -0.32143947], | ||
| 160 | + [0.94264149, -0.33380686], | ||
| 161 | + [0.93819134, -0.34611706], | ||
| 162 | + [0.93358043, -0.35836795], | ||
| 163 | + [0.92880955, -0.37055744], | ||
| 164 | + [0.92387953, -0.38268343], | ||
| 165 | + [0.91879121, -0.39474386], | ||
| 166 | + [0.91354546, -0.40673664], | ||
| 167 | + [0.90814317, -0.41865974], | ||
| 168 | + [0.90258528, -0.43051110], | ||
| 169 | + [0.89687274, -0.44228869], | ||
| 170 | + [0.89100652, -0.45399050], | ||
| 171 | + [0.88498764, -0.46561452], | ||
| 172 | + [0.87881711, -0.47715876], | ||
| 173 | + [0.87249601, -0.48862124], | ||
| 174 | + [0.86602540, -0.50000000], | ||
| 175 | + [0.85940641, -0.51129309], | ||
| 176 | + [0.85264016, -0.52249856], | ||
| 177 | + [0.84572782, -0.53361452], | ||
| 178 | + [0.83867057, -0.54463904], | ||
| 179 | + [0.83146961, -0.55557023], | ||
| 180 | + [0.82412619, -0.56640624], | ||
| 181 | + [0.81664156, -0.57714519], | ||
| 182 | + [0.80901699, -0.58778525], | ||
| 183 | + [0.80125381, -0.59832460], | ||
| 184 | + [0.79335334, -0.60876143], | ||
| 185 | + [0.78531693, -0.61909395], | ||
| 186 | + [0.77714596, -0.62932039], | ||
| 187 | + [0.76884183, -0.63943900], | ||
| 188 | + [0.76040597, -0.64944805], | ||
| 189 | + [0.75183981, -0.65934582], | ||
| 190 | + [0.74314483, -0.66913061], | ||
| 191 | + [0.73432251, -0.67880075], | ||
| 192 | + [0.72537437, -0.68835458], | ||
| 193 | + [0.71630194, -0.69779046], | ||
| 194 | + [0.70710678, -0.70710678], | ||
| 195 | + [0.69779046, -0.71630194], | ||
| 196 | + [0.68835458, -0.72537437], | ||
| 197 | + [0.67880075, -0.73432251], | ||
| 198 | + [0.66913061, -0.74314483], | ||
| 199 | + [0.65934582, -0.75183981], | ||
| 200 | + [0.64944805, -0.76040597], | ||
| 201 | + [0.63943900, -0.76884183], | ||
| 202 | + [0.62932039, -0.77714596], | ||
| 203 | + [0.61909395, -0.78531693], | ||
| 204 | + [0.60876143, -0.79335334], | ||
| 205 | + [0.59832460, -0.80125381], | ||
| 206 | + [0.58778525, -0.80901699], | ||
| 207 | + [0.57714519, -0.81664156], | ||
| 208 | + [0.56640624, -0.82412619], | ||
| 209 | + [0.55557023, -0.83146961], | ||
| 210 | + [0.54463904, -0.83867057], | ||
| 211 | + [0.53361452, -0.84572782], | ||
| 212 | + [0.52249856, -0.85264016], | ||
| 213 | + [0.51129309, -0.85940641], | ||
| 214 | + [0.50000000, -0.86602540], | ||
| 215 | + [0.48862124, -0.87249601], | ||
| 216 | + [0.47715876, -0.87881711], | ||
| 217 | + [0.46561452, -0.88498764], | ||
| 218 | + [0.45399050, -0.89100652], | ||
| 219 | + [0.44228869, -0.89687274], | ||
| 220 | + [0.43051110, -0.90258528], | ||
| 221 | + [0.41865974, -0.90814317], | ||
| 222 | + [0.40673664, -0.91354546], | ||
| 223 | + [0.39474386, -0.91879121], | ||
| 224 | + [0.38268343, -0.92387953], | ||
| 225 | + [0.37055744, -0.92880955], | ||
| 226 | + [0.35836795, -0.93358043], | ||
| 227 | + [0.34611706, -0.93819134], | ||
| 228 | + [0.33380686, -0.94264149], | ||
| 229 | + [0.32143947, -0.94693013], | ||
| 230 | + [0.30901699, -0.95105652], | ||
| 231 | + [0.29654157, -0.95501994], | ||
| 232 | + [0.28401534, -0.95881973], | ||
| 233 | + [0.27144045, -0.96245524], | ||
| 234 | + [0.25881905, -0.96592583], | ||
| 235 | + [0.24615329, -0.96923091], | ||
| 236 | + [0.23344536, -0.97236992], | ||
| 237 | + [0.22069744, -0.97534232], | ||
| 238 | + [0.20791169, -0.97814760], | ||
| 239 | + [0.19509032, -0.98078528], | ||
| 240 | + [0.18223553, -0.98325491], | ||
| 241 | + [0.16934950, -0.98555606], | ||
| 242 | + [0.15643447, -0.98768834], | ||
| 243 | + [0.14349262, -0.98965139], | ||
| 244 | + [0.13052619, -0.99144486], | ||
| 245 | + [0.11753740, -0.99306846], | ||
| 246 | + [0.10452846, -0.99452190], | ||
| 247 | + [0.091501619, -0.99580493], | ||
| 248 | + [0.078459096, -0.99691733], | ||
| 249 | + [0.065403129, -0.99785892], | ||
| 250 | + [0.052335956, -0.99862953], | ||
| 251 | + [0.039259816, -0.99922904], | ||
| 252 | + [0.026176948, -0.99965732], | ||
| 253 | + [0.013089596, -0.99991433], | ||
| 254 | + [6.1232340e-17, -1.0000000], | ||
| 255 | + [-0.013089596, -0.99991433], | ||
| 256 | + [-0.026176948, -0.99965732], | ||
| 257 | + [-0.039259816, -0.99922904], | ||
| 258 | + [-0.052335956, -0.99862953], | ||
| 259 | + [-0.065403129, -0.99785892], | ||
| 260 | + [-0.078459096, -0.99691733], | ||
| 261 | + [-0.091501619, -0.99580493], | ||
| 262 | + [-0.10452846, -0.99452190], | ||
| 263 | + [-0.11753740, -0.99306846], | ||
| 264 | + [-0.13052619, -0.99144486], | ||
| 265 | + [-0.14349262, -0.98965139], | ||
| 266 | + [-0.15643447, -0.98768834], | ||
| 267 | + [-0.16934950, -0.98555606], | ||
| 268 | + [-0.18223553, -0.98325491], | ||
| 269 | + [-0.19509032, -0.98078528], | ||
| 270 | + [-0.20791169, -0.97814760], | ||
| 271 | + [-0.22069744, -0.97534232], | ||
| 272 | + [-0.23344536, -0.97236992], | ||
| 273 | + [-0.24615329, -0.96923091], | ||
| 274 | + [-0.25881905, -0.96592583], | ||
| 275 | + [-0.27144045, -0.96245524], | ||
| 276 | + [-0.28401534, -0.95881973], | ||
| 277 | + [-0.29654157, -0.95501994], | ||
| 278 | + [-0.30901699, -0.95105652], | ||
| 279 | + [-0.32143947, -0.94693013], | ||
| 280 | + [-0.33380686, -0.94264149], | ||
| 281 | + [-0.34611706, -0.93819134], | ||
| 282 | + [-0.35836795, -0.93358043], | ||
| 283 | + [-0.37055744, -0.92880955], | ||
| 284 | + [-0.38268343, -0.92387953], | ||
| 285 | + [-0.39474386, -0.91879121], | ||
| 286 | + [-0.40673664, -0.91354546], | ||
| 287 | + [-0.41865974, -0.90814317], | ||
| 288 | + [-0.43051110, -0.90258528], | ||
| 289 | + [-0.44228869, -0.89687274], | ||
| 290 | + [-0.45399050, -0.89100652], | ||
| 291 | + [-0.46561452, -0.88498764], | ||
| 292 | + [-0.47715876, -0.87881711], | ||
| 293 | + [-0.48862124, -0.87249601], | ||
| 294 | + [-0.50000000, -0.86602540], | ||
| 295 | + [-0.51129309, -0.85940641], | ||
| 296 | + [-0.52249856, -0.85264016], | ||
| 297 | + [-0.53361452, -0.84572782], | ||
| 298 | + [-0.54463904, -0.83867057], | ||
| 299 | + [-0.55557023, -0.83146961], | ||
| 300 | + [-0.56640624, -0.82412619], | ||
| 301 | + [-0.57714519, -0.81664156], | ||
| 302 | + [-0.58778525, -0.80901699], | ||
| 303 | + [-0.59832460, -0.80125381], | ||
| 304 | + [-0.60876143, -0.79335334], | ||
| 305 | + [-0.61909395, -0.78531693], | ||
| 306 | + [-0.62932039, -0.77714596], | ||
| 307 | + [-0.63943900, -0.76884183], | ||
| 308 | + [-0.64944805, -0.76040597], | ||
| 309 | + [-0.65934582, -0.75183981], | ||
| 310 | + [-0.66913061, -0.74314483], | ||
| 311 | + [-0.67880075, -0.73432251], | ||
| 312 | + [-0.68835458, -0.72537437], | ||
| 313 | + [-0.69779046, -0.71630194], | ||
| 314 | + [-0.70710678, -0.70710678], | ||
| 315 | + [-0.71630194, -0.69779046], | ||
| 316 | + [-0.72537437, -0.68835458], | ||
| 317 | + [-0.73432251, -0.67880075], | ||
| 318 | + [-0.74314483, -0.66913061], | ||
| 319 | + [-0.75183981, -0.65934582], | ||
| 320 | + [-0.76040597, -0.64944805], | ||
| 321 | + [-0.76884183, -0.63943900], | ||
| 322 | + [-0.77714596, -0.62932039], | ||
| 323 | + [-0.78531693, -0.61909395], | ||
| 324 | + [-0.79335334, -0.60876143], | ||
| 325 | + [-0.80125381, -0.59832460], | ||
| 326 | + [-0.80901699, -0.58778525], | ||
| 327 | + [-0.81664156, -0.57714519], | ||
| 328 | + [-0.82412619, -0.56640624], | ||
| 329 | + [-0.83146961, -0.55557023], | ||
| 330 | + [-0.83867057, -0.54463904], | ||
| 331 | + [-0.84572782, -0.53361452], | ||
| 332 | + [-0.85264016, -0.52249856], | ||
| 333 | + [-0.85940641, -0.51129309], | ||
| 334 | + [-0.86602540, -0.50000000], | ||
| 335 | + [-0.87249601, -0.48862124], | ||
| 336 | + [-0.87881711, -0.47715876], | ||
| 337 | + [-0.88498764, -0.46561452], | ||
| 338 | + [-0.89100652, -0.45399050], | ||
| 339 | + [-0.89687274, -0.44228869], | ||
| 340 | + [-0.90258528, -0.43051110], | ||
| 341 | + [-0.90814317, -0.41865974], | ||
| 342 | + [-0.91354546, -0.40673664], | ||
| 343 | + [-0.91879121, -0.39474386], | ||
| 344 | + [-0.92387953, -0.38268343], | ||
| 345 | + [-0.92880955, -0.37055744], | ||
| 346 | + [-0.93358043, -0.35836795], | ||
| 347 | + [-0.93819134, -0.34611706], | ||
| 348 | + [-0.94264149, -0.33380686], | ||
| 349 | + [-0.94693013, -0.32143947], | ||
| 350 | + [-0.95105652, -0.30901699], | ||
| 351 | + [-0.95501994, -0.29654157], | ||
| 352 | + [-0.95881973, -0.28401534], | ||
| 353 | + [-0.96245524, -0.27144045], | ||
| 354 | + [-0.96592583, -0.25881905], | ||
| 355 | + [-0.96923091, -0.24615329], | ||
| 356 | + [-0.97236992, -0.23344536], | ||
| 357 | + [-0.97534232, -0.22069744], | ||
| 358 | + [-0.97814760, -0.20791169], | ||
| 359 | + [-0.98078528, -0.19509032], | ||
| 360 | + [-0.98325491, -0.18223553], | ||
| 361 | + [-0.98555606, -0.16934950], | ||
| 362 | + [-0.98768834, -0.15643447], | ||
| 363 | + [-0.98965139, -0.14349262], | ||
| 364 | + [-0.99144486, -0.13052619], | ||
| 365 | + [-0.99306846, -0.11753740], | ||
| 366 | + [-0.99452190, -0.10452846], | ||
| 367 | + [-0.99580493, -0.091501619], | ||
| 368 | + [-0.99691733, -0.078459096], | ||
| 369 | + [-0.99785892, -0.065403129], | ||
| 370 | + [-0.99862953, -0.052335956], | ||
| 371 | + [-0.99922904, -0.039259816], | ||
| 372 | + [-0.99965732, -0.026176948], | ||
| 373 | + [-0.99991433, -0.013089596], | ||
| 374 | + [-1.0000000, -1.2246468e-16], | ||
| 375 | + [-0.99991433, 0.013089596], | ||
| 376 | + [-0.99965732, 0.026176948], | ||
| 377 | + [-0.99922904, 0.039259816], | ||
| 378 | + [-0.99862953, 0.052335956], | ||
| 379 | + [-0.99785892, 0.065403129], | ||
| 380 | + [-0.99691733, 0.078459096], | ||
| 381 | + [-0.99580493, 0.091501619], | ||
| 382 | + [-0.99452190, 0.10452846], | ||
| 383 | + [-0.99306846, 0.11753740], | ||
| 384 | + [-0.99144486, 0.13052619], | ||
| 385 | + [-0.98965139, 0.14349262], | ||
| 386 | + [-0.98768834, 0.15643447], | ||
| 387 | + [-0.98555606, 0.16934950], | ||
| 388 | + [-0.98325491, 0.18223553], | ||
| 389 | + [-0.98078528, 0.19509032], | ||
| 390 | + [-0.97814760, 0.20791169], | ||
| 391 | + [-0.97534232, 0.22069744], | ||
| 392 | + [-0.97236992, 0.23344536], | ||
| 393 | + [-0.96923091, 0.24615329], | ||
| 394 | + [-0.96592583, 0.25881905], | ||
| 395 | + [-0.96245524, 0.27144045], | ||
| 396 | + [-0.95881973, 0.28401534], | ||
| 397 | + [-0.95501994, 0.29654157], | ||
| 398 | + [-0.95105652, 0.30901699], | ||
| 399 | + [-0.94693013, 0.32143947], | ||
| 400 | + [-0.94264149, 0.33380686], | ||
| 401 | + [-0.93819134, 0.34611706], | ||
| 402 | + [-0.93358043, 0.35836795], | ||
| 403 | + [-0.92880955, 0.37055744], | ||
| 404 | + [-0.92387953, 0.38268343], | ||
| 405 | + [-0.91879121, 0.39474386], | ||
| 406 | + [-0.91354546, 0.40673664], | ||
| 407 | + [-0.90814317, 0.41865974], | ||
| 408 | + [-0.90258528, 0.43051110], | ||
| 409 | + [-0.89687274, 0.44228869], | ||
| 410 | + [-0.89100652, 0.45399050], | ||
| 411 | + [-0.88498764, 0.46561452], | ||
| 412 | + [-0.87881711, 0.47715876], | ||
| 413 | + [-0.87249601, 0.48862124], | ||
| 414 | + [-0.86602540, 0.50000000], | ||
| 415 | + [-0.85940641, 0.51129309], | ||
| 416 | + [-0.85264016, 0.52249856], | ||
| 417 | + [-0.84572782, 0.53361452], | ||
| 418 | + [-0.83867057, 0.54463904], | ||
| 419 | + [-0.83146961, 0.55557023], | ||
| 420 | + [-0.82412619, 0.56640624], | ||
| 421 | + [-0.81664156, 0.57714519], | ||
| 422 | + [-0.80901699, 0.58778525], | ||
| 423 | + [-0.80125381, 0.59832460], | ||
| 424 | + [-0.79335334, 0.60876143], | ||
| 425 | + [-0.78531693, 0.61909395], | ||
| 426 | + [-0.77714596, 0.62932039], | ||
| 427 | + [-0.76884183, 0.63943900], | ||
| 428 | + [-0.76040597, 0.64944805], | ||
| 429 | + [-0.75183981, 0.65934582], | ||
| 430 | + [-0.74314483, 0.66913061], | ||
| 431 | + [-0.73432251, 0.67880075], | ||
| 432 | + [-0.72537437, 0.68835458], | ||
| 433 | + [-0.71630194, 0.69779046], | ||
| 434 | + [-0.70710678, 0.70710678], | ||
| 435 | + [-0.69779046, 0.71630194], | ||
| 436 | + [-0.68835458, 0.72537437], | ||
| 437 | + [-0.67880075, 0.73432251], | ||
| 438 | + [-0.66913061, 0.74314483], | ||
| 439 | + [-0.65934582, 0.75183981], | ||
| 440 | + [-0.64944805, 0.76040597], | ||
| 441 | + [-0.63943900, 0.76884183], | ||
| 442 | + [-0.62932039, 0.77714596], | ||
| 443 | + [-0.61909395, 0.78531693], | ||
| 444 | + [-0.60876143, 0.79335334], | ||
| 445 | + [-0.59832460, 0.80125381], | ||
| 446 | + [-0.58778525, 0.80901699], | ||
| 447 | + [-0.57714519, 0.81664156], | ||
| 448 | + [-0.56640624, 0.82412619], | ||
| 449 | + [-0.55557023, 0.83146961], | ||
| 450 | + [-0.54463904, 0.83867057], | ||
| 451 | + [-0.53361452, 0.84572782], | ||
| 452 | + [-0.52249856, 0.85264016], | ||
| 453 | + [-0.51129309, 0.85940641], | ||
| 454 | + [-0.50000000, 0.86602540], | ||
| 455 | + [-0.48862124, 0.87249601], | ||
| 456 | + [-0.47715876, 0.87881711], | ||
| 457 | + [-0.46561452, 0.88498764], | ||
| 458 | + [-0.45399050, 0.89100652], | ||
| 459 | + [-0.44228869, 0.89687274], | ||
| 460 | + [-0.43051110, 0.90258528], | ||
| 461 | + [-0.41865974, 0.90814317], | ||
| 462 | + [-0.40673664, 0.91354546], | ||
| 463 | + [-0.39474386, 0.91879121], | ||
| 464 | + [-0.38268343, 0.92387953], | ||
| 465 | + [-0.37055744, 0.92880955], | ||
| 466 | + [-0.35836795, 0.93358043], | ||
| 467 | + [-0.34611706, 0.93819134], | ||
| 468 | + [-0.33380686, 0.94264149], | ||
| 469 | + [-0.32143947, 0.94693013], | ||
| 470 | + [-0.30901699, 0.95105652], | ||
| 471 | + [-0.29654157, 0.95501994], | ||
| 472 | + [-0.28401534, 0.95881973], | ||
| 473 | + [-0.27144045, 0.96245524], | ||
| 474 | + [-0.25881905, 0.96592583], | ||
| 475 | + [-0.24615329, 0.96923091], | ||
| 476 | + [-0.23344536, 0.97236992], | ||
| 477 | + [-0.22069744, 0.97534232], | ||
| 478 | + [-0.20791169, 0.97814760], | ||
| 479 | + [-0.19509032, 0.98078528], | ||
| 480 | + [-0.18223553, 0.98325491], | ||
| 481 | + [-0.16934950, 0.98555606], | ||
| 482 | + [-0.15643447, 0.98768834], | ||
| 483 | + [-0.14349262, 0.98965139], | ||
| 484 | + [-0.13052619, 0.99144486], | ||
| 485 | + [-0.11753740, 0.99306846], | ||
| 486 | + [-0.10452846, 0.99452190], | ||
| 487 | + [-0.091501619, 0.99580493], | ||
| 488 | + [-0.078459096, 0.99691733], | ||
| 489 | + [-0.065403129, 0.99785892], | ||
| 490 | + [-0.052335956, 0.99862953], | ||
| 491 | + [-0.039259816, 0.99922904], | ||
| 492 | + [-0.026176948, 0.99965732], | ||
| 493 | + [-0.013089596, 0.99991433], | ||
| 494 | + [-1.8369702e-16, 1.0000000], | ||
| 495 | + [0.013089596, 0.99991433], | ||
| 496 | + [0.026176948, 0.99965732], | ||
| 497 | + [0.039259816, 0.99922904], | ||
| 498 | + [0.052335956, 0.99862953], | ||
| 499 | + [0.065403129, 0.99785892], | ||
| 500 | + [0.078459096, 0.99691733], | ||
| 501 | + [0.091501619, 0.99580493], | ||
| 502 | + [0.10452846, 0.99452190], | ||
| 503 | + [0.11753740, 0.99306846], | ||
| 504 | + [0.13052619, 0.99144486], | ||
| 505 | + [0.14349262, 0.98965139], | ||
| 506 | + [0.15643447, 0.98768834], | ||
| 507 | + [0.16934950, 0.98555606], | ||
| 508 | + [0.18223553, 0.98325491], | ||
| 509 | + [0.19509032, 0.98078528], | ||
| 510 | + [0.20791169, 0.97814760], | ||
| 511 | + [0.22069744, 0.97534232], | ||
| 512 | + [0.23344536, 0.97236992], | ||
| 513 | + [0.24615329, 0.96923091], | ||
| 514 | + [0.25881905, 0.96592583], | ||
| 515 | + [0.27144045, 0.96245524], | ||
| 516 | + [0.28401534, 0.95881973], | ||
| 517 | + [0.29654157, 0.95501994], | ||
| 518 | + [0.30901699, 0.95105652], | ||
| 519 | + [0.32143947, 0.94693013], | ||
| 520 | + [0.33380686, 0.94264149], | ||
| 521 | + [0.34611706, 0.93819134], | ||
| 522 | + [0.35836795, 0.93358043], | ||
| 523 | + [0.37055744, 0.92880955], | ||
| 524 | + [0.38268343, 0.92387953], | ||
| 525 | + [0.39474386, 0.91879121], | ||
| 526 | + [0.40673664, 0.91354546], | ||
| 527 | + [0.41865974, 0.90814317], | ||
| 528 | + [0.43051110, 0.90258528], | ||
| 529 | + [0.44228869, 0.89687274], | ||
| 530 | + [0.45399050, 0.89100652], | ||
| 531 | + [0.46561452, 0.88498764], | ||
| 532 | + [0.47715876, 0.87881711], | ||
| 533 | + [0.48862124, 0.87249601], | ||
| 534 | + [0.50000000, 0.86602540], | ||
| 535 | + [0.51129309, 0.85940641], | ||
| 536 | + [0.52249856, 0.85264016], | ||
| 537 | + [0.53361452, 0.84572782], | ||
| 538 | + [0.54463904, 0.83867057], | ||
| 539 | + [0.55557023, 0.83146961], | ||
| 540 | + [0.56640624, 0.82412619], | ||
| 541 | + [0.57714519, 0.81664156], | ||
| 542 | + [0.58778525, 0.80901699], | ||
| 543 | + [0.59832460, 0.80125381], | ||
| 544 | + [0.60876143, 0.79335334], | ||
| 545 | + [0.61909395, 0.78531693], | ||
| 546 | + [0.62932039, 0.77714596], | ||
| 547 | + [0.63943900, 0.76884183], | ||
| 548 | + [0.64944805, 0.76040597], | ||
| 549 | + [0.65934582, 0.75183981], | ||
| 550 | + [0.66913061, 0.74314483], | ||
| 551 | + [0.67880075, 0.73432251], | ||
| 552 | + [0.68835458, 0.72537437], | ||
| 553 | + [0.69779046, 0.71630194], | ||
| 554 | + [0.70710678, 0.70710678], | ||
| 555 | + [0.71630194, 0.69779046], | ||
| 556 | + [0.72537437, 0.68835458], | ||
| 557 | + [0.73432251, 0.67880075], | ||
| 558 | + [0.74314483, 0.66913061], | ||
| 559 | + [0.75183981, 0.65934582], | ||
| 560 | + [0.76040597, 0.64944805], | ||
| 561 | + [0.76884183, 0.63943900], | ||
| 562 | + [0.77714596, 0.62932039], | ||
| 563 | + [0.78531693, 0.61909395], | ||
| 564 | + [0.79335334, 0.60876143], | ||
| 565 | + [0.80125381, 0.59832460], | ||
| 566 | + [0.80901699, 0.58778525], | ||
| 567 | + [0.81664156, 0.57714519], | ||
| 568 | + [0.82412619, 0.56640624], | ||
| 569 | + [0.83146961, 0.55557023], | ||
| 570 | + [0.83867057, 0.54463904], | ||
| 571 | + [0.84572782, 0.53361452], | ||
| 572 | + [0.85264016, 0.52249856], | ||
| 573 | + [0.85940641, 0.51129309], | ||
| 574 | + [0.86602540, 0.50000000], | ||
| 575 | + [0.87249601, 0.48862124], | ||
| 576 | + [0.87881711, 0.47715876], | ||
| 577 | + [0.88498764, 0.46561452], | ||
| 578 | + [0.89100652, 0.45399050], | ||
| 579 | + [0.89687274, 0.44228869], | ||
| 580 | + [0.90258528, 0.43051110], | ||
| 581 | + [0.90814317, 0.41865974], | ||
| 582 | + [0.91354546, 0.40673664], | ||
| 583 | + [0.91879121, 0.39474386], | ||
| 584 | + [0.92387953, 0.38268343], | ||
| 585 | + [0.92880955, 0.37055744], | ||
| 586 | + [0.93358043, 0.35836795], | ||
| 587 | + [0.93819134, 0.34611706], | ||
| 588 | + [0.94264149, 0.33380686], | ||
| 589 | + [0.94693013, 0.32143947], | ||
| 590 | + [0.95105652, 0.30901699], | ||
| 591 | + [0.95501994, 0.29654157], | ||
| 592 | + [0.95881973, 0.28401534], | ||
| 593 | + [0.96245524, 0.27144045], | ||
| 594 | + [0.96592583, 0.25881905], | ||
| 595 | + [0.96923091, 0.24615329], | ||
| 596 | + [0.97236992, 0.23344536], | ||
| 597 | + [0.97534232, 0.22069744], | ||
| 598 | + [0.97814760, 0.20791169], | ||
| 599 | + [0.98078528, 0.19509032], | ||
| 600 | + [0.98325491, 0.18223553], | ||
| 601 | + [0.98555606, 0.16934950], | ||
| 602 | + [0.98768834, 0.15643447], | ||
| 603 | + [0.98965139, 0.14349262], | ||
| 604 | + [0.99144486, 0.13052619], | ||
| 605 | + [0.99306846, 0.11753740], | ||
| 606 | + [0.99452190, 0.10452846], | ||
| 607 | + [0.99580493, 0.091501619], | ||
| 608 | + [0.99691733, 0.078459096], | ||
| 609 | + [0.99785892, 0.065403129], | ||
| 610 | + [0.99862953, 0.052335956], | ||
| 611 | + [0.99922904, 0.039259816], | ||
| 612 | + [0.99965732, 0.026176948], | ||
| 613 | + [0.99991433, 0.013089596], | ||
| 614 | +]; | ||
| 615 | +/// `fft_bitrev480`. | ||
| 616 | +pub(crate) static FFT_BITREV480: [i16; 480] = [ | ||
| 617 | + 0, 96, 192, 288, 384, 32, 128, 224, 320, 416, 64, 160, 256, 352, 448, 8, 104, 200, 296, 392, | ||
| 618 | + 40, 136, 232, 328, 424, 72, 168, 264, 360, 456, 16, 112, 208, 304, 400, 48, 144, 240, 336, 432, | ||
| 619 | + 80, 176, 272, 368, 464, 24, 120, 216, 312, 408, 56, 152, 248, 344, 440, 88, 184, 280, 376, 472, | ||
| 620 | + 4, 100, 196, 292, 388, 36, 132, 228, 324, 420, 68, 164, 260, 356, 452, 12, 108, 204, 300, 396, | ||
| 621 | + 44, 140, 236, 332, 428, 76, 172, 268, 364, 460, 20, 116, 212, 308, 404, 52, 148, 244, 340, 436, | ||
| 622 | + 84, 180, 276, 372, 468, 28, 124, 220, 316, 412, 60, 156, 252, 348, 444, 92, 188, 284, 380, 476, | ||
| 623 | + 1, 97, 193, 289, 385, 33, 129, 225, 321, 417, 65, 161, 257, 353, 449, 9, 105, 201, 297, 393, | ||
| 624 | + 41, 137, 233, 329, 425, 73, 169, 265, 361, 457, 17, 113, 209, 305, 401, 49, 145, 241, 337, 433, | ||
| 625 | + 81, 177, 273, 369, 465, 25, 121, 217, 313, 409, 57, 153, 249, 345, 441, 89, 185, 281, 377, 473, | ||
| 626 | + 5, 101, 197, 293, 389, 37, 133, 229, 325, 421, 69, 165, 261, 357, 453, 13, 109, 205, 301, 397, | ||
| 627 | + 45, 141, 237, 333, 429, 77, 173, 269, 365, 461, 21, 117, 213, 309, 405, 53, 149, 245, 341, 437, | ||
| 628 | + 85, 181, 277, 373, 469, 29, 125, 221, 317, 413, 61, 157, 253, 349, 445, 93, 189, 285, 381, 477, | ||
| 629 | + 2, 98, 194, 290, 386, 34, 130, 226, 322, 418, 66, 162, 258, 354, 450, 10, 106, 202, 298, 394, | ||
| 630 | + 42, 138, 234, 330, 426, 74, 170, 266, 362, 458, 18, 114, 210, 306, 402, 50, 146, 242, 338, 434, | ||
| 631 | + 82, 178, 274, 370, 466, 26, 122, 218, 314, 410, 58, 154, 250, 346, 442, 90, 186, 282, 378, 474, | ||
| 632 | + 6, 102, 198, 294, 390, 38, 134, 230, 326, 422, 70, 166, 262, 358, 454, 14, 110, 206, 302, 398, | ||
| 633 | + 46, 142, 238, 334, 430, 78, 174, 270, 366, 462, 22, 118, 214, 310, 406, 54, 150, 246, 342, 438, | ||
| 634 | + 86, 182, 278, 374, 470, 30, 126, 222, 318, 414, 62, 158, 254, 350, 446, 94, 190, 286, 382, 478, | ||
| 635 | + 3, 99, 195, 291, 387, 35, 131, 227, 323, 419, 67, 163, 259, 355, 451, 11, 107, 203, 299, 395, | ||
| 636 | + 43, 139, 235, 331, 427, 75, 171, 267, 363, 459, 19, 115, 211, 307, 403, 51, 147, 243, 339, 435, | ||
| 637 | + 83, 179, 275, 371, 467, 27, 123, 219, 315, 411, 59, 155, 251, 347, 443, 91, 187, 283, 379, 475, | ||
| 638 | + 7, 103, 199, 295, 391, 39, 135, 231, 327, 423, 71, 167, 263, 359, 455, 15, 111, 207, 303, 399, | ||
| 639 | + 47, 143, 239, 335, 431, 79, 175, 271, 367, 463, 23, 119, 215, 311, 407, 55, 151, 247, 343, 439, | ||
| 640 | + 87, 183, 279, 375, 471, 31, 127, 223, 319, 415, 63, 159, 255, 351, 447, 95, 191, 287, 383, 479, | ||
| 641 | +]; | ||
| 642 | +/// `fft_bitrev240`. | ||
| 643 | +pub(crate) static FFT_BITREV240: [i16; 240] = [ | ||
| 644 | + 0, 48, 96, 144, 192, 16, 64, 112, 160, 208, 32, 80, 128, 176, 224, 4, 52, 100, 148, 196, 20, | ||
| 645 | + 68, 116, 164, 212, 36, 84, 132, 180, 228, 8, 56, 104, 152, 200, 24, 72, 120, 168, 216, 40, 88, | ||
| 646 | + 136, 184, 232, 12, 60, 108, 156, 204, 28, 76, 124, 172, 220, 44, 92, 140, 188, 236, 1, 49, 97, | ||
| 647 | + 145, 193, 17, 65, 113, 161, 209, 33, 81, 129, 177, 225, 5, 53, 101, 149, 197, 21, 69, 117, 165, | ||
| 648 | + 213, 37, 85, 133, 181, 229, 9, 57, 105, 153, 201, 25, 73, 121, 169, 217, 41, 89, 137, 185, 233, | ||
| 649 | + 13, 61, 109, 157, 205, 29, 77, 125, 173, 221, 45, 93, 141, 189, 237, 2, 50, 98, 146, 194, 18, | ||
| 650 | + 66, 114, 162, 210, 34, 82, 130, 178, 226, 6, 54, 102, 150, 198, 22, 70, 118, 166, 214, 38, 86, | ||
| 651 | + 134, 182, 230, 10, 58, 106, 154, 202, 26, 74, 122, 170, 218, 42, 90, 138, 186, 234, 14, 62, | ||
| 652 | + 110, 158, 206, 30, 78, 126, 174, 222, 46, 94, 142, 190, 238, 3, 51, 99, 147, 195, 19, 67, 115, | ||
| 653 | + 163, 211, 35, 83, 131, 179, 227, 7, 55, 103, 151, 199, 23, 71, 119, 167, 215, 39, 87, 135, 183, | ||
| 654 | + 231, 11, 59, 107, 155, 203, 27, 75, 123, 171, 219, 43, 91, 139, 187, 235, 15, 63, 111, 159, | ||
| 655 | + 207, 31, 79, 127, 175, 223, 47, 95, 143, 191, 239, | ||
| 656 | +]; | ||
| 657 | +/// `fft_bitrev120`. | ||
| 658 | +pub(crate) static FFT_BITREV120: [i16; 120] = [ | ||
| 659 | + 0, 24, 48, 72, 96, 8, 32, 56, 80, 104, 16, 40, 64, 88, 112, 4, 28, 52, 76, 100, 12, 36, 60, 84, | ||
| 660 | + 108, 20, 44, 68, 92, 116, 1, 25, 49, 73, 97, 9, 33, 57, 81, 105, 17, 41, 65, 89, 113, 5, 29, | ||
| 661 | + 53, 77, 101, 13, 37, 61, 85, 109, 21, 45, 69, 93, 117, 2, 26, 50, 74, 98, 10, 34, 58, 82, 106, | ||
| 662 | + 18, 42, 66, 90, 114, 6, 30, 54, 78, 102, 14, 38, 62, 86, 110, 22, 46, 70, 94, 118, 3, 27, 51, | ||
| 663 | + 75, 99, 11, 35, 59, 83, 107, 19, 43, 67, 91, 115, 7, 31, 55, 79, 103, 15, 39, 63, 87, 111, 23, | ||
| 664 | + 47, 71, 95, 119, | ||
| 665 | +]; | ||
| 666 | +/// `fft_bitrev60`. | ||
| 667 | +pub(crate) static FFT_BITREV60: [i16; 60] = [ | ||
| 668 | + 0, 12, 24, 36, 48, 4, 16, 28, 40, 52, 8, 20, 32, 44, 56, 1, 13, 25, 37, 49, 5, 17, 29, 41, 53, | ||
| 669 | + 9, 21, 33, 45, 57, 2, 14, 26, 38, 50, 6, 18, 30, 42, 54, 10, 22, 34, 46, 58, 3, 15, 27, 39, 51, | ||
| 670 | + 7, 19, 31, 43, 55, 11, 23, 35, 47, 59, | ||
| 671 | +]; | ||
| 672 | +/// `fft_state48000_960_0..3`, indexed by mdct shift. | ||
| 673 | +pub(crate) static FFT_STATES: [FftState; 4] = [ | ||
| 674 | + FftState { | ||
| 675 | + scale: 0.0020833334, | ||
| 676 | + shift: -1, | ||
| 677 | + factors: [5, 96, 3, 32, 4, 8, 2, 4, 4, 1, 0, 0, 0, 0, 0, 0], | ||
| 678 | + bitrev: &FFT_BITREV480, | ||
| 679 | + }, | ||
| 680 | + FftState { | ||
| 681 | + scale: 0.0041666669, | ||
| 682 | + shift: 1, | ||
| 683 | + factors: [5, 48, 3, 16, 4, 4, 4, 1, 0, 0, 0, 0, 0, 0, 0, 0], | ||
| 684 | + bitrev: &FFT_BITREV240, | ||
| 685 | + }, | ||
| 686 | + FftState { | ||
| 687 | + scale: 0.0083333338, | ||
| 688 | + shift: 2, | ||
| 689 | + factors: [5, 24, 3, 8, 2, 4, 4, 1, 0, 0, 0, 0, 0, 0, 0, 0], | ||
| 690 | + bitrev: &FFT_BITREV120, | ||
| 691 | + }, | ||
| 692 | + FftState { | ||
| 693 | + scale: 0.016666668, | ||
| 694 | + shift: 3, | ||
| 695 | + factors: [5, 12, 3, 4, 4, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], | ||
| 696 | + bitrev: &FFT_BITREV60, | ||
| 697 | + }, | ||
| 698 | +]; | ||
| 699 | +/// `mdct_twiddles960`. | ||
| 700 | +pub(crate) static MDCT_TWIDDLES: [f32; 1800] = [ | ||
| 701 | + -0.00040906153, | ||
| 702 | + 0.99999992, | ||
| 703 | + -0.0036815456, | ||
| 704 | + 0.99999322, | ||
| 705 | + -0.0069539902, | ||
| 706 | + 0.99997582, | ||
| 707 | + -0.010226360, | ||
| 708 | + 0.99994771, | ||
| 709 | + -0.013498621, | ||
| 710 | + 0.99990889, | ||
| 711 | + -0.016770737, | ||
| 712 | + 0.99985936, | ||
| 713 | + -0.020042673, | ||
| 714 | + 0.99979913, | ||
| 715 | + -0.023314395, | ||
| 716 | + 0.99972818, | ||
| 717 | + -0.026585867, | ||
| 718 | + 0.99964653, | ||
| 719 | + -0.029857055, | ||
| 720 | + 0.99955418, | ||
| 721 | + -0.033127923, | ||
| 722 | + 0.99945112, | ||
| 723 | + -0.036398436, | ||
| 724 | + 0.99933736, | ||
| 725 | + -0.039668559, | ||
| 726 | + 0.99921289, | ||
| 727 | + -0.042938257, | ||
| 728 | + 0.99907773, | ||
| 729 | + -0.046207495, | ||
| 730 | + 0.99893186, | ||
| 731 | + -0.049476239, | ||
| 732 | + 0.99877530, | ||
| 733 | + -0.052744453, | ||
| 734 | + 0.99860804, | ||
| 735 | + -0.056012102, | ||
| 736 | + 0.99843009, | ||
| 737 | + -0.059279151, | ||
| 738 | + 0.99824144, | ||
| 739 | + -0.062545565, | ||
| 740 | + 0.99804211, | ||
| 741 | + -0.065811309, | ||
| 742 | + 0.99783209, | ||
| 743 | + -0.069076349, | ||
| 744 | + 0.99761138, | ||
| 745 | + -0.072340649, | ||
| 746 | + 0.99737998, | ||
| 747 | + -0.075604174, | ||
| 748 | + 0.99713791, | ||
| 749 | + -0.078866890, | ||
| 750 | + 0.99688516, | ||
| 751 | + -0.082128761, | ||
| 752 | + 0.99662173, | ||
| 753 | + -0.085389752, | ||
| 754 | + 0.99634763, | ||
| 755 | + -0.088649829, | ||
| 756 | + 0.99606285, | ||
| 757 | + -0.091908956, | ||
| 758 | + 0.99576741, | ||
| 759 | + -0.095167100, | ||
| 760 | + 0.99546131, | ||
| 761 | + -0.098424224, | ||
| 762 | + 0.99514455, | ||
| 763 | + -0.10168029, | ||
| 764 | + 0.99481713, | ||
| 765 | + -0.10493528, | ||
| 766 | + 0.99447905, | ||
| 767 | + -0.10818913, | ||
| 768 | + 0.99413033, | ||
| 769 | + -0.11144183, | ||
| 770 | + 0.99377096, | ||
| 771 | + -0.11469334, | ||
| 772 | + 0.99340095, | ||
| 773 | + -0.11794361, | ||
| 774 | + 0.99302029, | ||
| 775 | + -0.12119263, | ||
| 776 | + 0.99262901, | ||
| 777 | + -0.12444034, | ||
| 778 | + 0.99222709, | ||
| 779 | + -0.12768673, | ||
| 780 | + 0.99181455, | ||
| 781 | + -0.13093174, | ||
| 782 | + 0.99139139, | ||
| 783 | + -0.13417536, | ||
| 784 | + 0.99095760, | ||
| 785 | + -0.13741753, | ||
| 786 | + 0.99051321, | ||
| 787 | + -0.14065824, | ||
| 788 | + 0.99005821, | ||
| 789 | + -0.14389744, | ||
| 790 | + 0.98959261, | ||
| 791 | + -0.14713510, | ||
| 792 | + 0.98911641, | ||
| 793 | + -0.15037118, | ||
| 794 | + 0.98862961, | ||
| 795 | + -0.15360565, | ||
| 796 | + 0.98813223, | ||
| 797 | + -0.15683848, | ||
| 798 | + 0.98762427, | ||
| 799 | + -0.16006962, | ||
| 800 | + 0.98710573, | ||
| 801 | + -0.16329906, | ||
| 802 | + 0.98657662, | ||
| 803 | + -0.16652674, | ||
| 804 | + 0.98603694, | ||
| 805 | + -0.16975264, | ||
| 806 | + 0.98548670, | ||
| 807 | + -0.17297673, | ||
| 808 | + 0.98492591, | ||
| 809 | + -0.17619896, | ||
| 810 | + 0.98435457, | ||
| 811 | + -0.17941930, | ||
| 812 | + 0.98377269, | ||
| 813 | + -0.18263772, | ||
| 814 | + 0.98318028, | ||
| 815 | + -0.18585419, | ||
| 816 | + 0.98257734, | ||
| 817 | + -0.18906866, | ||
| 818 | + 0.98196387, | ||
| 819 | + -0.19228112, | ||
| 820 | + 0.98133989, | ||
| 821 | + -0.19549151, | ||
| 822 | + 0.98070539, | ||
| 823 | + -0.19869981, | ||
| 824 | + 0.98006040, | ||
| 825 | + -0.20190598, | ||
| 826 | + 0.97940491, | ||
| 827 | + -0.20510998, | ||
| 828 | + 0.97873893, | ||
| 829 | + -0.20831180, | ||
| 830 | + 0.97806247, | ||
| 831 | + -0.21151138, | ||
| 832 | + 0.97737554, | ||
| 833 | + -0.21470869, | ||
| 834 | + 0.97667813, | ||
| 835 | + -0.21790371, | ||
| 836 | + 0.97597027, | ||
| 837 | + -0.22109639, | ||
| 838 | + 0.97525196, | ||
| 839 | + -0.22428671, | ||
| 840 | + 0.97452320, | ||
| 841 | + -0.22747462, | ||
| 842 | + 0.97378401, | ||
| 843 | + -0.23066010, | ||
| 844 | + 0.97303439, | ||
| 845 | + -0.23384310, | ||
| 846 | + 0.97227435, | ||
| 847 | + -0.23702361, | ||
| 848 | + 0.97150389, | ||
| 849 | + -0.24020157, | ||
| 850 | + 0.97072303, | ||
| 851 | + -0.24337696, | ||
| 852 | + 0.96993178, | ||
| 853 | + -0.24654975, | ||
| 854 | + 0.96913014, | ||
| 855 | + -0.24971989, | ||
| 856 | + 0.96831812, | ||
| 857 | + -0.25288736, | ||
| 858 | + 0.96749573, | ||
| 859 | + -0.25605213, | ||
| 860 | + 0.96666298, | ||
| 861 | + -0.25921415, | ||
| 862 | + 0.96581987, | ||
| 863 | + -0.26237339, | ||
| 864 | + 0.96496643, | ||
| 865 | + -0.26552983, | ||
| 866 | + 0.96410265, | ||
| 867 | + -0.26868342, | ||
| 868 | + 0.96322854, | ||
| 869 | + -0.27183413, | ||
| 870 | + 0.96234412, | ||
| 871 | + -0.27498193, | ||
| 872 | + 0.96144939, | ||
| 873 | + -0.27812679, | ||
| 874 | + 0.96054437, | ||
| 875 | + -0.28126867, | ||
| 876 | + 0.95962906, | ||
| 877 | + -0.28440754, | ||
| 878 | + 0.95870347, | ||
| 879 | + -0.28754336, | ||
| 880 | + 0.95776762, | ||
| 881 | + -0.29067610, | ||
| 882 | + 0.95682151, | ||
| 883 | + -0.29380573, | ||
| 884 | + 0.95586515, | ||
| 885 | + -0.29693221, | ||
| 886 | + 0.95489856, | ||
| 887 | + -0.30005551, | ||
| 888 | + 0.95392174, | ||
| 889 | + -0.30317560, | ||
| 890 | + 0.95293471, | ||
| 891 | + -0.30629245, | ||
| 892 | + 0.95193746, | ||
| 893 | + -0.30940601, | ||
| 894 | + 0.95093003, | ||
| 895 | + -0.31251626, | ||
| 896 | + 0.94991241, | ||
| 897 | + -0.31562316, | ||
| 898 | + 0.94888462, | ||
| 899 | + -0.31872668, | ||
| 900 | + 0.94784667, | ||
| 901 | + -0.32182679, | ||
| 902 | + 0.94679856, | ||
| 903 | + -0.32492345, | ||
| 904 | + 0.94574032, | ||
| 905 | + -0.32801664, | ||
| 906 | + 0.94467195, | ||
| 907 | + -0.33110631, | ||
| 908 | + 0.94359346, | ||
| 909 | + -0.33419243, | ||
| 910 | + 0.94250486, | ||
| 911 | + -0.33727497, | ||
| 912 | + 0.94140618, | ||
| 913 | + -0.34035391, | ||
| 914 | + 0.94029741, | ||
| 915 | + -0.34342920, | ||
| 916 | + 0.93917857, | ||
| 917 | + -0.34650081, | ||
| 918 | + 0.93804967, | ||
| 919 | + -0.34956871, | ||
| 920 | + 0.93691073, | ||
| 921 | + -0.35263286, | ||
| 922 | + 0.93576176, | ||
| 923 | + -0.35569324, | ||
| 924 | + 0.93460276, | ||
| 925 | + -0.35874981, | ||
| 926 | + 0.93343375, | ||
| 927 | + -0.36180254, | ||
| 928 | + 0.93225475, | ||
| 929 | + -0.36485139, | ||
| 930 | + 0.93106577, | ||
| 931 | + -0.36789634, | ||
| 932 | + 0.92986681, | ||
| 933 | + -0.37093735, | ||
| 934 | + 0.92865789, | ||
| 935 | + -0.37397438, | ||
| 936 | + 0.92743903, | ||
| 937 | + -0.37700741, | ||
| 938 | + 0.92621024, | ||
| 939 | + -0.38003640, | ||
| 940 | + 0.92497153, | ||
| 941 | + -0.38306132, | ||
| 942 | + 0.92372291, | ||
| 943 | + -0.38608214, | ||
| 944 | + 0.92246440, | ||
| 945 | + -0.38909883, | ||
| 946 | + 0.92119602, | ||
| 947 | + -0.39211135, | ||
| 948 | + 0.91991776, | ||
| 949 | + -0.39511967, | ||
| 950 | + 0.91862966, | ||
| 951 | + -0.39812375, | ||
| 952 | + 0.91733172, | ||
| 953 | + -0.40112358, | ||
| 954 | + 0.91602395, | ||
| 955 | + -0.40411910, | ||
| 956 | + 0.91470637, | ||
| 957 | + -0.40711031, | ||
| 958 | + 0.91337900, | ||
| 959 | + -0.41009715, | ||
| 960 | + 0.91204185, | ||
| 961 | + -0.41307959, | ||
| 962 | + 0.91069493, | ||
| 963 | + -0.41605762, | ||
| 964 | + 0.90933825, | ||
| 965 | + -0.41903119, | ||
| 966 | + 0.90797184, | ||
| 967 | + -0.42200027, | ||
| 968 | + 0.90659570, | ||
| 969 | + -0.42496483, | ||
| 970 | + 0.90520986, | ||
| 971 | + -0.42792484, | ||
| 972 | + 0.90381432, | ||
| 973 | + -0.43088027, | ||
| 974 | + 0.90240910, | ||
| 975 | + -0.43383109, | ||
| 976 | + 0.90099422, | ||
| 977 | + -0.43677726, | ||
| 978 | + 0.89956969, | ||
| 979 | + -0.43971875, | ||
| 980 | + 0.89813553, | ||
| 981 | + -0.44265553, | ||
| 982 | + 0.89669174, | ||
| 983 | + -0.44558757, | ||
| 984 | + 0.89523836, | ||
| 985 | + -0.44851484, | ||
| 986 | + 0.89377538, | ||
| 987 | + -0.45143731, | ||
| 988 | + 0.89230284, | ||
| 989 | + -0.45435494, | ||
| 990 | + 0.89082074, | ||
| 991 | + -0.45726770, | ||
| 992 | + 0.88932910, | ||
| 993 | + -0.46017557, | ||
| 994 | + 0.88782793, | ||
| 995 | + -0.46307851, | ||
| 996 | + 0.88631726, | ||
| 997 | + -0.46597650, | ||
| 998 | + 0.88479710, | ||
| 999 | + -0.46886949, | ||
| 1000 | + 0.88326746, | ||
| 1001 | + -0.47175746, | ||
| 1002 | + 0.88172836, | ||
| 1003 | + -0.47464038, | ||
| 1004 | + 0.88017982, | ||
| 1005 | + -0.47751821, | ||
| 1006 | + 0.87862185, | ||
| 1007 | + -0.48039093, | ||
| 1008 | + 0.87705448, | ||
| 1009 | + -0.48325851, | ||
| 1010 | + 0.87547771, | ||
| 1011 | + -0.48612091, | ||
| 1012 | + 0.87389156, | ||
| 1013 | + -0.48897811, | ||
| 1014 | + 0.87229606, | ||
| 1015 | + -0.49183006, | ||
| 1016 | + 0.87069121, | ||
| 1017 | + -0.49467676, | ||
| 1018 | + 0.86907704, | ||
| 1019 | + -0.49751815, | ||
| 1020 | + 0.86745357, | ||
| 1021 | + -0.50035422, | ||
| 1022 | + 0.86582080, | ||
| 1023 | + -0.50318492, | ||
| 1024 | + 0.86417876, | ||
| 1025 | + -0.50601024, | ||
| 1026 | + 0.86252747, | ||
| 1027 | + -0.50883014, | ||
| 1028 | + 0.86086694, | ||
| 1029 | + -0.51164459, | ||
| 1030 | + 0.85919719, | ||
| 1031 | + -0.51445356, | ||
| 1032 | + 0.85751824, | ||
| 1033 | + -0.51725703, | ||
| 1034 | + 0.85583010, | ||
| 1035 | + -0.52005495, | ||
| 1036 | + 0.85413281, | ||
| 1037 | + -0.52284730, | ||
| 1038 | + 0.85242636, | ||
| 1039 | + -0.52563406, | ||
| 1040 | + 0.85071078, | ||
| 1041 | + -0.52841518, | ||
| 1042 | + 0.84898610, | ||
| 1043 | + -0.53119065, | ||
| 1044 | + 0.84725232, | ||
| 1045 | + -0.53396043, | ||
| 1046 | + 0.84550947, | ||
| 1047 | + -0.53672449, | ||
| 1048 | + 0.84375756, | ||
| 1049 | + -0.53948280, | ||
| 1050 | + 0.84199662, | ||
| 1051 | + -0.54223533, | ||
| 1052 | + 0.84022666, | ||
| 1053 | + -0.54498206, | ||
| 1054 | + 0.83844771, | ||
| 1055 | + -0.54772295, | ||
| 1056 | + 0.83665977, | ||
| 1057 | + -0.55045797, | ||
| 1058 | + 0.83486287, | ||
| 1059 | + -0.55318710, | ||
| 1060 | + 0.83305704, | ||
| 1061 | + -0.55591031, | ||
| 1062 | + 0.83124228, | ||
| 1063 | + -0.55862756, | ||
| 1064 | + 0.82941862, | ||
| 1065 | + -0.56133883, | ||
| 1066 | + 0.82758608, | ||
| 1067 | + -0.56404409, | ||
| 1068 | + 0.82574467, | ||
| 1069 | + -0.56674331, | ||
| 1070 | + 0.82389442, | ||
| 1071 | + -0.56943646, | ||
| 1072 | + 0.82203535, | ||
| 1073 | + -0.57212351, | ||
| 1074 | + 0.82016748, | ||
| 1075 | + -0.57480443, | ||
| 1076 | + 0.81829082, | ||
| 1077 | + -0.57747920, | ||
| 1078 | + 0.81640540, | ||
| 1079 | + -0.58014778, | ||
| 1080 | + 0.81451123, | ||
| 1081 | + -0.58281015, | ||
| 1082 | + 0.81260835, | ||
| 1083 | + -0.58546628, | ||
| 1084 | + 0.81069676, | ||
| 1085 | + -0.58811614, | ||
| 1086 | + 0.80877649, | ||
| 1087 | + -0.59075970, | ||
| 1088 | + 0.80684755, | ||
| 1089 | + -0.59339694, | ||
| 1090 | + 0.80490998, | ||
| 1091 | + -0.59602782, | ||
| 1092 | + 0.80296379, | ||
| 1093 | + -0.59865231, | ||
| 1094 | + 0.80100899, | ||
| 1095 | + -0.60127040, | ||
| 1096 | + 0.79904562, | ||
| 1097 | + -0.60388204, | ||
| 1098 | + 0.79707370, | ||
| 1099 | + -0.60648722, | ||
| 1100 | + 0.79509323, | ||
| 1101 | + -0.60908591, | ||
| 1102 | + 0.79310425, | ||
| 1103 | + -0.61167807, | ||
| 1104 | + 0.79110678, | ||
| 1105 | + -0.61426368, | ||
| 1106 | + 0.78910084, | ||
| 1107 | + -0.61684271, | ||
| 1108 | + 0.78708644, | ||
| 1109 | + -0.61941514, | ||
| 1110 | + 0.78506362, | ||
| 1111 | + -0.62198093, | ||
| 1112 | + 0.78303239, | ||
| 1113 | + -0.62454007, | ||
| 1114 | + 0.78099277, | ||
| 1115 | + -0.62709251, | ||
| 1116 | + 0.77894479, | ||
| 1117 | + -0.62963824, | ||
| 1118 | + 0.77688847, | ||
| 1119 | + -0.63217722, | ||
| 1120 | + 0.77482382, | ||
| 1121 | + -0.63470944, | ||
| 1122 | + 0.77275088, | ||
| 1123 | + -0.63723486, | ||
| 1124 | + 0.77066967, | ||
| 1125 | + -0.63975345, | ||
| 1126 | + 0.76858020, | ||
| 1127 | + -0.64226519, | ||
| 1128 | + 0.76648250, | ||
| 1129 | + -0.64477006, | ||
| 1130 | + 0.76437659, | ||
| 1131 | + -0.64726802, | ||
| 1132 | + 0.76226250, | ||
| 1133 | + -0.64975905, | ||
| 1134 | + 0.76014024, | ||
| 1135 | + -0.65224312, | ||
| 1136 | + 0.75800984, | ||
| 1137 | + -0.65472020, | ||
| 1138 | + 0.75587132, | ||
| 1139 | + -0.65719027, | ||
| 1140 | + 0.75372471, | ||
| 1141 | + -0.65965331, | ||
| 1142 | + 0.75157003, | ||
| 1143 | + -0.66210928, | ||
| 1144 | + 0.74940730, | ||
| 1145 | + -0.66455816, | ||
| 1146 | + 0.74723654, | ||
| 1147 | + -0.66699992, | ||
| 1148 | + 0.74505779, | ||
| 1149 | + -0.66943454, | ||
| 1150 | + 0.74287105, | ||
| 1151 | + -0.67186199, | ||
| 1152 | + 0.74067635, | ||
| 1153 | + -0.67428225, | ||
| 1154 | + 0.73847373, | ||
| 1155 | + -0.67669528, | ||
| 1156 | + 0.73626320, | ||
| 1157 | + -0.67910107, | ||
| 1158 | + 0.73404478, | ||
| 1159 | + -0.68149959, | ||
| 1160 | + 0.73181850, | ||
| 1161 | + -0.68389080, | ||
| 1162 | + 0.72958438, | ||
| 1163 | + -0.68627470, | ||
| 1164 | + 0.72734245, | ||
| 1165 | + -0.68865124, | ||
| 1166 | + 0.72509273, | ||
| 1167 | + -0.69102041, | ||
| 1168 | + 0.72283525, | ||
| 1169 | + -0.69338218, | ||
| 1170 | + 0.72057002, | ||
| 1171 | + -0.69573652, | ||
| 1172 | + 0.71829708, | ||
| 1173 | + -0.69808341, | ||
| 1174 | + 0.71601644, | ||
| 1175 | + -0.70042283, | ||
| 1176 | + 0.71372814, | ||
| 1177 | + -0.70275474, | ||
| 1178 | + 0.71143220, | ||
| 1179 | + -0.70507913, | ||
| 1180 | + 0.70912863, | ||
| 1181 | + -0.70739597, | ||
| 1182 | + 0.70681747, | ||
| 1183 | + -0.70970524, | ||
| 1184 | + 0.70449874, | ||
| 1185 | + -0.71200690, | ||
| 1186 | + 0.70217247, | ||
| 1187 | + -0.71430093, | ||
| 1188 | + 0.69983868, | ||
| 1189 | + -0.71658732, | ||
| 1190 | + 0.69749739, | ||
| 1191 | + -0.71886604, | ||
| 1192 | + 0.69514863, | ||
| 1193 | + -0.72113705, | ||
| 1194 | + 0.69279243, | ||
| 1195 | + -0.72340034, | ||
| 1196 | + 0.69042881, | ||
| 1197 | + -0.72565589, | ||
| 1198 | + 0.68805780, | ||
| 1199 | + -0.72790366, | ||
| 1200 | + 0.68567941, | ||
| 1201 | + -0.73014364, | ||
| 1202 | + 0.68329369, | ||
| 1203 | + -0.73237580, | ||
| 1204 | + 0.68090064, | ||
| 1205 | + -0.73460012, | ||
| 1206 | + 0.67850031, | ||
| 1207 | + -0.73681657, | ||
| 1208 | + 0.67609270, | ||
| 1209 | + -0.73902513, | ||
| 1210 | + 0.67367786, | ||
| 1211 | + -0.74122577, | ||
| 1212 | + 0.67125580, | ||
| 1213 | + -0.74341848, | ||
| 1214 | + 0.66882656, | ||
| 1215 | + -0.74560322, | ||
| 1216 | + 0.66639015, | ||
| 1217 | + -0.74777998, | ||
| 1218 | + 0.66394661, | ||
| 1219 | + -0.74994874, | ||
| 1220 | + 0.66149595, | ||
| 1221 | + -0.75210946, | ||
| 1222 | + 0.65903821, | ||
| 1223 | + -0.75426212, | ||
| 1224 | + 0.65657341, | ||
| 1225 | + -0.75640671, | ||
| 1226 | + 0.65410159, | ||
| 1227 | + -0.75854320, | ||
| 1228 | + 0.65162275, | ||
| 1229 | + -0.76067157, | ||
| 1230 | + 0.64913694, | ||
| 1231 | + -0.76279178, | ||
| 1232 | + 0.64664418, | ||
| 1233 | + -0.76490383, | ||
| 1234 | + 0.64414449, | ||
| 1235 | + -0.76700769, | ||
| 1236 | + 0.64163790, | ||
| 1237 | + -0.76910334, | ||
| 1238 | + 0.63912444, | ||
| 1239 | + -0.77119075, | ||
| 1240 | + 0.63660414, | ||
| 1241 | + -0.77326989, | ||
| 1242 | + 0.63407702, | ||
| 1243 | + -0.77534076, | ||
| 1244 | + 0.63154311, | ||
| 1245 | + -0.77740333, | ||
| 1246 | + 0.62900244, | ||
| 1247 | + -0.77945757, | ||
| 1248 | + 0.62645503, | ||
| 1249 | + -0.78150346, | ||
| 1250 | + 0.62390091, | ||
| 1251 | + -0.78354098, | ||
| 1252 | + 0.62134011, | ||
| 1253 | + -0.78557011, | ||
| 1254 | + 0.61877265, | ||
| 1255 | + -0.78759083, | ||
| 1256 | + 0.61619857, | ||
| 1257 | + -0.78960312, | ||
| 1258 | + 0.61361789, | ||
| 1259 | + -0.79160694, | ||
| 1260 | + 0.61103064, | ||
| 1261 | + -0.79360229, | ||
| 1262 | + 0.60843685, | ||
| 1263 | + -0.79558915, | ||
| 1264 | + 0.60583654, | ||
| 1265 | + -0.79756748, | ||
| 1266 | + 0.60322974, | ||
| 1267 | + -0.79953727, | ||
| 1268 | + 0.60061648, | ||
| 1269 | + -0.80149850, | ||
| 1270 | + 0.59799679, | ||
| 1271 | + -0.80345114, | ||
| 1272 | + 0.59537069, | ||
| 1273 | + -0.80539518, | ||
| 1274 | + 0.59273822, | ||
| 1275 | + -0.80733060, | ||
| 1276 | + 0.59009940, | ||
| 1277 | + -0.80925737, | ||
| 1278 | + 0.58745427, | ||
| 1279 | + -0.81117547, | ||
| 1280 | + 0.58480284, | ||
| 1281 | + -0.81308489, | ||
| 1282 | + 0.58214514, | ||
| 1283 | + -0.81498559, | ||
| 1284 | + 0.57948122, | ||
| 1285 | + -0.81687757, | ||
| 1286 | + 0.57681109, | ||
| 1287 | + -0.81876081, | ||
| 1288 | + 0.57413478, | ||
| 1289 | + -0.82063527, | ||
| 1290 | + 0.57145232, | ||
| 1291 | + -0.82250095, | ||
| 1292 | + 0.56876374, | ||
| 1293 | + -0.82435781, | ||
| 1294 | + 0.56606907, | ||
| 1295 | + -0.82620585, | ||
| 1296 | + 0.56336834, | ||
| 1297 | + -0.82804505, | ||
| 1298 | + 0.56066158, | ||
| 1299 | + -0.82987537, | ||
| 1300 | + 0.55794881, | ||
| 1301 | + -0.83169681, | ||
| 1302 | + 0.55523006, | ||
| 1303 | + -0.83350933, | ||
| 1304 | + 0.55250537, | ||
| 1305 | + -0.83531294, | ||
| 1306 | + 0.54977477, | ||
| 1307 | + -0.83710760, | ||
| 1308 | + 0.54703827, | ||
| 1309 | + -0.83889329, | ||
| 1310 | + 0.54429592, | ||
| 1311 | + -0.84067000, | ||
| 1312 | + 0.54154774, | ||
| 1313 | + -0.84243770, | ||
| 1314 | + 0.53879376, | ||
| 1315 | + -0.84419639, | ||
| 1316 | + 0.53603401, | ||
| 1317 | + -0.84594603, | ||
| 1318 | + 0.53326852, | ||
| 1319 | + -0.84768662, | ||
| 1320 | + 0.53049731, | ||
| 1321 | + -0.84941812, | ||
| 1322 | + 0.52772043, | ||
| 1323 | + -0.85114053, | ||
| 1324 | + 0.52493790, | ||
| 1325 | + -0.85285383, | ||
| 1326 | + 0.52214974, | ||
| 1327 | + -0.85455799, | ||
| 1328 | + 0.51935599, | ||
| 1329 | + -0.85625300, | ||
| 1330 | + 0.51655668, | ||
| 1331 | + -0.85793884, | ||
| 1332 | + 0.51375184, | ||
| 1333 | + -0.85961549, | ||
| 1334 | + 0.51094149, | ||
| 1335 | + -0.86128294, | ||
| 1336 | + 0.50812568, | ||
| 1337 | + -0.86294116, | ||
| 1338 | + 0.50530442, | ||
| 1339 | + -0.86459014, | ||
| 1340 | + 0.50247775, | ||
| 1341 | + -0.86622986, | ||
| 1342 | + 0.49964570, | ||
| 1343 | + -0.86786031, | ||
| 1344 | + 0.49680830, | ||
| 1345 | + -0.86948146, | ||
| 1346 | + 0.49396558, | ||
| 1347 | + -0.87109330, | ||
| 1348 | + 0.49111757, | ||
| 1349 | + -0.87269581, | ||
| 1350 | + 0.48826430, | ||
| 1351 | + -0.87428898, | ||
| 1352 | + 0.48540580, | ||
| 1353 | + -0.87587278, | ||
| 1354 | + 0.48254210, | ||
| 1355 | + -0.87744720, | ||
| 1356 | + 0.47967323, | ||
| 1357 | + -0.87901223, | ||
| 1358 | + 0.47679923, | ||
| 1359 | + -0.88056784, | ||
| 1360 | + 0.47392012, | ||
| 1361 | + -0.88211402, | ||
| 1362 | + 0.47103594, | ||
| 1363 | + -0.88365076, | ||
| 1364 | + 0.46814671, | ||
| 1365 | + -0.88517803, | ||
| 1366 | + 0.46525247, | ||
| 1367 | + -0.88669582, | ||
| 1368 | + 0.46235324, | ||
| 1369 | + -0.88820412, | ||
| 1370 | + 0.45944907, | ||
| 1371 | + -0.88970290, | ||
| 1372 | + 0.45653997, | ||
| 1373 | + -0.89119216, | ||
| 1374 | + 0.45362599, | ||
| 1375 | + -0.89267187, | ||
| 1376 | + 0.45070714, | ||
| 1377 | + -0.89414203, | ||
| 1378 | + 0.44778347, | ||
| 1379 | + -0.89560260, | ||
| 1380 | + 0.44485501, | ||
| 1381 | + -0.89705359, | ||
| 1382 | + 0.44192178, | ||
| 1383 | + -0.89849497, | ||
| 1384 | + 0.43898381, | ||
| 1385 | + -0.89992673, | ||
| 1386 | + 0.43604115, | ||
| 1387 | + -0.90134885, | ||
| 1388 | + 0.43309382, | ||
| 1389 | + -0.90276131, | ||
| 1390 | + 0.43014185, | ||
| 1391 | + -0.90416411, | ||
| 1392 | + 0.42718527, | ||
| 1393 | + -0.90555723, | ||
| 1394 | + 0.42422412, | ||
| 1395 | + -0.90694065, | ||
| 1396 | + 0.42125842, | ||
| 1397 | + -0.90831436, | ||
| 1398 | + 0.41828822, | ||
| 1399 | + -0.90967833, | ||
| 1400 | + 0.41531353, | ||
| 1401 | + -0.91103257, | ||
| 1402 | + 0.41233440, | ||
| 1403 | + -0.91237705, | ||
| 1404 | + 0.40935085, | ||
| 1405 | + -0.91371176, | ||
| 1406 | + 0.40636291, | ||
| 1407 | + -0.91503669, | ||
| 1408 | + 0.40337063, | ||
| 1409 | + -0.91635181, | ||
| 1410 | + 0.40037402, | ||
| 1411 | + -0.91765712, | ||
| 1412 | + 0.39737313, | ||
| 1413 | + -0.91895261, | ||
| 1414 | + 0.39436798, | ||
| 1415 | + -0.92023825, | ||
| 1416 | + 0.39135861, | ||
| 1417 | + -0.92151404, | ||
| 1418 | + 0.38834505, | ||
| 1419 | + -0.92277996, | ||
| 1420 | + 0.38532733, | ||
| 1421 | + -0.92403600, | ||
| 1422 | + 0.38230548, | ||
| 1423 | + -0.92528214, | ||
| 1424 | + 0.37927953, | ||
| 1425 | + -0.92651837, | ||
| 1426 | + 0.37624953, | ||
| 1427 | + -0.92774468, | ||
| 1428 | + 0.37321550, | ||
| 1429 | + -0.92896106, | ||
| 1430 | + 0.37017747, | ||
| 1431 | + -0.93016748, | ||
| 1432 | + 0.36713547, | ||
| 1433 | + -0.93136395, | ||
| 1434 | + 0.36408955, | ||
| 1435 | + -0.93255044, | ||
| 1436 | + 0.36103972, | ||
| 1437 | + -0.93372694, | ||
| 1438 | + 0.35798603, | ||
| 1439 | + -0.93489345, | ||
| 1440 | + 0.35492850, | ||
| 1441 | + -0.93604994, | ||
| 1442 | + 0.35186718, | ||
| 1443 | + -0.93719641, | ||
| 1444 | + 0.34880208, | ||
| 1445 | + -0.93833284, | ||
| 1446 | + 0.34573325, | ||
| 1447 | + -0.93945922, | ||
| 1448 | + 0.34266072, | ||
| 1449 | + -0.94057555, | ||
| 1450 | + 0.33958451, | ||
| 1451 | + -0.94168180, | ||
| 1452 | + 0.33650468, | ||
| 1453 | + -0.94277796, | ||
| 1454 | + 0.33342123, | ||
| 1455 | + -0.94386403, | ||
| 1456 | + 0.33033422, | ||
| 1457 | + -0.94493999, | ||
| 1458 | + 0.32724367, | ||
| 1459 | + -0.94600583, | ||
| 1460 | + 0.32414961, | ||
| 1461 | + -0.94706154, | ||
| 1462 | + 0.32105209, | ||
| 1463 | + -0.94810711, | ||
| 1464 | + 0.31795112, | ||
| 1465 | + -0.94914252, | ||
| 1466 | + 0.31484675, | ||
| 1467 | + -0.95016777, | ||
| 1468 | + 0.31173901, | ||
| 1469 | + -0.95118284, | ||
| 1470 | + 0.30862793, | ||
| 1471 | + -0.95218773, | ||
| 1472 | + 0.30551354, | ||
| 1473 | + -0.95318242, | ||
| 1474 | + 0.30239588, | ||
| 1475 | + -0.95416690, | ||
| 1476 | + 0.29927499, | ||
| 1477 | + -0.95514117, | ||
| 1478 | + 0.29615089, | ||
| 1479 | + -0.95610520, | ||
| 1480 | + 0.29302362, | ||
| 1481 | + -0.95705900, | ||
| 1482 | + 0.28989321, | ||
| 1483 | + -0.95800255, | ||
| 1484 | + 0.28675969, | ||
| 1485 | + -0.95893583, | ||
| 1486 | + 0.28362310, | ||
| 1487 | + -0.95985885, | ||
| 1488 | + 0.28048348, | ||
| 1489 | + -0.96077159, | ||
| 1490 | + 0.27734085, | ||
| 1491 | + -0.96167404, | ||
| 1492 | + 0.27419526, | ||
| 1493 | + -0.96256619, | ||
| 1494 | + 0.27104672, | ||
| 1495 | + -0.96344803, | ||
| 1496 | + 0.26789529, | ||
| 1497 | + -0.96431956, | ||
| 1498 | + 0.26474098, | ||
| 1499 | + -0.96518076, | ||
| 1500 | + 0.26158384, | ||
| 1501 | + -0.96603162, | ||
| 1502 | + 0.25842390, | ||
| 1503 | + -0.96687213, | ||
| 1504 | + 0.25526119, | ||
| 1505 | + -0.96770230, | ||
| 1506 | + 0.25209575, | ||
| 1507 | + -0.96852209, | ||
| 1508 | + 0.24892761, | ||
| 1509 | + -0.96933152, | ||
| 1510 | + 0.24575680, | ||
| 1511 | + -0.97013057, | ||
| 1512 | + 0.24258336, | ||
| 1513 | + -0.97091922, | ||
| 1514 | + 0.23940732, | ||
| 1515 | + -0.97169748, | ||
| 1516 | + 0.23622872, | ||
| 1517 | + -0.97246533, | ||
| 1518 | + 0.23304759, | ||
| 1519 | + -0.97322277, | ||
| 1520 | + 0.22986396, | ||
| 1521 | + -0.97396979, | ||
| 1522 | + 0.22667787, | ||
| 1523 | + -0.97470637, | ||
| 1524 | + 0.22348935, | ||
| 1525 | + -0.97543252, | ||
| 1526 | + 0.22029844, | ||
| 1527 | + -0.97614822, | ||
| 1528 | + 0.21710517, | ||
| 1529 | + -0.97685347, | ||
| 1530 | + 0.21390958, | ||
| 1531 | + -0.97754825, | ||
| 1532 | + 0.21071169, | ||
| 1533 | + -0.97823257, | ||
| 1534 | + 0.20751155, | ||
| 1535 | + -0.97890641, | ||
| 1536 | + 0.20430919, | ||
| 1537 | + -0.97956977, | ||
| 1538 | + 0.20110463, | ||
| 1539 | + -0.98022263, | ||
| 1540 | + 0.19789793, | ||
| 1541 | + -0.98086500, | ||
| 1542 | + 0.19468910, | ||
| 1543 | + -0.98149687, | ||
| 1544 | + 0.19147819, | ||
| 1545 | + -0.98211822, | ||
| 1546 | + 0.18826523, | ||
| 1547 | + -0.98272906, | ||
| 1548 | + 0.18505026, | ||
| 1549 | + -0.98332937, | ||
| 1550 | + 0.18183330, | ||
| 1551 | + -0.98391915, | ||
| 1552 | + 0.17861439, | ||
| 1553 | + -0.98449840, | ||
| 1554 | + 0.17539357, | ||
| 1555 | + -0.98506710, | ||
| 1556 | + 0.17217088, | ||
| 1557 | + -0.98562525, | ||
| 1558 | + 0.16894634, | ||
| 1559 | + -0.98617285, | ||
| 1560 | + 0.16571999, | ||
| 1561 | + -0.98670988, | ||
| 1562 | + 0.16249186, | ||
| 1563 | + -0.98723635, | ||
| 1564 | + 0.15926200, | ||
| 1565 | + -0.98775225, | ||
| 1566 | + 0.15603043, | ||
| 1567 | + -0.98825757, | ||
| 1568 | + 0.15279719, | ||
| 1569 | + -0.98875230, | ||
| 1570 | + 0.14956231, | ||
| 1571 | + -0.98923645, | ||
| 1572 | + 0.14632583, | ||
| 1573 | + -0.98971000, | ||
| 1574 | + 0.14308778, | ||
| 1575 | + -0.99017295, | ||
| 1576 | + 0.13984820, | ||
| 1577 | + -0.99062530, | ||
| 1578 | + 0.13660713, | ||
| 1579 | + -0.99106704, | ||
| 1580 | + 0.13336459, | ||
| 1581 | + -0.99149817, | ||
| 1582 | + 0.13012062, | ||
| 1583 | + -0.99191868, | ||
| 1584 | + 0.12687526, | ||
| 1585 | + -0.99232857, | ||
| 1586 | + 0.12362854, | ||
| 1587 | + -0.99272783, | ||
| 1588 | + 0.12038049, | ||
| 1589 | + -0.99311645, | ||
| 1590 | + 0.11713116, | ||
| 1591 | + -0.99349445, | ||
| 1592 | + 0.11388057, | ||
| 1593 | + -0.99386180, | ||
| 1594 | + 0.11062877, | ||
| 1595 | + -0.99421851, | ||
| 1596 | + 0.10737578, | ||
| 1597 | + -0.99456457, | ||
| 1598 | + 0.10412163, | ||
| 1599 | + -0.99489998, | ||
| 1600 | + 0.10086638, | ||
| 1601 | + -0.99522474, | ||
| 1602 | + 0.097610040, | ||
| 1603 | + -0.99553884, | ||
| 1604 | + 0.094352658, | ||
| 1605 | + -0.99584227, | ||
| 1606 | + 0.091094266, | ||
| 1607 | + -0.99613505, | ||
| 1608 | + 0.087834897, | ||
| 1609 | + -0.99641715, | ||
| 1610 | + 0.084574589, | ||
| 1611 | + -0.99668858, | ||
| 1612 | + 0.081313374, | ||
| 1613 | + -0.99694934, | ||
| 1614 | + 0.078051289, | ||
| 1615 | + -0.99719943, | ||
| 1616 | + 0.074788367, | ||
| 1617 | + -0.99743883, | ||
| 1618 | + 0.071524645, | ||
| 1619 | + -0.99766756, | ||
| 1620 | + 0.068260157, | ||
| 1621 | + -0.99788559, | ||
| 1622 | + 0.064994938, | ||
| 1623 | + -0.99809295, | ||
| 1624 | + 0.061729023, | ||
| 1625 | + -0.99828961, | ||
| 1626 | + 0.058462447, | ||
| 1627 | + -0.99847558, | ||
| 1628 | + 0.055195244, | ||
| 1629 | + -0.99865086, | ||
| 1630 | + 0.051927451, | ||
| 1631 | + -0.99881544, | ||
| 1632 | + 0.048659101, | ||
| 1633 | + -0.99896933, | ||
| 1634 | + 0.045390231, | ||
| 1635 | + -0.99911252, | ||
| 1636 | + 0.042120874, | ||
| 1637 | + -0.99924501, | ||
| 1638 | + 0.038851066, | ||
| 1639 | + -0.99936680, | ||
| 1640 | + 0.035580842, | ||
| 1641 | + -0.99947789, | ||
| 1642 | + 0.032310238, | ||
| 1643 | + -0.99957827, | ||
| 1644 | + 0.029039287, | ||
| 1645 | + -0.99966795, | ||
| 1646 | + 0.025768025, | ||
| 1647 | + -0.99974692, | ||
| 1648 | + 0.022496487, | ||
| 1649 | + -0.99981519, | ||
| 1650 | + 0.019224708, | ||
| 1651 | + -0.99987275, | ||
| 1652 | + 0.015952723, | ||
| 1653 | + -0.99991960, | ||
| 1654 | + 0.012680568, | ||
| 1655 | + -0.99995574, | ||
| 1656 | + 0.0094082767, | ||
| 1657 | + -0.99998118, | ||
| 1658 | + 0.0061358846, | ||
| 1659 | + -0.99999590, | ||
| 1660 | + 0.0028634269, | ||
| 1661 | + -0.00081812300, | ||
| 1662 | + 0.99999967, | ||
| 1663 | + -0.0073630412, | ||
| 1664 | + 0.99997289, | ||
| 1665 | + -0.013907644, | ||
| 1666 | + 0.99990328, | ||
| 1667 | + -0.020451651, | ||
| 1668 | + 0.99979084, | ||
| 1669 | + -0.026994782, | ||
| 1670 | + 0.99963557, | ||
| 1671 | + -0.033536757, | ||
| 1672 | + 0.99943748, | ||
| 1673 | + -0.040077295, | ||
| 1674 | + 0.99919658, | ||
| 1675 | + -0.046616116, | ||
| 1676 | + 0.99891288, | ||
| 1677 | + -0.053152941, | ||
| 1678 | + 0.99858638, | ||
| 1679 | + -0.059687488, | ||
| 1680 | + 0.99821711, | ||
| 1681 | + -0.066219479, | ||
| 1682 | + 0.99780508, | ||
| 1683 | + -0.072748633, | ||
| 1684 | + 0.99735031, | ||
| 1685 | + -0.079274670, | ||
| 1686 | + 0.99685281, | ||
| 1687 | + -0.085797312, | ||
| 1688 | + 0.99631261, | ||
| 1689 | + -0.092316279, | ||
| 1690 | + 0.99572973, | ||
| 1691 | + -0.098831291, | ||
| 1692 | + 0.99510420, | ||
| 1693 | + -0.10534207, | ||
| 1694 | + 0.99443605, | ||
| 1695 | + -0.11184834, | ||
| 1696 | + 0.99372529, | ||
| 1697 | + -0.11834981, | ||
| 1698 | + 0.99297196, | ||
| 1699 | + -0.12484622, | ||
| 1700 | + 0.99217610, | ||
| 1701 | + -0.13133727, | ||
| 1702 | + 0.99133774, | ||
| 1703 | + -0.13782270, | ||
| 1704 | + 0.99045692, | ||
| 1705 | + -0.14430223, | ||
| 1706 | + 0.98953366, | ||
| 1707 | + -0.15077558, | ||
| 1708 | + 0.98856802, | ||
| 1709 | + -0.15724246, | ||
| 1710 | + 0.98756003, | ||
| 1711 | + -0.16370261, | ||
| 1712 | + 0.98650973, | ||
| 1713 | + -0.17015575, | ||
| 1714 | + 0.98541718, | ||
| 1715 | + -0.17660160, | ||
| 1716 | + 0.98428242, | ||
| 1717 | + -0.18303989, | ||
| 1718 | + 0.98310549, | ||
| 1719 | + -0.18947033, | ||
| 1720 | + 0.98188645, | ||
| 1721 | + -0.19589266, | ||
| 1722 | + 0.98062534, | ||
| 1723 | + -0.20230660, | ||
| 1724 | + 0.97932224, | ||
| 1725 | + -0.20871187, | ||
| 1726 | + 0.97797718, | ||
| 1727 | + -0.21510820, | ||
| 1728 | + 0.97659022, | ||
| 1729 | + -0.22149531, | ||
| 1730 | + 0.97516144, | ||
| 1731 | + -0.22787294, | ||
| 1732 | + 0.97369088, | ||
| 1733 | + -0.23424080, | ||
| 1734 | + 0.97217861, | ||
| 1735 | + -0.24059864, | ||
| 1736 | + 0.97062469, | ||
| 1737 | + -0.24694616, | ||
| 1738 | + 0.96902920, | ||
| 1739 | + -0.25328311, | ||
| 1740 | + 0.96739220, | ||
| 1741 | + -0.25960920, | ||
| 1742 | + 0.96571376, | ||
| 1743 | + -0.26592418, | ||
| 1744 | + 0.96399395, | ||
| 1745 | + -0.27222777, | ||
| 1746 | + 0.96223284, | ||
| 1747 | + -0.27851969, | ||
| 1748 | + 0.96043052, | ||
| 1749 | + -0.28479968, | ||
| 1750 | + 0.95858705, | ||
| 1751 | + -0.29106748, | ||
| 1752 | + 0.95670253, | ||
| 1753 | + -0.29732280, | ||
| 1754 | + 0.95477702, | ||
| 1755 | + -0.30356539, | ||
| 1756 | + 0.95281061, | ||
| 1757 | + -0.30979497, | ||
| 1758 | + 0.95080338, | ||
| 1759 | + -0.31601129, | ||
| 1760 | + 0.94875543, | ||
| 1761 | + -0.32221406, | ||
| 1762 | + 0.94666684, | ||
| 1763 | + -0.32840304, | ||
| 1764 | + 0.94453769, | ||
| 1765 | + -0.33457794, | ||
| 1766 | + 0.94236808, | ||
| 1767 | + -0.34073852, | ||
| 1768 | + 0.94015810, | ||
| 1769 | + -0.34688450, | ||
| 1770 | + 0.93790786, | ||
| 1771 | + -0.35301562, | ||
| 1772 | + 0.93561743, | ||
| 1773 | + -0.35913161, | ||
| 1774 | + 0.93328693, | ||
| 1775 | + -0.36523223, | ||
| 1776 | + 0.93091644, | ||
| 1777 | + -0.37131719, | ||
| 1778 | + 0.92850608, | ||
| 1779 | + -0.37738626, | ||
| 1780 | + 0.92605595, | ||
| 1781 | + -0.38343915, | ||
| 1782 | + 0.92356614, | ||
| 1783 | + -0.38947562, | ||
| 1784 | + 0.92103677, | ||
| 1785 | + -0.39549541, | ||
| 1786 | + 0.91846795, | ||
| 1787 | + -0.40149825, | ||
| 1788 | + 0.91585979, | ||
| 1789 | + -0.40748390, | ||
| 1790 | + 0.91321239, | ||
| 1791 | + -0.41345209, | ||
| 1792 | + 0.91052587, | ||
| 1793 | + -0.41940257, | ||
| 1794 | + 0.90780035, | ||
| 1795 | + -0.42533508, | ||
| 1796 | + 0.90503595, | ||
| 1797 | + -0.43124938, | ||
| 1798 | + 0.90223277, | ||
| 1799 | + -0.43714520, | ||
| 1800 | + 0.89939095, | ||
| 1801 | + -0.44302229, | ||
| 1802 | + 0.89651059, | ||
| 1803 | + -0.44888041, | ||
| 1804 | + 0.89359184, | ||
| 1805 | + -0.45471930, | ||
| 1806 | + 0.89063481, | ||
| 1807 | + -0.46053871, | ||
| 1808 | + 0.88763962, | ||
| 1809 | + -0.46633839, | ||
| 1810 | + 0.88460641, | ||
| 1811 | + -0.47211810, | ||
| 1812 | + 0.88153531, | ||
| 1813 | + -0.47787758, | ||
| 1814 | + 0.87842644, | ||
| 1815 | + -0.48361659, | ||
| 1816 | + 0.87527995, | ||
| 1817 | + -0.48933489, | ||
| 1818 | + 0.87209596, | ||
| 1819 | + -0.49503222, | ||
| 1820 | + 0.86887462, | ||
| 1821 | + -0.50070835, | ||
| 1822 | + 0.86561605, | ||
| 1823 | + -0.50636303, | ||
| 1824 | + 0.86232041, | ||
| 1825 | + -0.51199602, | ||
| 1826 | + 0.85898782, | ||
| 1827 | + -0.51760707, | ||
| 1828 | + 0.85561844, | ||
| 1829 | + -0.52319595, | ||
| 1830 | + 0.85221241, | ||
| 1831 | + -0.52876243, | ||
| 1832 | + 0.84876987, | ||
| 1833 | + -0.53430625, | ||
| 1834 | + 0.84529098, | ||
| 1835 | + -0.53982718, | ||
| 1836 | + 0.84177587, | ||
| 1837 | + -0.54532499, | ||
| 1838 | + 0.83822471, | ||
| 1839 | + -0.55079944, | ||
| 1840 | + 0.83463763, | ||
| 1841 | + -0.55625029, | ||
| 1842 | + 0.83101481, | ||
| 1843 | + -0.56167732, | ||
| 1844 | + 0.82735639, | ||
| 1845 | + -0.56708028, | ||
| 1846 | + 0.82366252, | ||
| 1847 | + -0.57245896, | ||
| 1848 | + 0.81993338, | ||
| 1849 | + -0.57781311, | ||
| 1850 | + 0.81616911, | ||
| 1851 | + -0.58314251, | ||
| 1852 | + 0.81236987, | ||
| 1853 | + -0.58844693, | ||
| 1854 | + 0.80853584, | ||
| 1855 | + -0.59372614, | ||
| 1856 | + 0.80466718, | ||
| 1857 | + -0.59897992, | ||
| 1858 | + 0.80076404, | ||
| 1859 | + -0.60420805, | ||
| 1860 | + 0.79682660, | ||
| 1861 | + -0.60941029, | ||
| 1862 | + 0.79285503, | ||
| 1863 | + -0.61458642, | ||
| 1864 | + 0.78884950, | ||
| 1865 | + -0.61973623, | ||
| 1866 | + 0.78481017, | ||
| 1867 | + -0.62485949, | ||
| 1868 | + 0.78073723, | ||
| 1869 | + -0.62995598, | ||
| 1870 | + 0.77663084, | ||
| 1871 | + -0.63502549, | ||
| 1872 | + 0.77249118, | ||
| 1873 | + -0.64006780, | ||
| 1874 | + 0.76831844, | ||
| 1875 | + -0.64508268, | ||
| 1876 | + 0.76411277, | ||
| 1877 | + -0.65006994, | ||
| 1878 | + 0.75987438, | ||
| 1879 | + -0.65502934, | ||
| 1880 | + 0.75560344, | ||
| 1881 | + -0.65996069, | ||
| 1882 | + 0.75130013, | ||
| 1883 | + -0.66486377, | ||
| 1884 | + 0.74696464, | ||
| 1885 | + -0.66973837, | ||
| 1886 | + 0.74259715, | ||
| 1887 | + -0.67458427, | ||
| 1888 | + 0.73819784, | ||
| 1889 | + -0.67940128, | ||
| 1890 | + 0.73376692, | ||
| 1891 | + -0.68418919, | ||
| 1892 | + 0.72930457, | ||
| 1893 | + -0.68894779, | ||
| 1894 | + 0.72481097, | ||
| 1895 | + -0.69367688, | ||
| 1896 | + 0.72028632, | ||
| 1897 | + -0.69837625, | ||
| 1898 | + 0.71573083, | ||
| 1899 | + -0.70304571, | ||
| 1900 | + 0.71114467, | ||
| 1901 | + -0.70768504, | ||
| 1902 | + 0.70652804, | ||
| 1903 | + -0.71229407, | ||
| 1904 | + 0.70188116, | ||
| 1905 | + -0.71687258, | ||
| 1906 | + 0.69720420, | ||
| 1907 | + -0.72142039, | ||
| 1908 | + 0.69249738, | ||
| 1909 | + -0.72593729, | ||
| 1910 | + 0.68776090, | ||
| 1911 | + -0.73042309, | ||
| 1912 | + 0.68299495, | ||
| 1913 | + -0.73487761, | ||
| 1914 | + 0.67819975, | ||
| 1915 | + -0.73930064, | ||
| 1916 | + 0.67337550, | ||
| 1917 | + -0.74369201, | ||
| 1918 | + 0.66852240, | ||
| 1919 | + -0.74805152, | ||
| 1920 | + 0.66364066, | ||
| 1921 | + -0.75237898, | ||
| 1922 | + 0.65873050, | ||
| 1923 | + -0.75667422, | ||
| 1924 | + 0.65379211, | ||
| 1925 | + -0.76093704, | ||
| 1926 | + 0.64882573, | ||
| 1927 | + -0.76516727, | ||
| 1928 | + 0.64383154, | ||
| 1929 | + -0.76936471, | ||
| 1930 | + 0.63880978, | ||
| 1931 | + -0.77352921, | ||
| 1932 | + 0.63376065, | ||
| 1933 | + -0.77766056, | ||
| 1934 | + 0.62868438, | ||
| 1935 | + -0.78175861, | ||
| 1936 | + 0.62358117, | ||
| 1937 | + -0.78582316, | ||
| 1938 | + 0.61845126, | ||
| 1939 | + -0.78985406, | ||
| 1940 | + 0.61329485, | ||
| 1941 | + -0.79385112, | ||
| 1942 | + 0.60811216, | ||
| 1943 | + -0.79781417, | ||
| 1944 | + 0.60290343, | ||
| 1945 | + -0.80174305, | ||
| 1946 | + 0.59766888, | ||
| 1947 | + -0.80563758, | ||
| 1948 | + 0.59240872, | ||
| 1949 | + -0.80949760, | ||
| 1950 | + 0.58712318, | ||
| 1951 | + -0.81332295, | ||
| 1952 | + 0.58181249, | ||
| 1953 | + -0.81711346, | ||
| 1954 | + 0.57647688, | ||
| 1955 | + -0.82086896, | ||
| 1956 | + 0.57111658, | ||
| 1957 | + -0.82458930, | ||
| 1958 | + 0.56573181, | ||
| 1959 | + -0.82827432, | ||
| 1960 | + 0.56032281, | ||
| 1961 | + -0.83192386, | ||
| 1962 | + 0.55488980, | ||
| 1963 | + -0.83553776, | ||
| 1964 | + 0.54943303, | ||
| 1965 | + -0.83911587, | ||
| 1966 | + 0.54395272, | ||
| 1967 | + -0.84265803, | ||
| 1968 | + 0.53844911, | ||
| 1969 | + -0.84616410, | ||
| 1970 | + 0.53292243, | ||
| 1971 | + -0.84963392, | ||
| 1972 | + 0.52737292, | ||
| 1973 | + -0.85306735, | ||
| 1974 | + 0.52180083, | ||
| 1975 | + -0.85646423, | ||
| 1976 | + 0.51620638, | ||
| 1977 | + -0.85982442, | ||
| 1978 | + 0.51058981, | ||
| 1979 | + -0.86314779, | ||
| 1980 | + 0.50495138, | ||
| 1981 | + -0.86643418, | ||
| 1982 | + 0.49929132, | ||
| 1983 | + -0.86968345, | ||
| 1984 | + 0.49360987, | ||
| 1985 | + -0.87289547, | ||
| 1986 | + 0.48790727, | ||
| 1987 | + -0.87607009, | ||
| 1988 | + 0.48218377, | ||
| 1989 | + -0.87920719, | ||
| 1990 | + 0.47643962, | ||
| 1991 | + -0.88230663, | ||
| 1992 | + 0.47067506, | ||
| 1993 | + -0.88536827, | ||
| 1994 | + 0.46489034, | ||
| 1995 | + -0.88839199, | ||
| 1996 | + 0.45908570, | ||
| 1997 | + -0.89137765, | ||
| 1998 | + 0.45326139, | ||
| 1999 | + -0.89432512, | ||
| 2000 | + 0.44741768, | ||
crates/ec-opus/src/celt_flp/vq.rsadded+250 -0
| @@ -0,0 +1,250 @@ | |||
| 1 | +use super::{EPSILON, celt_atan2p_norm, celt_cos_norm, celt_rcp, celt_rsqrt, celt_sqrt}; | ||
| 2 | +use crate::celt::{pvq_u, pvq_v}; | ||
| 3 | +use crate::range::RangeEncoder; | ||
| 4 | + | ||
| 5 | +const SPREAD_FACTOR: [i32; 3] = [15, 10, 5]; | ||
| 6 | +const MAX_N: usize = 176; | ||
| 7 | + | ||
| 8 | +fn inner_prod(x: &[f32], y: &[f32], n: usize) -> f32 { | ||
| 9 | + let mut xy: f32 = 0.0; | ||
| 10 | + for i in 0..n { | ||
| 11 | + xy += x[i] * y[i]; | ||
| 12 | + } | ||
| 13 | + xy | ||
| 14 | +} | ||
| 15 | + | ||
| 16 | +fn exp_rotation1(x: &mut [f32], len: usize, stride: usize, c: f32, s: f32) { | ||
| 17 | + let ms = -s; | ||
| 18 | + for i in 0..len.saturating_sub(stride) { | ||
| 19 | + let x1 = x[i]; | ||
| 20 | + let x2 = x[i + stride]; | ||
| 21 | + x[i + stride] = c * x2 + s * x1; | ||
| 22 | + x[i] = c * x1 + ms * x2; | ||
| 23 | + } | ||
| 24 | + for i in (0..len.saturating_sub(2 * stride)).rev() { | ||
| 25 | + let x1 = x[i]; | ||
| 26 | + let x2 = x[i + stride]; | ||
| 27 | + x[i + stride] = c * x2 + s * x1; | ||
| 28 | + x[i] = c * x1 + ms * x2; | ||
| 29 | + } | ||
| 30 | +} | ||
| 31 | + | ||
| 32 | +/// `exp_rotation`. | ||
| 33 | +pub(crate) fn exp_rotation( | ||
| 34 | + x: &mut [f32], | ||
| 35 | + len: usize, | ||
| 36 | + dir: i32, | ||
| 37 | + stride: usize, | ||
| 38 | + k: i32, | ||
| 39 | + spread: i32, | ||
| 40 | +) { | ||
| 41 | + if 2 * k >= len as i32 || spread == 0 { | ||
| 42 | + return; | ||
| 43 | + } | ||
| 44 | + let factor = SPREAD_FACTOR[(spread - 1) as usize]; | ||
| 45 | + let gain = len as f32 / (len as i32 + factor * k) as f32; | ||
| 46 | + let theta = 0.5f32 * (gain * gain); | ||
| 47 | + let c = celt_cos_norm(theta); | ||
| 48 | + let s = celt_cos_norm(1.0 - theta); | ||
| 49 | + let mut stride2 = 0usize; | ||
| 50 | + if len >= 8 * stride { | ||
| 51 | + stride2 = 1; | ||
| 52 | + while (stride2 * stride2 + stride2) * stride + (stride >> 2) < len { | ||
| 53 | + stride2 += 1; | ||
| 54 | + } | ||
| 55 | + } | ||
| 56 | + let len = len / stride; | ||
| 57 | + for i in 0..stride { | ||
| 58 | + let seg = &mut x[i * len..]; | ||
| 59 | + if dir < 0 { | ||
| 60 | + if stride2 != 0 { | ||
| 61 | + exp_rotation1(seg, len, stride2, s, c); | ||
| 62 | + } | ||
| 63 | + exp_rotation1(seg, len, 1, c, s); | ||
| 64 | + } else { | ||
| 65 | + exp_rotation1(seg, len, 1, c, -s); | ||
| 66 | + if stride2 != 0 { | ||
| 67 | + exp_rotation1(seg, len, stride2, s, -c); | ||
| 68 | + } | ||
| 69 | + } | ||
| 70 | + } | ||
| 71 | +} | ||
| 72 | + | ||
| 73 | +fn normalise_residual(iy: &[i32], x: &mut [f32], n: usize, ryy: f32, gain: f32) { | ||
| 74 | + let g = celt_rsqrt(ryy) * gain; | ||
| 75 | + for i in 0..n { | ||
| 76 | + x[i] = iy[i] as f32 * g; | ||
| 77 | + } | ||
| 78 | +} | ||
| 79 | + | ||
| 80 | +fn extract_collapse_mask(iy: &[i32], n: usize, b: usize) -> u32 { | ||
| 81 | + if b <= 1 { | ||
| 82 | + return 1; | ||
| 83 | + } | ||
| 84 | + let n0 = n / b; | ||
| 85 | + let mut mask = 0u32; | ||
| 86 | + for i in 0..b { | ||
| 87 | + let mut tmp = 0u32; | ||
| 88 | + for j in 0..n0 { | ||
| 89 | + tmp |= iy[i * n0 + j] as u32; | ||
| 90 | + } | ||
| 91 | + mask |= ((tmp != 0) as u32) << i; | ||
| 92 | + } | ||
| 93 | + mask | ||
| 94 | +} | ||
| 95 | + | ||
| 96 | +fn op_pvq_search(x: &mut [f32], iy: &mut [i32], k: i32, n: usize) -> f32 { | ||
| 97 | + let mut y_buf = [0f32; MAX_N]; | ||
| 98 | + let mut signx_buf = [0i32; MAX_N]; | ||
| 99 | + let y = &mut y_buf[..n]; | ||
| 100 | + let signx = &mut signx_buf[..n]; | ||
| 101 | + for j in 0..n { | ||
| 102 | + signx[j] = (x[j] < 0.0) as i32; | ||
| 103 | + x[j] = x[j].abs(); | ||
| 104 | + iy[j] = 0; | ||
| 105 | + y[j] = 0.0; | ||
| 106 | + } | ||
| 107 | + | ||
| 108 | + let mut xy: f32 = 0.0; | ||
| 109 | + let mut yy: f32 = 0.0; | ||
| 110 | + let mut pulses_left = k; | ||
| 111 | + | ||
| 112 | + if k > (n >> 1) as i32 { | ||
| 113 | + let mut sum: f32 = 0.0; | ||
| 114 | + for j in 0..n { | ||
| 115 | + sum += x[j]; | ||
| 116 | + } | ||
| 117 | + if !(sum > EPSILON && sum < 64.0) { | ||
| 118 | + x[0] = 1.0; | ||
| 119 | + for j in 1..n { | ||
| 120 | + x[j] = 0.0; | ||
| 121 | + } | ||
| 122 | + sum = 1.0; | ||
| 123 | + } | ||
| 124 | + let rcp = (k as f32 + 0.8f32) * celt_rcp(sum); | ||
| 125 | + for j in 0..n { | ||
| 126 | + iy[j] = ((rcp * x[j]) as f64).floor() as i32; | ||
| 127 | + y[j] = iy[j] as f32; | ||
| 128 | + yy += y[j] * y[j]; | ||
| 129 | + xy += x[j] * y[j]; | ||
| 130 | + y[j] *= 2.0; | ||
| 131 | + pulses_left -= iy[j]; | ||
| 132 | + } | ||
| 133 | + } | ||
| 134 | + | ||
| 135 | + if pulses_left > n as i32 + 3 { | ||
| 136 | + let tmp = pulses_left as f32; | ||
| 137 | + yy += tmp * tmp; | ||
| 138 | + yy += tmp * y[0]; | ||
| 139 | + iy[0] += pulses_left; | ||
| 140 | + pulses_left = 0; | ||
| 141 | + } | ||
| 142 | + | ||
| 143 | + for _ in 0..pulses_left { | ||
| 144 | + let mut best_id = 0usize; | ||
| 145 | + yy += 1.0; | ||
| 146 | + let mut rxy = xy + x[0]; | ||
| 147 | + let mut ryy = yy + y[0]; | ||
| 148 | + rxy = rxy * rxy; | ||
| 149 | + let mut best_den = ryy; | ||
| 150 | + let mut best_num = rxy; | ||
| 151 | + for j in 1..n { | ||
| 152 | + rxy = xy + x[j]; | ||
| 153 | + ryy = yy + y[j]; | ||
| 154 | + rxy = rxy * rxy; | ||
| 155 | + if best_den * rxy > ryy * best_num { | ||
| 156 | + best_den = ryy; | ||
| 157 | + best_num = rxy; | ||
| 158 | + best_id = j; | ||
| 159 | + } | ||
| 160 | + } | ||
| 161 | + xy += x[best_id]; | ||
| 162 | + yy += y[best_id]; | ||
| 163 | + y[best_id] += 2.0; | ||
| 164 | + iy[best_id] += 1; | ||
| 165 | + } | ||
| 166 | + | ||
| 167 | + for j in 0..n { | ||
| 168 | + if signx[j] != 0 { | ||
| 169 | + iy[j] = -iy[j]; | ||
| 170 | + } | ||
| 171 | + } | ||
| 172 | + yy | ||
| 173 | +} | ||
| 174 | + | ||
| 175 | +fn icwrs(n: usize, y: &[i32]) -> u32 { | ||
| 176 | + let mut j = n - 1; | ||
| 177 | + let mut i = (y[j] < 0) as u32; | ||
| 178 | + let mut k = y[j].unsigned_abs() as usize; | ||
| 179 | + loop { | ||
| 180 | + j -= 1; | ||
| 181 | + i = i.wrapping_add(pvq_u(n - j, k)); | ||
| 182 | + k += y[j].unsigned_abs() as usize; | ||
| 183 | + if y[j] < 0 { | ||
| 184 | + i = i.wrapping_add(pvq_u(n - j, k + 1)); | ||
| 185 | + } | ||
| 186 | + if j == 0 { | ||
| 187 | + break; | ||
| 188 | + } | ||
| 189 | + } | ||
| 190 | + i | ||
| 191 | +} | ||
| 192 | + | ||
| 193 | +fn encode_pulses(y: &[i32], n: usize, k: i32, enc: &mut RangeEncoder) { | ||
| 194 | + enc.enc_uint(icwrs(n, y), pvq_v(n, k as usize)); | ||
| 195 | +} | ||
| 196 | + | ||
| 197 | +/// `alg_quant` (encoder, no QEXT); returns the collapse mask. | ||
| 198 | +pub(crate) fn alg_quant( | ||
| 199 | + x: &mut [f32], | ||
| 200 | + n: usize, | ||
| 201 | + k: i32, | ||
| 202 | + spread: i32, | ||
| 203 | + b: i32, | ||
| 204 | + enc: &mut RangeEncoder, | ||
| 205 | + gain: f32, | ||
| 206 | + resynth: bool, | ||
| 207 | +) -> u32 { | ||
| 208 | + let b = b as usize; | ||
| 209 | + let mut iy_buf = [0i32; MAX_N + 3]; | ||
| 210 | + let iy = &mut iy_buf[..n + 3]; | ||
| 211 | + exp_rotation(x, n, 1, b, k, spread); | ||
| 212 | + let yy = op_pvq_search(x, iy, k, n); | ||
| 213 | + let collapse_mask = extract_collapse_mask(iy, n, b); | ||
| 214 | + encode_pulses(iy, n, k, enc); | ||
| 215 | + if resynth { | ||
| 216 | + normalise_residual(iy, x, n, yy, gain); | ||
| 217 | + exp_rotation(x, n, -1, b, k, spread); | ||
| 218 | + } | ||
| 219 | + collapse_mask | ||
| 220 | +} | ||
| 221 | + | ||
| 222 | +/// `stereo_itheta`. | ||
| 223 | +pub(crate) fn stereo_itheta(x: &[f32], y: &[f32], stereo: bool, n: usize) -> i32 { | ||
| 224 | + let mut emid: f32 = 0.0; | ||
| 225 | + let mut eside: f32 = 0.0; | ||
| 226 | + if stereo { | ||
| 227 | + for i in 0..n { | ||
| 228 | + let m = x[i] + y[i]; | ||
| 229 | + let s = x[i] - y[i]; | ||
| 230 | + emid += m * m; | ||
| 231 | + eside += s * s; | ||
| 232 | + } | ||
| 233 | + } else { | ||
| 234 | + emid += inner_prod(x, x, n); | ||
| 235 | + eside += inner_prod(y, y, n); | ||
| 236 | + } | ||
| 237 | + let mid = celt_sqrt(emid); | ||
| 238 | + let side = celt_sqrt(eside); | ||
| 239 | + let v = 0.5f32 + (65536.0f32 * 16384.0f32) * celt_atan2p_norm(side, mid); | ||
| 240 | + (v as f64).floor() as i32 | ||
| 241 | +} | ||
| 242 | + | ||
| 243 | +/// `renormalise_vector`. | ||
| 244 | +pub(crate) fn renormalise_vector(x: &mut [f32], n: usize, gain: f32) { | ||
| 245 | + let e = EPSILON + inner_prod(x, x, n); | ||
| 246 | + let g = celt_rsqrt(e) * gain; | ||
| 247 | + for i in 0..n { | ||
| 248 | + x[i] *= g; | ||
| 249 | + } | ||
| 250 | +} | ||
crates/ec-opus/src/encoder.rsmodified+312 -220
| @@ -27,7 +27,8 @@ | |||
| 27 | use ec_core::{Error, Result}; | 27 | use ec_core::{Error, Result}; |
| 28 | 28 | ||
| 29 | use crate::analysis::{AnalysisInfo, TonalityAnalysis}; | 29 | use crate::analysis::{AnalysisInfo, TonalityAnalysis}; |
| 30 | -use crate::celt_enc::CeltEncoder; | 30 | +use crate::celt_flp::enc::{BITRATE_MAX, CeltEnc}; |
| 31 | +use crate::celt_flp::tables::WINDOW120; | ||
| 31 | use crate::packet::{Bandwidth, Mode}; | 32 | use crate::packet::{Bandwidth, Mode}; |
| 32 | use crate::range::RangeEncoder; | 33 | use crate::range::RangeEncoder; |
| 33 | use crate::silk_flp::opus::{ | 34 | use crate::silk_flp::opus::{ |
| @@ -100,6 +101,7 @@ struct Decision { | |||
| 100 | to_celt: bool, | 101 | to_celt: bool, |
| 101 | prefill: Prefill, | 102 | prefill: Prefill, |
| 102 | to_mono: bool, | 103 | to_mono: bool, |
| 104 | + toc_only: Option<usize>, | ||
| 103 | } | 105 | } |
| 104 | 106 | ||
| 105 | #[derive(Clone, Copy, Debug, Default)] | 107 | #[derive(Clone, Copy, Debug, Default)] |
| @@ -227,11 +229,26 @@ const DTX_START_Q1: i32 = 10 * 2 * 20; | |||
| 227 | const DTX_END_Q1: i32 = (10 + 20) * 2 * 20; | 229 | const DTX_END_Q1: i32 = (10 + 20) * 2 * 20; |
| 228 | const DTX_ACTIVITY_THRESHOLD: f32 = 0.1; | 230 | const DTX_ACTIVITY_THRESHOLD: f32 = 0.1; |
| 229 | const DTX_PSEUDO_SNR_THRESHOLD: f32 = 316.23; | 231 | const DTX_PSEUDO_SNR_THRESHOLD: f32 = 316.23; |
| 230 | -const DTX_SILENCE: f32 = 1.0 / 16_777_216.0; | ||
| 231 | 232 | ||
| 232 | /// The TOC-only packet libopus sends in DTX: code 0 is the TOC alone; code 3 | 233 | /// The TOC-only packet libopus sends in DTX: code 0 is the TOC alone; code 3 |
| 233 | /// keeps its frame-count byte with no frames. Self-delimited framing adds a | 234 | /// keeps its frame-count byte with no frames. Self-delimited framing adds a |
| 234 | /// zero frame length after it. | 235 | /// zero frame length after it. |
| 236 | +fn gen_toc(mode: Mode, frame_rate: usize, bw: Bandwidth, channels: usize) -> u8 { | ||
| 237 | + let mut period = 0; | ||
| 238 | + let mut rate = frame_rate; | ||
| 239 | + while rate < 400 { | ||
| 240 | + rate <<= 1; | ||
| 241 | + period += 1; | ||
| 242 | + } | ||
| 243 | + let bw = bw_index(bw) as u8; | ||
| 244 | + let toc = match mode { | ||
| 245 | + Mode::Silk => (bw << 5) | ((period - 2) << 3), | ||
| 246 | + Mode::Celt => 0x80 | (bw.saturating_sub(1) << 5) | (period << 3), | ||
| 247 | + Mode::Hybrid => 0x60 | ((bw - 3) << 4) | ((period - 2) << 3), | ||
| 248 | + }; | ||
| 249 | + toc | (u8::from(channels == 2) << 2) | ||
| 250 | +} | ||
| 251 | + | ||
| 235 | fn dtx_packet(toc: u8, count: u8, self_delimited: bool) -> ([u8; 3], usize) { | 252 | fn dtx_packet(toc: u8, count: u8, self_delimited: bool) -> ([u8; 3], usize) { |
| 236 | let mut bytes = [0u8; 3]; | 253 | let mut bytes = [0u8; 3]; |
| 237 | let len = if toc & 3 == 3 { | 254 | let len = if toc & 3 == 3 { |
| @@ -249,14 +266,12 @@ fn encoder_buffer(sample_rate: u32) -> usize { | |||
| 249 | sample_rate as usize / 100 | 266 | sample_rate as usize / 100 |
| 250 | } | 267 | } |
| 251 | 268 | ||
| 252 | -fn total_buffer(sample_rate: u32) -> usize { | ||
| 253 | - sample_rate as usize / 250 | ||
| 254 | -} | ||
| 255 | - | ||
| 256 | /// One elementary Opus encoder: mono or stereo. | 269 | /// One elementary Opus encoder: mono or stereo. |
| 257 | #[derive(Clone, Debug)] | 270 | #[derive(Clone, Debug)] |
| 258 | pub struct Encoder { | 271 | pub struct Encoder { |
| 259 | - celt: CeltEncoder, | 272 | + celt: CeltEnc, |
| 273 | + bitrate_bps: i32, | ||
| 274 | + lsb_depth: i32, | ||
| 260 | range: RangeEncoder, | 275 | range: RangeEncoder, |
| 261 | sample_rate: u32, | 276 | sample_rate: u32, |
| 262 | /// 48000 / `sample_rate`: the zero-stuffing factor into CELT. | 277 | /// 48000 / `sample_rate`: the zero-stuffing factor into CELT. |
| @@ -295,10 +310,7 @@ pub struct Encoder { | |||
| 295 | analysis: TonalityAnalysis, | 310 | analysis: TonalityAnalysis, |
| 296 | /// The current frame's analysis output, handed to `celt.encode`. | 311 | /// The current frame's analysis output, handed to `celt.encode`. |
| 297 | info: AnalysisInfo, | 312 | info: AnalysisInfo, |
| 298 | - /// Whether the analysis runs at all — see `celt_enc::analysis_params`. | ||
| 299 | analysis_on: bool, | 313 | analysis_on: bool, |
| 300 | - /// Whether the detected bandwidth may lower the coded one (`EC_OPUS_BW_DETECT`). | ||
| 301 | - bw_detect: bool, | ||
| 302 | inband_fec: bool, | 314 | inband_fec: bool, |
| 303 | packet_loss_perc: u8, | 315 | packet_loss_perc: u8, |
| 304 | lbrr_coded: bool, | 316 | lbrr_coded: bool, |
| @@ -414,7 +426,9 @@ impl Encoder { | |||
| 414 | )); | 426 | )); |
| 415 | } | 427 | } |
| 416 | let mut enc = Encoder { | 428 | let mut enc = Encoder { |
| 417 | - celt: CeltEncoder::new(channels, upsample), | 429 | + celt: CeltEnc::new(channels, upsample), |
| 430 | + bitrate_bps: 0, | ||
| 431 | + lsb_depth: 24, | ||
| 418 | range: RangeEncoder::new(), | 432 | range: RangeEncoder::new(), |
| 419 | sample_rate, | 433 | sample_rate, |
| 420 | upsample, | 434 | upsample, |
| @@ -436,8 +450,7 @@ impl Encoder { | |||
| 436 | redundant: RangeEncoder::new(), | 450 | redundant: RangeEncoder::new(), |
| 437 | analysis: TonalityAnalysis::new(sample_rate), | 451 | analysis: TonalityAnalysis::new(sample_rate), |
| 438 | info: AnalysisInfo::default(), | 452 | info: AnalysisInfo::default(), |
| 439 | - analysis_on: crate::celt_enc::analysis_params().0, | 453 | + analysis_on: true, |
| 440 | - bw_detect: crate::celt_enc::analysis_params().5, | ||
| 441 | inband_fec: false, | 454 | inband_fec: false, |
| 442 | packet_loss_perc: 0, | 455 | packet_loss_perc: 0, |
| 443 | lbrr_coded: false, | 456 | lbrr_coded: false, |
| @@ -460,15 +473,13 @@ impl Encoder { | |||
| 460 | nonfinal: false, | 473 | nonfinal: false, |
| 461 | prev_hb_gain: 1.0, | 474 | prev_hb_gain: 1.0, |
| 462 | }; | 475 | }; |
| 463 | - enc.celt.set_align_input(false); | 476 | + enc.celt.set_complexity(DEFAULT_COMPLEXITY); |
| 464 | Ok(enc) | 477 | Ok(enc) |
| 465 | } | 478 | } |
| 466 | 479 | ||
| 467 | - /// Turns the tonality analysis on or off for this encoder. It is off | 480 | + /// Turns libopus's tonality analysis on (the default) or off. Off saves |
| 468 | - /// unless one of its consumers is switched on (see | 481 | + /// about a quarter of the encoder's time but drops what it feeds: speech/music |
| 469 | - /// `celt_enc::analysis_params`), because it costs ~25% of the encoder; | 482 | + /// detection, bandwidth detection, and CELT's tonality-driven allocation. |
| 470 | - /// turn it on to read `music_prob`/`tonality` back through | ||
| 471 | - /// [`Encoder::last_celt_diag`]. | ||
| 472 | pub fn set_analysis(&mut self, on: bool) { | 483 | pub fn set_analysis(&mut self, on: bool) { |
| 473 | self.analysis_on = on; | 484 | self.analysis_on = on; |
| 474 | } | 485 | } |
| @@ -561,7 +572,6 @@ impl Encoder { | |||
| 561 | /// becomes 312, not 120, and the Ogg pre-skip must follow it. | 572 | /// becomes 312, not 120, and the Ogg pre-skip must follow it. |
| 562 | pub fn set_libopus_input_alignment(&mut self, on: bool) { | 573 | pub fn set_libopus_input_alignment(&mut self, on: bool) { |
| 563 | self.align_input = on; | 574 | self.align_input = on; |
| 564 | - self.celt.set_align_input(false); | ||
| 565 | self.filter = InputFilter::new(); | 575 | self.filter = InputFilter::new(); |
| 566 | } | 576 | } |
| 567 | 577 | ||
| @@ -585,6 +595,7 @@ impl Encoder { | |||
| 585 | /// OPUS_SET_PACKET_LOSS_PERC: expected packet loss, 0..=100 (clamped). | 595 | /// OPUS_SET_PACKET_LOSS_PERC: expected packet loss, 0..=100 (clamped). |
| 586 | pub fn set_packet_loss_perc(&mut self, perc: u8) { | 596 | pub fn set_packet_loss_perc(&mut self, perc: u8) { |
| 587 | self.packet_loss_perc = perc.min(100); | 597 | self.packet_loss_perc = perc.min(100); |
| 598 | + self.celt.set_loss_rate(i32::from(self.packet_loss_perc)); | ||
| 588 | } | 599 | } |
| 589 | 600 | ||
| 590 | /// OPUS_SET_DTX: send TOC-only packets during silence/inactivity (after 200 ms), refreshing every 400 ms. | 601 | /// OPUS_SET_DTX: send TOC-only packets during silence/inactivity (after 200 ms), refreshing every 400 ms. |
| @@ -595,7 +606,11 @@ impl Encoder { | |||
| 595 | /// libopus's peak signal energy tracker, run on every frame after the analysis. | 606 | /// libopus's peak signal energy tracker, run on every frame after the analysis. |
| 596 | fn track_peak(&mut self, pcm: &[f32], frame_size: usize) { | 607 | fn track_peak(&mut self, pcm: &[f32], frame_size: usize) { |
| 597 | let n = frame_size * self.channels; | 608 | let n = frame_size * self.channels; |
| 598 | - if pcm.iter().take(n).all(|x| x.abs() <= DTX_SILENCE) { | 609 | + if pcm |
| 610 | + .iter() | ||
| 611 | + .take(n) | ||
| 612 | + .all(|x| x.abs() <= self.silence_threshold()) | ||
| 613 | + { | ||
| 599 | return; | 614 | return; |
| 600 | } | 615 | } |
| 601 | if !self.info.valid || self.info.activity_probability > DTX_ACTIVITY_THRESHOLD { | 616 | if !self.info.valid || self.info.activity_probability > DTX_ACTIVITY_THRESHOLD { |
| @@ -608,7 +623,11 @@ impl Encoder { | |||
| 608 | /// -1 (`VAD_NO_DECISION`) without it. | 623 | /// -1 (`VAD_NO_DECISION`) without it. |
| 609 | fn silk_activity(&self, pcm: &[f32], frame_size: usize) -> i32 { | 624 | fn silk_activity(&self, pcm: &[f32], frame_size: usize) -> i32 { |
| 610 | let n = frame_size * self.channels; | 625 | let n = frame_size * self.channels; |
| 611 | - if pcm.iter().take(n).all(|x| x.abs() <= DTX_SILENCE) { | 626 | + if pcm |
| 627 | + .iter() | ||
| 628 | + .take(n) | ||
| 629 | + .all(|x| x.abs() <= self.silence_threshold()) | ||
| 630 | + { | ||
| 612 | return 0; | 631 | return 0; |
| 613 | } | 632 | } |
| 614 | if !self.info.valid { | 633 | if !self.info.valid { |
| @@ -629,7 +648,7 @@ impl Encoder { | |||
| 629 | } | 648 | } |
| 630 | let n = frame_size * self.channels; | 649 | let n = frame_size * self.channels; |
| 631 | let energy = pcm.iter().take(n).map(|x| x * x).sum::<f32>() / n as f32; | 650 | let energy = pcm.iter().take(n).map(|x| x * x).sum::<f32>() / n as f32; |
| 632 | - let is_silence = pcm.iter().all(|x| x.abs() <= DTX_SILENCE); | 651 | + let is_silence = pcm.iter().all(|x| x.abs() <= self.silence_threshold()); |
| 633 | let (valid, prob) = (self.info.valid, self.info.activity_probability); | 652 | let (valid, prob) = (self.info.valid, self.info.activity_probability); |
| 634 | let active = if is_silence { | 653 | let active = if is_silence { |
| 635 | false | 654 | false |
| @@ -672,16 +691,6 @@ impl Encoder { | |||
| 672 | self.final_range | 691 | self.final_range |
| 673 | } | 692 | } |
| 674 | 693 | ||
| 675 | - /// Per-frame CELT diagnostics from the most recent [`encode_float`] call. | ||
| 676 | - /// Intended for the reelm@64k dropout investigation; the fields are only | ||
| 677 | - /// meaningful when the last frame was coded as pure CELT (the path every | ||
| 678 | - /// fullband Audio frame at 64 kbps stereo takes). | ||
| 679 | - /// | ||
| 680 | - /// [`encode_float`]: Encoder::encode_float | ||
| 681 | - pub fn last_celt_diag(&self) -> &crate::celt_enc::CeltFrameDiag { | ||
| 682 | - self.celt.last_diag() | ||
| 683 | - } | ||
| 684 | - | ||
| 685 | /// Drops all inter-frame state; the next packet starts like the first. | 694 | /// Drops all inter-frame state; the next packet starts like the first. |
| 686 | pub fn reset(&mut self) { | 695 | pub fn reset(&mut self) { |
| 687 | self.celt.reset(); | 696 | self.celt.reset(); |
| @@ -799,12 +808,17 @@ impl Encoder { | |||
| 799 | ) -> Result<(u8, &[u8])> { | 808 | ) -> Result<(u8, &[u8])> { |
| 800 | let cursor = self.analysis.cursor(); | 809 | let cursor = self.analysis.cursor(); |
| 801 | self.info = if self.analysis_on { | 810 | self.info = if self.analysis_on { |
| 802 | - self.analysis.run(pcm, frame_size, self.channels, 24) | 811 | + self.analysis |
| 812 | + .run(pcm, frame_size, self.channels, self.lsb_depth) | ||
| 803 | } else { | 813 | } else { |
| 804 | AnalysisInfo::default() | 814 | AnalysisInfo::default() |
| 805 | }; | 815 | }; |
| 806 | self.track_peak(pcm, frame_size); | 816 | self.track_peak(pcm, frame_size); |
| 807 | let d = self.decide(pcm, frame_size, cap + 1); | 817 | let d = self.decide(pcm, frame_size, cap + 1); |
| 818 | + if let Some(max_data) = d.toc_only { | ||
| 819 | + let (toc, n) = self.toc_only_packet(d, frame_size, cap + 1, max_data)?; | ||
| 820 | + return Ok((toc, &self.silk_buf[..n])); | ||
| 821 | + } | ||
| 808 | if d.prefill == Prefill::Reset { | 822 | if d.prefill == Prefill::Reset { |
| 809 | self.silk_layer().reset(); | 823 | self.silk_layer().reset(); |
| 810 | } | 824 | } |
| @@ -818,6 +832,57 @@ impl Encoder { | |||
| 818 | Ok((toc, self.payload_bytes(payload))) | 832 | Ok((toc, self.payload_bytes(payload))) |
| 819 | } | 833 | } |
| 820 | 834 | ||
| 835 | + fn toc_only_packet( | ||
| 836 | + &mut self, | ||
| 837 | + d: Decision, | ||
| 838 | + frame_size: usize, | ||
| 839 | + out_bytes: usize, | ||
| 840 | + max_data: usize, | ||
| 841 | + ) -> Result<(u8, usize)> { | ||
| 842 | + let mut frame_rate = 48000 / (frame_size * self.upsample); | ||
| 843 | + let mut mode = d.mode; | ||
| 844 | + let mut bw = d.bandwidth; | ||
| 845 | + let mut code = 0u8; | ||
| 846 | + let mut count = 1; | ||
| 847 | + if frame_rate > 100 { | ||
| 848 | + mode = Mode::Celt; | ||
| 849 | + } | ||
| 850 | + if frame_rate == 25 && mode != Mode::Silk { | ||
| 851 | + frame_rate = 50; | ||
| 852 | + code = 1; | ||
| 853 | + count = 2; | ||
| 854 | + } | ||
| 855 | + if frame_rate <= 16 { | ||
| 856 | + if out_bytes == 1 || (mode == Mode::Silk && frame_rate != 10) { | ||
| 857 | + mode = Mode::Silk; | ||
| 858 | + code = u8::from(frame_rate <= 12); | ||
| 859 | + count = if code == 1 { 2 } else { 1 }; | ||
| 860 | + frame_rate = if frame_rate == 12 { 25 } else { 16 }; | ||
| 861 | + } else { | ||
| 862 | + count = 50 / frame_rate; | ||
| 863 | + frame_rate = 50; | ||
| 864 | + code = 3; | ||
| 865 | + } | ||
| 866 | + } | ||
| 867 | + bw = match mode { | ||
| 868 | + Mode::Silk if bw > Bandwidth::Wide => Bandwidth::Wide, | ||
| 869 | + Mode::Celt if bw == Bandwidth::Medium => Bandwidth::Narrow, | ||
| 870 | + Mode::Hybrid if bw <= Bandwidth::SuperWide => Bandwidth::SuperWide, | ||
| 871 | + _ => bw, | ||
| 872 | + }; | ||
| 873 | + let toc = gen_toc(mode, frame_rate, bw, d.stream_channels); | ||
| 874 | + let frames = vec![Vec::new(); count]; | ||
| 875 | + if !self.vbr && max_data > 1 + usize::from(code >= 2) { | ||
| 876 | + let (_, n) = self.pack_frames(&frames, max_data, true)?; | ||
| 877 | + return Ok((toc | 3, n)); | ||
| 878 | + } | ||
| 879 | + if code == 3 { | ||
| 880 | + self.silk_buf[0] = count as u8; | ||
| 881 | + return Ok((toc | 3, 1)); | ||
| 882 | + } | ||
| 883 | + Ok((toc | code, 0)) | ||
| 884 | + } | ||
| 885 | + | ||
| 821 | fn encode_frame_decided( | 886 | fn encode_frame_decided( |
| 822 | &mut self, | 887 | &mut self, |
| 823 | pcm: &[f32], | 888 | pcm: &[f32], |
| @@ -853,6 +918,7 @@ impl Encoder { | |||
| 853 | self.hp_buf = buf; | 918 | self.hp_buf = buf; |
| 854 | self.pcm_buf = delayed; | 919 | self.pcm_buf = delayed; |
| 855 | self.prev_mode = Some(if d.to_celt { Mode::Celt } else { d.mode }); | 920 | self.prev_mode = Some(if d.to_celt { Mode::Celt } else { d.mode }); |
| 921 | + self.prev_channels = d.stream_channels; | ||
| 856 | r | 922 | r |
| 857 | } | 923 | } |
| 858 | 924 | ||
| @@ -885,16 +951,14 @@ impl Encoder { | |||
| 885 | }; | 951 | }; |
| 886 | self.filter | 952 | self.filter |
| 887 | .hp_cutoff(&pcm[..n], out, smth1, self.channels, fs); | 953 | .hp_cutoff(&pcm[..n], out, smth1, self.channels, fs); |
| 888 | - } else if self.align_input { | ||
| 889 | - self.filter.dc_reject(&pcm[..n], out, self.channels, fs); | ||
| 890 | } else { | 954 | } else { |
| 891 | - out.copy_from_slice(&pcm[..n]); | 955 | + self.filter.dc_reject(&pcm[..n], out, self.channels, fs); |
| 892 | } | 956 | } |
| 893 | } | 957 | } |
| 894 | 958 | ||
| 895 | fn delay_input(&self, frame: &[f32], frame_size: usize, out: &mut Vec<f32>) { | 959 | fn delay_input(&self, frame: &[f32], frame_size: usize, out: &mut Vec<f32>) { |
| 896 | let ch = self.channels; | 960 | let ch = self.channels; |
| 897 | - let start = (encoder_buffer(self.sample_rate) - total_buffer(self.sample_rate)) * ch; | 961 | + let start = (encoder_buffer(self.sample_rate) - self.total_buffer()) * ch; |
| 898 | out.clear(); | 962 | out.clear(); |
| 899 | out.extend_from_slice(&self.delay_buffer[start..]); | 963 | out.extend_from_slice(&self.delay_buffer[start..]); |
| 900 | out.extend_from_slice(&frame[..frame_size * ch]); | 964 | out.extend_from_slice(&frame[..frame_size * ch]); |
| @@ -903,7 +967,7 @@ impl Encoder { | |||
| 903 | fn update_delay(&mut self, delayed: &[f32], frame_size: usize) { | 967 | fn update_delay(&mut self, delayed: &[f32], frame_size: usize) { |
| 904 | let ch = self.channels; | 968 | let ch = self.channels; |
| 905 | let eb = encoder_buffer(self.sample_rate) * ch; | 969 | let eb = encoder_buffer(self.sample_rate) * ch; |
| 906 | - let tb = total_buffer(self.sample_rate) * ch; | 970 | + let tb = self.total_buffer() * ch; |
| 907 | let fb = frame_size * ch; | 971 | let fb = frame_size * ch; |
| 908 | if eb > fb + tb { | 972 | if eb > fb + tb { |
| 909 | let keep = eb - fb - tb; | 973 | let keep = eb - fb - tb; |
| @@ -923,14 +987,7 @@ impl Encoder { | |||
| 923 | { | 987 | { |
| 924 | let g1 = self.hybrid_stereo_width_q14 as f32 / 16384.0; | 988 | let g1 = self.hybrid_stereo_width_q14 as f32 / 16384.0; |
| 925 | let g2 = self.stereo_width_q14 as f32 / 16384.0; | 989 | let g2 = self.stereo_width_q14 as f32 / 16384.0; |
| 926 | - stereo_fade( | 990 | + stereo_fade(delayed, g1, g2, &WINDOW120, frame_size, self.sample_rate); |
| 927 | - delayed, | ||
| 928 | - g1, | ||
| 929 | - g2, | ||
| 930 | - self.celt.window(), | ||
| 931 | - frame_size, | ||
| 932 | - self.sample_rate, | ||
| 933 | - ); | ||
| 934 | self.hybrid_stereo_width_q14 = self.stereo_width_q14; | 991 | self.hybrid_stereo_width_q14 = self.stereo_width_q14; |
| 935 | } | 992 | } |
| 936 | } | 993 | } |
| @@ -942,7 +999,7 @@ impl Encoder { | |||
| 942 | delayed, | 999 | delayed, |
| 943 | prev, | 1000 | prev, |
| 944 | hb_gain, | 1001 | hb_gain, |
| 945 | - self.celt.window(), | 1002 | + &WINDOW120, |
| 946 | frame_size, | 1003 | frame_size, |
| 947 | self.channels, | 1004 | self.channels, |
| 948 | self.sample_rate, | 1005 | self.sample_rate, |
| @@ -983,12 +1040,12 @@ impl Encoder { | |||
| 983 | fn fade_prefill_history(&mut self) { | 1040 | fn fade_prefill_history(&mut self) { |
| 984 | let (fs, ch) = (self.sample_rate, self.channels); | 1041 | let (fs, ch) = (self.sample_rate, self.channels); |
| 985 | let n = fs as usize / 400; | 1042 | let n = fs as usize / 400; |
| 986 | - let off = (encoder_buffer(fs) - total_buffer(fs) - n) * ch; | 1043 | + let off = (encoder_buffer(fs) - self.total_buffer() - n) * ch; |
| 987 | gain_fade( | 1044 | gain_fade( |
| 988 | &mut self.delay_buffer[off..], | 1045 | &mut self.delay_buffer[off..], |
| 989 | 0.0, | 1046 | 0.0, |
| 990 | 1.0, | 1047 | 1.0, |
| 991 | - self.celt.window(), | 1048 | + &WINDOW120, |
| 992 | n, | 1049 | n, |
| 993 | ch, | 1050 | ch, |
| 994 | fs, | 1051 | fs, |
| @@ -1006,71 +1063,95 @@ impl Encoder { | |||
| 1006 | self.history = history; | 1063 | self.history = history; |
| 1007 | } | 1064 | } |
| 1008 | 1065 | ||
| 1009 | - fn celt_dummy( | 1066 | + fn celt_setup(&mut self, mode: Mode, end: usize, stream_channels: usize) { |
| 1010 | - &mut self, | 1067 | + self.celt.set_lsb_depth(self.lsb_depth); |
| 1011 | - pcm: &[f32], | 1068 | + self.celt.set_end_band(end); |
| 1012 | - frame_48k: usize, | 1069 | + self.celt.set_stream_channels(stream_channels); |
| 1013 | - start: usize, | 1070 | + self.celt.set_bitrate(BITRATE_MAX); |
| 1014 | - end: usize, | 1071 | + if mode != Mode::Silk { |
| 1015 | - vbr_rate: u32, | 1072 | + self.celt.set_prediction(2); |
| 1016 | - pred: u8, | 1073 | + } |
| 1017 | - ) { | ||
| 1018 | - self.celt.set_prediction(pred); | ||
| 1019 | - self.redundant.reset(2); | ||
| 1020 | - let _ = self.celt.encode( | ||
| 1021 | - &mut self.redundant, | ||
| 1022 | - pcm, | ||
| 1023 | - frame_48k, | ||
| 1024 | - start, | ||
| 1025 | - end, | ||
| 1026 | - vbr_rate, | ||
| 1027 | - &self.info, | ||
| 1028 | - ); | ||
| 1029 | } | 1074 | } |
| 1030 | 1075 | ||
| 1031 | - fn celt_prefill(&mut self, start: usize, end: usize, vbr_rate: u32) { | 1076 | + fn celt_own(&mut self, pcm: &[f32], frame_size: usize, bytes: usize) -> u32 { |
| 1032 | - let (fs, ch) = (self.sample_rate, self.channels); | 1077 | + let mut enc = std::mem::take(&mut self.redundant); |
| 1033 | - let n = fs as usize / 400 * ch; | 1078 | + self.celt.encode(pcm, frame_size, bytes, &mut enc, true); |
| 1034 | - let off = (encoder_buffer(fs) - total_buffer(fs)) * ch - n; | 1079 | + self.redundant = enc; |
| 1035 | - let mut tmp = [0.0f32; 2 * 120]; | 1080 | + self.celt.final_range() |
| 1036 | - tmp[..n].copy_from_slice(&self.history[off..off + n]); | 1081 | + } |
| 1082 | + | ||
| 1083 | + fn celt_to_silk_redundancy(&mut self, delayed: &[f32], bytes: usize, out: &mut [u8]) -> u32 { | ||
| 1084 | + let n2 = self.sample_rate as usize / 200; | ||
| 1085 | + self.celt.set_start_band(0); | ||
| 1086 | + self.celt.set_vbr(false); | ||
| 1087 | + self.celt.set_bitrate(BITRATE_MAX); | ||
| 1088 | + let rng = self.celt_own(&delayed[..self.channels * n2], n2, bytes); | ||
| 1089 | + out[..bytes].copy_from_slice(&self.redundant.data()[..bytes]); | ||
| 1037 | self.celt.reset(); | 1090 | self.celt.reset(); |
| 1038 | - self.celt_dummy(&tmp[..n], 120, start, end, vbr_rate, 2); | 1091 | + rng |
| 1039 | - self.celt.set_prediction(0); | ||
| 1040 | } | 1092 | } |
| 1041 | 1093 | ||
| 1042 | - fn celt_redundancy( | 1094 | + fn celt_main( |
| 1043 | &mut self, | 1095 | &mut self, |
| 1044 | - pcm: &[f32], | 1096 | + mode: Mode, |
| 1045 | - frame_48k: usize, | 1097 | + delayed: &[f32], |
| 1046 | - end: usize, | 1098 | + frame_size: usize, |
| 1047 | - bytes: usize, | 1099 | + nb_compr: usize, |
| 1048 | - pred: u8, | 1100 | + celt_rate: i32, |
| 1049 | - out: &mut [u8], | 1101 | + ) -> usize { |
| 1050 | - ) -> Result<u32> { | 1102 | + self.celt.set_vbr(self.vbr); |
| 1051 | - self.celt.set_prediction(pred); | 1103 | + if self.vbr { |
| 1052 | - self.redundant.reset(bytes); | 1104 | + if mode == Mode::Hybrid { |
| 1053 | - self.celt | 1105 | + self.celt.set_bitrate(celt_rate.max(501)); |
| 1054 | - .encode(&mut self.redundant, pcm, frame_48k, 0, end, 0, &self.info)?; | 1106 | + self.celt.set_vbr_constraint(false); |
| 1055 | - out[..bytes].copy_from_slice(&self.redundant.data()[..bytes]); | 1107 | + } else { |
| 1056 | - Ok(self.redundant.range()) | 1108 | + self.celt.set_vbr_constraint(true); |
| 1109 | + self.celt.set_bitrate(self.bitrate_bps); | ||
| 1110 | + } | ||
| 1111 | + } | ||
| 1112 | + if self.prev_mode.is_some_and(|p| p != mode) { | ||
| 1113 | + let (fs, ch) = (self.sample_rate as usize, self.channels); | ||
| 1114 | + let n = fs / 400; | ||
| 1115 | + let off = (encoder_buffer(fs as u32) - self.total_buffer()) * ch - n * ch; | ||
| 1116 | + let mut tmp = [0.0f32; 2 * 120]; | ||
| 1117 | + tmp[..n * ch].copy_from_slice(&self.history[off..off + n * ch]); | ||
| 1118 | + self.celt.reset(); | ||
| 1119 | + self.celt_own(&tmp[..n * ch], n, 2); | ||
| 1120 | + self.celt.set_prediction(0); | ||
| 1121 | + } | ||
| 1122 | + let mut ret = nb_compr; | ||
| 1123 | + if self.range.tell() as usize <= 8 * nb_compr { | ||
| 1124 | + let mut range = std::mem::take(&mut self.range); | ||
| 1125 | + let r = self | ||
| 1126 | + .celt | ||
| 1127 | + .encode(delayed, frame_size, nb_compr, &mut range, false); | ||
| 1128 | + self.range = range; | ||
| 1129 | + ret = r.max(0) as usize; | ||
| 1130 | + } | ||
| 1131 | + self.final_range = self.celt.final_range(); | ||
| 1132 | + ret | ||
| 1057 | } | 1133 | } |
| 1058 | 1134 | ||
| 1059 | fn silk_to_celt_redundancy( | 1135 | fn silk_to_celt_redundancy( |
| 1060 | &mut self, | 1136 | &mut self, |
| 1061 | delayed: &[f32], | 1137 | delayed: &[f32], |
| 1062 | frame_size: usize, | 1138 | frame_size: usize, |
| 1063 | - end: usize, | ||
| 1064 | bytes: usize, | 1139 | bytes: usize, |
| 1065 | out: &mut [u8], | 1140 | out: &mut [u8], |
| 1066 | - ) -> Result<u32> { | 1141 | + ) -> u32 { |
| 1067 | let ch = self.channels; | 1142 | let ch = self.channels; |
| 1068 | let n2 = self.sample_rate as usize / 200; | 1143 | let n2 = self.sample_rate as usize / 200; |
| 1069 | let n4 = self.sample_rate as usize / 400; | 1144 | let n4 = self.sample_rate as usize / 400; |
| 1070 | self.celt.reset(); | 1145 | self.celt.reset(); |
| 1146 | + self.celt.set_start_band(0); | ||
| 1147 | + self.celt.set_prediction(0); | ||
| 1148 | + self.celt.set_vbr(false); | ||
| 1149 | + self.celt.set_bitrate(BITRATE_MAX); | ||
| 1071 | let tail = &delayed[ch * (frame_size - n2 - n4)..ch * frame_size]; | 1150 | let tail = &delayed[ch * (frame_size - n2 - n4)..ch * frame_size]; |
| 1072 | - self.celt_dummy(&tail[..ch * n4], 120, 0, end, 0, 0); | 1151 | + self.celt_own(&tail[..ch * n4], n4, 2); |
| 1073 | - self.celt_redundancy(&tail[ch * n4..], 240, end, bytes, 0, out) | 1152 | + let rng = self.celt_own(&tail[ch * n4..], n2, bytes); |
| 1153 | + out[..bytes].copy_from_slice(&self.redundant.data()[..bytes]); | ||
| 1154 | + rng | ||
| 1074 | } | 1155 | } |
| 1075 | 1156 | ||
| 1076 | fn code_redundancy_flags(&mut self, d: &mut Decision, max_data: usize, hybrid: bool) { | 1157 | fn code_redundancy_flags(&mut self, d: &mut Decision, max_data: usize, hybrid: bool) { |
| @@ -1110,7 +1191,6 @@ impl Encoder { | |||
| 1110 | cap: usize, | 1191 | cap: usize, |
| 1111 | d: Decision, | 1192 | d: Decision, |
| 1112 | ) -> Result<(u8, Payload)> { | 1193 | ) -> Result<(u8, Payload)> { |
| 1113 | - self.celt.set_stream_channels(d.stream_channels); | ||
| 1114 | match d.mode { | 1194 | match d.mode { |
| 1115 | Mode::Silk => self.encode_silk(raw, pcm, delayed, frame_size, cap, d), | 1195 | Mode::Silk => self.encode_silk(raw, pcm, delayed, frame_size, cap, d), |
| 1116 | Mode::Hybrid => { | 1196 | Mode::Hybrid => { |
| @@ -1131,9 +1211,9 @@ impl Encoder { | |||
| 1131 | let (toc, frame_48k, end) = self.toc(frame_size, d.bandwidth, d.stream_channels)?; | 1211 | let (toc, frame_48k, end) = self.toc(frame_size, d.bandwidth, d.stream_channels)?; |
| 1132 | self.fade_celt_input(delayed, frame_size, 1.0); | 1212 | self.fade_celt_input(delayed, frame_size, 1.0); |
| 1133 | self.stereo_fade_step(delayed, frame_size, d); | 1213 | self.stereo_fade_step(delayed, frame_size, d); |
| 1134 | - let input = if self.align_input { &*delayed } else { pcm }; | 1214 | + let input = &*delayed; |
| 1135 | - let switch = self.prev_mode.is_some_and(|p| p != Mode::Celt); | 1215 | + let _ = frame_48k; |
| 1136 | - let n = self.encode_frame(input, frame_48k, end, cap, switch)?; | 1216 | + let n = self.encode_frame(input, frame_size, end, cap, d.stream_channels)?; |
| 1137 | Ok((toc, Payload::Range(n))) | 1217 | Ok((toc, Payload::Range(n))) |
| 1138 | } | 1218 | } |
| 1139 | } | 1219 | } |
| @@ -1171,20 +1251,16 @@ impl Encoder { | |||
| 1171 | self.code_redundancy_flags(&mut d, max_data_bytes, false); | 1251 | self.code_redundancy_flags(&mut d, max_data_bytes, false); |
| 1172 | let khz = silk.internal_khz; | 1252 | let khz = silk.internal_khz; |
| 1173 | let end = if khz == 8 { 13 } else { 17 }; | 1253 | let end = if khz == 8 { 13 } else { 17 }; |
| 1254 | + self.celt_setup(Mode::Silk, end, d.stream_channels); | ||
| 1255 | + if d.redundancy { | ||
| 1256 | + self.celt.set_analysis(&self.info); | ||
| 1257 | + } | ||
| 1174 | let mut red = [0u8; MAX_REDUNDANCY_BYTES]; | 1258 | let mut red = [0u8; MAX_REDUNDANCY_BYTES]; |
| 1175 | let mut red_rng = 0; | 1259 | let mut red_rng = 0; |
| 1176 | if d.redundancy && d.celt_to_silk { | 1260 | if d.redundancy && d.celt_to_silk { |
| 1177 | - let n2 = self.sample_rate as usize / 200; | 1261 | + red_rng = self.celt_to_silk_redundancy(delayed, d.redundancy_bytes, &mut red); |
| 1178 | - red_rng = self.celt_redundancy( | ||
| 1179 | - &delayed[..self.channels * n2], | ||
| 1180 | - 240, | ||
| 1181 | - end, | ||
| 1182 | - d.redundancy_bytes, | ||
| 1183 | - 2, | ||
| 1184 | - &mut red, | ||
| 1185 | - )?; | ||
| 1186 | - self.celt.reset(); | ||
| 1187 | } | 1262 | } |
| 1263 | + self.celt.set_start_band(17); | ||
| 1188 | let mut len = (self.range.tell() as usize).div_ceil(8); | 1264 | let mut len = (self.range.tell() as usize).div_ceil(8); |
| 1189 | self.range.done(); | 1265 | self.range.done(); |
| 1190 | let bust = self.range.tell() as usize > (max_data_bytes - 1) * 8; | 1266 | let bust = self.range.tell() as usize > (max_data_bytes - 1) * 8; |
| @@ -1197,13 +1273,8 @@ impl Encoder { | |||
| 1197 | } | 1273 | } |
| 1198 | } | 1274 | } |
| 1199 | if d.redundancy && !d.celt_to_silk { | 1275 | if d.redundancy && !d.celt_to_silk { |
| 1200 | - red_rng = self.silk_to_celt_redundancy( | 1276 | + red_rng = |
| 1201 | - delayed, | 1277 | + self.silk_to_celt_redundancy(delayed, frame_size, d.redundancy_bytes, &mut red); |
| 1202 | - frame_size, | ||
| 1203 | - end, | ||
| 1204 | - d.redundancy_bytes, | ||
| 1205 | - &mut red, | ||
| 1206 | - )?; | ||
| 1207 | } | 1278 | } |
| 1208 | let red_len = if d.redundancy { d.redundancy_bytes } else { 0 }; | 1279 | let red_len = if d.redundancy { d.redundancy_bytes } else { 0 }; |
| 1209 | self.final_range = if bust { | 1280 | self.final_range = if bust { |
| @@ -1324,7 +1395,7 @@ impl Encoder { | |||
| 1324 | result?; | 1395 | result?; |
| 1325 | let dtx = frames.iter().filter(|f| f.is_empty()).count(); | 1396 | let dtx = frames.iter().filter(|f| f.is_empty()).count(); |
| 1326 | let pad = !self_delimited && !self.vbr && dtx != count; | 1397 | let pad = !self_delimited && !self.vbr && dtx != count; |
| 1327 | - let (code, size) = self.pack_frames(&frames, max_data, pad, self_delimited)?; | 1398 | + let (code, size) = self.pack_frames(&frames, max_data, pad)?; |
| 1328 | Ok(((toc & !3) | code, Payload::Silk(size))) | 1399 | Ok(((toc & !3) | code, Payload::Silk(size))) |
| 1329 | } | 1400 | } |
| 1330 | 1401 | ||
| @@ -1333,14 +1404,13 @@ impl Encoder { | |||
| 1333 | frames: &[Vec<u8>], | 1404 | frames: &[Vec<u8>], |
| 1334 | max_data: usize, | 1405 | max_data: usize, |
| 1335 | pad: bool, | 1406 | pad: bool, |
| 1336 | - self_delimited: bool, | ||
| 1337 | ) -> Result<(u8, usize)> { | 1407 | ) -> Result<(u8, usize)> { |
| 1338 | let count = frames.len(); | 1408 | let count = frames.len(); |
| 1339 | let len0 = frames[0].len(); | 1409 | let len0 = frames[0].len(); |
| 1340 | let limit = max_data - 1; | 1410 | let limit = max_data - 1; |
| 1341 | let lens_differ = frames.iter().any(|f| f.len() != len0); | 1411 | let lens_differ = frames.iter().any(|f| f.len() != len0); |
| 1342 | let too_big = || Error::corrupt("opus encode: multi-frame packet exceeds its budget"); | 1412 | let too_big = || Error::corrupt("opus encode: multi-frame packet exceeds its budget"); |
| 1343 | - if count == 2 && !self_delimited { | 1413 | + if count == 2 { |
| 1344 | let size = if lens_differ { | 1414 | let size = if lens_differ { |
| 1345 | len0 + frames[1].len() + 1 + usize::from(len0 >= 252) | 1415 | len0 + frames[1].len() + 1 + usize::from(len0 >= 252) |
| 1346 | } else { | 1416 | } else { |
| @@ -1362,7 +1432,7 @@ impl Encoder { | |||
| 1362 | return Ok((if lens_differ { 2 } else { 1 }, pos)); | 1432 | return Ok((if lens_differ { 2 } else { 1 }, pos)); |
| 1363 | } | 1433 | } |
| 1364 | } | 1434 | } |
| 1365 | - let vbr = self_delimited || lens_differ; | 1435 | + let vbr = lens_differ; |
| 1366 | let size = if vbr { | 1436 | let size = if vbr { |
| 1367 | 1 + frames[..count - 1] | 1437 | 1 + frames[..count - 1] |
| 1368 | .iter() | 1438 | .iter() |
| @@ -1396,12 +1466,61 @@ impl Encoder { | |||
| 1396 | pos += f.len(); | 1466 | pos += f.len(); |
| 1397 | } | 1467 | } |
| 1398 | if pad_amount != 0 { | 1468 | if pad_amount != 0 { |
| 1399 | - buf[pos..limit].fill(1); | 1469 | + buf[pos..limit].fill(0); |
| 1400 | pos = limit; | 1470 | pos = limit; |
| 1401 | } | 1471 | } |
| 1402 | Ok((3, pos)) | 1472 | Ok((3, pos)) |
| 1403 | } | 1473 | } |
| 1404 | 1474 | ||
| 1475 | + fn frame_len_at(payload: &[u8], pos: usize) -> (usize, usize) { | ||
| 1476 | + let b0 = usize::from(payload[pos]); | ||
| 1477 | + if b0 < 252 { | ||
| 1478 | + (b0, 1) | ||
| 1479 | + } else { | ||
| 1480 | + (b0 + 4 * usize::from(payload[pos + 1]), 2) | ||
| 1481 | + } | ||
| 1482 | + } | ||
| 1483 | + | ||
| 1484 | + fn self_delimited_split(toc: u8, payload: &[u8]) -> (usize, usize) { | ||
| 1485 | + match toc & 3 { | ||
| 1486 | + 0 => (0, payload.len()), | ||
| 1487 | + 1 => (0, payload.len() / 2), | ||
| 1488 | + 2 => { | ||
| 1489 | + let (len0, used) = Self::frame_len_at(payload, 0); | ||
| 1490 | + (used, payload.len() - used - len0) | ||
| 1491 | + } | ||
| 1492 | + _ => { | ||
| 1493 | + let count = usize::from(payload[0] & 0x3F); | ||
| 1494 | + let vbr = payload[0] & 0x80 != 0; | ||
| 1495 | + let mut pos = 1; | ||
| 1496 | + let mut pad = 0; | ||
| 1497 | + if payload[0] & 0x40 != 0 { | ||
| 1498 | + loop { | ||
| 1499 | + let p = usize::from(payload[pos]); | ||
| 1500 | + pos += 1; | ||
| 1501 | + if p == 255 { | ||
| 1502 | + pad += 254; | ||
| 1503 | + } else { | ||
| 1504 | + pad += p; | ||
| 1505 | + break; | ||
| 1506 | + } | ||
| 1507 | + } | ||
| 1508 | + } | ||
| 1509 | + if vbr { | ||
| 1510 | + let mut sum = 0; | ||
| 1511 | + for _ in 1..count { | ||
| 1512 | + let (len, used) = Self::frame_len_at(payload, pos); | ||
| 1513 | + sum += len; | ||
| 1514 | + pos += used; | ||
| 1515 | + } | ||
| 1516 | + (pos, payload.len() - pos - pad - sum) | ||
| 1517 | + } else { | ||
| 1518 | + (pos, (payload.len() - pos - pad) / count) | ||
| 1519 | + } | ||
| 1520 | + } | ||
| 1521 | + } | ||
| 1522 | + } | ||
| 1523 | + | ||
| 1405 | /// The TOC byte, the frame size in 48 kHz samples and the CELT end band | 1524 | /// The TOC byte, the frame size in 48 kHz samples and the CELT end band |
| 1406 | /// for a frame of `frame_size` input samples per channel. | 1525 | /// for a frame of `frame_size` input samples per channel. |
| 1407 | fn toc( | 1526 | fn toc( |
| @@ -1494,7 +1613,7 @@ impl Encoder { | |||
| 1494 | let is_silence = pcm | 1613 | let is_silence = pcm |
| 1495 | .iter() | 1614 | .iter() |
| 1496 | .take(frame_size * self.channels) | 1615 | .take(frame_size * self.channels) |
| 1497 | - .all(|x| x.abs() <= DTX_SILENCE); | 1616 | + .all(|x| x.abs() <= self.silence_threshold()); |
| 1498 | let stereo_width = if self.channels == 2 && !self.force_mono { | 1617 | let stereo_width = if self.channels == 2 && !self.force_mono { |
| 1499 | update_stereo_width(&mut self.width_mem, pcm, frame_size, self.sample_rate) | 1618 | update_stereo_width(&mut self.width_mem, pcm, frame_size, self.sample_rate) |
| 1500 | } else { | 1619 | } else { |
| @@ -1511,8 +1630,10 @@ impl Encoder { | |||
| 1511 | }; | 1630 | }; |
| 1512 | self.voice_ratio = (0.5 + 100.0 * (1.0 - prob)).floor() as i32; | 1631 | self.voice_ratio = (0.5 + 100.0 * (1.0 - prob)).floor() as i32; |
| 1513 | } | 1632 | } |
| 1514 | - let detected = | 1633 | + let detected = self |
| 1515 | - (self.bw_detect && self.info.valid).then(|| detected_bandwidth(self.info.bandwidth)); | 1634 | + .info |
| 1635 | + .valid | ||
| 1636 | + .then(|| detected_bandwidth(self.info.bandwidth)); | ||
| 1516 | 1637 | ||
| 1517 | let mut bitrate = | 1638 | let mut bitrate = |
| 1518 | (self.bitrate as i32).min(bits_to_bitrate(max_data_bytes as i32 * 8, fs, fsz)); | 1639 | (self.bitrate as i32).min(bits_to_bitrate(max_data_bytes as i32 * 8, fs, fsz)); |
| @@ -1522,6 +1643,25 @@ impl Encoder { | |||
| 1522 | bitrate = bits_to_bitrate(cbr_bytes * 8, fs, fsz); | 1643 | bitrate = bits_to_bitrate(cbr_bytes * 8, fs, fsz); |
| 1523 | max_data = cbr_bytes.max(1); | 1644 | max_data = cbr_bytes.max(1); |
| 1524 | } | 1645 | } |
| 1646 | + self.bitrate_bps = bitrate; | ||
| 1647 | + if max_data < 3 | ||
| 1648 | + || bitrate < 3 * frame_rate * 8 | ||
| 1649 | + || (frame_rate < 50 && (max_data * frame_rate < 300 || bitrate < 2400)) | ||
| 1650 | + { | ||
| 1651 | + return Decision { | ||
| 1652 | + mode: self.prev_mode.unwrap_or(Mode::Hybrid), | ||
| 1653 | + bandwidth: self.coded_bandwidth, | ||
| 1654 | + stream_channels: self.stream_channels, | ||
| 1655 | + equiv_rate: 0, | ||
| 1656 | + redundancy: false, | ||
| 1657 | + redundancy_bytes: 0, | ||
| 1658 | + celt_to_silk: false, | ||
| 1659 | + to_celt: false, | ||
| 1660 | + prefill: Prefill::Off, | ||
| 1661 | + to_mono: false, | ||
| 1662 | + toc_only: Some(max_data as usize), | ||
| 1663 | + }; | ||
| 1664 | + } | ||
| 1525 | let max_rate = bits_to_bitrate(max_data * 8, fs, fsz); | 1665 | let max_rate = bits_to_bitrate(max_data * 8, fs, fsz); |
| 1526 | let ve = self.voice_est(); | 1666 | let ve = self.voice_est(); |
| 1527 | let mut equiv = compute_equiv_rate(bitrate, channels, frame_rate, self.vbr, None, loss); | 1667 | let mut equiv = compute_equiv_rate(bitrate, channels, frame_rate, self.vbr, None, loss); |
| @@ -1735,6 +1875,7 @@ impl Encoder { | |||
| 1735 | to_celt, | 1875 | to_celt, |
| 1736 | prefill, | 1876 | prefill, |
| 1737 | to_mono, | 1877 | to_mono, |
| 1878 | + toc_only: None, | ||
| 1738 | } | 1879 | } |
| 1739 | } | 1880 | } |
| 1740 | 1881 | ||
| @@ -1781,7 +1922,22 @@ impl Encoder { | |||
| 1781 | /// [`Encoder::encode_float`] from 16-bit samples. | 1922 | /// [`Encoder::encode_float`] from 16-bit samples. |
| 1782 | pub fn encode(&mut self, pcm: &[i16], frame_size: usize, out: &mut [u8]) -> Result<usize> { | 1923 | pub fn encode(&mut self, pcm: &[i16], frame_size: usize, out: &mut [u8]) -> Result<usize> { |
| 1783 | let float: Vec<f32> = pcm.iter().map(|&v| v as f32 * (1.0 / 32768.0)).collect(); | 1924 | let float: Vec<f32> = pcm.iter().map(|&v| v as f32 * (1.0 / 32768.0)).collect(); |
| 1784 | - self.encode_float(&float, frame_size, out) | 1925 | + self.lsb_depth = 16; |
| 1926 | + let r = self.encode_float(&float, frame_size, out); | ||
| 1927 | + self.lsb_depth = 24; | ||
| 1928 | + r | ||
| 1929 | + } | ||
| 1930 | + | ||
| 1931 | + fn total_buffer(&self) -> usize { | ||
| 1932 | + if self.align_input { | ||
| 1933 | + self.sample_rate as usize / 250 | ||
| 1934 | + } else { | ||
| 1935 | + 0 | ||
| 1936 | + } | ||
| 1937 | + } | ||
| 1938 | + | ||
| 1939 | + fn silence_threshold(&self) -> f32 { | ||
| 1940 | + 1.0 / (1u32 << self.lsb_depth) as f32 | ||
| 1785 | } | 1941 | } |
| 1786 | 1942 | ||
| 1787 | /// [`Encoder::encode_float`] in the self-delimited framing of RFC 6716 | 1943 | /// [`Encoder::encode_float`] in the self-delimited framing of RFC 6716 |
| @@ -1797,24 +1953,7 @@ impl Encoder { | |||
| 1797 | Err(e) => Err(e), | 1953 | Err(e) => Err(e), |
| 1798 | Ok((toc, payload)) => { | 1954 | Ok((toc, payload)) => { |
| 1799 | let count = payload.first().copied().unwrap_or(0); | 1955 | let count = payload.first().copied().unwrap_or(0); |
| 1800 | - let (head, last) = if toc & 3 == 3 { | 1956 | + let (head, last) = Self::self_delimited_split(toc, payload); |
| 1801 | - let count = usize::from(payload[0] & 0x3F); | ||
| 1802 | - let mut pos = 1; | ||
| 1803 | - let mut sum = 0; | ||
| 1804 | - for _ in 1..count { | ||
| 1805 | - let b0 = usize::from(payload[pos]); | ||
| 1806 | - let (len, used) = if b0 < 252 { | ||
| 1807 | - (b0, 1) | ||
| 1808 | - } else { | ||
| 1809 | - (b0 + 4 * usize::from(payload[pos + 1]), 2) | ||
| 1810 | - }; | ||
| 1811 | - sum += len; | ||
| 1812 | - pos += used; | ||
| 1813 | - } | ||
| 1814 | - (pos, payload.len() - pos - sum) | ||
| 1815 | - } else { | ||
| 1816 | - (0, payload.len()) | ||
| 1817 | - }; | ||
| 1818 | let mut len = [0u8; 2]; | 1957 | let mut len = [0u8; 2]; |
| 1819 | let mut len_bytes = 0; | 1958 | let mut len_bytes = 0; |
| 1820 | let r = Self::write_frame_len(&mut len, &mut len_bytes, last); | 1959 | let r = Self::write_frame_len(&mut len, &mut len_bytes, last); |
| @@ -1874,7 +2013,7 @@ impl Encoder { | |||
| 1874 | } | 2013 | } |
| 1875 | let max_data_bytes = self.frame_max_data(frame_48k, cap); | 2014 | let max_data_bytes = self.frame_max_data(frame_48k, cap); |
| 1876 | let budget = max_data_bytes - 1; | 2015 | let budget = max_data_bytes - 1; |
| 1877 | - self.range.reset(cap); | 2016 | + self.range.reset(budget); |
| 1878 | let f = self.silk_frame( | 2017 | let f = self.silk_frame( |
| 1879 | d, | 2018 | d, |
| 1880 | max_data_bytes, | 2019 | max_data_bytes, |
| @@ -1896,104 +2035,55 @@ impl Encoder { | |||
| 1896 | self.switch_ready(&mut d, max_data_bytes, frame_size); | 2035 | self.switch_ready(&mut d, max_data_bytes, frame_size); |
| 1897 | } | 2036 | } |
| 1898 | let celt_rate = silk.total_bit_rate - silk.bit_rate; | 2037 | let celt_rate = silk.total_bit_rate - silk.bit_rate; |
| 1899 | - let hb_gain = 1.0 - 0.5 * (-(celt_rate as f32) / 1024.0).exp2(); | 2038 | + let hb_gain = 1.0 - crate::celt_flp::celt_exp2(-(celt_rate as f32) * (1.0 / 1024.0)); |
| 1900 | self.fade_celt_input(delayed, frame_size, hb_gain); | 2039 | self.fade_celt_input(delayed, frame_size, hb_gain); |
| 1901 | self.stereo_fade_step(delayed, frame_size, d); | 2040 | self.stereo_fade_step(delayed, frame_size, d); |
| 1902 | - let tell_bytes = (self.range.tell() as usize).div_ceil(8); | ||
| 1903 | self.code_redundancy_flags(&mut d, max_data_bytes, true); | 2041 | self.code_redundancy_flags(&mut d, max_data_bytes, true); |
| 1904 | let end = bandwidth.celt_end_band(); | 2042 | let end = bandwidth.celt_end_band(); |
| 1905 | let red_len = if d.redundancy { d.redundancy_bytes } else { 0 }; | 2043 | let red_len = if d.redundancy { d.redundancy_bytes } else { 0 }; |
| 2044 | + let nb_compr = budget - red_len; | ||
| 2045 | + self.range.shrink(nb_compr); | ||
| 2046 | + self.celt_setup(Mode::Hybrid, end, d.stream_channels); | ||
| 2047 | + self.celt.set_analysis(&self.info); | ||
| 2048 | + self.celt.set_silk_info(silk.signal_type, silk.offset); | ||
| 1906 | let mut red = [0u8; MAX_REDUNDANCY_BYTES]; | 2049 | let mut red = [0u8; MAX_REDUNDANCY_BYTES]; |
| 1907 | let mut red_rng = 0; | 2050 | let mut red_rng = 0; |
| 1908 | if d.redundancy && d.celt_to_silk { | 2051 | if d.redundancy && d.celt_to_silk { |
| 1909 | - let n2 = self.sample_rate as usize / 200; | 2052 | + red_rng = self.celt_to_silk_redundancy(delayed, red_len, &mut red); |
| 1910 | - red_rng = self.celt_redundancy( | ||
| 1911 | - &delayed[..self.channels * n2], | ||
| 1912 | - 240, | ||
| 1913 | - end, | ||
| 1914 | - red_len, | ||
| 1915 | - 2, | ||
| 1916 | - &mut red, | ||
| 1917 | - )?; | ||
| 1918 | - self.celt.reset(); | ||
| 1919 | } | 2053 | } |
| 1920 | - let nb_base = if self.vbr { | 2054 | + self.celt.set_start_band(17); |
| 1921 | - cap | 2055 | + let celt_rate = self.bitrate_bps - silk.bit_rate; |
| 1922 | - } else { | 2056 | + let n = self.celt_main(Mode::Hybrid, delayed, frame_size, nb_compr, celt_rate); |
| 1923 | - budget.max(tell_bytes + HYBRID_CELT_MIN_BYTES).min(cap) | ||
| 1924 | - }; | ||
| 1925 | - self.range.shrink(nb_base - red_len); | ||
| 1926 | - self.celt.set_constrained_vbr(!self.vbr); | ||
| 1927 | - self.celt.set_silk_offset(silk.offset); | ||
| 1928 | - let vbr_rate = if self.vbr { | ||
| 1929 | - (self.bitrate as i32 - silk.bit_rate).max(501) as u32 | ||
| 1930 | - } else { | ||
| 1931 | - 0 | ||
| 1932 | - }; | ||
| 1933 | - let switch = self.prev_mode.is_some_and(|p| p != d.mode); | ||
| 1934 | - if switch { | ||
| 1935 | - self.celt_prefill(17, end, vbr_rate); | ||
| 1936 | - } | ||
| 1937 | - let n = self.celt.encode( | ||
| 1938 | - &mut self.range, | ||
| 1939 | - delayed, | ||
| 1940 | - frame_48k, | ||
| 1941 | - 17, | ||
| 1942 | - end, | ||
| 1943 | - vbr_rate, | ||
| 1944 | - &self.info, | ||
| 1945 | - )?; | ||
| 1946 | if d.redundancy && !d.celt_to_silk { | 2057 | if d.redundancy && !d.celt_to_silk { |
| 1947 | - red_rng = self.silk_to_celt_redundancy(delayed, frame_size, end, red_len, &mut red)?; | 2058 | + self.range.shrink(n); |
| 2059 | + red_rng = self.silk_to_celt_redundancy(delayed, frame_size, red_len, &mut red); | ||
| 1948 | } | 2060 | } |
| 1949 | - self.final_range = self.range.range() ^ red_rng; | 2061 | + let final_range = self.final_range ^ red_rng; |
| 2062 | + self.final_range = final_range; | ||
| 1950 | self.silk_buf[..n].copy_from_slice(&self.range.data()[..n]); | 2063 | self.silk_buf[..n].copy_from_slice(&self.range.data()[..n]); |
| 1951 | self.silk_buf[n..n + red_len].copy_from_slice(&red[..red_len]); | 2064 | self.silk_buf[n..n + red_len].copy_from_slice(&red[..red_len]); |
| 1952 | Ok(Payload::Silk(n + red_len)) | 2065 | Ok(Payload::Silk(n + red_len)) |
| 1953 | } | 2066 | } |
| 1954 | 2067 | ||
| 1955 | - /// Encodes the CELT frame into the internal range coder and returns its | ||
| 1956 | - /// byte length. `frame_size` is in 48 kHz samples, `end` is the last coded | ||
| 1957 | - /// band, and `cap` bounds the frame (the caller's buffer minus headers). | ||
| 1958 | - /// `switch` is set when the previous frame was another mode: the CELT | ||
| 1959 | - /// state is reset and primed first, as libopus does. | ||
| 1960 | fn encode_frame( | 2068 | fn encode_frame( |
| 1961 | &mut self, | 2069 | &mut self, |
| 1962 | - pcm: &[f32], | 2070 | + delayed: &[f32], |
| 1963 | frame_size: usize, | 2071 | frame_size: usize, |
| 1964 | end: usize, | 2072 | end: usize, |
| 1965 | cap: usize, | 2073 | cap: usize, |
| 1966 | - switch: bool, | 2074 | + stream_channels: usize, |
| 1967 | ) -> Result<usize> { | 2075 | ) -> Result<usize> { |
| 1968 | - let cap = cap.min(MAX_FRAME_BYTES); | 2076 | + let max_data_bytes = self.frame_max_data(frame_size * self.upsample, cap); |
| 1969 | - if cap < 2 { | 2077 | + if max_data_bytes < 3 { |
| 1970 | return Err(Error::corrupt( | 2078 | return Err(Error::corrupt( |
| 1971 | "opus encode: output buffer smaller than the minimum packet", | 2079 | "opus encode: output buffer smaller than the minimum packet", |
| 1972 | )); | 2080 | )); |
| 1973 | } | 2081 | } |
| 1974 | - // One byte per packet goes to the TOC; the CELT layer sees the rest. | 2082 | + self.range.reset(max_data_bytes - 1); |
| 1975 | - let toc_bps = 8 * 48000 / frame_size as u32; | 2083 | + self.celt_setup(Mode::Celt, end, stream_channels); |
| 1976 | - let (budget, vbr_rate) = if self.vbr { | 2084 | + self.celt.set_analysis(&self.info); |
| 1977 | - (cap, self.bitrate.saturating_sub(toc_bps).max(500)) | 2085 | + self.celt.set_start_band(0); |
| 1978 | - } else { | 2086 | + let n = self.celt_main(Mode::Celt, delayed, frame_size, max_data_bytes - 1, 0); |
| 1979 | - let b = ((self.bitrate as u64 * frame_size as u64 + 4 * 48000) / (8 * 48000)) as usize; | ||
| 1980 | - (b.saturating_sub(1).clamp(2, cap), 0) | ||
| 1981 | - }; | ||
| 1982 | - self.range.reset(budget); | ||
| 1983 | - self.celt.set_constrained_vbr(true); | ||
| 1984 | - if switch { | ||
| 1985 | - self.celt_prefill(0, end, vbr_rate); | ||
| 1986 | - } | ||
| 1987 | - let n = self.celt.encode( | ||
| 1988 | - &mut self.range, | ||
| 1989 | - pcm, | ||
| 1990 | - frame_size, | ||
| 1991 | - 0, | ||
| 1992 | - end, | ||
| 1993 | - vbr_rate, | ||
| 1994 | - &self.info, | ||
| 1995 | - )?; | ||
| 1996 | - self.final_range = self.range.range(); | ||
| 1997 | Ok(n) | 2087 | Ok(n) |
| 1998 | } | 2088 | } |
| 1999 | } | 2089 | } |
| @@ -2014,8 +2104,6 @@ mod tests { | |||
| 2014 | e.set_bitrate(64_000); | 2104 | e.set_bitrate(64_000); |
| 2015 | e.info.valid = true; | 2105 | e.info.valid = true; |
| 2016 | e.info.bandwidth = 15; | 2106 | e.info.bandwidth = 15; |
| 2017 | - assert_eq!(decided_bandwidth(&mut e), Bandwidth::Full); | ||
| 2018 | - e.bw_detect = true; | ||
| 2019 | assert_eq!(decided_bandwidth(&mut e), Bandwidth::SuperWide); | 2107 | assert_eq!(decided_bandwidth(&mut e), Bandwidth::SuperWide); |
| 2020 | e.info.bandwidth = 20; | 2108 | e.info.bandwidth = 20; |
| 2021 | assert_eq!(decided_bandwidth(&mut e), Bandwidth::Full); | 2109 | assert_eq!(decided_bandwidth(&mut e), Bandwidth::Full); |
| @@ -2074,7 +2162,11 @@ mod tests { | |||
| 2074 | let mut last = 0u8; | 2162 | let mut last = 0u8; |
| 2075 | for per_channel in 500..=45_000u32 { | 2163 | for per_channel in 500..=45_000u32 { |
| 2076 | e.set_bitrate(per_channel * channels as u32); | 2164 | e.set_bitrate(per_channel * channels as u32); |
| 2077 | - let class = match e.decide(&pcm, 960, 1276).mode { | 2165 | + let d = e.decide(&pcm, 960, 1276); |
| 2166 | + if d.toc_only.is_some() { | ||
| 2167 | + continue; | ||
| 2168 | + } | ||
| 2169 | + let class = match d.mode { | ||
| 2078 | Mode::Silk => 0, | 2170 | Mode::Silk => 0, |
| 2079 | Mode::Hybrid => 1, | 2171 | Mode::Hybrid => 1, |
| 2080 | Mode::Celt => 2, | 2172 | Mode::Celt => 2, |
crates/ec-opus/src/lib.rsmodified+1 -2
| @@ -66,7 +66,7 @@ | |||
| 66 | 66 | ||
| 67 | pub(crate) mod analysis; | 67 | pub(crate) mod analysis; |
| 68 | pub mod celt; | 68 | pub mod celt; |
| 69 | -pub mod celt_enc; | 69 | +pub(crate) mod celt_flp; |
| 70 | pub mod encoder; | 70 | pub mod encoder; |
| 71 | pub mod multistream; | 71 | pub mod multistream; |
| 72 | pub mod multistream_enc; | 72 | pub mod multistream_enc; |
| @@ -79,7 +79,6 @@ pub(crate) mod silk_flp; | |||
| 79 | mod stack_budget; | 79 | mod stack_budget; |
| 80 | 80 | ||
| 81 | pub use celt::CeltDecoder; | 81 | pub use celt::CeltDecoder; |
| 82 | -pub use celt_enc::CeltFrameDiag; | ||
| 83 | pub use encoder::{Application, Encoder}; | 82 | pub use encoder::{Application, Encoder}; |
| 84 | pub use multistream::MultistreamDecoder; | 83 | pub use multistream::MultistreamDecoder; |
| 85 | pub use multistream_enc::MultistreamEncoder; | 84 | pub use multistream_enc::MultistreamEncoder; |
crates/ec-opus/src/range.rsmodified+5 -0
| @@ -611,6 +611,11 @@ impl RangeEncoder { | |||
| 611 | self.nbits_total.saturating_mul(8).saturating_sub(lg) | 611 | self.nbits_total.saturating_mul(8).saturating_sub(lg) |
| 612 | } | 612 | } |
| 613 | 613 | ||
| 614 | + /// `enc->nbits_total += bits` (the CELT silence path). | ||
| 615 | + pub fn add_tell(&mut self, bits: i32) { | ||
| 616 | + self.nbits_total = (self.nbits_total as i32 + bits) as u32; | ||
| 617 | + } | ||
| 618 | + | ||
| 614 | /// Declares the rest of the frame used, so [`RangeEncoder::tell`] reports | 619 | /// Declares the rest of the frame used, so [`RangeEncoder::tell`] reports |
| 615 | /// the whole frame — the encoder side of the decoder's `skip_to_end`, | 620 | /// the whole frame — the encoder side of the decoder's `skip_to_end`, |
| 616 | /// which is what a silent CELT frame does with its remaining bits. | 621 | /// which is what a silent CELT frame does with its remaining bits. |
crates/ec-opus/src/silk.rsmodified+1 -1
| @@ -1057,7 +1057,7 @@ pub(crate) fn nlsf2a(nlsf: &[i16], order: usize) -> [i16; MAX_LPC_ORDER] { | |||
| 1057 | if maxabs_q12 > 32767 { | 1057 | if maxabs_q12 > 32767 { |
| 1058 | let maxabs_q12 = maxabs_q12.min(163838); | 1058 | let maxabs_q12 = maxabs_q12.min(163838); |
| 1059 | let sc_q16 = | 1059 | let sc_q16 = |
| 1060 | - 65471 - ((maxabs_q12 - 32767) << 14) / ((maxabs_q12 * (idx as i32 + 1)) >> 2); | 1060 | + 65470 - ((maxabs_q12 - 32767) << 14) / ((maxabs_q12 * (idx as i32 + 1)) >> 2); |
| 1061 | bwexpander_32(&mut a32_qa1[..order], sc_q16); | 1061 | bwexpander_32(&mut a32_qa1[..order], sc_q16); |
| 1062 | } else { | 1062 | } else { |
| 1063 | break; | 1063 | break; |
crates/ec-opus/src/silk_flp/encode.rsmodified+11 -6
| @@ -22,6 +22,7 @@ const VARIABLE_HP_MIN_CUTOFF_HZ_Q16: i32 = fix_const(60.0, 16); | |||
| 22 | const VARIABLE_HP_MAX_DELTA_FREQ_Q7: i32 = fix_const(0.4, 7); | 22 | const VARIABLE_HP_MAX_DELTA_FREQ_Q7: i32 = fix_const(0.4, 7); |
| 23 | const VARIABLE_HP_SMTH_COEF1_Q16: i32 = fix_const(0.1, 16); | 23 | const VARIABLE_HP_SMTH_COEF1_Q16: i32 = fix_const(0.1, 16); |
| 24 | const VAD_NO_ACTIVITY: i32 = 0; | 24 | const VAD_NO_ACTIVITY: i32 = 0; |
| 25 | +const MAX_FRAME_BYTES: usize = 1275; | ||
| 25 | 26 | ||
| 26 | pub(crate) const TRANSITION_FRAMES: i32 = 5120 / MAX_FRAME_LENGTH_MS as i32; | 27 | pub(crate) const TRANSITION_FRAMES: i32 = 5120 / MAX_FRAME_LENGTH_MS as i32; |
| 27 | const TRANSITION_NB: usize = 3; | 28 | const TRANSITION_NB: usize = 3; |
| @@ -311,8 +312,10 @@ pub(crate) fn encode_frame( | |||
| 311 | find_pred_coefs(st, &mut ctrl, &res_pitch, cond_coding); | 312 | find_pred_coefs(st, &mut ctrl, &res_pitch, cond_coding); |
| 312 | process_gains(st, &mut ctrl, cond_coding); | 313 | process_gains(st, &mut ctrl, cond_coding); |
| 313 | 314 | ||
| 314 | - let x: Vec<f32> = st.x_buf[x_frame..x_frame + frame_length].to_vec(); | 315 | + let mut x_copy = [0f32; MAX_FRAME_LENGTH]; |
| 315 | - lbrr_encode(st, &mut ctrl, &x, cond_coding); | 316 | + x_copy[..frame_length].copy_from_slice(&st.x_buf[x_frame..x_frame + frame_length]); |
| 317 | + let x = &x_copy[..frame_length]; | ||
| 318 | + lbrr_encode(st, &mut ctrl, x, cond_coding); | ||
| 316 | 319 | ||
| 317 | let mut gain_mult_q8 = 256i32; | 320 | let mut gain_mult_q8 = 256i32; |
| 318 | let mut found_lower = false; | 321 | let mut found_lower = false; |
| @@ -337,7 +340,8 @@ pub(crate) fn encode_frame( | |||
| 337 | let prev_lag_copy = st.ec_prev_lag_index; | 340 | let prev_lag_copy = st.ec_prev_lag_index; |
| 338 | let prev_sig_copy = st.ec_prev_signal_type; | 341 | let prev_sig_copy = st.ec_prev_signal_type; |
| 339 | let mut snap2 = snap_start; | 342 | let mut snap2 = snap_start; |
| 340 | - let mut ec_buf_copy: Vec<u8> = Vec::new(); | 343 | + let mut ec_buf_copy = [0u8; MAX_FRAME_BYTES]; |
| 344 | + let mut ec_buf_len = 0usize; | ||
| 341 | 345 | ||
| 342 | let mut iter = 0; | 346 | let mut iter = 0; |
| 343 | loop { | 347 | loop { |
| @@ -355,7 +359,7 @@ pub(crate) fn encode_frame( | |||
| 355 | st.ec_prev_signal_type = prev_sig_copy; | 359 | st.ec_prev_signal_type = prev_sig_copy; |
| 356 | } | 360 | } |
| 357 | 361 | ||
| 358 | - run_nsq(st, &ctrl, &x); | 362 | + run_nsq(st, &ctrl, x); |
| 359 | 363 | ||
| 360 | if iter == MAX_ITER && !found_lower { | 364 | if iter == MAX_ITER && !found_lower { |
| 361 | snap2 = enc.snapshot(); | 365 | snap2 = enc.snapshot(); |
| @@ -386,7 +390,7 @@ pub(crate) fn encode_frame( | |||
| 386 | if iter == MAX_ITER { | 390 | if iter == MAX_ITER { |
| 387 | if found_lower && (gains_id_cur == gains_id_lower || n_bits > max_bits) { | 391 | if found_lower && (gains_id_cur == gains_id_lower || n_bits > max_bits) { |
| 388 | enc.restore(&snap2); | 392 | enc.restore(&snap2); |
| 389 | - enc.front_write(0, &ec_buf_copy); | 393 | + enc.front_write(0, &ec_buf_copy[..ec_buf_len]); |
| 390 | st.s_nsq = nsq_copy1.clone(); | 394 | st.s_nsq = nsq_copy1.clone(); |
| 391 | st.s_shape.last_gain_index = last_gain_index_copy2; | 395 | st.s_shape.last_gain_index = last_gain_index_copy2; |
| 392 | } | 396 | } |
| @@ -412,7 +416,8 @@ pub(crate) fn encode_frame( | |||
| 412 | if gains_id_cur != gains_id_lower { | 416 | if gains_id_cur != gains_id_lower { |
| 413 | gains_id_lower = gains_id_cur; | 417 | gains_id_lower = gains_id_cur; |
| 414 | snap2 = enc.snapshot(); | 418 | snap2 = enc.snapshot(); |
| 415 | - ec_buf_copy = enc.front().to_vec(); | 419 | + ec_buf_len = enc.front().len(); |
| 420 | + ec_buf_copy[..ec_buf_len].copy_from_slice(enc.front()); | ||
| 416 | nsq_copy1 = st.s_nsq.clone(); | 421 | nsq_copy1 = st.s_nsq.clone(); |
| 417 | last_gain_index_copy2 = st.s_shape.last_gain_index; | 422 | last_gain_index_copy2 = st.s_shape.last_gain_index; |
| 418 | } | 423 | } |
crates/ec-opus/src/silk_flp/opus.rsmodified+2 -0
| @@ -237,6 +237,7 @@ impl SilkLayer { | |||
| 237 | total_bit_rate: total_bitrate, | 237 | total_bit_rate: total_bitrate, |
| 238 | bit_rate, | 238 | bit_rate, |
| 239 | offset: self.ctl.offset, | 239 | offset: self.ctl.offset, |
| 240 | + signal_type: self.ctl.signal_type, | ||
| 240 | stereo_width_q14: self.ctl.stereo_width_q14, | 241 | stereo_width_q14: self.ctl.stereo_width_q14, |
| 241 | opus_can_switch: self.ctl.opus_can_switch, | 242 | opus_can_switch: self.ctl.opus_can_switch, |
| 242 | } | 243 | } |
| @@ -276,6 +277,7 @@ pub(crate) struct SilkResult { | |||
| 276 | pub(crate) total_bit_rate: i32, | 277 | pub(crate) total_bit_rate: i32, |
| 277 | pub(crate) bit_rate: i32, | 278 | pub(crate) bit_rate: i32, |
| 278 | pub(crate) offset: i32, | 279 | pub(crate) offset: i32, |
| 280 | + pub(crate) signal_type: i32, | ||
| 279 | pub(crate) stereo_width_q14: i32, | 281 | pub(crate) stereo_width_q14: i32, |
| 280 | pub(crate) opus_can_switch: bool, | 282 | pub(crate) opus_can_switch: bool, |
| 281 | } | 283 | } |
crates/ec-opus/src/stack_budget.rsmodified+18 -33
| @@ -68,9 +68,9 @@ | |||
| 68 | //! that holds one is a `Box`, which | 68 | //! that holds one is a `Box`, which |
| 69 | //! [`the_crate_private_silk_encoders_stay_behind_a_box`] pins by source. | 69 | //! [`the_crate_private_silk_encoders_stay_behind_a_box`] pins by source. |
| 70 | //! | 70 | //! |
| 71 | -//! **Where the number sits.** At 8 KiB with the worst budgeted return at 4,016 | 71 | +//! **Where the number sits.** At 8 KiB with the worst budgeted return at 2,936 |
| 72 | -//! bytes ([`Encoder`]), the worst a caller owes is `2 x 4232 = 8,464` bytes -- | 72 | +//! bytes ([`Encoder`]), the worst a caller owes is `2 x 2936 = 5,872` bytes -- |
| 73 | -//! **0.39%** of a 2 MiB thread -- and the budget sits 2.04x above the | 73 | +//! **0.28%** of a 2 MiB thread -- and the budget sits 2.79x above the |
| 74 | //! incumbent. The pre-fix `Encoder` (87,024 B) is **10.62x over** and the | 74 | //! incumbent. The pre-fix `Encoder` (87,024 B) is **10.62x over** and the |
| 75 | //! pre-fix `Decoder` (7,576 B) sat at 92.5% of it, so the historical defect | 75 | //! pre-fix `Decoder` (7,576 B) sat at 92.5% of it, so the historical defect |
| 76 | //! and the near-miss both red by a factor rather than by a hair. | 76 | //! and the near-miss both red by a factor rather than by a hair. |
| @@ -121,7 +121,7 @@ pub(crate) const BY_VALUE_TYPES: &[(&str, Option<usize>, bool, &str)] = &[ | |||
| 121 | // -- encoder.rs ------------------------------------------------------- | 121 | // -- encoder.rs ------------------------------------------------------- |
| 122 | ( | 122 | ( |
| 123 | "Encoder", | 123 | "Encoder", |
| 124 | - Some(4232), | 124 | + Some(2936), |
| 125 | true, | 125 | true, |
| 126 | "Encoder::new -> Result<Encoder>. Was 87024, 10.62x the budget: six \ | 126 | "Encoder::new -> Result<Encoder>. Was 87024, 10.62x the budget: six \ |
| 127 | inline SILK encoder slots (79176 together) and an inline 3831-byte \ | 127 | inline SILK encoder slots (79176 together) and an inline 3831-byte \ |
| @@ -142,24 +142,6 @@ pub(crate) const BY_VALUE_TYPES: &[(&str, Option<usize>, bool, &str)] = &[ | |||
| 142 | "celt::CeltDecoder::new(channels, downsample) -> Self; also moved by \ | 142 | "celt::CeltDecoder::new(channels, downsample) -> Self; also moved by \ |
| 143 | value into Decoder::celt", | 143 | value into Decoder::celt", |
| 144 | ), | 144 | ), |
| 145 | - // -- celt_enc.rs ------------------------------------------------------ | ||
| 146 | - ( | ||
| 147 | - "CeltEncoder", | ||
| 148 | - Some(1600), | ||
| 149 | - false, | ||
| 150 | - "celt_enc::CeltEncoder::new -> Self. `pub`, and stored inline in \ | ||
| 151 | - Encoder::celt, but 1600 is 20% of budget and it is the second \ | ||
| 152 | - largest field of a type that is itself budgeted; the crate-private \ | ||
| 153 | - 19744-byte SILK stereo layer is the one this module had to pin", | ||
| 154 | - ), | ||
| 155 | - ( | ||
| 156 | - "CeltFrameDiag", | ||
| 157 | - Some(424), | ||
| 158 | - true, | ||
| 159 | - "celt_enc::last_diag(&self) -> &CeltFrameDiag hands back a \ | ||
| 160 | - reference; the row is here because Encoder::last_celt_diag and \ | ||
| 161 | - Decoder::last_celt_diag name it in their signatures", | ||
| 162 | - ), | ||
| 163 | // -- multistream.rs / multistream_enc.rs ------------------------------ | 145 | // -- multistream.rs / multistream_enc.rs ------------------------------ |
| 164 | ( | 146 | ( |
| 165 | "MultistreamDecoder", | 147 | "MultistreamDecoder", |
| @@ -234,10 +216,10 @@ pub(crate) const BY_VALUE_TYPES: &[(&str, Option<usize>, bool, &str)] = &[ | |||
| 234 | // -- analysis.rs (crate-private) -------------------------------------- | 216 | // -- analysis.rs (crate-private) -------------------------------------- |
| 235 | ( | 217 | ( |
| 236 | "TonalityAnalysis", | 218 | "TonalityAnalysis", |
| 237 | - Some(2168), | 219 | + Some(2096), |
| 238 | false, | 220 | false, |
| 239 | "analysis::TonalityAnalysis::new(sample_rate) -> Self, stored \ | 221 | "analysis::TonalityAnalysis::new(sample_rate) -> Self, stored \ |
| 240 | - INLINE in Encoder::analysis. 2168 is inside the budget and the field \ | 222 | + INLINE in Encoder::analysis. 2096 is inside the budget and the field \ |
| 241 | is reached only through an Encoder that is itself budgeted, so it is \ | 223 | is reached only through an Encoder that is itself budgeted, so it is \ |
| 242 | measured here rather than pinned behind a Box", | 224 | measured here rather than pinned behind a Box", |
| 243 | ), | 225 | ), |
| @@ -269,14 +251,6 @@ fn measured_by_name() -> Vec<(&'static str, usize)> { | |||
| 269 | "CeltDecoder", | 251 | "CeltDecoder", |
| 270 | std::mem::size_of::<crate::celt::CeltDecoder>(), | 252 | std::mem::size_of::<crate::celt::CeltDecoder>(), |
| 271 | ), | 253 | ), |
| 272 | - ( | ||
| 273 | - "CeltEncoder", | ||
| 274 | - std::mem::size_of::<crate::celt_enc::CeltEncoder>(), | ||
| 275 | - ), | ||
| 276 | - ( | ||
| 277 | - "CeltFrameDiag", | ||
| 278 | - std::mem::size_of::<crate::celt_enc::CeltFrameDiag>(), | ||
| 279 | - ), | ||
| 280 | ( | 254 | ( |
| 281 | "MultistreamDecoder", | 255 | "MultistreamDecoder", |
| 282 | std::mem::size_of::<crate::multistream::MultistreamDecoder>(), | 256 | std::mem::size_of::<crate::multistream::MultistreamDecoder>(), |
| @@ -406,7 +380,18 @@ mod tests { | |||
| 406 | const FILES: &[(&str, &str)] = &[ | 380 | const FILES: &[(&str, &str)] = &[ |
| 407 | ("analysis.rs", include_str!("analysis.rs")), | 381 | ("analysis.rs", include_str!("analysis.rs")), |
| 408 | ("celt.rs", include_str!("celt.rs")), | 382 | ("celt.rs", include_str!("celt.rs")), |
| 409 | - ("celt_enc.rs", include_str!("celt_enc.rs")), | 383 | + ("celt_flp/bands.rs", include_str!("celt_flp/bands.rs")), |
| 384 | + ("celt_flp/enc.rs", include_str!("celt_flp/enc.rs")), | ||
| 385 | + ("celt_flp/enc_an.rs", include_str!("celt_flp/enc_an.rs")), | ||
| 386 | + ("celt_flp/fft.rs", include_str!("celt_flp/fft.rs")), | ||
| 387 | + ("celt_flp/mod.rs", include_str!("celt_flp/mod.rs")), | ||
| 388 | + ("celt_flp/pitch.rs", include_str!("celt_flp/pitch.rs")), | ||
| 389 | + ( | ||
| 390 | + "celt_flp/quant_bands.rs", | ||
| 391 | + include_str!("celt_flp/quant_bands.rs"), | ||
| 392 | + ), | ||
| 393 | + ("celt_flp/tables.rs", include_str!("celt_flp/tables.rs")), | ||
| 394 | + ("celt_flp/vq.rs", include_str!("celt_flp/vq.rs")), | ||
| 410 | ("encoder.rs", include_str!("encoder.rs")), | 395 | ("encoder.rs", include_str!("encoder.rs")), |
| 411 | ("lib.rs", include_str!("lib.rs")), | 396 | ("lib.rs", include_str!("lib.rs")), |
| 412 | ("multistream.rs", include_str!("multistream.rs")), | 397 | ("multistream.rs", include_str!("multistream.rs")), |
crates/ec-opus/tests/conformance.rsmodified+2 -1213
| @@ -3027,276 +3027,6 @@ fn per_second_corr(source: &[f32], decoded: &[f32], channels: usize) -> (f64, u3 | |||
| 3027 | (min_c, drops) | 3027 | (min_c, drops) |
| 3028 | } | 3028 | } |
| 3029 | 3029 | ||
| 3030 | -// --------------------------------------------------------------------------- | ||
| 3031 | -// Per-second diagnostic: reelm@64k encoder decisions vs libopus correlation | ||
| 3032 | -// --------------------------------------------------------------------------- | ||
| 3033 | -// | ||
| 3034 | -// Dumps per-second correlation (ours vs ref) with per-frame CeltFrameDiag to | ||
| 3035 | -// lanes/opus-64-r1.seconds.txt. Run with: | ||
| 3036 | -// cargo test -p ec-opus --release --test conformance reelm64_persecond_diag -- --ignored --nocapture | ||
| 3037 | - | ||
| 3038 | -#[test] | ||
| 3039 | -#[ignore = "probe: per-second correlation dump for the 64k lane; unblocks when ~/Music/reelm.wav is back in the corpus (hard-asserts src.exists)"] | ||
| 3040 | -fn reelm64_persecond_diag() { | ||
| 3041 | - let _timing = timing_shared(); | ||
| 3042 | - const SECS: f64 = 120.0; | ||
| 3043 | - const FRAME: usize = 960; // 20 ms | ||
| 3044 | - const CHANNELS: usize = 2; | ||
| 3045 | - const MAX_LAG: usize = 2000; | ||
| 3046 | - const KBPS: u32 = 64; | ||
| 3047 | - | ||
| 3048 | - let src = shellexpand("~/Music/reelm.wav"); | ||
| 3049 | - assert!(src.exists(), "reelm.wav not found at {}", src.display()); | ||
| 3050 | - let source_pcm = ffmpeg_decode_pcm(&src, SECS); | ||
| 3051 | - let source_frames = source_pcm.len() / CHANNELS; | ||
| 3052 | - let seconds = source_frames as f64 / 48000.0; | ||
| 3053 | - | ||
| 3054 | - // Reference: ffmpeg libopus | ||
| 3055 | - let lanes_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../lanes"); | ||
| 3056 | - fs::create_dir_all(&lanes_dir).unwrap(); | ||
| 3057 | - let scratch = lanes_dir.join("opus-64-r1.scratch.ogg"); | ||
| 3058 | - ffmpeg_encode_libopus(&src, KBPS, &scratch, SECS); | ||
| 3059 | - let ref_packets = ogg_packets(&fs::read(&scratch).unwrap()); | ||
| 3060 | - let ref_payload: Vec<usize> = ref_packets | ||
| 3061 | - .iter() | ||
| 3062 | - .skip(2) // skip opus_head + opus_comment | ||
| 3063 | - .filter(|p| !p.is_empty()) | ||
| 3064 | - .map(|p| p.len()) | ||
| 3065 | - .collect(); | ||
| 3066 | - let (ref_dec, ref_ch) = decode_ogg(&scratch); | ||
| 3067 | - assert_eq!(ref_ch, CHANNELS); | ||
| 3068 | - let (_, ref_aligned) = align_to_source(&source_pcm, &ref_dec, CHANNELS, MAX_LAG); | ||
| 3069 | - let _ = fs::remove_file(&scratch); | ||
| 3070 | - | ||
| 3071 | - // Ours: ec-opus encoder, collecting per-frame diag | ||
| 3072 | - let mut enc = Encoder::new(48000, CHANNELS, Application::Audio).expect("encoder"); | ||
| 3073 | - enc.set_bitrate(KBPS * 1000); | ||
| 3074 | - enc.set_vbr_constrained(true); | ||
| 3075 | - let mut dec = Decoder::new(48000, CHANNELS).unwrap(); | ||
| 3076 | - let mut out = vec![0u8; 1500]; | ||
| 3077 | - let mut buf = vec![0.0f32; 5760 * CHANNELS]; | ||
| 3078 | - let mut padded = Vec::new(); | ||
| 3079 | - let mut ours_dec = Vec::new(); | ||
| 3080 | - let mut diags: Vec<ec_opus::CeltFrameDiag> = Vec::new(); | ||
| 3081 | - let mut ours_bytes: Vec<usize> = Vec::new(); | ||
| 3082 | - | ||
| 3083 | - for block in source_pcm.chunks(FRAME * CHANNELS) { | ||
| 3084 | - let block = if block.len() < FRAME * CHANNELS { | ||
| 3085 | - padded.clear(); | ||
| 3086 | - padded.extend_from_slice(block); | ||
| 3087 | - padded.resize(FRAME * CHANNELS, 0.0); | ||
| 3088 | - &padded[..] | ||
| 3089 | - } else { | ||
| 3090 | - block | ||
| 3091 | - }; | ||
| 3092 | - let len = enc.encode_float(block, FRAME, &mut out).expect("encode"); | ||
| 3093 | - let d = enc.last_celt_diag().clone(); | ||
| 3094 | - ours_bytes.push(len); | ||
| 3095 | - diags.push(d); | ||
| 3096 | - let n = dec.decode_float(&out[..len], &mut buf).expect("decode"); | ||
| 3097 | - ours_dec.extend_from_slice(&buf[..n * CHANNELS]); | ||
| 3098 | - } | ||
| 3099 | - let (_, ours_aligned) = align_to_source(&source_pcm, &ours_dec, CHANNELS, MAX_LAG); | ||
| 3100 | - | ||
| 3101 | - // Per-second correlation for both | ||
| 3102 | - let n_frames = (source_frames) | ||
| 3103 | - .min(ours_aligned.len() / CHANNELS) | ||
| 3104 | - .min(ref_aligned.len() / CHANNELS); | ||
| 3105 | - let sec_samples = 48000usize; | ||
| 3106 | - let frames_per_sec = sec_samples / FRAME; // 50 | ||
| 3107 | - | ||
| 3108 | - let mut sec_rows: Vec<(usize, f64, f64, f64)> = Vec::new(); // (sec, corr_ours, corr_ref, gap) | ||
| 3109 | - let mut start = 0usize; | ||
| 3110 | - let mut sec_idx = 0usize; | ||
| 3111 | - while start + sec_samples <= n_frames { | ||
| 3112 | - let mut acc_o = 0.0f64; | ||
| 3113 | - let mut acc_r = 0.0f64; | ||
| 3114 | - for ch in 0..CHANNELS { | ||
| 3115 | - let (mut sxy_o, mut sxx_o, mut syy_o) = (0.0f64, 0.0f64, 0.0f64); | ||
| 3116 | - let (mut sxy_r, mut sxx_r, mut syy_r) = (0.0f64, 0.0f64, 0.0f64); | ||
| 3117 | - for i in 0..sec_samples { | ||
| 3118 | - let s = source_pcm[(start + i) * CHANNELS + ch] as f64; | ||
| 3119 | - let o = ours_aligned[(start + i) * CHANNELS + ch] as f64; | ||
| 3120 | - let r = ref_aligned[(start + i) * CHANNELS + ch] as f64; | ||
| 3121 | - sxy_o += s * o; | ||
| 3122 | - sxx_o += s * s; | ||
| 3123 | - syy_o += o * o; | ||
| 3124 | - sxy_r += s * r; | ||
| 3125 | - sxx_r += s * s; | ||
| 3126 | - syy_r += r * r; | ||
| 3127 | - } | ||
| 3128 | - if sxx_o > 0.0 && syy_o > 0.0 { | ||
| 3129 | - acc_o += sxy_o / (sxx_o * syy_o).sqrt(); | ||
| 3130 | - } | ||
| 3131 | - if sxx_r > 0.0 && syy_r > 0.0 { | ||
| 3132 | - acc_r += sxy_r / (sxx_r * syy_r).sqrt(); | ||
| 3133 | - } | ||
| 3134 | - } | ||
| 3135 | - let co = acc_o / CHANNELS as f64; | ||
| 3136 | - let cr = acc_r / CHANNELS as f64; | ||
| 3137 | - sec_rows.push((sec_idx, co, cr, cr - co)); | ||
| 3138 | - start += sec_samples; | ||
| 3139 | - sec_idx += 1; | ||
| 3140 | - } | ||
| 3141 | - | ||
| 3142 | - // Sort by gap descending | ||
| 3143 | - let mut sorted = sec_rows.clone(); | ||
| 3144 | - sorted.sort_by(|a, b| b.3.partial_cmp(&a.3).unwrap()); | ||
| 3145 | - | ||
| 3146 | - let mut out_str = String::new(); | ||
| 3147 | - out_str.push_str("# reelm@64k per-second diagnostic (r1, current code)\n"); | ||
| 3148 | - out_str.push_str("# 120s cap, 20ms frames, VBR constrained, 48kHz stereo\n"); | ||
| 3149 | - out_str.push_str(&format!( | ||
| 3150 | - "# total frames: ours={} ref={}\n", | ||
| 3151 | - diags.len(), | ||
| 3152 | - ref_payload.len() | ||
| 3153 | - )); | ||
| 3154 | - let total_corr_o: f64 = sec_rows.iter().map(|r| r.1).sum::<f64>() / sec_rows.len() as f64; | ||
| 3155 | - let total_corr_r: f64 = sec_rows.iter().map(|r| r.2).sum::<f64>() / sec_rows.len() as f64; | ||
| 3156 | - out_str.push_str(&format!( | ||
| 3157 | - "# avg corr: ours={:.4} ref={:.4} gap={:+.4}\n\n", | ||
| 3158 | - total_corr_o, | ||
| 3159 | - total_corr_r, | ||
| 3160 | - total_corr_r - total_corr_o | ||
| 3161 | - )); | ||
| 3162 | - | ||
| 3163 | - // Per-second summary table | ||
| 3164 | - out_str.push_str("# sec\tcorr_ours\tcorr_ref\tgap\tavg_trim\tdual_n\tint_typ\tavg_B_ours\tavg_B_ref\ttf_chng_n\ttrans_n\n"); | ||
| 3165 | - for &(s, co, cr, g) in &sec_rows { | ||
| 3166 | - let f0 = s * frames_per_sec; | ||
| 3167 | - let f1 = ((s + 1) * frames_per_sec).min(diags.len()); | ||
| 3168 | - let sec_diags = &diags[f0..f1.min(diags.len())]; | ||
| 3169 | - let avg_trim: f64 = if !sec_diags.is_empty() { | ||
| 3170 | - sec_diags.iter().map(|d| d.alloc_trim as f64).sum::<f64>() / sec_diags.len() as f64 | ||
| 3171 | - } else { | ||
| 3172 | - -1.0 | ||
| 3173 | - }; | ||
| 3174 | - let dual_n = sec_diags.iter().filter(|d| d.dual_stereo).count(); | ||
| 3175 | - let int_typ = if !sec_diags.is_empty() { | ||
| 3176 | - sec_diags.iter().map(|d| d.intensity).max().unwrap_or(0) | ||
| 3177 | - } else { | ||
| 3178 | - 0 | ||
| 3179 | - }; | ||
| 3180 | - let avg_b_o: f64 = if !sec_diags.is_empty() { | ||
| 3181 | - sec_diags | ||
| 3182 | - .iter() | ||
| 3183 | - .map(|d| d.nb_compressed as f64) | ||
| 3184 | - .sum::<f64>() | ||
| 3185 | - / sec_diags.len() as f64 | ||
| 3186 | - } else { | ||
| 3187 | - 0.0 | ||
| 3188 | - }; | ||
| 3189 | - let ref_f0 = f0.min(ref_payload.len()); | ||
| 3190 | - let ref_f1 = f1.min(ref_payload.len()); | ||
| 3191 | - let avg_b_r: f64 = if ref_f1 > ref_f0 { | ||
| 3192 | - ref_payload[ref_f0..ref_f1] | ||
| 3193 | - .iter() | ||
| 3194 | - .map(|&b| b as f64) | ||
| 3195 | - .sum::<f64>() | ||
| 3196 | - / (ref_f1 - ref_f0) as f64 | ||
| 3197 | - } else { | ||
| 3198 | - 0.0 | ||
| 3199 | - }; | ||
| 3200 | - // tf_changed: count bands where tf_res != 0 (we don't have tf_res in diag, | ||
| 3201 | - // but is_transient tells us if short blocks were used) | ||
| 3202 | - let trans_n = sec_diags.iter().filter(|d| d.is_transient).count(); | ||
| 3203 | - out_str.push_str(&format!( | ||
| 3204 | - "{}\t{:.4}\t{:.4}\t{:+.4}\t{:.1}\t{}\t{}\t{:.0}\t{:.0}\t-\t{}\n", | ||
| 3205 | - s, co, cr, g, avg_trim, dual_n, int_typ, avg_b_o, avg_b_r, trans_n | ||
| 3206 | - )); | ||
| 3207 | - } | ||
| 3208 | - | ||
| 3209 | - // Top 10 worst seconds with per-frame diag | ||
| 3210 | - out_str.push_str("\n# --- 10 worst seconds by gap (per-frame diag) ---\n"); | ||
| 3211 | - out_str.push_str("# frame\tt_ms\tB_ours\tB_ref\ttrans\tshort\tintra\tsil\tlm\tstart\tbands\tint\tdual\ttrim\treservoir\tpulses[0..5]\tfine[0..5]\n"); | ||
| 3212 | - for &(s, _co, _cr, g) in sorted.iter().take(10) { | ||
| 3213 | - let f0 = s * frames_per_sec; | ||
| 3214 | - let f1 = ((s + 1) * frames_per_sec).min(diags.len()); | ||
| 3215 | - out_str.push_str(&format!("# second {} gap={:+.4}\n", s, g)); | ||
| 3216 | - // Index loop kept: the index also drives other lookups or parallel arrays. | ||
| 3217 | - #[allow(clippy::needless_range_loop)] | ||
| 3218 | - for fi in f0..f1.min(diags.len()) { | ||
| 3219 | - let d = &diags[fi]; | ||
| 3220 | - let b_ref = ref_payload.get(fi).copied().unwrap_or(0); | ||
| 3221 | - let p5: Vec<String> = (0..5).map(|i| format!("{}", d.pulses[i])).collect(); | ||
| 3222 | - let f5: Vec<String> = (0..5).map(|i| format!("{}", d.fine_quant[i])).collect(); | ||
| 3223 | - out_str.push_str(&format!( | ||
| 3224 | - "{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n", | ||
| 3225 | - fi, | ||
| 3226 | - fi * 20, | ||
| 3227 | - d.nb_compressed, | ||
| 3228 | - b_ref, | ||
| 3229 | - d.is_transient as u8, | ||
| 3230 | - d.short_blocks, | ||
| 3231 | - d.intra as u8, | ||
| 3232 | - d.silence as u8, | ||
| 3233 | - d.lm, | ||
| 3234 | - d.start, | ||
| 3235 | - d.coded_bands, | ||
| 3236 | - d.intensity, | ||
| 3237 | - d.dual_stereo as u8, | ||
| 3238 | - d.alloc_trim, | ||
| 3239 | - d.vbr_reservoir, | ||
| 3240 | - p5.join(","), | ||
| 3241 | - f5.join(",") | ||
| 3242 | - )); | ||
| 3243 | - } | ||
| 3244 | - out_str.push('\n'); | ||
| 3245 | - } | ||
| 3246 | - | ||
| 3247 | - // Global stats | ||
| 3248 | - out_str.push_str("# --- global stats ---\n"); | ||
| 3249 | - let trim_hist: Vec<(i32, usize)> = { | ||
| 3250 | - let mut h = std::collections::HashMap::new(); | ||
| 3251 | - for d in &diags { | ||
| 3252 | - *h.entry(d.alloc_trim).or_insert(0) += 1; | ||
| 3253 | - } | ||
| 3254 | - let mut v: Vec<_> = h.into_iter().collect(); | ||
| 3255 | - v.sort(); | ||
| 3256 | - v | ||
| 3257 | - }; | ||
| 3258 | - out_str.push_str(&format!("# alloc_trim histogram: {:?}\n", trim_hist)); | ||
| 3259 | - let dual_count = diags.iter().filter(|d| d.dual_stereo).count(); | ||
| 3260 | - out_str.push_str(&format!( | ||
| 3261 | - "# dual_stereo frames: {}/{}\n", | ||
| 3262 | - dual_count, | ||
| 3263 | - diags.len() | ||
| 3264 | - )); | ||
| 3265 | - let trans_count = diags.iter().filter(|d| d.is_transient).count(); | ||
| 3266 | - out_str.push_str(&format!( | ||
| 3267 | - "# transient frames: {}/{}\n", | ||
| 3268 | - trans_count, | ||
| 3269 | - diags.len() | ||
| 3270 | - )); | ||
| 3271 | - let intensity_hist: Vec<(usize, usize)> = { | ||
| 3272 | - let mut h = std::collections::HashMap::new(); | ||
| 3273 | - for d in &diags { | ||
| 3274 | - *h.entry(d.intensity).or_insert(0) += 1; | ||
| 3275 | - } | ||
| 3276 | - let mut v: Vec<_> = h.into_iter().collect(); | ||
| 3277 | - v.sort(); | ||
| 3278 | - v | ||
| 3279 | - }; | ||
| 3280 | - out_str.push_str(&format!("# intensity histogram: {:?}\n", intensity_hist)); | ||
| 3281 | - let avg_b_ours: f64 = | ||
| 3282 | - diags.iter().map(|d| d.nb_compressed as f64).sum::<f64>() / diags.len() as f64; | ||
| 3283 | - let avg_b_ref: f64 = | ||
| 3284 | - ref_payload.iter().map(|&b| b as f64).sum::<f64>() / ref_payload.len() as f64; | ||
| 3285 | - out_str.push_str(&format!( | ||
| 3286 | - "# avg bytes/frame: ours={:.1} ref={:.1}\n", | ||
| 3287 | - avg_b_ours, avg_b_ref | ||
| 3288 | - )); | ||
| 3289 | - let ours_kbps = ours_bytes.iter().map(|&b| b as f64).sum::<f64>() * 8.0 / seconds / 1000.0; | ||
| 3290 | - let ref_kbps = ref_payload.iter().map(|&b| b as f64).sum::<f64>() * 8.0 / seconds / 1000.0; | ||
| 3291 | - out_str.push_str(&format!( | ||
| 3292 | - "# realised kbps: ours={:.1} ref={:.1}\n", | ||
| 3293 | - ours_kbps, ref_kbps | ||
| 3294 | - )); | ||
| 3295 | - | ||
| 3296 | - let out_path = lanes_dir.join("opus-64-r1.seconds.txt"); | ||
| 3297 | - fs::write(&out_path, out_str).unwrap(); | ||
| 3298 | - println!("wrote {}", out_path.display()); | ||
| 3299 | -} | ||
| 3300 | #[test] | 3030 | #[test] |
| 3301 | #[ignore = "library gate: hand-run 14-row sweep, 120s per source, needs ffmpeg libopus and the local ~/Music corpus (~12 min); the reelm@64k dropout that first failed it is fixed per lanes/opus-drop-r2.report.md, so only the corpus dependency keeps it out of the default suite"] | 3031 | #[ignore = "library gate: hand-run 14-row sweep, 120s per source, needs ffmpeg libopus and the local ~/Music corpus (~12 min); the reelm@64k dropout that first failed it is fixed per lanes/opus-drop-r2.report.md, so only the corpus dependency keeps it out of the default suite"] |
| 3302 | fn encoder_library_gate_vs_libopus() { | 3032 | fn encoder_library_gate_vs_libopus() { |
| @@ -4672,458 +4402,12 @@ fn opus_compare_err_pinned_against_c() { | |||
| 4672 | ); | 4402 | ); |
| 4673 | } | 4403 | } |
| 4674 | 4404 | ||
| 4675 | -// --------------------------------------------------------------------------- | ||
| 4676 | -// Spectral-divergence diagnostic: WHERE the 96 kbps err_ratio outlier loses | ||
| 4677 | -// its error. Per opus_compare band: mean ln-energy error ours-vs-source and | ||
| 4678 | -// ref-vs-source, plus the band's share of the frame error; per source: the | ||
| 4679 | -// top-5 worst seconds with what the encoder did there (CeltFrameDiag). | ||
| 4680 | -// Run: SWEEP_ONLY=reell,dl8a cargo test -p ec-opus --release \ | ||
| 4681 | -// spectral_divergence_vs_libopus -- --ignored --nocapture | ||
| 4682 | -// Writes lanes/opus-reell-r1.bands.txt. | ||
| 4683 | -// --------------------------------------------------------------------------- | ||
| 4684 | - | ||
| 4685 | /// libopus CELT band edges (copy of `celt.rs::E_BANDS`, which is pub(crate)): | 4405 | /// libopus CELT band edges (copy of `celt.rs::E_BANDS`, which is pub(crate)): |
| 4686 | /// band `i` ends at `CELT_EBANDS[i] * 240` Hz at 48 kHz. | 4406 | /// band `i` ends at `CELT_EBANDS[i] * 240` Hz at 48 kHz. |
| 4687 | const CELT_EBANDS: [usize; NBANDS + 1] = [ | 4407 | const CELT_EBANDS: [usize; NBANDS + 1] = [ |
| 4688 | 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 34, 40, 48, 60, 78, 100, | 4408 | 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 34, 40, 48, 60, 78, 100, |
| 4689 | ]; | 4409 | ]; |
| 4690 | 4410 | ||
| 4691 | -#[test] | ||
| 4692 | -#[ignore = "probe: per-window CELT band divergence sweep over the local corpus; a multi-minute ffmpeg report run, not a suite gate"] | ||
| 4693 | -fn spectral_divergence_vs_libopus() { | ||
| 4694 | - let _timing = timing_shared(); | ||
| 4695 | - const SECS: f64 = 120.0; | ||
| 4696 | - const FRAME: usize = 960; | ||
| 4697 | - const CHANNELS: usize = 2; | ||
| 4698 | - const MAX_LAG: usize = 2000; | ||
| 4699 | - let kbps_env: u32 = std::env::var("SWEEP_KBPS") | ||
| 4700 | - .ok() | ||
| 4701 | - .and_then(|v| v.parse().ok()) | ||
| 4702 | - .unwrap_or(96); | ||
| 4703 | - #[allow(non_snake_case)] | ||
| 4704 | - let KBPS: u32 = kbps_env; | ||
| 4705 | - | ||
| 4706 | - let all: &[(&str, &str)] = &[ | ||
| 4707 | - ("reell", "~/Music/reell.mp4"), | ||
| 4708 | - ("reelo", "~/Music/reelo.mp3"), | ||
| 4709 | - ("nik", "~/Music/reeln.mp4"), | ||
| 4710 | - ("dl8a", "~/Downloads/8a3b6d1d19.mp3"), | ||
| 4711 | - ("her", "~/Music/reeli.mp3"), | ||
| 4712 | - ("reelm", "~/Music/reelm.wav"), | ||
| 4713 | - ("hein", "~/Downloads/reelm.mp3"), | ||
| 4714 | - ]; | ||
| 4715 | - let only: Vec<String> = std::env::var("SWEEP_ONLY") | ||
| 4716 | - .unwrap_or_else(|_| "reell,dl8a".to_owned()) | ||
| 4717 | - .split(',') | ||
| 4718 | - .filter(|s| !s.is_empty()) | ||
| 4719 | - .map(|s| s.trim().to_owned()) | ||
| 4720 | - .collect(); | ||
| 4721 | - let sources: Vec<(String, PathBuf)> = all | ||
| 4722 | - .iter() | ||
| 4723 | - .filter(|(tag, _)| only.iter().any(|o| o == tag)) | ||
| 4724 | - .map(|(tag, p)| (tag.to_string(), shellexpand(p))) | ||
| 4725 | - .collect(); | ||
| 4726 | - assert!(!sources.is_empty(), "SWEEP_ONLY matched no sources"); | ||
| 4727 | - | ||
| 4728 | - let lanes_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../lanes"); | ||
| 4729 | - fs::create_dir_all(&lanes_dir).unwrap(); | ||
| 4730 | - let stem = std::env::var("SWEEP_TAG").unwrap_or_else(|_| "opus-reell-r2".to_owned()); | ||
| 4731 | - let out_path = lanes_dir.join(format!("{stem}.bands.txt")); | ||
| 4732 | - let frames_path = lanes_dir.join(format!("{stem}.frames.txt")); | ||
| 4733 | - let scratch = lanes_dir.join("opus-reell-r1.scratch.ogg"); | ||
| 4734 | - let mut frames_all = String::new(); | ||
| 4735 | - let mut report = String::new(); | ||
| 4736 | - | ||
| 4737 | - for (tag, src) in &sources { | ||
| 4738 | - if !src.exists() { | ||
| 4739 | - eprintln!("SKIP {tag}: missing {}", src.display()); | ||
| 4740 | - continue; | ||
| 4741 | - } | ||
| 4742 | - let source_pcm = ffmpeg_decode_pcm(src, SECS); | ||
| 4743 | - let source_frames = source_pcm.len() / CHANNELS; | ||
| 4744 | - let seconds = source_frames as f64 / 48000.0; | ||
| 4745 | - let source_i16 = to_i16(&source_pcm); | ||
| 4746 | - | ||
| 4747 | - // Reference: ffmpeg libopus at 96k, VBR, decoded by our decoder. | ||
| 4748 | - ffmpeg_encode_libopus(src, KBPS, &scratch, SECS); | ||
| 4749 | - let ref_bytes = fs::metadata(&scratch) | ||
| 4750 | - .map(|m| m.len() as usize) | ||
| 4751 | - .unwrap_or(0); | ||
| 4752 | - let ref_kbps = ref_bytes as f64 * 8.0 / seconds / 1000.0; | ||
| 4753 | - let ref_pkts: Vec<Vec<u8>> = ogg_packets(&fs::read(&scratch).unwrap()) | ||
| 4754 | - .into_iter() | ||
| 4755 | - .skip(2) | ||
| 4756 | - .collect(); | ||
| 4757 | - let (ref_dec, ref_ch) = decode_ogg(&scratch); | ||
| 4758 | - assert_eq!(ref_ch, CHANNELS, "{tag}: ref not stereo"); | ||
| 4759 | - let (_, ref_aligned) = align_to_source(&source_pcm, &ref_dec, CHANNELS, MAX_LAG); | ||
| 4760 | - | ||
| 4761 | - // Ours at the reference's realised rate, per-frame diag captured. | ||
| 4762 | - let mut enc = Encoder::new(48000, CHANNELS, Application::Audio).expect("encoder"); | ||
| 4763 | - enc.set_bitrate((ref_kbps * 1000.0).round() as u32); | ||
| 4764 | - enc.set_vbr_constrained(true); | ||
| 4765 | - let mut dec = Decoder::new(48000, CHANNELS).unwrap(); | ||
| 4766 | - let mut packet = vec![0u8; 1500]; | ||
| 4767 | - let mut dbuf = vec![0.0f32; 5760 * CHANNELS]; | ||
| 4768 | - let mut ours_dec = Vec::new(); | ||
| 4769 | - let mut first_pkts: Vec<Vec<u8>> = Vec::new(); | ||
| 4770 | - let mut diags = Vec::new(); | ||
| 4771 | - let mut ours_bytes = 0usize; | ||
| 4772 | - for block in source_pcm.chunks(FRAME * CHANNELS) { | ||
| 4773 | - let mut padded = block.to_vec(); | ||
| 4774 | - padded.resize(FRAME * CHANNELS, 0.0); | ||
| 4775 | - let len = enc | ||
| 4776 | - .encode_float(&padded, FRAME, &mut packet) | ||
| 4777 | - .expect("encode"); | ||
| 4778 | - if first_pkts.len() < 10 { | ||
| 4779 | - first_pkts.push(packet[..len].to_vec()); | ||
| 4780 | - } | ||
| 4781 | - ours_bytes += len; | ||
| 4782 | - let n = dec.decode_float(&packet[..len], &mut dbuf).expect("decode"); | ||
| 4783 | - ours_dec.extend_from_slice(&dbuf[..n * CHANNELS]); | ||
| 4784 | - diags.push(enc.last_celt_diag().clone()); | ||
| 4785 | - } | ||
| 4786 | - let ours_kbps = ours_bytes as f64 * 8.0 / seconds / 1000.0; | ||
| 4787 | - // Transient-frame counts as the decoder sees them: libopus vs ours. | ||
| 4788 | - let count_transients = |pkts: &[Vec<u8>]| -> (usize, usize) { | ||
| 4789 | - let mut d = Decoder::new(48000, CHANNELS).unwrap(); | ||
| 4790 | - let mut buf = vec![0.0f32; 5760 * CHANNELS]; | ||
| 4791 | - let mut t = 0usize; | ||
| 4792 | - for p in pkts { | ||
| 4793 | - if d.decode_float(p, &mut buf).is_ok() && d.last_celt_diag().transient { | ||
| 4794 | - t += 1; | ||
| 4795 | - } | ||
| 4796 | - } | ||
| 4797 | - (t, pkts.len()) | ||
| 4798 | - }; | ||
| 4799 | - let (ref_tr, ref_n) = count_transients(&ref_pkts); | ||
| 4800 | - let ours_tr = diags.iter().filter(|d| d.is_transient).count(); | ||
| 4801 | - eprintln!( | ||
| 4802 | - "{tag}@{KBPS}k transient frames: ours {ours_tr}/{} ref {ref_tr}/{ref_n}", | ||
| 4803 | - diags.len() | ||
| 4804 | - ); | ||
| 4805 | - let ours_trim: Vec<f32> = ours_dec | ||
| 4806 | - .into_iter() | ||
| 4807 | - .take(source_frames * CHANNELS) | ||
| 4808 | - .collect(); | ||
| 4809 | - let (_, ours_aligned) = align_to_source(&source_pcm, &ours_trim, CHANNELS, MAX_LAG); | ||
| 4810 | - let ours_i16 = to_i16(&ours_aligned); | ||
| 4811 | - let ref_i16 = to_i16(&ref_aligned); | ||
| 4812 | - | ||
| 4813 | - let cmp_frames = (source_i16.len() / CHANNELS) | ||
| 4814 | - .min(ours_i16.len() / CHANNELS) | ||
| 4815 | - .min(ref_i16.len() / CHANNELS); | ||
| 4816 | - let trim = |v: &[i16]| -> Vec<i16> { v[..cmp_frames * CHANNELS].to_vec() }; | ||
| 4817 | - let s_i = trim(&source_i16); | ||
| 4818 | - let o_i = trim(&ours_i16); | ||
| 4819 | - let r_i = trim(&ref_i16); | ||
| 4820 | - | ||
| 4821 | - // Metric totals, per-band shares, per-frame errors. | ||
| 4822 | - let (err_o, eb2_o, ef2_o) = opus_compare_err_parts(&s_i, &o_i, CHANNELS); | ||
| 4823 | - let (err_r, eb2_r, ef2_r) = opus_compare_err_parts(&s_i, &r_i, CHANNELS); | ||
| 4824 | - let corr_o = corr_interleaved(&source_pcm, &ours_aligned, CHANNELS); | ||
| 4825 | - let corr_r = corr_interleaved(&source_pcm, &ref_aligned, CHANNELS); | ||
| 4826 | - | ||
| 4827 | - // Raw per-band energies (no masking): spectral shape in the ln domain. | ||
| 4828 | - let nframes = (cmp_frames - WIN_SIZE + WIN_STEP) / WIN_STEP; | ||
| 4829 | - let as_f64 = |v: &[i16]| -> Vec<f64> { v.iter().map(|&x| x as f64).collect() }; | ||
| 4830 | - let mut bands_s = Vec::new(); | ||
| 4831 | - let mut bands_o = Vec::new(); | ||
| 4832 | - let mut bands_r = Vec::new(); | ||
| 4833 | - let mut scratch_ps = Vec::new(); | ||
| 4834 | - band_energy( | ||
| 4835 | - &as_f64(&s_i), | ||
| 4836 | - CHANNELS, | ||
| 4837 | - nframes, | ||
| 4838 | - &mut Some(&mut bands_s), | ||
| 4839 | - &mut scratch_ps, | ||
| 4840 | - ); | ||
| 4841 | - band_energy( | ||
| 4842 | - &as_f64(&o_i), | ||
| 4843 | - CHANNELS, | ||
| 4844 | - nframes, | ||
| 4845 | - &mut Some(&mut bands_o), | ||
| 4846 | - &mut scratch_ps, | ||
| 4847 | - ); | ||
| 4848 | - band_energy( | ||
| 4849 | - &as_f64(&r_i), | ||
| 4850 | - CHANNELS, | ||
| 4851 | - nframes, | ||
| 4852 | - &mut Some(&mut bands_r), | ||
| 4853 | - &mut scratch_ps, | ||
| 4854 | - ); | ||
| 4855 | - | ||
| 4856 | - report.push_str(&format!( | ||
| 4857 | - "\n# source {tag} @{KBPS}k: ours {ours_kbps:.1} kbps, ref {ref_kbps:.1} kbps; \ | ||
| 4858 | - corr o={corr_o:.4} r={corr_r:.4}; err o={err_o:.3} r={err_r:.3} ratio={:.2}\n", | ||
| 4859 | - err_o / err_r | ||
| 4860 | - )); | ||
| 4861 | - // opus_compare's err is (mean ef²)^(1/16), so one window can carry a | ||
| 4862 | - // whole file. Recompute both sides with the worst k windows dropped | ||
| 4863 | - // (same denominator) to separate a broadband gap from an outlier one. | ||
| 4864 | - let drop_err = |v: &[f64], k: usize| -> f64 { | ||
| 4865 | - let mut w = v.to_vec(); | ||
| 4866 | - w.sort_by(|a, b| b.partial_cmp(a).unwrap()); | ||
| 4867 | - (w[k..].iter().sum::<f64>() / v.len() as f64).powf(1.0 / 16.0) | ||
| 4868 | - }; | ||
| 4869 | - for k in [0usize, 1, 8, ef2_o.len() / 100] { | ||
| 4870 | - let (eo, er) = (drop_err(&ef2_o, k), drop_err(&ef2_r, k)); | ||
| 4871 | - report.push_str(&format!( | ||
| 4872 | - "# drop-{k} worst windows ({} total): err o={eo:.3} r={er:.3} ratio={:.3}\n", | ||
| 4873 | - ef2_o.len(), | ||
| 4874 | - eo / er | ||
| 4875 | - )); | ||
| 4876 | - } | ||
| 4877 | - report.push_str( | ||
| 4878 | - "# dln = mean ln(E_test/E_src) per channel (neg = energy missing); \ | ||
| 4879 | - err = mean |dln|; eb2 = band's mean share of the pre-squared frame error\n", | ||
| 4880 | - ); | ||
| 4881 | - report.push_str( | ||
| 4882 | - "# lo_hz\thi_hz\tdlnL_o\tdlnR_o\tdlnL_r\tdlnR_r\terrL_o\terrR_o\terrL_r\terrR_r\teb2_o\teb2_r\n", | ||
| 4883 | - ); | ||
| 4884 | - for bi in 0..NBANDS { | ||
| 4885 | - let (mut dol, mut dor, mut drl, mut drr) = (0.0f64, 0.0, 0.0, 0.0); | ||
| 4886 | - let (mut aol, mut aor, mut arl, mut arr) = (0.0f64, 0.0, 0.0, 0.0); | ||
| 4887 | - for xi in 0..nframes { | ||
| 4888 | - let e = |b: &Vec<f64>, ci: usize| b[(xi * NBANDS + bi) * CHANNELS + ci].ln(); | ||
| 4889 | - let (sl, sr) = (e(&bands_s, 0), e(&bands_s, 1)); | ||
| 4890 | - let (o_l, o_r) = (e(&bands_o, 0) - sl, e(&bands_o, 1) - sr); | ||
| 4891 | - let (r_l, r_r) = (e(&bands_r, 0) - sl, e(&bands_r, 1) - sr); | ||
| 4892 | - dol += o_l; | ||
| 4893 | - dor += o_r; | ||
| 4894 | - drl += r_l; | ||
| 4895 | - drr += r_r; | ||
| 4896 | - aol += o_l.abs(); | ||
| 4897 | - aor += o_r.abs(); | ||
| 4898 | - arl += r_l.abs(); | ||
| 4899 | - arr += r_r.abs(); | ||
| 4900 | - } | ||
| 4901 | - let n = nframes as f64; | ||
| 4902 | - report.push_str(&format!( | ||
| 4903 | - "{}\t{}\t{:+.3}\t{:+.3}\t{:+.3}\t{:+.3}\t{:.3}\t{:.3}\t{:.3}\t{:.3}\t{:.3e}\t{:.3e}\n", | ||
| 4904 | - BANDS[bi] * 100, | ||
| 4905 | - BANDS[bi + 1] * 100, | ||
| 4906 | - dol / n, | ||
| 4907 | - dor / n, | ||
| 4908 | - drl / n, | ||
| 4909 | - drr / n, | ||
| 4910 | - aol / n, | ||
| 4911 | - aor / n, | ||
| 4912 | - arl / n, | ||
| 4913 | - arr / n, | ||
| 4914 | - eb2_o[bi], | ||
| 4915 | - eb2_r[bi], | ||
| 4916 | - )); | ||
| 4917 | - } | ||
| 4918 | - | ||
| 4919 | - // Top-5 worst seconds by ours per-frame error, with encoder behavior. | ||
| 4920 | - let mframes_per_sec = 48000 / WIN_STEP; // 400 metric frames per second | ||
| 4921 | - let eframes_per_sec = 48000 / FRAME; // 50 encoder frames per second | ||
| 4922 | - let nsecs = cmp_frames / 48000; | ||
| 4923 | - let mut sec_score: Vec<(usize, f64)> = (0..nsecs) | ||
| 4924 | - .map(|s| { | ||
| 4925 | - let (mut sum, mut cnt) = (0.0f64, 0usize); | ||
| 4926 | - for xi in s * mframes_per_sec..(s + 1) * mframes_per_sec { | ||
| 4927 | - if xi < ef2_o.len() { | ||
| 4928 | - sum += ef2_o[xi]; | ||
| 4929 | - cnt += 1; | ||
| 4930 | - } | ||
| 4931 | - } | ||
| 4932 | - (s, sum / cnt.max(1) as f64) | ||
| 4933 | - }) | ||
| 4934 | - .collect(); | ||
| 4935 | - sec_score.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap()); | ||
| 4936 | - report.push_str("# top-5 seconds by ours frame error (mean ef²) with encoder diag:\n"); | ||
| 4937 | - report.push_str( | ||
| 4938 | - "# sec\tscore\ttrans\tcbb_min_hz\tcbb_mean_hz\tint_mean_hz\tdual\tintra\tbits/fr\n", | ||
| 4939 | - ); | ||
| 4940 | - for &(s, score) in &sec_score[..nsecs.min(5)] { | ||
| 4941 | - let f0 = s * eframes_per_sec; | ||
| 4942 | - let f1 = ((s + 1) * eframes_per_sec).min(diags.len()); | ||
| 4943 | - let fr = &diags[f0.min(f1)..f1]; | ||
| 4944 | - let dn = fr.len(); | ||
| 4945 | - if dn == 0 { | ||
| 4946 | - continue; | ||
| 4947 | - } | ||
| 4948 | - let transient = fr.iter().filter(|d| d.is_transient).count(); | ||
| 4949 | - let dual = fr.iter().filter(|d| d.dual_stereo).count(); | ||
| 4950 | - let intra = fr.iter().filter(|d| d.intra).count(); | ||
| 4951 | - let cbb_min = fr.iter().map(|d| d.coded_bands).min().unwrap_or(0); | ||
| 4952 | - let cbb_mean = fr.iter().map(|d| d.coded_bands).sum::<usize>() as f64 / dn as f64; | ||
| 4953 | - let int_mean = fr.iter().map(|d| d.intensity).sum::<usize>() as f64 / dn as f64; | ||
| 4954 | - let bits = fr.iter().map(|d| d.nb_compressed).sum::<usize>() as f64 * 8.0 / dn as f64; | ||
| 4955 | - report.push_str(&format!( | ||
| 4956 | - "{}\t{:.3e}\t{}/{}\t{}\t{}\t{}\t{}/{}\t{}/{}\t{:.0}\n", | ||
| 4957 | - s, | ||
| 4958 | - score, | ||
| 4959 | - transient, | ||
| 4960 | - dn, | ||
| 4961 | - CELT_EBANDS[cbb_min] * 240, | ||
| 4962 | - CELT_EBANDS[cbb_mean as usize] * 240, | ||
| 4963 | - CELT_EBANDS[int_mean as usize] * 240, | ||
| 4964 | - dual, | ||
| 4965 | - dn, | ||
| 4966 | - intra, | ||
| 4967 | - dn, | ||
| 4968 | - bits, | ||
| 4969 | - )); | ||
| 4970 | - } | ||
| 4971 | - | ||
| 4972 | - // Whole-file encoder summary for ours. | ||
| 4973 | - let dn = diags.len(); | ||
| 4974 | - if dn > 0 { | ||
| 4975 | - let transient = diags.iter().filter(|d| d.is_transient).count(); | ||
| 4976 | - let dual = diags.iter().filter(|d| d.dual_stereo).count(); | ||
| 4977 | - let intra = diags.iter().filter(|d| d.intra).count(); | ||
| 4978 | - let cbb_min = diags.iter().map(|d| d.coded_bands).min().unwrap_or(0); | ||
| 4979 | - let cbb_mean = diags.iter().map(|d| d.coded_bands).sum::<usize>() as f64 / dn as f64; | ||
| 4980 | - let int_mean = diags.iter().map(|d| d.intensity).sum::<usize>() as f64 / dn as f64; | ||
| 4981 | - let bits = | ||
| 4982 | - diags.iter().map(|d| d.nb_compressed).sum::<usize>() as f64 * 8.0 / dn as f64; | ||
| 4983 | - report.push_str(&format!( | ||
| 4984 | - "# whole file: transient {}/{} dual {}/{} intra {}/{}; coded_bands min {} mean {} Hz; \ | ||
| 4985 | - intensity mean {} Hz; bits/frame {:.0}\n", | ||
| 4986 | - transient, | ||
| 4987 | - dn, | ||
| 4988 | - dual, | ||
| 4989 | - dn, | ||
| 4990 | - intra, | ||
| 4991 | - dn, | ||
| 4992 | - CELT_EBANDS[cbb_min] * 240, | ||
| 4993 | - CELT_EBANDS[cbb_mean as usize] * 240, | ||
| 4994 | - CELT_EBANDS[int_mean as usize] * 240, | ||
| 4995 | - bits, | ||
| 4996 | - )); | ||
| 4997 | - } | ||
| 4998 | - | ||
| 4999 | - // Top-8 worst single metric windows (ours vs ref), with the encoder | ||
| 5000 | - // frame each window lands in. | ||
| 5001 | - let mut byf: Vec<(usize, f64)> = ef2_o.iter().cloned().enumerate().collect(); | ||
| 5002 | - byf.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap()); | ||
| 5003 | - report | ||
| 5004 | - .push_str("# top-8 metric windows by ours ef²: offset_ms ours ref | enc frame diag\n"); | ||
| 5005 | - for &(xi, v) in &byf[..byf.len().min(8)] { | ||
| 5006 | - let rv = if xi < ef2_r.len() { | ||
| 5007 | - ef2_r[xi] | ||
| 5008 | - } else { | ||
| 5009 | - f64::NAN | ||
| 5010 | - }; | ||
| 5011 | - let ms = xi * WIN_STEP * 1000 / 48000; | ||
| 5012 | - let eidx = xi * WIN_STEP / FRAME; | ||
| 5013 | - let d = diags.get(eidx); | ||
| 5014 | - let ds = d.map(|d| { | ||
| 5015 | - format!( | ||
| 5016 | - "{}:trans{},intra{},sil{},cbb{}Hz,int{}Hz,bt{}", | ||
| 5017 | - eidx, | ||
| 5018 | - d.is_transient as u8, | ||
| 5019 | - d.intra as u8, | ||
| 5020 | - d.silence as u8, | ||
| 5021 | - CELT_EBANDS[d.coded_bands] * 240, | ||
| 5022 | - CELT_EBANDS[d.intensity] * 240, | ||
| 5023 | - d.nb_compressed | ||
| 5024 | - ) | ||
| 5025 | - }); | ||
| 5026 | - report.push_str(&format!( | ||
| 5027 | - "+{}ms\t{:.3e}\t{:.3e}\t{}\n", | ||
| 5028 | - ms, | ||
| 5029 | - v, | ||
| 5030 | - rv, | ||
| 5031 | - ds.as_deref().unwrap_or("-") | ||
| 5032 | - )); | ||
| 5033 | - } | ||
| 5034 | - | ||
| 5035 | - // Startup behavior: first 10 encoder frames. | ||
| 5036 | - report | ||
| 5037 | - .push_str("# first encoder frames: idx trans intra silence cbb_hz int_hz dual bytes\n"); | ||
| 5038 | - for (i, d) in diags.iter().take(10).enumerate() { | ||
| 5039 | - report.push_str(&format!( | ||
| 5040 | - "{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n", | ||
| 5041 | - i, | ||
| 5042 | - d.is_transient as u8, | ||
| 5043 | - d.intra as u8, | ||
| 5044 | - d.silence as u8, | ||
| 5045 | - CELT_EBANDS[d.coded_bands] * 240, | ||
| 5046 | - CELT_EBANDS[d.intensity] * 240, | ||
| 5047 | - d.dual_stereo as u8, | ||
| 5048 | - d.nb_compressed | ||
| 5049 | - )); | ||
| 5050 | - } | ||
| 5051 | - | ||
| 5052 | - // Per-window per-band ln-energies for the metric windows 12..=20 | ||
| 5053 | - // (+120..+200 ms): the leak's shape, band by band. | ||
| 5054 | - report.push_str("# windows 12..=20: win +ms band lo-hi | lnE src/ours/ref, ch L then R\n"); | ||
| 5055 | - // WIN_CENTRE=<window index> recentres the dump on another window. | ||
| 5056 | - let wc: usize = std::env::var("WIN_CENTRE") | ||
| 5057 | - .ok() | ||
| 5058 | - .and_then(|v| v.parse().ok()) | ||
| 5059 | - .unwrap_or(16); | ||
| 5060 | - for xi in wc.saturating_sub(4)..=wc + 4 { | ||
| 5061 | - if xi >= nframes { | ||
| 5062 | - break; | ||
| 5063 | - } | ||
| 5064 | - for bi in 0..NBANDS { | ||
| 5065 | - let e = |b: &Vec<f64>, ci: usize| b[(xi * NBANDS + bi) * CHANNELS + ci].ln(); | ||
| 5066 | - let (sl, sr) = (e(&bands_s, 0), e(&bands_s, 1)); | ||
| 5067 | - let (ol, or_) = (e(&bands_o, 0), e(&bands_o, 1)); | ||
| 5068 | - let (rl, rr) = (e(&bands_r, 0), e(&bands_r, 1)); | ||
| 5069 | - report.push_str(&format!( | ||
| 5070 | - "w{xi} +{}ms b{bi} {}-{}Hz\t{:+8.2} {:+8.2} {:+8.2} | {:+8.2} {:+8.2} {:+8.2}\n", | ||
| 5071 | - xi * WIN_STEP * 1000 / 48000, | ||
| 5072 | - CELT_EBANDS[bi] * 240, | ||
| 5073 | - CELT_EBANDS[bi + 1] * 240, | ||
| 5074 | - sl, | ||
| 5075 | - ol, | ||
| 5076 | - rl, | ||
| 5077 | - sr, | ||
| 5078 | - or_, | ||
| 5079 | - rr, | ||
| 5080 | - )); | ||
| 5081 | - } | ||
| 5082 | - } | ||
| 5083 | - | ||
| 5084 | - // Decode the first 10 packets of each stream with our decoder: does | ||
| 5085 | - // the silence flag survive, and what energies does it leave behind? | ||
| 5086 | - frames_all.push_str(&format!( | ||
| 5087 | - "# {tag}: first 10 packets through our decoder; energies are log2 old_band_e\n" | ||
| 5088 | - )); | ||
| 5089 | - for (label, pkts) in [("ours", &first_pkts), ("ref", &ref_pkts)] { | ||
| 5090 | - let mut d = Decoder::new(48000, CHANNELS).unwrap(); | ||
| 5091 | - let mut ob = vec![0.0f32; 5760 * CHANNELS]; | ||
| 5092 | - for (i, p) in pkts.iter().take(10).enumerate() { | ||
| 5093 | - let _ = d.decode_float(p, &mut ob).expect("decode"); | ||
| 5094 | - let g = d.last_celt_diag(); | ||
| 5095 | - frames_all.push_str(&format!( | ||
| 5096 | - "{label} {i} bytes={} toc={:#04x} sil{} intra{} trans{} bits{}\n", | ||
| 5097 | - p.len(), | ||
| 5098 | - p.first().copied().unwrap_or(0), | ||
| 5099 | - g.silence as u8, | ||
| 5100 | - g.intra as u8, | ||
| 5101 | - g.transient as u8, | ||
| 5102 | - g.total_bits, | ||
| 5103 | - )); | ||
| 5104 | - for (ch, name) in [(0usize, 'L'), (1usize, 'R')] { | ||
| 5105 | - let band = &g.old_band_e | ||
| 5106 | - [ch * ec_opus::celt::NB_BANDS..(ch + 1) * ec_opus::celt::NB_BANDS]; | ||
| 5107 | - let e: Vec<String> = band.iter().map(|v| format!("{v:+6.1}")).collect(); | ||
| 5108 | - frames_all.push_str(&format!(" {name} {}\n", e.join(" "))); | ||
| 5109 | - } | ||
| 5110 | - } | ||
| 5111 | - } | ||
| 5112 | - println!( | ||
| 5113 | - "{tag}@{KBPS}k: err o={err_o:.3} r={err_r:.3} ratio={:.2}", | ||
| 5114 | - err_o / err_r | ||
| 5115 | - ); | ||
| 5116 | - } | ||
| 5117 | - let _ = fs::remove_file(&scratch); | ||
| 5118 | - let header = format!( | ||
| 5119 | - "# spectral divergence vs libopus @ {KBPS}k, {SECS:.0}s cap, sources {}\n", | ||
| 5120 | - only.join(",") | ||
| 5121 | - ); | ||
| 5122 | - fs::write(&out_path, header + &report).unwrap(); | ||
| 5123 | - fs::write(&frames_path, &frames_all).unwrap(); | ||
| 5124 | - println!("wrote {}", out_path.display()); | ||
| 5125 | -} | ||
| 5126 | - | ||
| 5127 | /// Startup leak repro (lane-opus-reell): the first frames of the reell source | 4411 | /// Startup leak repro (lane-opus-reell): the first frames of the reell source |
| 5128 | /// (digital silence then an attack) through the library gate's encoder | 4412 | /// (digital silence then an attack) through the library gate's encoder |
| 5129 | /// settings and our decoder. Prints per-frame CELT facts; fails if the decode | 4413 | /// settings and our decoder. Prints per-frame CELT facts; fails if the decode |
| @@ -5150,15 +4434,14 @@ fn celt_silence_then_attack_decodes_bounded() { | |||
| 5150 | let pcm_i16 = to_i16(slice); | 4434 | let pcm_i16 = to_i16(slice); |
| 5151 | let mut buf = [0u8; 1500]; | 4435 | let mut buf = [0u8; 1500]; |
| 5152 | let n = enc.encode(&pcm_i16, fs, &mut buf).unwrap(); | 4436 | let n = enc.encode(&pcm_i16, fs, &mut buf).unwrap(); |
| 5153 | - let ed = enc.last_celt_diag().clone(); | ||
| 5154 | let mut out = vec![0f32; fs * ch]; | 4437 | let mut out = vec![0f32; fs * ch]; |
| 5155 | let got = dec.decode_float(&buf[..n], &mut out).unwrap(); | 4438 | let got = dec.decode_float(&buf[..n], &mut out).unwrap(); |
| 5156 | let d = dec.last_celt_diag().clone(); | 4439 | let d = dec.last_celt_diag().clone(); |
| 5157 | let peak = out[..got * ch].iter().fold(0f32, |a, &x| a.max(x.abs())); | 4440 | let peak = out[..got * ch].iter().fold(0f32, |a, &x| a.max(x.abs())); |
| 5158 | let emax = d.old_band_e.iter().cloned().fold(f32::MIN, f32::max); | 4441 | let emax = d.old_band_e.iter().cloned().fold(f32::MIN, f32::max); |
| 5159 | println!( | 4442 | println!( |
| 5160 | - "frame {frame}: in_peak {in_peak:.5} bytes {n} enc(sil {} intra {} trans {}) dec(sil {} intra {} trans {} bits {}) bandE max {emax:.2} peak {peak:.5}", | 4443 | + "frame {frame}: in_peak {in_peak:.5} bytes {n} dec(sil {} intra {} trans {} bits {}) bandE max {emax:.2} peak {peak:.5}", |
| 5161 | - ed.silence, ed.intra, ed.is_transient, d.silence, d.intra, d.transient, d.total_bits | 4444 | + d.silence, d.intra, d.transient, d.total_bits |
| 5162 | ); | 4445 | ); |
| 5163 | if peak > 4.0 * in_peak.max(1e-4) { | 4446 | if peak > 4.0 * in_peak.max(1e-4) { |
| 5164 | bad.push(frame); | 4447 | bad.push(frame); |
| @@ -5167,118 +4450,6 @@ fn celt_silence_then_attack_decodes_bounded() { | |||
| 5167 | assert!(bad.is_empty(), "decode peak >4x input in frames {bad:?}"); | 4450 | assert!(bad.is_empty(), "decode peak >4x input in frames {bad:?}"); |
| 5168 | } | 4451 | } |
| 5169 | 4452 | ||
| 5170 | -/// Sample-level view of the reell startup: per-120-sample energy of source, | ||
| 5171 | -/// ours (gate path) and libopus reference around the first attack. | ||
| 5172 | -#[test] | ||
| 5173 | -#[ignore = "probe: HOP_SRC/HOP_MS-driven hop-energy dump around the reell startup attack; returns silently when HOP_SRC is absent, so it can never be a suite gate"] | ||
| 5174 | -fn reell_startup_hop_energies() { | ||
| 5175 | - let _timing = timing_shared(); | ||
| 5176 | - const CH: usize = 2; | ||
| 5177 | - // HOP_SRC / HOP_MS pick another source and window centre (diagnostic). | ||
| 5178 | - let src_s = std::env::var("HOP_SRC").unwrap_or_else(|_| "~/Music/reell.mp4".into()); | ||
| 5179 | - let centre_ms: f64 = std::env::var("HOP_MS") | ||
| 5180 | - .ok() | ||
| 5181 | - .and_then(|v| v.parse().ok()) | ||
| 5182 | - .unwrap_or(42.5); | ||
| 5183 | - let src = shellexpand(&src_s); | ||
| 5184 | - if !src.exists() { | ||
| 5185 | - return; | ||
| 5186 | - } | ||
| 5187 | - let secs = (centre_ms / 1000.0 + 1.0).max(2.0); | ||
| 5188 | - let pcm = ffmpeg_decode_pcm(&src, secs); | ||
| 5189 | - let scratch = std::env::temp_dir().join("ec-opus-reell-startup.opus"); | ||
| 5190 | - let kbps: u32 = std::env::var("HOP_KBPS") | ||
| 5191 | - .ok() | ||
| 5192 | - .and_then(|v| v.parse().ok()) | ||
| 5193 | - .unwrap_or(96); | ||
| 5194 | - ffmpeg_encode_libopus(&src, kbps, &scratch, secs); | ||
| 5195 | - let (ref_dec, _) = decode_ogg(&scratch); | ||
| 5196 | - let (lag_r, ref_al) = align_to_source(&pcm, &ref_dec, CH, 2000); | ||
| 5197 | - let mut enc = Encoder::new(48000, CH, Application::Audio).unwrap(); | ||
| 5198 | - enc.set_bitrate(kbps * 1000); | ||
| 5199 | - enc.set_vbr_constrained(true); | ||
| 5200 | - let mut frames_diag = Vec::new(); | ||
| 5201 | - let mut dec = Decoder::new(48000, CH).unwrap(); | ||
| 5202 | - let mut out = vec![0u8; 1500]; | ||
| 5203 | - let mut buf = vec![0f32; 5760 * CH]; | ||
| 5204 | - let mut ours_dec = Vec::new(); | ||
| 5205 | - for block in pcm.as_chunks::<{ 960 * CH }>().0 { | ||
| 5206 | - let n = enc.encode_float(block, 960, &mut out).unwrap(); | ||
| 5207 | - let m = dec.decode_float(&out[..n], &mut buf).unwrap(); | ||
| 5208 | - ours_dec.extend_from_slice(&buf[..m * CH]); | ||
| 5209 | - let e = enc.last_celt_diag().clone(); | ||
| 5210 | - let d = dec.last_celt_diag().clone(); | ||
| 5211 | - frames_diag.push(( | ||
| 5212 | - n, | ||
| 5213 | - e.is_transient, | ||
| 5214 | - e.intra, | ||
| 5215 | - d.tf_res.clone(), | ||
| 5216 | - d.anti_collapse, | ||
| 5217 | - )); | ||
| 5218 | - } | ||
| 5219 | - let (lag_o, ours_al) = align_to_source(&pcm, &ours_dec, CH, 2000); | ||
| 5220 | - let first = |v: &[f32]| v.iter().position(|x| x.abs() > 1e-4).map(|i| i / CH); | ||
| 5221 | - println!( | ||
| 5222 | - "lag ref {lag_r} ours {lag_o}; first>1e-4: src {:?} ours {:?} ref {:?}", | ||
| 5223 | - first(&pcm), | ||
| 5224 | - first(&ours_al), | ||
| 5225 | - first(&ref_al) | ||
| 5226 | - ); | ||
| 5227 | - let e = |v: &[f32], h: usize| -> f64 { | ||
| 5228 | - let a = (h * 120 * CH).min(v.len()); | ||
| 5229 | - let b = ((h + 1) * 120 * CH).min(v.len()); | ||
| 5230 | - v[a..b].iter().map(|&x| (x as f64) * (x as f64)).sum() | ||
| 5231 | - }; | ||
| 5232 | - let hc = (centre_ms / 2.5) as usize; | ||
| 5233 | - for f in (hc / 8).saturating_sub(1)..=(hc / 8 + 1) { | ||
| 5234 | - if let Some((n, t, i, tf, ac)) = frames_diag.get(f) { | ||
| 5235 | - println!( | ||
| 5236 | - "frame {f} ({:.1} ms): bytes {n} trans {t} intra {i} ac {ac} tf {tf:?}", | ||
| 5237 | - f as f64 * 20.0 | ||
| 5238 | - ); | ||
| 5239 | - } | ||
| 5240 | - } | ||
| 5241 | - println!("hop(ms)\tsrc\tours\tref"); | ||
| 5242 | - for h in hc.saturating_sub(8)..hc + 8 { | ||
| 5243 | - println!( | ||
| 5244 | - "{:.1}\t{:.3e}\t{:.3e}\t{:.3e}", | ||
| 5245 | - h as f64 * 2.5, | ||
| 5246 | - e(&pcm, h), | ||
| 5247 | - e(&ours_al, h), | ||
| 5248 | - e(&ref_al, h) | ||
| 5249 | - ); | ||
| 5250 | - } | ||
| 5251 | -} | ||
| 5252 | - | ||
| 5253 | -/// Where a lone click lands after a CELT-only fullband roundtrip, relative to | ||
| 5254 | -/// the encoder look-ahead (diagnostic for the hybrid alignment tolerance). | ||
| 5255 | -#[test] | ||
| 5256 | -#[ignore = "probe: self-contained, but prints where a synthetic click lands after a CELT-only roundtrip and asserts nothing; unblocks when that offset is turned into a tolerance assert"] | ||
| 5257 | -fn celt_click_peak_offset() { | ||
| 5258 | - let _timing = timing_shared(); | ||
| 5259 | - let mut click = vec![0f32; 48000]; | ||
| 5260 | - let at = 960 * 10 + 300; | ||
| 5261 | - click[at] = 0.9; | ||
| 5262 | - for bps in [32_000u32, 64_000, 128_000] { | ||
| 5263 | - let mut enc = Encoder::new(48000, 1, Application::Audio).unwrap(); | ||
| 5264 | - enc.set_mode(Some(ec_opus::Mode::Celt)); | ||
| 5265 | - enc.set_bitrate(bps); | ||
| 5266 | - let (dec, _) = roundtrip_own(&mut enc, &click, 1, 960); | ||
| 5267 | - let p = dec | ||
| 5268 | - .iter() | ||
| 5269 | - .enumerate() | ||
| 5270 | - .max_by(|a, b| a.1.abs().partial_cmp(&b.1.abs()).unwrap()) | ||
| 5271 | - .unwrap() | ||
| 5272 | - .0; | ||
| 5273 | - let d = enc.last_celt_diag().clone(); | ||
| 5274 | - println!( | ||
| 5275 | - "celt click {bps}: peak +{} (lm {})", | ||
| 5276 | - p as i64 - at as i64, | ||
| 5277 | - d.lm | ||
| 5278 | - ); | ||
| 5279 | - } | ||
| 5280 | -} | ||
| 5281 | - | ||
| 5282 | /// Per-frame allocation diagnostics for SHORT-block (transient) frames at a | 4453 | /// Per-frame allocation diagnostics for SHORT-block (transient) frames at a |
| 5283 | /// fixed bitrate: decodes both our stream and libopus's with our decoder, then | 4454 | /// fixed bitrate: decodes both our stream and libopus's with our decoder, then |
| 5284 | /// prints per-band mean pulses, fine_quant, alloc_trim, coded_bands, intensity, | 4455 | /// prints per-band mean pulses, fine_quant, alloc_trim, coded_bands, intensity, |
| @@ -5568,258 +4739,6 @@ fn short_block_bits_vs_libopus() { | |||
| 5568 | // the same analysis for any row of the library gate, not just her@96. | 4739 | // the same analysis for any row of the library gate, not just her@96. |
| 5569 | // --------------------------------------------------------------------------- | 4740 | // --------------------------------------------------------------------------- |
| 5570 | 4741 | ||
| 5571 | -#[test] | ||
| 5572 | -#[ignore = "probe: EC_ERRMAP_SRC-driven per-window error map; returns silently when the named source is missing, so it can never be a suite gate"] | ||
| 5573 | -fn err_map_vs_libopus() { | ||
| 5574 | - let _timing = timing_shared(); | ||
| 5575 | - const SECS: f64 = 120.0; | ||
| 5576 | - const FRAME: usize = 960; | ||
| 5577 | - const CH: usize = 2; | ||
| 5578 | - const HOP: usize = 120; // WIN_STEP: one opus_compare hop = 2.5 ms | ||
| 5579 | - const HOPS_PER_WIN: usize = 48_000 / HOP; // 1 s window = 400 hops | ||
| 5580 | - let kbps_env: u32 = std::env::var("EC_ERRMAP_KBPS") | ||
| 5581 | - .or_else(|_| std::env::var("HER_KBPS")) | ||
| 5582 | - .ok() | ||
| 5583 | - .and_then(|v| v.parse().ok()) | ||
| 5584 | - .unwrap_or(96); | ||
| 5585 | - let tag = std::env::var("EC_ERRMAP_TAG").unwrap_or_else(|_| "opus-her-r1".to_string()); | ||
| 5586 | - | ||
| 5587 | - let src = shellexpand( | ||
| 5588 | - &std::env::var("EC_ERRMAP_SRC").unwrap_or_else(|_| "~/Music/reeli.mp3".to_string()), | ||
| 5589 | - ); | ||
| 5590 | - if !src.exists() { | ||
| 5591 | - eprintln!("SKIP: missing {}", src.display()); | ||
| 5592 | - return; | ||
| 5593 | - } | ||
| 5594 | - let lanes_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../lanes"); | ||
| 5595 | - fs::create_dir_all(&lanes_dir).unwrap(); | ||
| 5596 | - let scratch = lanes_dir.join(format!("{tag}.scratch.ogg")); | ||
| 5597 | - let out_path = lanes_dir.join(format!("{tag}.map.txt")); | ||
| 5598 | - | ||
| 5599 | - let source_pcm = ffmpeg_decode_pcm(&src, SECS); | ||
| 5600 | - let source_frames = source_pcm.len() / CH; | ||
| 5601 | - let seconds = source_frames as f64 / 48000.0; | ||
| 5602 | - let source_i16 = to_i16(&source_pcm); | ||
| 5603 | - | ||
| 5604 | - // Reference: ffmpeg libopus, VBR — the gate's path. | ||
| 5605 | - ffmpeg_encode_libopus(&src, kbps_env, &scratch, SECS); | ||
| 5606 | - let ref_bytes = fs::metadata(&scratch) | ||
| 5607 | - .map(|m| m.len() as usize) | ||
| 5608 | - .unwrap_or(0); | ||
| 5609 | - let ref_kbps = ref_bytes as f64 * 8.0 / seconds / 1000.0; | ||
| 5610 | - let (ref_dec, ref_ch) = decode_ogg(&scratch); | ||
| 5611 | - assert_eq!(ref_ch, CH, "ref not stereo"); | ||
| 5612 | - let (_, ref_aligned) = align_to_source(&source_pcm, &ref_dec, CH, 2000); | ||
| 5613 | - | ||
| 5614 | - // Ref per-packet decoder diag, tagged with its first source sample. | ||
| 5615 | - struct FD { | ||
| 5616 | - sample: usize, | ||
| 5617 | - enc: Option<ec_opus::celt_enc::CeltFrameDiag>, | ||
| 5618 | - dec: ec_opus::celt::CeltDecDiag, | ||
| 5619 | - } | ||
| 5620 | - let ref_pkts: Vec<Vec<u8>> = ogg_packets(&fs::read(&scratch).unwrap()) | ||
| 5621 | - .into_iter() | ||
| 5622 | - .skip(2) | ||
| 5623 | - .collect(); | ||
| 5624 | - let mut ref_fd: Vec<FD> = Vec::new(); | ||
| 5625 | - { | ||
| 5626 | - let mut d = Decoder::new(48000, CH).unwrap(); | ||
| 5627 | - let mut buf = vec![0f32; 5760 * CH]; | ||
| 5628 | - let mut at = 0usize; | ||
| 5629 | - for p in &ref_pkts { | ||
| 5630 | - if p.is_empty() { | ||
| 5631 | - continue; | ||
| 5632 | - } | ||
| 5633 | - let toc = ec_opus::Toc::new(p[0]); | ||
| 5634 | - let got = d.decode_float(p, &mut buf).unwrap_or(0); | ||
| 5635 | - if toc.mode() != Mode::Silk { | ||
| 5636 | - ref_fd.push(FD { | ||
| 5637 | - sample: at, | ||
| 5638 | - enc: None, | ||
| 5639 | - dec: d.last_celt_diag().clone(), | ||
| 5640 | - }); | ||
| 5641 | - } | ||
| 5642 | - at += got; | ||
| 5643 | - } | ||
| 5644 | - } | ||
| 5645 | - | ||
| 5646 | - // Ours at the reference's realised rate (gate path), with per-frame diags. | ||
| 5647 | - let mut enc = Encoder::new(48000, CH, Application::Audio).expect("encoder"); | ||
| 5648 | - enc.set_bitrate((ref_kbps * 1000.0).round() as u32); | ||
| 5649 | - enc.set_vbr_constrained(true); | ||
| 5650 | - let mut dec = Decoder::new(48000, CH).unwrap(); | ||
| 5651 | - let mut pkt = vec![0u8; 1500]; | ||
| 5652 | - let mut dbuf = vec![0f32; 5760 * CH]; | ||
| 5653 | - let mut ours_dec = Vec::new(); | ||
| 5654 | - let mut ours_bytes = 0usize; | ||
| 5655 | - let mut ours_fd: Vec<FD> = Vec::new(); | ||
| 5656 | - for (fi, block) in source_pcm.chunks(FRAME * CH).enumerate() { | ||
| 5657 | - let mut padded = block.to_vec(); | ||
| 5658 | - padded.resize(FRAME * CH, 0.0); | ||
| 5659 | - let n = enc.encode_float(&padded, FRAME, &mut pkt).unwrap(); | ||
| 5660 | - ours_bytes += n; | ||
| 5661 | - let m = dec.decode_float(&pkt[..n], &mut dbuf).unwrap(); | ||
| 5662 | - ours_dec.extend_from_slice(&dbuf[..m * CH]); | ||
| 5663 | - ours_fd.push(FD { | ||
| 5664 | - sample: fi * FRAME, | ||
| 5665 | - enc: Some(enc.last_celt_diag().clone()), | ||
| 5666 | - dec: dec.last_celt_diag().clone(), | ||
| 5667 | - }); | ||
| 5668 | - } | ||
| 5669 | - let (_, ours_aligned) = align_to_source(&source_pcm, &ours_dec, CH, 2000); | ||
| 5670 | - let ours_i16 = to_i16(&ours_aligned); | ||
| 5671 | - let ref_i16 = to_i16(&ref_aligned); | ||
| 5672 | - let ours_kbps = ours_bytes as f64 * 8.0 / seconds / 1000.0; | ||
| 5673 | - | ||
| 5674 | - // Per-hop ef² for both encoders (gate numerics). | ||
| 5675 | - let cmp_frames = (source_i16.len() / CH) | ||
| 5676 | - .min(ours_i16.len() / CH) | ||
| 5677 | - .min(ref_i16.len() / CH); | ||
| 5678 | - let trim = |v: &[i16]| -> Vec<i16> { v[..cmp_frames * CH].to_vec() }; | ||
| 5679 | - let (err_o, _, hop_o) = opus_compare_err_parts(&trim(&source_i16), &trim(&ours_i16), CH); | ||
| 5680 | - let (err_r, _, hop_r) = opus_compare_err_parts(&trim(&source_i16), &trim(&ref_i16), CH); | ||
| 5681 | - | ||
| 5682 | - // 1 s windows. | ||
| 5683 | - let nwin = hop_o.len() / HOPS_PER_WIN; | ||
| 5684 | - let sum = |h: &[f64], w: usize| { | ||
| 5685 | - h[w * HOPS_PER_WIN..(w + 1) * HOPS_PER_WIN] | ||
| 5686 | - .iter() | ||
| 5687 | - .sum::<f64>() | ||
| 5688 | - }; | ||
| 5689 | - let tot_o: f64 = hop_o.iter().sum(); | ||
| 5690 | - let tot_r: f64 = hop_r.iter().sum(); | ||
| 5691 | - let mut wins: Vec<(usize, f64, f64, f64)> = (0..nwin) | ||
| 5692 | - .map(|w| (w, sum(&hop_o, w), sum(&hop_r, w), 0.0)) | ||
| 5693 | - .collect(); | ||
| 5694 | - for w in wins.iter_mut() { | ||
| 5695 | - w.3 = w.1 / w.2.max(f64::MIN_POSITIVE); | ||
| 5696 | - } | ||
| 5697 | - let max_share = wins.iter().map(|w| w.1).fold(0.0f64, f64::max); | ||
| 5698 | - | ||
| 5699 | - let mut out = String::new(); | ||
| 5700 | - out.push_str(&format!( | ||
| 5701 | - "# {tag}@{kbps_env}k error map: ref {ref_kbps:.1} ours {ours_kbps:.1} kbps, \ | ||
| 5702 | - err o={err_o:.3} r={err_r:.3} ratio {:.3}, {nwin} s windows\n", | ||
| 5703 | - err_o / err_r | ||
| 5704 | - )); | ||
| 5705 | - out.push_str("# window time = first hop of the 1 s bucket; ratio = ours/ref window ef² sum\n"); | ||
| 5706 | - out.push_str("# ratio table de-noised: windows with ours share < 1e-6·max excluded\n"); | ||
| 5707 | - | ||
| 5708 | - let fmt_fd = |f: &FD| -> String { | ||
| 5709 | - let e = f.enc.as_ref(); | ||
| 5710 | - format!( | ||
| 5711 | - "trans{} intra{} trim{} int{} cb{} dual{} | tf_sum {:+3} tf8 {:?} sp{} ac{} bits{}", | ||
| 5712 | - f.dec.transient as u8, | ||
| 5713 | - f.dec.intra as u8, | ||
| 5714 | - f.dec.alloc_trim, | ||
| 5715 | - f.dec.intensity, | ||
| 5716 | - f.dec.coded_bands, | ||
| 5717 | - f.dec.dual_stereo as u8, | ||
| 5718 | - f.dec.tf_res.iter().sum::<i32>(), | ||
| 5719 | - f.dec.tf_res.iter().take(8).collect::<Vec<_>>(), | ||
| 5720 | - f.dec.spread, | ||
| 5721 | - f.dec.anti_collapse as u8, | ||
| 5722 | - f.dec.total_bits, | ||
| 5723 | - ) + &e | ||
| 5724 | - .map(|e| format!(" | ENC sb{} vbr{}", e.short_blocks, e.vbr_reservoir)) | ||
| 5725 | - .unwrap_or_default() | ||
| 5726 | - }; | ||
| 5727 | - let ref_at = |s: usize| -> Option<&FD> { | ||
| 5728 | - let i = ref_fd.partition_point(|f| f.sample <= s); | ||
| 5729 | - i.checked_sub(1).map(|i| &ref_fd[i]) | ||
| 5730 | - }; | ||
| 5731 | - | ||
| 5732 | - for (label, order) in [ | ||
| 5733 | - ("TOP-10 WINDOWS BY ours/ref RATIO", { | ||
| 5734 | - let mut v: Vec<usize> = (0..nwin) | ||
| 5735 | - .filter(|&w| wins[w].1 >= 1e-6 * max_share) | ||
| 5736 | - .collect(); | ||
| 5737 | - v.sort_by(|&a, &b| wins[b].3.total_cmp(&wins[a].3)); | ||
| 5738 | - v | ||
| 5739 | - }), | ||
| 5740 | - ("TOP-10 WINDOWS BY ours ERROR SHARE", { | ||
| 5741 | - let mut v: Vec<usize> = (0..nwin).collect(); | ||
| 5742 | - v.sort_by(|&a, &b| wins[b].1.total_cmp(&wins[a].1)); | ||
| 5743 | - v | ||
| 5744 | - }), | ||
| 5745 | - ] { | ||
| 5746 | - out.push_str(&format!("\n== {label} ==\n")); | ||
| 5747 | - for w in order.into_iter().take(10) { | ||
| 5748 | - let (wo, wr, ratio) = (wins[w].1, wins[w].2, wins[w].3); | ||
| 5749 | - out.push_str(&format!( | ||
| 5750 | - "t={:5.0}s: ours {:.3e} ({:4.1}% of ours) ref {:.3e} ({:4.1}% of ref) ratio {:.1}\n", | ||
| 5751 | - w as f64, | ||
| 5752 | - wo, | ||
| 5753 | - 100.0 * wo / tot_o, | ||
| 5754 | - wr, | ||
| 5755 | - 100.0 * wr / tot_r, | ||
| 5756 | - ratio, | ||
| 5757 | - )); | ||
| 5758 | - // Worst hop in the window: flags from both encoders. | ||
| 5759 | - let (hw, he) = (w * HOPS_PER_WIN, (w + 1) * HOPS_PER_WIN); | ||
| 5760 | - let hb = hop_o[hw..he] | ||
| 5761 | - .iter() | ||
| 5762 | - .enumerate() | ||
| 5763 | - .max_by(|a, b| a.1.total_cmp(b.1)) | ||
| 5764 | - .map(|(i, v)| (hw + i, *v)) | ||
| 5765 | - .unwrap(); | ||
| 5766 | - let mid = hb.0 * HOP + 240; // centre sample of the hop | ||
| 5767 | - let fi = mid / FRAME; | ||
| 5768 | - out.push_str(&format!( | ||
| 5769 | - " worst hop {:.1} ms (frame {fi}) ours_ef2 {:.3e}\n", | ||
| 5770 | - hb.0 as f64 * 2.5, | ||
| 5771 | - hb.1 | ||
| 5772 | - )); | ||
| 5773 | - if let Some(f) = ours_fd.get(fi) { | ||
| 5774 | - out.push_str(&format!(" OUR {}/{}: {}\n", fi, f.sample, fmt_fd(f))); | ||
| 5775 | - } | ||
| 5776 | - if let Some(f) = ref_at(mid) { | ||
| 5777 | - out.push_str(&format!(" REF @{}: {}\n", f.sample, fmt_fd(f))); | ||
| 5778 | - } | ||
| 5779 | - if let (Some(o), Some(r)) = (ours_fd.get(fi), ref_at(mid)) { | ||
| 5780 | - let d0: Vec<String> = (0..ec_opus::celt::NB_BANDS) | ||
| 5781 | - .map(|b| format!("{:+5.1}", o.dec.old_band_e[b] - r.dec.old_band_e[b])) | ||
| 5782 | - .collect(); | ||
| 5783 | - let d1: Vec<String> = (0..ec_opus::celt::NB_BANDS) | ||
| 5784 | - .map(|b| { | ||
| 5785 | - format!( | ||
| 5786 | - "{:+5.1}", | ||
| 5787 | - o.dec.old_band_e[ec_opus::celt::NB_BANDS + b] | ||
| 5788 | - - r.dec.old_band_e[ec_opus::celt::NB_BANDS + b] | ||
| 5789 | - ) | ||
| 5790 | - }) | ||
| 5791 | - .collect(); | ||
| 5792 | - out.push_str(&format!( | ||
| 5793 | - " Δlog2E L {}\n R {}\n", | ||
| 5794 | - d0.join(" "), | ||
| 5795 | - d1.join(" ") | ||
| 5796 | - )); | ||
| 5797 | - } | ||
| 5798 | - } | ||
| 5799 | - } | ||
| 5800 | - | ||
| 5801 | - // The single worst ours window, frame by frame: where do decisions diverge. | ||
| 5802 | - let worst = (0..nwin) | ||
| 5803 | - .max_by(|&a, &b| wins[a].1.total_cmp(&wins[b].1)) | ||
| 5804 | - .unwrap(); | ||
| 5805 | - out.push_str(&format!( | ||
| 5806 | - "\n== WORST WINDOW t={}..{}s, ALL FRAMES (OUR | REF) ==\n", | ||
| 5807 | - worst, | ||
| 5808 | - worst + 1 | ||
| 5809 | - )); | ||
| 5810 | - for fi in worst * 50..(worst + 1) * 50 { | ||
| 5811 | - let our = ours_fd.get(fi).map(fmt_fd).unwrap_or_else(|| "-".into()); | ||
| 5812 | - let rf = ref_at(fi * FRAME + 480) | ||
| 5813 | - .map(fmt_fd) | ||
| 5814 | - .unwrap_or_else(|| "-".into()); | ||
| 5815 | - out.push_str(&format!("f{fi}: OUR {our}\n REF {rf}\n")); | ||
| 5816 | - } | ||
| 5817 | - | ||
| 5818 | - fs::write(&out_path, &out).unwrap(); | ||
| 5819 | - let _ = fs::remove_file(&scratch); | ||
| 5820 | - println!("wrote {}", out_path.display()); | ||
| 5821 | -} | ||
| 5822 | - | ||
| 5823 | /// Per-frame ours-vs-libopus coded decisions over a window of frames, decoded | 4742 | /// Per-frame ours-vs-libopus coded decisions over a window of frames, decoded |
| 5824 | /// with our own decoder on both sides. FRAME_SRC / FRAME_KBPS / FRAME_FROM / | 4743 | /// with our own decoder on both sides. FRAME_SRC / FRAME_KBPS / FRAME_FROM / |
| 5825 | /// FRAME_TO pick the source, rate and frame range (diagnostic). | 4744 | /// FRAME_TO pick the source, rate and frame range (diagnostic). |
| @@ -5987,136 +4906,6 @@ fn frame_decisions_vs_libopus() { | |||
| 5987 | 4906 | ||
| 5988 | const NB_BANDS_DIAG: usize = ec_opus::celt::NB_BANDS; | 4907 | const NB_BANDS_DIAG: usize = ec_opus::celt::NB_BANDS; |
| 5989 | 4908 | ||
| 5990 | -/// The ported tonality analysis (`crates/ec-opus/src/analysis.rs`) must | ||
| 5991 | -/// actually tell speech from music, since `music_prob` is what libopus's mode | ||
| 5992 | -/// and bandwidth decisions read. Drives the real entry surface | ||
| 5993 | -/// (`Encoder::encode_float`) over 30 s of each gate source and reads the | ||
| 5994 | -/// per-frame value back through [`CeltFrameDiag`]. Speech (hein) must land | ||
| 5995 | -/// clearly below the two music sources (reell, reelo). | ||
| 5996 | -#[test] | ||
| 5997 | -#[ignore = "needs the local library sources; run with --ignored"] | ||
| 5998 | -fn analysis_music_prob_separates_speech_from_music() { | ||
| 5999 | - let _timing = timing_shared(); | ||
| 6000 | - const SECS: f64 = 30.0; | ||
| 6001 | - const FRAME: usize = 960; | ||
| 6002 | - const CHANNELS: usize = 2; | ||
| 6003 | - let sources: &[(&str, &str, bool)] = &[ | ||
| 6004 | - ("hein", "~/Downloads/reelm.mp3", false), | ||
| 6005 | - ("reell", "~/Music/reell.mp4", true), | ||
| 6006 | - ("reelo", "~/Music/reelo.mp3", true), | ||
| 6007 | - ]; | ||
| 6008 | - // Oracle: libopus v1.6 built from source with one fprintf of `analysis_info` | ||
| 6009 | - // after `run_analysis()` in `opus_encode_native`, fed the same 30 s of | ||
| 6010 | - // ffmpeg-decoded f32 at the same settings, 1498-1499 valid windows each. | ||
| 6011 | - // Means of (music_prob, tonality, tonality_slope, activity). | ||
| 6012 | - let oracle = |tag: &str| -> Option<[f64; 4]> { | ||
| 6013 | - match tag { | ||
| 6014 | - "hein" => Some([0.160, 0.155, -0.0876, 0.567]), | ||
| 6015 | - "reell" => Some([0.991, 0.362, -0.1680, 0.701]), | ||
| 6016 | - "reelo" => Some([0.977, 0.313, -0.1333, 0.735]), | ||
| 6017 | - _ => None, | ||
| 6018 | - } | ||
| 6019 | - }; | ||
| 6020 | - let mut means: Vec<(String, bool, f64)> = Vec::new(); | ||
| 6021 | - for (tag, path, is_music) in sources { | ||
| 6022 | - let src = shellexpand(path); | ||
| 6023 | - if !src.exists() { | ||
| 6024 | - eprintln!("SKIP {tag}: missing {}", src.display()); | ||
| 6025 | - continue; | ||
| 6026 | - } | ||
| 6027 | - let pcm = ffmpeg_decode_pcm(&src, SECS); | ||
| 6028 | - let mut enc = Encoder::new(48000, CHANNELS, Application::Audio).expect("encoder"); | ||
| 6029 | - enc.set_bitrate(96_000); | ||
| 6030 | - enc.set_vbr_constrained(true); | ||
| 6031 | - // The analysis is off unless a consumer needs it (it costs ~25% of the | ||
| 6032 | - // encoder); the diagnostics are exactly the "explicitly asked for it" | ||
| 6033 | - // case. | ||
| 6034 | - enc.set_analysis(true); | ||
| 6035 | - let mut out = vec![0u8; 4000]; | ||
| 6036 | - let mut sum = [0.0f64; 4]; | ||
| 6037 | - let mut n = 0usize; | ||
| 6038 | - let mut valid = 0usize; | ||
| 6039 | - // Histogram of the detected bandwidth index, which drives | ||
| 6040 | - // `opus_encoder.c`'s `detected_bandwidth` clamp. | ||
| 6041 | - let mut bw_hist = [0u32; 21]; | ||
| 6042 | - for chunk in pcm.as_chunks::<{ FRAME * CHANNELS }>().0 { | ||
| 6043 | - enc.encode_float(chunk, FRAME, &mut out).expect("encode"); | ||
| 6044 | - let d = enc.last_celt_diag(); | ||
| 6045 | - n += 1; | ||
| 6046 | - if d.analysis_valid { | ||
| 6047 | - valid += 1; | ||
| 6048 | - sum[0] += f64::from(d.music_prob); | ||
| 6049 | - sum[1] += f64::from(d.tonality); | ||
| 6050 | - sum[2] += f64::from(d.tonality_slope); | ||
| 6051 | - sum[3] += f64::from(d.activity); | ||
| 6052 | - bw_hist[(d.analysis_bandwidth.clamp(0, 20)) as usize] += 1; | ||
| 6053 | - } | ||
| 6054 | - } | ||
| 6055 | - assert!( | ||
| 6056 | - valid * 10 > n * 9, | ||
| 6057 | - "{tag}: analysis valid on only {valid}/{n} frames" | ||
| 6058 | - ); | ||
| 6059 | - let bw: Vec<String> = bw_hist | ||
| 6060 | - .iter() | ||
| 6061 | - .enumerate() | ||
| 6062 | - .filter(|&(_, &c)| c > 0) | ||
| 6063 | - .map(|(i, c)| format!("{i}:{c}")) | ||
| 6064 | - .collect(); | ||
| 6065 | - println!("analysis {tag}: bandwidth histogram {}", bw.join(" ")); | ||
| 6066 | - let m = sum.map(|v| v / valid as f64); | ||
| 6067 | - println!( | ||
| 6068 | - "analysis {tag}: music {:.3} tonality {:.3} slope {:.4} activity {:.3} over {valid}/{n} frames (music={is_music})", | ||
| 6069 | - m[0], m[1], m[2], m[3] | ||
| 6070 | - ); | ||
| 6071 | - if let Some(o) = oracle(tag) { | ||
| 6072 | - for (i, name) in ["music_prob", "tonality", "tonality_slope", "activity"] | ||
| 6073 | - .iter() | ||
| 6074 | - .enumerate() | ||
| 6075 | - { | ||
| 6076 | - assert!( | ||
| 6077 | - (m[i] - o[i]).abs() < 0.02, | ||
| 6078 | - "{tag} {name}: ours {:.4} vs libopus {:.4}", | ||
| 6079 | - m[i], | ||
| 6080 | - o[i] | ||
| 6081 | - ); | ||
| 6082 | - } | ||
| 6083 | - } | ||
| 6084 | - means.push(((*tag).to_string(), *is_music, m[0])); | ||
| 6085 | - } | ||
| 6086 | - if means.len() < 2 { | ||
| 6087 | - eprintln!("SKIP: fewer than two sources present"); | ||
| 6088 | - return; | ||
| 6089 | - } | ||
| 6090 | - let speech: Vec<_> = means.iter().filter(|m| !m.1).collect(); | ||
| 6091 | - let music: Vec<_> = means.iter().filter(|m| m.1).collect(); | ||
| 6092 | - for s in &speech { | ||
| 6093 | - assert!( | ||
| 6094 | - s.2 < 0.5, | ||
| 6095 | - "{}: speech music_prob {:.3} should be < 0.5", | ||
| 6096 | - s.0, | ||
| 6097 | - s.2 | ||
| 6098 | - ); | ||
| 6099 | - for m in &music { | ||
| 6100 | - assert!( | ||
| 6101 | - m.2 - s.2 > 0.2, | ||
| 6102 | - "{} ({:.3}) does not separate from {} ({:.3}) by 0.2", | ||
| 6103 | - m.0, | ||
| 6104 | - m.2, | ||
| 6105 | - s.0, | ||
| 6106 | - s.2 | ||
| 6107 | - ); | ||
| 6108 | - } | ||
| 6109 | - } | ||
| 6110 | - for m in &music { | ||
| 6111 | - assert!( | ||
| 6112 | - m.2 > 0.5, | ||
| 6113 | - "{}: music music_prob {:.3} should be > 0.5", | ||
| 6114 | - m.0, | ||
| 6115 | - m.2 | ||
| 6116 | - ); | ||
| 6117 | - } | ||
| 6118 | -} | ||
| 6119 | - | ||
| 6120 | // --------------------------------------------------------------------------- | 4909 | // --------------------------------------------------------------------------- |
| 6121 | // Rate against the target: the CBR default must land within 5% of the bitrate | 4910 | // Rate against the target: the CBR default must land within 5% of the bitrate |
| 6122 | // asked for, on stereo music and speech. | 4911 | // asked for, on stereo music and speech. |