forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB00c1b3fTahinli2 months ago1999 commits

silk_enc_write.rs1450 lines, 53.5 KiBHistoryRawDownload
1//! SILK payload writer (subtask D2a): turns the analysis in [`crate::silk_enc`]
2//! into decodable SILK packets, NB (8 kHz), MB (12 kHz) or WB (16 kHz).
3//!
4//! Symbol order is exactly `silk::decode()`'s, and every decision is made
5//! against the decoder's own tables and reconstruction functions. The
6//! encoder keeps a [`SilkDecoder`] of its own and feeds it every packet it
7//! writes, so the synthesis history its LTP search and residual computation
8//! use *is* the real decoder's state — there is no encoder-side model of the
9//! decoder that could drift.
10//!
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`].
16
17// Same idiom as silk.rs: index loops mirror the decoder's position arithmetic.
18#![allow(clippy::needless_range_loop)]
19
20use ec_core::Result;
21
22use crate::range::{RangeDecoder, RangeEncoder};
23use crate::silk::tables::*;
24use crate::silk::{
25 MAX_LPC_ORDER, MAX_NB_SUBFR, PE_MAX_LAG_MS, PE_MIN_LAG_MS, SilkDecoder, decode_pitch, nlsf_cb,
26 nlsf2a, silk_rand,
27};
28use crate::silk_enc::{
29 NlsfQuant, Resampler48, Vad, estimate_pitch, lpc_analyze, quantize_gains, quantize_nlsf,
30};
31
32const SHELL_LEN: usize = 16;
33const LTP_ORDER: usize = 5;
34/// `QUANT_LEVEL_ADJUST_Q10` in `decode_core`: a non-zero pulse decodes 80/1024
35/// closer to zero than its integer value.
36const LEVEL_ADJUST: f32 = 80.0 / 1024.0;
37/// Largest pulse magnitude the shell coder's 10-level LSB escape can carry
38/// with 16 such pulses in one block.
39const MAX_PULSE: i32 = 1023;
40
41/// Per-frame SILK diagnostics captured at the end of the last `encode_inner`
42/// call, for the speech-quality diagnostic lane.
43#[derive(Clone, Debug, Default)]
44pub struct SilkFrameDiag {
45 pub voiced: bool,
46 pub signal_type: i32,
47 pub gain_idx: [i8; MAX_NB_SUBFR],
48 pub nb_subfr: usize,
49 pub lag_index: i32,
50 pub pitch_l: [i32; MAX_NB_SUBFR],
51 pub nlsf_interp: i32,
52 pub bytes: usize,
53 pub ltp_gain: f32,
54}
55
56/// A mono, 10/20/40/60 ms, NB/MB/WB SILK encoder.
57#[derive(Clone, Debug)]
58pub struct SilkEncoder {
59 fs_khz: usize,
60 resampler: Resampler48,
61 vad: Vad,
62 /// Replays every packet this encoder writes: its state is the decoder's.
63 mirror: SilkDecoder,
64 range: RangeEncoder,
65 prev_gain_index: i32,
66 final_range: u32,
67 /// The mirror decoder's range state after the last replay.
68 mirror_range: u32,
69 voiced_frames: usize,
70 mirror_out: Vec<i16>,
71 target_bps: Option<u32>,
72 /// Bits the rate loop owes (+) or banked (-) against the target.
73 reservoir: f32,
74 /// Last frame's gain-step operating point (libopus carries its gain
75 /// multiplier's effect through `LastGainIndex`; the x4 bound is per frame).
76 rate_step: i32,
77 rate_ema: f32,
78 /// Noise-shaping state: output error, its AR-filtered form, and the
79 /// shaped quantiser error, for the last frame.
80 shape_d: Vec<f32>,
81 shape_u: Vec<f32>,
82 shape_gq: Vec<f32>,
83 prev_pitch_lag: i32,
84 last_diag: SilkFrameDiag,
85}
86
87/// Noise-shaping constants: AR (denominator) and MA (numerator) bandwidth
88/// expansions of the LPC, harmonic comb depth, voiced spectral tilt, and the
89/// linear ratio of one gain-quantiser step (2^(1.365 dB / 6.02)).
90const SHAPE_AR: f32 = 0.96;
91const SHAPE_MA: f32 = 0.85;
92const SHAPE_HARMONIC: f32 = 0.3;
93const SHAPE_TILT: f32 = 0.1;
94const GAIN_STEP: f32 = 1.1702;
95/// Frames' worth of bits the rate loop may bank or borrow.
96const RESERVOIR_FRAMES: f32 = 4.0;
97/// libopus reservoir semantics for the SILK rate loop (see the loop).
98const LIBOPUS_RESERVOIR: bool = true;
99/// libopus `BITRESERVOIR_DECAY_TIME_MS`.
100const BITRESERVOIR_DECAY_TIME_MS: f32 = 500.0;
101/// libopus clamps `nBitsExceeded` to 0..10000.
102const MAX_BITS_EXCEEDED: f32 = 10000.0;
103/// Quantiser steps in libopus's x4 gain-multiplier bound (1024/256 in Q8).
104const MAX_GAIN_STEPS: i32 = 9;
105/// libopus `MIN_TARGET_RATE_BPS`.
106const MIN_TARGET_RATE_BPS: f32 = 5000.0;
107/// Upper bound on the carried operating point (a channel whose share is
108/// below the rate floor otherwise walks the gain up 9 steps a frame
109/// forever). Below, libopus's absolute x0.25 bound holds: a near-silent
110/// stereo side channel spending up to its share walked the gain down 30
111/// steps and drowned the mid (stereo 16k oracle corr .07).
112const MAX_RATE_STEP: i32 = 30;
113/// Start each frame's rate loop at the previous frame's operating point.
114const CARRY_RATE_STEP: bool = true;
115/// Operating-point smoothing: the loop starts each frame at the slow
116/// average of past steps (libopus derives its gains from the target rate
117/// before its x4-bounded loop; carrying the previous frame's exact point
118/// instead cost reelm@12k .05 corr).
119const CARRY_EMA: f32 = 1.0 / 16.0;
120const TARGET_FLOOR: bool = true;
121/// Rate penalty per unit pulse magnitude in the quantiser's squared-error
122/// cost: a dead zone that lets the rate loop keep finer gains for the same
123/// bits. NB 20 ms speech wants a smaller dead zone; 10 ms WB needs a
124/// slightly smaller one than the 10 ms NB/MB rows to keep upper-band pulses.
125const PULSE_LAMBDA: f32 = 1.5;
126
127impl SilkEncoder {
128 /// `wideband`: 16 kHz internal rate (TOC config 9), else 8 kHz (config 1).
129 pub fn new(wideband: bool) -> SilkEncoder {
130 Self::with_fs_khz(if wideband { 16 } else { 8 })
131 }
132
133 /// Mediumband, 12 kHz internal rate (TOC config 5).
134 pub fn new_mediumband() -> SilkEncoder {
135 Self::with_fs_khz(12)
136 }
137
138 fn with_fs_khz(fs_khz: usize) -> SilkEncoder {
139 debug_assert!(matches!(fs_khz, 8 | 12 | 16));
140 SilkEncoder {
141 fs_khz,
142 resampler: Resampler48::new(fs_khz as u32),
143 vad: Vad::new(),
144 mirror: SilkDecoder::new(fs_khz as u32 * 1000, 1),
145 range: RangeEncoder::new(),
146 prev_gain_index: 10,
147 final_range: 0,
148 mirror_range: 0,
149 voiced_frames: 0,
150 prev_pitch_lag: 0,
151 mirror_out: vec![0; 20 * 16],
152 target_bps: None,
153 reservoir: 0.0,
154 rate_step: 0,
155 rate_ema: 0.0,
156 shape_d: vec![0.0; 20 * fs_khz],
157 shape_u: vec![0.0; 20 * fs_khz],
158 shape_gq: vec![0.0; 20 * fs_khz],
159 last_diag: SilkFrameDiag::default(),
160 }
161 }
162
163 /// The range coder state after the last packet; a conformant decoder
164 /// reports the same value after decoding it.
165 pub fn final_range(&self) -> u32 {
166 self.final_range
167 }
168
169 /// Frames so far coded with the long-term (pitch) predictor.
170 pub fn voiced_frames(&self) -> usize {
171 self.voiced_frames
172 }
173
174 /// Per-frame diagnostics captured at the end of the last `encode_inner`
175 /// call.
176 pub fn last_diag(&self) -> &SilkFrameDiag {
177 &self.last_diag
178 }
179
180 /// Target bit rate in bits per second; `None` (the default) codes pulses
181 /// at unit excitation RMS with no rate loop.
182 pub fn set_bitrate(&mut self, bps: u32) {
183 self.target_bps = Some(bps);
184 }
185
186 fn reset_state(&mut self) {
187 *self = Self::with_fs_khz(self.fs_khz);
188 }
189
190 /// Algorithmic delay in 48 kHz samples: the analysis resampler only
191 /// (the decoder adds its own resampler delay on the way back up).
192 pub fn delay_samples(&self) -> usize {
193 self.resampler.delay_samples()
194 }
195
196 /// Encodes 960 mono 48 kHz samples as one 20 ms code-0 packet in `out`,
197 /// returning its length.
198 pub fn encode_frame(&mut self, pcm48: &[f32], out: &mut [u8]) -> Result<usize> {
199 self.encode_frame_ms(pcm48, out, 20)
200 }
201
202 /// Encodes 10, 20, 40 or 60 ms of mono 48 kHz samples as one code-0
203 /// packet in `out`, returning its length.
204 pub fn encode_frame_ms(
205 &mut self,
206 pcm48: &[f32],
207 out: &mut [u8],
208 frame_ms: usize,
209 ) -> Result<usize> {
210 let frames_per_packet = match frame_ms {
211 10 | 20 => 1usize,
212 40 => 2,
213 60 => 3,
214 _ => {
215 return Err(ec_core::Error::unsupported(
216 format!("silk encode frame of {frame_ms} ms"),
217 "SILK encoder writes 10, 20, 40 or 60 ms packets",
218 ));
219 }
220 };
221 assert_eq!(
222 pcm48.len(),
223 48 * frame_ms,
224 "SilkEncoder input is 48 kHz mono"
225 );
226 let mut frames = Vec::with_capacity(frames_per_packet);
227 let sub_ms = if frame_ms == 10 { 10 } else { 20 };
228 let mut prev_signal_type = 0;
229 for i in 0..frames_per_packet {
230 let from = i * sub_ms * 48;
231 let to = from + sub_ms * 48;
232 let conditional = i > 0;
233 let trial = self.encode_inner(
234 &pcm48[from..to],
235 sub_ms,
236 None,
237 conditional,
238 prev_signal_type,
239 frames_per_packet == 1,
240 )?;
241 prev_signal_type = trial.signal_type;
242 frames.push(trial);
243 }
244 if frames.iter().any(|frame| frame.voiced) {
245 self.voiced_frames += 1;
246 }
247 self.range.reset(1275);
248 let refs: Vec<&Trial> = frames.iter().collect();
249 write_packet_header(&mut self.range, &refs);
250 prev_signal_type = 0;
251 for (i, frame) in frames.iter().enumerate() {
252 write_frame_data(&mut self.range, frame, i > 0, prev_signal_type);
253 prev_signal_type = frame.signal_type;
254 }
255 self.range.done();
256 debug_assert!(!self.range.error());
257 let len = self.range.range_bytes();
258 self.final_range = self.range.range();
259 let duration = match frame_ms {
260 10 => 0u8,
261 20 => 1,
262 40 => 2,
263 60 => 3,
264 _ => unreachable!(),
265 };
266 let base = match self.fs_khz {
267 8 => 0u8,
268 12 => 4,
269 _ => 8,
270 };
271 let toc = (base + duration) << 3;
272 if out.len() < 1 + len {
273 return Err(ec_core::Error::corrupt(format!(
274 "silk encode: packet needs {} bytes, buffer holds {}",
275 1 + len,
276 out.len()
277 )));
278 }
279 out[0] = toc;
280 out[1..1 + len].copy_from_slice(&self.range.data()[..len]);
281 self.replay_ms(&out[1..1 + len], frame_ms)?;
282 debug_assert_eq!(self.mirror_range, self.final_range);
283 Ok(1 + len)
284 }
285
286 /// The SILK layer of a hybrid packet: codes one mono 48 kHz frame into
287 /// `enc`, the packet's shared range coder (SILK symbols first; the CELT
288 /// layer continues in the same coder), without finishing it. The caller
289 /// must [`SilkEncoder::replay_hybrid`] the finished payload so this
290 /// encoder's decoder mirror advances.
291 pub fn encode_hybrid_ms(
292 &mut self,
293 pcm48: &[f32],
294 enc: &mut RangeEncoder,
295 frame_ms: usize,
296 ) -> Result<()> {
297 let trial = self.encode_inner(pcm48, frame_ms, Some(enc), false, 0, true)?;
298 self.voiced_frames += usize::from(trial.voiced);
299 Ok(())
300 }
301
302 /// Decodes a finished hybrid payload (TOC stripped) through the mirror
303 /// decoder so the next frame predicts from the decoder's state.
304 pub fn replay_hybrid(&mut self, payload: &[u8], frame_ms: usize) -> Result<()> {
305 self.replay_ms(payload, frame_ms)
306 }
307
308 fn replay_ms(&mut self, payload: &[u8], frame_ms: usize) -> Result<()> {
309 let fs = self.fs_khz;
310 let mut dec = RangeDecoder::new(payload);
311 let total = frame_ms * fs;
312 if self.mirror_out.len() < total {
313 self.mirror_out.resize(total, 0);
314 }
315 let mut done = 0usize;
316 let mut first = true;
317 while done < total {
318 let n = self.mirror.decode(
319 &mut dec,
320 &mut self.mirror_out[done..],
321 frame_ms,
322 fs as u32 * 1000,
323 1,
324 first,
325 )?;
326 if n == 0 {
327 break;
328 }
329 done += n;
330 first = false;
331 }
332 self.mirror_range = dec.range();
333 Ok(())
334 }
335
336 /// Analysis, closed-loop quantisation and rate control of one frame; the
337 /// returned trial's `bytes` are the standalone SILK payload (TOC
338 /// excluded). With `shared`, the chosen frame's symbols are also written
339 /// into that coder (the hybrid path).
340 fn encode_inner(
341 &mut self,
342 pcm48: &[f32],
343 frame_ms: usize,
344 shared: Option<&mut RangeEncoder>,
345 conditional: bool,
346 prev_signal_type: i32,
347 single_frame_packet: bool,
348 ) -> Result<Trial> {
349 assert!(
350 matches!(frame_ms, 10 | 20),
351 "SilkEncoder codes 10 or 20 ms mono frames"
352 );
353 assert_eq!(
354 pcm48.len(),
355 48 * frame_ms,
356 "SilkEncoder input is 48 kHz mono"
357 );
358 let fs = self.fs_khz;
359 let order = if fs == 16 { MAX_LPC_ORDER } else { 10 };
360 let nb_subfr = frame_ms / 5;
361 let n = frame_ms * fs;
362 let sub = 5 * fs;
363 if self.shape_d.len() != n {
364 self.shape_d.resize(n, 0.0);
365 self.shape_u.resize(n, 0.0);
366 self.shape_gq.resize(n, 0.0);
367 }
368 let x: Vec<f32> = self
369 .resampler
370 .process(pcm48)
371 .iter()
372 .map(|v| v * 32768.0)
373 .collect();
374 let vad = self.vad.analyze(&x);
375
376 // LPC -> NLSF indices -> the decoder's dequantised filter.
377 let nlsf_target = lpc_analyze(&x, order)
378 .map(|a| a.nlsf_q15)
379 .unwrap_or_else(|| {
380 let mut flat = [0i16; MAX_LPC_ORDER];
381 for (i, v) in flat.iter_mut().enumerate().take(order) {
382 *v = ((i + 1) * 32768 / (order + 1)) as i16;
383 }
384 flat
385 });
386 let wb = fs == 16;
387 let nq = quantize_nlsf(&nlsf_target[..order], wb);
388 let a_q12 = nlsf2a(&nq.nlsf_q15[..order], order);
389 let a: Vec<f32> = a_q12[..order].iter().map(|&v| v as f32 / 4096.0).collect();
390
391 // Residual of this frame with the decoder's real past output as filter
392 // memory, and the whitened past output itself (the LTP history the
393 // decoder rebuilds at subframe 0).
394 // (Empty before the first packet: the decoder's history is all zero.)
395 let mut hist: Vec<f32> = self.mirror.history().iter().map(|&v| v as f32).collect();
396 hist.resize(n, 0.0);
397 let sample = |i: isize| -> f32 {
398 if i < 0 {
399 hist[(n as isize + i) as usize]
400 } else {
401 x[i as usize]
402 }
403 };
404 let whiten = |i: isize| -> f32 {
405 let mut acc = sample(i);
406 for (j, &aj) in a.iter().enumerate() {
407 let idx = i - 1 - j as isize;
408 if idx >= -(n as isize) {
409 acc -= aj * sample(idx);
410 }
411 }
412 acc
413 };
414 let res: Vec<f32> = (0..n as isize).map(whiten).collect();
415
416 // Pitch / LTP.
417 let prior = if self.prev_pitch_lag > 0 { Some(self.prev_pitch_lag) } else { None };
418 let pitch = estimate_pitch(&x, fs as i32, nb_subfr, prior).filter(|p| p.voiced);
419 if let Some(p) = &pitch {
420 self.prev_pitch_lag = p.lag;
421 } else {
422 self.prev_pitch_lag = 0;
423 }
424 let voiced = pitch.is_some();
425
426 let (lag_index, contour_index, pitch_l) = match &pitch {
427 Some(p) => {
428 let max_index = (PE_MAX_LAG_MS - PE_MIN_LAG_MS) * fs as i32 - 1;
429 let li = p.lag_index.clamp(0, max_index);
430 (
431 li,
432 p.contour_index,
433 decode_pitch(li, p.contour_index, fs as i32, nb_subfr),
434 )
435 }
436 None => (0, 0, [0; MAX_NB_SUBFR]),
437 };
438 let ltp_pred = |r: &[f32], b: &[i8; 5], k: usize, i: usize| -> f32 {
439 let pos = n + k * sub + i - pitch_l[k] as usize + LTP_ORDER / 2;
440 let mut acc = 0f32;
441 for (j, &bj) in b.iter().enumerate() {
442 acc += bj as f32 / 128.0 * r[pos - j];
443 }
444 acc
445 };
446 let codebook = |per: usize| -> &'static [[i8; 5]] {
447 match per {
448 0 => &LTP_GAIN_VQ_0,
449 1 => &LTP_GAIN_VQ_1,
450 _ => &LTP_GAIN_VQ_2,
451 }
452 };
453
454 // Open-loop pass: the excitation RMS per subframe (best LTP vector
455 // against the unquantised residual) sets the gain targets; the tap sum
456 // of the best vector is the LTP gain that picks the scale index.
457 let mut targets = [0i32; MAX_NB_SUBFR];
458 let mut ltp_gain = 0f32;
459 {
460 let mut r_ol: Vec<f32> = (-(n as isize)..0).map(whiten).collect();
461 r_ol.extend_from_slice(&res);
462 for k in 0..nb_subfr {
463 let (e, gsum) = if voiced {
464 LTP_GAIN_VQ_2
465 .iter()
466 .map(|b| {
467 let e = (0..sub)
468 .map(|i| (res[k * sub + i] - ltp_pred(&r_ol, b, k, i)).powi(2))
469 .sum::<f32>();
470 (e, b.iter().map(|&v| v as f32 / 128.0).sum::<f32>())
471 })
472 .fold((f32::INFINITY, 0.0), |a, b| if b.0 < a.0 { b } else { a })
473 } else {
474 ((0..sub).map(|i| res[k * sub + i].powi(2)).sum(), 0.0)
475 };
476 ltp_gain = ltp_gain.max(gsum);
477 let rms = (e / sub as f32).sqrt();
478 targets[k] = ((rms * 65536.0).round() as i64).clamp(1, i32::MAX as i64) as i32;
479 }
480 }
481 let vad_flag = vad.active || voiced;
482 let signal_type: i32 = if !vad_flag {
483 0
484 } else if voiced {
485 2
486 } else {
487 1
488 };
489 // Over-unity LTP gain: scale the previous frame's history down so
490 // quantisation error does not build up through the pitch loop.
491 let ltp_scale_index = if !voiced {
492 0
493 } else if ltp_gain > 1.25 {
494 2
495 } else if ltp_gain > 1.0 {
496 1
497 } else {
498 0
499 };
500 let ltp_scale = LTPSCALES_TABLE_Q14[ltp_scale_index] as f32 / 16384.0;
501 // Inactive or low-energy frames (and sparse voiced excitation) take the
502 // small quantisation offset; dense unvoiced excitation the large one.
503 let mean_rms = targets[..nb_subfr]
504 .iter()
505 .map(|&t| t as f32 / 65536.0)
506 .sum::<f32>()
507 / nb_subfr as f32;
508 let quant_offset_type = usize::from(signal_type == 1 && mean_rms > 64.0);
509 let offset =
510 QUANTIZATION_OFFSETS_Q10[signal_type as usize >> 1][quant_offset_type] as f32 / 1024.0;
511
512 // Noise shaping filters, from the bandwidth-expanded LPC: the output
513 // error d follows A(z/g2)(1 - tilt z^-1) / (A(z/g1)(1 - h z^-L)), i.e.
514 // the quantisation noise sits under the formants and, when voiced,
515 // under the harmonics, instead of being white at the decoder output.
516 let (g1, g2, tilt) = (SHAPE_AR, SHAPE_MA, if voiced { SHAPE_TILT } else { 0.0 });
517 let c: Vec<f32> = a
518 .iter()
519 .enumerate()
520 .map(|(j, &aj)| aj * g1.powi(j as i32 + 1))
521 .collect();
522 let b2: Vec<f32> = a
523 .iter()
524 .enumerate()
525 .map(|(j, &aj)| aj * g2.powi(j as i32 + 1))
526 .collect();
527 // (1 - B2(z))(1 - tilt z^-1) = 1 - NB(z).
528 let mut nb = vec![0f32; order + 1];
529 for j in 0..order {
530 nb[j] += b2[j];
531 nb[j + 1] -= tilt * b2[j];
532 }
533 nb[0] += tilt;
534 let harm = if voiced {
535 SHAPE_HARMONIC * ltp_gain.clamp(0.0, 1.0)
536 } else {
537 0.0
538 };
539
540 // `r`: LTP history in absolute sample units, past frame first (scaled
541 // by ltp_scale as the decoder scales its rebuilt history), then this
542 // frame's reconstructed residual as it is quantised.
543 let mut r: Vec<f32> = (-(n as isize)..0).map(|i| whiten(i) * ltp_scale).collect();
544 r.resize(2 * n, 0.0);
545 let seed_index = 0i32;
546
547 // Noise-shaping quantiser, closed loop: per subframe pick the LTP
548 // vector that best predicts the residual from the *reconstructed*
549 // history, then quantise sample by sample with the shaped output error
550 // fed back into the target, under the decoder's seed-driven sign flips.
551 let pulse_lambda = match (single_frame_packet, frame_ms, fs) {
552 (true, 20, 8) => 1.25,
553 (_, 10, 16) => 1.45,
554 _ => PULSE_LAMBDA,
555 };
556 let run = |per: usize, gains_q16: &[i32; MAX_NB_SUBFR]| -> Run {
557 let cbk = codebook(per);
558 let mut r = r.clone();
559 let mut y = hist.clone();
560 y.resize(2 * n, 0.0);
561 let mut d = self.shape_d.clone();
562 d.resize(2 * n, 0.0);
563 let mut u = self.shape_u.clone();
564 u.resize(2 * n, 0.0);
565 let mut gq = self.shape_gq.clone();
566 gq.resize(2 * n, 0.0);
567 let mut ltp_index = [0usize; MAX_NB_SUBFR];
568 let mut pulses = vec![0i32; n];
569 let mut seed = seed_index;
570 let mut err = 0f32;
571 for k in 0..nb_subfr {
572 if voiced {
573 // In-subframe taps (lag shorter than the subframe) see the
574 // unquantised residual as a stand-in.
575 let mut r_ol = r.clone();
576 r_ol[n + k * sub..n + (k + 1) * sub]
577 .copy_from_slice(&res[k * sub..(k + 1) * sub]);
578 let mut best = f32::INFINITY;
579 for (v, b) in cbk.iter().enumerate() {
580 let e: f32 = (0..sub)
581 .map(|i| (res[k * sub + i] - ltp_pred(&r_ol, b, k, i)).powi(2))
582 .sum();
583 if e < best {
584 best = e;
585 ltp_index[k] = v;
586 }
587 }
588 }
589 let g = gains_q16[k] as f32 / 65536.0;
590 let lag = pitch_l[k] as usize;
591 for i in 0..sub {
592 let idx = k * sub + i;
593 let p = n + idx;
594 let lpc: f32 = a.iter().enumerate().map(|(j, &aj)| aj * y[p - 1 - j]).sum();
595 let pred = if voiced {
596 ltp_pred(&r, &cbk[ltp_index[k]], k, i)
597 } else {
598 0.0
599 };
600 let mut s: f32 = c.iter().enumerate().map(|(j, &cj)| cj * d[p - 1 - j]).sum();
601 s -= nb
602 .iter()
603 .enumerate()
604 .map(|(j, &bj)| bj * gq[p - 1 - j])
605 .sum::<f32>();
606 if harm > 0.0 {
607 s += harm * u[p - lag];
608 }
609 let e = (x[idx] - lpc - pred + s) / g;
610 seed = silk_rand(seed);
611 let flip = seed < 0;
612 let target = if flip { -e } else { e };
613 let recon = |p: i32| -> f32 {
614 let lvl = p as f32 - LEVEL_ADJUST * (p.signum() as f32);
615 lvl + offset
616 };
617 let c0 = (target.round() as i32).clamp(-MAX_PULSE, MAX_PULSE);
618 let pl = [c0 - 1, c0, c0 + 1]
619 .into_iter()
620 .filter(|p| p.abs() <= MAX_PULSE)
621 .min_by(|&a, &b| {
622 let cost = |p: i32| {
623 (recon(p) - target).powi(2) + pulse_lambda * p.abs() as f32
624 };
625 cost(a).partial_cmp(&cost(b)).unwrap()
626 })
627 .unwrap();
628 pulses[idx] = pl;
629 seed = seed.wrapping_add(pl);
630 let exc = if flip { -recon(pl) } else { recon(pl) };
631 r[p] = g * exc + pred;
632 y[p] = r[p] + lpc;
633 d[p] = y[p] - x[idx];
634 gq[p] = d[p] - s;
635 u[p] = d[p]
636 - c.iter()
637 .enumerate()
638 .map(|(j, &cj)| cj * d[p - 1 - j])
639 .sum::<f32>();
640 err += d[p] * d[p];
641 }
642 }
643 Run {
644 ltp_index,
645 pulses,
646 err,
647 d,
648 u,
649 gq,
650 }
651 };
652
653 let fs = self.fs_khz;
654 // One full trial at a common gain offset (in quantiser steps): returns
655 // the coded packet body so the rate loop can read its exact size.
656 let candidates: Vec<usize> = if voiced { vec![0, 1, 2] } else { vec![0] };
657 let mut trial = |step: i32| -> Trial {
658 let scale = GAIN_STEP.powi(step);
659 let mut t = targets;
660 for v in t.iter_mut() {
661 *v = ((*v as f64 * scale as f64).round() as i64).clamp(1, i32::MAX as i64) as i32;
662 }
663 let mut prev_gain_index = self.prev_gain_index;
664 let (gain_idx, gains_q16) =
665 quantize_gains(&t, &mut prev_gain_index, conditional, nb_subfr);
666 let (per_index, run) = candidates
667 .iter()
668 .map(|&per| (per, run(per, &gains_q16)))
669 .min_by(|a, b| a.1.err.partial_cmp(&b.1.err).unwrap())
670 .unwrap();
671
672 let mut trial = Trial {
673 bytes: Vec::new(),
674 range: 0,
675 prev_gain_index,
676 gain_idx,
677 per_index,
678 run,
679 vad_flag,
680 signal_type,
681 quant_offset_type,
682 wb,
683 order,
684 nb_subfr,
685 fs,
686 lag_index,
687 contour_index,
688 voiced,
689 ltp_scale_index,
690 nq: nq.clone(),
691 ltp_gain,
692 seed_index,
693 };
694 let enc = &mut self.range;
695 enc.reset(1275);
696 write_packet_header(enc, &[&trial]);
697 write_frame_data(enc, &trial, conditional, prev_signal_type);
698 enc.done();
699 debug_assert!(!enc.error());
700 let len = enc.range_bytes();
701 trial.bytes = enc.data()[..len].to_vec();
702 trial.range = enc.range();
703 trial
704 };
705
706 // Rate control: a common gain offset moves every subframe's pulse
707 // magnitudes together; the reservoir carries each packet's miss.
708 let mut best = trial(if CARRY_RATE_STEP { self.rate_step } else { 0 });
709 if let Some(bps) = self.target_bps {
710 let frame_bits = bps as f32 * frame_ms as f32 / 1000.0;
711 // libopus (enc_API.c): only overspend is remembered
712 // (`nBitsExceeded`, clamped 0..10000 bits) and it is repaid at
713 // `frame_ms / BITRESERVOIR_DECAY_TIME_MS` per frame, never all
714 // at once. Repaying a whole frame's debt in one frame starved
715 // voiced frames to 14-16 B with gains[0] at the ceiling (lane
716 // opus-silkq r2: 24 packets carried ~100% of the 12k error).
717 let target = if LIBOPUS_RESERVOIR {
718 // Credit is deliberately not banked: banking it (spend
719 // 2x, then starve) brought the 12k bursts back (err_ratio
720 // 3.2 -> 11.6 on the speech gate).
721 // libopus then limits TargetRate_bps to MIN_TARGET_RATE_BPS.
722 let t = frame_bits - self.reservoir.max(0.0) * frame_ms as f32 / BITRESERVOIR_DECAY_TIME_MS;
723 if TARGET_FLOOR { t.max(MIN_TARGET_RATE_BPS * frame_ms as f32 / 1000.0) } else { t }
724 } else {
725 frame_bits + self.reservoir.clamp(-frame_bits, frame_bits)
726 };
727 let bits_of = |t: &Trial| t.bytes.len() as f32 * 8.0;
728 let start = if CARRY_RATE_STEP { self.rate_step } else { 0 };
729 let (mut s0, mut b0) = (start, bits_of(&best));
730 // Each quantiser step is ~0.227 bit per sample; a second trial
731 // corrects the slope from the first measurement.
732 let mut slope = 0.227 * n as f32;
733 for _ in 0..2 {
734 let mut step = s0 + ((b0 - target) / slope).round() as i32;
735 if LIBOPUS_RESERVOIR {
736 // libopus bounds gainMult_Q8 to 64..1024 (x0.25..x4).
737 step = step.clamp(start - MAX_GAIN_STEPS, start + MAX_GAIN_STEPS);
738 }
739 if step == s0 {
740 break;
741 }
742 let t = trial(step);
743 let b1 = bits_of(&t);
744 if (b1 - target).abs() < (b0 - target).abs() {
745 if b1 != b0 {
746 slope = ((b1 - b0) / (step - s0) as f32).abs().max(1.0);
747 }
748 best = t;
749 s0 = step;
750 b0 = b1;
751 } else {
752 break;
753 }
754 }
755 self.rate_ema += (s0 as f32 - self.rate_ema) * CARRY_EMA;
756 self.rate_step = (self.rate_ema.round() as i32).clamp(-MAX_RATE_STEP, MAX_RATE_STEP);
757 self.reservoir = if LIBOPUS_RESERVOIR {
758 // Debt only (bits over the frame's share), as `nBitsExceeded`.
759 (self.reservoir + b0 - frame_bits).clamp(0.0, MAX_BITS_EXCEEDED)
760 } else {
761 (self.reservoir + frame_bits - b0).clamp(
762 -RESERVOIR_FRAMES * frame_bits,
763 RESERVOIR_FRAMES * frame_bits,
764 )
765 };
766 }
767 if let Some(enc) = shared {
768 let trial_ref = &best;
769 write_packet_header(enc, &[trial_ref]);
770 write_frame_data(enc, trial_ref, conditional, prev_signal_type);
771 }
772 self.prev_gain_index = best.prev_gain_index;
773 self.shape_d.copy_from_slice(&best.run.d[n..]);
774 self.shape_u.copy_from_slice(&best.run.u[n..]);
775 self.shape_gq.copy_from_slice(&best.run.gq[n..]);
776 self.last_diag = SilkFrameDiag {
777 voiced: best.voiced,
778 signal_type: best.signal_type,
779 gain_idx: best.gain_idx,
780 nb_subfr: best.nb_subfr,
781 lag_index: best.lag_index,
782 pitch_l: {
783 let mut pl = [0i32; MAX_NB_SUBFR];
784 for (i, &v) in pitch_l.iter().enumerate().take(best.nb_subfr) {
785 pl[i] = v;
786 }
787 pl
788 },
789 nlsf_interp: best.nq.interp_index,
790 bytes: best.bytes.len(),
791 ltp_gain: best.ltp_gain,
792 };
793 Ok(best)
794 }
795}
796
797/// A stereo, 10 or 20 ms, NB/MB/WB SILK encoder.
798#[derive(Clone, Debug)]
799pub struct SilkStereoEncoder {
800 fs_khz: usize,
801 mid: SilkEncoder,
802 side: SilkEncoder,
803 range: RangeEncoder,
804 mirror: SilkDecoder,
805 final_range: u32,
806 mirror_range: u32,
807 mirror_out: Vec<i16>,
808 target_bps: Option<u32>,
809 /// libopus `smth_width_Q14`: smoothed stereo width. A fresh mono->stereo
810 /// transition starts it at 1.0 (`enc_API.c` line 191).
811 smth_width: f32,
812 /// libopus `width_prev_Q14 == 0`: the previous frame had zero width.
813 width_prev_zero: bool,
814 prev_mid_only: bool,
815 voiced_frames: usize,
816}
817
818impl SilkStereoEncoder {
819 /// Narrowband or wideband stereo encoder.
820 pub fn new(wideband: bool) -> SilkStereoEncoder {
821 Self::with_fs_khz(if wideband { 16 } else { 8 })
822 }
823
824 /// Mediumband stereo encoder.
825 pub fn new_mediumband() -> SilkStereoEncoder {
826 Self::with_fs_khz(12)
827 }
828
829 fn with_fs_khz(fs_khz: usize) -> SilkStereoEncoder {
830 SilkStereoEncoder {
831 fs_khz,
832 mid: SilkEncoder::with_fs_khz(fs_khz),
833 side: SilkEncoder::with_fs_khz(fs_khz),
834 range: RangeEncoder::new(),
835 mirror: SilkDecoder::new(fs_khz as u32 * 1000, 2),
836 final_range: 0,
837 mirror_range: 0,
838 mirror_out: vec![0; 2 * 20 * fs_khz],
839 target_bps: None,
840 smth_width: 1.0,
841 width_prev_zero: true,
842 prev_mid_only: false,
843 voiced_frames: 0,
844 }
845 }
846
847 /// The range coder state after the last packet.
848 pub fn final_range(&self) -> u32 {
849 self.final_range
850 }
851
852 /// Packets so far coded with a long-term predictor in either channel.
853 pub fn voiced_frames(&self) -> usize {
854 self.voiced_frames
855 }
856
857 /// Target bit rate in bits per second for the whole stereo packet. The
858 /// mid/side split is applied per frame by `stereo_rates`, mirroring
859 /// libopus `silk_stereo_LR_to_MS`.
860 pub fn set_bitrate(&mut self, bps: u32) {
861 self.target_bps = Some(bps);
862 }
863
864 /// libopus `silk_stereo_LR_to_MS` rate split and panned-mono rule.
865 /// `frac` is the sqrt of the side/mid energy ratio, standing in for
866 /// libopus's LP/HP residual ratios. Simplifications: no LP/HP band split,
867 /// the width smoother runs at the full 0.01/frame coefficient (libopus
868 /// scales it by speech activity), and the silent-side taper is skipped
869 /// (a no-op for 20 ms frames). Width never enters the bitstream directly
870 /// (our packets carry zero stereo predictors); it acts only through
871 /// these rates and the mid-only flag.
872 fn stereo_rates(&mut self, frame_ms: usize, frac: f32) -> (u32, u32, bool) {
873 let bps = self.target_bps.expect("stereo rate split needs a target");
874 // Approximate bitrate spent coding the stereo parameters.
875 let total = bps
876 .saturating_sub(if frame_ms == 10 { 1200 } else { 600 })
877 .max(1);
878 let min_mid = 2000 + 600 * self.fs_khz as u32;
879 // 8 parts mid, 5 + 3*frac parts side; below the mid minimum the
880 // stereo width is reduced instead.
881 let mut mid = (8.0 * total as f32) / (13.0 + 3.0 * frac);
882 let mut width = if mid < min_mid as f32 {
883 mid = min_mid as f32;
884 let side = total as f32 - mid;
885 (4.0 * (2.0 * side - min_mid as f32)
886 / ((1.0 + 3.0 * frac) * min_mid as f32))
887 .clamp(0.0, 1.0)
888 } else {
889 1.0
890 };
891 self.smth_width += (width - self.smth_width) * 0.01;
892 let mid_only = if self.width_prev_zero
893 && (8 * total < 13 * min_mid || frac * self.smth_width < 0.05)
894 {
895 // Panned mono: the previous frame already had zero width.
896 width = 0.0;
897 true
898 } else if !self.width_prev_zero
899 && (8 * total < 11 * min_mid || frac * self.smth_width < 0.02)
900 {
901 // Transition to zero width; the side is still coded this frame.
902 width = 0.0;
903 false
904 } else if self.smth_width > 0.95 {
905 width = 1.0;
906 false
907 } else {
908 width = self.smth_width;
909 false
910 };
911 self.width_prev_zero = width == 0.0;
912 if mid_only {
913 (total, 0, true)
914 } else {
915 // Keep at least 1 bps on the side (libopus tail).
916 let side = (total as f32 - mid).max(1.0);
917 ((total - side as u32).max(1), side as u32, false)
918 }
919 }
920
921 /// Algorithmic delay in 48 kHz samples.
922 pub fn delay_samples(&self) -> usize {
923 self.mid.delay_samples()
924 }
925
926 /// The SILK layer of a hybrid packet: codes one interleaved stereo 48 kHz
927 /// frame into the packet's shared range coder without finishing it.
928 pub fn encode_hybrid_ms(
929 &mut self,
930 pcm48: &[f32],
931 enc: &mut RangeEncoder,
932 frame_ms: usize,
933 ) -> Result<()> {
934 assert!(
935 matches!(frame_ms, 10 | 20),
936 "SilkStereoEncoder codes 10 or 20 ms stereo frames"
937 );
938 assert_eq!(
939 pcm48.len(),
940 2 * 48 * frame_ms,
941 "SilkStereoEncoder input is 48 kHz stereo"
942 );
943 if self.prev_mid_only {
944 self.side.reset_state();
945 }
946 let samples = 48 * frame_ms;
947 let mut mid = Vec::with_capacity(samples);
948 let mut side = Vec::with_capacity(samples);
949 let mut mid_energy = 0.0f32;
950 let mut side_energy = 0.0f32;
951 for lr in pcm48.chunks_exact(2) {
952 let m = 0.5 * (lr[0] + lr[1]);
953 let s = 0.5 * (lr[0] - lr[1]);
954 mid.push(m);
955 side.push(s);
956 mid_energy += m * m;
957 side_energy += s * s;
958 }
959 let frac = if mid_energy > 0.0 {
960 (side_energy / mid_energy).sqrt().min(1.0)
961 } else {
962 f32::from(side_energy > 0.0)
963 };
964 let mid_only = if self.target_bps.is_some() {
965 let (mid_bps, side_bps, mid_only) = self.stereo_rates(frame_ms, frac);
966 self.mid.set_bitrate(mid_bps.max(500));
967 if !mid_only {
968 self.side.set_bitrate(side_bps.max(500));
969 }
970 mid_only
971 } else {
972 side_energy < 1.0e-10
973 };
974 let mid_trial = self
975 .mid
976 .encode_inner(&mid, frame_ms, None, false, 0, true)?;
977 let side_trial = if mid_only {
978 None
979 } else {
980 Some(
981 self.side
982 .encode_inner(&side, frame_ms, None, false, 0, true)?,
983 )
984 };
985 let side_vad = side_trial.as_ref().map(|t| t.vad_flag).unwrap_or(false);
986 write_stereo_packet_header(enc, mid_trial.vad_flag, side_vad);
987 write_stereo_zero_pred(enc);
988 if !side_vad {
989 enc.enc_icdf(usize::from(mid_only), &STEREO_ONLY_CODE_MID_ICDF, 8);
990 }
991 write_frame_data(enc, &mid_trial, false, 0);
992 if let Some(trial) = &side_trial {
993 write_frame_data(enc, trial, false, 0);
994 }
995 self.mid.replay_ms(&mid_trial.bytes, frame_ms)?;
996 match &side_trial {
997 Some(trial) => self.side.replay_ms(&trial.bytes, frame_ms)?,
998 None => self.side.reset_state(),
999 }
1000 self.prev_mid_only = mid_only;
1001 self.voiced_frames +=
1002 usize::from(mid_trial.voiced || side_trial.as_ref().is_some_and(|t| t.voiced));
1003 Ok(())
1004 }
1005
1006 /// Encodes one 10 or 20 ms interleaved stereo frame at 48 kHz.
1007 pub fn encode_frame_ms(
1008 &mut self,
1009 pcm48: &[f32],
1010 out: &mut [u8],
1011 frame_ms: usize,
1012 ) -> Result<usize> {
1013 assert!(
1014 matches!(frame_ms, 10 | 20),
1015 "SilkStereoEncoder codes 10 or 20 ms stereo frames"
1016 );
1017 assert_eq!(
1018 pcm48.len(),
1019 2 * 48 * frame_ms,
1020 "SilkStereoEncoder input is 48 kHz stereo"
1021 );
1022 if self.prev_mid_only {
1023 self.side.reset_state();
1024 }
1025 let samples = 48 * frame_ms;
1026 let mut mid = Vec::with_capacity(samples);
1027 let mut side = Vec::with_capacity(samples);
1028 let mut mid_energy = 0.0f32;
1029 let mut side_energy = 0.0f32;
1030 for lr in pcm48.chunks_exact(2) {
1031 let m = 0.5 * (lr[0] + lr[1]);
1032 let s = 0.5 * (lr[0] - lr[1]);
1033 mid.push(m);
1034 side.push(s);
1035 mid_energy += m * m;
1036 side_energy += s * s;
1037 }
1038 let frac = if mid_energy > 0.0 {
1039 (side_energy / mid_energy).sqrt().min(1.0)
1040 } else {
1041 f32::from(side_energy > 0.0)
1042 };
1043 let mid_only = if self.target_bps.is_some() {
1044 let (mid_bps, side_bps, mid_only) = self.stereo_rates(frame_ms, frac);
1045 self.mid.set_bitrate(mid_bps.max(500));
1046 if !mid_only {
1047 self.side.set_bitrate(side_bps.max(500));
1048 }
1049 mid_only
1050 } else {
1051 side_energy < 1.0e-10
1052 };
1053 let mid_trial = self
1054 .mid
1055 .encode_inner(&mid, frame_ms, None, false, 0, true)?;
1056 let side_trial = if mid_only {
1057 None
1058 } else {
1059 Some(
1060 self.side
1061 .encode_inner(&side, frame_ms, None, false, 0, true)?,
1062 )
1063 };
1064
1065 self.range.reset(1275);
1066 write_stereo_packet_header(
1067 &mut self.range,
1068 mid_trial.vad_flag,
1069 side_trial.as_ref().map(|t| t.vad_flag).unwrap_or(false),
1070 );
1071 write_stereo_zero_pred(&mut self.range);
1072 if !side_trial.as_ref().map(|t| t.vad_flag).unwrap_or(false) {
1073 self.range
1074 .enc_icdf(usize::from(mid_only), &STEREO_ONLY_CODE_MID_ICDF, 8);
1075 }
1076 write_frame_data(&mut self.range, &mid_trial, false, 0);
1077 if let Some(trial) = &side_trial {
1078 write_frame_data(&mut self.range, trial, false, 0);
1079 }
1080 self.range.done();
1081 debug_assert!(!self.range.error());
1082 let len = self.range.range_bytes();
1083 self.final_range = self.range.range();
1084 let duration = if frame_ms == 10 { 0u8 } else { 1 };
1085 let base = match self.fs_khz {
1086 8 => 0u8,
1087 12 => 4,
1088 _ => 8,
1089 };
1090 if out.len() < 1 + len {
1091 return Err(ec_core::Error::corrupt(format!(
1092 "silk stereo encode: packet needs {} bytes, buffer holds {}",
1093 1 + len,
1094 out.len()
1095 )));
1096 }
1097 out[0] = ((base + duration) << 3) | 0x04;
1098 out[1..1 + len].copy_from_slice(&self.range.data()[..len]);
1099 self.replay_ms(&out[1..1 + len], frame_ms)?;
1100 self.mid.replay_ms(&mid_trial.bytes, frame_ms)?;
1101 match &side_trial {
1102 Some(trial) => self.side.replay_ms(&trial.bytes, frame_ms)?,
1103 None => self.side.reset_state(),
1104 }
1105 self.prev_mid_only = mid_only;
1106 self.voiced_frames +=
1107 usize::from(mid_trial.voiced || side_trial.as_ref().is_some_and(|t| t.voiced));
1108 debug_assert_eq!(self.mirror_range, self.final_range);
1109 Ok(1 + len)
1110 }
1111
1112 /// Decodes a finished hybrid payload (TOC stripped) through the stereo
1113 /// mirror so the range state can be checked against the packet encoder.
1114 pub fn replay_hybrid(&mut self, payload: &[u8], frame_ms: usize) -> Result<()> {
1115 self.replay_ms(payload, frame_ms)
1116 }
1117
1118 fn replay_ms(&mut self, payload: &[u8], frame_ms: usize) -> Result<()> {
1119 let fs = self.fs_khz;
1120 let mut dec = RangeDecoder::new(payload);
1121 let total = 2 * frame_ms * fs;
1122 if self.mirror_out.len() < total {
1123 self.mirror_out.resize(total, 0);
1124 }
1125 let n = self.mirror.decode(
1126 &mut dec,
1127 &mut self.mirror_out[..total],
1128 frame_ms,
1129 fs as u32 * 1000,
1130 2,
1131 true,
1132 )?;
1133 debug_assert_eq!(n, frame_ms * fs);
1134 self.mirror_range = dec.range();
1135 Ok(())
1136 }
1137}
1138
1139fn write_stereo_packet_header(enc: &mut RangeEncoder, mid_vad: bool, side_vad: bool) {
1140 enc.enc_bit_logp(mid_vad, 1);
1141 enc.enc_bit_logp(false, 1);
1142 enc.enc_bit_logp(side_vad, 1);
1143 enc.enc_bit_logp(false, 1);
1144}
1145
1146fn write_stereo_zero_pred(enc: &mut RangeEncoder) {
1147 enc.enc_icdf(12, &STEREO_PRED_JOINT_ICDF, 8);
1148 enc.enc_icdf(1, &UNIFORM3_ICDF, 8);
1149 enc.enc_icdf(2, &UNIFORM5_ICDF, 8);
1150 enc.enc_icdf(1, &UNIFORM3_ICDF, 8);
1151 enc.enc_icdf(2, &UNIFORM5_ICDF, 8);
1152}
1153/// One closed-loop quantisation of a frame.
1154struct Run {
1155 ltp_index: [usize; MAX_NB_SUBFR],
1156 pulses: Vec<i32>,
1157 err: f32,
1158 d: Vec<f32>,
1159 u: Vec<f32>,
1160 gq: Vec<f32>,
1161}
1162
1163struct Trial {
1164 bytes: Vec<u8>,
1165 range: u32,
1166 prev_gain_index: i32,
1167 gain_idx: [i8; MAX_NB_SUBFR],
1168 per_index: usize,
1169 run: Run,
1170 vad_flag: bool,
1171 signal_type: i32,
1172 quant_offset_type: usize,
1173 wb: bool,
1174 order: usize,
1175 nb_subfr: usize,
1176 fs: usize,
1177 lag_index: i32,
1178 contour_index: i32,
1179 voiced: bool,
1180 ltp_scale_index: usize,
1181 nq: NlsfQuant,
1182 ltp_gain: f32,
1183 seed_index: i32,
1184}
1185
1186fn write_packet_header(enc: &mut RangeEncoder, frames: &[&Trial]) {
1187 for frame in frames {
1188 enc.enc_bit_logp(frame.vad_flag, 1);
1189 }
1190 enc.enc_bit_logp(false, 1);
1191}
1192
1193fn write_frame_data(
1194 enc: &mut RangeEncoder,
1195 frame: &Trial,
1196 conditional: bool,
1197 prev_signal_type: i32,
1198) {
1199 if frame.vad_flag {
1200 enc.enc_icdf(
1201 ((frame.signal_type << 1) | frame.quant_offset_type as i32) as usize - 2,
1202 &TYPE_OFFSET_VAD_ICDF,
1203 8,
1204 );
1205 } else {
1206 enc.enc_icdf(frame.quant_offset_type, &TYPE_OFFSET_NO_VAD_ICDF, 8);
1207 }
1208 if conditional {
1209 enc.enc_icdf(frame.gain_idx[0] as usize, &DELTA_GAIN_ICDF, 8);
1210 } else {
1211 enc.enc_icdf(
1212 (frame.gain_idx[0] as usize) >> 3,
1213 &GAIN_ICDF[frame.signal_type as usize],
1214 8,
1215 );
1216 enc.enc_icdf((frame.gain_idx[0] as usize) & 7, &UNIFORM8_ICDF, 8);
1217 }
1218 for k in 1..frame.nb_subfr {
1219 enc.enc_icdf(frame.gain_idx[k] as usize, &DELTA_GAIN_ICDF, 8);
1220 }
1221 let cb = nlsf_cb(frame.wb);
1222 let stage1_icdf = &cb.cb1_icdf[(frame.signal_type as usize >> 1) * cb.n_vectors..];
1223 enc.enc_icdf(frame.nq.indices[0] as usize, stage1_icdf, 8);
1224 let (ec_ix, _) = crate::silk::nlsf_unpack(cb, frame.nq.indices[0] as usize);
1225 for i in 0..frame.order {
1226 let q = frame.nq.indices[i + 1] as i32;
1227 let icdf = &cb.ec_icdf[ec_ix[i] as usize..];
1228 if q <= -4 {
1229 enc.enc_icdf(0, icdf, 8);
1230 enc.enc_icdf((-4 - q) as usize, &NLSF_EXT_ICDF, 8);
1231 } else if q >= 4 {
1232 enc.enc_icdf(8, icdf, 8);
1233 enc.enc_icdf((q - 4) as usize, &NLSF_EXT_ICDF, 8);
1234 } else {
1235 enc.enc_icdf((q + 4) as usize, icdf, 8);
1236 }
1237 }
1238 if frame.nb_subfr == MAX_NB_SUBFR {
1239 enc.enc_icdf(
1240 frame.nq.interp_index as usize,
1241 &NLSF_INTERPOLATION_FACTOR_ICDF,
1242 8,
1243 );
1244 }
1245 if frame.voiced {
1246 if conditional && prev_signal_type == 2 {
1247 enc.enc_icdf(0, &PITCH_DELTA_ICDF, 8);
1248 }
1249 let half = frame.fs as i32 >> 1;
1250 enc.enc_icdf((frame.lag_index / half) as usize, &PITCH_LAG_ICDF, 8);
1251 let low_icdf: &[u8] = match frame.fs {
1252 16 => &UNIFORM8_ICDF,
1253 12 => &UNIFORM6_ICDF,
1254 _ => &UNIFORM4_ICDF,
1255 };
1256 enc.enc_icdf((frame.lag_index % half) as usize, low_icdf, 8);
1257 let contour_icdf: &[u8] = match (frame.fs, frame.nb_subfr) {
1258 (8, 4) => &PITCH_CONTOUR_NB_ICDF,
1259 (8, _) => &PITCH_CONTOUR_10_MS_NB_ICDF,
1260 (_, 4) => &PITCH_CONTOUR_ICDF,
1261 _ => &PITCH_CONTOUR_10_MS_ICDF,
1262 };
1263 enc.enc_icdf(frame.contour_index as usize, contour_icdf, 8);
1264 enc.enc_icdf(frame.per_index, &LTP_PER_INDEX_ICDF, 8);
1265 let gain_icdf: &[u8] = match frame.per_index {
1266 0 => &LTP_GAIN_ICDF_0,
1267 1 => &LTP_GAIN_ICDF_1,
1268 _ => &LTP_GAIN_ICDF_2,
1269 };
1270 for k in 0..frame.nb_subfr {
1271 enc.enc_icdf(frame.run.ltp_index[k], gain_icdf, 8);
1272 }
1273 if !conditional {
1274 enc.enc_icdf(frame.ltp_scale_index, &LTPSCALE_ICDF, 8);
1275 }
1276 }
1277 enc.enc_icdf(frame.seed_index as usize, &UNIFORM4_ICDF, 8);
1278 encode_pulses(
1279 enc,
1280 &frame.run.pulses,
1281 frame.signal_type,
1282 frame.quant_offset_type as i32,
1283 );
1284}
1285
1286/// Bits an ICDF symbol costs, for choosing among equivalent codings.
1287fn icdf_bits(k: usize, icdf: &[u8]) -> f32 {
1288 let hi = if k == 0 { 256 } else { icdf[k - 1] as u32 };
1289 (256.0 / (hi - icdf[k] as u32) as f32).log2()
1290}
1291
1292/// Inverse of `decode_pulses`: rate level, shell-coded block sums with the
1293/// LSB escape, LSBs, signs.
1294fn encode_pulses(enc: &mut RangeEncoder, pulses: &[i32], signal_type: i32, quant_offset_type: i32) {
1295 let iter = pulses.len().div_ceil(SHELL_LEN);
1296 let mut abs = vec![0i32; iter * SHELL_LEN];
1297 for (a, &p) in abs.iter_mut().zip(pulses) {
1298 *a = p.abs();
1299 }
1300 let mut sums = vec![0i32; iter];
1301 let mut shifts = vec![0u32; iter];
1302 for i in 0..iter {
1303 let block = &abs[i * SHELL_LEN..(i + 1) * SHELL_LEN];
1304 let mut s = block.iter().sum::<i32>();
1305 while s > 16 {
1306 shifts[i] += 1;
1307 s = block.iter().map(|&a| a >> shifts[i]).sum();
1308 }
1309 sums[i] = s;
1310 debug_assert!(shifts[i] <= 10);
1311 }
1312 // Rate level: whichever table codes these block sums cheapest.
1313 let rate_level = (0..9)
1314 .min_by(|&a, &b| {
1315 let cost = |rl: usize| -> f32 {
1316 (0..iter)
1317 .map(|i| {
1318 let sym = if shifts[i] > 0 { 17 } else { sums[i] as usize };
1319 icdf_bits(sym, &PULSES_PER_BLOCK_ICDF[rl])
1320 })
1321 .sum::<f32>()
1322 + icdf_bits(rl, &RATE_LEVELS_ICDF[signal_type as usize >> 1])
1323 };
1324 cost(a).partial_cmp(&cost(b)).unwrap()
1325 })
1326 .unwrap();
1327 enc.enc_icdf(rate_level, &RATE_LEVELS_ICDF[signal_type as usize >> 1], 8);
1328 for i in 0..iter {
1329 let first = if shifts[i] > 0 { 17 } else { sums[i] as usize };
1330 enc.enc_icdf(first, &PULSES_PER_BLOCK_ICDF[rate_level], 8);
1331 for level in 1..=shifts[i] {
1332 let icdf = &PULSES_PER_BLOCK_ICDF[9][usize::from(level == 10)..];
1333 let sym = if level < shifts[i] {
1334 17
1335 } else {
1336 sums[i] as usize
1337 };
1338 enc.enc_icdf(sym, icdf, 8);
1339 }
1340 }
1341 for i in 0..iter {
1342 if sums[i] > 0 {
1343 let block: Vec<i32> = abs[i * SHELL_LEN..(i + 1) * SHELL_LEN]
1344 .iter()
1345 .map(|&a| a >> shifts[i])
1346 .collect();
1347 shell_encode(enc, &block);
1348 }
1349 }
1350 for i in 0..iter {
1351 if shifts[i] > 0 {
1352 for &a in &abs[i * SHELL_LEN..(i + 1) * SHELL_LEN] {
1353 for bit in (0..shifts[i]).rev() {
1354 enc.enc_icdf(((a >> bit) & 1) as usize, &LSB_ICDF, 8);
1355 }
1356 }
1357 }
1358 }
1359 let base = 7 * (quant_offset_type + (signal_type << 1)) as usize;
1360 for i in 0..iter {
1361 let p = sums[i] | ((shifts[i] as i32) << 5);
1362 if p > 0 {
1363 let icdf = [SIGN_ICDF[base + (p & 0x1F).min(6) as usize], 0];
1364 for j in 0..SHELL_LEN {
1365 let idx = i * SHELL_LEN + j;
1366 if idx < pulses.len() && pulses[idx] != 0 {
1367 enc.enc_icdf(usize::from(pulses[idx] > 0), &icdf, 8);
1368 }
1369 }
1370 }
1371 }
1372}
1373
1374/// Inverse of `shell_decode`: the same binary split tree, written top down.
1375fn shell_encode(enc: &mut RangeEncoder, p: &[i32]) {
1376 fn join(enc: &mut RangeEncoder, a: i32, b: i32, table: &[u8]) -> i32 {
1377 let sum = a + b;
1378 if sum > 0 {
1379 enc.enc_icdf(
1380 a as usize,
1381 &table[SHELL_CODE_TABLE_OFFSETS[sum as usize] as usize..],
1382 8,
1383 );
1384 }
1385 sum
1386 }
1387 let p1: Vec<i32> = (0..8).map(|i| p[2 * i] + p[2 * i + 1]).collect();
1388 let p2: Vec<i32> = (0..4).map(|i| p1[2 * i] + p1[2 * i + 1]).collect();
1389 let p3: Vec<i32> = (0..2).map(|i| p2[2 * i] + p2[2 * i + 1]).collect();
1390 join(enc, p3[0], p3[1], &SHELL_CODE_TABLE3);
1391 join(enc, p2[0], p2[1], &SHELL_CODE_TABLE2);
1392 join(enc, p1[0], p1[1], &SHELL_CODE_TABLE1);
1393 join(enc, p[0], p[1], &SHELL_CODE_TABLE0);
1394 join(enc, p[2], p[3], &SHELL_CODE_TABLE0);
1395 join(enc, p1[2], p1[3], &SHELL_CODE_TABLE1);
1396 join(enc, p[4], p[5], &SHELL_CODE_TABLE0);
1397 join(enc, p[6], p[7], &SHELL_CODE_TABLE0);
1398 join(enc, p2[2], p2[3], &SHELL_CODE_TABLE2);
1399 join(enc, p1[4], p1[5], &SHELL_CODE_TABLE1);
1400 join(enc, p[8], p[9], &SHELL_CODE_TABLE0);
1401 join(enc, p[10], p[11], &SHELL_CODE_TABLE0);
1402 join(enc, p1[6], p1[7], &SHELL_CODE_TABLE1);
1403 join(enc, p[12], p[13], &SHELL_CODE_TABLE0);
1404 join(enc, p[14], p[15], &SHELL_CODE_TABLE0);
1405}
1406
1407#[cfg(test)]
1408mod tests {
1409 use super::*;
1410
1411 /// Every pulse pattern the shell coder can see — including the LSB
1412 /// escape and a block that needs several shifts — survives a round trip
1413 /// through the decoder's own `decode_pulses` path via a full packet.
1414 #[test]
1415 fn pulses_roundtrip_through_the_decoder() {
1416 for (wb, seed) in [(false, 1u32), (true, 7u32), (false, 99u32)] {
1417 let mut enc = SilkEncoder::new(wb);
1418 let mut dec = SilkDecoder::new(if wb { 16000 } else { 8000 }, 1);
1419 let mut out = vec![0u8; 1500];
1420 let mut pcm = vec![0i16; 320];
1421 let mut s = seed;
1422 for frame in 0..6 {
1423 let x: Vec<f32> = (0..960)
1424 .map(|i| {
1425 s = s.wrapping_mul(1664525).wrapping_add(1013904223);
1426 let noise = (s >> 8) as f32 / (1u32 << 24) as f32 - 0.5;
1427 // A loud click to force the LSB escape.
1428 let click = if frame == 2 && i == 400 { 0.9 } else { 0.0 };
1429 noise * 0.2 + click
1430 })
1431 .collect();
1432 let len = enc.encode_frame(&x, &mut out).unwrap();
1433 let mut rd = RangeDecoder::new(&out[1..len]);
1434 let n = dec
1435 .decode(
1436 &mut rd,
1437 &mut pcm,
1438 20,
1439 if wb { 16000 } else { 8000 },
1440 1,
1441 true,
1442 )
1443 .unwrap();
1444 assert_eq!(n, if wb { 320 } else { 160 });
1445 assert_eq!(rd.range(), enc.final_range(), "frame {frame}");
1446 assert_eq!(&pcm[..n], &enc.mirror_out[..n]);
1447 }
1448 }
1449 }
1450}