forge
Explore
Log in

Don't you dare go Hollow

SILK payload writer, mono 20 ms NB/WB, decoder-mirrored state

Browse files at this commit

12e4d277983c347be463b132d8438057f4d81fc6Ahmet Kaan GümüşParent: 79db13a
  • feat
    • SILK payload writer, mono 20 ms NB/WB, decoder-mirrored state
Show full message
feat(opus-silk): SILK payload writer, mono 20 ms NB/WB, decoder-mirrored state

Writes every symbol in silk::decode()'s order (VAD/LBRR flags, frame type,
gains, NLSF stage 1/2 + interp, pitch lag/contour + LTP codebook + scale,
seed, rate level, shell-coded pulses with LSB escape, signs) and quantises
the excitation open-loop against the decoder's own reconstruction, with
the encoder replaying each packet through a SilkDecoder so its LTP history
is the real one. Unit test round-trips NB/WB through the decoder including
the LSB escape, range state equal.
crates/ec-opus/src/lib.rsmodified+2 -0
@@ -71,6 +71,7 @@ pub mod packet;
7171 pub mod range;
7272 pub mod silk;
7373 pub(crate) mod silk_enc;
74+pub mod silk_enc_write;
7475
7576 pub use celt::CeltDecoder;
7677 pub use celt_enc::CeltEncoder;
@@ -80,6 +81,7 @@ pub use multistream_enc::MultistreamEncoder;
8081 pub use packet::{Bandwidth, Mode, Packet, Toc};
8182 pub use range::{RangeDecoder, RangeEncoder};
8283 pub use silk::SilkDecoder;
84+pub use silk_enc_write::SilkEncoder;
8385
8486 use ec_core::{Error, Result};
8587
crates/ec-opus/src/silk.rsmodified+11 -1
@@ -221,7 +221,7 @@ fn lshift_sat32(a: i32, shift: i32) -> i32 {
221221
222222 /// `silk_RAND`: the excitation sign PRNG.
223223 #[inline]
224-fn silk_rand(seed: i32) -> i32 {
224+pub(crate) fn silk_rand(seed: i32) -> i32 {
225225 (907633515i32).wrapping_add(seed.wrapping_mul(196314165))
226226 }
227227
@@ -410,6 +410,16 @@ impl SilkDecoder {
410410 }
411411 }
412412
413+ /// The last 20 ms of decoded output of channel 0 at the internal rate:
414+ /// the synthesis history `decode_core` whitens for its LTP state. The
415+ /// encoder mirrors its own packets through a `SilkDecoder` and reads this
416+ /// so its LTP search runs on exactly what the real decoder will predict
417+ /// from.
418+ pub(crate) fn history(&self) -> &[i16] {
419+ let ch = &self.channels[0];
420+ &ch.out_buf[..ch.ltp_mem_length]
421+ }
422+
413423 /// Drops all inter-packet state.
414424 pub fn reset(&mut self) {
415425 let api_rate = self.api_rate;
crates/ec-opus/src/silk_enc_write.rsadded+500 -0
@@ -0,0 +1,500 @@
1+//! SILK payload writer (subtask D2a): turns the analysis in [`crate::silk_enc`]
2+//! into a decodable mono 20 ms SILK packet, NB (8 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 quantiser is deliberately simple (open-loop LPC residual,
12+//! analysis-by-synthesis LTP codebook pick, nearest-level pulse rounding
13+//! under the decoder's seed/offset convention). Noise shaping (NSQ), 10/40/60
14+//! ms frames and stereo are subtask D2b.
15+
16+use ec_core::Result;
17+
18+use crate::range::{RangeDecoder, RangeEncoder};
19+use crate::silk::tables::*;
20+use crate::silk::{
21+ decode_pitch, nlsf2a, nlsf_cb, silk_rand, SilkDecoder, MAX_LPC_ORDER, MAX_NB_SUBFR,
22+ PE_MAX_LAG_MS, PE_MIN_LAG_MS,
23+};
24+use crate::silk_enc::{estimate_pitch, lpc_analyze, quantize_gains, quantize_nlsf, Resampler48, Vad};
25+
26+const NB_SUBFR: usize = 4;
27+const SHELL_LEN: usize = 16;
28+const LTP_ORDER: usize = 5;
29+/// `QUANT_LEVEL_ADJUST_Q10` in `decode_core`: a non-zero pulse decodes 80/1024
30+/// closer to zero than its integer value.
31+const LEVEL_ADJUST: f32 = 80.0 / 1024.0;
32+/// Largest pulse magnitude the shell coder's 10-level LSB escape can carry
33+/// with 16 such pulses in one block.
34+const MAX_PULSE: i32 = 1023;
35+
36+/// A mono, 20 ms, NB or WB SILK encoder.
37+pub struct SilkEncoder {
38+ fs_khz: usize,
39+ resampler: Resampler48,
40+ vad: Vad,
41+ /// Replays every packet this encoder writes: its state is the decoder's.
42+ mirror: SilkDecoder,
43+ range: RangeEncoder,
44+ prev_gain_index: i32,
45+ final_range: u32,
46+ voiced_frames: usize,
47+ mirror_out: Vec<i16>,
48+}
49+
50+impl SilkEncoder {
51+ /// `wideband`: 16 kHz internal rate (TOC config 9), else 8 kHz (config 1).
52+ pub fn new(wideband: bool) -> SilkEncoder {
53+ let fs_khz = if wideband { 16 } else { 8 };
54+ SilkEncoder {
55+ fs_khz,
56+ resampler: Resampler48::new(fs_khz as u32),
57+ vad: Vad::new(),
58+ mirror: SilkDecoder::new(fs_khz as u32 * 1000, 1),
59+ range: RangeEncoder::new(),
60+ prev_gain_index: 10,
61+ final_range: 0,
62+ voiced_frames: 0,
63+ mirror_out: vec![0; 20 * 16],
64+ }
65+ }
66+
67+ /// The range coder state after the last packet; a conformant decoder
68+ /// reports the same value after decoding it.
69+ pub fn final_range(&self) -> u32 {
70+ self.final_range
71+ }
72+
73+ /// Frames so far coded with the long-term (pitch) predictor.
74+ pub fn voiced_frames(&self) -> usize {
75+ self.voiced_frames
76+ }
77+
78+ /// Algorithmic delay in 48 kHz samples: the analysis resampler only
79+ /// (the decoder adds its own resampler delay on the way back up).
80+ pub fn delay_samples(&self) -> usize {
81+ self.resampler.delay_samples()
82+ }
83+
84+ /// Encodes 960 mono 48 kHz samples as one code-0 packet in `out`,
85+ /// returning its length.
86+ pub fn encode_frame(&mut self, pcm48: &[f32], out: &mut [u8]) -> Result<usize> {
87+ assert_eq!(pcm48.len(), 960, "SilkEncoder codes 20 ms mono frames");
88+ let fs = self.fs_khz;
89+ let order = if fs == 16 { MAX_LPC_ORDER } else { 10 };
90+ let n = 20 * fs;
91+ let sub = 5 * fs;
92+ let x: Vec<f32> = self
93+ .resampler
94+ .process(pcm48)
95+ .iter()
96+ .map(|v| v * 32768.0)
97+ .collect();
98+ let vad = self.vad.analyze(&x);
99+
100+ // LPC -> NLSF indices -> the decoder's dequantised filter.
101+ let nlsf_target = lpc_analyze(&x, order).map(|a| a.nlsf_q15).unwrap_or_else(|| {
102+ let mut flat = [0i16; MAX_LPC_ORDER];
103+ for (i, v) in flat.iter_mut().enumerate().take(order) {
104+ *v = ((i + 1) * 32768 / (order + 1)) as i16;
105+ }
106+ flat
107+ });
108+ let wb = fs == 16;
109+ let nq = quantize_nlsf(&nlsf_target[..order], wb);
110+ let a_q12 = nlsf2a(&nq.nlsf_q15[..order], order);
111+ let a: Vec<f32> = a_q12[..order].iter().map(|&v| v as f32 / 4096.0).collect();
112+
113+ // Residual of this frame with the decoder's real past output as filter
114+ // memory, and the whitened past output itself (the LTP history the
115+ // decoder rebuilds at subframe 0).
116+ // (Empty before the first packet: the decoder's history is all zero.)
117+ let mut hist: Vec<f32> = self.mirror.history().iter().map(|&v| v as f32).collect();
118+ hist.resize(n, 0.0);
119+ let sample = |i: isize| -> f32 {
120+ if i < 0 {
121+ hist[(n as isize + i) as usize]
122+ } else {
123+ x[i as usize]
124+ }
125+ };
126+ let whiten = |i: isize| -> f32 {
127+ let mut acc = sample(i);
128+ for (j, &aj) in a.iter().enumerate() {
129+ let idx = i - 1 - j as isize;
130+ if idx >= -(n as isize) {
131+ acc -= aj * sample(idx);
132+ }
133+ }
134+ acc
135+ };
136+ let res: Vec<f32> = (0..n as isize).map(whiten).collect();
137+
138+ // Pitch / LTP.
139+ let pitch = estimate_pitch(&x, fs as i32, NB_SUBFR).filter(|p| p.voiced);
140+ let voiced = pitch.is_some();
141+ let vad_flag = vad.active || voiced;
142+ let signal_type: i32 = if !vad_flag { 0 } else if voiced { 2 } else { 1 };
143+ let quant_offset_type = 0usize;
144+ let offset = QUANTIZATION_OFFSETS_Q10[signal_type as usize >> 1][quant_offset_type] as f32
145+ / 1024.0;
146+
147+ let ltp_scale_index = 0usize;
148+ let ltp_scale = LTPSCALES_TABLE_Q14[ltp_scale_index] as f32 / 16384.0;
149+ // `r`: LTP history in absolute sample units, past frame first (scaled
150+ // by ltp_scale as the decoder scales its rebuilt history), then this
151+ // frame's reconstructed residual as it is quantised.
152+ let mut r: Vec<f32> = (-(n as isize)..0).map(|i| whiten(i) * ltp_scale).collect();
153+ r.resize(2 * n, 0.0);
154+
155+ let (lag_index, contour_index, pitch_l) = match &pitch {
156+ Some(p) => {
157+ let max_index = (PE_MAX_LAG_MS - PE_MIN_LAG_MS) * fs as i32 - 1;
158+ let li = p.lag_index.clamp(0, max_index);
159+ (li, p.contour_index, decode_pitch(li, p.contour_index, fs as i32, NB_SUBFR))
160+ }
161+ None => (0, 0, [0; MAX_NB_SUBFR]),
162+ };
163+ let ltp_pred = |r: &[f32], b: &[i8; 5], k: usize, i: usize| -> f32 {
164+ let pos = n + k * sub + i - pitch_l[k] as usize + LTP_ORDER / 2;
165+ let mut acc = 0f32;
166+ for (j, &bj) in b.iter().enumerate() {
167+ acc += bj as f32 / 128.0 * r[pos - j];
168+ }
169+ acc
170+ };
171+ // Codebook pick by min squared error, open loop (the frame's own
172+ // residual stands in for the not-yet-quantised part of the history).
173+ let mut per_index = 0usize;
174+ let mut ltp_index = [0usize; MAX_NB_SUBFR];
175+ if voiced {
176+ let mut r_ol = r.clone();
177+ r_ol[n..].copy_from_slice(&res);
178+ let mut best_total = f32::INFINITY;
179+ for (per, cbk) in [&LTP_GAIN_VQ_0[..], &LTP_GAIN_VQ_1[..], &LTP_GAIN_VQ_2[..]]
180+ .iter()
181+ .enumerate()
182+ {
183+ let mut total = 0f32;
184+ let mut idx = [0usize; MAX_NB_SUBFR];
185+ for k in 0..NB_SUBFR {
186+ let mut best = f32::INFINITY;
187+ for (v, b) in cbk.iter().enumerate() {
188+ let err: f32 = (0..sub)
189+ .map(|i| {
190+ let d = res[k * sub + i] - ltp_pred(&r_ol, b, k, i);
191+ d * d
192+ })
193+ .sum();
194+ if err < best {
195+ best = err;
196+ idx[k] = v;
197+ }
198+ }
199+ total += best;
200+ }
201+ if total < best_total {
202+ best_total = total;
203+ per_index = per;
204+ ltp_index = idx;
205+ }
206+ }
207+ }
208+ let cbk: &[[i8; 5]] = match per_index {
209+ 0 => &LTP_GAIN_VQ_0,
210+ 1 => &LTP_GAIN_VQ_1,
211+ _ => &LTP_GAIN_VQ_2,
212+ };
213+
214+ // Gains: the open-loop excitation RMS per subframe, so pulses land
215+ // around unit magnitude.
216+ let mut targets = [0i32; MAX_NB_SUBFR];
217+ for k in 0..NB_SUBFR {
218+ let mut r_ol = r.clone();
219+ r_ol[n..].copy_from_slice(&res);
220+ let e: f32 = (0..sub)
221+ .map(|i| {
222+ let p = if voiced { ltp_pred(&r_ol, &cbk[ltp_index[k]], k, i) } else { 0.0 };
223+ let d = res[k * sub + i] - p;
224+ d * d
225+ })
226+ .sum::<f32>()
227+ / sub as f32;
228+ targets[k] = ((e.sqrt() * 65536.0).round() as i64).clamp(1, i32::MAX as i64) as i32;
229+ }
230+ let (gain_idx, gains_q16) =
231+ quantize_gains(&targets, &mut self.prev_gain_index, false, NB_SUBFR);
232+
233+ // Pulses: sequential, under the decoder's seed-driven sign flips.
234+ let seed_index = 0i32;
235+ let mut seed = seed_index;
236+ let mut pulses = vec![0i32; n];
237+ for k in 0..NB_SUBFR {
238+ let g = gains_q16[k] as f32 / 65536.0;
239+ for i in 0..sub {
240+ let idx = k * sub + i;
241+ let pred = if voiced { ltp_pred(&r, &cbk[ltp_index[k]], k, i) } else { 0.0 };
242+ let e = (res[idx] - pred) / g;
243+ seed = silk_rand(seed);
244+ let flip = seed < 0;
245+ let target = if flip { -e } else { e };
246+ let recon = |p: i32| -> f32 {
247+ let lvl = p as f32 - LEVEL_ADJUST * (p.signum() as f32);
248+ lvl + offset
249+ };
250+ let c = (target.round() as i32).clamp(-MAX_PULSE, MAX_PULSE);
251+ let p = [c - 1, c, c + 1]
252+ .into_iter()
253+ .filter(|p| p.abs() <= MAX_PULSE)
254+ .min_by(|&a, &b| {
255+ (recon(a) - target)
256+ .abs()
257+ .partial_cmp(&(recon(b) - target).abs())
258+ .unwrap()
259+ })
260+ .unwrap();
261+ pulses[idx] = p;
262+ seed = seed.wrapping_add(p);
263+ let exc = if flip { -recon(p) } else { recon(p) };
264+ r[n + idx] = g * (exc + pred);
265+ }
266+ }
267+
268+ // --- Bitstream, in decode()'s order. ---
269+ let enc = &mut self.range;
270+ enc.reset(1275);
271+ enc.enc_bit_logp(vad_flag, 1); // VAD flag
272+ enc.enc_bit_logp(false, 1); // LBRR flag
273+ // Frame type.
274+ if vad_flag {
275+ enc.enc_icdf(((signal_type << 1) | quant_offset_type as i32) as usize - 2, &TYPE_OFFSET_VAD_ICDF, 8);
276+ } else {
277+ enc.enc_icdf(quant_offset_type, &TYPE_OFFSET_NO_VAD_ICDF, 8);
278+ }
279+ // Gains: one frame per packet, so always independently coded.
280+ enc.enc_icdf((gain_idx[0] as usize) >> 3, &GAIN_ICDF[signal_type as usize], 8);
281+ enc.enc_icdf((gain_idx[0] as usize) & 7, &UNIFORM8_ICDF, 8);
282+ for k in 1..NB_SUBFR {
283+ enc.enc_icdf(gain_idx[k] as usize, &DELTA_GAIN_ICDF, 8);
284+ }
285+ // NLSFs.
286+ let cb = nlsf_cb(wb);
287+ let stage1_icdf = &cb.cb1_icdf[(signal_type as usize >> 1) * cb.n_vectors..];
288+ enc.enc_icdf(nq.indices[0] as usize, stage1_icdf, 8);
289+ let (ec_ix, _) = crate::silk::nlsf_unpack(cb, nq.indices[0] as usize);
290+ for i in 0..order {
291+ let q = nq.indices[i + 1] as i32;
292+ let icdf = &cb.ec_icdf[ec_ix[i] as usize..];
293+ if q < -4 {
294+ enc.enc_icdf(0, icdf, 8);
295+ enc.enc_icdf((-4 - q) as usize, &NLSF_EXT_ICDF, 8);
296+ } else if q > 4 {
297+ enc.enc_icdf(8, icdf, 8);
298+ enc.enc_icdf((q - 4) as usize, &NLSF_EXT_ICDF, 8);
299+ } else {
300+ enc.enc_icdf((q + 4) as usize, icdf, 8);
301+ }
302+ }
303+ enc.enc_icdf(nq.interp_index as usize, &NLSF_INTERPOLATION_FACTOR_ICDF, 8);
304+ // Pitch + LTP.
305+ if voiced {
306+ let half = fs as i32 >> 1;
307+ enc.enc_icdf((lag_index / half) as usize, &PITCH_LAG_ICDF, 8);
308+ let low_icdf: &[u8] = if wb { &UNIFORM8_ICDF } else { &UNIFORM4_ICDF };
309+ enc.enc_icdf((lag_index % half) as usize, low_icdf, 8);
310+ let contour_icdf: &[u8] = if wb { &PITCH_CONTOUR_ICDF } else { &PITCH_CONTOUR_NB_ICDF };
311+ enc.enc_icdf(contour_index as usize, contour_icdf, 8);
312+ enc.enc_icdf(per_index, &LTP_PER_INDEX_ICDF, 8);
313+ let gain_icdf: &[u8] = match per_index {
314+ 0 => &LTP_GAIN_ICDF_0,
315+ 1 => &LTP_GAIN_ICDF_1,
316+ _ => &LTP_GAIN_ICDF_2,
317+ };
318+ for k in 0..NB_SUBFR {
319+ enc.enc_icdf(ltp_index[k], gain_icdf, 8);
320+ }
321+ enc.enc_icdf(ltp_scale_index, &LTPSCALE_ICDF, 8);
322+ self.voiced_frames += 1;
323+ }
324+ enc.enc_icdf(seed_index as usize, &UNIFORM4_ICDF, 8);
325+ encode_pulses(enc, &pulses, signal_type, quant_offset_type as i32);
326+ enc.done();
327+ debug_assert!(!enc.error());
328+ let len = enc.range_bytes();
329+ self.final_range = enc.range();
330+
331+ let toc = if wb { 9u8 << 3 } else { 1u8 << 3 };
332+ if out.len() < 1 + len {
333+ return Err(ec_core::Error::corrupt(format!(
334+ "silk encode: packet needs {} bytes, buffer holds {}",
335+ 1 + len,
336+ out.len()
337+ )));
338+ }
339+ out[0] = toc;
340+ out[1..1 + len].copy_from_slice(&enc.data()[..len]);
341+
342+ // Replay through the mirror so the next frame sees decoder state.
343+ let mut dec = RangeDecoder::new(&out[1..1 + len]);
344+ self.mirror
345+ .decode(&mut dec, &mut self.mirror_out, 20, fs as u32 * 1000, 1, true)?;
346+ debug_assert_eq!(dec.range(), self.final_range);
347+ Ok(1 + len)
348+ }
349+}
350+
351+/// Bits an ICDF symbol costs, for choosing among equivalent codings.
352+fn icdf_bits(k: usize, icdf: &[u8]) -> f32 {
353+ let hi = if k == 0 { 256 } else { icdf[k - 1] as u32 };
354+ (256.0 / (hi - icdf[k] as u32) as f32).log2()
355+}
356+
357+/// Inverse of `decode_pulses`: rate level, shell-coded block sums with the
358+/// LSB escape, LSBs, signs.
359+fn encode_pulses(enc: &mut RangeEncoder, pulses: &[i32], signal_type: i32, quant_offset_type: i32) {
360+ let iter = pulses.len().div_ceil(SHELL_LEN);
361+ let mut abs = vec![0i32; iter * SHELL_LEN];
362+ for (a, &p) in abs.iter_mut().zip(pulses) {
363+ *a = p.abs();
364+ }
365+ let mut sums = vec![0i32; iter];
366+ let mut shifts = vec![0u32; iter];
367+ for i in 0..iter {
368+ let block = &abs[i * SHELL_LEN..(i + 1) * SHELL_LEN];
369+ let mut s = block.iter().sum::<i32>();
370+ while s > 16 {
371+ shifts[i] += 1;
372+ s = block.iter().map(|&a| a >> shifts[i]).sum();
373+ }
374+ sums[i] = s;
375+ debug_assert!(shifts[i] <= 10);
376+ }
377+ // Rate level: whichever table codes these block sums cheapest.
378+ let rate_level = (0..9)
379+ .min_by(|&a, &b| {
380+ let cost = |rl: usize| -> f32 {
381+ (0..iter)
382+ .map(|i| {
383+ let sym = if shifts[i] > 0 { 17 } else { sums[i] as usize };
384+ icdf_bits(sym, &PULSES_PER_BLOCK_ICDF[rl])
385+ })
386+ .sum::<f32>()
387+ + icdf_bits(rl, &RATE_LEVELS_ICDF[signal_type as usize >> 1])
388+ };
389+ cost(a).partial_cmp(&cost(b)).unwrap()
390+ })
391+ .unwrap();
392+ enc.enc_icdf(rate_level, &RATE_LEVELS_ICDF[signal_type as usize >> 1], 8);
393+ for i in 0..iter {
394+ let first = if shifts[i] > 0 { 17 } else { sums[i] as usize };
395+ enc.enc_icdf(first, &PULSES_PER_BLOCK_ICDF[rate_level], 8);
396+ for level in 1..=shifts[i] {
397+ let icdf = &PULSES_PER_BLOCK_ICDF[9][usize::from(level == 10)..];
398+ let sym = if level < shifts[i] { 17 } else { sums[i] as usize };
399+ enc.enc_icdf(sym, icdf, 8);
400+ }
401+ }
402+ for i in 0..iter {
403+ if sums[i] > 0 {
404+ let block: Vec<i32> = abs[i * SHELL_LEN..(i + 1) * SHELL_LEN]
405+ .iter()
406+ .map(|&a| a >> shifts[i])
407+ .collect();
408+ shell_encode(enc, &block);
409+ }
410+ }
411+ for i in 0..iter {
412+ if shifts[i] > 0 {
413+ for &a in &abs[i * SHELL_LEN..(i + 1) * SHELL_LEN] {
414+ for bit in (0..shifts[i]).rev() {
415+ enc.enc_icdf(((a >> bit) & 1) as usize, &LSB_ICDF, 8);
416+ }
417+ }
418+ }
419+ }
420+ let base = 7 * (quant_offset_type + (signal_type << 1)) as usize;
421+ for i in 0..iter {
422+ let p = sums[i] | ((shifts[i] as i32) << 5);
423+ if p > 0 {
424+ let icdf = [SIGN_ICDF[base + (p & 0x1F).min(6) as usize], 0];
425+ for j in 0..SHELL_LEN {
426+ let idx = i * SHELL_LEN + j;
427+ if idx < pulses.len() && pulses[idx] != 0 {
428+ enc.enc_icdf(usize::from(pulses[idx] > 0), &icdf, 8);
429+ }
430+ }
431+ }
432+ }
433+}
434+
435+/// Inverse of `shell_decode`: the same binary split tree, written top down.
436+fn shell_encode(enc: &mut RangeEncoder, p: &[i32]) {
437+ fn join(enc: &mut RangeEncoder, a: i32, b: i32, table: &[u8]) -> i32 {
438+ let sum = a + b;
439+ if sum > 0 {
440+ enc.enc_icdf(a as usize, &table[SHELL_CODE_TABLE_OFFSETS[sum as usize] as usize..], 8);
441+ }
442+ sum
443+ }
444+ let p1: Vec<i32> = (0..8).map(|i| p[2 * i] + p[2 * i + 1]).collect();
445+ let p2: Vec<i32> = (0..4).map(|i| p1[2 * i] + p1[2 * i + 1]).collect();
446+ let p3: Vec<i32> = (0..2).map(|i| p2[2 * i] + p2[2 * i + 1]).collect();
447+ join(enc, p3[0], p3[1], &SHELL_CODE_TABLE3);
448+ join(enc, p2[0], p2[1], &SHELL_CODE_TABLE2);
449+ join(enc, p1[0], p1[1], &SHELL_CODE_TABLE1);
450+ join(enc, p[0], p[1], &SHELL_CODE_TABLE0);
451+ join(enc, p[2], p[3], &SHELL_CODE_TABLE0);
452+ join(enc, p1[2], p1[3], &SHELL_CODE_TABLE1);
453+ join(enc, p[4], p[5], &SHELL_CODE_TABLE0);
454+ join(enc, p[6], p[7], &SHELL_CODE_TABLE0);
455+ join(enc, p2[2], p2[3], &SHELL_CODE_TABLE2);
456+ join(enc, p1[4], p1[5], &SHELL_CODE_TABLE1);
457+ join(enc, p[8], p[9], &SHELL_CODE_TABLE0);
458+ join(enc, p[10], p[11], &SHELL_CODE_TABLE0);
459+ join(enc, p1[6], p1[7], &SHELL_CODE_TABLE1);
460+ join(enc, p[12], p[13], &SHELL_CODE_TABLE0);
461+ join(enc, p[14], p[15], &SHELL_CODE_TABLE0);
462+}
463+
464+#[cfg(test)]
465+mod tests {
466+ use super::*;
467+
468+ /// Every pulse pattern the shell coder can see — including the LSB
469+ /// escape and a block that needs several shifts — survives a round trip
470+ /// through the decoder's own `decode_pulses` path via a full packet.
471+ #[test]
472+ fn pulses_roundtrip_through_the_decoder() {
473+ for (wb, seed) in [(false, 1u32), (true, 7u32), (false, 99u32)] {
474+ let mut enc = SilkEncoder::new(wb);
475+ let mut dec = SilkDecoder::new(if wb { 16000 } else { 8000 }, 1);
476+ let mut out = vec![0u8; 1500];
477+ let mut pcm = vec![0i16; 320];
478+ let mut s = seed;
479+ for frame in 0..6 {
480+ let x: Vec<f32> = (0..960)
481+ .map(|i| {
482+ s = s.wrapping_mul(1664525).wrapping_add(1013904223);
483+ let noise = (s >> 8) as f32 / (1u32 << 24) as f32 - 0.5;
484+ // A loud click to force the LSB escape.
485+ let click = if frame == 2 && i == 400 { 0.9 } else { 0.0 };
486+ noise * 0.2 + click
487+ })
488+ .collect();
489+ let len = enc.encode_frame(&x, &mut out).unwrap();
490+ let mut rd = RangeDecoder::new(&out[1..len]);
491+ let n = dec
492+ .decode(&mut rd, &mut pcm, 20, if wb { 16000 } else { 8000 }, 1, true)
493+ .unwrap();
494+ assert_eq!(n, if wb { 320 } else { 160 });
495+ assert_eq!(rd.range(), enc.final_range(), "frame {frame}");
496+ assert_eq!(&pcm[..n], &enc.mirror_out[..n]);
497+ }
498+ }
499+ }
500+}
fixturesadded+1 -0
@@ -0,0 +1 @@
1+/home/user/Documents/Code/Rust/edith_codecs/fixtures
\ No newline at end of file