diff --git a/crates/ec-opus/src/silk_enc.rs b/crates/ec-opus/src/silk_enc.rs index 7c11e92f..36969bf6 100644 --- a/crates/ec-opus/src/silk_enc.rs +++ b/crates/ec-opus/src/silk_enc.rs @@ -295,8 +295,10 @@ fn lpc_to_nlsf(lpc: &[f64], order: usize) -> [i16; MAX_LPC_ORDER] { let mut im = 0.0; for (k, &a) in lpc.iter().enumerate() { let kw = (k as f64 + 1.0) * w; - re += a * kw.cos(); - im -= a * kw.sin(); + // `lpc` is the predictor (`x[n] ~= sum a[k] x[n-k-1]`), so the + // analysis polynomial is A(z) = 1 - sum a[k] z^-(k+1). + re -= a * kw.cos(); + im += a * kw.sin(); } let half = m1 * w / 2.0; let (hs, hc) = half.sin_cos(); diff --git a/crates/ec-opus/src/silk_enc_write.rs b/crates/ec-opus/src/silk_enc_write.rs index 171eb443..b240b92c 100644 --- a/crates/ec-opus/src/silk_enc_write.rs +++ b/crates/ec-opus/src/silk_enc_write.rs @@ -13,6 +13,9 @@ //! under the decoder's seed/offset convention). Noise shaping (NSQ), 10/40/60 //! ms frames and stereo are subtask D2b. +// Same idiom as silk.rs: index loops mirror the decoder's position arithmetic. +#![allow(clippy::needless_range_loop)] + use ec_core::Result; use crate::range::{RangeDecoder, RangeEncoder}; @@ -168,102 +171,112 @@ impl SilkEncoder { } acc }; - // Codebook pick by min squared error, open loop (the frame's own - // residual stands in for the not-yet-quantised part of the history). - let mut per_index = 0usize; - let mut ltp_index = [0usize; MAX_NB_SUBFR]; - if voiced { - let mut r_ol = r.clone(); - r_ol[n..].copy_from_slice(&res); - let mut best_total = f32::INFINITY; - for (per, cbk) in [<P_GAIN_VQ_0[..], <P_GAIN_VQ_1[..], <P_GAIN_VQ_2[..]] - .iter() - .enumerate() - { - let mut total = 0f32; - let mut idx = [0usize; MAX_NB_SUBFR]; - for k in 0..NB_SUBFR { - let mut best = f32::INFINITY; - for (v, b) in cbk.iter().enumerate() { - let err: f32 = (0..sub) - .map(|i| { - let d = res[k * sub + i] - ltp_pred(&r_ol, b, k, i); - d * d - }) - .sum(); - if err < best { - best = err; - idx[k] = v; - } - } - total += best; - } - if total < best_total { - best_total = total; - per_index = per; - ltp_index = idx; - } + let codebook = |per: usize| -> &'static [[i8; 5]] { + match per { + 0 => <P_GAIN_VQ_0, + 1 => <P_GAIN_VQ_1, + _ => <P_GAIN_VQ_2, } - } - let cbk: &[[i8; 5]] = match per_index { - 0 => <P_GAIN_VQ_0, - 1 => <P_GAIN_VQ_1, - _ => <P_GAIN_VQ_2, }; - - // Gains: the open-loop excitation RMS per subframe, so pulses land - // around unit magnitude. + // Gains: the open-loop excitation RMS per subframe (LTP vector picked + // against the unquantised residual), so pulses land around unit + // magnitude. let mut targets = [0i32; MAX_NB_SUBFR]; - for k in 0..NB_SUBFR { + { let mut r_ol = r.clone(); r_ol[n..].copy_from_slice(&res); - let e: f32 = (0..sub) - .map(|i| { - let p = if voiced { ltp_pred(&r_ol, &cbk[ltp_index[k]], k, i) } else { 0.0 }; - let d = res[k * sub + i] - p; - d * d - }) - .sum::() - / sub as f32; - targets[k] = ((e.sqrt() * 65536.0).round() as i64).clamp(1, i32::MAX as i64) as i32; + for k in 0..NB_SUBFR { + let e = if voiced { + LTP_GAIN_VQ_2 + .iter() + .map(|b| { + (0..sub) + .map(|i| { + let d = res[k * sub + i] - ltp_pred(&r_ol, b, k, i); + d * d + }) + .sum::() + }) + .fold(f32::INFINITY, f32::min) + } else { + (0..sub).map(|i| res[k * sub + i].powi(2)).sum() + }; + let rms = (e / sub as f32).sqrt(); + targets[k] = ((rms * 65536.0).round() as i64).clamp(1, i32::MAX as i64) as i32; + } } let (gain_idx, gains_q16) = quantize_gains(&targets, &mut self.prev_gain_index, false, NB_SUBFR); - // Pulses: sequential, under the decoder's seed-driven sign flips. + // Excitation, closed loop: for each candidate LTP codebook, per + // subframe pick the vector that best predicts the residual from the + // *reconstructed* history (so quantisation noise fed back through the + // pitch loop is accounted for), then quantise the pulses sequentially + // under the decoder's seed-driven sign flips. Keep the codebook with + // the least reconstruction error. let seed_index = 0i32; - let mut seed = seed_index; - let mut pulses = vec![0i32; n]; - for k in 0..NB_SUBFR { - let g = gains_q16[k] as f32 / 65536.0; - for i in 0..sub { - let idx = k * sub + i; - let pred = if voiced { ltp_pred(&r, &cbk[ltp_index[k]], k, i) } else { 0.0 }; - let e = (res[idx] - pred) / g; - seed = silk_rand(seed); - let flip = seed < 0; - let target = if flip { -e } else { e }; - let recon = |p: i32| -> f32 { - let lvl = p as f32 - LEVEL_ADJUST * (p.signum() as f32); - lvl + offset - }; - let c = (target.round() as i32).clamp(-MAX_PULSE, MAX_PULSE); - let p = [c - 1, c, c + 1] - .into_iter() - .filter(|p| p.abs() <= MAX_PULSE) - .min_by(|&a, &b| { - (recon(a) - target) - .abs() - .partial_cmp(&(recon(b) - target).abs()) - .unwrap() - }) - .unwrap(); - pulses[idx] = p; - seed = seed.wrapping_add(p); - let exc = if flip { -recon(p) } else { recon(p) }; - r[n + idx] = g * (exc + pred); + let run = |per: usize| -> ([usize; MAX_NB_SUBFR], Vec, Vec, f32) { + let cbk = codebook(per); + let mut r = r.clone(); + let mut ltp_index = [0usize; MAX_NB_SUBFR]; + let mut pulses = vec![0i32; n]; + let mut seed = seed_index; + let mut err = 0f32; + for k in 0..NB_SUBFR { + if voiced { + // In-subframe taps (lag shorter than the subframe) see the + // unquantised residual as a stand-in. + let mut r_ol = r.clone(); + r_ol[n + k * sub..n + (k + 1) * sub].copy_from_slice(&res[k * sub..(k + 1) * sub]); + let mut best = f32::INFINITY; + for (v, b) in cbk.iter().enumerate() { + let e: f32 = (0..sub) + .map(|i| (res[k * sub + i] - ltp_pred(&r_ol, b, k, i)).powi(2)) + .sum(); + if e < best { + best = e; + ltp_index[k] = v; + } + } + } + let g = gains_q16[k] as f32 / 65536.0; + for i in 0..sub { + let idx = k * sub + i; + let pred = if voiced { ltp_pred(&r, &cbk[ltp_index[k]], k, i) } else { 0.0 }; + let e = (res[idx] - pred) / g; + seed = silk_rand(seed); + let flip = seed < 0; + let target = if flip { -e } else { e }; + let recon = |p: i32| -> f32 { + let lvl = p as f32 - LEVEL_ADJUST * (p.signum() as f32); + lvl + offset + }; + let c = (target.round() as i32).clamp(-MAX_PULSE, MAX_PULSE); + let p = [c - 1, c, c + 1] + .into_iter() + .filter(|p| p.abs() <= MAX_PULSE) + .min_by(|&a, &b| { + (recon(a) - target) + .abs() + .partial_cmp(&(recon(b) - target).abs()) + .unwrap() + }) + .unwrap(); + pulses[idx] = p; + seed = seed.wrapping_add(p); + let exc = if flip { -recon(p) } else { recon(p) }; + r[n + idx] = g * exc + pred; + err += (r[n + idx] - res[idx]).powi(2); + } } - } + (ltp_index, pulses, r, err) + }; + let candidates: Vec = if voiced { vec![0, 1, 2] } else { vec![0] }; + let (per_index, (ltp_index, pulses, _, _)) = candidates + .into_iter() + .map(|per| (per, run(per))) + .min_by(|a, b| a.1 .3.partial_cmp(&b.1 .3).unwrap()) + .unwrap(); // --- Bitstream, in decode()'s order. --- let enc = &mut self.range; @@ -290,10 +303,10 @@ impl SilkEncoder { for i in 0..order { let q = nq.indices[i + 1] as i32; let icdf = &cb.ec_icdf[ec_ix[i] as usize..]; - if q < -4 { + if q <= -4 { enc.enc_icdf(0, icdf, 8); enc.enc_icdf((-4 - q) as usize, &NLSF_EXT_ICDF, 8); - } else if q > 4 { + } else if q >= 4 { enc.enc_icdf(8, icdf, 8); enc.enc_icdf((q - 4) as usize, &NLSF_EXT_ICDF, 8); } else { @@ -498,3 +511,4 @@ mod tests { } } } + diff --git a/crates/ec-opus/tests/conformance.rs b/crates/ec-opus/tests/conformance.rs index be64842f..e0b99470 100644 --- a/crates/ec-opus/tests/conformance.rs +++ b/crates/ec-opus/tests/conformance.rs @@ -1383,3 +1383,169 @@ fn garbage_payloads_never_panic() { } } } + +// --------------------------------------------------------------------------- +// SILK encoder (mono, 20 ms, NB/WB) +// --------------------------------------------------------------------------- + +use ec_opus::SilkEncoder; + +/// A 1 s speech-like signal at 48 kHz: 0.6 s of a pitch-modulated pulse train +/// through a formant-ish AR(2) filter, then 0.4 s of filtered noise. +fn speech_like() -> Vec { + let mut out = Vec::with_capacity(48000); + let (mut y1, mut y2) = (0f32, 0f32); + let mut phase = 0f64; + let mut s = 12345u32; + for i in 0..48000 { + let t = i as f64 / 48000.0; + let e = if t < 0.6 { + let f0 = 120.0 + 30.0 * (2.0 * std::f64::consts::PI * 2.0 * t).sin(); + phase += f0 / 48000.0; + if phase >= 1.0 { + phase -= 1.0; + 1.0 + } else { + 0.0 + } + } else { + s = s.wrapping_mul(1664525).wrapping_add(1013904223); + ((s >> 8) as f32 / (1u32 << 24) as f32 - 0.5) * 0.3 + }; + // Resonance near 700 Hz, radius 0.97. + let (r, w) = (0.97f32, 2.0 * std::f32::consts::PI * 700.0 / 48000.0); + let y = e + 2.0 * r * w.cos() * y1 - r * r * y2; + y2 = y1; + y1 = y; + out.push(y * 0.03); + } + out +} + +/// 16-bit PCM mono WAV at 48 kHz, as `f32`. +fn read_wav_mono(path: &Path) -> Vec { + let d = fs::read(path).unwrap(); + assert_eq!(u16::from_le_bytes([d[22], d[23]]), 1, "mono fixture"); + assert_eq!(u32::from_le_bytes([d[24], d[25], d[26], d[27]]), 48000); + let mut pos = 12; + loop { + let id = &d[pos..pos + 4]; + let len = u32::from_le_bytes([d[pos + 4], d[pos + 5], d[pos + 6], d[pos + 7]]) as usize; + if id == b"data" { + return d[pos + 8..pos + 8 + len] + .chunks_exact(2) + .map(|c| i16::from_le_bytes([c[0], c[1]]) as f32 / 32768.0) + .collect(); + } + pos += 8 + len + (len & 1); + } +} + +/// Windowed-sinc low-pass at `cutoff_hz` (48 kHz input), zero-phase. +fn lowpass(x: &[f32], cutoff_hz: f64) -> Vec { + let taps = 127usize; + let c = cutoff_hz / 48000.0; + let h: Vec = (0..taps) + .map(|i| { + let m = i as f64 - (taps - 1) as f64 / 2.0; + let sinc = if m == 0.0 { 2.0 * c } else { (2.0 * std::f64::consts::PI * c * m).sin() / (std::f64::consts::PI * m) }; + sinc * (0.54 - 0.46 * (2.0 * std::f64::consts::PI * i as f64 / (taps - 1) as f64).cos()) + }) + .collect(); + let half = (taps - 1) / 2; + (0..x.len()) + .map(|n| { + h.iter() + .enumerate() + .map(|(k, &hk)| { + let idx = n as isize + half as isize - k as isize; + if idx >= 0 && (idx as usize) < x.len() { hk * x[idx as usize] as f64 } else { 0.0 } + }) + .sum::() as f32 + }) + .collect() +} + +/// Encodes `pcm` NB or WB, decodes each packet with our decoder asserting the +/// range-coder invariant, returns (decoded 48 kHz, packets, voiced frames, +/// encoder delay). +fn silk_roundtrip(pcm: &[f32], wideband: bool) -> (Vec, Vec>, usize, usize) { + let mut enc = SilkEncoder::new(wideband); + let mut dec = Decoder::new(48000, 1).unwrap(); + let mut out = vec![0u8; 1500]; + let mut buf = vec![0f32; 5760]; + let mut decoded = Vec::new(); + let mut packets = Vec::new(); + let mut padded = pcm.to_vec(); + padded.resize(pcm.len().div_ceil(960) * 960 + 960, 0.0); + for block in padded.chunks(960) { + let len = enc.encode_frame(block, &mut out).expect("silk encode"); + let n = dec.decode_float(&out[..len], &mut buf).expect("silk decode"); + assert_eq!(n, 960); + assert_eq!(dec.final_range(), enc.final_range(), "range state diverged"); + decoded.extend_from_slice(&buf[..n]); + packets.push(out[..len].to_vec()); + } + (decoded, packets, enc.voiced_frames(), enc.delay_samples()) +} + +/// Correlation after aligning `decoded` to `reference` at the best lag in +/// `[0, max_lag)`; the peak must be interior (a peak at the search bound is +/// no measurement). +fn aligned_corr(reference: &[f32], decoded: &[f32], max_lag: usize) -> (f64, usize) { + let (mut best, mut best_lag) = (-1.0f64, 0usize); + for lag in 0..max_lag { + let c = correlation(reference, &decoded[lag..]); + if c > best { + best = c; + best_lag = lag; + } + } + assert!(best_lag + 1 < max_lag, "alignment peak at the search bound"); + (best, best_lag) +} + +#[test] +fn silk_mono_nb_wb_roundtrip() { + let wav = fixture("wav16-mono-48000.wav"); + let mut sources = vec![("synthetic", speech_like())]; + if wav.exists() { + let w = read_wav_mono(&wav); + sources.push(("wav16-mono-48000", w[..w.len().min(96000)].to_vec())); + } + for (name, pcm) in &sources { + for wideband in [false, true] { + let (decoded, packets, voiced, delay) = silk_roundtrip(pcm, wideband); + let band = if wideband { 7000.0 } else { 3500.0 }; + let reference = lowpass(pcm, band); + let (corr, lag) = aligned_corr(&reference, &decoded, 2000); + let bytes: usize = packets.iter().map(Vec::len).sum(); + let tag = if wideband { "WB" } else { "NB" }; + eprintln!( + "silk {name} {tag}: corr {corr:.4} at lag {lag} (resampler delay {delay}), voiced {voiced}/{} frames, {} kbps", + packets.len(), + bytes * 8 / (packets.len() * 20) + ); + assert!(corr >= 0.8, "{name} {tag}: corr {corr:.4}"); + assert!(lag >= delay, "{name} {tag}: aligned before the documented delay"); + if *name == "synthetic" { + assert!(voiced > 0, "{name} {tag}: no frame coded with LTP"); + } + + // Reference oracle: the packets in an Ogg-Opus file decode cleanly. + if Command::new("ffmpeg").arg("-version").output().is_ok() { + let path = temp_path(&format!("silk-{name}-{tag}.opus")); + write_ogg_opus(&path, &packets, opus_head(1, None), 1, pcm.len()); + let out = Command::new("ffmpeg") + .args(["-v", "warning", "-c:a", "libopus", "-i"]) + .arg(&path) + .args(["-f", "null", "-"]) + .output() + .unwrap(); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(out.status.success() && stderr.trim().is_empty(), "{name} {tag}: ffmpeg: {stderr}"); + let _ = fs::remove_file(&path); + } + } + } +}