forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB5c8eff8Tahinli2 months ago2949 commits

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