Noise-shaping quantiser, gain-offset rate control, LTP scale by gain
Browse files at this commitba4dea47d5058a7b72f022d8c1d6a0551ef099f4Parent: 68c7064- feat
- noise-shaping quantiser, gain-offset rate control, LTP scale by gain
2 changed files +344 -121
crates/ec-opus/src/silk_enc_write.rsmodified+263 -119
| @@ -8,10 +8,12 @@ | ||
| 8 | 8 | //! use *is* the real decoder's state — there is no encoder-side model of the |
| 9 | 9 | //! decoder that could drift. |
| 10 | 10 | //! |
| 11 | -//! The excitation quantiser is deliberately simple (open-loop LPC residual, | |
| 12 | -//! analysis-by-synthesis LTP codebook pick, nearest-level pulse rounding | |
| 13 | -//! under the decoder's seed/offset convention). Noise shaping (NSQ), 10/40/60 | |
| 14 | -//! ms frames and stereo are subtask D2b. | |
| 11 | +//! The excitation is coded by a noise-shaping quantiser: the decoder's | |
| 12 | +//! output error is fed back through short-term (bandwidth-expanded LPC), | |
| 13 | +//! harmonic and tilt shaping filters so the noise hides under the signal's | |
| 14 | +//! own spectrum, and a gain-offset rate loop sizes each packet against | |
| 15 | +//! [`SilkEncoder::set_bitrate`]. 10/40/60 ms frames and stereo are not | |
| 16 | +//! written yet. | |
| 15 | 17 | |
| 16 | 18 | // Same idiom as silk.rs: index loops mirror the decoder's position arithmetic. |
| 17 | 19 | #![allow(clippy::needless_range_loop)] |
| @@ -48,8 +50,31 @@ pub struct SilkEncoder { | ||
| 48 | 50 | final_range: u32, |
| 49 | 51 | voiced_frames: usize, |
| 50 | 52 | mirror_out: Vec<i16>, |
| 53 | + target_bps: Option<u32>, | |
| 54 | + /// Bits the rate loop owes (+) or banked (-) against the target. | |
| 55 | + reservoir: f32, | |
| 56 | + /// Noise-shaping state: output error, its AR-filtered form, and the | |
| 57 | + /// shaped quantiser error, for the last frame. | |
| 58 | + shape_d: Vec<f32>, | |
| 59 | + shape_u: Vec<f32>, | |
| 60 | + shape_gq: Vec<f32>, | |
| 51 | 61 | } |
| 52 | 62 | |
| 63 | +/// Noise-shaping constants: AR (denominator) and MA (numerator) bandwidth | |
| 64 | +/// expansions of the LPC, harmonic comb depth, voiced spectral tilt, and the | |
| 65 | +/// linear ratio of one gain-quantiser step (2^(1.365 dB / 6.02)). | |
| 66 | +const SHAPE_AR: f32 = 0.96; | |
| 67 | +const SHAPE_MA: f32 = 0.85; | |
| 68 | +const SHAPE_HARMONIC: f32 = 0.3; | |
| 69 | +const SHAPE_TILT: f32 = 0.1; | |
| 70 | +const GAIN_STEP: f32 = 1.1702; | |
| 71 | +/// Frames' worth of bits the rate loop may bank or borrow. | |
| 72 | +const RESERVOIR_FRAMES: f32 = 4.0; | |
| 73 | +/// Rate penalty per unit pulse magnitude in the quantiser's squared-error | |
| 74 | +/// cost: a dead zone that lets the rate loop keep finer gains for the same | |
| 75 | +/// bits (swept 0..2.5 on speech-like content; 1.5 maximised correlation). | |
| 76 | +const PULSE_LAMBDA: f32 = 1.5; | |
| 77 | + | |
| 53 | 78 | impl SilkEncoder { |
| 54 | 79 | /// `wideband`: 16 kHz internal rate (TOC config 9), else 8 kHz (config 1). |
| 55 | 80 | pub fn new(wideband: bool) -> SilkEncoder { |
| @@ -64,6 +89,11 @@ impl SilkEncoder { | ||
| 64 | 89 | final_range: 0, |
| 65 | 90 | voiced_frames: 0, |
| 66 | 91 | mirror_out: vec![0; 20 * 16], |
| 92 | + target_bps: None, | |
| 93 | + reservoir: 0.0, | |
| 94 | + shape_d: vec![0.0; 20 * fs_khz], | |
| 95 | + shape_u: vec![0.0; 20 * fs_khz], | |
| 96 | + shape_gq: vec![0.0; 20 * fs_khz], | |
| 67 | 97 | } |
| 68 | 98 | } |
| 69 | 99 | |
| @@ -78,6 +108,12 @@ impl SilkEncoder { | ||
| 78 | 108 | self.voiced_frames |
| 79 | 109 | } |
| 80 | 110 | |
| 111 | + /// Target bit rate in bits per second; `None` (the default) codes pulses | |
| 112 | + /// at unit excitation RMS with no rate loop. | |
| 113 | + pub fn set_bitrate(&mut self, bps: u32) { | |
| 114 | + self.target_bps = Some(bps); | |
| 115 | + } | |
| 116 | + | |
| 81 | 117 | /// Algorithmic delay in 48 kHz samples: the analysis resampler only |
| 82 | 118 | /// (the decoder adds its own resampler delay on the way back up). |
| 83 | 119 | pub fn delay_samples(&self) -> usize { |
| @@ -141,19 +177,6 @@ impl SilkEncoder { | ||
| 141 | 177 | // Pitch / LTP. |
| 142 | 178 | let pitch = estimate_pitch(&x, fs as i32, NB_SUBFR).filter(|p| p.voiced); |
| 143 | 179 | let voiced = pitch.is_some(); |
| 144 | - let vad_flag = vad.active || voiced; | |
| 145 | - let signal_type: i32 = if !vad_flag { 0 } else if voiced { 2 } else { 1 }; | |
| 146 | - let quant_offset_type = 0usize; | |
| 147 | - let offset = QUANTIZATION_OFFSETS_Q10[signal_type as usize >> 1][quant_offset_type] as f32 | |
| 148 | - / 1024.0; | |
| 149 | - | |
| 150 | - let ltp_scale_index = 0usize; | |
| 151 | - let ltp_scale = LTPSCALES_TABLE_Q14[ltp_scale_index] as f32 / 16384.0; | |
| 152 | - // `r`: LTP history in absolute sample units, past frame first (scaled | |
| 153 | - // by ltp_scale as the decoder scales its rebuilt history), then this | |
| 154 | - // frame's reconstructed residual as it is quantised. | |
| 155 | - let mut r: Vec<f32> = (-(n as isize)..0).map(|i| whiten(i) * ltp_scale).collect(); | |
| 156 | - r.resize(2 * n, 0.0); | |
| 157 | 180 | |
| 158 | 181 | let (lag_index, contour_index, pitch_l) = match &pitch { |
| 159 | 182 | Some(p) => { |
| @@ -178,46 +201,85 @@ impl SilkEncoder { | ||
| 178 | 201 | _ => <P_GAIN_VQ_2, |
| 179 | 202 | } |
| 180 | 203 | }; |
| 181 | - // Gains: the open-loop excitation RMS per subframe (LTP vector picked | |
| 182 | - // against the unquantised residual), so pulses land around unit | |
| 183 | - // magnitude. | |
| 204 | + | |
| 205 | + // Open-loop pass: the excitation RMS per subframe (best LTP vector | |
| 206 | + // against the unquantised residual) sets the gain targets; the tap sum | |
| 207 | + // of the best vector is the LTP gain that picks the scale index. | |
| 184 | 208 | let mut targets = [0i32; MAX_NB_SUBFR]; |
| 209 | + let mut ltp_gain = 0f32; | |
| 185 | 210 | { |
| 186 | - let mut r_ol = r.clone(); | |
| 187 | - r_ol[n..].copy_from_slice(&res); | |
| 211 | + let mut r_ol: Vec<f32> = (-(n as isize)..0).map(whiten).collect(); | |
| 212 | + r_ol.extend_from_slice(&res); | |
| 188 | 213 | for k in 0..NB_SUBFR { |
| 189 | - let e = if voiced { | |
| 214 | + let (e, gsum) = if voiced { | |
| 190 | 215 | LTP_GAIN_VQ_2 |
| 191 | 216 | .iter() |
| 192 | 217 | .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>() | |
| 218 | + let e = (0..sub) | |
| 219 | + .map(|i| (res[k * sub + i] - ltp_pred(&r_ol, b, k, i)).powi(2)) | |
| 220 | + .sum::<f32>(); | |
| 221 | + (e, b.iter().map(|&v| v as f32 / 128.0).sum::<f32>()) | |
| 199 | 222 | }) |
| 200 | - .fold(f32::INFINITY, f32::min) | |
| 223 | + .fold((f32::INFINITY, 0.0), |a, b| if b.0 < a.0 { b } else { a }) | |
| 201 | 224 | } else { |
| 202 | - (0..sub).map(|i| res[k * sub + i].powi(2)).sum() | |
| 225 | + ((0..sub).map(|i| res[k * sub + i].powi(2)).sum(), 0.0) | |
| 203 | 226 | }; |
| 227 | + ltp_gain = ltp_gain.max(gsum); | |
| 204 | 228 | let rms = (e / sub as f32).sqrt(); |
| 205 | 229 | targets[k] = ((rms * 65536.0).round() as i64).clamp(1, i32::MAX as i64) as i32; |
| 206 | 230 | } |
| 207 | 231 | } |
| 208 | - let (gain_idx, gains_q16) = | |
| 209 | - quantize_gains(&targets, &mut self.prev_gain_index, false, NB_SUBFR); | |
| 210 | - | |
| 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. | |
| 232 | + let vad_flag = vad.active || voiced; | |
| 233 | + let signal_type: i32 = if !vad_flag { 0 } else if voiced { 2 } else { 1 }; | |
| 234 | + // Over-unity LTP gain: scale the previous frame's history down so | |
| 235 | + // quantisation error does not build up through the pitch loop. | |
| 236 | + let ltp_scale_index = if !voiced { 0 } else if ltp_gain > 1.25 { 2 } else if ltp_gain > 1.0 { 1 } else { 0 }; | |
| 237 | + let ltp_scale = LTPSCALES_TABLE_Q14[ltp_scale_index] as f32 / 16384.0; | |
| 238 | + // Inactive or low-energy frames (and sparse voiced excitation) take the | |
| 239 | + // small quantisation offset; dense unvoiced excitation the large one. | |
| 240 | + let mean_rms = targets.iter().map(|&t| t as f32 / 65536.0).sum::<f32>() / NB_SUBFR as f32; | |
| 241 | + let quant_offset_type = usize::from(signal_type == 1 && mean_rms > 64.0); | |
| 242 | + let offset = QUANTIZATION_OFFSETS_Q10[signal_type as usize >> 1][quant_offset_type] as f32 | |
| 243 | + / 1024.0; | |
| 244 | + | |
| 245 | + // Noise shaping filters, from the bandwidth-expanded LPC: the output | |
| 246 | + // error d follows A(z/g2)(1 - tilt z^-1) / (A(z/g1)(1 - h z^-L)), i.e. | |
| 247 | + // the quantisation noise sits under the formants and, when voiced, | |
| 248 | + // under the harmonics, instead of being white at the decoder output. | |
| 249 | + let (g1, g2, tilt) = (SHAPE_AR, SHAPE_MA, if voiced { SHAPE_TILT } else { 0.0 }); | |
| 250 | + let c: Vec<f32> = a.iter().enumerate().map(|(j, &aj)| aj * g1.powi(j as i32 + 1)).collect(); | |
| 251 | + let b2: Vec<f32> = a.iter().enumerate().map(|(j, &aj)| aj * g2.powi(j as i32 + 1)).collect(); | |
| 252 | + // (1 - B2(z))(1 - tilt z^-1) = 1 - NB(z). | |
| 253 | + let mut nb = vec![0f32; order + 1]; | |
| 254 | + for j in 0..order { | |
| 255 | + nb[j] += b2[j]; | |
| 256 | + nb[j + 1] -= tilt * b2[j]; | |
| 257 | + } | |
| 258 | + nb[0] += tilt; | |
| 259 | + let harm = if voiced { SHAPE_HARMONIC * ltp_gain.clamp(0.0, 1.0) } else { 0.0 }; | |
| 260 | + | |
| 261 | + // `r`: LTP history in absolute sample units, past frame first (scaled | |
| 262 | + // by ltp_scale as the decoder scales its rebuilt history), then this | |
| 263 | + // frame's reconstructed residual as it is quantised. | |
| 264 | + let mut r: Vec<f32> = (-(n as isize)..0).map(|i| whiten(i) * ltp_scale).collect(); | |
| 265 | + r.resize(2 * n, 0.0); | |
| 217 | 266 | let seed_index = 0i32; |
| 218 | - let run = |per: usize| -> ([usize; MAX_NB_SUBFR], Vec<i32>, Vec<f32>, f32) { | |
| 267 | + | |
| 268 | + // Noise-shaping quantiser, closed loop: per subframe pick the LTP | |
| 269 | + // vector that best predicts the residual from the *reconstructed* | |
| 270 | + // history, then quantise sample by sample with the shaped output error | |
| 271 | + // fed back into the target, under the decoder's seed-driven sign flips. | |
| 272 | + let run = |per: usize, gains_q16: &[i32; MAX_NB_SUBFR]| -> Run { | |
| 219 | 273 | let cbk = codebook(per); |
| 220 | 274 | let mut r = r.clone(); |
| 275 | + let mut y = hist.clone(); | |
| 276 | + y.resize(2 * n, 0.0); | |
| 277 | + let mut d = self.shape_d.clone(); | |
| 278 | + d.resize(2 * n, 0.0); | |
| 279 | + let mut u = self.shape_u.clone(); | |
| 280 | + u.resize(2 * n, 0.0); | |
| 281 | + let mut gq = self.shape_gq.clone(); | |
| 282 | + gq.resize(2 * n, 0.0); | |
| 221 | 283 | let mut ltp_index = [0usize; MAX_NB_SUBFR]; |
| 222 | 284 | let mut pulses = vec![0i32; n]; |
| 223 | 285 | let mut seed = seed_index; |
| @@ -240,10 +302,18 @@ impl SilkEncoder { | ||
| 240 | 302 | } |
| 241 | 303 | } |
| 242 | 304 | let g = gains_q16[k] as f32 / 65536.0; |
| 305 | + let lag = pitch_l[k] as usize; | |
| 243 | 306 | for i in 0..sub { |
| 244 | 307 | let idx = k * sub + i; |
| 308 | + let p = n + idx; | |
| 309 | + let lpc: f32 = a.iter().enumerate().map(|(j, &aj)| aj * y[p - 1 - j]).sum(); | |
| 245 | 310 | let pred = if voiced { ltp_pred(&r, &cbk[ltp_index[k]], k, i) } else { 0.0 }; |
| 246 | - let e = (res[idx] - pred) / g; | |
| 311 | + let mut s: f32 = c.iter().enumerate().map(|(j, &cj)| cj * d[p - 1 - j]).sum(); | |
| 312 | + s -= nb.iter().enumerate().map(|(j, &bj)| bj * gq[p - 1 - j]).sum::<f32>(); | |
| 313 | + if harm > 0.0 { | |
| 314 | + s += harm * u[p - lag]; | |
| 315 | + } | |
| 316 | + let e = (x[idx] - lpc - pred + s) / g; | |
| 247 | 317 | seed = silk_rand(seed); |
| 248 | 318 | let flip = seed < 0; |
| 249 | 319 | let target = if flip { -e } else { e }; |
| @@ -251,95 +321,150 @@ impl SilkEncoder { | ||
| 251 | 321 | let lvl = p as f32 - LEVEL_ADJUST * (p.signum() as f32); |
| 252 | 322 | lvl + offset |
| 253 | 323 | }; |
| 254 | - let c = (target.round() as i32).clamp(-MAX_PULSE, MAX_PULSE); | |
| 255 | - let p = [c - 1, c, c + 1] | |
| 324 | + let c0 = (target.round() as i32).clamp(-MAX_PULSE, MAX_PULSE); | |
| 325 | + let pl = [c0 - 1, c0, c0 + 1] | |
| 256 | 326 | .into_iter() |
| 257 | 327 | .filter(|p| p.abs() <= MAX_PULSE) |
| 258 | 328 | .min_by(|&a, &b| { |
| 259 | - (recon(a) - target) | |
| 260 | - .abs() | |
| 261 | - .partial_cmp(&(recon(b) - target).abs()) | |
| 262 | - .unwrap() | |
| 329 | + let cost = |p: i32| (recon(p) - target).powi(2) + PULSE_LAMBDA * p.abs() as f32; | |
| 330 | + cost(a).partial_cmp(&cost(b)).unwrap() | |
| 263 | 331 | }) |
| 264 | 332 | .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); | |
| 333 | + pulses[idx] = pl; | |
| 334 | + seed = seed.wrapping_add(pl); | |
| 335 | + let exc = if flip { -recon(pl) } else { recon(pl) }; | |
| 336 | + r[p] = g * exc + pred; | |
| 337 | + y[p] = r[p] + lpc; | |
| 338 | + d[p] = y[p] - x[idx]; | |
| 339 | + gq[p] = d[p] - s; | |
| 340 | + u[p] = d[p] - c.iter().enumerate().map(|(j, &cj)| cj * d[p - 1 - j]).sum::<f32>(); | |
| 341 | + err += d[p] * d[p]; | |
| 270 | 342 | } |
| 271 | 343 | } |
| 272 | - (ltp_index, pulses, r, err) | |
| 344 | + Run { ltp_index, pulses, err, d, u, gq } | |
| 273 | 345 | }; |
| 346 | + | |
| 347 | + // One full trial at a common gain offset (in quantiser steps): returns | |
| 348 | + // the coded packet body so the rate loop can read its exact size. | |
| 274 | 349 | 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(); | |
| 280 | - | |
| 281 | - // --- Bitstream, in decode()'s order. --- | |
| 282 | - let enc = &mut self.range; | |
| 283 | - enc.reset(1275); | |
| 284 | - enc.enc_bit_logp(vad_flag, 1); // VAD flag | |
| 285 | - enc.enc_bit_logp(false, 1); // LBRR flag | |
| 286 | - // Frame type. | |
| 287 | - if vad_flag { | |
| 288 | - enc.enc_icdf(((signal_type << 1) | quant_offset_type as i32) as usize - 2, &TYPE_OFFSET_VAD_ICDF, 8); | |
| 289 | - } else { | |
| 290 | - enc.enc_icdf(quant_offset_type, &TYPE_OFFSET_NO_VAD_ICDF, 8); | |
| 291 | - } | |
| 292 | - // Gains: one frame per packet, so always independently coded. | |
| 293 | - enc.enc_icdf((gain_idx[0] as usize) >> 3, &GAIN_ICDF[signal_type as usize], 8); | |
| 294 | - enc.enc_icdf((gain_idx[0] as usize) & 7, &UNIFORM8_ICDF, 8); | |
| 295 | - for k in 1..NB_SUBFR { | |
| 296 | - enc.enc_icdf(gain_idx[k] as usize, &DELTA_GAIN_ICDF, 8); | |
| 297 | - } | |
| 298 | - // NLSFs. | |
| 299 | - let cb = nlsf_cb(wb); | |
| 300 | - let stage1_icdf = &cb.cb1_icdf[(signal_type as usize >> 1) * cb.n_vectors..]; | |
| 301 | - enc.enc_icdf(nq.indices[0] as usize, stage1_icdf, 8); | |
| 302 | - let (ec_ix, _) = crate::silk::nlsf_unpack(cb, nq.indices[0] as usize); | |
| 303 | - for i in 0..order { | |
| 304 | - let q = nq.indices[i + 1] as i32; | |
| 305 | - let icdf = &cb.ec_icdf[ec_ix[i] as usize..]; | |
| 306 | - if q <= -4 { | |
| 307 | - enc.enc_icdf(0, icdf, 8); | |
| 308 | - enc.enc_icdf((-4 - q) as usize, &NLSF_EXT_ICDF, 8); | |
| 309 | - } else if q >= 4 { | |
| 310 | - enc.enc_icdf(8, icdf, 8); | |
| 311 | - enc.enc_icdf((q - 4) as usize, &NLSF_EXT_ICDF, 8); | |
| 350 | + let mut trial = |step: i32| -> Trial { | |
| 351 | + let scale = GAIN_STEP.powi(step); | |
| 352 | + let mut t = targets; | |
| 353 | + for v in t.iter_mut() { | |
| 354 | + *v = ((*v as f64 * scale as f64).round() as i64).clamp(1, i32::MAX as i64) as i32; | |
| 355 | + } | |
| 356 | + let mut prev_gain_index = self.prev_gain_index; | |
| 357 | + let (gain_idx, gains_q16) = quantize_gains(&t, &mut prev_gain_index, false, NB_SUBFR); | |
| 358 | + let (per_index, run) = candidates | |
| 359 | + .iter() | |
| 360 | + .map(|&per| (per, run(per, &gains_q16))) | |
| 361 | + .min_by(|a, b| a.1.err.partial_cmp(&b.1.err).unwrap()) | |
| 362 | + .unwrap(); | |
| 363 | + | |
| 364 | + // --- Bitstream, in decode()'s order. --- | |
| 365 | + let enc = &mut self.range; | |
| 366 | + enc.reset(1275); | |
| 367 | + enc.enc_bit_logp(vad_flag, 1); // VAD flag | |
| 368 | + enc.enc_bit_logp(false, 1); // LBRR flag | |
| 369 | + // Frame type. | |
| 370 | + if vad_flag { | |
| 371 | + enc.enc_icdf(((signal_type << 1) | quant_offset_type as i32) as usize - 2, &TYPE_OFFSET_VAD_ICDF, 8); | |
| 312 | 372 | } else { |
| 313 | - enc.enc_icdf((q + 4) as usize, icdf, 8); | |
| 373 | + enc.enc_icdf(quant_offset_type, &TYPE_OFFSET_NO_VAD_ICDF, 8); | |
| 314 | 374 | } |
| 315 | - } | |
| 316 | - enc.enc_icdf(nq.interp_index as usize, &NLSF_INTERPOLATION_FACTOR_ICDF, 8); | |
| 317 | - // Pitch + LTP. | |
| 318 | - if voiced { | |
| 319 | - let half = fs as i32 >> 1; | |
| 320 | - enc.enc_icdf((lag_index / half) as usize, &PITCH_LAG_ICDF, 8); | |
| 321 | - let low_icdf: &[u8] = if wb { &UNIFORM8_ICDF } else { &UNIFORM4_ICDF }; | |
| 322 | - enc.enc_icdf((lag_index % half) as usize, low_icdf, 8); | |
| 323 | - let contour_icdf: &[u8] = if wb { &PITCH_CONTOUR_ICDF } else { &PITCH_CONTOUR_NB_ICDF }; | |
| 324 | - enc.enc_icdf(contour_index as usize, contour_icdf, 8); | |
| 325 | - enc.enc_icdf(per_index, <P_PER_INDEX_ICDF, 8); | |
| 326 | - let gain_icdf: &[u8] = match per_index { | |
| 327 | - 0 => <P_GAIN_ICDF_0, | |
| 328 | - 1 => <P_GAIN_ICDF_1, | |
| 329 | - _ => <P_GAIN_ICDF_2, | |
| 330 | - }; | |
| 331 | - for k in 0..NB_SUBFR { | |
| 332 | - enc.enc_icdf(ltp_index[k], gain_icdf, 8); | |
| 375 | + // Gains: one frame per packet, so always independently coded. | |
| 376 | + enc.enc_icdf((gain_idx[0] as usize) >> 3, &GAIN_ICDF[signal_type as usize], 8); | |
| 377 | + enc.enc_icdf((gain_idx[0] as usize) & 7, &UNIFORM8_ICDF, 8); | |
| 378 | + for k in 1..NB_SUBFR { | |
| 379 | + enc.enc_icdf(gain_idx[k] as usize, &DELTA_GAIN_ICDF, 8); | |
| 333 | 380 | } |
| 334 | - enc.enc_icdf(ltp_scale_index, <PSCALE_ICDF, 8); | |
| 335 | - self.voiced_frames += 1; | |
| 381 | + // NLSFs. | |
| 382 | + let cb = nlsf_cb(wb); | |
| 383 | + let stage1_icdf = &cb.cb1_icdf[(signal_type as usize >> 1) * cb.n_vectors..]; | |
| 384 | + enc.enc_icdf(nq.indices[0] as usize, stage1_icdf, 8); | |
| 385 | + let (ec_ix, _) = crate::silk::nlsf_unpack(cb, nq.indices[0] as usize); | |
| 386 | + for i in 0..order { | |
| 387 | + let q = nq.indices[i + 1] as i32; | |
| 388 | + let icdf = &cb.ec_icdf[ec_ix[i] as usize..]; | |
| 389 | + if q <= -4 { | |
| 390 | + enc.enc_icdf(0, icdf, 8); | |
| 391 | + enc.enc_icdf((-4 - q) as usize, &NLSF_EXT_ICDF, 8); | |
| 392 | + } else if q >= 4 { | |
| 393 | + enc.enc_icdf(8, icdf, 8); | |
| 394 | + enc.enc_icdf((q - 4) as usize, &NLSF_EXT_ICDF, 8); | |
| 395 | + } else { | |
| 396 | + enc.enc_icdf((q + 4) as usize, icdf, 8); | |
| 397 | + } | |
| 398 | + } | |
| 399 | + enc.enc_icdf(nq.interp_index as usize, &NLSF_INTERPOLATION_FACTOR_ICDF, 8); | |
| 400 | + // Pitch + LTP. (One frame per packet: the decoder only takes the | |
| 401 | + // lag-delta code path for the 2nd+ frame of a packet, so the | |
| 402 | + // absolute lag is always coded here.) | |
| 403 | + if voiced { | |
| 404 | + let half = fs as i32 >> 1; | |
| 405 | + enc.enc_icdf((lag_index / half) as usize, &PITCH_LAG_ICDF, 8); | |
| 406 | + let low_icdf: &[u8] = if wb { &UNIFORM8_ICDF } else { &UNIFORM4_ICDF }; | |
| 407 | + enc.enc_icdf((lag_index % half) as usize, low_icdf, 8); | |
| 408 | + let contour_icdf: &[u8] = if wb { &PITCH_CONTOUR_ICDF } else { &PITCH_CONTOUR_NB_ICDF }; | |
| 409 | + enc.enc_icdf(contour_index as usize, contour_icdf, 8); | |
| 410 | + enc.enc_icdf(per_index, <P_PER_INDEX_ICDF, 8); | |
| 411 | + let gain_icdf: &[u8] = match per_index { | |
| 412 | + 0 => <P_GAIN_ICDF_0, | |
| 413 | + 1 => <P_GAIN_ICDF_1, | |
| 414 | + _ => <P_GAIN_ICDF_2, | |
| 415 | + }; | |
| 416 | + for k in 0..NB_SUBFR { | |
| 417 | + enc.enc_icdf(run.ltp_index[k], gain_icdf, 8); | |
| 418 | + } | |
| 419 | + enc.enc_icdf(ltp_scale_index, <PSCALE_ICDF, 8); | |
| 420 | + } | |
| 421 | + enc.enc_icdf(seed_index as usize, &UNIFORM4_ICDF, 8); | |
| 422 | + encode_pulses(enc, &run.pulses, signal_type, quant_offset_type as i32); | |
| 423 | + enc.done(); | |
| 424 | + debug_assert!(!enc.error()); | |
| 425 | + let len = enc.range_bytes(); | |
| 426 | + Trial { bytes: enc.data()[..len].to_vec(), range: enc.range(), prev_gain_index, run } | |
| 427 | + }; | |
| 428 | + | |
| 429 | + // Rate control: a common gain offset moves every subframe's pulse | |
| 430 | + // magnitudes together; the reservoir carries each packet's miss. | |
| 431 | + let mut best = trial(0); | |
| 432 | + if let Some(bps) = self.target_bps { | |
| 433 | + let frame_bits = bps as f32 * 0.02; | |
| 434 | + let target = frame_bits + self.reservoir.clamp(-frame_bits, frame_bits); | |
| 435 | + let bits_of = |t: &Trial| t.bytes.len() as f32 * 8.0; | |
| 436 | + let (mut s0, mut b0) = (0i32, bits_of(&best)); | |
| 437 | + // Each quantiser step is ~0.227 bit per sample; a second trial | |
| 438 | + // corrects the slope from the first measurement. | |
| 439 | + let mut slope = 0.227 * n as f32; | |
| 440 | + for _ in 0..2 { | |
| 441 | + let step = s0 + ((b0 - target) / slope).round() as i32; | |
| 442 | + if step == s0 { | |
| 443 | + break; | |
| 444 | + } | |
| 445 | + let t = trial(step); | |
| 446 | + let b1 = bits_of(&t); | |
| 447 | + if (b1 - target).abs() < (b0 - target).abs() { | |
| 448 | + if b1 != b0 { | |
| 449 | + slope = ((b1 - b0) / (step - s0) as f32).abs().max(1.0); | |
| 450 | + } | |
| 451 | + best = t; | |
| 452 | + s0 = step; | |
| 453 | + b0 = b1; | |
| 454 | + } else { | |
| 455 | + break; | |
| 456 | + } | |
| 457 | + } | |
| 458 | + self.reservoir = (self.reservoir + frame_bits - b0).clamp(-RESERVOIR_FRAMES * frame_bits, RESERVOIR_FRAMES * frame_bits); | |
| 336 | 459 | } |
| 337 | - enc.enc_icdf(seed_index as usize, &UNIFORM4_ICDF, 8); | |
| 338 | - encode_pulses(enc, &pulses, signal_type, quant_offset_type as i32); | |
| 339 | - enc.done(); | |
| 340 | - debug_assert!(!enc.error()); | |
| 341 | - let len = enc.range_bytes(); | |
| 342 | - self.final_range = enc.range(); | |
| 460 | + let Trial { bytes, range, prev_gain_index, run } = best; | |
| 461 | + let len = bytes.len(); | |
| 462 | + self.prev_gain_index = prev_gain_index; | |
| 463 | + self.voiced_frames += usize::from(voiced); | |
| 464 | + self.final_range = range; | |
| 465 | + self.shape_d.copy_from_slice(&run.d[n..]); | |
| 466 | + self.shape_u.copy_from_slice(&run.u[n..]); | |
| 467 | + self.shape_gq.copy_from_slice(&run.gq[n..]); | |
| 343 | 468 | |
| 344 | 469 | let toc = if wb { 9u8 << 3 } else { 1u8 << 3 }; |
| 345 | 470 | if out.len() < 1 + len { |
| @@ -350,7 +475,7 @@ impl SilkEncoder { | ||
| 350 | 475 | ))); |
| 351 | 476 | } |
| 352 | 477 | out[0] = toc; |
| 353 | - out[1..1 + len].copy_from_slice(&enc.data()[..len]); | |
| 478 | + out[1..1 + len].copy_from_slice(&bytes); | |
| 354 | 479 | |
| 355 | 480 | // Replay through the mirror so the next frame sees decoder state. |
| 356 | 481 | let mut dec = RangeDecoder::new(&out[1..1 + len]); |
| @@ -361,6 +486,25 @@ impl SilkEncoder { | ||
| 361 | 486 | } |
| 362 | 487 | } |
| 363 | 488 | |
| 489 | +/// One closed-loop quantisation of a frame. | |
| 490 | +struct Run { | |
| 491 | + ltp_index: [usize; MAX_NB_SUBFR], | |
| 492 | + pulses: Vec<i32>, | |
| 493 | + err: f32, | |
| 494 | + d: Vec<f32>, | |
| 495 | + u: Vec<f32>, | |
| 496 | + gq: Vec<f32>, | |
| 497 | +} | |
| 498 | + | |
| 499 | +/// One coded candidate of a frame at a given gain offset. | |
| 500 | +struct Trial { | |
| 501 | + bytes: Vec<u8>, | |
| 502 | + range: u32, | |
| 503 | + prev_gain_index: i32, | |
| 504 | + run: Run, | |
| 505 | +} | |
| 506 | + | |
| 507 | + | |
| 364 | 508 | /// Bits an ICDF symbol costs, for choosing among equivalent codings. |
| 365 | 509 | fn icdf_bits(k: usize, icdf: &[u8]) -> f32 { |
| 366 | 510 | let hi = if k == 0 { 256 } else { icdf[k - 1] as u32 }; |
crates/ec-opus/tests/conformance.rsmodified+81 -2
| @@ -1469,8 +1469,11 @@ fn lowpass(x: &[f32], cutoff_hz: f64) -> Vec<f32> { | ||
| 1469 | 1469 | /// Encodes `pcm` NB or WB, decodes each packet with our decoder asserting the |
| 1470 | 1470 | /// range-coder invariant, returns (decoded 48 kHz, packets, voiced frames, |
| 1471 | 1471 | /// encoder delay). |
| 1472 | -fn silk_roundtrip(pcm: &[f32], wideband: bool) -> (Vec<f32>, Vec<Vec<u8>>, usize, usize) { | |
| 1472 | +fn silk_roundtrip(pcm: &[f32], wideband: bool, bitrate: Option<u32>) -> (Vec<f32>, Vec<Vec<u8>>, usize, usize) { | |
| 1473 | 1473 | let mut enc = SilkEncoder::new(wideband); |
| 1474 | + if let Some(bps) = bitrate { | |
| 1475 | + enc.set_bitrate(bps); | |
| 1476 | + } | |
| 1474 | 1477 | let mut dec = Decoder::new(48000, 1).unwrap(); |
| 1475 | 1478 | let mut out = vec![0u8; 1500]; |
| 1476 | 1479 | let mut buf = vec![0f32; 5760]; |
| @@ -1515,7 +1518,7 @@ fn silk_mono_nb_wb_roundtrip() { | ||
| 1515 | 1518 | } |
| 1516 | 1519 | for (name, pcm) in &sources { |
| 1517 | 1520 | for wideband in [false, true] { |
| 1518 | - let (decoded, packets, voiced, delay) = silk_roundtrip(pcm, wideband); | |
| 1521 | + let (decoded, packets, voiced, delay) = silk_roundtrip(pcm, wideband, None); | |
| 1519 | 1522 | let band = if wideband { 7000.0 } else { 3500.0 }; |
| 1520 | 1523 | let reference = lowpass(pcm, band); |
| 1521 | 1524 | let (corr, lag) = aligned_corr(&reference, &decoded, 2000); |
| @@ -1549,3 +1552,79 @@ fn silk_mono_nb_wb_roundtrip() { | ||
| 1549 | 1552 | } |
| 1550 | 1553 | } |
| 1551 | 1554 | } |
| 1555 | + | |
| 1556 | +/// Reference oracle decode of `packets` as Ogg-Opus, or `None` without ffmpeg. | |
| 1557 | +fn oracle_decode(name: &str, packets: &[Vec<u8>], samples: usize) -> Option<Vec<f32>> { | |
| 1558 | + if Command::new("ffmpeg").arg("-version").output().is_err() { | |
| 1559 | + return None; | |
| 1560 | + } | |
| 1561 | + let path = temp_path(&format!("{name}.opus")); | |
| 1562 | + write_ogg_opus(&path, packets, opus_head(1, None), 1, samples); | |
| 1563 | + let out = Command::new("ffmpeg") | |
| 1564 | + .args(["-v", "warning", "-c:a", "libopus", "-i"]) | |
| 1565 | + .arg(&path) | |
| 1566 | + .args(["-f", "null", "-"]) | |
| 1567 | + .output() | |
| 1568 | + .unwrap(); | |
| 1569 | + let stderr = String::from_utf8_lossy(&out.stderr); | |
| 1570 | + assert!(out.status.success() && stderr.trim().is_empty(), "{name}: ffmpeg: {stderr}"); | |
| 1571 | + let decoded = ffmpeg_decode(&path, 1); | |
| 1572 | + let _ = fs::remove_file(&path); | |
| 1573 | + decoded | |
| 1574 | +} | |
| 1575 | + | |
| 1576 | +fn silk_sources() -> Vec<(&'static str, Vec<f32>)> { | |
| 1577 | + let wav = fixture("wav16-mono-48000.wav"); | |
| 1578 | + let mut sources = vec![("synthetic", speech_like())]; | |
| 1579 | + if wav.exists() { | |
| 1580 | + let w = read_wav_mono(&wav); | |
| 1581 | + sources.push(("wav16-mono-48000", w[..w.len().min(96000)].to_vec())); | |
| 1582 | + } | |
| 1583 | + sources | |
| 1584 | +} | |
| 1585 | + | |
| 1586 | +/// Noise-shaped, closed-loop quantisation at a controlled 16 kbps WB beats | |
| 1587 | +/// the open-loop writer's quality at 27-50 kbps. | |
| 1588 | +#[test] | |
| 1589 | +fn silk_nsq_improves_quality_at_equal_rate() { | |
| 1590 | + let mut failures = Vec::new(); | |
| 1591 | + for (name, pcm) in &silk_sources() { | |
| 1592 | + let (decoded, packets, _, _) = silk_roundtrip(pcm, true, Some(16000)); | |
| 1593 | + let reference = lowpass(pcm, 7000.0); | |
| 1594 | + let (corr, lag) = aligned_corr(&reference, &decoded, 2000); | |
| 1595 | + let bytes: usize = packets.iter().map(Vec::len).sum(); | |
| 1596 | + let kbps = bytes as f64 * 8.0 / (packets.len() as f64 * 20.0); | |
| 1597 | + eprintln!("silk nsq {name} WB @16k: corr {corr:.4} at lag {lag}, {kbps:.1} kbps"); | |
| 1598 | + // The synthetic signal's noise tail (0.4 s of filtered noise) caps | |
| 1599 | + // at ~0.96 at this rate; its pulse-train part alone reaches 0.992. | |
| 1600 | + let floor = if *name == "synthetic" { 0.96 } else { 0.99 }; | |
| 1601 | + if corr < floor || kbps > 16.0 * 1.2 { | |
| 1602 | + failures.push(format!("{name}: corr {corr:.4} (floor {floor}) at {kbps:.1} kbps")); | |
| 1603 | + } | |
| 1604 | + if let Some(oracle) = oracle_decode(&format!("silk-nsq-{name}"), &packets, pcm.len()) { | |
| 1605 | + let (c, _) = aligned_corr(&oracle, &decoded, 2000); | |
| 1606 | + assert!(c >= 0.99, "{name}: our decode vs oracle decode corr {c:.4}"); | |
| 1607 | + } | |
| 1608 | + } | |
| 1609 | + assert!(failures.is_empty(), "{failures:?}"); | |
| 1610 | +} | |
| 1611 | + | |
| 1612 | +/// `set_bitrate` lands the coded rate within 20% of 8/12/16/24 kbps. | |
| 1613 | +#[test] | |
| 1614 | +fn silk_rate_control_tracks_target() { | |
| 1615 | + for (name, pcm) in &silk_sources() { | |
| 1616 | + for wideband in [false, true] { | |
| 1617 | + for kbps_target in [8u32, 12, 16, 24] { | |
| 1618 | + let (decoded, packets, _, _) = silk_roundtrip(pcm, wideband, Some(kbps_target * 1000)); | |
| 1619 | + let bytes: usize = packets.iter().map(Vec::len).sum(); | |
| 1620 | + let kbps = bytes as f64 * 8.0 / (packets.len() as f64 * 20.0); | |
| 1621 | + let reference = lowpass(pcm, if wideband { 7000.0 } else { 3500.0 }); | |
| 1622 | + let (corr, _) = aligned_corr(&reference, &decoded, 2000); | |
| 1623 | + let tag = if wideband { "WB" } else { "NB" }; | |
| 1624 | + eprintln!("silk rate {name} {tag} target {kbps_target}: {kbps:.2} kbps, corr {corr:.4}"); | |
| 1625 | + let ratio = kbps / kbps_target as f64; | |
| 1626 | + assert!((0.8..=1.2).contains(&ratio), "{name} {tag} target {kbps_target}: got {kbps:.2} kbps"); | |
| 1627 | + } | |
| 1628 | + } | |
| 1629 | + } | |
| 1630 | +} |