ec-opus: CELT packet loss concealment (Decoder::conceal, empty packet = lost): pitch-periodic LPC extension then decaying band noise, MDCT-overlap recovery; normal decode output unchanged
Browse files at this commit712f5aa33fd4944e1499e7da0dcd48277a9f28c6Parent: 4da3bdf4 changed files +417 -19
- crates/ec-opus/src/celt.rs +283 -11
- crates/ec-opus/src/lib.rs +53 -6
- crates/ec-opus/src/stack_budget.rs +2 -2
- crates/ec-opus/tests/plc.rs +79 -0
crates/ec-opus/src/celt.rsmodified+283 -11
| @@ -42,6 +42,11 @@ const MAX_PERIOD: usize = 1024; | ||
| 42 | 42 | const MIN_PERIOD: usize = 15; |
| 43 | 43 | /// Synthesis history kept per channel. |
| 44 | 44 | const DECODE_BUFFER: usize = 2048; |
| 45 | +const PLC_LPC_ORDER: usize = 24; | |
| 46 | +const PLC_PITCH_MIN: usize = 100; | |
| 47 | +const PLC_PITCH_MAX: usize = 720; | |
| 48 | +const PLC_PERIODIC_LOSSES: usize = 5; | |
| 49 | +const PLC_PERIODIC_DECAY: f32 = 0.32; | |
| 45 | 50 | /// Error text for a stereo or split band without a side channel offset. `y` is set |
| 46 | 51 | /// together with the split flag and never cleared, so a well-formed stream cannot |
| 47 | 52 | /// reach it; a band that does is a decoder defect, reported as corrupt input rather |
| @@ -1317,6 +1322,19 @@ pub struct CeltDecoder { | ||
| 1317 | 1322 | iy: Vec<i32>, |
| 1318 | 1323 | mdct_buf: Vec<f32>, |
| 1319 | 1324 | diag: CeltDecDiag, |
| 1325 | + plc: Plc, | |
| 1326 | +} | |
| 1327 | + | |
| 1328 | +#[derive(Clone, Debug)] | |
| 1329 | +struct Plc { | |
| 1330 | + loss_count: usize, | |
| 1331 | + pitch: usize, | |
| 1332 | + lpc: [[f32; PLC_LPC_ORDER]; 2], | |
| 1333 | + exc: Vec<f32>, | |
| 1334 | + ext: Vec<f32>, | |
| 1335 | + start: usize, | |
| 1336 | + end: usize, | |
| 1337 | + transient: bool, | |
| 1320 | 1338 | } |
| 1321 | 1339 | |
| 1322 | 1340 | impl CeltDecoder { |
| @@ -1359,6 +1377,16 @@ impl CeltDecoder { | ||
| 1359 | 1377 | collapse_masks: [0; 2 * NB_BANDS], |
| 1360 | 1378 | iy: vec![0; max_n], |
| 1361 | 1379 | mdct_buf: vec![0.0; max_n + OVERLAP], |
| 1380 | + plc: Plc { | |
| 1381 | + loss_count: 0, | |
| 1382 | + pitch: PLC_PITCH_MAX, | |
| 1383 | + lpc: [[0.0; PLC_LPC_ORDER]; 2], | |
| 1384 | + exc: vec![0.0; MAX_PERIOD], | |
| 1385 | + ext: vec![0.0; max_n + OVERLAP], | |
| 1386 | + start: 0, | |
| 1387 | + end: NB_BANDS, | |
| 1388 | + transient: false, | |
| 1389 | + }, | |
| 1362 | 1390 | diag: CeltDecDiag { |
| 1363 | 1391 | silence: false, |
| 1364 | 1392 | intra: false, |
| @@ -1403,6 +1431,7 @@ impl CeltDecoder { | ||
| 1403 | 1431 | self.postfilter_tapset = 0; |
| 1404 | 1432 | self.postfilter_tapset_old = 0; |
| 1405 | 1433 | self.rng = 0; |
| 1434 | + self.plc.loss_count = 0; | |
| 1406 | 1435 | } |
| 1407 | 1436 | |
| 1408 | 1437 | /// The range decoder state after the last frame — the test vectors' oracle. |
| @@ -1431,21 +1460,14 @@ impl CeltDecoder { | ||
| 1431 | 1460 | end: usize, |
| 1432 | 1461 | stream_channels: usize, |
| 1433 | 1462 | ) -> Result<()> { |
| 1434 | - let lm = match frame_size { | |
| 1435 | - 120 => 0, | |
| 1436 | - 240 => 1, | |
| 1437 | - 480 => 2, | |
| 1438 | - 960 => 3, | |
| 1439 | - _ => { | |
| 1440 | - return Err(Error::corrupt(format!( | |
| 1441 | - "celt: frame size {frame_size} is not 120, 240, 480 or 960" | |
| 1442 | - ))); | |
| 1443 | - } | |
| 1444 | - }; | |
| 1463 | + let lm = frame_lm(frame_size)?; | |
| 1445 | 1464 | let m = 1usize << lm; |
| 1446 | 1465 | let n = m * SHORT_MDCT; |
| 1447 | 1466 | let cc = self.channels; |
| 1448 | 1467 | let c = stream_channels; |
| 1468 | + self.plc.loss_count = 0; | |
| 1469 | + self.plc.start = start; | |
| 1470 | + self.plc.end = end.min(NB_BANDS); | |
| 1449 | 1471 | let eff_end = end.min(NB_BANDS); |
| 1450 | 1472 | let len = dec.len(); |
| 1451 | 1473 | let total_bits = (len * 8) as i32; |
| @@ -1500,6 +1522,7 @@ impl CeltDecoder { | ||
| 1500 | 1522 | false |
| 1501 | 1523 | }; |
| 1502 | 1524 | let short_blocks = if transient { m } else { 0 }; |
| 1525 | + self.plc.transient = transient; | |
| 1503 | 1526 | |
| 1504 | 1527 | let intra = if tell + 3 <= total_bits { |
| 1505 | 1528 | dec.dec_bit_logp(3) |
| @@ -2699,6 +2722,255 @@ impl CeltDecoder { | ||
| 2699 | 2722 | } |
| 2700 | 2723 | } |
| 2701 | 2724 | |
| 2725 | +fn frame_lm(frame_size: usize) -> Result<usize> { | |
| 2726 | + match frame_size { | |
| 2727 | + 120 => Ok(0), | |
| 2728 | + 240 => Ok(1), | |
| 2729 | + 480 => Ok(2), | |
| 2730 | + 960 => Ok(3), | |
| 2731 | + _ => Err(Error::corrupt(format!( | |
| 2732 | + "celt: frame size {frame_size} is not 120, 240, 480 or 960" | |
| 2733 | + ))), | |
| 2734 | + } | |
| 2735 | +} | |
| 2736 | + | |
| 2737 | +impl CeltDecoder { | |
| 2738 | + /// Packet loss concealment for one lost frame of `frame_size` 48 kHz | |
| 2739 | + /// samples: pitch-periodic LPC extension for the first losses, then | |
| 2740 | + /// band-shaped noise decaying towards the background level. | |
| 2741 | + pub fn conceal(&mut self, out: &mut [f32], frame_size: usize) -> Result<()> { | |
| 2742 | + let lm = frame_lm(frame_size)?; | |
| 2743 | + let n = frame_size; | |
| 2744 | + if self.plc.loss_count < PLC_PERIODIC_LOSSES && self.plc.start == 0 { | |
| 2745 | + if self.plc.loss_count > 0 { | |
| 2746 | + self.decay_energy(PLC_PERIODIC_DECAY); | |
| 2747 | + } | |
| 2748 | + self.conceal_periodic(n); | |
| 2749 | + } else { | |
| 2750 | + let decay = if self.plc.loss_count == 0 { 1.5 } else { 0.5 }; | |
| 2751 | + self.decay_energy(decay); | |
| 2752 | + self.conceal_noise(lm, n); | |
| 2753 | + } | |
| 2754 | + self.postfilter_gain = 0.0; | |
| 2755 | + self.postfilter_gain_old = 0.0; | |
| 2756 | + self.plc.loss_count += 1; | |
| 2757 | + self.deemphasis(out, n, self.channels); | |
| 2758 | + Ok(()) | |
| 2759 | + } | |
| 2760 | + | |
| 2761 | + fn conceal_periodic(&mut self, n: usize) { | |
| 2762 | + if self.plc.loss_count == 0 { | |
| 2763 | + self.plc.pitch = self.plc_pitch_search(); | |
| 2764 | + } | |
| 2765 | + let fade = if self.plc.loss_count == 0 { 1.0 } else { 0.8 }; | |
| 2766 | + let pitch = self.plc.pitch; | |
| 2767 | + let exc_len = (2 * pitch).min(MAX_PERIOD); | |
| 2768 | + let decay_len = exc_len / 2; | |
| 2769 | + let total = n + OVERLAP; | |
| 2770 | + for ch in 0..self.channels { | |
| 2771 | + let base = ch * DECODE_BUFFER; | |
| 2772 | + let hist = &self.decode_mem[base..base + DECODE_BUFFER]; | |
| 2773 | + if self.plc.loss_count == 0 { | |
| 2774 | + self.plc.lpc[ch] = plc_lpc(&hist[DECODE_BUFFER - MAX_PERIOD..], &self.window); | |
| 2775 | + } | |
| 2776 | + let lpc = self.plc.lpc[ch]; | |
| 2777 | + let exc = &mut self.plc.exc; | |
| 2778 | + let h = &hist[DECODE_BUFFER - MAX_PERIOD - PLC_LPC_ORDER..]; | |
| 2779 | + for i in 0..MAX_PERIOD { | |
| 2780 | + let mut s = h[i + PLC_LPC_ORDER]; | |
| 2781 | + for (k, a) in lpc.iter().enumerate() { | |
| 2782 | + s += a * h[i + PLC_LPC_ORDER - 1 - k]; | |
| 2783 | + } | |
| 2784 | + exc[i] = s; | |
| 2785 | + } | |
| 2786 | + let mut e1 = 1.0f32; | |
| 2787 | + let mut e2 = 1.0f32; | |
| 2788 | + for i in 0..decay_len { | |
| 2789 | + e1 += exc[MAX_PERIOD - decay_len + i].powi(2); | |
| 2790 | + e2 += exc[MAX_PERIOD - 2 * decay_len + i].powi(2); | |
| 2791 | + } | |
| 2792 | + let decay = (e1.min(e2) / e2).sqrt(); | |
| 2793 | + let ext = &mut self.plc.ext[..total]; | |
| 2794 | + let mut att = fade * decay; | |
| 2795 | + let mut j = 0; | |
| 2796 | + for v in ext.iter_mut() { | |
| 2797 | + if j >= pitch { | |
| 2798 | + j -= pitch; | |
| 2799 | + att *= decay; | |
| 2800 | + } | |
| 2801 | + *v = att * exc[MAX_PERIOD - pitch + j]; | |
| 2802 | + j += 1; | |
| 2803 | + } | |
| 2804 | + let mut mem = [0.0f32; PLC_LPC_ORDER]; | |
| 2805 | + for (k, m) in mem.iter_mut().enumerate() { | |
| 2806 | + *m = hist[DECODE_BUFFER - 1 - k]; | |
| 2807 | + } | |
| 2808 | + for v in ext.iter_mut() { | |
| 2809 | + let mut y = *v; | |
| 2810 | + for (a, m) in lpc.iter().zip(mem.iter()) { | |
| 2811 | + y -= a * m; | |
| 2812 | + } | |
| 2813 | + mem.copy_within(0..PLC_LPC_ORDER - 1, 1); | |
| 2814 | + mem[0] = y; | |
| 2815 | + *v = y; | |
| 2816 | + } | |
| 2817 | + let s1: f32 = hist[DECODE_BUFFER - total..].iter().map(|v| v * v).sum(); | |
| 2818 | + let s2: f32 = ext.iter().map(|v| v * v).sum(); | |
| 2819 | + if s1.is_nan() || s2.is_nan() || s1 <= 0.2 * s2 { | |
| 2820 | + ext.fill(0.0); | |
| 2821 | + } else if s1 < s2 { | |
| 2822 | + let ratio = ((s1 + 1.0) / (s2 + 1.0)).sqrt(); | |
| 2823 | + for (i, v) in ext.iter_mut().enumerate() { | |
| 2824 | + *v *= if i < OVERLAP { | |
| 2825 | + 1.0 - self.window[i] * (1.0 - ratio) | |
| 2826 | + } else { | |
| 2827 | + ratio | |
| 2828 | + }; | |
| 2829 | + } | |
| 2830 | + } | |
| 2831 | + self.decode_mem | |
| 2832 | + .copy_within(base + n..base + DECODE_BUFFER, base); | |
| 2833 | + self.decode_mem[base + DECODE_BUFFER - n..base + DECODE_BUFFER] | |
| 2834 | + .copy_from_slice(&ext[..n]); | |
| 2835 | + let w = &self.window; | |
| 2836 | + for j in 0..OVERLAP { | |
| 2837 | + let m = OVERLAP - 1 - j; | |
| 2838 | + self.overlap_mem[ch * OVERLAP + j] = w[m] * (w[m] * ext[n + j] + w[j] * ext[n + m]); | |
| 2839 | + } | |
| 2840 | + } | |
| 2841 | + } | |
| 2842 | + | |
| 2843 | + fn decay_energy(&mut self, decay: f32) { | |
| 2844 | + for ch in 0..self.channels { | |
| 2845 | + for i in self.plc.start..self.plc.end { | |
| 2846 | + let k = ch * NB_BANDS + i; | |
| 2847 | + self.old_band_e[k] = self.background_log_e[k].max(self.old_band_e[k] - decay); | |
| 2848 | + } | |
| 2849 | + } | |
| 2850 | + } | |
| 2851 | + | |
| 2852 | + fn conceal_noise(&mut self, lm: usize, n: usize) { | |
| 2853 | + let m = 1usize << lm; | |
| 2854 | + let cc = self.channels; | |
| 2855 | + let (start, end) = (self.plc.start, self.plc.end); | |
| 2856 | + let mut seed = self.rng; | |
| 2857 | + for ch in 0..cc { | |
| 2858 | + let x = &mut self.x[ch * n..(ch + 1) * n]; | |
| 2859 | + x.fill(0.0); | |
| 2860 | + for i in start..end { | |
| 2861 | + let band = &mut x[m * E_BANDS[i]..m * E_BANDS[i + 1]]; | |
| 2862 | + for v in band.iter_mut() { | |
| 2863 | + seed = celt_lcg_rand(seed); | |
| 2864 | + *v = ((seed as i32) >> 20) as f32; | |
| 2865 | + } | |
| 2866 | + renormalise(band, 1.0); | |
| 2867 | + } | |
| 2868 | + for (i, mean) in E_MEANS.iter().enumerate() { | |
| 2869 | + let k = ch * NB_BANDS + i; | |
| 2870 | + self.band_e[k] = if i < start || i >= end { | |
| 2871 | + 0.0 | |
| 2872 | + } else { | |
| 2873 | + (self.old_band_e[k] + mean).min(32.0).exp2() | |
| 2874 | + }; | |
| 2875 | + } | |
| 2876 | + } | |
| 2877 | + self.rng = seed; | |
| 2878 | + self.denormalise_bands(end, cc, m, n); | |
| 2879 | + let bound = (m * E_BANDS[end]).min(n / self.downsample); | |
| 2880 | + for ch in 0..cc { | |
| 2881 | + self.freq[ch * n + bound..(ch + 1) * n].fill(0.0); | |
| 2882 | + let base = ch * DECODE_BUFFER; | |
| 2883 | + self.decode_mem | |
| 2884 | + .copy_within(base + n..base + DECODE_BUFFER, base); | |
| 2885 | + } | |
| 2886 | + let short_blocks = if self.plc.transient { m } else { 0 }; | |
| 2887 | + self.inverse_mdcts(short_blocks, lm, n, cc); | |
| 2888 | + } | |
| 2889 | + | |
| 2890 | + fn plc_pitch_search(&self) -> usize { | |
| 2891 | + let half = DECODE_BUFFER / 2; | |
| 2892 | + let mut x = vec![0.0f32; DECODE_BUFFER]; | |
| 2893 | + for ch in 0..self.channels { | |
| 2894 | + let h = &self.decode_mem[ch * DECODE_BUFFER..(ch + 1) * DECODE_BUFFER]; | |
| 2895 | + for (v, s) in x.iter_mut().zip(h) { | |
| 2896 | + *v += s; | |
| 2897 | + } | |
| 2898 | + } | |
| 2899 | + let d: Vec<f32> = (0..half).map(|i| x[2 * i] + x[2 * i + 1]).collect(); | |
| 2900 | + let score = |sig: &[f32], len: usize, t: usize| { | |
| 2901 | + let end = sig.len(); | |
| 2902 | + let a = &sig[end - len..]; | |
| 2903 | + let b = &sig[end - len - t..end - t]; | |
| 2904 | + let c: f32 = a.iter().zip(b).map(|(p, q)| p * q).sum(); | |
| 2905 | + let e: f32 = b.iter().map(|q| q * q).sum::<f32>() + 1.0; | |
| 2906 | + if c > 0.0 { c * c / e } else { 0.0 } | |
| 2907 | + }; | |
| 2908 | + let mut best = (PLC_PITCH_MAX / 2, 0.0f32); | |
| 2909 | + for t in PLC_PITCH_MIN / 2..=PLC_PITCH_MAX / 2 { | |
| 2910 | + let s = score(&d, MAX_PERIOD / 2, t); | |
| 2911 | + if s > best.1 { | |
| 2912 | + best = (t, s); | |
| 2913 | + } | |
| 2914 | + } | |
| 2915 | + let mut fine = (2 * best.0, 0.0f32); | |
| 2916 | + for t in (2 * best.0 - 2).max(PLC_PITCH_MIN)..=(2 * best.0 + 2).min(PLC_PITCH_MAX) { | |
| 2917 | + let s = score(&x, MAX_PERIOD, t); | |
| 2918 | + if s > fine.1 { | |
| 2919 | + fine = (t, s); | |
| 2920 | + } | |
| 2921 | + } | |
| 2922 | + fine.0 | |
| 2923 | + } | |
| 2924 | +} | |
| 2925 | + | |
| 2926 | +fn plc_lpc(x: &[f32], window: &[f32]) -> [f32; PLC_LPC_ORDER] { | |
| 2927 | + let len = x.len(); | |
| 2928 | + let xw: Vec<f64> = x | |
| 2929 | + .iter() | |
| 2930 | + .enumerate() | |
| 2931 | + .map(|(i, &v)| { | |
| 2932 | + let w = if i < OVERLAP { | |
| 2933 | + window[i] | |
| 2934 | + } else if i >= len - OVERLAP { | |
| 2935 | + window[len - 1 - i] | |
| 2936 | + } else { | |
| 2937 | + 1.0 | |
| 2938 | + }; | |
| 2939 | + v as f64 * w as f64 | |
| 2940 | + }) | |
| 2941 | + .collect(); | |
| 2942 | + let mut ac = [0.0f64; PLC_LPC_ORDER + 1]; | |
| 2943 | + for (k, a) in ac.iter_mut().enumerate() { | |
| 2944 | + *a = xw[k..].iter().zip(&xw).map(|(p, q)| p * q).sum(); | |
| 2945 | + } | |
| 2946 | + ac[0] *= 1.0001; | |
| 2947 | + for (i, a) in ac.iter_mut().enumerate().skip(1) { | |
| 2948 | + *a -= *a * 0.008 * 0.008 * (i * i) as f64; | |
| 2949 | + } | |
| 2950 | + let mut lpc = [0.0f64; PLC_LPC_ORDER]; | |
| 2951 | + let mut error = ac[0]; | |
| 2952 | + if ac[0] > 1e-10 { | |
| 2953 | + for i in 0..PLC_LPC_ORDER { | |
| 2954 | + let mut rr = ac[i + 1]; | |
| 2955 | + for j in 0..i { | |
| 2956 | + rr += lpc[j] * ac[i - j]; | |
| 2957 | + } | |
| 2958 | + let r = -rr / error; | |
| 2959 | + lpc[i] = r; | |
| 2960 | + for j in 0..i.div_ceil(2) { | |
| 2961 | + let (a, b) = (lpc[j], lpc[i - 1 - j]); | |
| 2962 | + lpc[j] = a + r * b; | |
| 2963 | + lpc[i - 1 - j] = b + r * a; | |
| 2964 | + } | |
| 2965 | + error -= r * r * error; | |
| 2966 | + if error <= 0.001 * ac[0] { | |
| 2967 | + break; | |
| 2968 | + } | |
| 2969 | + } | |
| 2970 | + } | |
| 2971 | + lpc.map(|v| v as f32) | |
| 2972 | +} | |
| 2973 | + | |
| 2702 | 2974 | /// `ec_laplace_decode()`: the coarse-energy prediction error. |
| 2703 | 2975 | pub(crate) fn laplace_decode(dec: &mut RangeDecoder, fs0: u32, decay: i32) -> i32 { |
| 2704 | 2976 | const MINP: u32 = 1; |
crates/ec-opus/src/lib.rsmodified+53 -6
| @@ -21,11 +21,11 @@ | ||
| 21 | 21 | //! - **Output is `f32`, interleaved, at the rate you asked for.** 48, 24, 16, |
| 22 | 22 | //! 12 and 8 kHz are supported; SILK's internal rate is resampled up (by the |
| 23 | 23 | //! normative resampler in [`silk`]) and CELT decimates on the way out. |
| 24 | -//! - **There is no packet loss concealment.** A frame of one byte or none — | |
| 25 | -//! a dropped or DTX frame — decodes to silence, where the reference | |
| 26 | -//! extrapolates from the previous frame. This decoder is fed whole packets by | |
| 27 | -//! a container, never a gap, so the concealment would be dead weight; a | |
| 28 | -//! caller that needs it (an RTP receiver) has to add it. | |
| 24 | +//! - **Packet loss concealment is CELT-only.** [`Decoder::conceal`] (or an | |
| 25 | +//! empty packet to [`Decoder::decode_float`]) extends the last CELT frame: | |
| 26 | +//! pitch-periodic LPC extension for the first losses, then decaying | |
| 27 | +//! band-shaped noise. After a SILK or hybrid frame it yields silence, as does | |
| 28 | +//! a one-byte (DTX) frame inside a packet. | |
| 29 | 29 | //! |
| 30 | 30 | //! The crate also carries the family's Opus *encoder* — [`Encoder`] for one |
| 31 | 31 | //! stream, [`MultistreamEncoder`] for surround — CELT-only, fullband, mono |
| @@ -102,7 +102,7 @@ pub struct Decoder { | ||
| 102 | 102 | celt: CeltDecoder, |
| 103 | 103 | /// Boxed because a `SilkDecoder` is 6304 bytes, 83% of what a `Decoder` |
| 104 | 104 | /// costs a caller taking one BY VALUE from `Decoder::new`. It is the |
| 105 | - /// decoder's largest field and its only large one; `celt` is 1168. | |
| 105 | + /// decoder's largest field and its only large one; `celt` is 1448. | |
| 106 | 106 | /// `Stack`: crate::stack_budget. |
| 107 | 107 | silk: Box<SilkDecoder>, |
| 108 | 108 | /// The CELT overlap window, reused for redundancy cross-fades. |
| @@ -114,6 +114,8 @@ pub struct Decoder { | ||
| 114 | 114 | prev_mode: Option<Mode>, |
| 115 | 115 | prev_redundancy: bool, |
| 116 | 116 | range_final: u32, |
| 117 | + /// Samples per channel of the last packet, the default concealment length. | |
| 118 | + last_packet_size: usize, | |
| 117 | 119 | /// Test hook: drop the (CELT, SILK) layer's output before the sum. |
| 118 | 120 | debug_mute: (bool, bool), |
| 119 | 121 | } |
| @@ -172,6 +174,7 @@ impl Decoder { | ||
| 172 | 174 | prev_mode: None, |
| 173 | 175 | prev_redundancy: false, |
| 174 | 176 | range_final: 0, |
| 177 | + last_packet_size: 960 / downsample, | |
| 175 | 178 | debug_mute: (false, false), |
| 176 | 179 | }) |
| 177 | 180 | } |
| @@ -203,10 +206,15 @@ impl Decoder { | ||
| 203 | 206 | } |
| 204 | 207 | |
| 205 | 208 | /// Decodes one packet into interleaved `f32`, returning samples per channel. |
| 209 | + /// An empty `packet` is a lost one: it is concealed for the last packet's | |
| 210 | + /// duration (see [`Decoder::conceal`]). | |
| 206 | 211 | /// |
| 207 | 212 | /// `out` must hold `channels * 120 ms` worth of samples for the general |
| 208 | 213 | /// case (5760 per channel at 48 kHz). |
| 209 | 214 | pub fn decode_float(&mut self, packet: &[u8], out: &mut [f32]) -> Result<usize> { |
| 215 | + if packet.is_empty() { | |
| 216 | + return self.conceal(self.last_packet_size, out); | |
| 217 | + } | |
| 210 | 218 | let (samples, _) = self.decode_impl(packet, out, false)?; |
| 211 | 219 | Ok(samples) |
| 212 | 220 | } |
| @@ -222,6 +230,44 @@ impl Decoder { | ||
| 222 | 230 | self.decode_impl(data, out, true) |
| 223 | 231 | } |
| 224 | 232 | |
| 233 | + /// Conceals `frame_size` lost samples per channel (a multiple of 2.5 ms, | |
| 234 | + /// at most 120 ms), the equivalent of the reference's `decode(NULL)`. | |
| 235 | + /// Consecutive calls decay towards background noise; the next real | |
| 236 | + /// packet cross-fades in through the MDCT overlap. | |
| 237 | + pub fn conceal(&mut self, frame_size: usize, out: &mut [f32]) -> Result<usize> { | |
| 238 | + let total_48k = frame_size * self.downsample; | |
| 239 | + if total_48k == 0 || !total_48k.is_multiple_of(120) || total_48k > 5760 { | |
| 240 | + return Err(Error::corrupt(format!( | |
| 241 | + "opus: conceal size {frame_size} is not a multiple of 2.5 ms up to 120 ms" | |
| 242 | + ))); | |
| 243 | + } | |
| 244 | + let needed = frame_size * self.channels; | |
| 245 | + if out.len() < needed { | |
| 246 | + return Err(Error::corrupt(format!( | |
| 247 | + "opus: output buffer holds {} samples, concealment needs {needed}", | |
| 248 | + out.len() | |
| 249 | + ))); | |
| 250 | + } | |
| 251 | + let mut done_48k = 0usize; | |
| 252 | + while done_48k < total_48k { | |
| 253 | + let left = total_48k - done_48k; | |
| 254 | + let chunk = [960, 480, 240, 120] | |
| 255 | + .into_iter() | |
| 256 | + .find(|&c| c <= left) | |
| 257 | + .unwrap_or(120); | |
| 258 | + let a = done_48k / self.downsample * self.channels; | |
| 259 | + let b = (done_48k + chunk) / self.downsample * self.channels; | |
| 260 | + let dst = &mut out[a..b]; | |
| 261 | + if self.prev_mode == Some(Mode::Celt) { | |
| 262 | + self.celt.conceal(dst, chunk)?; | |
| 263 | + } else { | |
| 264 | + dst.fill(0.0); | |
| 265 | + } | |
| 266 | + done_48k += chunk; | |
| 267 | + } | |
| 268 | + Ok(frame_size) | |
| 269 | + } | |
| 270 | + | |
| 225 | 271 | fn decode_impl( |
| 226 | 272 | &mut self, |
| 227 | 273 | data: &[u8], |
| @@ -247,6 +293,7 @@ impl Decoder { | ||
| 247 | 293 | done += frame_out; |
| 248 | 294 | } |
| 249 | 295 | self.range_final = range; |
| 296 | + self.last_packet_size = done; | |
| 250 | 297 | Ok((done, parsed.consumed)) |
| 251 | 298 | } |
| 252 | 299 |
crates/ec-opus/src/stack_budget.rsmodified+2 -2
| @@ -114,7 +114,7 @@ pub(crate) const BY_VALUE_TYPES: &[(&str, Option<usize>, bool, &str)] = &[ | ||
| 114 | 114 | // -- lib.rs ----------------------------------------------------------- |
| 115 | 115 | ( |
| 116 | 116 | "Decoder", |
| 117 | - Some(1280), | |
| 117 | + Some(1568), | |
| 118 | 118 | true, |
| 119 | 119 | "Decoder::new -> Result<Decoder>. Was 7576, 92.5% of the budget, \ |
| 120 | 120 | because a 6304-byte SilkDecoder sat inline; that field is now a Box", |
| @@ -138,7 +138,7 @@ pub(crate) const BY_VALUE_TYPES: &[(&str, Option<usize>, bool, &str)] = &[ | ||
| 138 | 138 | // -- celt.rs ---------------------------------------------------------- |
| 139 | 139 | ( |
| 140 | 140 | "CeltDecoder", |
| 141 | - Some(1168), | |
| 141 | + Some(1448), | |
| 142 | 142 | true, |
| 143 | 143 | "celt::CeltDecoder::new(channels, downsample) -> Self; also moved by \ |
| 144 | 144 | value into Decoder::celt", |
crates/ec-opus/tests/plc.rsadded+79 -0
| @@ -0,0 +1,79 @@ | ||
| 1 | +use ec_opus::{Application, Decoder, Encoder, Mode}; | |
| 2 | + | |
| 3 | +const FRAME: usize = 960; | |
| 4 | + | |
| 5 | +fn voice(frames: usize) -> Vec<f32> { | |
| 6 | + (0..frames * FRAME) | |
| 7 | + .map(|i| { | |
| 8 | + let t = i as f32 / 48000.0; | |
| 9 | + let f0 = 140.0 + 10.0 * (2.0 * std::f32::consts::PI * 0.7 * t).sin(); | |
| 10 | + (1..12) | |
| 11 | + .map(|h| (2.0 * std::f32::consts::PI * f0 * h as f32 * t).sin() * 0.25 / h as f32) | |
| 12 | + .sum() | |
| 13 | + }) | |
| 14 | + .collect() | |
| 15 | +} | |
| 16 | + | |
| 17 | +fn corr(a: &[f32], b: &[f32]) -> f32 { | |
| 18 | + let ab: f32 = a.iter().zip(b).map(|(x, y)| x * y).sum(); | |
| 19 | + let aa: f32 = a.iter().map(|x| x * x).sum(); | |
| 20 | + let bb: f32 = b.iter().map(|x| x * x).sum(); | |
| 21 | + ab / (aa * bb).sqrt().max(1e-9) | |
| 22 | +} | |
| 23 | + | |
| 24 | +fn rms(a: &[f32]) -> f32 { | |
| 25 | + (a.iter().map(|x| x * x).sum::<f32>() / a.len() as f32).sqrt() | |
| 26 | +} | |
| 27 | + | |
| 28 | +#[test] | |
| 29 | +fn concealment_tracks_and_recovers() { | |
| 30 | + let pcm = voice(60); | |
| 31 | + let mut enc = Encoder::new(48000, 1, Application::Voip).unwrap(); | |
| 32 | + enc.set_bitrate(32000); | |
| 33 | + enc.set_mode(Some(Mode::Celt)); | |
| 34 | + let mut pkt = vec![0u8; 1500]; | |
| 35 | + let packets: Vec<Vec<u8>> = pcm | |
| 36 | + .chunks_exact(FRAME) | |
| 37 | + .map(|f| { | |
| 38 | + let n = enc.encode_float(f, FRAME, &mut pkt).unwrap(); | |
| 39 | + pkt[..n].to_vec() | |
| 40 | + }) | |
| 41 | + .collect(); | |
| 42 | + let lost = [20usize, 40, 41, 42, 43, 44, 45, 46, 47]; | |
| 43 | + let mut clean = Decoder::new(48000, 1).unwrap(); | |
| 44 | + let mut lossy = Decoder::new(48000, 1).unwrap(); | |
| 45 | + let mut buf = vec![0f32; 5760]; | |
| 46 | + let (mut a, mut b) = (Vec::new(), Vec::new()); | |
| 47 | + for (i, p) in packets.iter().enumerate() { | |
| 48 | + let k = clean.decode_float(p, &mut buf).unwrap(); | |
| 49 | + a.extend_from_slice(&buf[..k]); | |
| 50 | + let k = if lost.contains(&i) { | |
| 51 | + lossy.decode_float(&[], &mut buf).unwrap() | |
| 52 | + } else { | |
| 53 | + lossy.decode_float(p, &mut buf).unwrap() | |
| 54 | + }; | |
| 55 | + b.extend_from_slice(&buf[..k]); | |
| 56 | + } | |
| 57 | + let f = |i: usize| i * FRAME..(i + 1) * FRAME; | |
| 58 | + let c20 = corr(&a[f(20)], &b[f(20)]); | |
| 59 | + let r20 = rms(&b[f(20)]) / rms(&a[f(20)]); | |
| 60 | + let c22 = corr(&a[f(22)], &b[f(22)]); | |
| 61 | + let r47 = rms(&b[f(47)]) / rms(&a[f(47)]); | |
| 62 | + let c50 = corr(&a[f(50)], &b[f(50)]); | |
| 63 | + let jump = b | |
| 64 | + .windows(2) | |
| 65 | + .map(|w| (w[1] - w[0]).abs()) | |
| 66 | + .fold(0.0f32, f32::max); | |
| 67 | + let jump_ref = a | |
| 68 | + .windows(2) | |
| 69 | + .map(|w| (w[1] - w[0]).abs()) | |
| 70 | + .fold(0.0f32, f32::max); | |
| 71 | + eprintln!( | |
| 72 | + "c20 {c20:.3} r20 {r20:.3} c22 {c22:.3} r47 {r47:.3} c50 {c50:.3} jump {jump:.4} ref {jump_ref:.4}" | |
| 73 | + ); | |
| 74 | + assert!(c20 > 0.5 && (0.5..1.5).contains(&r20)); | |
| 75 | + assert!(c22 > 0.9); | |
| 76 | + assert!(r47 < 0.5); | |
| 77 | + assert!(c50 > 0.9); | |
| 78 | + assert!(jump < 2.0 * jump_ref); | |
| 79 | +} |