forge
Explore
Log in

Don't you dare go Hollow

SILK layer, hybrid frames and packet redundancy

Browse files at this commit

ece2a353c9f56cc023c1d87b4d138aabcb1bb994Ahmet Kaan GümüşParent: c7660d1
  • feat
    • SILK layer, hybrid frames and packet redundancy
Show full message
feat(opus): SILK layer, hybrid frames and packet redundancy

Full RFC 6716 Section 4.2 decode in exact integer arithmetic: header and LBRR
flags, gains, NLSF stage-1/stage-2 dequantisation with Laroia weighting,
stabilisation and interpolation, LSF-to-LPC conversion with prediction-gain
limiting, pitch lags and LTP filters, shell-coded excitation with LSBs and
signs, LTP and LPC synthesis, stereo unmixing, and the output resampler for
8/12/16 kHz internal rates. The Opus layer now joins the two layers: SILK-only,
hybrid (SILK below 8 kHz plus CELT above), and the redundancy frames that carry
a mode switch across a packet boundary.

Check: all twelve RFC 6716 vectors, decoded at 48 kHz stereo, match the
reference range coder state on every one of 18075 packets, and score 96.96 to
100.00 % on the opus_compare metric (0 is the passing threshold). The three
SILK-only vectors are sample-for-sample identical to the reference output.
Unit checks cover the fixed-point helpers, gain dequantisation monotonicity and
LSF stabilisation.
crates/ec-opus/src/celt.rsmodified+1 -1
@@ -280,7 +280,7 @@ fn isqrt32(x: u32) -> u32 {
280 }280 }
281 281
282 /// The CELT low-overlap window (Section 4.3.7), computed rather than tabulated.282 /// The CELT low-overlap window (Section 4.3.7), computed rather than tabulated.
283-fn overlap_window() -> Vec<f32> {283+pub(crate) fn overlap_window() -> Vec<f32> {
284 (0..OVERLAP)284 (0..OVERLAP)
285 .map(|i| {285 .map(|i| {
286 let inner = (core::f64::consts::FRAC_PI_2 * (i as f64 + 0.5) / OVERLAP as f64).sin();286 let inner = (core::f64::consts::FRAC_PI_2 * (i as f64 + 0.5) / OVERLAP as f64).sin();
crates/ec-opus/src/lib.rsmodified+193 -9
@@ -29,10 +29,12 @@
29 pub mod celt;29 pub mod celt;
30 pub mod packet;30 pub mod packet;
31 pub mod range;31 pub mod range;
32+pub mod silk;
32 33
33 pub use celt::CeltDecoder;34 pub use celt::CeltDecoder;
34 pub use packet::{Bandwidth, Mode, Packet, Toc};35 pub use packet::{Bandwidth, Mode, Packet, Toc};
35 pub use range::RangeDecoder;36 pub use range::RangeDecoder;
37+pub use silk::SilkDecoder;
36 38
37 use ec_core::{Error, Result};39 use ec_core::{Error, Result};
38 40
@@ -48,6 +50,9 @@ pub struct Decoder {
48 channels: usize,50 channels: usize,
49 downsample: usize,51 downsample: usize,
50 celt: CeltDecoder,52 celt: CeltDecoder,
53+ silk: SilkDecoder,
54+ /// The CELT overlap window, reused for redundancy cross-fades.
55+ celt_window: Vec<f32>,
51 prev_mode: Option<Mode>,56 prev_mode: Option<Mode>,
52 prev_redundancy: bool,57 prev_redundancy: bool,
53 range_final: u32,58 range_final: u32,
@@ -81,6 +86,8 @@ impl Decoder {
81 channels,86 channels,
82 downsample,87 downsample,
83 celt: CeltDecoder::new(channels, downsample),88 celt: CeltDecoder::new(channels, downsample),
89+ silk: SilkDecoder::new(sample_rate, channels),
90+ celt_window: celt::overlap_window(),
84 prev_mode: None,91 prev_mode: None,
85 prev_redundancy: false,92 prev_redundancy: false,
86 range_final: 0,93 range_final: 0,
@@ -107,6 +114,7 @@ impl Decoder {
107 /// Drops all inter-packet state; call after a seek.114 /// Drops all inter-packet state; call after a seek.
108 pub fn reset(&mut self) {115 pub fn reset(&mut self) {
109 self.celt.reset();116 self.celt.reset();
117+ self.silk.reset();
110 self.prev_mode = None;118 self.prev_mode = None;
111 self.prev_redundancy = false;119 self.prev_redundancy = false;
112 self.range_final = 0;120 self.range_final = 0;
@@ -161,6 +169,11 @@ impl Decoder {
161 }169 }
162 170
163 /// Decodes one Opus frame (one entropy-coded unit) of a packet.171 /// Decodes one Opus frame (one entropy-coded unit) of a packet.
172+ ///
173+ /// The three modes share this path: SILK fills the low band, CELT the high
174+ /// one, and a hybrid frame is their sum. The order of everything read from
175+ /// the range decoder here is normative — SILK, then the redundancy flags,
176+ /// then CELT (RFC 6716, Sections 4.2, 4.5.1 and 4.3).
164 fn decode_frame(177 fn decode_frame(
165 &mut self,178 &mut self,
166 data: &[u8],179 data: &[u8],
@@ -171,28 +184,199 @@ impl Decoder {
171 let mode = toc.mode();184 let mode = toc.mode();
172 let stream_channels = toc.channels();185 let stream_channels = toc.channels();
173 if data.len() <= 1 {186 if data.len() <= 1 {
174- // DTX or a dropped frame: no PLC in this decoder, so emit silence.187+ // DTX or a dropped frame. There is no PLC here (the container
188+ // layer feeds this decoder whole packets), so the frame is silent.
175 out.fill(0.0);189 out.fill(0.0);
190+ self.prev_mode = None;
176 return Ok(0);191 return Ok(0);
177 }192 }
178 let mut dec = RangeDecoder::new(data);193 let mut dec = RangeDecoder::new(data);
194+ let mut len = data.len();
195+ let frame_out = frame_48k / self.downsample;
196+ let f5 = 240 / self.downsample;
197+ let f2_5 = 120 / self.downsample;
179 198
199+ // --- SILK layer -----------------------------------------------------
200+ let mut silk_pcm = vec![0i16; frame_out * self.channels];
180 if mode != Mode::Celt {201 if mode != Mode::Celt {
181- return Err(Error::unsupported(202+ if self.prev_mode == Some(Mode::Celt) {
182- "Opus SILK layer",203+ self.silk.reset();
183- "only the CELT layer is implemented in this build",204+ }
184- ));205+ let internal_rate = if mode == Mode::Hybrid {
206+ 16000
207+ } else {
208+ match toc.bandwidth() {
209+ Bandwidth::Narrow => 8000,
210+ Bandwidth::Medium => 12000,
211+ _ => 16000,
212+ }
213+ };
214+ let payload_ms = (frame_48k / 48).max(10);
215+ let mut done = 0usize;
216+ let mut first = true;
217+ while done < frame_out {
218+ let n = self.silk.decode(
219+ &mut dec,
220+ &mut silk_pcm[done * self.channels..],
221+ payload_ms,
222+ internal_rate,
223+ stream_channels,
224+ first,
225+ )?;
226+ if n == 0 {
227+ break;
228+ }
229+ done += n;
230+ first = false;
231+ }
232+ }
233+
234+ // --- Redundancy (Section 4.5.1) -------------------------------------
235+ let mut redundancy = false;
236+ let mut celt_to_silk = false;
237+ let mut redundancy_bytes = 0usize;
238+ if mode != Mode::Celt
239+ && dec.tell() as usize + 17 + 20 * usize::from(mode == Mode::Hybrid) <= 8 * len
240+ {
241+ redundancy = if mode == Mode::Hybrid {
242+ dec.dec_bit_logp(12)
243+ } else {
244+ true
245+ };
246+ if redundancy {
247+ celt_to_silk = dec.dec_bit_logp(1);
248+ redundancy_bytes = if mode == Mode::Hybrid {
249+ dec.dec_uint(256) as usize + 2
250+ } else {
251+ len - ((dec.tell() as usize + 7) >> 3)
252+ };
253+ if redundancy_bytes > len {
254+ redundancy_bytes = 0;
255+ redundancy = false;
256+ } else {
257+ len -= redundancy_bytes;
258+ if len * 8 < dec.tell() as usize {
259+ len = 0;
260+ redundancy_bytes = 0;
261+ redundancy = false;
262+ }
263+ dec.shrink(len);
264+ }
185 }265 }
266+ }
267+
268+ let end_band = toc.bandwidth().celt_end_band();
269+ let start_band = if mode == Mode::Celt { 0 } else { 17 };
270+ let mut redundant = vec![0.0f32; f5 * self.channels];
186 271
272+ // A redundancy frame that precedes the main one is decoded first.
273+ let mut redundant_rng = 0u32;
274+ if redundancy && celt_to_silk {
275+ let tail = &data[len..len + redundancy_bytes];
276+ let mut rdec = RangeDecoder::new(tail);
277+ self.celt
278+ .decode(&mut rdec, &mut redundant, 240, 0, end_band, stream_channels)?;
279+ redundant_rng = rdec.range();
280+ }
281+
282+ // --- CELT layer -----------------------------------------------------
283+ if mode != Mode::Silk {
187 // A mode switch invalidates the MDCT overlap and energy history.284 // A mode switch invalidates the MDCT overlap and energy history.
188 if self.prev_mode.is_some_and(|p| p != mode) && !self.prev_redundancy {285 if self.prev_mode.is_some_and(|p| p != mode) && !self.prev_redundancy {
189 self.celt.reset();286 self.celt.reset();
190 }287 }
191- let end_band = toc.bandwidth().celt_end_band();288+ self.celt.decode(
289+ &mut dec,
290+ out,
291+ frame_48k.min(960),
292+ start_band,
293+ end_band,
294+ stream_channels,
295+ )?;
296+ } else {
297+ out.fill(0.0);
298+ // Fade the CELT layer out when leaving hybrid, as the reference
299+ // does, by decoding one silent 2.5 ms frame.
300+ if self.prev_mode == Some(Mode::Hybrid) && !(redundancy && celt_to_silk) {
301+ let silence = [0xFFu8, 0xFF];
302+ let mut sdec = RangeDecoder::new(&silence);
303+ let mut tmp = vec![0.0f32; f2_5 * self.channels];
192 self.celt304 self.celt
193- .decode(&mut dec, out, frame_48k, 0, end_band, stream_channels)?;305+ .decode(&mut sdec, &mut tmp, 120, 0, end_band, stream_channels)?;
306+ }
307+ }
308+
309+ // Sum the two layers.
310+ if mode != Mode::Celt {
311+ for (o, s) in out.iter_mut().zip(silk_pcm.iter()) {
312+ *o += *s as f32 * (1.0 / 32768.0);
313+ }
314+ }
315+
316+ // A redundancy frame that follows the main one is cross-faded in.
317+ if redundancy && !celt_to_silk {
318+ self.celt.reset();
319+ let tail = &data[len..len + redundancy_bytes];
320+ let mut rdec = RangeDecoder::new(tail);
321+ self.celt
322+ .decode(&mut rdec, &mut redundant, 240, 0, end_band, stream_channels)?;
323+ redundant_rng = rdec.range();
324+ let base = (frame_out - f2_5) * self.channels;
325+ smooth_fade(
326+ &mut out[base..],
327+ &redundant[f2_5 * self.channels..],
328+ f2_5,
329+ self.channels,
330+ &self.celt_window,
331+ self.downsample,
332+ );
333+ }
334+ if redundancy && celt_to_silk {
335+ for c in 0..self.channels {
336+ for i in 0..f2_5 {
337+ out[self.channels * i + c] = redundant[self.channels * i + c];
338+ }
339+ }
340+ // Then fade from the redundancy frame into the frame proper.
341+ let split = f2_5 * self.channels;
342+ for c in 0..self.channels {
343+ for i in 0..f2_5 {
344+ let w = {
345+ let x = self.celt_window[i * self.downsample];
346+ x * x
347+ };
348+ let idx = split + i * self.channels + c;
349+ if idx < out.len() && idx < redundant.len() {
350+ out[idx] = w * out[idx] + (1.0 - w) * redundant[idx];
351+ }
352+ }
353+ }
354+ }
355+
194 self.prev_mode = Some(mode);356 self.prev_mode = Some(mode);
195- self.prev_redundancy = false;357+ self.prev_redundancy = redundancy && !celt_to_silk;
196- Ok(dec.range())358+ Ok(dec.range() ^ redundant_rng)
359+ }
360+}
361+
362+/// Cross-fades `b` over `a` across `overlap` samples using the CELT window,
363+/// the shape the reference uses for redundancy and mode transitions.
364+fn smooth_fade(
365+ a: &mut [f32],
366+ b: &[f32],
367+ overlap: usize,
368+ channels: usize,
369+ window: &[f32],
370+ downsample: usize,
371+) {
372+ let inc = downsample;
373+ for c in 0..channels {
374+ for i in 0..overlap {
375+ let w = window[i * inc] * window[i * inc];
376+ let idx = i * channels + c;
377+ if idx < a.len() && idx < b.len() {
378+ a[idx] = w * b[idx] + (1.0 - w) * a[idx];
379+ }
380+ }
197 }381 }
198 }382 }
crates/ec-opus/src/range.rsmodified+9 -0
@@ -224,6 +224,15 @@ impl<'a> RangeDecoder<'a> {
224 }224 }
225 }225 }
226 226
227+ /// Shrinks the frame to `len` bytes, which is what the redundancy framing
228+ /// does when it reserves the tail of a packet for a second CELT frame
229+ /// (RFC 6716, Section 4.5.1). Bytes already read are unaffected.
230+ pub fn shrink(&mut self, len: usize) {
231+ if len <= self.buf.len() {
232+ self.buf = &self.buf[..len];
233+ }
234+ }
235+
227 /// Declares the rest of the frame consumed, so [`RangeDecoder::tell`]236 /// Declares the rest of the frame consumed, so [`RangeDecoder::tell`]
228 /// reports the whole frame. CELT does this for a silent frame, whose237 /// reports the whole frame. CELT does this for a silent frame, whose
229 /// remaining bits carry nothing (RFC 6716, Section 4.3).238 /// remaining bits carry nothing (RFC 6716, Section 4.3).
crates/ec-opus/src/silk.rsadded+1806 -0
@@ -0,0 +1,1806 @@
1+//! The SILK (linear-prediction) layer of Opus — RFC 6716 Section 4.2.
2+//!
3+//! SILK is a speech coder: each 20 ms frame carries an LPC filter (as line
4+//! spectral frequencies), a per-subframe gain, an optional long-term (pitch)
5+//! predictor, and a pulse-coded excitation. Decoding runs that chain backwards
6+//! — excitation, LTP synthesis, LPC synthesis — then unmixes stereo and
7+//! resamples from the internal 8/12/16 kHz to the output rate.
8+//!
9+//! Unlike CELT, SILK has no floating-point form: every operation below is the
10+//! exact integer arithmetic of the normative decoder (RFC 6716 Section 6 makes
11+//! the Appendix A reference implementation normative, and Section 4.2 is
12+//! written as fixed-point pseudo-code for the same reason). The tables are the
13+//! ones the RFC tabulates in Section 4.2, in the layout the reference uses.
14+//!
15+//! Packet loss concealment is not implemented: this decoder is fed complete
16+//! packets by the container layer, so a lost or empty frame yields silence
17+//! rather than an extrapolation. Everything else in the layer is complete.
18+
19+// SILK is transliterated fixed-point arithmetic: the loops below index parallel
20+// arrays by position because the reference's index arithmetic is the
21+// specification. Iterator forms would hide that correspondence.
22+#![allow(clippy::needless_range_loop)]
23+
24+use ec_core::Result;
25+
26+use crate::range::RangeDecoder;
27+
28+mod tables {
29+ #![allow(clippy::all)]
30+ include!("silk_tables.rs");
31+}
32+
33+use tables::*;
34+
35+const MAX_LPC_ORDER: usize = 16;
36+const LTP_ORDER: usize = 5;
37+const MAX_NB_SUBFR: usize = 4;
38+const SUB_FRAME_LENGTH_MS: usize = 5;
39+const LTP_MEM_LENGTH_MS: usize = 20;
40+const MAX_FRAME_LENGTH: usize = 20 * 16;
41+const QUANT_LEVEL_ADJUST_Q10: i32 = 80;
42+const N_LEVELS_QGAIN: i32 = 64;
43+const MIN_DELTA_GAIN_QUANT: i32 = -4;
44+const MAX_DELTA_GAIN_QUANT: i32 = 36;
45+const MIN_QGAIN_DB: i32 = 2;
46+const MAX_QGAIN_DB: i32 = 88;
47+const NLSF_QUANT_MAX_AMPLITUDE: i32 = 4;
48+const SHELL_LEN: usize = 16;
49+const MAX_PULSES: i32 = 16;
50+const N_RATE_LEVELS: usize = 10;
51+const PE_MIN_LAG_MS: i32 = 2;
52+const PE_MAX_LAG_MS: i32 = 18;
53+const STEREO_INTERP_LEN_MS: usize = 8;
54+const TYPE_VOICED: i32 = 2;
55+const MAX_LPC_STABILIZE_ITERATIONS: usize = 16;
56+
57+/// Gain quantiser constants (`gain_quant.c`).
58+const GAIN_OFFSET: i32 = (MIN_QGAIN_DB * 128) / 6 + 16 * 128;
59+const GAIN_INV_SCALE_Q16: i32 =
60+ (65536 * (((MAX_QGAIN_DB - MIN_QGAIN_DB) * 128) / 6)) / (N_LEVELS_QGAIN - 1);
61+
62+/// How a frame's parameters relate to the previous frame's.
63+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
64+enum CondCoding {
65+ Independently,
66+ IndependentlyNoLtpScaling,
67+ Conditionally,
68+}
69+
70+// ---------------------------------------------------------------------------
71+// Fixed-point helpers. These are the reference's macros; they are written out
72+// because SILK's output is defined by them bit for bit.
73+// ---------------------------------------------------------------------------
74+
75+#[inline]
76+fn smulwb(a: i32, b: i32) -> i32 {
77+ (((a >> 16) * (b as i16 as i32)) as i64 + ((((a & 0xFFFF) * (b as i16 as i32)) >> 16) as i64))
78+ as i32
79+}
80+
81+#[inline]
82+fn smlawb(a: i32, b: i32, c: i32) -> i32 {
83+ a.wrapping_add(smulwb(b, c))
84+}
85+
86+#[inline]
87+fn smulbb(a: i32, b: i32) -> i32 {
88+ (a as i16 as i32).wrapping_mul(b as i16 as i32)
89+}
90+
91+#[inline]
92+fn smlabb(a: i32, b: i32, c: i32) -> i32 {
93+ a.wrapping_add(smulbb(b, c))
94+}
95+
96+#[inline]
97+fn rshift_round(a: i32, shift: u32) -> i32 {
98+ if shift == 1 {
99+ (a >> 1) + (a & 1)
100+ } else {
101+ ((a >> (shift - 1)) + 1) >> 1
102+ }
103+}
104+
105+#[inline]
106+fn rshift_round64(a: i64, shift: u32) -> i64 {
107+ if shift == 1 {
108+ (a >> 1) + (a & 1)
109+ } else {
110+ ((a >> (shift - 1)) + 1) >> 1
111+ }
112+}
113+
114+#[inline]
115+fn smulww(a: i32, b: i32) -> i32 {
116+ smulwb(a, b).wrapping_add(a.wrapping_mul(rshift_round(b, 16)))
117+}
118+
119+#[inline]
120+fn smlaww(a: i32, b: i32, c: i32) -> i32 {
121+ smlawb(a, b, c).wrapping_add(b.wrapping_mul(rshift_round(c, 16)))
122+}
123+
124+/// `silk_SMMUL`: the top 32 bits of a 32x32 product.
125+#[inline]
126+fn smmul(a: i32, b: i32) -> i32 {
127+ ((a as i64 * b as i64) >> 32) as i32
128+}
129+
130+#[inline]
131+fn sat16(a: i32) -> i16 {
132+ a.clamp(-32768, 32767) as i16
133+}
134+
135+#[inline]
136+fn clz32(x: i32) -> i32 {
137+ if x == 0 {
138+ 32
139+ } else {
140+ (x as u32).leading_zeros() as i32
141+ }
142+}
143+
144+/// `silk_CLZ_FRAC`: leading zeros plus the seven bits below the leading one.
145+#[inline]
146+fn clz_frac(x: i32) -> (i32, i32) {
147+ let lz = clz32(x);
148+ let frac = (x as u32).rotate_right((24 - lz) as u32) as i32 & 0x7F;
149+ (lz, frac)
150+}
151+
152+fn sqrt_approx(x: i32) -> i32 {
153+ if x <= 0 {
154+ return 0;
155+ }
156+ let (lz, frac) = clz_frac(x);
157+ let mut y = if lz & 1 != 0 { 32768 } else { 46214 };
158+ y >>= lz >> 1;
159+ smlawb(y, y, smulbb(213, frac))
160+}
161+
162+
163+fn log2lin(log_q7: i32) -> i32 {
164+ if log_q7 < 0 {
165+ return 0;
166+ }
167+ let mut out = 1i32 << (log_q7 >> 7);
168+ let frac = log_q7 & 0x7F;
169+ let adj = smlawb(frac, smulbb(frac, 128 - frac), -174);
170+ if log_q7 < 2048 {
171+ out += ((out as i64 * adj as i64) >> 7) as i32;
172+ } else {
173+ out = out.wrapping_add((out >> 7).wrapping_mul(adj));
174+ }
175+ out
176+}
177+
178+/// `silk_INVERSE32_varQ`: `(1 << q) / b`, to about 30 bits.
179+fn inverse32_var_q(b32: i32, qres: u32) -> i32 {
180+ debug_assert!(b32 != 0);
181+ let b_headrm = clz32(b32.abs()) - 1;
182+ let b32_nrm = b32 << b_headrm;
183+ let b32_inv = (i32::MAX >> 2) / (b32_nrm >> 16);
184+ let mut result = b32_inv << 16;
185+ let err_q32 = ((1 << 29) - smulwb(b32_nrm, b32_inv)) << 3;
186+ result = smlaww(result, err_q32, b32_inv);
187+ let lshift = 61 - b_headrm - qres as i32;
188+ if lshift <= 0 {
189+ lshift_sat32(result, -lshift)
190+ } else if lshift < 32 {
191+ result >> lshift
192+ } else {
193+ 0
194+ }
195+}
196+
197+/// `silk_DIV32_varQ`: `(a << q) / b`.
198+fn div32_var_q(a32: i32, b32: i32, qres: u32) -> i32 {
199+ debug_assert!(b32 != 0);
200+ let a_headrm = clz32(a32.abs()) - 1;
201+ let mut a32_nrm = a32 << a_headrm;
202+ let b_headrm = clz32(b32.abs()) - 1;
203+ let b32_nrm = b32 << b_headrm;
204+ let b32_inv = (i32::MAX >> 2) / (b32_nrm >> 16);
205+ let mut result = smulwb(a32_nrm, b32_inv);
206+ a32_nrm = a32_nrm.wrapping_sub(smmul(b32_nrm, result).wrapping_shl(3));
207+ result = smlawb(result, a32_nrm, b32_inv);
208+ let lshift = 29 + a_headrm - b_headrm - qres as i32;
209+ if lshift < 0 {
210+ lshift_sat32(result, -lshift)
211+ } else if lshift < 32 {
212+ result >> lshift
213+ } else {
214+ 0
215+ }
216+}
217+
218+fn lshift_sat32(a: i32, shift: i32) -> i32 {
219+ let lim = i32::MAX >> shift;
220+ a.clamp(-lim - 1, lim) << shift
221+}
222+
223+/// `silk_RAND`: the excitation sign PRNG.
224+#[inline]
225+fn silk_rand(seed: i32) -> i32 {
226+ (907633515i32).wrapping_add(seed.wrapping_mul(196314165))
227+}
228+
229+// ---------------------------------------------------------------------------
230+// Decoder state
231+// ---------------------------------------------------------------------------
232+
233+/// Per-frame parameters decoded from the bitstream.
234+#[derive(Clone, Debug, Default)]
235+struct Indices {
236+ signal_type: i32,
237+ quant_offset_type: i32,
238+ gains: [i8; MAX_NB_SUBFR],
239+ nlsf: [i8; MAX_LPC_ORDER + 1],
240+ nlsf_interp_coef_q2: i32,
241+ lag_index: i32,
242+ contour_index: i32,
243+ per_index: usize,
244+ ltp_index: [usize; MAX_NB_SUBFR],
245+ ltp_scale_index: usize,
246+ seed: i32,
247+}
248+
249+/// Everything `decode_parameters` produces for one frame.
250+#[derive(Clone, Debug)]
251+struct FrameCtrl {
252+ gains_q16: [i32; MAX_NB_SUBFR],
253+ pred_coef_q12: [[i16; MAX_LPC_ORDER]; 2],
254+ ltp_coef_q14: [i16; LTP_ORDER * MAX_NB_SUBFR],
255+ ltp_scale_q14: i32,
256+ pitch_l: [i32; MAX_NB_SUBFR],
257+}
258+
259+impl Default for FrameCtrl {
260+ fn default() -> Self {
261+ FrameCtrl {
262+ gains_q16: [0; MAX_NB_SUBFR],
263+ pred_coef_q12: [[0; MAX_LPC_ORDER]; 2],
264+ ltp_coef_q14: [0; LTP_ORDER * MAX_NB_SUBFR],
265+ ltp_scale_q14: 0,
266+ pitch_l: [0; MAX_NB_SUBFR],
267+ }
268+ }
269+}
270+
271+/// One SILK channel's inter-frame state.
272+#[derive(Clone, Debug)]
273+struct ChannelState {
274+ fs_khz: usize,
275+ frame_length: usize,
276+ subfr_length: usize,
277+ ltp_mem_length: usize,
278+ nb_subfr: usize,
279+ lpc_order: usize,
280+ frames_per_packet: usize,
281+ frames_decoded: usize,
282+ /// Wideband uses the 16th-order codebook, NB/MB the 10th-order one.
283+ wb_codebook: bool,
284+ indices: Indices,
285+ /// Synthesis history, `ltp_mem_length + frame_length` samples.
286+ out_buf: [i16; MAX_FRAME_LENGTH + MAX_FRAME_LENGTH],
287+ s_lpc_q14: [i32; MAX_LPC_ORDER],
288+ exc_q14: [i32; MAX_FRAME_LENGTH],
289+ prev_nlsf_q15: [i16; MAX_LPC_ORDER],
290+ prev_gain_q16: i32,
291+ last_gain_index: i32,
292+ prev_signal_type: i32,
293+ ec_prev_signal_type: i32,
294+ ec_prev_lag_index: i32,
295+ lag_prev: i32,
296+ first_frame_after_reset: bool,
297+ vad_flags: [bool; 3],
298+ lbrr_flag: bool,
299+ lbrr_flags: [bool; 3],
300+ resampler: Resampler,
301+}
302+
303+impl ChannelState {
304+ fn new() -> ChannelState {
305+ ChannelState {
306+ fs_khz: 0,
307+ frame_length: 0,
308+ subfr_length: 0,
309+ ltp_mem_length: 0,
310+ nb_subfr: 0,
311+ lpc_order: 0,
312+ frames_per_packet: 1,
313+ frames_decoded: 0,
314+ wb_codebook: false,
315+ indices: Indices::default(),
316+ out_buf: [0; MAX_FRAME_LENGTH * 2],
317+ s_lpc_q14: [0; MAX_LPC_ORDER],
318+ exc_q14: [0; MAX_FRAME_LENGTH],
319+ prev_nlsf_q15: [0; MAX_LPC_ORDER],
320+ prev_gain_q16: 65536,
321+ last_gain_index: 10,
322+ prev_signal_type: 0,
323+ ec_prev_signal_type: 0,
324+ ec_prev_lag_index: 0,
325+ lag_prev: 100,
326+ first_frame_after_reset: true,
327+ vad_flags: [false; 3],
328+ lbrr_flag: false,
329+ lbrr_flags: [false; 3],
330+ resampler: Resampler::default(),
331+ }
332+ }
333+
334+ /// `silk_decoder_set_fs`: geometry for an internal rate.
335+ fn set_fs(&mut self, fs_khz: usize, api_rate: u32) {
336+ self.subfr_length = SUB_FRAME_LENGTH_MS * fs_khz;
337+ let frame_length = self.nb_subfr * self.subfr_length;
338+ if self.fs_khz != fs_khz || self.resampler.fs_out_khz * 1000 != api_rate as usize {
339+ self.resampler = Resampler::new(fs_khz, api_rate as usize / 1000);
340+ }
341+ if self.fs_khz != fs_khz {
342+ self.ltp_mem_length = LTP_MEM_LENGTH_MS * fs_khz;
343+ if fs_khz == 16 {
344+ self.lpc_order = MAX_LPC_ORDER;
345+ self.wb_codebook = true;
346+ } else {
347+ self.lpc_order = 10;
348+ self.wb_codebook = false;
349+ }
350+ self.first_frame_after_reset = true;
351+ self.lag_prev = 100;
352+ self.last_gain_index = 10;
353+ self.prev_signal_type = 0;
354+ self.out_buf.fill(0);
355+ self.s_lpc_q14.fill(0);
356+ }
357+ self.fs_khz = fs_khz;
358+ self.frame_length = frame_length;
359+ }
360+
361+ fn pitch_contour_icdf(&self) -> &'static [u8] {
362+ match (self.fs_khz, self.nb_subfr) {
363+ (8, 4) => &PITCH_CONTOUR_NB_ICDF,
364+ (8, _) => &PITCH_CONTOUR_10_MS_NB_ICDF,
365+ (_, 4) => &PITCH_CONTOUR_ICDF,
366+ _ => &PITCH_CONTOUR_10_MS_ICDF,
367+ }
368+ }
369+
370+ fn pitch_lag_low_bits_icdf(&self) -> &'static [u8] {
371+ match self.fs_khz {
372+ 16 => &UNIFORM8_ICDF,
373+ 12 => &UNIFORM6_ICDF,
374+ _ => &UNIFORM4_ICDF,
375+ }
376+ }
377+}
378+
379+/// Stereo prediction state carried between frames.
380+#[derive(Clone, Debug, Default)]
381+struct StereoState {
382+ pred_prev_q13: [i32; 2],
383+ s_mid: [i16; 2],
384+ s_side: [i16; 2],
385+}
386+
387+/// The SILK decoder for one Opus stream (one or two channels).
388+#[derive(Clone, Debug)]
389+pub struct SilkDecoder {
390+ channels: [ChannelState; 2],
391+ stereo: StereoState,
392+ channels_internal: usize,
393+ channels_api: usize,
394+ api_rate: u32,
395+ prev_decode_only_middle: bool,
396+}
397+
398+impl SilkDecoder {
399+ /// A decoder producing `channels_api` channels at `api_rate` Hz.
400+ pub fn new(api_rate: u32, channels_api: usize) -> SilkDecoder {
401+ SilkDecoder {
402+ channels: [ChannelState::new(), ChannelState::new()],
403+ stereo: StereoState::default(),
404+ channels_internal: 1,
405+ channels_api,
406+ api_rate,
407+ prev_decode_only_middle: false,
408+ }
409+ }
410+
411+ /// Drops all inter-packet state.
412+ pub fn reset(&mut self) {
413+ let api_rate = self.api_rate;
414+ let channels_api = self.channels_api;
415+ *self = SilkDecoder::new(api_rate, channels_api);
416+ }
417+
418+ /// Decodes the SILK part of one Opus frame.
419+ ///
420+ /// `payload_ms` is the Opus frame duration (10, 20, 40 or 60 ms),
421+ /// `internal_rate` the SILK sample rate the TOC implies (8000, 12000 or
422+ /// 16000 Hz), and `channels_internal` how many channels the packet codes.
423+ /// Output is interleaved `i16` at the API rate, `channels_api` channels.
424+ pub fn decode(
425+ &mut self,
426+ dec: &mut RangeDecoder,
427+ out: &mut [i16],
428+ payload_ms: usize,
429+ internal_rate: u32,
430+ channels_internal: usize,
431+ new_packet: bool,
432+ ) -> Result<usize> {
433+ let fs_khz = (internal_rate / 1000) as usize;
434+ if new_packet {
435+ for ch in self.channels.iter_mut() {
436+ ch.frames_decoded = 0;
437+ }
438+ }
439+ let (frames_per_packet, nb_subfr) = match payload_ms {
440+ 10 => (1, 2),
441+ 20 => (1, 4),
442+ 40 => (2, 4),
443+ 60 => (3, 4),
444+ _ => (1, 4),
445+ };
446+ // A stream that gains a second channel starts it from scratch.
447+ if channels_internal > self.channels_internal {
448+ self.channels[1] = ChannelState::new();
449+ }
450+ if self.channels[0].frames_decoded == 0 {
451+ for ch in self.channels.iter_mut().take(channels_internal) {
452+ ch.frames_per_packet = frames_per_packet;
453+ ch.nb_subfr = nb_subfr;
454+ ch.set_fs(fs_khz, self.api_rate);
455+ }
456+ }
457+ if self.channels_api == 2 && channels_internal == 2 && self.channels_internal == 1 {
458+ // The side channel starts from the mid channel's resampler state,
459+ // so the two stay in phase across the mono-to-stereo switch.
460+ self.stereo.pred_prev_q13 = [0; 2];
461+ self.stereo.s_side = [0; 2];
462+ self.channels[1].resampler = self.channels[0].resampler.clone();
463+ }
464+ self.channels_internal = channels_internal;
465+
466+ let mut ms_pred_q13 = [0i32; 2];
467+ let mut decode_only_middle = false;
468+
469+ // Header bits: per-frame VAD flags and the LBRR flag (Section 4.2.3).
470+ if self.channels[0].frames_decoded == 0 {
471+ for n in 0..channels_internal {
472+ for i in 0..self.channels[n].frames_per_packet {
473+ self.channels[n].vad_flags[i] = dec.dec_bit_logp(1);
474+ }
475+ self.channels[n].lbrr_flag = dec.dec_bit_logp(1);
476+ }
477+ for n in 0..channels_internal {
478+ self.channels[n].lbrr_flags = [false; 3];
479+ if self.channels[n].lbrr_flag {
480+ if self.channels[n].frames_per_packet == 1 {
481+ self.channels[n].lbrr_flags[0] = true;
482+ } else {
483+ let icdf: &[u8] = if self.channels[n].frames_per_packet == 2 {
484+ &LBRR_FLAGS_2_ICDF
485+ } else {
486+ &LBRR_FLAGS_3_ICDF
487+ };
488+ let sym = dec.dec_icdf(icdf, 8) as i32 + 1;
489+ for i in 0..self.channels[n].frames_per_packet {
490+ self.channels[n].lbrr_flags[i] = (sym >> i) & 1 != 0;
491+ }
492+ }
493+ }
494+ }
495+ // Skip the LBRR frames: they are only useful for concealment, but
496+ // their symbols must still be consumed to stay in sync.
497+ for i in 0..self.channels[0].frames_per_packet {
498+ for n in 0..channels_internal {
499+ if self.channels[n].lbrr_flags[i] {
500+ if channels_internal == 2 && n == 0 {
501+ stereo_decode_pred(dec, &mut ms_pred_q13);
502+ if !self.channels[1].lbrr_flags[i] {
503+ let _ = dec.dec_icdf(&STEREO_ONLY_CODE_MID_ICDF, 8);
504+ }
505+ }
506+ let cond = if i > 0 && self.channels[n].lbrr_flags[i - 1] {
507+ CondCoding::Conditionally
508+ } else {
509+ CondCoding::Independently
510+ };
511+ let ch = &mut self.channels[n];
512+ decode_indices(ch, dec, i, true, cond);
513+ let mut pulses = [0i32; MAX_FRAME_LENGTH + SHELL_LEN];
514+ let n = ch.frame_length;
515+ decode_pulses(
516+ dec,
517+ &mut pulses,
518+ n,
519+ ch.indices.signal_type,
520+ ch.indices.quant_offset_type,
521+ );
522+ }
523+ }
524+ }
525+ }
526+
527+ // Stereo prediction weights for this frame.
528+ if channels_internal == 2 {
529+ stereo_decode_pred(dec, &mut ms_pred_q13);
530+ let frame = self.channels[0].frames_decoded;
531+ if !self.channels[1].vad_flags[frame] {
532+ decode_only_middle = dec.dec_icdf(&STEREO_ONLY_CODE_MID_ICDF, 8) != 0;
533+ }
534+ }
535+ if channels_internal == 2 && !decode_only_middle && self.prev_decode_only_middle {
536+ self.channels[1].out_buf.fill(0);
537+ self.channels[1].s_lpc_q14.fill(0);
538+ self.channels[1].lag_prev = 100;
539+ self.channels[1].last_gain_index = 10;
540+ self.channels[1].prev_signal_type = 0;
541+ self.channels[1].first_frame_after_reset = true;
542+ }
543+
544+ let has_side = !decode_only_middle;
545+ let mut mid = [0i16; MAX_FRAME_LENGTH + 2];
546+ let mut side = [0i16; MAX_FRAME_LENGTH + 2];
547+ let mut n_samples_dec = 0usize;
548+ for n in 0..channels_internal {
549+ let buf: &mut [i16] = if n == 0 { &mut mid } else { &mut side };
550+ if n == 0 || has_side {
551+ let frame_index = self.channels[0].frames_decoded as i32 - n as i32;
552+ let cond = if frame_index <= 0 {
553+ CondCoding::Independently
554+ } else if n > 0 && self.prev_decode_only_middle {
555+ CondCoding::IndependentlyNoLtpScaling
556+ } else {
557+ CondCoding::Conditionally
558+ };
559+ n_samples_dec = decode_frame(&mut self.channels[n], dec, &mut buf[2..], cond);
560+ } else {
561+ buf[2..2 + n_samples_dec].fill(0);
562+ }
563+ self.channels[n].frames_decoded += 1;
564+ }
565+
566+ // Stereo unmixing, then resampling to the output rate.
567+ if self.channels_api == 2 && channels_internal == 2 {
568+ stereo_ms_to_lr(
569+ &mut self.stereo,
570+ &mut mid,
571+ &mut side,
572+ &ms_pred_q13,
573+ self.channels[0].fs_khz,
574+ n_samples_dec,
575+ );
576+ } else {
577+ mid[0] = self.stereo.s_mid[0];
578+ mid[1] = self.stereo.s_mid[1];
579+ self.stereo.s_mid[0] = mid[n_samples_dec];
580+ self.stereo.s_mid[1] = mid[n_samples_dec + 1];
581+ }
582+ self.prev_decode_only_middle = decode_only_middle;
583+
584+ let out_len = n_samples_dec * self.api_rate as usize / (self.channels[0].fs_khz * 1000);
585+ let mut tmp = vec![0i16; out_len];
586+ let chans = self.channels_api.min(channels_internal);
587+ for n in 0..chans {
588+ let src: &[i16] = if n == 0 { &mid[1..] } else { &side[1..] };
589+ let state = &mut self.channels[n].resampler;
590+ state.process(&mut tmp, &src[..n_samples_dec], n_samples_dec);
591+ if self.channels_api == 2 {
592+ for i in 0..out_len {
593+ out[n + 2 * i] = tmp[i];
594+ }
595+ } else {
596+ out[..out_len].copy_from_slice(&tmp[..out_len]);
597+ }
598+ }
599+ // A mono stream fed to a stereo output is duplicated.
600+ if self.channels_api == 2 && channels_internal == 1 {
601+ for i in 0..out_len {
602+ out[1 + 2 * i] = out[2 * i];
603+ }
604+ }
605+ Ok(out_len)
606+ }
607+}
608+
609+/// `silk_decode_indices` (Section 4.2.7).
610+fn decode_indices(
611+ ch: &mut ChannelState,
612+ dec: &mut RangeDecoder,
613+ frame_index: usize,
614+ decode_lbrr: bool,
615+ cond: CondCoding,
616+) {
617+ let ix = if decode_lbrr || ch.vad_flags[frame_index] {
618+ dec.dec_icdf(&TYPE_OFFSET_VAD_ICDF, 8) as i32 + 2
619+ } else {
620+ dec.dec_icdf(&TYPE_OFFSET_NO_VAD_ICDF, 8) as i32
621+ };
622+ ch.indices.signal_type = ix >> 1;
623+ ch.indices.quant_offset_type = ix & 1;
624+
625+ // Subframe gains (Section 4.2.7.4).
626+ if cond == CondCoding::Conditionally {
627+ ch.indices.gains[0] = dec.dec_icdf(&DELTA_GAIN_ICDF, 8) as i8;
628+ } else {
629+ let msb = dec.dec_icdf(&GAIN_ICDF[ch.indices.signal_type as usize], 8) as i32;
630+ let lsb = dec.dec_icdf(&UNIFORM8_ICDF, 8) as i32;
631+ ch.indices.gains[0] = ((msb << 3) + lsb) as i8;
632+ }
633+ for i in 1..ch.nb_subfr {
634+ ch.indices.gains[i] = dec.dec_icdf(&DELTA_GAIN_ICDF, 8) as i8;
635+ }
636+
637+ // Normalised LSFs (Section 4.2.7.5).
638+ let cb = nlsf_cb(ch.wb_codebook);
639+ let stage1_icdf = &cb.cb1_icdf[(ch.indices.signal_type as usize >> 1) * cb.n_vectors..];
640+ ch.indices.nlsf[0] = dec.dec_icdf(stage1_icdf, 8) as i8;
641+ let (ec_ix, _pred) = nlsf_unpack(cb, ch.indices.nlsf[0] as usize);
642+ for i in 0..cb.order {
643+ let mut ix = dec.dec_icdf(&cb.ec_icdf[ec_ix[i] as usize..], 8) as i32;
644+ if ix == 0 {
645+ ix -= dec.dec_icdf(&NLSF_EXT_ICDF, 8) as i32;
646+ } else if ix == 2 * NLSF_QUANT_MAX_AMPLITUDE {
647+ ix += dec.dec_icdf(&NLSF_EXT_ICDF, 8) as i32;
648+ }
649+ ch.indices.nlsf[i + 1] = (ix - NLSF_QUANT_MAX_AMPLITUDE) as i8;
650+ }
651+ ch.indices.nlsf_interp_coef_q2 = if ch.nb_subfr == MAX_NB_SUBFR {
652+ dec.dec_icdf(&NLSF_INTERPOLATION_FACTOR_ICDF, 8) as i32
653+ } else {
654+ 4
655+ };
656+
657+ // Pitch and LTP (Section 4.2.7.6).
658+ if ch.indices.signal_type == TYPE_VOICED {
659+ let mut absolute = true;
660+ if cond == CondCoding::Conditionally && ch.ec_prev_signal_type == TYPE_VOICED {
661+ let delta = dec.dec_icdf(&PITCH_DELTA_ICDF, 8) as i32;
662+ if delta > 0 {
663+ ch.indices.lag_index = ch.ec_prev_lag_index + delta - 9;
664+ absolute = false;
665+ }
666+ }
667+ if absolute {
668+ ch.indices.lag_index =
669+ dec.dec_icdf(&PITCH_LAG_ICDF, 8) as i32 * (ch.fs_khz as i32 >> 1);
670+ ch.indices.lag_index += dec.dec_icdf(ch.pitch_lag_low_bits_icdf(), 8) as i32;
671+ }
672+ ch.ec_prev_lag_index = ch.indices.lag_index;
673+ ch.indices.contour_index = dec.dec_icdf(ch.pitch_contour_icdf(), 8) as i32;
674+ ch.indices.per_index = dec.dec_icdf(&LTP_PER_INDEX_ICDF, 8);
675+ let gain_icdf: &[u8] = match ch.indices.per_index {
676+ 0 => &LTP_GAIN_ICDF_0,
677+ 1 => &LTP_GAIN_ICDF_1,
678+ _ => &LTP_GAIN_ICDF_2,
679+ };
680+ for k in 0..ch.nb_subfr {
681+ ch.indices.ltp_index[k] = dec.dec_icdf(gain_icdf, 8);
682+ }
683+ ch.indices.ltp_scale_index = if cond == CondCoding::Independently {
684+ dec.dec_icdf(&LTPSCALE_ICDF, 8)
685+ } else {
686+ 0
687+ };
688+ }
689+ ch.ec_prev_signal_type = ch.indices.signal_type;
690+ ch.indices.seed = dec.dec_icdf(&UNIFORM4_ICDF, 8) as i32;
691+}
692+
693+/// `silk_decode_pulses` (Section 4.2.7.8): the excitation.
694+fn decode_pulses(
695+ dec: &mut RangeDecoder,
696+ pulses: &mut [i32],
697+ frame_length: usize,
698+ signal_type: i32,
699+ quant_offset_type: i32,
700+) {
701+ // A 12 kHz 10 ms frame is 120 samples, which is not a whole number of
702+ // 16-sample shell blocks: the last block runs past the frame and its extra
703+ // pulses are discarded, so `pulses` must have room for them.
704+ debug_assert!(pulses.len() >= frame_length.div_ceil(SHELL_LEN) * SHELL_LEN);
705+ let rate_level = dec.dec_icdf(&RATE_LEVELS_ICDF[signal_type as usize >> 1], 8);
706+ let mut iter = frame_length >> 4;
707+ if iter * SHELL_LEN < frame_length {
708+ iter += 1;
709+ }
710+ let mut sum_pulses = [0i32; MAX_FRAME_LENGTH / SHELL_LEN + 1];
711+ let mut n_lshifts = [0i32; MAX_FRAME_LENGTH / SHELL_LEN + 1];
712+ for i in 0..iter {
713+ sum_pulses[i] = dec.dec_icdf(&PULSES_PER_BLOCK_ICDF[rate_level], 8) as i32;
714+ while sum_pulses[i] == MAX_PULSES + 1 {
715+ n_lshifts[i] += 1;
716+ let icdf = &PULSES_PER_BLOCK_ICDF[N_RATE_LEVELS - 1][usize::from(n_lshifts[i] == 10)..];
717+ sum_pulses[i] = dec.dec_icdf(icdf, 8) as i32;
718+ }
719+ }
720+ for i in 0..iter {
721+ let block = &mut pulses[i * SHELL_LEN..];
722+ if sum_pulses[i] > 0 {
723+ shell_decode(dec, block, sum_pulses[i]);
724+ } else {
725+ block[..SHELL_LEN].fill(0);
726+ }
727+ }
728+ // Least significant bits for blocks that overflowed the pulse count.
729+ for i in 0..iter {
730+ if n_lshifts[i] > 0 {
731+ let block = &mut pulses[i * SHELL_LEN..];
732+ for k in 0..SHELL_LEN {
733+ let mut abs_q = block[k];
734+ for _ in 0..n_lshifts[i] {
735+ abs_q <<= 1;
736+ abs_q += dec.dec_icdf(&LSB_ICDF, 8) as i32;
737+ }
738+ block[k] = abs_q;
739+ }
740+ sum_pulses[i] |= n_lshifts[i] << 5;
741+ }
742+ }
743+ decode_signs(
744+ dec,
745+ pulses,
746+ signal_type,
747+ quant_offset_type,
748+ &sum_pulses[..iter],
749+ );
750+}
751+
752+/// One 16-sample shell block (Section 4.2.7.8.3).
753+fn shell_decode(dec: &mut RangeDecoder, pulses0: &mut [i32], total: i32) {
754+ fn split(dec: &mut RangeDecoder, p: i32, table: &[u8]) -> (i32, i32) {
755+ if p > 0 {
756+ let a = dec.dec_icdf(&table[SHELL_CODE_TABLE_OFFSETS[p as usize] as usize..], 8) as i32;
757+ (a, p - a)
758+ } else {
759+ (0, 0)
760+ }
761+ }
762+ let mut p3 = [0i32; 2];
763+ let mut p2 = [0i32; 4];
764+ let mut p1 = [0i32; 8];
765+ (p3[0], p3[1]) = split(dec, total, &SHELL_CODE_TABLE3);
766+ (p2[0], p2[1]) = split(dec, p3[0], &SHELL_CODE_TABLE2);
767+ (p1[0], p1[1]) = split(dec, p2[0], &SHELL_CODE_TABLE1);
768+ (pulses0[0], pulses0[1]) = split(dec, p1[0], &SHELL_CODE_TABLE0);
769+ (pulses0[2], pulses0[3]) = split(dec, p1[1], &SHELL_CODE_TABLE0);
770+ (p1[2], p1[3]) = split(dec, p2[1], &SHELL_CODE_TABLE1);
771+ (pulses0[4], pulses0[5]) = split(dec, p1[2], &SHELL_CODE_TABLE0);
772+ (pulses0[6], pulses0[7]) = split(dec, p1[3], &SHELL_CODE_TABLE0);
773+ (p2[2], p2[3]) = split(dec, p3[1], &SHELL_CODE_TABLE2);
774+ (p1[4], p1[5]) = split(dec, p2[2], &SHELL_CODE_TABLE1);
775+ (pulses0[8], pulses0[9]) = split(dec, p1[4], &SHELL_CODE_TABLE0);
776+ (pulses0[10], pulses0[11]) = split(dec, p1[5], &SHELL_CODE_TABLE0);
777+ (p1[6], p1[7]) = split(dec, p2[3], &SHELL_CODE_TABLE1);
778+ (pulses0[12], pulses0[13]) = split(dec, p1[6], &SHELL_CODE_TABLE0);
779+ (pulses0[14], pulses0[15]) = split(dec, p1[7], &SHELL_CODE_TABLE0);
780+}
781+
782+/// Excitation signs (Section 4.2.7.8.5).
783+fn decode_signs(
784+ dec: &mut RangeDecoder,
785+ pulses: &mut [i32],
786+ signal_type: i32,
787+ quant_offset_type: i32,
788+ sum_pulses: &[i32],
789+) {
790+ let base = 7 * (quant_offset_type + (signal_type << 1)) as usize;
791+ for (i, &p) in sum_pulses.iter().enumerate() {
792+ if p > 0 {
793+ let icdf = [SIGN_ICDF[base + (p & 0x1F).min(6) as usize], 0];
794+ for j in 0..SHELL_LEN {
795+ let idx = i * SHELL_LEN + j;
796+ if idx < pulses.len() && pulses[idx] > 0 {
797+ pulses[idx] *= 2 * dec.dec_icdf(&icdf, 8) as i32 - 1;
798+ }
799+ }
800+ }
801+ }
802+}
803+
804+/// The NLSF codebook for one bandwidth (Section 4.2.7.5).
805+struct NlsfCodebook {
806+ n_vectors: usize,
807+ order: usize,
808+ quant_step_size_q16: i32,
809+ cb1_q8: &'static [u8],
810+ cb1_icdf: &'static [u8],
811+ pred_q8: &'static [u8],
812+ ec_sel: &'static [u8],
813+ ec_icdf: &'static [u8],
814+ delta_min_q15: &'static [i16],
815+}
816+
817+fn nlsf_cb(wideband: bool) -> &'static NlsfCodebook {
818+ static NB_MB: NlsfCodebook = NlsfCodebook {
819+ n_vectors: 32,
820+ order: 10,
821+ // 0.18 in Q16.
822+ quant_step_size_q16: 11796,
823+ cb1_q8: &NLSF_CB1_NB_MB_Q8,
824+ cb1_icdf: &NLSF_CB1_ICDF_NB_MB,
825+ pred_q8: &NLSF_PRED_NB_MB_Q8,
826+ ec_sel: &NLSF_CB2_SELECT_NB_MB,
827+ ec_icdf: &NLSF_CB2_ICDF_NB_MB,
828+ delta_min_q15: &NLSF_DELTA_MIN_NB_MB_Q15,
829+ };
830+ static WB: NlsfCodebook = NlsfCodebook {
831+ n_vectors: 32,
832+ order: 16,
833+ quant_step_size_q16: 9830,
834+ cb1_q8: &NLSF_CB1_WB_Q8,
835+ cb1_icdf: &NLSF_CB1_ICDF_WB,
836+ pred_q8: &NLSF_PRED_WB_Q8,
837+ ec_sel: &NLSF_CB2_SELECT_WB,
838+ ec_icdf: &NLSF_CB2_ICDF_WB,
839+ delta_min_q15: &NLSF_DELTA_MIN_WB_Q15,
840+ };
841+ if wideband { &WB } else { &NB_MB }
842+}
843+
844+/// `silk_NLSF_unpack`: per-coefficient entropy-table selectors and predictors.
845+fn nlsf_unpack(cb: &NlsfCodebook, cb1_index: usize) -> ([i16; MAX_LPC_ORDER], [u8; MAX_LPC_ORDER]) {
846+ let mut ec_ix = [0i16; MAX_LPC_ORDER];
847+ let mut pred = [0u8; MAX_LPC_ORDER];
848+ let sel = &cb.ec_sel[cb1_index * cb.order / 2..];
849+ for i in (0..cb.order).step_by(2) {
850+ let entry = sel[i / 2];
851+ ec_ix[i] = (((entry >> 1) & 7) as i16) * (2 * NLSF_QUANT_MAX_AMPLITUDE as i16 + 1);
852+ pred[i] = cb.pred_q8[i + (entry & 1) as usize * (cb.order - 1)];
853+ ec_ix[i + 1] = (((entry >> 5) & 7) as i16) * (2 * NLSF_QUANT_MAX_AMPLITUDE as i16 + 1);
854+ pred[i + 1] = cb.pred_q8[i + ((entry >> 4) & 1) as usize * (cb.order - 1) + 1];
855+ }
856+ (ec_ix, pred)
857+}
858+
859+/// `silk_NLSF_decode`: indices to normalised LSFs (Section 4.2.7.5.3).
860+fn nlsf_decode(indices: &[i8], cb: &NlsfCodebook) -> [i16; MAX_LPC_ORDER] {
861+ let mut nlsf_q15 = [0i16; MAX_LPC_ORDER];
862+ let base = indices[0] as usize * cb.order;
863+ for i in 0..cb.order {
864+ nlsf_q15[i] = (cb.cb1_q8[base + i] as i16) << 7;
865+ }
866+ let (_, pred_q8) = nlsf_unpack(cb, indices[0] as usize);
867+ // Residual dequantisation, back to front so the prediction chains.
868+ let mut res_q10 = [0i16; MAX_LPC_ORDER];
869+ let mut out_q10 = 0i32;
870+ for i in (0..cb.order).rev() {
871+ let pred_q10 = smulbb(out_q10, pred_q8[i] as i32) >> 8;
872+ out_q10 = (indices[i + 1] as i32) << 10;
873+ if out_q10 > 0 {
874+ out_q10 -= 102; // 0.1 in Q10
875+ } else if out_q10 < 0 {
876+ out_q10 += 102;
877+ }
878+ out_q10 = smlawb(pred_q10, out_q10, cb.quant_step_size_q16);
879+ res_q10[i] = out_q10 as i16;
880+ }
881+ // Weight by the Laroia measure, add, then enforce the minimum spacing.
882+ let w_qw = nlsf_vq_weights_laroia(&nlsf_q15[..cb.order]);
883+ for i in 0..cb.order {
884+ let w_q9 = sqrt_approx((w_qw[i] as i32) << 16);
885+ let v = nlsf_q15[i] as i32 + (((res_q10[i] as i32) << 14) / w_q9);
886+ nlsf_q15[i] = v.clamp(0, 32767) as i16;
887+ }
888+ nlsf_stabilize(&mut nlsf_q15[..cb.order], cb.delta_min_q15);
889+ nlsf_q15
890+}
891+
892+/// `silk_NLSF_VQ_weights_laroia` (Section 4.2.7.5.3).
893+fn nlsf_vq_weights_laroia(nlsf_q15: &[i16]) -> [i16; MAX_LPC_ORDER] {
894+ let d = nlsf_q15.len();
895+ let mut w = [0i16; MAX_LPC_ORDER];
896+ let inv = |x: i32| (1i32 << 17) / x.max(1);
897+ let mut tmp1 = inv(nlsf_q15[0] as i32);
898+ let mut tmp2 = inv(nlsf_q15[1] as i32 - nlsf_q15[0] as i32);
899+ w[0] = (tmp1 + tmp2).min(32767) as i16;
900+ let mut k = 1;
901+ while k < d - 1 {
902+ tmp1 = inv(nlsf_q15[k + 1] as i32 - nlsf_q15[k] as i32);
903+ w[k] = (tmp1 + tmp2).min(32767) as i16;
904+ tmp2 = inv(nlsf_q15[k + 2] as i32 - nlsf_q15[k + 1] as i32);
905+ w[k + 1] = (tmp1 + tmp2).min(32767) as i16;
906+ k += 2;
907+ }
908+ tmp1 = inv((1 << 15) - nlsf_q15[d - 1] as i32);
909+ w[d - 1] = (tmp1 + tmp2).min(32767) as i16;
910+ w
911+}
912+
913+/// `silk_NLSF_stabilize` (Section 4.2.7.5.4): enforce the minimum spacing.
914+fn nlsf_stabilize(nlsf_q15: &mut [i16], delta_min_q15: &[i16]) {
915+ let l = nlsf_q15.len();
916+ for _ in 0..20 {
917+ let mut min_diff = nlsf_q15[0] as i32 - delta_min_q15[0] as i32;
918+ let mut i_min = 0usize;
919+ for i in 1..l {
920+ let diff = nlsf_q15[i] as i32 - (nlsf_q15[i - 1] as i32 + delta_min_q15[i] as i32);
921+ if diff < min_diff {
922+ min_diff = diff;
923+ i_min = i;
924+ }
925+ }
926+ let diff = (1 << 15) - (nlsf_q15[l - 1] as i32 + delta_min_q15[l] as i32);
927+ if diff < min_diff {
928+ min_diff = diff;
929+ i_min = l;
930+ }
931+ if min_diff >= 0 {
932+ return;
933+ }
934+ if i_min == 0 {
935+ nlsf_q15[0] = delta_min_q15[0];
936+ } else if i_min == l {
937+ nlsf_q15[l - 1] = ((1 << 15) - delta_min_q15[l] as i32) as i16;
938+ } else {
939+ let mut min_center = 0i32;
940+ for k in 0..i_min {
941+ min_center += delta_min_q15[k] as i32;
942+ }
943+ min_center += delta_min_q15[i_min] as i32 >> 1;
944+ let mut max_center = 1i32 << 15;
945+ for k in (i_min + 1..=l).rev() {
946+ max_center -= delta_min_q15[k] as i32;
947+ }
948+ max_center -= delta_min_q15[i_min] as i32 >> 1;
949+ let center = rshift_round(nlsf_q15[i_min - 1] as i32 + nlsf_q15[i_min] as i32, 1)
950+ .clamp(min_center, max_center);
951+ nlsf_q15[i_min - 1] = (center - (delta_min_q15[i_min] as i32 >> 1)) as i16;
952+ nlsf_q15[i_min] = nlsf_q15[i_min - 1] + delta_min_q15[i_min];
953+ }
954+ }
955+ // Last resort: sort and clamp (the reference's fallback after 20 loops).
956+ nlsf_q15.sort_unstable();
957+ nlsf_q15[0] = nlsf_q15[0].max(delta_min_q15[0]);
958+ for i in 1..l {
959+ nlsf_q15[i] = nlsf_q15[i].max(nlsf_q15[i - 1].saturating_add(delta_min_q15[i]));
960+ }
961+ nlsf_q15[l - 1] = nlsf_q15[l - 1].min(((1 << 15) - delta_min_q15[l] as i32) as i16);
962+ for i in (0..l - 1).rev() {
963+ nlsf_q15[i] = nlsf_q15[i].min(nlsf_q15[i + 1] - delta_min_q15[i + 1]);
964+ }
965+}
966+
967+/// `silk_NLSF2A` (Section 4.2.7.5.6): LSFs to LPC coefficients.
968+fn nlsf2a(nlsf: &[i16], order: usize) -> [i16; MAX_LPC_ORDER] {
969+ const QA: u32 = 16;
970+ const ORDER16: [usize; 16] = [0, 15, 8, 7, 4, 11, 12, 3, 2, 13, 10, 5, 6, 9, 14, 1];
971+ const ORDER10: [usize; 10] = [0, 9, 6, 3, 4, 5, 8, 1, 2, 7];
972+ let ordering: &[usize] = if order == 16 { &ORDER16 } else { &ORDER10 };
973+
974+ let mut cos_lsf_qa = [0i32; MAX_LPC_ORDER];
975+ for k in 0..order {
976+ let f_int = (nlsf[k] >> 8) as usize;
977+ let f_frac = nlsf[k] as i32 - ((f_int as i32) << 8);
978+ let cos_val = LSFCOSTAB_FIX_Q12[f_int] as i32;
979+ let delta = LSFCOSTAB_FIX_Q12[f_int + 1] as i32 - cos_val;
980+ cos_lsf_qa[ordering[k]] = rshift_round((cos_val << 8) + delta * f_frac, 20 - QA);
981+ }
982+ let dd = order / 2;
983+ let p = nlsf2a_find_poly(&cos_lsf_qa, dd, 0);
984+ let q = nlsf2a_find_poly(&cos_lsf_qa, dd, 1);
985+
986+ let mut a32_qa1 = [0i32; MAX_LPC_ORDER];
987+ for k in 0..dd {
988+ let ptmp = p[k + 1] + p[k];
989+ let qtmp = q[k + 1] - q[k];
990+ a32_qa1[k] = -qtmp - ptmp;
991+ a32_qa1[order - k - 1] = qtmp - ptmp;
992+ }
993+
994+ // Clamp into Q12 without letting the filter blow up.
995+ let mut a_q12 = [0i16; MAX_LPC_ORDER];
996+ let mut i = 0;
997+ while i < 10 {
998+ let mut maxabs = 0i32;
999+ let mut idx = 0usize;
1000+ for k in 0..order {
1001+ let absval = a32_qa1[k].abs();
1002+ if absval > maxabs {
1003+ maxabs = absval;
1004+ idx = k;
1005+ }
1006+ }
1007+ let maxabs_q12 = rshift_round(maxabs, QA + 1 - 12);
1008+ if maxabs_q12 > 32767 {
1009+ let maxabs_q12 = maxabs_q12.min(163838);
1010+ let sc_q16 =
1011+ 65471 - ((maxabs_q12 - 32767) << 14) / ((maxabs_q12 * (idx as i32 + 1)) >> 2);
1012+ bwexpander_32(&mut a32_qa1[..order], sc_q16);
1013+ } else {
1014+ break;
1015+ }
1016+ i += 1;
1017+ }
1018+ if i == 10 {
1019+ for k in 0..order {
1020+ a_q12[k] = sat16(rshift_round(a32_qa1[k], QA + 1 - 12));
1021+ a32_qa1[k] = (a_q12[k] as i32) << (QA + 1 - 12);
1022+ }
1023+ } else {
1024+ for k in 0..order {
1025+ a_q12[k] = rshift_round(a32_qa1[k], QA + 1 - 12) as i16;
1026+ }
1027+ }
1028+ // Bandwidth expansion until the prediction gain is sane.
1029+ for i in 0..MAX_LPC_STABILIZE_ITERATIONS {
1030+ if lpc_inverse_pred_gain(&a_q12[..order]) < 107374 {
1031+ bwexpander_32(&mut a32_qa1[..order], 65536 - (2 << i));
1032+ for k in 0..order {
1033+ a_q12[k] = rshift_round(a32_qa1[k], QA + 1 - 12) as i16;
1034+ }
1035+ } else {
1036+ break;
1037+ }
1038+ }
1039+ a_q12
1040+}
1041+
1042+fn nlsf2a_find_poly(cos_lsf_qa: &[i32], dd: usize, offset: usize) -> [i32; MAX_LPC_ORDER / 2 + 1] {
1043+ const QA: u32 = 16;
1044+ let mut out = [0i32; MAX_LPC_ORDER / 2 + 1];
1045+ out[0] = 1 << QA;
1046+ out[1] = -cos_lsf_qa[offset];
1047+ for k in 1..dd {
1048+ let ftmp = cos_lsf_qa[2 * k + offset];
1049+ out[k + 1] = (out[k - 1] << 1) - rshift_round64(ftmp as i64 * out[k] as i64, QA) as i32;
1050+ for n in (2..=k).rev() {
1051+ out[n] += out[n - 2] - rshift_round64(ftmp as i64 * out[n - 1] as i64, QA) as i32;
1052+ }
1053+ out[1] -= ftmp;
1054+ }
1055+ out
1056+}
1057+
1058+fn bwexpander_32(ar: &mut [i32], chirp_q16: i32) {
1059+ let mut chirp = chirp_q16;
1060+ let chirp_minus_one = chirp_q16 - 65536;
1061+ let d = ar.len();
1062+ for coef in ar.iter_mut().take(d - 1) {
1063+ *coef = smulww(chirp, *coef);
1064+ chirp += rshift_round(chirp.wrapping_mul(chirp_minus_one), 16);
1065+ }
1066+ ar[d - 1] = smulww(chirp, ar[d - 1]);
1067+}
1068+
1069+/// `silk_LPC_inverse_pred_gain` (Section 4.2.7.5.8), in Q30.
1070+fn lpc_inverse_pred_gain(a_q12: &[i16]) -> i32 {
1071+ const QA: u32 = 24;
1072+ const A_LIMIT: i32 = 16773022; // 0.99975 in Q24
1073+ let order = a_q12.len();
1074+ let mut a = [[0i32; MAX_LPC_ORDER]; 2];
1075+ let mut dc_resp = 0i32;
1076+ for k in 0..order {
1077+ dc_resp += a_q12[k] as i32;
1078+ a[order & 1][k] = (a_q12[k] as i32) << (QA - 12);
1079+ }
1080+ if dc_resp >= 4096 {
1081+ return 0;
1082+ }
1083+ let mut cur = order & 1;
1084+ let mut inv_gain_q30 = 1i32 << 30;
1085+ for k in (1..order).rev() {
1086+ if a[cur][k] > A_LIMIT || a[cur][k] < -A_LIMIT {
1087+ return 0;
1088+ }
1089+ let rc_q31 = -(a[cur][k] << (31 - QA));
1090+ let rc_mult1_q30 = (1i32 << 30) - smmul(rc_q31, rc_q31);
1091+ let mult2q = 32 - clz32(rc_mult1_q30.abs());
1092+ let rc_mult2 = inverse32_var_q(rc_mult1_q30, (mult2q + 30) as u32);
1093+ inv_gain_q30 = smmul(inv_gain_q30, rc_mult1_q30) << 2;
1094+ let old = cur;
1095+ cur = k & 1;
1096+ for n in 0..k {
1097+ let tmp = a[old][n] - mul32_frac_q(a[old][k - n - 1], rc_q31, 31);
1098+ a[cur][n] = mul32_frac_q(tmp, rc_mult2, mult2q as u32);
1099+ }
1100+ }
1101+ if a[cur][0] > A_LIMIT || a[cur][0] < -A_LIMIT {
1102+ return 0;
1103+ }
1104+ let rc_q31 = -(a[cur][0] << (31 - QA));
1105+ let rc_mult1_q30 = (1i32 << 30) - smmul(rc_q31, rc_q31);
1106+ smmul(inv_gain_q30, rc_mult1_q30) << 2
1107+}
1108+
1109+#[inline]
1110+fn mul32_frac_q(a: i32, b: i32, q: u32) -> i32 {
1111+ rshift_round64(a as i64 * b as i64, q) as i32
1112+}
1113+
1114+/// `silk_gains_dequant` (Section 4.2.7.4).
1115+fn gains_dequant(
1116+ indices: &[i8],
1117+ prev_ind: &mut i32,
1118+ conditional: bool,
1119+ nb_subfr: usize,
1120+) -> [i32; MAX_NB_SUBFR] {
1121+ let mut gains = [0i32; MAX_NB_SUBFR];
1122+ for k in 0..nb_subfr {
1123+ if k == 0 && !conditional {
1124+ // A gain may not drop more than 16 steps below the last one.
1125+ *prev_ind = (indices[k] as i32).max(*prev_ind - 16);
1126+ } else {
1127+ let ind_tmp = indices[k] as i32 + MIN_DELTA_GAIN_QUANT;
1128+ let threshold = 2 * MAX_DELTA_GAIN_QUANT - N_LEVELS_QGAIN + *prev_ind;
1129+ if ind_tmp > threshold {
1130+ *prev_ind += (ind_tmp << 1) - threshold;
1131+ } else {
1132+ *prev_ind += ind_tmp;
1133+ }
1134+ }
1135+ *prev_ind = (*prev_ind).clamp(0, N_LEVELS_QGAIN - 1);
1136+ gains[k] = log2lin((smulwb(GAIN_INV_SCALE_Q16, *prev_ind) + GAIN_OFFSET).min(3967));
1137+ }
1138+ gains
1139+}
1140+
1141+/// `silk_decode_pitch` (Section 4.2.7.6.1).
1142+fn decode_pitch(
1143+ lag_index: i32,
1144+ contour_index: i32,
1145+ fs_khz: i32,
1146+ nb_subfr: usize,
1147+) -> [i32; MAX_NB_SUBFR] {
1148+ let mut pitch = [0i32; MAX_NB_SUBFR];
1149+ let min_lag = PE_MIN_LAG_MS * fs_khz;
1150+ let max_lag = PE_MAX_LAG_MS * fs_khz;
1151+ let lag = min_lag + lag_index;
1152+ for k in 0..nb_subfr {
1153+ let offset = if fs_khz == 8 {
1154+ if nb_subfr == 4 {
1155+ CB_LAGS_STAGE2[k][contour_index as usize]
1156+ } else {
1157+ CB_LAGS_STAGE2_10_MS[k][contour_index as usize]
1158+ }
1159+ } else if nb_subfr == 4 {
1160+ CB_LAGS_STAGE3[k][contour_index as usize]
1161+ } else {
1162+ CB_LAGS_STAGE3_10_MS[k][contour_index as usize]
1163+ };
1164+ pitch[k] = (lag + offset as i32).clamp(min_lag, max_lag);
1165+ }
1166+ pitch
1167+}
1168+
1169+/// `silk_decode_parameters`.
1170+fn decode_parameters(ch: &mut ChannelState, cond: CondCoding) -> FrameCtrl {
1171+ let mut ctrl = FrameCtrl {
1172+ gains_q16: gains_dequant(
1173+ &ch.indices.gains,
1174+ &mut ch.last_gain_index,
1175+ cond == CondCoding::Conditionally,
1176+ ch.nb_subfr,
1177+ ),
1178+ ..Default::default()
1179+ };
1180+ let cb = nlsf_cb(ch.wb_codebook);
1181+ let nlsf_q15 = nlsf_decode(&ch.indices.nlsf, cb);
1182+ ctrl.pred_coef_q12[1] = nlsf2a(&nlsf_q15[..ch.lpc_order], ch.lpc_order);
1183+
1184+ if ch.first_frame_after_reset {
1185+ ch.indices.nlsf_interp_coef_q2 = 4;
1186+ }
1187+ if ch.indices.nlsf_interp_coef_q2 < 4 {
1188+ // Interpolate the first half of the frame from the previous LSFs.
1189+ let mut nlsf0 = [0i16; MAX_LPC_ORDER];
1190+ for i in 0..ch.lpc_order {
1191+ nlsf0[i] = (ch.prev_nlsf_q15[i] as i32
1192+ + ((ch.indices.nlsf_interp_coef_q2
1193+ * (nlsf_q15[i] as i32 - ch.prev_nlsf_q15[i] as i32))
1194+ >> 2)) as i16;
1195+ }
1196+ ctrl.pred_coef_q12[0] = nlsf2a(&nlsf0[..ch.lpc_order], ch.lpc_order);
1197+ } else {
1198+ ctrl.pred_coef_q12[0] = ctrl.pred_coef_q12[1];
1199+ }
1200+ ch.prev_nlsf_q15[..ch.lpc_order].copy_from_slice(&nlsf_q15[..ch.lpc_order]);
1201+
1202+ if ch.indices.signal_type == TYPE_VOICED {
1203+ ctrl.pitch_l = decode_pitch(
1204+ ch.indices.lag_index,
1205+ ch.indices.contour_index,
1206+ ch.fs_khz as i32,
1207+ ch.nb_subfr,
1208+ );
1209+ let cbk: &[[i8; 5]] = match ch.indices.per_index {
1210+ 0 => &LTP_GAIN_VQ_0,
1211+ 1 => &LTP_GAIN_VQ_1,
1212+ _ => &LTP_GAIN_VQ_2,
1213+ };
1214+ for k in 0..ch.nb_subfr {
1215+ let v = &cbk[ch.indices.ltp_index[k]];
1216+ for i in 0..LTP_ORDER {
1217+ ctrl.ltp_coef_q14[k * LTP_ORDER + i] = (v[i] as i16) << 7;
1218+ }
1219+ }
1220+ ctrl.ltp_scale_q14 = LTPSCALES_TABLE_Q14[ch.indices.ltp_scale_index] as i32;
1221+ }
1222+ ctrl
1223+}
1224+
1225+/// `silk_LPC_analysis_filter`: the whitening filter used to rebuild the LTP
1226+/// state from previously decoded output.
1227+fn lpc_analysis_filter(out: &mut [i16], input: &[i16], b_q12: &[i16], len: usize, d: usize) {
1228+ for ix in d..len {
1229+ let mut acc = 0i32;
1230+ for j in 0..d {
1231+ acc = acc.wrapping_add(smulbb(input[ix - 1 - j] as i32, b_q12[j] as i32));
1232+ }
1233+ let v = ((input[ix] as i32) << 12).wrapping_sub(acc);
1234+ out[ix] = sat16(rshift_round(v, 12));
1235+ }
1236+ out[..d].fill(0);
1237+}
1238+
1239+/// `silk_decode_core` (Section 4.2.7.9): excitation to output samples.
1240+fn decode_core(ch: &mut ChannelState, ctrl: &FrameCtrl, xq: &mut [i16], pulses: &[i32]) {
1241+ let offset_q10 = QUANTIZATION_OFFSETS_Q10[ch.indices.signal_type as usize >> 1]
1242+ [ch.indices.quant_offset_type as usize] as i32;
1243+ let nlsf_interpolated = ch.indices.nlsf_interp_coef_q2 < 4;
1244+
1245+ // Excitation: pulses with a quantisation offset and a pseudo-random sign.
1246+ let mut rand_seed = ch.indices.seed;
1247+ for i in 0..ch.frame_length {
1248+ rand_seed = silk_rand(rand_seed);
1249+ let mut e = pulses[i] << 14;
1250+ if e > 0 {
1251+ e -= QUANT_LEVEL_ADJUST_Q10 << 4;
1252+ } else if e < 0 {
1253+ e += QUANT_LEVEL_ADJUST_Q10 << 4;
1254+ }
1255+ e += offset_q10 << 4;
1256+ ch.exc_q14[i] = if rand_seed < 0 { -e } else { e };
1257+ rand_seed = rand_seed.wrapping_add(pulses[i]);
1258+ }
1259+
1260+ let mut s_lpc_q14 = [0i32; MAX_LPC_ORDER + 5 * 16];
1261+ s_lpc_q14[..MAX_LPC_ORDER].copy_from_slice(&ch.s_lpc_q14);
1262+ let mut s_ltp = [0i16; MAX_FRAME_LENGTH];
1263+ let mut s_ltp_q15 = [0i32; 2 * MAX_FRAME_LENGTH];
1264+ let mut sltp_buf_idx = ch.ltp_mem_length;
1265+ let mut lag = 0usize;
1266+ let mut res_q14 = [0i32; 5 * 16];
1267+
1268+ for k in 0..ch.nb_subfr {
1269+ let a_q12 = &ctrl.pred_coef_q12[k >> 1];
1270+ let b_q14 = &ctrl.ltp_coef_q14[k * LTP_ORDER..k * LTP_ORDER + LTP_ORDER];
1271+ let gain_q10 = ctrl.gains_q16[k] >> 6;
1272+ let mut inv_gain_q31 = inverse32_var_q(ctrl.gains_q16[k], 47);
1273+ let gain_adj_q16 = if ctrl.gains_q16[k] != ch.prev_gain_q16 {
1274+ let adj = div32_var_q(ch.prev_gain_q16, ctrl.gains_q16[k], 16);
1275+ for v in s_lpc_q14.iter_mut().take(MAX_LPC_ORDER) {
1276+ *v = smulww(adj, *v);
1277+ }
1278+ adj
1279+ } else {
1280+ 1 << 16
1281+ };
1282+ ch.prev_gain_q16 = ctrl.gains_q16[k];
1283+
1284+ if ch.indices.signal_type == TYPE_VOICED {
1285+ lag = ctrl.pitch_l[k] as usize;
1286+ if k == 0 || (k == 2 && nlsf_interpolated) {
1287+ // Rebuild the LTP history by whitening past output.
1288+ let start_idx = ch.ltp_mem_length - lag - ch.lpc_order - LTP_ORDER / 2;
1289+ if k == 2 {
1290+ let n = 2 * ch.subfr_length;
1291+ let base = ch.ltp_mem_length;
1292+ ch.out_buf[base..base + n].copy_from_slice(&xq[..n]);
1293+ }
1294+ lpc_analysis_filter(
1295+ &mut s_ltp[start_idx..],
1296+ &ch.out_buf[start_idx + k * ch.subfr_length..],
1297+ a_q12,
1298+ ch.ltp_mem_length - start_idx,
1299+ ch.lpc_order,
1300+ );
1301+ if k == 0 {
1302+ inv_gain_q31 = smulwb(inv_gain_q31, ctrl.ltp_scale_q14) << 2;
1303+ }
1304+ for i in 0..lag + LTP_ORDER / 2 {
1305+ s_ltp_q15[sltp_buf_idx - i - 1] =
1306+ smulwb(inv_gain_q31, s_ltp[ch.ltp_mem_length - i - 1] as i32);
1307+ }
1308+ } else if gain_adj_q16 != 1 << 16 {
1309+ for i in 0..lag + LTP_ORDER / 2 {
1310+ s_ltp_q15[sltp_buf_idx - i - 1] =
1311+ smulww(gain_adj_q16, s_ltp_q15[sltp_buf_idx - i - 1]);
1312+ }
1313+ }
1314+ }
1315+
1316+ // Long-term prediction.
1317+ let exc_base = k * ch.subfr_length;
1318+ let pres_q14: &[i32] = if ch.indices.signal_type == TYPE_VOICED {
1319+ let pred_base = sltp_buf_idx - lag + LTP_ORDER / 2;
1320+ for i in 0..ch.subfr_length {
1321+ let pred_idx = pred_base + i;
1322+ let mut ltp_pred_q13 = 2i32;
1323+ for (j, &b) in b_q14.iter().enumerate() {
1324+ ltp_pred_q13 = smlawb(ltp_pred_q13, s_ltp_q15[pred_idx - j], b as i32);
1325+ }
1326+ res_q14[i] = ch.exc_q14[exc_base + i].wrapping_add(ltp_pred_q13 << 1);
1327+ s_ltp_q15[sltp_buf_idx] = res_q14[i] << 1;
1328+ sltp_buf_idx += 1;
1329+ }
1330+ &res_q14[..ch.subfr_length]
1331+ } else {
1332+ &ch.exc_q14[exc_base..exc_base + ch.subfr_length]
1333+ };
1334+
1335+ // Short-term (LPC) synthesis.
1336+ for i in 0..ch.subfr_length {
1337+ let mut lpc_pred_q10 = (ch.lpc_order >> 1) as i32;
1338+ for j in 0..ch.lpc_order {
1339+ lpc_pred_q10 = smlawb(
1340+ lpc_pred_q10,
1341+ s_lpc_q14[MAX_LPC_ORDER + i - 1 - j],
1342+ a_q12[j] as i32,
1343+ );
1344+ }
1345+ s_lpc_q14[MAX_LPC_ORDER + i] = pres_q14[i].wrapping_add(lpc_pred_q10 << 4);
1346+ xq[k * ch.subfr_length + i] = sat16(rshift_round(
1347+ smulww(s_lpc_q14[MAX_LPC_ORDER + i], gain_q10),
1348+ 8,
1349+ ));
1350+ }
1351+ s_lpc_q14.copy_within(ch.subfr_length..ch.subfr_length + MAX_LPC_ORDER, 0);
1352+ }
1353+ ch.s_lpc_q14.copy_from_slice(&s_lpc_q14[..MAX_LPC_ORDER]);
1354+}
1355+
1356+/// `silk_decode_frame`: one SILK frame of one channel.
1357+fn decode_frame(
1358+ ch: &mut ChannelState,
1359+ dec: &mut RangeDecoder,
1360+ out: &mut [i16],
1361+ cond: CondCoding,
1362+) -> usize {
1363+ let frame_index = ch.frames_decoded;
1364+ decode_indices(ch, dec, frame_index, false, cond);
1365+ let mut pulses = [0i32; MAX_FRAME_LENGTH + SHELL_LEN];
1366+ decode_pulses(
1367+ dec,
1368+ &mut pulses,
1369+ ch.frame_length,
1370+ ch.indices.signal_type,
1371+ ch.indices.quant_offset_type,
1372+ );
1373+ let mut ctrl = decode_parameters(ch, cond);
1374+ if cond == CondCoding::IndependentlyNoLtpScaling {
1375+ ctrl.ltp_scale_q14 = LTPSCALES_TABLE_Q14[0] as i32;
1376+ }
1377+ decode_core(ch, &ctrl, out, &pulses);
1378+ ch.prev_signal_type = ch.indices.signal_type;
1379+ ch.first_frame_after_reset = false;
1380+ ch.lag_prev = ctrl.pitch_l[ch.nb_subfr - 1];
1381+
1382+ // Slide the synthesis history.
1383+ let mv_len = ch.ltp_mem_length - ch.frame_length;
1384+ ch.out_buf
1385+ .copy_within(ch.frame_length..ch.frame_length + mv_len, 0);
1386+ ch.out_buf[mv_len..mv_len + ch.frame_length].copy_from_slice(&out[..ch.frame_length]);
1387+ ch.frame_length
1388+}
1389+
1390+/// `silk_stereo_decode_pred` (Section 4.2.7.1).
1391+fn stereo_decode_pred(dec: &mut RangeDecoder, pred_q13: &mut [i32; 2]) {
1392+ let n = dec.dec_icdf(&STEREO_PRED_JOINT_ICDF, 8) as i32;
1393+ let mut ix = [[0i32; 3]; 2];
1394+ ix[0][2] = n / 5;
1395+ ix[1][2] = n - 5 * ix[0][2];
1396+ for row in ix.iter_mut() {
1397+ row[0] = dec.dec_icdf(&UNIFORM3_ICDF, 8) as i32;
1398+ row[1] = dec.dec_icdf(&UNIFORM5_ICDF, 8) as i32;
1399+ }
1400+ for n in 0..2 {
1401+ let i0 = (ix[n][0] + 3 * ix[n][2]) as usize;
1402+ let low = STEREO_PRED_QUANT_Q13[i0] as i32;
1403+ // 0.5/5 in Q16.
1404+ let step = smulwb(STEREO_PRED_QUANT_Q13[i0 + 1] as i32 - low, 6554);
1405+ pred_q13[n] = smlabb(low, step, 2 * ix[n][1] + 1);
1406+ }
1407+ pred_q13[0] -= pred_q13[1];
1408+}
1409+
1410+/// `silk_stereo_MS_to_LR` (Section 4.2.8): mid/side back to left/right.
1411+fn stereo_ms_to_lr(
1412+ state: &mut StereoState,
1413+ x1: &mut [i16],
1414+ x2: &mut [i16],
1415+ pred_q13: &[i32; 2],
1416+ fs_khz: usize,
1417+ frame_length: usize,
1418+) {
1419+ x1[0] = state.s_mid[0];
1420+ x1[1] = state.s_mid[1];
1421+ x2[0] = state.s_side[0];
1422+ x2[1] = state.s_side[1];
1423+ state.s_mid[0] = x1[frame_length];
1424+ state.s_mid[1] = x1[frame_length + 1];
1425+ state.s_side[0] = x2[frame_length];
1426+ state.s_side[1] = x2[frame_length + 1];
1427+
1428+ let interp = STEREO_INTERP_LEN_MS * fs_khz;
1429+ let mut pred0 = state.pred_prev_q13[0];
1430+ let mut pred1 = state.pred_prev_q13[1];
1431+ let denom_q16 = (1i32 << 16) / interp as i32;
1432+ let delta0 = rshift_round(smulbb(pred_q13[0] - state.pred_prev_q13[0], denom_q16), 16);
1433+ let delta1 = rshift_round(smulbb(pred_q13[1] - state.pred_prev_q13[1], denom_q16), 16);
1434+ for n in 0..frame_length {
1435+ if n < interp {
1436+ pred0 += delta0;
1437+ pred1 += delta1;
1438+ } else {
1439+ pred0 = pred_q13[0];
1440+ pred1 = pred_q13[1];
1441+ }
1442+ let sum = ((x1[n] as i32 + x1[n + 2] as i32) + ((x1[n + 1] as i32) << 1)) << 9;
1443+ let mut acc = smlawb((x2[n + 1] as i32) << 8, sum, pred0);
1444+ acc = smlawb(acc, (x1[n + 1] as i32) << 11, pred1);
1445+ x2[n + 1] = sat16(rshift_round(acc, 8));
1446+ }
1447+ state.pred_prev_q13[0] = pred_q13[0];
1448+ state.pred_prev_q13[1] = pred_q13[1];
1449+
1450+ for n in 0..frame_length {
1451+ let sum = x1[n + 1] as i32 + x2[n + 1] as i32;
1452+ let diff = x1[n + 1] as i32 - x2[n + 1] as i32;
1453+ x1[n + 1] = sat16(sum);
1454+ x2[n + 1] = sat16(diff);
1455+ }
1456+}
1457+
1458+// ---------------------------------------------------------------------------
1459+// Resampling (Section 4.2.9)
1460+// ---------------------------------------------------------------------------
1461+
1462+/// The SILK output resampler: 8/12/16 kHz internal to the API rate.
1463+///
1464+/// The RFC calls the resampler non-normative but its *delay* normative, so this
1465+/// is the reference's structure — a 2x all-pass upsampler followed by a
1466+/// 12-phase fractional FIR, with the same per-rate input delay.
1467+#[derive(Clone, Debug, Default)]
1468+struct Resampler {
1469+ fs_in_khz: usize,
1470+ fs_out_khz: usize,
1471+ input_delay: usize,
1472+ batch_size: usize,
1473+ inv_ratio_q16: i32,
1474+ /// All-pass state for the 2x upsampler.
1475+ s_iir: [i32; 6],
1476+ /// FIR history.
1477+ s_fir: [i16; 8],
1478+ delay_buf: DelayBuf,
1479+ /// Down-sampling coefficients, when the output rate is the lower one.
1480+ down: Option<DownFir>,
1481+}
1482+
1483+/// Fixed-size delay line; a newtype only because `[i16; 48]` has no `Default`.
1484+#[derive(Clone, Copy, Debug)]
1485+struct DelayBuf([i16; 48]);
1486+
1487+impl Default for DelayBuf {
1488+ fn default() -> Self {
1489+ DelayBuf([0; 48])
1490+ }
1491+}
1492+
1493+impl core::ops::Deref for DelayBuf {
1494+ type Target = [i16; 48];
1495+ fn deref(&self) -> &[i16; 48] {
1496+ &self.0
1497+ }
1498+}
1499+
1500+impl core::ops::DerefMut for DelayBuf {
1501+ fn deref_mut(&mut self) -> &mut [i16; 48] {
1502+ &mut self.0
1503+ }
1504+}
1505+
1506+#[derive(Clone, Debug)]
1507+struct DownFir {
1508+ fracs: usize,
1509+ order: usize,
1510+ coefs: &'static [i16],
1511+ state: [i32; 2],
1512+ buf: Vec<i32>,
1513+}
1514+
1515+/// `rateID` in the reference: an index into the delay matrix.
1516+fn rate_id(rate: usize) -> usize {
1517+ (((rate >> 12) - usize::from(rate > 16000)) >> usize::from(rate > 24000)) - 1
1518+}
1519+
1520+const DELAY_MATRIX_DEC: [[u8; 5]; 3] = [[4, 0, 2, 0, 0], [0, 9, 4, 7, 4], [0, 3, 12, 7, 7]];
1521+
1522+impl Resampler {
1523+ fn new(fs_in_khz: usize, fs_out_khz: usize) -> Resampler {
1524+ let fs_in = fs_in_khz * 1000;
1525+ let fs_out = fs_out_khz * 1000;
1526+ let mut r = Resampler {
1527+ fs_in_khz,
1528+ fs_out_khz,
1529+ input_delay: DELAY_MATRIX_DEC[rate_id(fs_in)][rate_id(fs_out)] as usize,
1530+ batch_size: fs_in_khz * 10,
1531+ ..Default::default()
1532+ };
1533+ let mut up2x = 0;
1534+ if fs_out > fs_in && fs_out != 2 * fs_in {
1535+ up2x = 1;
1536+ } else if fs_out < fs_in {
1537+ let (fracs, order, coefs): (usize, usize, &'static [i16]) = if fs_out * 4 == fs_in * 3 {
1538+ (3, 18, &RESAMPLER_3_4_COEFS)
1539+ } else if fs_out * 3 == fs_in * 2 {
1540+ (2, 18, &RESAMPLER_2_3_COEFS)
1541+ } else if fs_out * 2 == fs_in {
1542+ (1, 24, &RESAMPLER_1_2_COEFS)
1543+ } else if fs_out * 3 == fs_in {
1544+ (1, 36, &RESAMPLER_1_3_COEFS)
1545+ } else if fs_out * 4 == fs_in {
1546+ (1, 36, &RESAMPLER_1_4_COEFS)
1547+ } else {
1548+ (1, 36, &RESAMPLER_1_6_COEFS)
1549+ };
1550+ r.down = Some(DownFir {
1551+ fracs,
1552+ order,
1553+ coefs,
1554+ state: [0; 2],
1555+ buf: vec![0; 480 + 36],
1556+ });
1557+ }
1558+ r.inv_ratio_q16 = ((((fs_in as i64) << (14 + up2x)) / fs_out as i64) as i32) << 2;
1559+ while smulww(r.inv_ratio_q16, fs_out as i32) < ((fs_in as i32) << up2x) {
1560+ r.inv_ratio_q16 += 1;
1561+ }
1562+ r
1563+ }
1564+
1565+ /// Resamples `in_len` input samples into `in_len * out/in` outputs.
1566+ ///
1567+ /// The first `Fs_in_kHz` samples come from the delay line (the normative
1568+ /// per-rate input delay); the rest are read straight from `input`, and its
1569+ /// tail is kept for the next call.
1570+ fn process(&mut self, out: &mut [i16], input: &[i16], in_len: usize) {
1571+ let n_first = self.fs_in_khz - self.input_delay;
1572+ let mut head = [0i16; 48];
1573+ head[..self.input_delay].copy_from_slice(&self.delay_buf[..self.input_delay]);
1574+ head[self.input_delay..self.fs_in_khz].copy_from_slice(&input[..n_first]);
1575+ let head = &head[..self.fs_in_khz];
1576+ let rest = &input[n_first..n_first + (in_len - self.fs_in_khz)];
1577+ let split = self.fs_out_khz;
1578+ let rest_out = (in_len - self.fs_in_khz) * self.fs_out_khz / self.fs_in_khz;
1579+ if self.fs_in_khz == self.fs_out_khz {
1580+ out[..self.fs_in_khz].copy_from_slice(head);
1581+ out[split..split + rest_out].copy_from_slice(rest);
1582+ } else if self.down.is_some() {
1583+ let head = head.to_vec();
1584+ self.down_fir(&mut out[..split], &head);
1585+ self.down_fir(&mut out[split..split + rest_out], rest);
1586+ } else if self.fs_out_khz == 2 * self.fs_in_khz {
1587+ let head = head.to_vec();
1588+ self.up2_hq(&mut out[..split], &head);
1589+ self.up2_hq(&mut out[split..split + rest_out], rest);
1590+ } else {
1591+ let head = head.to_vec();
1592+ self.iir_fir(&mut out[..split], &head);
1593+ self.iir_fir(&mut out[split..split + rest_out], rest);
1594+ }
1595+ self.delay_buf[..self.input_delay]
1596+ .copy_from_slice(&input[in_len - self.input_delay..in_len]);
1597+ }
1598+
1599+ /// `silk_resampler_private_up2_HQ`: 2x all-pass upsampling.
1600+ fn up2_hq(&mut self, out: &mut [i16], input: &[i16]) {
1601+ for (k, &sample) in input.iter().enumerate() {
1602+ let in32 = (sample as i32) << 10;
1603+ let mut y = in32 - self.s_iir[0];
1604+ let mut x = smulwb(y, RESAMPLER_UP2_HQ_0[0] as i32);
1605+ let mut out32_1 = self.s_iir[0] + x;
1606+ self.s_iir[0] = in32 + x;
1607+ y = out32_1 - self.s_iir[1];
1608+ x = smulwb(y, RESAMPLER_UP2_HQ_0[1] as i32);
1609+ let mut out32_2 = self.s_iir[1] + x;
1610+ self.s_iir[1] = out32_1 + x;
1611+ y = out32_2 - self.s_iir[2];
1612+ x = smlawb(y, y, RESAMPLER_UP2_HQ_0[2] as i32);
1613+ out32_1 = self.s_iir[2] + x;
1614+ self.s_iir[2] = out32_2 + x;
1615+ out[2 * k] = sat16(rshift_round(out32_1, 10));
1616+
1617+ y = in32 - self.s_iir[3];
1618+ x = smulwb(y, RESAMPLER_UP2_HQ_1[0] as i32);
1619+ out32_1 = self.s_iir[3] + x;
1620+ self.s_iir[3] = in32 + x;
1621+ y = out32_1 - self.s_iir[4];
1622+ x = smulwb(y, RESAMPLER_UP2_HQ_1[1] as i32);
1623+ out32_2 = self.s_iir[4] + x;
1624+ self.s_iir[4] = out32_1 + x;
1625+ y = out32_2 - self.s_iir[5];
1626+ x = smlawb(y, y, RESAMPLER_UP2_HQ_1[2] as i32);
1627+ out32_1 = self.s_iir[5] + x;
1628+ self.s_iir[5] = out32_2 + x;
1629+ out[2 * k + 1] = sat16(rshift_round(out32_1, 10));
1630+ }
1631+ }
1632+
1633+ /// `silk_resampler_private_IIR_FIR`: 2x upsample then fractional FIR.
1634+ fn iir_fir(&mut self, out: &mut [i16], input: &[i16]) {
1635+ let mut written = 0usize;
1636+ let mut pos = 0usize;
1637+ let mut buf = vec![0i16; 2 * self.batch_size + 8];
1638+ buf[..8].copy_from_slice(&self.s_fir);
1639+ let mut n_samples_in = 0;
1640+ while pos < input.len() {
1641+ n_samples_in = (input.len() - pos).min(self.batch_size);
1642+ self.up2_hq(
1643+ &mut buf[8..8 + 2 * n_samples_in],
1644+ &input[pos..pos + n_samples_in],
1645+ );
1646+ let max_index_q16 = (n_samples_in as i32) << 17;
1647+ let mut index_q16 = 0i32;
1648+ while index_q16 < max_index_q16 {
1649+ let table_index = smulwb(index_q16 & 0xFFFF, 12) as usize;
1650+ let b = &buf[(index_q16 >> 16) as usize..];
1651+ let mut res = smulbb(b[0] as i32, RESAMPLER_FRAC_FIR_12[table_index][0] as i32);
1652+ res = smlabb(
1653+ res,
1654+ b[1] as i32,
1655+ RESAMPLER_FRAC_FIR_12[table_index][1] as i32,
1656+ );
1657+ res = smlabb(
1658+ res,
1659+ b[2] as i32,
1660+ RESAMPLER_FRAC_FIR_12[table_index][2] as i32,
1661+ );
1662+ res = smlabb(
1663+ res,
1664+ b[3] as i32,
1665+ RESAMPLER_FRAC_FIR_12[table_index][3] as i32,
1666+ );
1667+ res = smlabb(
1668+ res,
1669+ b[4] as i32,
1670+ RESAMPLER_FRAC_FIR_12[11 - table_index][3] as i32,
1671+ );
1672+ res = smlabb(
1673+ res,
1674+ b[5] as i32,
1675+ RESAMPLER_FRAC_FIR_12[11 - table_index][2] as i32,
1676+ );
1677+ res = smlabb(
1678+ res,
1679+ b[6] as i32,
1680+ RESAMPLER_FRAC_FIR_12[11 - table_index][1] as i32,
1681+ );
1682+ res = smlabb(
1683+ res,
1684+ b[7] as i32,
1685+ RESAMPLER_FRAC_FIR_12[11 - table_index][0] as i32,
1686+ );
1687+ if written < out.len() {
1688+ out[written] = sat16(rshift_round(res, 15));
1689+ }
1690+ written += 1;
1691+ index_q16 += self.inv_ratio_q16;
1692+ }
1693+ pos += n_samples_in;
1694+ if pos < input.len() {
1695+ buf.copy_within(2 * n_samples_in..2 * n_samples_in + 8, 0);
1696+ }
1697+ }
1698+ self.s_fir
1699+ .copy_from_slice(&buf[2 * n_samples_in..2 * n_samples_in + 8]);
1700+ }
1701+
1702+ /// `silk_resampler_private_down_FIR`, for output rates below the internal
1703+ /// rate (an AR2 pre-filter, then a polyphase FIR).
1704+ fn down_fir(&mut self, out: &mut [i16], input: &[i16]) {
1705+ let inv_ratio = self.inv_ratio_q16;
1706+ let d = self.down.as_mut().expect("down-sampling state");
1707+ let order = d.order;
1708+ let mut buf = core::mem::take(&mut d.buf);
1709+ // AR2 pre-filter into Q8.
1710+ let a_q14 = [d.coefs[0], d.coefs[1]];
1711+ for (k, &s) in input.iter().enumerate() {
1712+ let out32 = d.state[0] + ((s as i32) << 8);
1713+ buf[order + k] = out32;
1714+ let out32 = out32 << 2;
1715+ d.state[0] = smlawb(d.state[1], out32, a_q14[0] as i32);
1716+ d.state[1] = smulwb(out32, a_q14[1] as i32);
1717+ }
1718+ let fir = &d.coefs[2..];
1719+ let fracs = d.fracs;
1720+ let mut written = 0usize;
1721+ let max_index_q16 = (input.len() as i32) << 16;
1722+ let mut index_q16 = 0i32;
1723+ while index_q16 < max_index_q16 && written < out.len() {
1724+ let base = (index_q16 >> 16) as usize;
1725+ let interpol_ind = smulwb(index_q16 & 0xFFFF, fracs as i32) as usize;
1726+ let coefs = &fir[interpol_ind * (order / 2)..];
1727+ let mut res = 0i64;
1728+ for j in 0..order / 2 {
1729+ res += buf[base + j] as i64 * coefs[j] as i64;
1730+ res += buf[base + order - 1 - j] as i64 * coefs[j] as i64;
1731+ }
1732+ out[written] = sat16(rshift_round((res >> 16) as i32, 6));
1733+ written += 1;
1734+ index_q16 += inv_ratio;
1735+ }
1736+ let keep = order;
1737+ buf.copy_within(input.len()..input.len() + keep, 0);
1738+ d.buf = buf;
1739+ }
1740+}
1741+
1742+#[cfg(test)]
1743+mod tests {
1744+ use super::*;
1745+
1746+ #[test]
1747+ fn fixed_point_helpers_match_their_definitions() {
1748+ // Spot values computed from the reference macro definitions.
1749+ assert_eq!(smulwb(1 << 20, 3), 48);
1750+ assert_eq!(smulbb(-5, 7), -35);
1751+ assert_eq!(rshift_round(7, 1), 4);
1752+ assert_eq!(rshift_round(-7, 2), -2);
1753+ assert_eq!(sat16(40000), 32767);
1754+ assert_eq!(sat16(-40000), -32768);
1755+ // log2lin is the exponential the gain quantiser uses: 2^(q/128).
1756+ for q in [0i32, 128, 1000, 3967] {
1757+ let got = log2lin(q) as f64;
1758+ let want = (q as f64 / 128.0).exp2();
1759+ assert!(
1760+ (got - want).abs() / want < 0.02,
1761+ "log2lin({q}) = {got}, want {want}"
1762+ );
1763+ }
1764+ // sqrt_approx returns sqrt(x) in the same Q domain. It is a coarse
1765+ // approximation whose relative error only settles below ~1 % once the
1766+ // input has enough significant bits, which is where SILK uses it (the
1767+ // NLSF weights are shifted up by 16 first).
1768+ for x in [1 << 18, 1234567, 1 << 24, 1 << 30] {
1769+ let y = sqrt_approx(x) as f64;
1770+ let want = (x as f64).sqrt();
1771+ assert!(
1772+ (y - want).abs() / want < 0.02,
1773+ "sqrt({x}) = {y}, want {want}"
1774+ );
1775+ }
1776+ }
1777+
1778+ #[test]
1779+ fn gains_are_monotonic_in_the_index() {
1780+ let mut prev = 0;
1781+ let mut last = 0;
1782+ for i in 0..64i8 {
1783+ let g = gains_dequant(&[i, 0, 0, 0], &mut prev, false, 1)[0];
1784+ assert!(g > last, "gain for index {i} did not increase");
1785+ last = g;
1786+ prev = i as i32;
1787+ }
1788+ }
1789+
1790+ #[test]
1791+ fn nlsf_stabilize_enforces_the_minimum_spacing() {
1792+ let cb = nlsf_cb(false);
1793+ let mut nlsf = [100i16, 120, 130, 140, 150, 160, 170, 180, 190, 32700];
1794+ nlsf_stabilize(&mut nlsf, cb.delta_min_q15);
1795+ for i in 1..10 {
1796+ assert!(
1797+ nlsf[i] - nlsf[i - 1] >= cb.delta_min_q15[i],
1798+ "spacing at {i}: {} < {}",
1799+ nlsf[i] - nlsf[i - 1],
1800+ cb.delta_min_q15[i]
1801+ );
1802+ }
1803+ assert!(nlsf[0] >= cb.delta_min_q15[0]);
1804+ assert!((1 << 15) - nlsf[9] as i32 >= cb.delta_min_q15[10] as i32);
1805+ }
1806+}
crates/ec-opus/src/silk_tables.rsadded+176 -0
@@ -0,0 +1,176 @@
1+pub const GAIN_ICDF: [[u8; 8]; 3] = [
2+ [224, 112, 44, 15, 3, 2, 1, 0],
3+ [254, 237, 192, 132, 70, 23, 4, 0],
4+ [255, 252, 226, 155, 61, 11, 2, 0],
5+];
6+pub const DELTA_GAIN_ICDF: [u8; 41] = [250, 245, 234, 203, 71, 50, 42, 38, 35, 33, 31, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0];
7+pub const LTP_PER_INDEX_ICDF: [u8; 3] = [179, 99, 0];
8+pub const LTP_GAIN_ICDF_0: [u8; 8] = [71, 56, 43, 30, 21, 12, 6, 0];
9+pub const LTP_GAIN_ICDF_1: [u8; 16] = [199, 165, 144, 124, 109, 96, 84, 71, 61, 51, 42, 32, 23, 15, 8, 0];
10+pub const LTP_GAIN_ICDF_2: [u8; 32] = [241, 225, 211, 199, 187, 175, 164, 153, 142, 132, 123, 114, 105, 96, 88, 80, 72, 64, 57, 50, 44, 38, 33, 29, 24, 20, 16, 12, 9, 5, 2, 0];
11+pub const LTP_GAIN_VQ_0: [[i8; 5]; 8] = [
12+ [4, 6, 24, 7, 5],
13+ [0, 0, 2, 0, 0],
14+ [12, 28, 41, 13, -4],
15+ [-9, 15, 42, 25, 14],
16+ [1, -2, 62, 41, -9],
17+ [-10, 37, 65, -4, 3],
18+ [-6, 4, 66, 7, -8],
19+ [16, 14, 38, -3, 33],
20+];
21+pub const LTP_GAIN_VQ_1: [[i8; 5]; 16] = [
22+ [13, 22, 39, 23, 12],
23+ [-1, 36, 64, 27, -6],
24+ [-7, 10, 55, 43, 17],
25+ [1, 1, 8, 1, 1],
26+ [6, -11, 74, 53, -9],
27+ [-12, 55, 76, -12, 8],
28+ [-3, 3, 93, 27, -4],
29+ [26, 39, 59, 3, -8],
30+ [2, 0, 77, 11, 9],
31+ [-8, 22, 44, -6, 7],
32+ [40, 9, 26, 3, 9],
33+ [-7, 20, 101, -7, 4],
34+ [3, -8, 42, 26, 0],
35+ [-15, 33, 68, 2, 23],
36+ [-2, 55, 46, -2, 15],
37+ [3, -1, 21, 16, 41],
38+];
39+pub const LTP_GAIN_VQ_2: [[i8; 5]; 32] = [
40+ [-6, 27, 61, 39, 5],
41+ [-11, 42, 88, 4, 1],
42+ [-2, 60, 65, 6, -4],
43+ [-1, -5, 73, 56, 1],
44+ [-9, 19, 94, 29, -9],
45+ [0, 12, 99, 6, 4],
46+ [8, -19, 102, 46, -13],
47+ [3, 2, 13, 3, 2],
48+ [9, -21, 84, 72, -18],
49+ [-11, 46, 104, -22, 8],
50+ [18, 38, 48, 23, 0],
51+ [-16, 70, 83, -21, 11],
52+ [5, -11, 117, 22, -8],
53+ [-6, 23, 117, -12, 3],
54+ [3, -8, 95, 28, 4],
55+ [-10, 15, 77, 60, -15],
56+ [-1, 4, 124, 2, -4],
57+ [3, 38, 84, 24, -25],
58+ [2, 13, 42, 13, 31],
59+ [21, -4, 56, 46, -1],
60+ [-1, 35, 79, -13, 19],
61+ [-7, 65, 88, -9, -14],
62+ [20, 4, 81, 49, -29],
63+ [20, 0, 75, 3, -17],
64+ [5, -9, 44, 92, -8],
65+ [1, -3, 22, 69, 31],
66+ [-6, 95, 41, -12, 5],
67+ [39, 67, 16, -4, 1],
68+ [0, -6, 120, 55, -36],
69+ [-13, 44, 122, 4, -24],
70+ [81, 5, 11, 3, 7],
71+ [2, 0, 9, 10, 88],
72+];
73+pub const STEREO_PRED_QUANT_Q13: [i16; 16] = [-13732, -10050, -8266, -7526, -6500, -5000, -2950, -820, 820, 2950, 5000, 6500, 7526, 8266, 10050, 13732];
74+pub const STEREO_PRED_JOINT_ICDF: [u8; 25] = [249, 247, 246, 245, 244, 234, 210, 202, 201, 200, 197, 174, 82, 59, 56, 55, 54, 46, 22, 12, 11, 10, 9, 7, 0];
75+pub const STEREO_ONLY_CODE_MID_ICDF: [u8; 2] = [64, 0];
76+pub const LBRR_FLAGS_2_ICDF: [u8; 3] = [203, 150, 0];
77+pub const LBRR_FLAGS_3_ICDF: [u8; 7] = [215, 195, 166, 125, 110, 82, 0];
78+pub const LSB_ICDF: [u8; 2] = [120, 0];
79+pub const LTPSCALE_ICDF: [u8; 3] = [128, 64, 0];
80+pub const TYPE_OFFSET_VAD_ICDF: [u8; 4] = [232, 158, 10, 0];
81+pub const TYPE_OFFSET_NO_VAD_ICDF: [u8; 2] = [230, 0];
82+pub const NLSF_INTERPOLATION_FACTOR_ICDF: [u8; 5] = [243, 221, 192, 181, 0];
83+pub const QUANTIZATION_OFFSETS_Q10: [[i16; 2]; 2] = [
84+ [100, 240],
85+ [32, 100],
86+];
87+pub const LTPSCALES_TABLE_Q14: [i16; 3] = [15565, 12288, 8192];
88+pub const UNIFORM3_ICDF: [u8; 3] = [171, 85, 0];
89+pub const UNIFORM4_ICDF: [u8; 4] = [192, 128, 64, 0];
90+pub const UNIFORM5_ICDF: [u8; 5] = [205, 154, 102, 51, 0];
91+pub const UNIFORM6_ICDF: [u8; 6] = [213, 171, 128, 85, 43, 0];
92+pub const UNIFORM8_ICDF: [u8; 8] = [224, 192, 160, 128, 96, 64, 32, 0];
93+pub const NLSF_EXT_ICDF: [u8; 7] = [100, 40, 16, 7, 3, 1, 0];
94+pub const PITCH_LAG_ICDF: [u8; 32] = [253, 250, 244, 233, 212, 182, 150, 131, 120, 110, 98, 85, 72, 60, 49, 40, 32, 25, 19, 15, 13, 11, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0];
95+pub const PITCH_DELTA_ICDF: [u8; 21] = [210, 208, 206, 203, 199, 193, 183, 168, 142, 104, 74, 52, 37, 27, 20, 14, 10, 6, 4, 2, 0];
96+pub const PITCH_CONTOUR_ICDF: [u8; 34] = [223, 201, 183, 167, 152, 138, 124, 111, 98, 88, 79, 70, 62, 56, 50, 44, 39, 35, 31, 27, 24, 21, 18, 16, 14, 12, 10, 8, 6, 4, 3, 2, 1, 0];
97+pub const PITCH_CONTOUR_NB_ICDF: [u8; 11] = [188, 176, 155, 138, 119, 97, 67, 43, 26, 10, 0];
98+pub const PITCH_CONTOUR_10_MS_ICDF: [u8; 12] = [165, 119, 80, 61, 47, 35, 27, 20, 14, 9, 4, 0];
99+pub const PITCH_CONTOUR_10_MS_NB_ICDF: [u8; 3] = [113, 63, 0];
100+pub const PULSES_PER_BLOCK_ICDF: [[u8; 18]; 10] = [
101+ [125, 51, 26, 18, 15, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0],
102+ [198, 105, 45, 22, 15, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0],
103+ [213, 162, 116, 83, 59, 43, 32, 24, 18, 15, 12, 9, 7, 6, 5, 3, 2, 0],
104+ [239, 187, 116, 59, 28, 16, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0],
105+ [250, 229, 188, 135, 86, 51, 30, 19, 13, 10, 8, 6, 5, 4, 3, 2, 1, 0],
106+ [249, 235, 213, 185, 156, 128, 103, 83, 66, 53, 42, 33, 26, 21, 17, 13, 10, 0],
107+ [254, 249, 235, 206, 164, 118, 77, 46, 27, 16, 10, 7, 5, 4, 3, 2, 1, 0],
108+ [255, 253, 249, 239, 220, 191, 156, 119, 85, 57, 37, 23, 15, 10, 6, 4, 2, 0],
109+ [255, 253, 251, 246, 237, 223, 203, 179, 152, 124, 98, 75, 55, 40, 29, 21, 15, 0],
110+ [255, 254, 253, 247, 220, 162, 106, 67, 42, 28, 18, 12, 9, 6, 4, 3, 2, 0],
111+];
112+pub const RATE_LEVELS_ICDF: [[u8; 9]; 2] = [
113+ [241, 190, 178, 132, 87, 74, 41, 14, 0],
114+ [223, 193, 157, 140, 106, 57, 39, 18, 0],
115+];
116+pub const SHELL_CODE_TABLE0: [u8; 152] = [128, 0, 214, 42, 0, 235, 128, 21, 0, 244, 184, 72, 11, 0, 248, 214, 128, 42, 7, 0, 248, 225, 170, 80, 25, 5, 0, 251, 236, 198, 126, 54, 18, 3, 0, 250, 238, 211, 159, 82, 35, 15, 5, 0, 250, 231, 203, 168, 128, 88, 53, 25, 6, 0, 252, 238, 216, 185, 148, 108, 71, 40, 18, 4, 0, 253, 243, 225, 199, 166, 128, 90, 57, 31, 13, 3, 0, 254, 246, 233, 212, 183, 147, 109, 73, 44, 23, 10, 2, 0, 255, 250, 240, 223, 198, 166, 128, 90, 58, 33, 16, 6, 1, 0, 255, 251, 244, 231, 210, 181, 146, 110, 75, 46, 25, 12, 5, 1, 0, 255, 253, 248, 238, 221, 196, 164, 128, 92, 60, 35, 18, 8, 3, 1, 0, 255, 253, 249, 242, 229, 208, 180, 146, 110, 76, 48, 27, 14, 7, 3, 1, 0];
117+pub const SHELL_CODE_TABLE1: [u8; 152] = [129, 0, 207, 50, 0, 236, 129, 20, 0, 245, 185, 72, 10, 0, 249, 213, 129, 42, 6, 0, 250, 226, 169, 87, 27, 4, 0, 251, 233, 194, 130, 62, 20, 4, 0, 250, 236, 207, 160, 99, 47, 17, 3, 0, 255, 240, 217, 182, 131, 81, 41, 11, 1, 0, 255, 254, 233, 201, 159, 107, 61, 20, 2, 1, 0, 255, 249, 233, 206, 170, 128, 86, 50, 23, 7, 1, 0, 255, 250, 238, 217, 186, 148, 108, 70, 39, 18, 6, 1, 0, 255, 252, 243, 226, 200, 166, 128, 90, 56, 30, 13, 4, 1, 0, 255, 252, 245, 231, 209, 180, 146, 110, 76, 47, 25, 11, 4, 1, 0, 255, 253, 248, 237, 219, 194, 163, 128, 93, 62, 37, 19, 8, 3, 1, 0, 255, 254, 250, 241, 226, 205, 177, 145, 111, 79, 51, 30, 15, 6, 2, 1, 0];
118+pub const SHELL_CODE_TABLE2: [u8; 152] = [129, 0, 203, 54, 0, 234, 129, 23, 0, 245, 184, 73, 10, 0, 250, 215, 129, 41, 5, 0, 252, 232, 173, 86, 24, 3, 0, 253, 240, 200, 129, 56, 15, 2, 0, 253, 244, 217, 164, 94, 38, 10, 1, 0, 253, 245, 226, 189, 132, 71, 27, 7, 1, 0, 253, 246, 231, 203, 159, 105, 56, 23, 6, 1, 0, 255, 248, 235, 213, 179, 133, 85, 47, 19, 5, 1, 0, 255, 254, 243, 221, 194, 159, 117, 70, 37, 12, 2, 1, 0, 255, 254, 248, 234, 208, 171, 128, 85, 48, 22, 8, 2, 1, 0, 255, 254, 250, 240, 220, 189, 149, 107, 67, 36, 16, 6, 2, 1, 0, 255, 254, 251, 243, 227, 201, 166, 128, 90, 55, 29, 13, 5, 2, 1, 0, 255, 254, 252, 246, 234, 213, 183, 147, 109, 73, 43, 22, 10, 4, 2, 1, 0];
119+pub const SHELL_CODE_TABLE3: [u8; 152] = [130, 0, 200, 58, 0, 231, 130, 26, 0, 244, 184, 76, 12, 0, 249, 214, 130, 43, 6, 0, 252, 232, 173, 87, 24, 3, 0, 253, 241, 203, 131, 56, 14, 2, 0, 254, 246, 221, 167, 94, 35, 8, 1, 0, 254, 249, 232, 193, 130, 65, 23, 5, 1, 0, 255, 251, 239, 211, 162, 99, 45, 15, 4, 1, 0, 255, 251, 243, 223, 186, 131, 74, 33, 11, 3, 1, 0, 255, 252, 245, 230, 202, 158, 105, 57, 24, 8, 2, 1, 0, 255, 253, 247, 235, 214, 179, 132, 84, 44, 19, 7, 2, 1, 0, 255, 254, 250, 240, 223, 196, 159, 112, 69, 36, 15, 6, 2, 1, 0, 255, 254, 253, 245, 231, 209, 176, 136, 93, 55, 27, 11, 3, 2, 1, 0, 255, 254, 253, 252, 239, 221, 194, 158, 117, 76, 42, 18, 4, 3, 2, 1, 0];
120+pub const SHELL_CODE_TABLE_OFFSETS: [u8; 17] = [0, 0, 2, 5, 9, 14, 20, 27, 35, 44, 54, 65, 77, 90, 104, 119, 135];
121+pub const SIGN_ICDF: [u8; 42] = [254, 49, 67, 77, 82, 93, 99, 198, 11, 18, 24, 31, 36, 45, 255, 46, 66, 78, 87, 94, 104, 208, 14, 21, 32, 42, 51, 66, 255, 94, 104, 109, 112, 115, 118, 248, 53, 69, 80, 88, 95, 102];
122+pub const NLSF_CB1_NB_MB_Q8: [u8; 320] = [12, 35, 60, 83, 108, 132, 157, 180, 206, 228, 15, 32, 55, 77, 101, 125, 151, 175, 201, 225, 19, 42, 66, 89, 114, 137, 162, 184, 209, 230, 12, 25, 50, 72, 97, 120, 147, 172, 200, 223, 26, 44, 69, 90, 114, 135, 159, 180, 205, 225, 13, 22, 53, 80, 106, 130, 156, 180, 205, 228, 15, 25, 44, 64, 90, 115, 142, 168, 196, 222, 19, 24, 62, 82, 100, 120, 145, 168, 190, 214, 22, 31, 50, 79, 103, 120, 151, 170, 203, 227, 21, 29, 45, 65, 106, 124, 150, 171, 196, 224, 30, 49, 75, 97, 121, 142, 165, 186, 209, 229, 19, 25, 52, 70, 93, 116, 143, 166, 192, 219, 26, 34, 62, 75, 97, 118, 145, 167, 194, 217, 25, 33, 56, 70, 91, 113, 143, 165, 196, 223, 21, 34, 51, 72, 97, 117, 145, 171, 196, 222, 20, 29, 50, 67, 90, 117, 144, 168, 197, 221, 22, 31, 48, 66, 95, 117, 146, 168, 196, 222, 24, 33, 51, 77, 116, 134, 158, 180, 200, 224, 21, 28, 70, 87, 106, 124, 149, 170, 194, 217, 26, 33, 53, 64, 83, 117, 152, 173, 204, 225, 27, 34, 65, 95, 108, 129, 155, 174, 210, 225, 20, 26, 72, 99, 113, 131, 154, 176, 200, 219, 34, 43, 61, 78, 93, 114, 155, 177, 205, 229, 23, 29, 54, 97, 124, 138, 163, 179, 209, 229, 30, 38, 56, 89, 118, 129, 158, 178, 200, 231, 21, 29, 49, 63, 85, 111, 142, 163, 193, 222, 27, 48, 77, 103, 133, 158, 179, 196, 215, 232, 29, 47, 74, 99, 124, 151, 176, 198, 220, 237, 33, 42, 61, 76, 93, 121, 155, 174, 207, 225, 29, 53, 87, 112, 136, 154, 170, 188, 208, 227, 24, 30, 52, 84, 131, 150, 166, 186, 203, 229, 37, 48, 64, 84, 104, 118, 156, 177, 201, 230];
123+pub const NLSF_CB1_ICDF_NB_MB: [u8; 64] = [212, 178, 148, 129, 108, 96, 85, 82, 79, 77, 61, 59, 57, 56, 51, 49, 48, 45, 42, 41, 40, 38, 36, 34, 31, 30, 21, 12, 10, 3, 1, 0, 255, 245, 244, 236, 233, 225, 217, 203, 190, 176, 175, 161, 149, 136, 125, 114, 102, 91, 81, 71, 60, 52, 43, 35, 28, 20, 19, 18, 12, 11, 5, 0];
124+pub const NLSF_CB2_SELECT_NB_MB: [u8; 160] = [16, 0, 0, 0, 0, 99, 66, 36, 36, 34, 36, 34, 34, 34, 34, 83, 69, 36, 52, 34, 116, 102, 70, 68, 68, 176, 102, 68, 68, 34, 65, 85, 68, 84, 36, 116, 141, 152, 139, 170, 132, 187, 184, 216, 137, 132, 249, 168, 185, 139, 104, 102, 100, 68, 68, 178, 218, 185, 185, 170, 244, 216, 187, 187, 170, 244, 187, 187, 219, 138, 103, 155, 184, 185, 137, 116, 183, 155, 152, 136, 132, 217, 184, 184, 170, 164, 217, 171, 155, 139, 244, 169, 184, 185, 170, 164, 216, 223, 218, 138, 214, 143, 188, 218, 168, 244, 141, 136, 155, 170, 168, 138, 220, 219, 139, 164, 219, 202, 216, 137, 168, 186, 246, 185, 139, 116, 185, 219, 185, 138, 100, 100, 134, 100, 102, 34, 68, 68, 100, 68, 168, 203, 221, 218, 168, 167, 154, 136, 104, 70, 164, 246, 171, 137, 139, 137, 155, 218, 219, 139];
125+pub const NLSF_CB2_ICDF_NB_MB: [u8; 72] = [255, 254, 253, 238, 14, 3, 2, 1, 0, 255, 254, 252, 218, 35, 3, 2, 1, 0, 255, 254, 250, 208, 59, 4, 2, 1, 0, 255, 254, 246, 194, 71, 10, 2, 1, 0, 255, 252, 236, 183, 82, 8, 2, 1, 0, 255, 252, 235, 180, 90, 17, 2, 1, 0, 255, 248, 224, 171, 97, 30, 4, 1, 0, 255, 254, 236, 173, 95, 37, 7, 1, 0];
126+pub const NLSF_PRED_NB_MB_Q8: [u8; 18] = [179, 138, 140, 148, 151, 149, 153, 151, 163, 116, 67, 82, 59, 92, 72, 100, 89, 92];
127+pub const NLSF_DELTA_MIN_NB_MB_Q15: [i16; 11] = [250, 3, 6, 3, 3, 3, 4, 3, 3, 3, 461];
128+pub const NLSF_CB1_WB_Q8: [u8; 512] = [7, 23, 38, 54, 69, 85, 100, 116, 131, 147, 162, 178, 193, 208, 223, 239, 13, 25, 41, 55, 69, 83, 98, 112, 127, 142, 157, 171, 187, 203, 220, 236, 15, 21, 34, 51, 61, 78, 92, 106, 126, 136, 152, 167, 185, 205, 225, 240, 10, 21, 36, 50, 63, 79, 95, 110, 126, 141, 157, 173, 189, 205, 221, 237, 17, 20, 37, 51, 59, 78, 89, 107, 123, 134, 150, 164, 184, 205, 224, 240, 10, 15, 32, 51, 67, 81, 96, 112, 129, 142, 158, 173, 189, 204, 220, 236, 8, 21, 37, 51, 65, 79, 98, 113, 126, 138, 155, 168, 179, 192, 209, 218, 12, 15, 34, 55, 63, 78, 87, 108, 118, 131, 148, 167, 185, 203, 219, 236, 16, 19, 32, 36, 56, 79, 91, 108, 118, 136, 154, 171, 186, 204, 220, 237, 11, 28, 43, 58, 74, 89, 105, 120, 135, 150, 165, 180, 196, 211, 226, 241, 6, 16, 33, 46, 60, 75, 92, 107, 123, 137, 156, 169, 185, 199, 214, 225, 11, 19, 30, 44, 57, 74, 89, 105, 121, 135, 152, 169, 186, 202, 218, 234, 12, 19, 29, 46, 57, 71, 88, 100, 120, 132, 148, 165, 182, 199, 216, 233, 17, 23, 35, 46, 56, 77, 92, 106, 123, 134, 152, 167, 185, 204, 222, 237, 14, 17, 45, 53, 63, 75, 89, 107, 115, 132, 151, 171, 188, 206, 221, 240, 9, 16, 29, 40, 56, 71, 88, 103, 119, 137, 154, 171, 189, 205, 222, 237, 16, 19, 36, 48, 57, 76, 87, 105, 118, 132, 150, 167, 185, 202, 218, 236, 12, 17, 29, 54, 71, 81, 94, 104, 126, 136, 149, 164, 182, 201, 221, 237, 15, 28, 47, 62, 79, 97, 115, 129, 142, 155, 168, 180, 194, 208, 223, 238, 8, 14, 30, 45, 62, 78, 94, 111, 127, 143, 159, 175, 192, 207, 223, 239, 17, 30, 49, 62, 79, 92, 107, 119, 132, 145, 160, 174, 190, 204, 220, 235, 14, 19, 36, 45, 61, 76, 91, 108, 121, 138, 154, 172, 189, 205, 222, 238, 12, 18, 31, 45, 60, 76, 91, 107, 123, 138, 154, 171, 187, 204, 221, 236, 13, 17, 31, 43, 53, 70, 83, 103, 114, 131, 149, 167, 185, 203, 220, 237, 17, 22, 35, 42, 58, 78, 93, 110, 125, 139, 155, 170, 188, 206, 224, 240, 8, 15, 34, 50, 67, 83, 99, 115, 131, 146, 162, 178, 193, 209, 224, 239, 13, 16, 41, 66, 73, 86, 95, 111, 128, 137, 150, 163, 183, 206, 225, 241, 17, 25, 37, 52, 63, 75, 92, 102, 119, 132, 144, 160, 175, 191, 212, 231, 19, 31, 49, 65, 83, 100, 117, 133, 147, 161, 174, 187, 200, 213, 227, 242, 18, 31, 52, 68, 88, 103, 117, 126, 138, 149, 163, 177, 192, 207, 223, 239, 16, 29, 47, 61, 76, 90, 106, 119, 133, 147, 161, 176, 193, 209, 224, 240, 15, 21, 35, 50, 61, 73, 86, 97, 110, 119, 129, 141, 175, 198, 218, 237];
129+pub const NLSF_CB1_ICDF_WB: [u8; 64] = [225, 204, 201, 184, 183, 175, 158, 154, 153, 135, 119, 115, 113, 110, 109, 99, 98, 95, 79, 68, 52, 50, 48, 45, 43, 32, 31, 27, 18, 10, 3, 0, 255, 251, 235, 230, 212, 201, 196, 182, 167, 166, 163, 151, 138, 124, 110, 104, 90, 78, 76, 70, 69, 57, 45, 34, 24, 21, 11, 6, 5, 4, 3, 0];
130+pub const NLSF_CB2_SELECT_WB: [u8; 256] = [0, 0, 0, 0, 0, 0, 0, 1, 100, 102, 102, 68, 68, 36, 34, 96, 164, 107, 158, 185, 180, 185, 139, 102, 64, 66, 36, 34, 34, 0, 1, 32, 208, 139, 141, 191, 152, 185, 155, 104, 96, 171, 104, 166, 102, 102, 102, 132, 1, 0, 0, 0, 0, 16, 16, 0, 80, 109, 78, 107, 185, 139, 103, 101, 208, 212, 141, 139, 173, 153, 123, 103, 36, 0, 0, 0, 0, 0, 0, 1, 48, 0, 0, 0, 0, 0, 0, 32, 68, 135, 123, 119, 119, 103, 69, 98, 68, 103, 120, 118, 118, 102, 71, 98, 134, 136, 157, 184, 182, 153, 139, 134, 208, 168, 248, 75, 189, 143, 121, 107, 32, 49, 34, 34, 34, 0, 17, 2, 210, 235, 139, 123, 185, 137, 105, 134, 98, 135, 104, 182, 100, 183, 171, 134, 100, 70, 68, 70, 66, 66, 34, 131, 64, 166, 102, 68, 36, 2, 1, 0, 134, 166, 102, 68, 34, 34, 66, 132, 212, 246, 158, 139, 107, 107, 87, 102, 100, 219, 125, 122, 137, 118, 103, 132, 114, 135, 137, 105, 171, 106, 50, 34, 164, 214, 141, 143, 185, 151, 121, 103, 192, 34, 0, 0, 0, 0, 0, 1, 208, 109, 74, 187, 134, 249, 159, 137, 102, 110, 154, 118, 87, 101, 119, 101, 0, 2, 0, 36, 36, 66, 68, 35, 96, 164, 102, 100, 36, 0, 2, 33, 167, 138, 174, 102, 100, 84, 2, 2, 100, 107, 120, 119, 36, 197, 24, 0];
131+pub const NLSF_CB2_ICDF_WB: [u8; 72] = [255, 254, 253, 244, 12, 3, 2, 1, 0, 255, 254, 252, 224, 38, 3, 2, 1, 0, 255, 254, 251, 209, 57, 4, 2, 1, 0, 255, 254, 244, 195, 69, 4, 2, 1, 0, 255, 251, 232, 184, 84, 7, 2, 1, 0, 255, 254, 240, 186, 86, 14, 2, 1, 0, 255, 254, 239, 178, 91, 30, 5, 1, 0, 255, 248, 227, 177, 100, 19, 2, 1, 0];
132+pub const NLSF_PRED_WB_Q8: [u8; 30] = [175, 148, 160, 176, 178, 173, 174, 164, 177, 174, 196, 182, 198, 192, 182, 68, 62, 66, 60, 72, 117, 85, 90, 118, 136, 151, 142, 160, 142, 155];
133+pub const NLSF_DELTA_MIN_WB_Q15: [i16; 17] = [100, 3, 40, 3, 3, 3, 5, 14, 14, 10, 11, 3, 8, 9, 7, 3, 347];
134+pub const LSFCOSTAB_FIX_Q12: [i16; 129] = [8192, 8190, 8182, 8170, 8152, 8130, 8104, 8072, 8034, 7994, 7946, 7896, 7840, 7778, 7714, 7644, 7568, 7490, 7406, 7318, 7226, 7128, 7026, 6922, 6812, 6698, 6580, 6458, 6332, 6204, 6070, 5934, 5792, 5648, 5502, 5352, 5198, 5040, 4880, 4718, 4552, 4382, 4212, 4038, 3862, 3684, 3502, 3320, 3136, 2948, 2760, 2570, 2378, 2186, 1990, 1794, 1598, 1400, 1202, 1002, 802, 602, 402, 202, 0, -202, -402, -602, -802, -1002, -1202, -1400, -1598, -1794, -1990, -2186, -2378, -2570, -2760, -2948, -3136, -3320, -3502, -3684, -3862, -4038, -4212, -4382, -4552, -4718, -4880, -5040, -5198, -5352, -5502, -5648, -5792, -5934, -6070, -6204, -6332, -6458, -6580, -6698, -6812, -6922, -7026, -7128, -7226, -7318, -7406, -7490, -7568, -7644, -7714, -7778, -7840, -7896, -7946, -7994, -8034, -8072, -8104, -8130, -8152, -8170, -8182, -8190, -8192];
135+pub const RESAMPLER_UP2_HQ_0: [i16; 3] = [1746, 14986, -26453];
136+pub const RESAMPLER_UP2_HQ_1: [i16; 3] = [6854, 25769, -9994];
137+pub const RESAMPLER_FRAC_FIR_12: [[i16; 4]; 12] = [
138+ [189, -600, 617, 30567],
139+ [117, -159, -1070, 29704],
140+ [52, 221, -2392, 28276],
141+ [-4, 529, -3350, 26341],
142+ [-48, 758, -3956, 23973],
143+ [-80, 905, -4235, 21254],
144+ [-99, 972, -4222, 18278],
145+ [-107, 967, -3957, 15143],
146+ [-103, 896, -3487, 11950],
147+ [-91, 773, -2865, 8798],
148+ [-71, 611, -2143, 5784],
149+ [-46, 425, -1375, 2996],
150+];
151+pub const RESAMPLER_3_4_COEFS: [i16; 29] = [-20694, -13867, -49, 64, 17, -157, 353, -496, 163, 11047, 22205, -39, 6, 91, -170, 186, 23, -896, 6336, 19928, -19, -36, 102, -89, -24, 328, -951, 2568, 15909];
152+pub const RESAMPLER_2_3_COEFS: [i16; 20] = [-14457, -14019, 64, 128, -122, 36, 310, -768, 584, 9267, 17733, 12, 128, 18, -142, 288, -117, -865, 4123, 14459];
153+pub const RESAMPLER_1_2_COEFS: [i16; 14] = [616, -14323, -10, 39, 58, -46, -84, 120, 184, -315, -541, 1284, 5380, 9024];
154+pub const RESAMPLER_1_3_COEFS: [i16; 20] = [16102, -15162, -13, 0, 20, 26, 5, -31, -43, -4, 65, 90, 7, -157, -248, -44, 593, 1583, 2612, 3271];
155+pub const RESAMPLER_1_4_COEFS: [i16; 20] = [22500, -15099, 3, -14, -20, -15, 2, 25, 37, 25, -16, -71, -107, -79, 50, 292, 623, 982, 1288, 1464];
156+pub const RESAMPLER_1_6_COEFS: [i16; 20] = [27540, -15257, 17, 12, 8, 1, -10, -22, -30, -32, -22, 3, 44, 100, 168, 243, 317, 381, 429, 455];
157+pub const CB_LAGS_STAGE2: [[i8; 11]; 4] = [
158+ [0, 2, -1, -1, -1, 0, 0, 1, 1, 0, 1],
159+ [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0],
160+ [0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0],
161+ [0, -1, 2, 1, 0, 1, 1, 0, 0, -1, -1],
162+];
163+pub const CB_LAGS_STAGE3: [[i8; 34]; 4] = [
164+ [0, 0, 1, -1, 0, 1, -1, 0, -1, 1, -2, 2, -2, -2, 2, -3, 2, 3, -3, -4, 3, -4, 4, 4, -5, 5, -6, -5, 6, -7, 6, 5, 8, -9],
165+ [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, -1, 1, 0, 0, 1, -1, 0, 1, -1, -1, 1, -1, 2, 1, -1, 2, -2, -2, 2, -2, 2, 2, 3, -3],
166+ [0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, -1, 1, 0, 0, 2, 1, -1, 2, -1, -1, 2, -1, 2, 2, -1, 3, -2, -2, -2, 3],
167+ [0, 1, 0, 0, 1, 0, 1, -1, 2, -1, 2, -1, 2, 3, -2, 3, -2, -2, 4, 4, -3, 5, -3, -4, 6, -4, 6, 5, -5, 8, -6, -5, -7, 9],
168+];
169+pub const CB_LAGS_STAGE2_10_MS: [[i8; 3]; 2] = [
170+ [0, 1, 0],
171+ [0, 0, 1],
172+];
173+pub const CB_LAGS_STAGE3_10_MS: [[i8; 12]; 2] = [
174+ [0, 0, 1, -1, 1, -1, 2, -2, 2, -2, 3, -3],
175+ [0, 1, 0, 1, -1, 2, -1, 2, -2, 3, -2, 3],
176+];
crates/ec-opus/tests/conformance.rsmodified+42 -16
@@ -316,12 +316,29 @@ fn read_i16(path: &Path) -> Vec<i16> {
316 .collect()316 .collect()
317 }317 }
318 318
319-/// The CELT-only vectors, which need no SILK layer.319+/// Every vector in the RFC 6716 suite, in the order the RFC lists them.
320-const CELT_VECTORS: [&str; 3] = ["testvector01", "testvector07", "testvector11"];320+const VECTORS: [&str; 12] = [
321+ "testvector01",
322+ "testvector02",
323+ "testvector03",
324+ "testvector04",
325+ "testvector05",
326+ "testvector06",
327+ "testvector07",
328+ "testvector08",
329+ "testvector09",
330+ "testvector10",
331+ "testvector11",
332+ "testvector12",
333+];
321 334
335+/// The conformance test of RFC 6716 Section 6, both halves of it: the decoder's
336+/// range coder state MUST match the reference on every packet, and the output
337+/// MUST stay within the `opus_compare` threshold (quality >= 0).
322 #[test]338 #[test]
323-fn celt_vectors_match_the_reference_range_state() {339+fn rfc6716_test_vectors() {
324- for name in CELT_VECTORS {340+ let mut table = Vec::new();
341+ for name in VECTORS {
325 let path = vectors_dir().join(format!("{name}.bit"));342 let path = vectors_dir().join(format!("{name}.bit"));
326 if !path.exists() {343 if !path.exists() {
327 eprintln!("{name}: missing, skipped (run scripts/fetch-vectors.sh)");344 eprintln!("{name}: missing, skipped (run scripts/fetch-vectors.sh)");
@@ -329,23 +346,32 @@ fn celt_vectors_match_the_reference_range_state() {
329 }346 }
330 let packets = read_vector(&path);347 let packets = read_vector(&path);
331 let (pcm, matched, decoded) = decode_vector(&packets);348 let (pcm, matched, decoded) = decode_vector(&packets);
332- println!(349+ let reference = read_i16(&vectors_dir().join(format!("{name}.dec")));
333- "{name}: {matched}/{decoded} packets bit-exact, {} samples",350+ let mine = to_i16(&pcm);
334- pcm.len() / 2351+ assert_eq!(
352+ reference.len(),
353+ mine.len(),
354+ "{name}: decoded {} samples, reference has {}",
355+ mine.len() / 2,
356+ reference.len() / 2
335 );357 );
358+ let identical = reference.iter().zip(&mine).filter(|(a, b)| a == b).count();
359+ let quality = opus_compare(&reference, &mine, 2);
360+ table.push(format!(
361+ "{name}: {matched}/{decoded} packets range-exact, \
362+ {:.4} % samples identical, quality {quality:.2} %",
363+ 100.0 * identical as f64 / reference.len() as f64
364+ ));
336 assert_eq!(365 assert_eq!(
337 matched, decoded,366 matched, decoded,
338- "{name}: range state diverged from the reference"367+ "{name}: range coder state diverged from the reference"
339 );368 );
340-
341- let reference = read_i16(&vectors_dir().join(format!("{name}.dec")));
342- let mine = to_i16(&pcm);
343- let n = reference.len().min(mine.len());
344- let q = opus_compare(&reference[..n], &mine[..n], 2);
345- println!("{name}: opus_compare quality {q:.1} %");
346 assert!(369 assert!(
347- q >= 0.0,370+ quality >= 0.0,
348- "{name}: opus_compare quality {q:.1} % (must be >= 0)"371+ "{name}: opus_compare quality {quality:.2} %"
349 );372 );
350 }373 }
374+ for line in table {
375+ println!("{line}");
376+ }
351 }377 }