forge
Explore
Log in

Don't you dare go Hollow

LPC->NLSF polynomial sign, closed-loop LTP pick, conformance round trip

Browse files at this commit

68c706494daebf17252b21c925fd6ce9c1b7ae78Ahmet Kaan GümüşParent: 12e4d27
  • fix
    • LPC->NLSF polynomial sign, closed-loop LTP pick, conformance round trip
Show full message
fix(opus-silk): LPC->NLSF polynomial sign, closed-loop LTP pick, conformance round trip

lpc_to_nlsf evaluated A(z) = 1 + sum a z^-k for a predictor-convention
lpc (x ~= sum a x[n-k-1]); the decoder's nlsf2a thus got the anti-predictor
and every synthesised frame rang. LTP codebook vectors are now picked per
subframe against the reconstructed (quantised) history so pitch-loop
feedback of quantisation noise cannot run away; the reconstruction keeps
LTP prediction in sample units (g*exc + pred). silk_mono_nb_wb_roundtrip:
synthetic NB 0.975 / WB 0.981, wav16-mono NB 0.9999 / WB 0.9996, range
state equal every packet, ffmpeg decodes the Ogg clean.
crates/ec-opus/src/silk_enc.rsmodified+4 -2
@@ -295,8 +295,10 @@ fn lpc_to_nlsf(lpc: &[f64], order: usize) -> [i16; MAX_LPC_ORDER] {
295295 let mut im = 0.0;
296296 for (k, &a) in lpc.iter().enumerate() {
297297 let kw = (k as f64 + 1.0) * w;
298- re += a * kw.cos();
299- im -= a * kw.sin();
298+ // `lpc` is the predictor (`x[n] ~= sum a[k] x[n-k-1]`), so the
299+ // analysis polynomial is A(z) = 1 - sum a[k] z^-(k+1).
300+ re -= a * kw.cos();
301+ im += a * kw.sin();
300302 }
301303 let half = m1 * w / 2.0;
302304 let (hs, hc) = half.sin_cos();
crates/ec-opus/src/silk_enc_write.rsmodified+101 -87
@@ -13,6 +13,9 @@
1313 //! under the decoder's seed/offset convention). Noise shaping (NSQ), 10/40/60
1414 //! ms frames and stereo are subtask D2b.
1515
16+// Same idiom as silk.rs: index loops mirror the decoder's position arithmetic.
17+#![allow(clippy::needless_range_loop)]
18+
1619 use ec_core::Result;
1720
1821 use crate::range::{RangeDecoder, RangeEncoder};
@@ -168,102 +171,112 @@ impl SilkEncoder {
168171 }
169172 acc
170173 };
171- // Codebook pick by min squared error, open loop (the frame's own
172- // residual stands in for the not-yet-quantised part of the history).
173- let mut per_index = 0usize;
174- let mut ltp_index = [0usize; MAX_NB_SUBFR];
175- if voiced {
176- let mut r_ol = r.clone();
177- r_ol[n..].copy_from_slice(&res);
178- let mut best_total = f32::INFINITY;
179- for (per, cbk) in [&LTP_GAIN_VQ_0[..], &LTP_GAIN_VQ_1[..], &LTP_GAIN_VQ_2[..]]
180- .iter()
181- .enumerate()
182- {
183- let mut total = 0f32;
184- let mut idx = [0usize; MAX_NB_SUBFR];
185- for k in 0..NB_SUBFR {
186- let mut best = f32::INFINITY;
187- for (v, b) in cbk.iter().enumerate() {
188- let err: f32 = (0..sub)
189- .map(|i| {
190- let d = res[k * sub + i] - ltp_pred(&r_ol, b, k, i);
191- d * d
192- })
193- .sum();
194- if err < best {
195- best = err;
196- idx[k] = v;
197- }
198- }
199- total += best;
200- }
201- if total < best_total {
202- best_total = total;
203- per_index = per;
204- ltp_index = idx;
205- }
174+ let codebook = |per: usize| -> &'static [[i8; 5]] {
175+ match per {
176+ 0 => &LTP_GAIN_VQ_0,
177+ 1 => &LTP_GAIN_VQ_1,
178+ _ => &LTP_GAIN_VQ_2,
206179 }
207- }
208- let cbk: &[[i8; 5]] = match per_index {
209- 0 => &LTP_GAIN_VQ_0,
210- 1 => &LTP_GAIN_VQ_1,
211- _ => &LTP_GAIN_VQ_2,
212180 };
213-
214- // Gains: the open-loop excitation RMS per subframe, so pulses land
215- // around unit magnitude.
181+ // Gains: the open-loop excitation RMS per subframe (LTP vector picked
182+ // against the unquantised residual), so pulses land around unit
183+ // magnitude.
216184 let mut targets = [0i32; MAX_NB_SUBFR];
217- for k in 0..NB_SUBFR {
185+ {
218186 let mut r_ol = r.clone();
219187 r_ol[n..].copy_from_slice(&res);
220- let e: f32 = (0..sub)
221- .map(|i| {
222- let p = if voiced { ltp_pred(&r_ol, &cbk[ltp_index[k]], k, i) } else { 0.0 };
223- let d = res[k * sub + i] - p;
224- d * d
225- })
226- .sum::<f32>()
227- / sub as f32;
228- targets[k] = ((e.sqrt() * 65536.0).round() as i64).clamp(1, i32::MAX as i64) as i32;
188+ for k in 0..NB_SUBFR {
189+ let e = if voiced {
190+ LTP_GAIN_VQ_2
191+ .iter()
192+ .map(|b| {
193+ (0..sub)
194+ .map(|i| {
195+ let d = res[k * sub + i] - ltp_pred(&r_ol, b, k, i);
196+ d * d
197+ })
198+ .sum::<f32>()
199+ })
200+ .fold(f32::INFINITY, f32::min)
201+ } else {
202+ (0..sub).map(|i| res[k * sub + i].powi(2)).sum()
203+ };
204+ let rms = (e / sub as f32).sqrt();
205+ targets[k] = ((rms * 65536.0).round() as i64).clamp(1, i32::MAX as i64) as i32;
206+ }
229207 }
230208 let (gain_idx, gains_q16) =
231209 quantize_gains(&targets, &mut self.prev_gain_index, false, NB_SUBFR);
232210
233- // Pulses: sequential, under the decoder's seed-driven sign flips.
211+ // Excitation, closed loop: for each candidate LTP codebook, per
212+ // subframe pick the vector that best predicts the residual from the
213+ // *reconstructed* history (so quantisation noise fed back through the
214+ // pitch loop is accounted for), then quantise the pulses sequentially
215+ // under the decoder's seed-driven sign flips. Keep the codebook with
216+ // the least reconstruction error.
234217 let seed_index = 0i32;
235- let mut seed = seed_index;
236- let mut pulses = vec![0i32; n];
237- for k in 0..NB_SUBFR {
238- let g = gains_q16[k] as f32 / 65536.0;
239- for i in 0..sub {
240- let idx = k * sub + i;
241- let pred = if voiced { ltp_pred(&r, &cbk[ltp_index[k]], k, i) } else { 0.0 };
242- let e = (res[idx] - pred) / g;
243- seed = silk_rand(seed);
244- let flip = seed < 0;
245- let target = if flip { -e } else { e };
246- let recon = |p: i32| -> f32 {
247- let lvl = p as f32 - LEVEL_ADJUST * (p.signum() as f32);
248- lvl + offset
249- };
250- let c = (target.round() as i32).clamp(-MAX_PULSE, MAX_PULSE);
251- let p = [c - 1, c, c + 1]
252- .into_iter()
253- .filter(|p| p.abs() <= MAX_PULSE)
254- .min_by(|&a, &b| {
255- (recon(a) - target)
256- .abs()
257- .partial_cmp(&(recon(b) - target).abs())
258- .unwrap()
259- })
260- .unwrap();
261- pulses[idx] = p;
262- seed = seed.wrapping_add(p);
263- let exc = if flip { -recon(p) } else { recon(p) };
264- r[n + idx] = g * (exc + pred);
218+ let run = |per: usize| -> ([usize; MAX_NB_SUBFR], Vec<i32>, Vec<f32>, f32) {
219+ let cbk = codebook(per);
220+ let mut r = r.clone();
221+ let mut ltp_index = [0usize; MAX_NB_SUBFR];
222+ let mut pulses = vec![0i32; n];
223+ let mut seed = seed_index;
224+ let mut err = 0f32;
225+ for k in 0..NB_SUBFR {
226+ if voiced {
227+ // In-subframe taps (lag shorter than the subframe) see the
228+ // unquantised residual as a stand-in.
229+ let mut r_ol = r.clone();
230+ r_ol[n + k * sub..n + (k + 1) * sub].copy_from_slice(&res[k * sub..(k + 1) * sub]);
231+ let mut best = f32::INFINITY;
232+ for (v, b) in cbk.iter().enumerate() {
233+ let e: f32 = (0..sub)
234+ .map(|i| (res[k * sub + i] - ltp_pred(&r_ol, b, k, i)).powi(2))
235+ .sum();
236+ if e < best {
237+ best = e;
238+ ltp_index[k] = v;
239+ }
240+ }
241+ }
242+ let g = gains_q16[k] as f32 / 65536.0;
243+ for i in 0..sub {
244+ let idx = k * sub + i;
245+ let pred = if voiced { ltp_pred(&r, &cbk[ltp_index[k]], k, i) } else { 0.0 };
246+ let e = (res[idx] - pred) / g;
247+ seed = silk_rand(seed);
248+ let flip = seed < 0;
249+ let target = if flip { -e } else { e };
250+ let recon = |p: i32| -> f32 {
251+ let lvl = p as f32 - LEVEL_ADJUST * (p.signum() as f32);
252+ lvl + offset
253+ };
254+ let c = (target.round() as i32).clamp(-MAX_PULSE, MAX_PULSE);
255+ let p = [c - 1, c, c + 1]
256+ .into_iter()
257+ .filter(|p| p.abs() <= MAX_PULSE)
258+ .min_by(|&a, &b| {
259+ (recon(a) - target)
260+ .abs()
261+ .partial_cmp(&(recon(b) - target).abs())
262+ .unwrap()
263+ })
264+ .unwrap();
265+ pulses[idx] = p;
266+ seed = seed.wrapping_add(p);
267+ let exc = if flip { -recon(p) } else { recon(p) };
268+ r[n + idx] = g * exc + pred;
269+ err += (r[n + idx] - res[idx]).powi(2);
270+ }
265271 }
266- }
272+ (ltp_index, pulses, r, err)
273+ };
274+ let candidates: Vec<usize> = if voiced { vec![0, 1, 2] } else { vec![0] };
275+ let (per_index, (ltp_index, pulses, _, _)) = candidates
276+ .into_iter()
277+ .map(|per| (per, run(per)))
278+ .min_by(|a, b| a.1 .3.partial_cmp(&b.1 .3).unwrap())
279+ .unwrap();
267280
268281 // --- Bitstream, in decode()'s order. ---
269282 let enc = &mut self.range;
@@ -290,10 +303,10 @@ impl SilkEncoder {
290303 for i in 0..order {
291304 let q = nq.indices[i + 1] as i32;
292305 let icdf = &cb.ec_icdf[ec_ix[i] as usize..];
293- if q < -4 {
306+ if q <= -4 {
294307 enc.enc_icdf(0, icdf, 8);
295308 enc.enc_icdf((-4 - q) as usize, &NLSF_EXT_ICDF, 8);
296- } else if q > 4 {
309+ } else if q >= 4 {
297310 enc.enc_icdf(8, icdf, 8);
298311 enc.enc_icdf((q - 4) as usize, &NLSF_EXT_ICDF, 8);
299312 } else {
@@ -498,3 +511,4 @@ mod tests {
498511 }
499512 }
500513 }
514+
crates/ec-opus/tests/conformance.rsmodified+166 -0
@@ -1383,3 +1383,169 @@ fn garbage_payloads_never_panic() {
13831383 }
13841384 }
13851385 }
1386+
1387+// ---------------------------------------------------------------------------
1388+// SILK encoder (mono, 20 ms, NB/WB)
1389+// ---------------------------------------------------------------------------
1390+
1391+use ec_opus::SilkEncoder;
1392+
1393+/// A 1 s speech-like signal at 48 kHz: 0.6 s of a pitch-modulated pulse train
1394+/// through a formant-ish AR(2) filter, then 0.4 s of filtered noise.
1395+fn speech_like() -> Vec<f32> {
1396+ let mut out = Vec::with_capacity(48000);
1397+ let (mut y1, mut y2) = (0f32, 0f32);
1398+ let mut phase = 0f64;
1399+ let mut s = 12345u32;
1400+ for i in 0..48000 {
1401+ let t = i as f64 / 48000.0;
1402+ let e = if t < 0.6 {
1403+ let f0 = 120.0 + 30.0 * (2.0 * std::f64::consts::PI * 2.0 * t).sin();
1404+ phase += f0 / 48000.0;
1405+ if phase >= 1.0 {
1406+ phase -= 1.0;
1407+ 1.0
1408+ } else {
1409+ 0.0
1410+ }
1411+ } else {
1412+ s = s.wrapping_mul(1664525).wrapping_add(1013904223);
1413+ ((s >> 8) as f32 / (1u32 << 24) as f32 - 0.5) * 0.3
1414+ };
1415+ // Resonance near 700 Hz, radius 0.97.
1416+ let (r, w) = (0.97f32, 2.0 * std::f32::consts::PI * 700.0 / 48000.0);
1417+ let y = e + 2.0 * r * w.cos() * y1 - r * r * y2;
1418+ y2 = y1;
1419+ y1 = y;
1420+ out.push(y * 0.03);
1421+ }
1422+ out
1423+}
1424+
1425+/// 16-bit PCM mono WAV at 48 kHz, as `f32`.
1426+fn read_wav_mono(path: &Path) -> Vec<f32> {
1427+ let d = fs::read(path).unwrap();
1428+ assert_eq!(u16::from_le_bytes([d[22], d[23]]), 1, "mono fixture");
1429+ assert_eq!(u32::from_le_bytes([d[24], d[25], d[26], d[27]]), 48000);
1430+ let mut pos = 12;
1431+ loop {
1432+ let id = &d[pos..pos + 4];
1433+ let len = u32::from_le_bytes([d[pos + 4], d[pos + 5], d[pos + 6], d[pos + 7]]) as usize;
1434+ if id == b"data" {
1435+ return d[pos + 8..pos + 8 + len]
1436+ .chunks_exact(2)
1437+ .map(|c| i16::from_le_bytes([c[0], c[1]]) as f32 / 32768.0)
1438+ .collect();
1439+ }
1440+ pos += 8 + len + (len & 1);
1441+ }
1442+}
1443+
1444+/// Windowed-sinc low-pass at `cutoff_hz` (48 kHz input), zero-phase.
1445+fn lowpass(x: &[f32], cutoff_hz: f64) -> Vec<f32> {
1446+ let taps = 127usize;
1447+ let c = cutoff_hz / 48000.0;
1448+ let h: Vec<f64> = (0..taps)
1449+ .map(|i| {
1450+ let m = i as f64 - (taps - 1) as f64 / 2.0;
1451+ let sinc = if m == 0.0 { 2.0 * c } else { (2.0 * std::f64::consts::PI * c * m).sin() / (std::f64::consts::PI * m) };
1452+ sinc * (0.54 - 0.46 * (2.0 * std::f64::consts::PI * i as f64 / (taps - 1) as f64).cos())
1453+ })
1454+ .collect();
1455+ let half = (taps - 1) / 2;
1456+ (0..x.len())
1457+ .map(|n| {
1458+ h.iter()
1459+ .enumerate()
1460+ .map(|(k, &hk)| {
1461+ let idx = n as isize + half as isize - k as isize;
1462+ if idx >= 0 && (idx as usize) < x.len() { hk * x[idx as usize] as f64 } else { 0.0 }
1463+ })
1464+ .sum::<f64>() as f32
1465+ })
1466+ .collect()
1467+}
1468+
1469+/// Encodes `pcm` NB or WB, decodes each packet with our decoder asserting the
1470+/// range-coder invariant, returns (decoded 48 kHz, packets, voiced frames,
1471+/// encoder delay).
1472+fn silk_roundtrip(pcm: &[f32], wideband: bool) -> (Vec<f32>, Vec<Vec<u8>>, usize, usize) {
1473+ let mut enc = SilkEncoder::new(wideband);
1474+ let mut dec = Decoder::new(48000, 1).unwrap();
1475+ let mut out = vec![0u8; 1500];
1476+ let mut buf = vec![0f32; 5760];
1477+ let mut decoded = Vec::new();
1478+ let mut packets = Vec::new();
1479+ let mut padded = pcm.to_vec();
1480+ padded.resize(pcm.len().div_ceil(960) * 960 + 960, 0.0);
1481+ for block in padded.chunks(960) {
1482+ let len = enc.encode_frame(block, &mut out).expect("silk encode");
1483+ let n = dec.decode_float(&out[..len], &mut buf).expect("silk decode");
1484+ assert_eq!(n, 960);
1485+ assert_eq!(dec.final_range(), enc.final_range(), "range state diverged");
1486+ decoded.extend_from_slice(&buf[..n]);
1487+ packets.push(out[..len].to_vec());
1488+ }
1489+ (decoded, packets, enc.voiced_frames(), enc.delay_samples())
1490+}
1491+
1492+/// Correlation after aligning `decoded` to `reference` at the best lag in
1493+/// `[0, max_lag)`; the peak must be interior (a peak at the search bound is
1494+/// no measurement).
1495+fn aligned_corr(reference: &[f32], decoded: &[f32], max_lag: usize) -> (f64, usize) {
1496+ let (mut best, mut best_lag) = (-1.0f64, 0usize);
1497+ for lag in 0..max_lag {
1498+ let c = correlation(reference, &decoded[lag..]);
1499+ if c > best {
1500+ best = c;
1501+ best_lag = lag;
1502+ }
1503+ }
1504+ assert!(best_lag + 1 < max_lag, "alignment peak at the search bound");
1505+ (best, best_lag)
1506+}
1507+
1508+#[test]
1509+fn silk_mono_nb_wb_roundtrip() {
1510+ let wav = fixture("wav16-mono-48000.wav");
1511+ let mut sources = vec![("synthetic", speech_like())];
1512+ if wav.exists() {
1513+ let w = read_wav_mono(&wav);
1514+ sources.push(("wav16-mono-48000", w[..w.len().min(96000)].to_vec()));
1515+ }
1516+ for (name, pcm) in &sources {
1517+ for wideband in [false, true] {
1518+ let (decoded, packets, voiced, delay) = silk_roundtrip(pcm, wideband);
1519+ let band = if wideband { 7000.0 } else { 3500.0 };
1520+ let reference = lowpass(pcm, band);
1521+ let (corr, lag) = aligned_corr(&reference, &decoded, 2000);
1522+ let bytes: usize = packets.iter().map(Vec::len).sum();
1523+ let tag = if wideband { "WB" } else { "NB" };
1524+ eprintln!(
1525+ "silk {name} {tag}: corr {corr:.4} at lag {lag} (resampler delay {delay}), voiced {voiced}/{} frames, {} kbps",
1526+ packets.len(),
1527+ bytes * 8 / (packets.len() * 20)
1528+ );
1529+ assert!(corr >= 0.8, "{name} {tag}: corr {corr:.4}");
1530+ assert!(lag >= delay, "{name} {tag}: aligned before the documented delay");
1531+ if *name == "synthetic" {
1532+ assert!(voiced > 0, "{name} {tag}: no frame coded with LTP");
1533+ }
1534+
1535+ // Reference oracle: the packets in an Ogg-Opus file decode cleanly.
1536+ if Command::new("ffmpeg").arg("-version").output().is_ok() {
1537+ let path = temp_path(&format!("silk-{name}-{tag}.opus"));
1538+ write_ogg_opus(&path, &packets, opus_head(1, None), 1, pcm.len());
1539+ let out = Command::new("ffmpeg")
1540+ .args(["-v", "warning", "-c:a", "libopus", "-i"])
1541+ .arg(&path)
1542+ .args(["-f", "null", "-"])
1543+ .output()
1544+ .unwrap();
1545+ let stderr = String::from_utf8_lossy(&out.stderr);
1546+ assert!(out.status.success() && stderr.trim().is_empty(), "{name} {tag}: ffmpeg: {stderr}");
1547+ let _ = fs::remove_file(&path);
1548+ }
1549+ }
1550+ }
1551+}