From 712f5aa33fd4944e1499e7da0dcd48277a9f28c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Mon, 23 Nov 2026 23:56:09 +0300 Subject: [PATCH] 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 --- crates/ec-opus/src/celt.rs | 294 +++++++++++++++++++++++++++-- crates/ec-opus/src/lib.rs | 59 +++++- crates/ec-opus/src/stack_budget.rs | 4 +- crates/ec-opus/tests/plc.rs | 79 ++++++++ 4 files changed, 417 insertions(+), 19 deletions(-) create mode 100644 crates/ec-opus/tests/plc.rs diff --git a/crates/ec-opus/src/celt.rs b/crates/ec-opus/src/celt.rs index 497ed54d..bc968faf 100644 --- a/crates/ec-opus/src/celt.rs +++ b/crates/ec-opus/src/celt.rs @@ -42,6 +42,11 @@ const MAX_PERIOD: usize = 1024; const MIN_PERIOD: usize = 15; /// Synthesis history kept per channel. const DECODE_BUFFER: usize = 2048; +const PLC_LPC_ORDER: usize = 24; +const PLC_PITCH_MIN: usize = 100; +const PLC_PITCH_MAX: usize = 720; +const PLC_PERIODIC_LOSSES: usize = 5; +const PLC_PERIODIC_DECAY: f32 = 0.32; /// Error text for a stereo or split band without a side channel offset. `y` is set /// together with the split flag and never cleared, so a well-formed stream cannot /// reach it; a band that does is a decoder defect, reported as corrupt input rather @@ -1317,6 +1322,19 @@ pub struct CeltDecoder { iy: Vec, mdct_buf: Vec, diag: CeltDecDiag, + plc: Plc, +} + +#[derive(Clone, Debug)] +struct Plc { + loss_count: usize, + pitch: usize, + lpc: [[f32; PLC_LPC_ORDER]; 2], + exc: Vec, + ext: Vec, + start: usize, + end: usize, + transient: bool, } impl CeltDecoder { @@ -1359,6 +1377,16 @@ impl CeltDecoder { collapse_masks: [0; 2 * NB_BANDS], iy: vec![0; max_n], mdct_buf: vec![0.0; max_n + OVERLAP], + plc: Plc { + loss_count: 0, + pitch: PLC_PITCH_MAX, + lpc: [[0.0; PLC_LPC_ORDER]; 2], + exc: vec![0.0; MAX_PERIOD], + ext: vec![0.0; max_n + OVERLAP], + start: 0, + end: NB_BANDS, + transient: false, + }, diag: CeltDecDiag { silence: false, intra: false, @@ -1403,6 +1431,7 @@ impl CeltDecoder { self.postfilter_tapset = 0; self.postfilter_tapset_old = 0; self.rng = 0; + self.plc.loss_count = 0; } /// The range decoder state after the last frame — the test vectors' oracle. @@ -1431,21 +1460,14 @@ impl CeltDecoder { end: usize, stream_channels: usize, ) -> Result<()> { - let lm = match frame_size { - 120 => 0, - 240 => 1, - 480 => 2, - 960 => 3, - _ => { - return Err(Error::corrupt(format!( - "celt: frame size {frame_size} is not 120, 240, 480 or 960" - ))); - } - }; + let lm = frame_lm(frame_size)?; let m = 1usize << lm; let n = m * SHORT_MDCT; let cc = self.channels; let c = stream_channels; + self.plc.loss_count = 0; + self.plc.start = start; + self.plc.end = end.min(NB_BANDS); let eff_end = end.min(NB_BANDS); let len = dec.len(); let total_bits = (len * 8) as i32; @@ -1500,6 +1522,7 @@ impl CeltDecoder { false }; let short_blocks = if transient { m } else { 0 }; + self.plc.transient = transient; let intra = if tell + 3 <= total_bits { dec.dec_bit_logp(3) @@ -2699,6 +2722,255 @@ impl CeltDecoder { } } +fn frame_lm(frame_size: usize) -> Result { + match frame_size { + 120 => Ok(0), + 240 => Ok(1), + 480 => Ok(2), + 960 => Ok(3), + _ => Err(Error::corrupt(format!( + "celt: frame size {frame_size} is not 120, 240, 480 or 960" + ))), + } +} + +impl CeltDecoder { + /// Packet loss concealment for one lost frame of `frame_size` 48 kHz + /// samples: pitch-periodic LPC extension for the first losses, then + /// band-shaped noise decaying towards the background level. + pub fn conceal(&mut self, out: &mut [f32], frame_size: usize) -> Result<()> { + let lm = frame_lm(frame_size)?; + let n = frame_size; + if self.plc.loss_count < PLC_PERIODIC_LOSSES && self.plc.start == 0 { + if self.plc.loss_count > 0 { + self.decay_energy(PLC_PERIODIC_DECAY); + } + self.conceal_periodic(n); + } else { + let decay = if self.plc.loss_count == 0 { 1.5 } else { 0.5 }; + self.decay_energy(decay); + self.conceal_noise(lm, n); + } + self.postfilter_gain = 0.0; + self.postfilter_gain_old = 0.0; + self.plc.loss_count += 1; + self.deemphasis(out, n, self.channels); + Ok(()) + } + + fn conceal_periodic(&mut self, n: usize) { + if self.plc.loss_count == 0 { + self.plc.pitch = self.plc_pitch_search(); + } + let fade = if self.plc.loss_count == 0 { 1.0 } else { 0.8 }; + let pitch = self.plc.pitch; + let exc_len = (2 * pitch).min(MAX_PERIOD); + let decay_len = exc_len / 2; + let total = n + OVERLAP; + for ch in 0..self.channels { + let base = ch * DECODE_BUFFER; + let hist = &self.decode_mem[base..base + DECODE_BUFFER]; + if self.plc.loss_count == 0 { + self.plc.lpc[ch] = plc_lpc(&hist[DECODE_BUFFER - MAX_PERIOD..], &self.window); + } + let lpc = self.plc.lpc[ch]; + let exc = &mut self.plc.exc; + let h = &hist[DECODE_BUFFER - MAX_PERIOD - PLC_LPC_ORDER..]; + for i in 0..MAX_PERIOD { + let mut s = h[i + PLC_LPC_ORDER]; + for (k, a) in lpc.iter().enumerate() { + s += a * h[i + PLC_LPC_ORDER - 1 - k]; + } + exc[i] = s; + } + let mut e1 = 1.0f32; + let mut e2 = 1.0f32; + for i in 0..decay_len { + e1 += exc[MAX_PERIOD - decay_len + i].powi(2); + e2 += exc[MAX_PERIOD - 2 * decay_len + i].powi(2); + } + let decay = (e1.min(e2) / e2).sqrt(); + let ext = &mut self.plc.ext[..total]; + let mut att = fade * decay; + let mut j = 0; + for v in ext.iter_mut() { + if j >= pitch { + j -= pitch; + att *= decay; + } + *v = att * exc[MAX_PERIOD - pitch + j]; + j += 1; + } + let mut mem = [0.0f32; PLC_LPC_ORDER]; + for (k, m) in mem.iter_mut().enumerate() { + *m = hist[DECODE_BUFFER - 1 - k]; + } + for v in ext.iter_mut() { + let mut y = *v; + for (a, m) in lpc.iter().zip(mem.iter()) { + y -= a * m; + } + mem.copy_within(0..PLC_LPC_ORDER - 1, 1); + mem[0] = y; + *v = y; + } + let s1: f32 = hist[DECODE_BUFFER - total..].iter().map(|v| v * v).sum(); + let s2: f32 = ext.iter().map(|v| v * v).sum(); + if s1.is_nan() || s2.is_nan() || s1 <= 0.2 * s2 { + ext.fill(0.0); + } else if s1 < s2 { + let ratio = ((s1 + 1.0) / (s2 + 1.0)).sqrt(); + for (i, v) in ext.iter_mut().enumerate() { + *v *= if i < OVERLAP { + 1.0 - self.window[i] * (1.0 - ratio) + } else { + ratio + }; + } + } + self.decode_mem + .copy_within(base + n..base + DECODE_BUFFER, base); + self.decode_mem[base + DECODE_BUFFER - n..base + DECODE_BUFFER] + .copy_from_slice(&ext[..n]); + let w = &self.window; + for j in 0..OVERLAP { + let m = OVERLAP - 1 - j; + self.overlap_mem[ch * OVERLAP + j] = w[m] * (w[m] * ext[n + j] + w[j] * ext[n + m]); + } + } + } + + fn decay_energy(&mut self, decay: f32) { + for ch in 0..self.channels { + for i in self.plc.start..self.plc.end { + let k = ch * NB_BANDS + i; + self.old_band_e[k] = self.background_log_e[k].max(self.old_band_e[k] - decay); + } + } + } + + fn conceal_noise(&mut self, lm: usize, n: usize) { + let m = 1usize << lm; + let cc = self.channels; + let (start, end) = (self.plc.start, self.plc.end); + let mut seed = self.rng; + for ch in 0..cc { + let x = &mut self.x[ch * n..(ch + 1) * n]; + x.fill(0.0); + for i in start..end { + let band = &mut x[m * E_BANDS[i]..m * E_BANDS[i + 1]]; + for v in band.iter_mut() { + seed = celt_lcg_rand(seed); + *v = ((seed as i32) >> 20) as f32; + } + renormalise(band, 1.0); + } + for (i, mean) in E_MEANS.iter().enumerate() { + let k = ch * NB_BANDS + i; + self.band_e[k] = if i < start || i >= end { + 0.0 + } else { + (self.old_band_e[k] + mean).min(32.0).exp2() + }; + } + } + self.rng = seed; + self.denormalise_bands(end, cc, m, n); + let bound = (m * E_BANDS[end]).min(n / self.downsample); + for ch in 0..cc { + self.freq[ch * n + bound..(ch + 1) * n].fill(0.0); + let base = ch * DECODE_BUFFER; + self.decode_mem + .copy_within(base + n..base + DECODE_BUFFER, base); + } + let short_blocks = if self.plc.transient { m } else { 0 }; + self.inverse_mdcts(short_blocks, lm, n, cc); + } + + fn plc_pitch_search(&self) -> usize { + let half = DECODE_BUFFER / 2; + let mut x = vec![0.0f32; DECODE_BUFFER]; + for ch in 0..self.channels { + let h = &self.decode_mem[ch * DECODE_BUFFER..(ch + 1) * DECODE_BUFFER]; + for (v, s) in x.iter_mut().zip(h) { + *v += s; + } + } + let d: Vec = (0..half).map(|i| x[2 * i] + x[2 * i + 1]).collect(); + let score = |sig: &[f32], len: usize, t: usize| { + let end = sig.len(); + let a = &sig[end - len..]; + let b = &sig[end - len - t..end - t]; + let c: f32 = a.iter().zip(b).map(|(p, q)| p * q).sum(); + let e: f32 = b.iter().map(|q| q * q).sum::() + 1.0; + if c > 0.0 { c * c / e } else { 0.0 } + }; + let mut best = (PLC_PITCH_MAX / 2, 0.0f32); + for t in PLC_PITCH_MIN / 2..=PLC_PITCH_MAX / 2 { + let s = score(&d, MAX_PERIOD / 2, t); + if s > best.1 { + best = (t, s); + } + } + let mut fine = (2 * best.0, 0.0f32); + for t in (2 * best.0 - 2).max(PLC_PITCH_MIN)..=(2 * best.0 + 2).min(PLC_PITCH_MAX) { + let s = score(&x, MAX_PERIOD, t); + if s > fine.1 { + fine = (t, s); + } + } + fine.0 + } +} + +fn plc_lpc(x: &[f32], window: &[f32]) -> [f32; PLC_LPC_ORDER] { + let len = x.len(); + let xw: Vec = x + .iter() + .enumerate() + .map(|(i, &v)| { + let w = if i < OVERLAP { + window[i] + } else if i >= len - OVERLAP { + window[len - 1 - i] + } else { + 1.0 + }; + v as f64 * w as f64 + }) + .collect(); + let mut ac = [0.0f64; PLC_LPC_ORDER + 1]; + for (k, a) in ac.iter_mut().enumerate() { + *a = xw[k..].iter().zip(&xw).map(|(p, q)| p * q).sum(); + } + ac[0] *= 1.0001; + for (i, a) in ac.iter_mut().enumerate().skip(1) { + *a -= *a * 0.008 * 0.008 * (i * i) as f64; + } + let mut lpc = [0.0f64; PLC_LPC_ORDER]; + let mut error = ac[0]; + if ac[0] > 1e-10 { + for i in 0..PLC_LPC_ORDER { + let mut rr = ac[i + 1]; + for j in 0..i { + rr += lpc[j] * ac[i - j]; + } + let r = -rr / error; + lpc[i] = r; + for j in 0..i.div_ceil(2) { + let (a, b) = (lpc[j], lpc[i - 1 - j]); + lpc[j] = a + r * b; + lpc[i - 1 - j] = b + r * a; + } + error -= r * r * error; + if error <= 0.001 * ac[0] { + break; + } + } + } + lpc.map(|v| v as f32) +} + /// `ec_laplace_decode()`: the coarse-energy prediction error. pub(crate) fn laplace_decode(dec: &mut RangeDecoder, fs0: u32, decay: i32) -> i32 { const MINP: u32 = 1; diff --git a/crates/ec-opus/src/lib.rs b/crates/ec-opus/src/lib.rs index c88719a5..7ea61a78 100644 --- a/crates/ec-opus/src/lib.rs +++ b/crates/ec-opus/src/lib.rs @@ -21,11 +21,11 @@ //! - **Output is `f32`, interleaved, at the rate you asked for.** 48, 24, 16, //! 12 and 8 kHz are supported; SILK's internal rate is resampled up (by the //! normative resampler in [`silk`]) and CELT decimates on the way out. -//! - **There is no packet loss concealment.** A frame of one byte or none — -//! a dropped or DTX frame — decodes to silence, where the reference -//! extrapolates from the previous frame. This decoder is fed whole packets by -//! a container, never a gap, so the concealment would be dead weight; a -//! caller that needs it (an RTP receiver) has to add it. +//! - **Packet loss concealment is CELT-only.** [`Decoder::conceal`] (or an +//! empty packet to [`Decoder::decode_float`]) extends the last CELT frame: +//! pitch-periodic LPC extension for the first losses, then decaying +//! band-shaped noise. After a SILK or hybrid frame it yields silence, as does +//! a one-byte (DTX) frame inside a packet. //! //! The crate also carries the family's Opus *encoder* — [`Encoder`] for one //! stream, [`MultistreamEncoder`] for surround — CELT-only, fullband, mono @@ -102,7 +102,7 @@ pub struct Decoder { celt: CeltDecoder, /// Boxed because a `SilkDecoder` is 6304 bytes, 83% of what a `Decoder` /// costs a caller taking one BY VALUE from `Decoder::new`. It is the - /// decoder's largest field and its only large one; `celt` is 1168. + /// decoder's largest field and its only large one; `celt` is 1448. /// `Stack`: crate::stack_budget. silk: Box, /// The CELT overlap window, reused for redundancy cross-fades. @@ -114,6 +114,8 @@ pub struct Decoder { prev_mode: Option, prev_redundancy: bool, range_final: u32, + /// Samples per channel of the last packet, the default concealment length. + last_packet_size: usize, /// Test hook: drop the (CELT, SILK) layer's output before the sum. debug_mute: (bool, bool), } @@ -172,6 +174,7 @@ impl Decoder { prev_mode: None, prev_redundancy: false, range_final: 0, + last_packet_size: 960 / downsample, debug_mute: (false, false), }) } @@ -203,10 +206,15 @@ impl Decoder { } /// Decodes one packet into interleaved `f32`, returning samples per channel. + /// An empty `packet` is a lost one: it is concealed for the last packet's + /// duration (see [`Decoder::conceal`]). /// /// `out` must hold `channels * 120 ms` worth of samples for the general /// case (5760 per channel at 48 kHz). pub fn decode_float(&mut self, packet: &[u8], out: &mut [f32]) -> Result { + if packet.is_empty() { + return self.conceal(self.last_packet_size, out); + } let (samples, _) = self.decode_impl(packet, out, false)?; Ok(samples) } @@ -222,6 +230,44 @@ impl Decoder { self.decode_impl(data, out, true) } + /// Conceals `frame_size` lost samples per channel (a multiple of 2.5 ms, + /// at most 120 ms), the equivalent of the reference's `decode(NULL)`. + /// Consecutive calls decay towards background noise; the next real + /// packet cross-fades in through the MDCT overlap. + pub fn conceal(&mut self, frame_size: usize, out: &mut [f32]) -> Result { + let total_48k = frame_size * self.downsample; + if total_48k == 0 || !total_48k.is_multiple_of(120) || total_48k > 5760 { + return Err(Error::corrupt(format!( + "opus: conceal size {frame_size} is not a multiple of 2.5 ms up to 120 ms" + ))); + } + let needed = frame_size * self.channels; + if out.len() < needed { + return Err(Error::corrupt(format!( + "opus: output buffer holds {} samples, concealment needs {needed}", + out.len() + ))); + } + let mut done_48k = 0usize; + while done_48k < total_48k { + let left = total_48k - done_48k; + let chunk = [960, 480, 240, 120] + .into_iter() + .find(|&c| c <= left) + .unwrap_or(120); + let a = done_48k / self.downsample * self.channels; + let b = (done_48k + chunk) / self.downsample * self.channels; + let dst = &mut out[a..b]; + if self.prev_mode == Some(Mode::Celt) { + self.celt.conceal(dst, chunk)?; + } else { + dst.fill(0.0); + } + done_48k += chunk; + } + Ok(frame_size) + } + fn decode_impl( &mut self, data: &[u8], @@ -247,6 +293,7 @@ impl Decoder { done += frame_out; } self.range_final = range; + self.last_packet_size = done; Ok((done, parsed.consumed)) } diff --git a/crates/ec-opus/src/stack_budget.rs b/crates/ec-opus/src/stack_budget.rs index 4e7bb6c6..dcb9a9a6 100755 --- a/crates/ec-opus/src/stack_budget.rs +++ b/crates/ec-opus/src/stack_budget.rs @@ -114,7 +114,7 @@ pub(crate) const BY_VALUE_TYPES: &[(&str, Option, bool, &str)] = &[ // -- lib.rs ----------------------------------------------------------- ( "Decoder", - Some(1280), + Some(1568), true, "Decoder::new -> Result. Was 7576, 92.5% of the budget, \ 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, bool, &str)] = &[ // -- celt.rs ---------------------------------------------------------- ( "CeltDecoder", - Some(1168), + Some(1448), true, "celt::CeltDecoder::new(channels, downsample) -> Self; also moved by \ value into Decoder::celt", diff --git a/crates/ec-opus/tests/plc.rs b/crates/ec-opus/tests/plc.rs new file mode 100644 index 00000000..68545ffe --- /dev/null +++ b/crates/ec-opus/tests/plc.rs @@ -0,0 +1,79 @@ +use ec_opus::{Application, Decoder, Encoder, Mode}; + +const FRAME: usize = 960; + +fn voice(frames: usize) -> Vec { + (0..frames * FRAME) + .map(|i| { + let t = i as f32 / 48000.0; + let f0 = 140.0 + 10.0 * (2.0 * std::f32::consts::PI * 0.7 * t).sin(); + (1..12) + .map(|h| (2.0 * std::f32::consts::PI * f0 * h as f32 * t).sin() * 0.25 / h as f32) + .sum() + }) + .collect() +} + +fn corr(a: &[f32], b: &[f32]) -> f32 { + let ab: f32 = a.iter().zip(b).map(|(x, y)| x * y).sum(); + let aa: f32 = a.iter().map(|x| x * x).sum(); + let bb: f32 = b.iter().map(|x| x * x).sum(); + ab / (aa * bb).sqrt().max(1e-9) +} + +fn rms(a: &[f32]) -> f32 { + (a.iter().map(|x| x * x).sum::() / a.len() as f32).sqrt() +} + +#[test] +fn concealment_tracks_and_recovers() { + let pcm = voice(60); + let mut enc = Encoder::new(48000, 1, Application::Voip).unwrap(); + enc.set_bitrate(32000); + enc.set_mode(Some(Mode::Celt)); + let mut pkt = vec![0u8; 1500]; + let packets: Vec> = pcm + .chunks_exact(FRAME) + .map(|f| { + let n = enc.encode_float(f, FRAME, &mut pkt).unwrap(); + pkt[..n].to_vec() + }) + .collect(); + let lost = [20usize, 40, 41, 42, 43, 44, 45, 46, 47]; + let mut clean = Decoder::new(48000, 1).unwrap(); + let mut lossy = Decoder::new(48000, 1).unwrap(); + let mut buf = vec![0f32; 5760]; + let (mut a, mut b) = (Vec::new(), Vec::new()); + for (i, p) in packets.iter().enumerate() { + let k = clean.decode_float(p, &mut buf).unwrap(); + a.extend_from_slice(&buf[..k]); + let k = if lost.contains(&i) { + lossy.decode_float(&[], &mut buf).unwrap() + } else { + lossy.decode_float(p, &mut buf).unwrap() + }; + b.extend_from_slice(&buf[..k]); + } + let f = |i: usize| i * FRAME..(i + 1) * FRAME; + let c20 = corr(&a[f(20)], &b[f(20)]); + let r20 = rms(&b[f(20)]) / rms(&a[f(20)]); + let c22 = corr(&a[f(22)], &b[f(22)]); + let r47 = rms(&b[f(47)]) / rms(&a[f(47)]); + let c50 = corr(&a[f(50)], &b[f(50)]); + let jump = b + .windows(2) + .map(|w| (w[1] - w[0]).abs()) + .fold(0.0f32, f32::max); + let jump_ref = a + .windows(2) + .map(|w| (w[1] - w[0]).abs()) + .fold(0.0f32, f32::max); + eprintln!( + "c20 {c20:.3} r20 {r20:.3} c22 {c22:.3} r47 {r47:.3} c50 {c50:.3} jump {jump:.4} ref {jump_ref:.4}" + ); + assert!(c20 > 0.5 && (0.5..1.5).contains(&r20)); + assert!(c22 > 0.9); + assert!(r47 < 0.5); + assert!(c50 > 0.9); + assert!(jump < 2.0 * jump_ref); +}