forge
Explore
Log in

Don't you dare go Hollow

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 commit

712f5aa33fd4944e1499e7da0dcd48277a9f28c6Ahmet Kaan GümüşParent: 4da3bdf
crates/ec-opus/src/celt.rsmodified+283 -11
@@ -42,6 +42,11 @@ const MAX_PERIOD: usize = 1024;
4242 const MIN_PERIOD: usize = 15;
4343 /// Synthesis history kept per channel.
4444 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;
4550 /// Error text for a stereo or split band without a side channel offset. `y` is set
4651 /// together with the split flag and never cleared, so a well-formed stream cannot
4752 /// reach it; a band that does is a decoder defect, reported as corrupt input rather
@@ -1317,6 +1322,19 @@ pub struct CeltDecoder {
13171322 iy: Vec<i32>,
13181323 mdct_buf: Vec<f32>,
13191324 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,
13201338 }
13211339
13221340 impl CeltDecoder {
@@ -1359,6 +1377,16 @@ impl CeltDecoder {
13591377 collapse_masks: [0; 2 * NB_BANDS],
13601378 iy: vec![0; max_n],
13611379 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+ },
13621390 diag: CeltDecDiag {
13631391 silence: false,
13641392 intra: false,
@@ -1403,6 +1431,7 @@ impl CeltDecoder {
14031431 self.postfilter_tapset = 0;
14041432 self.postfilter_tapset_old = 0;
14051433 self.rng = 0;
1434+ self.plc.loss_count = 0;
14061435 }
14071436
14081437 /// The range decoder state after the last frame — the test vectors' oracle.
@@ -1431,21 +1460,14 @@ impl CeltDecoder {
14311460 end: usize,
14321461 stream_channels: usize,
14331462 ) -> 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)?;
14451464 let m = 1usize << lm;
14461465 let n = m * SHORT_MDCT;
14471466 let cc = self.channels;
14481467 let c = stream_channels;
1468+ self.plc.loss_count = 0;
1469+ self.plc.start = start;
1470+ self.plc.end = end.min(NB_BANDS);
14491471 let eff_end = end.min(NB_BANDS);
14501472 let len = dec.len();
14511473 let total_bits = (len * 8) as i32;
@@ -1500,6 +1522,7 @@ impl CeltDecoder {
15001522 false
15011523 };
15021524 let short_blocks = if transient { m } else { 0 };
1525+ self.plc.transient = transient;
15031526
15041527 let intra = if tell + 3 <= total_bits {
15051528 dec.dec_bit_logp(3)
@@ -2699,6 +2722,255 @@ impl CeltDecoder {
26992722 }
27002723 }
27012724
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+
27022974 /// `ec_laplace_decode()`: the coarse-energy prediction error.
27032975 pub(crate) fn laplace_decode(dec: &mut RangeDecoder, fs0: u32, decay: i32) -> i32 {
27042976 const MINP: u32 = 1;
crates/ec-opus/src/lib.rsmodified+53 -6
@@ -21,11 +21,11 @@
2121 //! - **Output is `f32`, interleaved, at the rate you asked for.** 48, 24, 16,
2222 //! 12 and 8 kHz are supported; SILK's internal rate is resampled up (by the
2323 //! 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.
2929 //!
3030 //! The crate also carries the family's Opus *encoder* — [`Encoder`] for one
3131 //! stream, [`MultistreamEncoder`] for surround — CELT-only, fullband, mono
@@ -102,7 +102,7 @@ pub struct Decoder {
102102 celt: CeltDecoder,
103103 /// Boxed because a `SilkDecoder` is 6304 bytes, 83% of what a `Decoder`
104104 /// 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.
106106 /// `Stack`: crate::stack_budget.
107107 silk: Box<SilkDecoder>,
108108 /// The CELT overlap window, reused for redundancy cross-fades.
@@ -114,6 +114,8 @@ pub struct Decoder {
114114 prev_mode: Option<Mode>,
115115 prev_redundancy: bool,
116116 range_final: u32,
117+ /// Samples per channel of the last packet, the default concealment length.
118+ last_packet_size: usize,
117119 /// Test hook: drop the (CELT, SILK) layer's output before the sum.
118120 debug_mute: (bool, bool),
119121 }
@@ -172,6 +174,7 @@ impl Decoder {
172174 prev_mode: None,
173175 prev_redundancy: false,
174176 range_final: 0,
177+ last_packet_size: 960 / downsample,
175178 debug_mute: (false, false),
176179 })
177180 }
@@ -203,10 +206,15 @@ impl Decoder {
203206 }
204207
205208 /// 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`]).
206211 ///
207212 /// `out` must hold `channels * 120 ms` worth of samples for the general
208213 /// case (5760 per channel at 48 kHz).
209214 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+ }
210218 let (samples, _) = self.decode_impl(packet, out, false)?;
211219 Ok(samples)
212220 }
@@ -222,6 +230,44 @@ impl Decoder {
222230 self.decode_impl(data, out, true)
223231 }
224232
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+
225271 fn decode_impl(
226272 &mut self,
227273 data: &[u8],
@@ -247,6 +293,7 @@ impl Decoder {
247293 done += frame_out;
248294 }
249295 self.range_final = range;
296+ self.last_packet_size = done;
250297 Ok((done, parsed.consumed))
251298 }
252299
crates/ec-opus/src/stack_budget.rsmodified+2 -2
@@ -114,7 +114,7 @@ pub(crate) const BY_VALUE_TYPES: &[(&str, Option<usize>, bool, &str)] = &[
114114 // -- lib.rs -----------------------------------------------------------
115115 (
116116 "Decoder",
117- Some(1280),
117+ Some(1568),
118118 true,
119119 "Decoder::new -> Result<Decoder>. Was 7576, 92.5% of the budget, \
120120 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)] = &[
138138 // -- celt.rs ----------------------------------------------------------
139139 (
140140 "CeltDecoder",
141- Some(1168),
141+ Some(1448),
142142 true,
143143 "celt::CeltDecoder::new(channels, downsample) -> Self; also moved by \
144144 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+}