forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'simplify/u11' into simplify/w1b

Browse files at this commit

0d956191dee5fc73346accf8adc1afcd14585008Ahmet Kaan GümüşParent: 329d10dcdccbc2

25 changed files +570 -1662

Cargo.lockmodified+0 -1
@@ -390,7 +390,6 @@ version = "0.1.0"
390390 dependencies = [
391391 "ec-core",
392392 "ec-mp4",
393- "ec-riff",
394393 "ec-testkit",
395394 ]
396395
crates/ec-amr/Cargo.tomlmodified+0 -1
@@ -11,5 +11,4 @@ ec-core = { workspace = true }
1111
1212 [dev-dependencies]
1313 ec-mp4 = { workspace = true }
14-ec-riff = { workspace = true }
1514 ec-testkit.workspace = true
crates/ec-amr/src/nb/basic.rsmodified+2 -183
@@ -2,7 +2,6 @@
22 //! opencore-amr C-equivalent basic_op. Word16 = i16, Word32 = i32.
33 //! Plain functions have no overflow flag; `*_o` variants additionally set `*ovf = true`
44 //! when the result saturated. `round_` is C `round`/`pv_round`.
5-#![allow(dead_code)]
65
76 pub const MAX_16: i16 = 0x7fff;
87 pub const MIN_16: i16 = -0x8000;
@@ -13,38 +12,10 @@ use super::tables::{INV_SQRT_TBL, LOG2_TBL, POW2_TBL, SQRT_L_TBL};
1312
1413 // ---------------------------------------------------------------- 16-bit
1514
16-/// C add (add_16). Saturating.
17-#[inline]
18-pub fn add_o(a: i16, b: i16, ovf: &mut bool) -> i16 {
19- let s = a as i32 + b as i32;
20- if s > 0x7fff {
21- *ovf = true;
22- MAX_16
23- } else if s < -32768 {
24- *ovf = true;
25- MIN_16
26- } else {
27- s as i16
28- }
29-}
3015 #[inline]
3116 pub fn add(a: i16, b: i16) -> i16 {
3217 (a as i32 + b as i32).clamp(-32768, 32767) as i16
3318 }
34-/// C sub. Saturating.
35-#[inline]
36-pub fn sub_o(a: i16, b: i16, ovf: &mut bool) -> i16 {
37- let s = a as i32 - b as i32;
38- if s > 0x7fff {
39- *ovf = true;
40- MAX_16
41- } else if s < -32768 {
42- *ovf = true;
43- MIN_16
44- } else {
45- s as i16
46- }
47-}
4819 #[inline]
4920 pub fn sub(a: i16, b: i16) -> i16 {
5021 (a as i32 - b as i32).clamp(-32768, 32767) as i16
@@ -77,24 +48,6 @@ pub fn mult(a: i16, b: i16) -> i16 {
7748 p as i16
7849 }
7950 }
80-/// (a*b + 0x4000)>>15 saturated.
81-#[inline]
82-pub fn mult_r_o(a: i16, b: i16, ovf: &mut bool) -> i16 {
83- let p = (a as i32 * b as i32 + 0x4000) >> 15;
84- if p > 0x7fff {
85- *ovf = true;
86- MAX_16
87- } else if p < -32768 {
88- *ovf = true;
89- MIN_16
90- } else {
91- p as i16
92- }
93-}
94-#[inline]
95-pub fn mult_r(a: i16, b: i16) -> i16 {
96- mult_r_o(a, b, &mut false)
97-}
9851
9952 /// C shl (left shift with saturation; negative count shifts right, count <= -15 gives 0).
10053 #[inline]
@@ -159,18 +112,6 @@ pub fn shr_r(var1: i16, var2: i16) -> i16 {
159112 out
160113 }
161114 }
162-#[inline]
163-pub fn shr_r_o(var1: i16, var2: i16, ovf: &mut bool) -> i16 {
164- if var2 > 15 {
165- 0
166- } else {
167- let mut out = shr_o(var1, var2, ovf);
168- if var2 > 0 && (var1 as i32 & (1 << (var2 - 1))) != 0 {
169- out = out.wrapping_add(1);
170- }
171- out
172- }
173-}
174115
175116 // ---------------------------------------------------------------- 32-bit
176117
@@ -189,16 +130,6 @@ pub fn l_add(a: i32, b: i32) -> i32 {
189130 a.saturating_add(b)
190131 }
191132 #[inline]
192-pub fn l_sub_o(a: i32, b: i32, ovf: &mut bool) -> i32 {
193- match a.checked_sub(b) {
194- Some(v) => v,
195- None => {
196- *ovf = true;
197- if a < 0 { MIN_32 } else { MAX_32 }
198- }
199- }
200-}
201-#[inline]
202133 pub fn l_sub(a: i32, b: i32) -> i32 {
203134 a.saturating_sub(b)
204135 }
@@ -212,11 +143,6 @@ pub fn l_mult(a: i16, b: i16) -> i32 {
212143 MAX_32
213144 }
214145 }
215-/// Plain 16x16 product, no doubling or saturation.
216-#[inline]
217-pub fn l_mult0(a: i16, b: i16) -> i32 {
218- (a as i32).wrapping_mul(b as i32)
219-}
220146 /// C L_mac: opencore semantics (0x4000_0000 product gives MAX_32).
221147 #[inline]
222148 pub fn l_mac_o(acc: i32, a: i16, b: i16, ovf: &mut bool) -> i32 {
@@ -232,39 +158,10 @@ pub fn l_mac_o(acc: i32, a: i16, b: i16, ovf: &mut bool) -> i32 {
232158 pub fn l_mac(acc: i32, a: i16, b: i16) -> i32 {
233159 l_mac_o(acc, a, b, &mut false)
234160 }
235-/// C L_msu = L_sub(acc, L_mult(a,b)).
236-#[inline]
237-pub fn l_msu_o(acc: i32, a: i16, b: i16, ovf: &mut bool) -> i32 {
238- l_sub_o(acc, l_mult(a, b), ovf)
239-}
240161 #[inline]
241162 pub fn l_msu(acc: i32, a: i16, b: i16) -> i32 {
242163 l_sub(acc, l_mult(a, b))
243164 }
244-#[inline]
245-pub fn l_negate(a: i32) -> i32 {
246- if a == MIN_32 { MAX_32 } else { -a }
247-}
248-#[inline]
249-pub fn l_abs(a: i32) -> i32 {
250- if a == MIN_32 { MAX_32 } else { a.abs() }
251-}
252-#[inline]
253-pub fn l_deposit_h(a: i16) -> i32 {
254- (a as i32) << 16
255-}
256-#[inline]
257-pub fn l_deposit_l(a: i16) -> i32 {
258- a as i32
259-}
260-#[inline]
261-pub fn extract_h(a: i32) -> i16 {
262- (a >> 16) as i16
263-}
264-#[inline]
265-pub fn extract_l(a: i32) -> i16 {
266- a as i16
267-}
268165 /// C L_shl: left shift with saturation (negative count: arithmetic right, count <= -31 gives 0).
269166 #[inline]
270167 pub fn l_shl_o(x: i32, n: i16, ovf: &mut bool) -> i32 {
@@ -324,16 +221,6 @@ pub fn l_shr_r(x: i32, n: i16) -> i32 {
324221 pub fn round_(x: i32) -> i16 {
325222 (l_add(x, 0x8000) >> 16) as i16
326223 }
327-/// L_mac then round.
328-#[inline]
329-pub fn mac_r(acc: i32, a: i16, b: i16) -> i16 {
330- round_(l_mac(acc, a, b))
331-}
332-/// L_msu then round.
333-#[inline]
334-pub fn msu_r(acc: i32, a: i16, b: i16) -> i16 {
335- round_(l_msu(acc, a, b))
336-}
337224
338225 /// Normalisation shift count for 16-bit (0 for 0 input).
339226 #[inline]
@@ -395,37 +282,6 @@ pub fn div_s(var1: i16, var2: i16) -> i16 {
395282
396283 // ---------------------------------------------------------------- 32-bit via hi/lo
397284
398-/// C L_Extract: split into (hi, lo) with lo in 0..0x7fff.
399-#[inline]
400-pub fn l_extract(x: i32, hi: &mut i16, lo: &mut i16) {
401- let h = (x >> 16) as i16;
402- *hi = h;
403- *lo = ((x >> 1) - ((h as i32) << 15)) as i16;
404-}
405-/// C L_Comp: inverse of l_extract.
406-#[inline]
407-pub fn l_comp(hi: i16, lo: i16) -> i32 {
408- l_mac(l_deposit_h(hi), lo, 1)
409-}
410-/// C Mpy_32: (hi1/lo1) * (hi2/lo2), result in Q31 (saturating as in C).
411-#[inline]
412-pub fn mpy_32(h1: i16, l1: i16, h2: i16, l2: i16) -> i32 {
413- let mut p = h1 as i32 * h2 as i32;
414- p = if p != 0x4000_0000 { p << 1 } else { MAX_32 };
415- let p32 = (h1 as i32 * l2 as i32) >> 15;
416- let s = p.wrapping_add(p32 << 1);
417- let mut sum = s;
418- if (p ^ p32) > 0 && ((s ^ p) >> 31) != 0 {
419- sum = if (p >> 31) != 0 { MIN_32 } else { MAX_32 };
420- }
421- let p = sum;
422- let p32 = (l1 as i32 * h2 as i32) >> 15;
423- let s = p.wrapping_add(p32 << 1);
424- if (p ^ p32) > 0 && ((s ^ p) >> 31) != 0 {
425- return if (p >> 31) != 0 { MIN_32 } else { MAX_32 };
426- }
427- s
428-}
429285 /// C Mpy_32_16: (hi/lo) * var2.
430286 #[inline]
431287 pub fn mpy_32_16(hi: i16, lo: i16, v: i16) -> i32 {
@@ -438,35 +294,6 @@ pub fn mpy_32_16(hi: i16, lo: i16, v: i16) -> i32 {
438294 }
439295 s
440296 }
441-/// C Mac_32: acc + (h1/l1)*(h2/l2).
442-#[inline]
443-pub fn mac_32(acc: i32, h1: i16, l1: i16, h2: i16, l2: i16) -> i32 {
444- let mut a = l_mac(acc, h1, h2);
445- a = l_mac(a, mult(h1, l2), 1);
446- l_mac(a, mult(l1, h2), 1)
447-}
448-/// C Mac_32_16: acc + (hi/lo)*var2.
449-#[inline]
450-pub fn mac_32_16(acc: i32, hi: i16, lo: i16, v: i16) -> i32 {
451- let a = l_mac(acc, hi, v);
452- l_mac(a, mult(lo, v), 1)
453-}
454-/// C Div_32: L_num / (denom_hi/denom_lo), result Q31.
455-#[inline]
456-pub fn div_32(l_num: i32, d_hi: i16, d_lo: i16) -> i32 {
457- let approx = div_s(0x3fff, d_hi);
458- let mut r = mpy_32_16(d_hi, d_lo, approx);
459- r = 0x7fff_ffff - r;
460- let hi = (r >> 16) as i16;
461- let lo = ((r >> 1) - ((hi as i32) << 15)) as i16;
462- r = mpy_32_16(hi, lo, approx);
463- let hi = (r >> 16) as i16;
464- let lo = ((r >> 1) - ((hi as i32) << 15)) as i16;
465- let n_hi = (l_num >> 16) as i16;
466- let n_lo = ((l_num >> 1) - ((n_hi as i32) << 15)) as i16;
467- r = mpy_32(n_hi, n_lo, hi, lo);
468- l_shl(r, 2)
469-}
470297
471298 // ---------------------------------------------------------------- math functions
472299
@@ -492,7 +319,7 @@ pub fn log2_norm(x: i32, exp: i16, exponent: &mut i16, fraction: &mut i16) {
492319 *exponent = 30i16.wrapping_sub(exp);
493320 let x = x >> 10;
494321 let i = ((x >> 15) as i16).wrapping_sub(32) as usize;
495- let a = (x & 0x7fff) as i32;
322+ let a = x & 0x7fff;
496323 let mut y = (LOG2_TBL[i] as i32) << 16;
497324 let tmp = LOG2_TBL[i].wrapping_sub(LOG2_TBL[i + 1]) as i32;
498325 y = y.wrapping_sub((tmp * a) << 1);
@@ -540,7 +367,7 @@ pub fn sqrt_l_exp(l_x: i32, exp: &mut i16) -> i32 {
540367 *exp = e;
541368 let x = x >> 10;
542369 let mut i = ((x >> 15) & 63) as usize;
543- let a = (x as i16 & 0x7fff) as i16;
370+ let a = x as i16 & 0x7fff;
544371 if i > 15 {
545372 i -= 16;
546373 }
@@ -584,7 +411,6 @@ mod tests {
584411 assert_eq!(l_mult(-32768, -32768), i32::MAX);
585412 assert_eq!(l_mac(5, -32768, -32768), i32::MAX);
586413 assert_eq!(mult(-32768, -32768), 32767);
587- assert_eq!(mult_r(-32768, -32768), 32767);
588414 assert_eq!(shl(0x4000, 1), 32767);
589415 assert_eq!(shl(-0x4001, 1), -32768);
590416 assert_eq!(shl(3, 2), 12);
@@ -596,9 +422,6 @@ mod tests {
596422 assert_eq!(l_shl(-0x4000_0001, 1), i32::MIN);
597423 assert_eq!(l_shr_r(5, 1), 3);
598424 assert_eq!(l_shr(1, -31), i32::MAX);
599- let mut o = false;
600- add_o(32767, 1, &mut o);
601- assert!(o);
602425 }
603426
604427 #[test]
@@ -619,9 +442,5 @@ mod tests {
619442 log2(1 << 20, &mut e, &mut f);
620443 assert_eq!((e, f), (20, 0));
621444 assert_eq!(gmed_n(&[5, 1, 9, 3, 7], 5), 5);
622- let (mut h, mut l) = (0, 0);
623- l_extract(0x1234_5678, &mut h, &mut l);
624- assert_eq!(l_comp(h, l), 0x1234_5678);
625445 }
626446 }
627-
crates/ec-amr/src/nb/bitstream.rsmodified+1 -2
@@ -1,6 +1,5 @@
11 //! AMR-NB bitstream: RFC 4867 / 3GPP TS 26.101 IF1 (octet-aligned, "MIME/IETF storage") frame
22 //! parsing into decoder parameters (wmf_to_ets + bits2prm of opencore-amr).
3-#![allow(dead_code)]
43
54 use super::tables::*;
65
@@ -178,7 +177,7 @@ mod tests {
178177 assert_eq!(frame_bytes(10), None);
179178 // (bits + 7) / 8 for each mode
180179 for ft in 0..8usize {
181- assert_eq!((NUMOFBITS[ft] as usize + 7) / 8, WMFDECBYTESPERFRAME[ft] as usize);
180+ assert_eq!((NUMOFBITS[ft] as usize).div_ceil(8), WMFDECBYTESPERFRAME[ft] as usize);
182181 }
183182 }
184183
crates/ec-amr/src/nb/decoder.rsmodified+5 -6
@@ -1,6 +1,5 @@
11 //! AMR-NB decoder: port of opencore-amr `dec_amr.cpp` (Decoder_amr) and `sp_dec.cpp`
22 //! (GSMFrameDecode), plus the `AMRDecode` frame-type handling of the libopencore-amrnb wrapper.
3-#![allow(clippy::all)]
43
54 use super::basic::*;
65 use super::bitstream::{parse_frame, BitstreamError, RxFrameType};
@@ -49,9 +48,9 @@ fn agc2(sig_in: &[i16], sig_out: &mut [i16]) {
4948 let mut exp = norm_l(s) - 1;
5049 let gain_out = round_(l_shl(s, exp));
5150 s = energy_new(&sig_in[..l]);
52- let g0: i16;
53- if s == 0 {
54- g0 = 0;
51+
52+ let g0: i16 = if s == 0 {
53+ 0
5554 } else {
5655 let i = norm_l(s);
5756 let gain_in = round_(l_shl(s, i));
@@ -74,8 +73,8 @@ fn agc2(sig_in: &[i16], sig_out: &mut [i16]) {
7473 } else {
7574 s << 9
7675 };
77- g0 = round_(lt);
78- }
76+ round_(lt)
77+ };
7978 for i in (0..l).rev() {
8079 let lt = l_mult(sig_out[i], g0);
8180 sig_out[i] = if lt > 0x0FFF_FFFF {
crates/ec-amr/src/nb/dtx.rsmodified+1 -2
@@ -1,6 +1,5 @@
11 //! Decoder-side DTX / error-concealment helpers: dtx_dec, lsp_avg, bgnscd, c_g_aver,
22 //! ec_gains, ex_ctrl, pseudonoise / build_CN_code.
3-#![allow(clippy::too_many_arguments, clippy::needless_range_loop)]
43
54 use super::basic::*;
65 use super::bitstream::RxFrameType;
@@ -659,7 +658,7 @@ pub fn dtx_dec(
659658 lsf_state.past_r_q = [0; M];
660659
661660 let log_en_index = parm[4];
662- if log_en_index > 63 || log_en_index < -64 {
661+ if !(-64..=63).contains(&log_en_index) {
663662 st.log_en = if log_en_index > 0 { i16::MAX } else { i16::MIN };
664663 } else {
665664 st.log_en = log_en_index << (11 - 2);
crates/ec-amr/src/nb/excitation.rsmodified+10 -11
@@ -1,6 +1,5 @@
11 //! AMR-NB excitation decoding: pitch lag, algebraic codebooks, gains, phase dispersion.
22 //! Bit-exact port of the 3GPP TS 26.073 reference (opencore-amr flavour).
3-#![allow(clippy::all, dead_code, unused_imports, unused_variables, unused_assignments)]
43
54 use super::basic::*;
65 use super::tables::*;
@@ -192,10 +191,10 @@ fn pulse_val(sign: i32) -> i16 {
192191 /// C `dec_10i40_35bits` (MR122 codebook). `index` has 10 entries; `cod` 40 samples.
193192 #[inline]
194193 pub fn dec_10i40_35bits(index: &[i16], cod: &mut [i16]) {
195- for c in cod[..L_CODE as usize].iter_mut() {
194+ for c in cod[..L_CODE].iter_mut() {
196195 *c = 0;
197196 }
198- for j in 0..NB_TRACK as usize {
197+ for j in 0..NB_TRACK {
199198 let tmp = index[j] as i32;
200199 let i = DGRAY[(tmp & 7) as usize] as i32;
201200 let pos1 = (i * 5) as usize + j;
@@ -327,7 +326,7 @@ fn decompress10(msbs: i32, lsbs: i32, index1: usize, index2: usize, index3: usiz
327326 #[inline]
328327 pub fn dec_8i40_31bits(index: &[i16], cod: &mut [i16]) {
329328 const NT: usize = 4;
330- for c in cod[..L_CODE as usize].iter_mut() {
329+ for c in cod[..L_CODE].iter_mut() {
331330 *c = 0;
332331 }
333332 let mut signs = [0i32; NT];
@@ -433,7 +432,7 @@ pub fn gc_pred(
433432 let mut exp = 0i16;
434433 let mut frac = 0i16;
435434 log2(ener_code, &mut exp, &mut frac);
436- let l1 = ((exp as i32 - 30) as i32).wrapping_shl(16);
435+ let l1 = (exp as i32 - 30).wrapping_shl(16);
437436 ener_code = l1.wrapping_add((frac as i32) << 1);
438437 let mut ener = MEAN_ENER_MR122;
439438 for i in 0..NPRED {
@@ -487,7 +486,7 @@ pub fn gc_pred(
487486 l_tmp <<= 10;
488487 }
489488 for i in 0..4 {
490- let l2 = ((PRED[i] * st.past_qua_en[i] as i32)) << 1;
489+ let l2 = (PRED[i] * st.past_qua_en[i] as i32) << 1;
491490 l_tmp = l_add(l_tmp, l2);
492491 }
493492 let gcode0 = (l_tmp >> 16) as i16;
@@ -616,17 +615,17 @@ pub fn d_gain_code(pred_state: &mut GcPredState, mode: Mode, index: i16, code: &
616615 );
617616 let index = (index & 31) as usize;
618617 let p = &QUA_GAIN_CODE[index + (index << 1)..];
619- let gain_code: i16;
620- if mode == Mode::Mr122 {
618+
619+ let gain_code: i16 = if mode == Mode::Mr122 {
621620 let mut gcode0 = pow2(exp, frac) as i16;
622621 gcode0 = shl(gcode0, 4);
623- gain_code = shl(mult(gcode0, p[0]), 1);
622+ shl(mult(gcode0, p[0]), 1)
624623 } else {
625624 let gcode0 = pow2(14, frac) as i16;
626625 let l = l_mult(p[0], gcode0);
627626 let l = l_shr(l, sub(9, exp));
628- gain_code = (l >> 16) as i16;
629- }
627+ (l >> 16) as i16
628+ };
630629 let qua_ener_mr122 = p[1];
631630 let qua_ener = p[2];
632631 gc_pred_update(pred_state, qua_ener_mr122, qua_ener);
crates/ec-amr/src/nb/lpc.rsmodified+0 -25
@@ -1,6 +1,5 @@
11 //! LSF/LSP decoding, conversion and interpolation (d_plsf*, int_lsf, lsp_lsf,
22 //! lsp_az, int_lpc, reorder). Bit-exact port of the 3GPP reference.
3-#![allow(dead_code)]
43
54 use super::basic::{add, mult, negate, shl, sub};
65 use super::tables::{
@@ -305,15 +304,6 @@ pub fn int_lpc_1and3(lsp_old: &[i16], lsp_mid: &[i16], lsp_new: &[i16], az: &mut
305304 lsp_az(lsp_new, &mut az[3 * MP1..]);
306305 }
307306
308-/// C `Int_lpc_1and3_2`: writes Az[0..11] (subframe 1) and Az[22..33] (subframe 3).
309-pub fn int_lpc_1and3_2(lsp_old: &[i16], lsp_mid: &[i16], lsp_new: &[i16], az: &mut [i16]) {
310- let mut lsp = [0i16; M];
311- half_sum(lsp_old, lsp_mid, &mut lsp);
312- lsp_az(&lsp, &mut az[0..]);
313- half_sum(lsp_mid, lsp_new, &mut lsp);
314- lsp_az(&lsp, &mut az[2 * MP1..]);
315-}
316-
317307 /// C `Int_lpc_1to3`: 4 subframes from old/new LSPs; writes Az[0..44].
318308 pub fn int_lpc_1to3(lsp_old: &[i16], lsp_new: &[i16], az: &mut [i16]) {
319309 let mut lsp = [0i16; M];
@@ -329,18 +319,3 @@ pub fn int_lpc_1to3(lsp_old: &[i16], lsp_new: &[i16], az: &mut [i16]) {
329319 lsp_az(&lsp, &mut az[2 * MP1..]);
330320 lsp_az(lsp_new, &mut az[3 * MP1..]);
331321 }
332-
333-/// C `Int_lpc_1to3_2`: like `int_lpc_1to3` but only Az[0..33] (first 3 subframes).
334-pub fn int_lpc_1to3_2(lsp_old: &[i16], lsp_new: &[i16], az: &mut [i16]) {
335- let mut lsp = [0i16; M];
336- for i in 0..M {
337- lsp[i] = (lsp_old[i].wrapping_sub(lsp_old[i] >> 2)).wrapping_add(lsp_new[i] >> 2);
338- }
339- lsp_az(&lsp, &mut az[0..]);
340- half_sum(lsp_new, lsp_old, &mut lsp);
341- lsp_az(&lsp, &mut az[MP1..]);
342- for i in 0..M {
343- lsp[i] = (lsp_new[i].wrapping_sub(lsp_new[i] >> 2)).wrapping_add(lsp_old[i] >> 2);
344- }
345- lsp_az(&lsp, &mut az[2 * MP1..]);
346-}
crates/ec-amr/src/nb/mod.rsmodified+7 -7
@@ -1,11 +1,11 @@
11 //! AMR-NB decoder (fixed-point, bit-exact port of the 3GPP TS 26.073 reference as
22 //! carried by the Apache-2.0 opencore-amr sources).
3-#![allow(clippy::all)]
4-pub mod basic;
3+#![allow(clippy::needless_range_loop, clippy::too_many_arguments, clippy::manual_memcpy, clippy::manual_clamp)]
54 pub mod bitstream;
65 pub mod decoder;
7-pub mod dtx;
8-pub mod excitation;
9-pub mod lpc;
10-pub mod post;
11-pub mod tables;
6+pub(crate) mod basic;
7+pub(crate) mod dtx;
8+pub(crate) mod excitation;
9+pub(crate) mod lpc;
10+pub(crate) mod post;
11+pub(crate) mod tables;
crates/ec-amr/src/nb/post.rsmodified+5 -19
@@ -1,7 +1,5 @@
11 //! AMR-NB post-processing chain: syn_filt, residu, weight_ai, a_refl, preemphasis,
22 //! agc, post_filter, post_process (bit-exact port of opencore-amr).
3-#![allow(clippy::all)]
4-#![allow(dead_code)]
53
64 use super::basic::*;
75 use super::tables::Mode;
@@ -128,9 +126,6 @@ impl PreemphasisState {
128126 pub fn new() -> Self {
129127 Self { mem_pre: 0 }
130128 }
131- pub fn reset(&mut self) {
132- self.mem_pre = 0;
133- }
134129 }
135130
136131 /// C preemphasis: in-place signal[0..l] -= g*signal[i-1] (mem for i=0).
@@ -155,9 +150,6 @@ impl AgcState {
155150 pub fn new() -> Self {
156151 Self { past_gain: 4096 }
157152 }
158- pub fn reset(&mut self) {
159- self.past_gain = 4096;
160- }
161153 }
162154
163155 fn energy_new(inp: &[i16], l: usize) -> i32 {
@@ -189,9 +181,9 @@ pub fn agc(st: &mut AgcState, sig_in: &[i16], sig_out: &mut [i16], agc_fac: i16,
189181 let l_temp = l_shl(s, exp);
190182 let gain_out = round_(l_temp);
191183 s = energy_new(&sig_in[..l], l);
192- let g0: i16;
193- if s == 0 {
194- g0 = 0;
184+
185+ let g0: i16 = if s == 0 {
186+ 0
195187 } else {
196188 let i = norm_l(s);
197189 let l_temp = s.wrapping_shl(i as u32);
@@ -204,8 +196,8 @@ pub fn agc(st: &mut AgcState, sig_in: &[i16], sig_out: &mut [i16], agc_fac: i16,
204196 let l_temp = s.wrapping_shl(9);
205197 let i = (l_temp.wrapping_add(0x8000) >> 16) as i16;
206198 let temp = 32767 - agc_fac;
207- g0 = (((i as i32) * (temp as i32)) >> 15) as i16;
208- }
199+ (((i as i32) * (temp as i32)) >> 15) as i16
200+ };
209201 let mut gain = st.past_gain;
210202 for i in 0..l {
211203 gain = (((gain as i32) * (agc_fac as i32)) >> 15) as i16;
@@ -236,9 +228,6 @@ impl PostFilterState {
236228 synth_buf: [0; M + L_FRAME],
237229 }
238230 }
239- pub fn reset(&mut self) {
240- *self = Self::new();
241- }
242231 }
243232
244233 /// C Post_Filter: syn[0..160] is the synthesis speech, replaced by the postfiltered
@@ -337,9 +326,6 @@ impl PostProcessState {
337326 pub fn new() -> Self {
338327 Self::default()
339328 }
340- pub fn reset(&mut self) {
341- *self = Self::default();
342- }
343329 }
344330
345331 /// C Post_Process: in-place high-pass filter and upscale of signal[0..lg].
crates/ec-amr/src/nb/tables.rsmodified+0 -107
@@ -1,98 +1,24 @@
11 //! Constant tables for the AMR-NB decoder. GENERATED by /tmp/amrsrc/gen/gen.py from the C sources; do not edit.
2-#![allow(dead_code)]
32
43 // ---- constants (cnst.h / mode.h / bitno_tab.h / table sizes) ----
5-pub const L_TOTAL: usize = 320;
6-pub const L_WINDOW: usize = 240;
74 pub const L_FRAME: usize = 160;
85 pub const L_FRAME_BY2: usize = 80;
96 pub const L_SUBFR: usize = 40;
107 pub const L_CODE: usize = 40;
118 pub const NB_TRACK: usize = 5;
12-pub const STEP: usize = 5;
13-pub const NB_TRACK_MR102: usize = 4;
14-pub const STEP_MR102: usize = 4;
159 pub const M: usize = 10;
1610 pub const MP1: usize = 11;
1711 pub const LSF_GAP: i16 = 205;
18-pub const LSP_PRED_FAC_MR122: i16 = 21299;
1912 pub const AZ_SIZE: usize = 44;
2013 pub const PIT_MIN_MR122: i16 = 18;
2114 pub const PIT_MIN: i16 = 20;
2215 pub const PIT_MAX: i16 = 143;
2316 pub const L_INTERPOL: usize = 11;
24-pub const L_INTER_SRCH: usize = 4;
25-pub const MU: i16 = 26214;
26-pub const AGC_FAC: i16 = 29491;
27-pub const L_NEXT: usize = 40;
2817 pub const SHARPMAX: i16 = 13017;
2918 pub const SHARPMIN: i16 = 0;
3019 pub const MAX_PRM_SIZE: usize = 57;
3120 pub const MAX_SERIAL_SIZE: usize = 244;
32-pub const GP_CLIP: i16 = 15565;
33-pub const N_FRAME: usize = 7;
34-pub const EHF_MASK: i16 = 8;
35-pub const MR795_1_SIZE: usize = 512;
36-pub const PAST_RQ_INIT_SIZE: usize = 8;
37-pub const DICO1_SIZE: usize = 256;
38-pub const DICO2_SIZE: usize = 512;
39-pub const DICO3_SIZE: usize = 512;
40-pub const MR515_3_SIZE: usize = 128;
41-pub const VQ_SIZE_HIGHRATES: usize = 128;
42-pub const VQ_SIZE_LOWRATES: usize = 64;
4321 pub const MR475_VQ_SIZE: usize = 256;
44-pub const NB_QUA_PITCH: usize = 16;
45-pub const NB_QUA_CODE: usize = 32;
46-pub const BIT_0: i16 = 0;
47-pub const BIT_1: i16 = 1;
48-pub const DICO1_5_SIZE: usize = 128;
49-pub const DICO2_5_SIZE: usize = 256;
50-pub const DICO3_5_SIZE: usize = 256;
51-pub const DICO4_5_SIZE: usize = 256;
52-pub const DICO5_5_SIZE: usize = 64;
53-pub const DTX_MAX_EMPTY_THRESH: usize = 50;
54-pub const DTX_HIST_SIZE: usize = 8;
55-pub const DTX_ELAPSED_FRAMES_THRESH: usize = 30;
56-pub const DTX_HANG_CONST: usize = 7;
57-pub const PRMNO_MR475: usize = 17;
58-pub const PRMNO_MR515: usize = 19;
59-pub const PRMNO_MR59: usize = 19;
60-pub const PRMNO_MR67: usize = 19;
61-pub const PRMNO_MR74: usize = 19;
62-pub const PRMNO_MR795: usize = 23;
63-pub const PRMNO_MR102: usize = 39;
64-pub const PRMNO_MR122: usize = 57;
65-pub const PRMNO_MRDTX: usize = 5;
66-pub const PRMNOFSF_MR475: usize = 7;
67-pub const PRMNOFSF_MR515: usize = 7;
68-pub const PRMNOFSF_MR59: usize = 7;
69-pub const PRMNOFSF_MR67: usize = 7;
70-pub const PRMNOFSF_MR74: usize = 7;
71-pub const PRMNOFSF_MR795: usize = 8;
72-pub const PRMNOFSF_MR102: usize = 12;
73-pub const PRMNOFSF_MR122: usize = 18;
74-pub const NPRED: usize = 4;
75-pub const UP_SAMP_MAX: usize = 6;
76-pub const FIR_SIZE: usize = 61;
77-pub const NUM_MODES: usize = 16;
78-pub const NUMBIT_MR475: usize = 95;
79-pub const NUMBIT_MR515: usize = 103;
80-pub const NUMBIT_MR59: usize = 118;
81-pub const NUMBIT_MR67: usize = 134;
82-pub const NUMBIT_MR74: usize = 148;
83-pub const NUMBIT_MR795: usize = 159;
84-pub const NUMBIT_MR102: usize = 204;
85-pub const NUMBIT_MR122: usize = 244;
86-pub const NUMBIT_AMR_SID: usize = 39;
87-pub const NUMBIT_GSMEFR_SID: usize = 43;
88-pub const NUMBIT_TDMAEFR_SID: usize = 38;
89-pub const NUMBIT_PDCEFR_SID: usize = 37;
90-pub const NUMBIT_UNUSED1: usize = 0;
91-pub const NUMBIT_UNUSED2: usize = 0;
92-pub const NUMBIT_UNUSED3: usize = 0;
93-pub const NUMBIT_NO_DATA: usize = 0;
94-pub const LTP_GAIN_HISTORY_LEN: usize = 9;
95-pub const GRID_POINTS: usize = 60;
9622
9723 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
9824 pub enum Mode { Mr475, Mr515, Mr59, Mr67, Mr74, Mr795, Mr102, Mr122, MrDtx }
@@ -100,9 +26,6 @@ pub enum Mode { Mr475, Mr515, Mr59, Mr67, Mr74, Mr795, Mr102, Mr122, MrDtx }
10026 pub static PRMNO: [i16; 9] = [
10127 17, 19, 19, 19, 19, 23, 39, 57, 5,
10228 ];
103-pub static PRMNOFSF: [i16; 8] = [
104- 7, 7, 7, 7, 7, 8, 12, 18,
105-];
10629 pub static BITNO_MR475: [i16; 17] = [
10730 8, 8, 7, 8, 7, 2, 8, 4, 7, 2, 4, 7,
10831 2, 8, 4, 7, 2,
@@ -267,10 +190,6 @@ pub static REORDERBITS_MR122: [i16; 244] = [
267190 225, 224, 229, 228, 227, 232, 231, 230, 235, 234, 233, 238,
268191 237, 236, 96, 199,
269192 ];
270-pub static NUMCOMPRESSEDBYTES: [i16; 16] = [
271- 13, 14, 16, 18, 19, 21, 26, 31, 6, 6, 6, 6,
272- 0, 0, 0, 1,
273-];
274193 pub static STARTPOS: [i16; 16] = [ // 2 cols
275194 0, 2, 0, 3, 0, 2, 0, 3, 1, 3, 2, 4,
276195 1, 4, 1, 4,
@@ -290,20 +209,9 @@ pub static QUA_GAIN_CODE: [i16; 99] = [ // 3 cols
290209 12510, 2673, 16096, 16263, 3060, 18429, 21142, 3448, 20763, 27485, 3836, 23097,
291210 27485, 3836, 23097,
292211 ];
293-pub static GRAY: [i16; 8] = [
294- 0, 1, 3, 2, 6, 4, 5, 7,
295-];
296212 pub static DGRAY: [i16; 8] = [
297213 0, 1, 3, 2, 5, 6, 4, 7,
298214 ];
299-pub static GRID: [i16; 61] = [
300- 32760, 32723, 32588, 32364, 32051, 31651, 31164, 30591, 29935, 29196, 28377, 27481,
301- 26509, 25465, 24351, 23170, 21926, 20621, 19260, 17846, 16384, 14876, 13327, 11743,
302- 10125, 8480, 6812, 5126, 3425, 1714, 0, -1714, -3425, -5126, -6812, -8480,
303- -10125, -11743, -13327, -14876, -16384, -17846, -19260, -20621, -21926, -23170, -24351, -25465,
304- -26509, -27481, -28377, -29196, -29935, -30591, -31164, -31651, -32051, -32364, -32588, -32723,
305- -32760,
306-];
307215 pub static INV_SQRT_TBL: [i16; 49] = [
308216 32767, 31790, 30894, 30070, 29309, 28602, 27945, 27330, 26755, 26214, 25705, 25225,
309217 24770, 24339, 23930, 23541, 23170, 22817, 22479, 22155, 21845, 21548, 21263, 20988,
@@ -332,9 +240,6 @@ pub static SLOPE: [i16; 64] = [
332240 -946, -998, -1059, -1132, -1219, -1322, -1450, -1608, -1811, -2081, -2444, -2979,
333241 -3813, -5323, -8812, -26887,
334242 ];
335-pub static LSP_INIT_DATA: [i16; 10] = [
336- 30000, 26000, 21000, 15000, 8000, 0, -8000, -15000, -21000, -26000,
337-];
338243 pub static PH_IMP_LOW_MR795: [i16; 40] = [
339244 26777, 801, 2505, -683, -1382, 582, 604, -1274, 3511, -5894, 4534, -499,
340245 -1940, 3011, -5058, 5614, -1990, -1061, -1459, 4442, -700, -5335, 4609, 452,
@@ -1335,22 +1240,10 @@ pub static SQRT_L_TBL: [i16; 50] = [
13351240 29537, 29819, 30099, 30377, 30652, 30924, 31194, 31462, 31727, 31991, 32252, 32511,
13361241 32767, 32767,
13371242 ];
1338-pub static INTER_6_PRED_LT: [i16; 61] = [
1339- 29443, 28346, 25207, 20449, 14701, 8693, 3143, -1352, -4402, -5865, -5850, -4673,
1340- -2783, -672, 1211, 2536, 3130, 2991, 2259, 1170, 0, -1001, -1652, -1868,
1341- -1666, -1147, -464, 218, 756, 1060, 1099, 904, 550, 135, -245, -514,
1342- -634, -602, -451, -231, 0, 191, 308, 340, 296, 198, 78, -36,
1343- -120, -163, -165, -132, -79, -19, 34, 73, 91, 89, 70, 38,
1344- 0,
1345-];
13461243 pub static WMFDECBYTESPERFRAME: [i16; 16] = [
13471244 12, 13, 15, 17, 19, 20, 26, 31, 5, 6, 5, 5,
13481245 0, 0, 0, 0,
13491246 ];
1350-pub static IF2DECBYTESPERFRAME: [i16; 16] = [
1351- 13, 14, 16, 18, 19, 21, 26, 31, 6, 6, 6, 6,
1352- 0, 0, 0, 1,
1353-];
13541247 pub static TABLE_GAIN_MR475: [i16; 1024] = [ // 4 cols
13551248 812, 128, 542, 140, 2873, 1135, 2266, 3402, 2067, 563, 12677, 647,
13561249 4132, 1798, 5601, 5285, 7689, 374, 3735, 441, 10912, 2638, 11807, 2494,
crates/ec-amr/src/wb/bits.rsmodified+4 -18
@@ -1,19 +1,9 @@
11 //! Bit reading (get_amr_wb_bits.cpp), MIME unsorting (mime_io.cpp) and decoder homing frame test (homing_amr_wb_dec.cpp).
2-#![allow(dead_code)]
32
43 use super::ops::*;
54
6-pub const BIT_0: i16 = -127;
75 pub const BIT_1: i16 = 127;
86
9-pub const MODE_7K: i16 = 0;
10-pub const MODE_9K: i16 = 1;
11-pub const MODE_12K: i16 = 2;
12-pub const MODE_14K: i16 = 3;
13-pub const MODE_16K: i16 = 4;
14-pub const MODE_18K: i16 = 5;
15-pub const MODE_20K: i16 = 6;
16-pub const MODE_23K: i16 = 7;
177 pub const MODE_24K: i16 = 8;
188 pub const MRDTX: i16 = 9;
199 pub const MRSID: i16 = 9;
@@ -66,14 +56,9 @@ pub fn Serial_parm_1bit(prms: &mut Prms) -> i16 {
6656
6757 // ---------------- mime_io.cpp ----------------
6858
69-pub static toc_byte: [u8; 16] = [
70- 0x04, 0x0C, 0x14, 0x1C, 0x24, 0x2C, 0x34, 0x3C, 0x44, 0x4C, 0x54, 0x5C, 0x64, 0x6C, 0x74, 0x7C,
71-];
7259 pub static unpacked_size: [i16; 16] = [
7360 132, 177, 253, 285, 317, 365, 397, 461, 477, 35, 0, 0, 0, 0, 0, 0,
7461 ];
75-pub static packed_size: [i16; 16] = [17, 23, 32, 36, 40, 46, 50, 58, 60, 5, 0, 0, 0, 0, 0, 0];
76-pub static unused_size: [i16; 16] = [4, 7, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0];
7762
7863 pub static sort_660: [i16; 132] = [
7964 0, 5, 6, 7, 61, 84, 107, 130, 62, 85, 8, 4, 37, 38, 39, 40, 58, 81, 104, 127, 60, 83, 106, 129,
@@ -247,7 +232,6 @@ pub static sort_sid: [i16; 35] = [
247232 /// RX_State of mime_io.
248233 #[derive(Clone, Copy, Default)]
249234 pub struct RxState {
250- pub prev_ft: i16,
251235 pub prev_mode: i16,
252236 }
253237
@@ -268,6 +252,7 @@ fn sorting_table(mode: i16) -> Option<&'static [i16]> {
268252 }
269253
270254 /// Port of `mime_unsorting`. `mode` must be 0..=15.
255+#[allow(unused_assignments)]
271256 pub fn mime_unsorting(
272257 unsorted_bits: &[u8],
273258 sorted_bits_into_int16: &mut [i16],
@@ -400,6 +385,7 @@ fn dhf_table(mode: i32) -> &'static [i16] {
400385 }
401386
402387 /// Port of `dhf_test`.
388+#[allow(unused_assignments)]
403389 pub fn dhf_test(input_frame: &[i16], mode: i32, nparms: i16) -> i16 {
404390 let dhf = dhf_table(mode);
405391 let mut param = [0i16; DHF_PARMS_MAX + 1];
@@ -453,8 +439,8 @@ pub fn dhf_test(input_frame: &[i16], mode: i32, nparms: i16) -> i16 {
453439 let mut tmp: i16 = 0x7fff;
454440 tmp >>= shift;
455441 tmp = shl_int16(tmp, shift);
456- tmp = dhf[i] & tmp;
457- tmp = param[i] ^ tmp;
442+ tmp &= dhf[i];
443+ tmp ^= param[i];
458444 j |= tmp;
459445 } else {
460446 j = 1;
crates/ec-amr/src/wb/core.rsmodified+1 -0
@@ -115,6 +115,7 @@ impl DecoderState {
115115
116116 /// `pvDecoder_AmrWb`: decode one frame of parameters (`prms`, one bit per i16 in
117117 /// the decoder's serial order) into 320 samples.
118+#[allow(unused_assignments)]
118119 pub fn decode_frame(
119120 mode: i16,
120121 prms_buf: &[i16],
crates/ec-amr/src/wb/dtx.rsmodified+6 -173
@@ -1,31 +1,22 @@
11 //! AMR-WB decoder DTX / comfort noise (port of dtx_decoder_amr_wb.cpp and dtx.h).
2-#![allow(dead_code)]
32
43 use super::bits::{Prms, Serial_parm, Serial_parm_1bit};
54 use super::ops::*;
65
76 pub const DTX_MAX_EMPTY_THRESH: i16 = 50;
87 pub const DTX_HIST_SIZE: usize = 8;
9-pub const DTX_HIST_SIZE_MIN_ONE: usize = 7;
108 pub const DTX_ELAPSED_FRAMES_THRESH: i16 = 24 + 7 - 1;
119 pub const DTX_HANG_CONST: i16 = 7;
12-pub const INV_MED_THRESH: i16 = 14564;
1310 pub const ISF_GAP: i16 = 128;
1411 pub const ISF_DITH_GAP: i16 = 448;
1512 pub const ISF_FACTOR_LOW: i16 = 256;
1613 pub const ISF_FACTOR_STEP: i16 = 2;
17-pub const GAIN_THR: i16 = 180;
1814 pub const GAIN_FACTOR: i16 = 75;
1915
2016 pub const SPEECH: i16 = 0;
2117 pub const DTX: i16 = 1;
2218 pub const DTX_MUTE: i16 = 2;
2319
24-pub const TX_SPEECH: i16 = 0;
25-pub const TX_SID_FIRST: i16 = 1;
26-pub const TX_SID_UPDATE: i16 = 2;
27-pub const TX_NO_DATA: i16 = 3;
28-
2920 pub const RX_SPEECH_GOOD: i16 = 0;
3021 pub const RX_SPEECH_PROBABLY_DEGRADED: i16 = 1;
3122 pub const RX_SPEECH_LOST: i16 = 2;
@@ -35,26 +26,12 @@ pub const RX_SID_UPDATE: i16 = 5;
3526 pub const RX_SID_BAD: i16 = 6;
3627 pub const RX_NO_DATA: i16 = 7;
3728
38-#[derive(Clone)]
39-pub struct DtxEncState {
40- pub isf_hist: [i16; M * DTX_HIST_SIZE],
41- pub log_en_hist: [i16; DTX_HIST_SIZE],
42- pub hist_ptr: i16,
43- pub log_en_index: i16,
44- pub cng_seed: i16,
45- pub dtxHangoverCount: i16,
46- pub decAnaElapsedCount: i16,
47- pub D: [i32; 28],
48- pub sumD: [i32; DTX_HIST_SIZE],
49-}
50-
5129 #[derive(Clone)]
5230 pub struct DtxDecState {
5331 pub since_last_sid: i16,
5432 pub true_sid_period_inv: i16,
5533 pub log_en: i16,
5634 pub old_log_en: i16,
57- pub level: i16,
5835 pub isf: [i16; M],
5936 pub isf_old: [i16; M],
6037 pub cng_seed: i16,
@@ -79,7 +56,6 @@ impl Default for DtxDecState {
7956 true_sid_period_inv: 0,
8057 log_en: 0,
8158 old_log_en: 0,
82- level: 0,
8359 isf: [0; M],
8460 isf_old: [0; M],
8561 cng_seed: 0,
@@ -192,7 +168,7 @@ pub fn dtx_dec_amr_wb(
192168 ind[2] = Serial_parm(6, prms);
193169 ind[3] = Serial_parm(5, prms);
194170 ind[4] = Serial_parm(5, prms);
195- super::isf::disf_ns(&mut ind, &mut st.isf);
171+ super::isf::disf_ns(&ind, &mut st.isf);
196172 let log_en_index = Serial_parm(6, prms);
197173 st.CN_dith = Serial_parm_1bit(prms);
198174 st.log_en = shl_int16(log_en_index, 15 - 6);
@@ -305,7 +281,7 @@ pub fn dtx_dec_amr_wb_activity_update(st: &mut DtxDecState, isf: &[i16], exc: &[
305281 /// Port of `rx_amr_wb_dtx_handler`.
306282 pub fn rx_amr_wb_dtx_handler(st: &mut DtxDecState, frame_type: i16) -> i16 {
307283 let mut new_state: i16;
308- let enc_state: i16;
284+
309285
310286 if frame_type == RX_SID_FIRST
311287 || frame_type == RX_SID_UPDATE
@@ -339,15 +315,15 @@ pub fn rx_amr_wb_dtx_handler(st: &mut DtxDecState, frame_type: i16) -> i16 {
339315 st.decAnaElapsedCount = add_int16(st.decAnaElapsedCount, 1);
340316 st.dtxHangoverAdded = 0;
341317
342- if frame_type == RX_SID_FIRST
318+ let enc_state: i16 = if frame_type == RX_SID_FIRST
343319 || frame_type == RX_SID_UPDATE
344320 || frame_type == RX_SID_BAD
345321 || frame_type == RX_NO_DATA
346322 {
347- enc_state = DTX;
323+ DTX
348324 } else {
349- enc_state = SPEECH;
350- }
325+ SPEECH
326+ };
351327
352328 if enc_state == SPEECH {
353329 st.dtxHangoverCount = DTX_HANG_CONST;
@@ -377,149 +353,6 @@ pub fn rx_amr_wb_dtx_handler(st: &mut DtxDecState, frame_type: i16) -> i16 {
377353 new_state
378354 }
379355
380-/// Port of `aver_isf_history`.
381-pub fn aver_isf_history(isf_old: &mut [i16], indices: &[i16], isf_aver: &mut [i32]) {
382- let mut isf_tmp = [0i16; 2 * M];
383- for k in 0..2 {
384- if indices[k] as i32 + 1 != 0 {
385- let ik = indices[k] as usize * M;
386- let i2 = indices[2] as usize * M;
387- for i in 0..M {
388- isf_tmp[k * M + i] = isf_old[ik + i];
389- isf_old[ik + i] = isf_old[i2 + i];
390- }
391- }
392- }
393- for j in 0..M {
394- let mut l_tmp: i32 = 0;
395- for i in 0..DTX_HIST_SIZE {
396- l_tmp = add_int32(l_tmp, isf_old[i * M + j] as i32);
397- }
398- isf_aver[j] = l_tmp;
399- }
400- for k in 0..2 {
401- if indices[k] as i32 + 1 != 0 {
402- let ik = indices[k] as usize * M;
403- for i in 0..M {
404- isf_old[ik + i] = isf_tmp[k * M + i];
405- }
406- }
407- }
408-}
409-
410-/// Port of `find_frame_indices`.
411-pub fn find_frame_indices(isf_old_tx: &[i16], indices: &mut [i16], st: &mut DtxEncState) {
412- let mut tmp: i32 = DTX_HIST_SIZE_MIN_ONE as i32;
413- let mut j: i32 = -1;
414- for i in 0..DTX_HIST_SIZE_MIN_ONE {
415- j += tmp;
416- st.sumD[i] = sub_int32(st.sumD[i], st.D[j as usize]);
417- tmp -= 1;
418- }
419- for i in (1..=DTX_HIST_SIZE_MIN_ONE).rev() {
420- st.sumD[i] = st.sumD[i - 1];
421- }
422- st.sumD[0] = 0;
423-
424- tmp = 0;
425- let mut i: i32 = 27;
426- while i >= 12 {
427- tmp += 1;
428- let mut jj = tmp;
429- while jj > 0 {
430- st.D[(i - jj + 1) as usize] = st.D[(i - jj - tmp) as usize];
431- jj -= 1;
432- }
433- i -= tmp;
434- }
435-
436- let mut ptr = st.hist_ptr as i32;
437- let hp = st.hist_ptr as usize;
438- for i in 1..DTX_HIST_SIZE {
439- ptr -= 1;
440- if ptr < 0 {
441- ptr = DTX_HIST_SIZE_MIN_ONE as i32;
442- }
443- let mut l_tmp: i32 = 0;
444- for j in 0..M {
445- let t = sub_int16(isf_old_tx[hp * M + j], isf_old_tx[ptr as usize * M + j]);
446- l_tmp = mac_16by16_to_int32(l_tmp, t, t);
447- }
448- st.D[i - 1] = l_tmp;
449- st.sumD[0] = add_int32(st.sumD[0], st.D[i - 1]);
450- st.sumD[i] = add_int32(st.sumD[i], st.D[i - 1]);
451- }
452-
453- let mut summax = st.sumD[0];
454- let mut summin = st.sumD[0];
455- indices[0] = 0;
456- indices[2] = 0;
457- for i in 1..DTX_HIST_SIZE {
458- if st.sumD[i] > summax {
459- indices[0] = i as i16;
460- summax = st.sumD[i];
461- }
462- if st.sumD[i] < summin {
463- indices[2] = i as i16;
464- summin = st.sumD[i];
465- }
466- }
467-
468- let mut summax2nd: i32 = -2147483647;
469- indices[1] = -1;
470- for i in 0..DTX_HIST_SIZE {
471- if st.sumD[i] > summax2nd && i as i16 != indices[0] {
472- indices[1] = i as i16;
473- summax2nd = st.sumD[i];
474- }
475- }
476-
477- for i in 0..3 {
478- indices[i] = sub_int16(st.hist_ptr, indices[i]);
479- if indices[i] < 0 {
480- indices[i] = add_int16(indices[i], DTX_HIST_SIZE as i16);
481- }
482- }
483-
484- let t = normalize_amr_wb(summax);
485- summax = summax.wrapping_shl(t as u32);
486- summin = summin.wrapping_shl(t as u32);
487- let mut l_tmp = mul_16by16_to_int32(amr_wb_round(summax), INV_MED_THRESH);
488- if l_tmp <= summin {
489- indices[0] = -1;
490- }
491- summax2nd = shl_int32(summax2nd, t);
492- l_tmp = mul_16by16_to_int32(amr_wb_round(summax2nd), INV_MED_THRESH);
493- if l_tmp <= summin {
494- indices[1] = -1;
495- }
496-}
497-
498-/// Port of `dithering_control`.
499-pub fn dithering_control(st: &DtxEncState) -> i16 {
500- let mut isf_diff: i32 = 0;
501- for i in 0..8 {
502- isf_diff = add_int32(isf_diff, st.sumD[i]);
503- }
504- let mut cn_dith: i16 = if (isf_diff >> 26) > 0 { 1 } else { 0 };
505-
506- let mut mean: i16 = 0;
507- for i in 0..DTX_HIST_SIZE {
508- mean = add_int16(mean, st.log_en_hist[i]);
509- }
510- mean >>= 3;
511- let mut gain_diff: i16 = 0;
512- for i in 0..DTX_HIST_SIZE {
513- let mut tmp = sub_int16(st.log_en_hist[i], mean);
514- tmp = tmp.wrapping_sub((tmp < 0) as i16);
515- gain_diff = gain_diff.wrapping_add(tmp ^ (tmp >> 15));
516- }
517- if gain_diff > GAIN_THR {
518- cn_dith = 1;
519- }
520- cn_dith
521-}
522-
523356 /// Port of `CN_dithering`.
524357 pub fn CN_dithering(isf: &mut [i16], l_log_en_int: &mut i32, dither_seed: &mut i16) {
525358 use super::exc::noise_gen_amrwb;
crates/ec-amr/src/wb/exc.rsmodified+6 -6
@@ -478,9 +478,9 @@ pub fn agc2_amr_wb(sig_in: &[i16], sig_out: &mut [i16], l_trm: i16) {
478478 temp = sig_in[i] >> 2;
479479 s = mac_16by16_to_int32(s, temp, temp);
480480 }
481- let g0: i16;
482- if s == 0 {
483- g0 = 0;
481+
482+ let g0: i16 = if s == 0 {
483+ 0
484484 } else {
485485 let i = normalize_amr_wb(s);
486486 let gain_in = amr_wb_round(s.wrapping_shl(i as u32));
@@ -489,8 +489,8 @@ pub fn agc2_amr_wb(sig_in: &[i16], sig_out: &mut [i16], l_trm: i16) {
489489 s2 = shl_int32(s2, 7);
490490 s2 = shr_int32(s2, exp);
491491 s2 = super::math::one_ov_sqrt(s2);
492- g0 = amr_wb_round(shl_int32(s2, 9));
493- }
492+ amr_wb_round(shl_int32(s2, 9))
493+ };
494494 for i in 0..l {
495495 sig_out[i] = super::math::extract_h(shl_int32(fxp_mul_16by16(sig_out[i], g0), 3));
496496 }
@@ -513,7 +513,6 @@ pub fn scale_signal(x: &mut [i16], lg: i16, exp: i16) {
513513 }
514514
515515 /// Ports `median5`. `x[c]` is the C `x[0]` (reads `x[c-2..=c+2]`).
516-#[allow(unused_assignments)]
517516 pub fn median5(x: &[i16], c: usize) -> i16 {
518517 let mut x1 = x[c - 2];
519518 let mut x2 = x[c - 1];
@@ -706,6 +705,7 @@ pub fn dec_gain2_amr_wb_init(mem: &mut [i16]) {
706705 }
707706
708707 /// Ports `dec_gain2_amr_wb`. `mem` has 23 words (see init).
708+#[allow(unused_assignments)]
709709 pub fn dec_gain2_amr_wb(
710710 index: i16,
711711 nbits: i16,
crates/ec-amr/src/wb/math.rsmodified+0 -8
@@ -6,17 +6,9 @@ pub fn extract_h(x: i32) -> i16 {
66 (x >> 16) as i16
77 }
88 #[inline]
9-pub fn extract_l(x: i32) -> i16 {
10- x as i16
11-}
12-#[inline]
139 pub fn l_deposit_h(x: i16) -> i32 {
1410 (x as i32).wrapping_shl(16)
1511 }
16-#[inline]
17-pub fn l_deposit_l(x: i16) -> i32 {
18- x as i32
19-}
2012
2113 /// Ports `mult_int16_r`.
2214 pub fn mult_int16_r(var1: i16, var2: i16) -> i16 {
crates/ec-amr/src/wb/mod.rsmodified+14 -33
@@ -1,23 +1,17 @@
11 //! AMR-WB (3GPP TS 26.173) fixed-point decoder.
2-#![allow(
3- clippy::all,
4- clippy::pedantic,
5- dead_code,
6- unused_assignments,
7- non_snake_case,
8- non_upper_case_globals
9-)]
10-
11-pub mod bits;
12-pub mod core;
13-pub mod dtx;
14-pub mod exc;
15-pub mod exc_tab;
16-pub mod isf;
17-pub mod isf_tab;
18-pub mod math;
19-pub mod ops;
20-pub mod synth;
2+#![allow(non_snake_case, non_upper_case_globals, clippy::if_same_then_else)]
3+#![allow(clippy::needless_range_loop, clippy::too_many_arguments, clippy::manual_memcpy, clippy::manual_clamp)]
4+
5+pub(crate) mod bits;
6+pub(crate) mod core;
7+pub(crate) mod dtx;
8+pub(crate) mod exc;
9+pub(crate) mod exc_tab;
10+pub(crate) mod isf;
11+pub(crate) mod isf_tab;
12+pub(crate) mod math;
13+pub(crate) mod ops;
14+pub(crate) mod synth;
2115
2216 use ec_core::error::{Error, Result};
2317 use ec_core::frame::{AudioFrame, ChannelLayout, Frame, SampleFormat};
@@ -34,16 +28,6 @@ use self::dtx::{RX_NO_DATA, RX_SPEECH_GOOD, RX_SPEECH_LOST};
3428 /// Samples in one decoded AMR-WB frame (20 ms at 16 kHz).
3529 pub const FRAME_SAMPLES: usize = 320;
3630
37-/// Payload bytes (after the ToC byte) of an AMR-WB frame type, `None` for reserved types.
38-fn payload_len(ft: u8) -> Option<usize> {
39- const SIZES: [usize; 10] = [17, 23, 32, 36, 40, 46, 50, 58, 60, 5];
40- match ft {
41- 0..=9 => Some(SIZES[usize::from(ft)]),
42- 14 | 15 => Some(0),
43- _ => None,
44- }
45-}
46-
4731 /// A fixed-point AMR-WB decoder (3GPP TS 26.173), bit-exact with the reference decoder's
4832 /// 14-bit output. Packets are one or more frames, each a ToC byte followed by the speech bits
4933 /// (the `sawb` sample layout and the `.awb` frame layout).
@@ -78,7 +62,6 @@ impl AmrWbDecoder {
7862 AmrWbDecoder {
7963 st: DecoderState::new(),
8064 rx: RxState {
81- prev_ft: RX_SPEECH_GOOD,
8265 prev_mode: 0,
8366 },
8467 mode_old: 0,
@@ -101,7 +84,6 @@ impl AmrWbDecoder {
10184 fn reset_state(&mut self) {
10285 self.st = DecoderState::new();
10386 self.rx = RxState {
104- prev_ft: RX_SPEECH_GOOD,
10587 prev_mode: 0,
10688 };
10789 self.mode_old = 0;
@@ -117,8 +99,7 @@ impl AmrWbDecoder {
11799 while at < data.len() {
118100 let toc = data[at];
119101 let ft = (toc >> 3) & 0x0F;
120- let n = payload_len(ft)
121- .ok_or_else(|| Error::corrupt(format!("AMR-WB frame type {ft} is reserved")))?;
102+ let n = crate::container::wb_frame_size(ft)?;
122103 if at + 1 + n > data.len() {
123104 return Err(Error::corrupt("AMR-WB frame is truncated"));
124105 }
crates/ec-amr/src/wb/ops.rsmodified+2 -15
@@ -1,10 +1,8 @@
11 //! ETSI-style saturating basic operators (port of the 3GPP TS 26.173 basic_op set).
2-#![allow(dead_code)]
32
43 pub const MAX_16: i16 = 32767;
54 pub const MIN_16: i16 = -32768;
65 pub const MAX_32: i32 = 0x7fff_ffff;
7-pub const MIN_32: i32 = i32::MIN;
86
97 #[inline]
108 pub fn sat16(x: i32) -> i16 {
@@ -71,7 +69,7 @@ pub fn amr_wb_shl1_round(l: i32) -> i16 {
7169 }
7270 #[inline]
7371 pub fn mul_32by16(hi: i16, lo: i16, n: i16) -> i32 {
74- (((hi as i32 * n as i32) + ((lo as i32 * n as i32) >> 15)) as i32).wrapping_shl(1)
72+ ((hi as i32 * n as i32) + ((lo as i32 * n as i32) >> 15)).wrapping_shl(1)
7573 }
7674 /// plain (non saturating) 16x16 -> 32 multiply-accumulate
7775 #[inline]
@@ -97,7 +95,7 @@ pub fn shl_int16(v: i16, s: i16) -> i16 {
9795 let s = (s & 0xf) as u32;
9896 let out = ((v as i32) << s) as i16;
9997 if ((out as i32) >> s) != v as i32 {
100- ((v >> 15) ^ MAX_16) as i16
98+ (v >> 15) ^ MAX_16
10199 } else {
102100 out
103101 }
@@ -158,10 +156,6 @@ pub fn normalize_amr_wb(x: i32) -> i16 {
158156 i as i16
159157 }
160158 #[inline]
161-pub fn norm_l(x: i32) -> i16 {
162- normalize_amr_wb(x)
163-}
164-#[inline]
165159 pub fn norm_s(x: i16) -> i16 {
166160 normalize_amr_wb(x as i32) - 16
167161 }
@@ -175,7 +169,6 @@ pub const M: usize = 16;
175169 pub const M16K: usize = 20;
176170 pub const L_FILT16K: usize = 15;
177171 pub const L_FILT: usize = 12;
178-pub const GP_CLIP: i16 = 15565;
179172 pub const PIT_SHARP: i16 = 27853;
180173 pub const PIT_MIN: i16 = 34;
181174 pub const PIT_FR2: i16 = 128;
@@ -184,14 +177,10 @@ pub const PIT_FR1_8B: i16 = 92;
184177 pub const PIT_MAX: i16 = 231;
185178 pub const L_INTERPOL: usize = 17;
186179 pub const PREEMPH_FAC: i16 = 22282;
187-pub const GAMMA1: i16 = 30147;
188-pub const TILT_FAC: i16 = 22282;
189180 pub const Q_MAX: i16 = 8;
190181 pub const RANDOM_INITSEED: i16 = 21845;
191182 pub const L_MEANBUF: usize = 3;
192-pub const ONE_PER_MEANBUF: i16 = 10923;
193183 pub const EHF_MASK: i16 = 0x0008;
194-pub const AMR_WB_PCM_FRAME: usize = 320;
195184 pub const NBBITS_7K: i16 = 132;
196185 pub const NBBITS_9K: i16 = 177;
197186 pub const NBBITS_12K: i16 = 253;
@@ -199,7 +188,5 @@ pub const NBBITS_14K: i16 = 285;
199188 pub const NBBITS_16K: i16 = 317;
200189 pub const NBBITS_18K: i16 = 365;
201190 pub const NBBITS_20K: i16 = 397;
202-pub const NBBITS_23K: i16 = 461;
203191 pub const NBBITS_24K: i16 = 477;
204-pub const NBBITS_SID: i16 = 35;
205192 pub const AMR_WB_COMPRESSED: [i16; 10] = [132, 177, 253, 285, 317, 365, 397, 461, 477, 35];
crates/ec-amr/src/wb/synth.rsmodified+0 -2
@@ -1,13 +1,11 @@
11 //! AMR-WB synthesis stage: ports of wb_syn_filt.cpp, synthesis_amr_wb.cpp,
22 //! oversamp_12k8_to_16k.cpp, highpass_50hz_at_12k8.cpp, highpass_400hz_at_12k8.cpp,
33 //! band_pass_6k_7k.cpp, low_pass_filt_7k.cpp, deemphasis_32.cpp, isf_extrapolation.cpp.
4-#![allow(dead_code)]
54
65 use super::ops::*;
76
87 const L_FIR_BP: usize = 30;
98 const L_FIR_LP: usize = 30;
10-const L_FILT16K_: usize = 15;
119 const SPEECH: i16 = 0;
1210
1311 pub static HP_GAIN: [i16; 16] = [
crates/ec-amr/tests/oracle.rsmodified+504 -191
@@ -1,227 +1,540 @@
1-//! AMR-NB oracle: synthetic sources are encoded with ffmpeg's libopencore_amrnb (every mode,
2-//! DTX on/off), then decoded by this crate and by ffmpeg. Against libopencore_amrnb (the
3-//! reference this port follows) the output must be bit-exact; against ffmpeg's native `amrnb`
4-//! decoder the SNR is reported and must stay high.
1+//! AMR-NB and AMR-WB against ffmpeg's libopencore decoders.
52 //!
3+//! NB: synthetic sources encoded with libopencore_amrnb (every mode, DTX on/off), decoded here and by
4+//! ffmpeg; bit-exact against libopencore_amrnb. WB: libopencore_amrwb / AWB and MP4 round trips,
5+//! bit-exact against the reference decoder.
66
7-use std::path::{Path, PathBuf};
8-
9-use ec_amr::nb::bitstream::frame_bytes;
10-use ec_amr::nb::decoder::AmrNbDecoder;
11-
12-const MODES: [(u32, &str); 8] = [
13- (4750, "mr475"),
14- (5150, "mr515"),
15- (5900, "mr59"),
16- (6700, "mr67"),
17- (7400, "mr74"),
18- (7950, "mr795"),
19- (10200, "mr102"),
20- (12200, "mr122"),
21-];
22-
23-const SPEECH: &str = "0.3*(sin(2*PI*140*t)+0.5*sin(2*PI*280*t)+0.3*sin(2*PI*420*t)+0.2*sin(2*PI*1100*t))*(0.5+0.5*sin(2*PI*3*t))";
24-
25-fn sources() -> Vec<(&'static str, String)> {
26- vec![
27- ("sweep", "aevalsrc=0.5*sin(2*PI*(200+400*t)*t):s=8000:d=5".into()),
28- ("noise", "anoisesrc=d=5:c=pink:r=8000:a=0.3".into()),
29- ("speech", format!("aevalsrc={SPEECH}:s=8000:d=5")),
30- (
31- "gaps",
32- format!(
33- "aevalsrc=if(between(mod(t\\,4)\\,1\\,2.5)\\,{SPEECH}\\,0.001*(random(0)-0.5)):s=8000:d=12"
7+mod nb {
8+ use std::path::{Path, PathBuf};
9+
10+ use ec_amr::nb::bitstream::frame_bytes;
11+ use ec_amr::nb::decoder::AmrNbDecoder;
12+
13+ const MODES: [(u32, &str); 8] = [
14+ (4750, "mr475"),
15+ (5150, "mr515"),
16+ (5900, "mr59"),
17+ (6700, "mr67"),
18+ (7400, "mr74"),
19+ (7950, "mr795"),
20+ (10200, "mr102"),
21+ (12200, "mr122"),
22+ ];
23+
24+ const SPEECH: &str = "0.3*(sin(2*PI*140*t)+0.5*sin(2*PI*280*t)+0.3*sin(2*PI*420*t)+0.2*sin(2*PI*1100*t))*(0.5+0.5*sin(2*PI*3*t))";
25+
26+ fn sources() -> Vec<(&'static str, String)> {
27+ vec![
28+ (
29+ "sweep",
30+ "aevalsrc=0.5*sin(2*PI*(200+400*t)*t):s=8000:d=5".into(),
3431 ),
35- ),
36- ]
37-}
32+ ("noise", "anoisesrc=d=5:c=pink:r=8000:a=0.3".into()),
33+ ("speech", format!("aevalsrc={SPEECH}:s=8000:d=5")),
34+ (
35+ "gaps",
36+ format!(
37+ "aevalsrc=if(between(mod(t\\,4)\\,1\\,2.5)\\,{SPEECH}\\,0.001*(random(0)-0.5)):s=8000:d=12"
38+ ),
39+ ),
40+ ]
41+ }
3842
39-fn workdir() -> PathBuf {
40- let d = std::env::temp_dir().join(format!("ec-amr-oracle-{}", std::process::id()));
41- std::fs::create_dir_all(&d).unwrap();
42- d
43-}
43+ fn workdir() -> PathBuf {
44+ let d = std::env::temp_dir().join(format!("ec-amr-oracle-{}", std::process::id()));
45+ std::fs::create_dir_all(&d).unwrap();
46+ d
47+ }
4448
45-fn ffmpeg_ok() -> bool {
46- ec_testkit::ffmpeg()
47- .args(["-hide_banner", "-h", "decoder=libopencore_amrnb"])
48- .output()
49- .map(|o| String::from_utf8_lossy(&o.stdout).contains("libopencore_amrnb"))
50- .unwrap_or(false)
51-}
49+ fn ffmpeg_ok() -> bool {
50+ ec_testkit::ffmpeg()
51+ .args(["-hide_banner", "-h", "decoder=libopencore_amrnb"])
52+ .output()
53+ .map(|o| String::from_utf8_lossy(&o.stdout).contains("libopencore_amrnb"))
54+ .unwrap_or(false)
55+ }
5256
53-fn run(args: &[&str]) -> Option<Vec<u8>> {
54- let out = ec_testkit::ffmpeg().args(["-nostdin", "-v", "error", "-y"]).args(args).output().ok()?;
55- out.status.success().then_some(out.stdout)
56-}
57+ fn run(args: &[&str]) -> Option<Vec<u8>> {
58+ let out = ec_testkit::ffmpeg()
59+ .args(["-nostdin", "-v", "error", "-y"])
60+ .args(args)
61+ .output()
62+ .ok()?;
63+ out.status.success().then_some(out.stdout)
64+ }
5765
58-/// Encode `src` (lavfi) to a .amr file with libopencore_amrnb.
59-fn encode(dir: &Path, name: &str, src: &str, bitrate: u32, dtx: bool) -> Option<PathBuf> {
60- let path = dir.join(format!("{name}-{bitrate}-{}.amr", dtx as u8));
61- let br = bitrate.to_string();
62- let p = path.to_str().unwrap();
63- run(&[
64- "-f", "lavfi", "-i", src, "-ar", "8000", "-ac", "1", "-c:a", "libopencore_amrnb", "-b:a", &br, "-dtx",
65- if dtx { "1" } else { "0" }, "-f", "amr", p,
66- ])?;
67- Some(path)
68-}
66+ /// Encode `src` (lavfi) to a .amr file with libopencore_amrnb.
67+ fn encode(dir: &Path, name: &str, src: &str, bitrate: u32, dtx: bool) -> Option<PathBuf> {
68+ let path = dir.join(format!("{name}-{bitrate}-{}.amr", dtx as u8));
69+ let br = bitrate.to_string();
70+ let p = path.to_str().unwrap();
71+ run(&[
72+ "-f",
73+ "lavfi",
74+ "-i",
75+ src,
76+ "-ar",
77+ "8000",
78+ "-ac",
79+ "1",
80+ "-c:a",
81+ "libopencore_amrnb",
82+ "-b:a",
83+ &br,
84+ "-dtx",
85+ if dtx { "1" } else { "0" },
86+ "-f",
87+ "amr",
88+ p,
89+ ])?;
90+ Some(path)
91+ }
6992
70-fn ffmpeg_decode(path: &Path, codec: &str) -> Vec<i16> {
71- let out = run(&["-c:a", codec, "-i", path.to_str().unwrap(), "-f", "s16le", "-"])
93+ fn ffmpeg_decode(path: &Path, codec: &str) -> Vec<i16> {
94+ let out = run(&[
95+ "-c:a",
96+ codec,
97+ "-i",
98+ path.to_str().unwrap(),
99+ "-f",
100+ "s16le",
101+ "-",
102+ ])
72103 .unwrap_or_else(|| panic!("ffmpeg -c:a {codec} failed on {}", path.display()));
73- out.as_chunks::<2>().0.iter().map(|b| i16::from_le_bytes(*b)).collect()
74-}
104+ out.as_chunks::<2>()
105+ .0
106+ .iter()
107+ .map(|b| i16::from_le_bytes(*b))
108+ .collect()
109+ }
75110
76-/// Split a `.amr` file into frames (ToC byte + payload).
77-fn parse_amr(data: &[u8]) -> Vec<Vec<u8>> {
78- let mut pos = if data.starts_with(b"#!AMR\n") { 6 } else { 0 };
79- let mut frames = Vec::new();
80- while pos < data.len() {
81- let ft = (data[pos] >> 3) & 15;
82- let Some(n) = frame_bytes(ft) else { break };
83- if pos + 1 + n > data.len() {
84- break;
111+ /// Split a `.amr` file into frames (ToC byte + payload).
112+ fn parse_amr(data: &[u8]) -> Vec<Vec<u8>> {
113+ let mut pos = if data.starts_with(b"#!AMR\n") { 6 } else { 0 };
114+ let mut frames = Vec::new();
115+ while pos < data.len() {
116+ let ft = (data[pos] >> 3) & 15;
117+ let Some(n) = frame_bytes(ft) else { break };
118+ if pos + 1 + n > data.len() {
119+ break;
120+ }
121+ frames.push(data[pos..pos + 1 + n].to_vec());
122+ pos += 1 + n;
85123 }
86- frames.push(data[pos..pos + 1 + n].to_vec());
87- pos += 1 + n;
124+ frames
88125 }
89- frames
90-}
91126
92-fn write_amr(path: &Path, frames: &[Vec<u8>]) {
93- let mut d = b"#!AMR\n".to_vec();
94- for f in frames {
95- d.extend_from_slice(f);
127+ fn write_amr(path: &Path, frames: &[Vec<u8>]) {
128+ let mut d = b"#!AMR\n".to_vec();
129+ for f in frames {
130+ d.extend_from_slice(f);
131+ }
132+ std::fs::write(path, d).unwrap();
96133 }
97- std::fs::write(path, d).unwrap();
98-}
99134
100-fn decode_all(frames: &[Vec<u8>]) -> Vec<i16> {
101- let mut dec = AmrNbDecoder::new();
102- let mut out = Vec::new();
103- for f in frames {
104- out.extend_from_slice(&dec.decode(f).expect("decode"));
135+ fn decode_all(frames: &[Vec<u8>]) -> Vec<i16> {
136+ let mut dec = AmrNbDecoder::new();
137+ let mut out = Vec::new();
138+ for f in frames {
139+ out.extend_from_slice(&dec.decode(f).expect("decode"));
140+ }
141+ out
105142 }
106- out
107-}
108143
109-fn snr_db(reference: &[i16], test: &[i16]) -> f64 {
110- let n = reference.len().min(test.len());
111- let (mut sig, mut err) = (0f64, 0f64);
112- for i in 0..n {
113- let r = reference[i] as f64;
114- sig += r * r;
115- let d = r - test[i] as f64;
116- err += d * d;
144+ fn snr_db(reference: &[i16], test: &[i16]) -> f64 {
145+ let n = reference.len().min(test.len());
146+ let (mut sig, mut err) = (0f64, 0f64);
147+ for i in 0..n {
148+ let r = reference[i] as f64;
149+ sig += r * r;
150+ let d = r - test[i] as f64;
151+ err += d * d;
152+ }
153+ if err == 0.0 {
154+ return 200.0;
155+ }
156+ 10.0 * (sig.max(1.0) / err).log10()
117157 }
118- if err == 0.0 {
119- return 200.0;
158+
159+ fn first_diff(a: &[i16], b: &[i16]) -> Option<usize> {
160+ (0..a.len().min(b.len()))
161+ .find(|&i| a[i] != b[i])
162+ .or((a.len() != b.len()).then_some(a.len().min(b.len())))
120163 }
121- 10.0 * (sig.max(1.0) / err).log10()
122-}
123164
124-fn first_diff(a: &[i16], b: &[i16]) -> Option<usize> {
125- (0..a.len().min(b.len())).find(|&i| a[i] != b[i]).or((a.len() != b.len()).then_some(a.len().min(b.len())))
126-}
165+ fn setup() -> PathBuf {
166+ assert!(ffmpeg_ok(), "ffmpeg with libopencore_amrnb is required");
167+ workdir()
168+ }
127169
128-fn setup() -> PathBuf {
129- assert!(ffmpeg_ok(), "ffmpeg with libopencore_amrnb is required");
130- workdir()
131-}
170+ #[test]
171+ fn all_modes_bit_exact_vs_libopencore() {
172+ let dir = setup();
173+ let mut checked = 0;
174+ for dtx in [false, true] {
175+ for (rate, label) in MODES {
176+ for (sname, src) in sources() {
177+ if dtx && sname != "gaps" && sname != "speech" {
178+ continue;
179+ }
180+ let path = encode(&dir, sname, &src, rate, dtx).expect("encode");
181+ let frames = parse_amr(&std::fs::read(&path).unwrap());
182+ assert!(frames.len() > 100);
183+ let sids = frames.iter().filter(|f| (f[0] >> 3) & 15 == 8).count();
184+ let nodata = frames.iter().filter(|f| (f[0] >> 3) & 15 == 15).count();
185+ let want = ffmpeg_decode(&path, "libopencore_amrnb");
186+ let got = decode_all(&frames);
187+ assert_eq!(
188+ first_diff(&got, &want),
189+ None,
190+ "{label} {sname} dtx={dtx}: differs from libopencore_amrnb ({} vs {} samples)",
191+ got.len(),
192+ want.len()
193+ );
194+ let native = ffmpeg_decode(&path, "amrnb");
195+ let snr = snr_db(&native, &got);
196+ eprintln!(
197+ "{label:6} {sname:7} dtx={} frames={} sid={sids} nodata={nodata}: bit-exact, SNR vs native amrnb = {snr:.1} dB",
198+ dtx as u8,
199+ frames.len()
200+ );
201+ if sids == 0 {
202+ assert!(snr > 15.0, "{label} {sname}: SNR vs native {snr:.1} dB");
203+ }
204+ checked += 1;
205+ }
206+ }
207+ }
208+ assert!(checked >= 8 * 6);
209+ }
210+
211+ /// Deterministic xorshift for corruption patterns.
212+ fn rng(state: &mut u64) -> u64 {
213+ *state ^= *state << 13;
214+ *state ^= *state >> 7;
215+ *state ^= *state << 17;
216+ *state
217+ }
132218
133-#[test]
134-fn all_modes_bit_exact_vs_libopencore() {
135- let dir = setup();
136- let mut checked = 0;
137- for dtx in [false, true] {
219+ #[test]
220+ fn lost_and_bit_flipped_frames_vs_libopencore() {
221+ let dir = setup();
222+ let mut seed = 0x1234_5678_9abc_def1u64;
138223 for (rate, label) in MODES {
139- for (sname, src) in sources() {
140- if dtx && sname != "gaps" && sname != "speech" {
141- continue;
224+ let (sname, src) = &sources()[2];
225+ let path = encode(&dir, sname, src, rate, false).expect("encode");
226+ let mut frames = parse_amr(&std::fs::read(&path).unwrap());
227+ for f in frames.iter_mut() {
228+ match rng(&mut seed) % 10 {
229+ 0 => *f = vec![15 << 3 | 4], // NO_DATA
230+ 1 | 2 if f.len() > 2 => {
231+ let i = 1 + (rng(&mut seed) as usize % (f.len() - 1));
232+ f[i] ^= 1 << (rng(&mut seed) % 8);
233+ }
234+ _ => {}
142235 }
143- let path = encode(&dir, sname, &src, rate, dtx).expect("encode");
144- let frames = parse_amr(&std::fs::read(&path).unwrap());
145- assert!(frames.len() > 100);
146- let sids = frames.iter().filter(|f| (f[0] >> 3) & 15 == 8).count();
147- let nodata = frames.iter().filter(|f| (f[0] >> 3) & 15 == 15).count();
148- let want = ffmpeg_decode(&path, "libopencore_amrnb");
149- let got = decode_all(&frames);
150- assert_eq!(
151- first_diff(&got, &want),
152- None,
153- "{label} {sname} dtx={dtx}: differs from libopencore_amrnb ({} vs {} samples)",
154- got.len(),
155- want.len()
156- );
157- let native = ffmpeg_decode(&path, "amrnb");
158- let snr = snr_db(&native, &got);
159- eprintln!(
160- "{label:6} {sname:7} dtx={} frames={} sid={sids} nodata={nodata}: bit-exact, SNR vs native amrnb = {snr:.1} dB",
161- dtx as u8,
162- frames.len()
163- );
164- if sids == 0 {
165- assert!(snr > 15.0, "{label} {sname}: SNR vs native {snr:.1} dB");
166- }
167- checked += 1;
168236 }
237+ let cpath = dir.join(format!("corrupt-{label}.amr"));
238+ write_amr(&cpath, &frames);
239+ let want = ffmpeg_decode(&cpath, "libopencore_amrnb");
240+ let got = decode_all(&frames);
241+ assert_eq!(
242+ first_diff(&got, &want),
243+ None,
244+ "{label}: corrupted stream differs from libopencore_amrnb"
245+ );
169246 }
170247 }
171- assert!(checked >= 8 * 6);
172-}
173248
174-/// Deterministic xorshift for corruption patterns.
175-fn rng(state: &mut u64) -> u64 {
176- *state ^= *state << 13;
177- *state ^= *state >> 7;
178- *state ^= *state << 17;
179- *state
249+ #[test]
250+ fn garbage_never_panics() {
251+ let mut dec = AmrNbDecoder::new();
252+ let mut seed = 0xdead_beef_cafe_f00du64;
253+ for i in 0..4000usize {
254+ let len = (rng(&mut seed) % 40) as usize;
255+ let mut f: Vec<u8> = (0..len).map(|_| rng(&mut seed) as u8).collect();
256+ if i % 3 == 0 && !f.is_empty() {
257+ f[0] = ((rng(&mut seed) % 16) as u8) << 3 | 4;
258+ }
259+ let pcm = dec.decode(&f).expect("decode never errors");
260+ assert_eq!(pcm.len(), 160);
261+ }
262+ // empty and truncated well-formed frames
263+ assert!(dec.decode(&[]).is_ok());
264+ assert!(dec.decode(&[7 << 3 | 4, 1, 2]).is_ok());
265+ assert!(dec.decode(&[8 << 3 | 4]).is_ok());
266+ // decoder keeps working afterwards
267+ assert_eq!(dec.decode(&[15 << 3 | 4]).unwrap().len(), 160);
268+ }
180269 }
181270
182-#[test]
183-fn lost_and_bit_flipped_frames_vs_libopencore() {
184- let dir = setup();
185- let mut seed = 0x1234_5678_9abc_def1u64;
186- for (rate, label) in MODES {
187- let (sname, src) = &sources()[2];
188- let path = encode(&dir, sname, src, rate, false).expect("encode");
189- let mut frames = parse_amr(&std::fs::read(&path).unwrap());
190- for f in frames.iter_mut() {
191- match rng(&mut seed) % 10 {
192- 0 => *f = vec![15 << 3 | 4], // NO_DATA
193- 1 | 2 if f.len() > 2 => {
194- let i = 1 + (rng(&mut seed) as usize % (f.len() - 1));
195- f[i] ^= 1 << (rng(&mut seed) % 8);
271+mod wb {
272+ use std::fs::File;
273+ use std::io::{BufReader, Cursor};
274+ use std::path::{Path, PathBuf};
275+
276+ use ec_amr::container::AmrDemuxer;
277+ use ec_amr::wb::AmrWbDecoder;
278+ use ec_core::registry::{CodecId, Decoder, Demuxer};
279+
280+ const RATES: [u32; 9] = [6600, 8850, 12650, 14250, 15850, 18250, 19850, 23050, 23850];
281+ const PAYLOAD: [usize; 10] = [17, 23, 32, 36, 40, 46, 50, 58, 60, 5];
282+
283+ fn ffmpeg(args: &[&str]) -> Option<Vec<u8>> {
284+ let out = ec_testkit::ffmpeg()
285+ .args(["-nostdin", "-v", "error", "-y"])
286+ .args(args)
287+ .output()
288+ .ok()?;
289+ out.status.success().then_some(out.stdout)
290+ }
291+
292+ struct Dir(PathBuf);
293+ impl Dir {
294+ fn new(tag: &str) -> Dir {
295+ let p = std::env::temp_dir().join(format!("ec-amr-wb-{tag}-{}", std::process::id()));
296+ std::fs::create_dir_all(&p).unwrap();
297+ Dir(p)
298+ }
299+ fn path(&self, name: &str) -> PathBuf {
300+ self.0.join(name)
301+ }
302+ }
303+ impl Drop for Dir {
304+ fn drop(&mut self) {
305+ let _ = std::fs::remove_dir_all(&self.0);
306+ }
307+ }
308+
309+ const SOURCE: &str = "aevalsrc='0.3*sin(2*PI*(200+60*sin(2*PI*0.7*t))*t)*(0.6+0.4*sin(2*PI*2.3*t))\
310++0.15*sin(2*PI*1700*t)*sin(2*PI*3*t)+0.04*(random(0)-0.5)':s=16000:d=3";
311+
312+ /// Encode the synthetic source at `rate` into `path` (format chosen by `fmt`).
313+ fn encode(path: &Path, rate: u32, fmt: &str) -> bool {
314+ ffmpeg(&[
315+ "-f",
316+ "lavfi",
317+ "-i",
318+ SOURCE,
319+ "-ac",
320+ "1",
321+ "-c:a",
322+ "libvo_amrwbenc",
323+ "-b:a",
324+ &rate.to_string(),
325+ "-f",
326+ fmt,
327+ path.to_str().unwrap(),
328+ ])
329+ .is_some()
330+ }
331+
332+ /// The reference decode of `path` as s16le.
333+ fn reference(path: &Path) -> Option<Vec<i16>> {
334+ let raw = ffmpeg(&[
335+ "-c:a",
336+ "libopencore_amrwb",
337+ "-i",
338+ path.to_str().unwrap(),
339+ "-f",
340+ "s16le",
341+ "-",
342+ ])?;
343+ Some(
344+ raw.as_chunks::<2>()
345+ .0
346+ .iter()
347+ .map(|b| i16::from_le_bytes(*b))
348+ .collect(),
349+ )
350+ }
351+
352+ fn decode_all(d: &mut dyn Demuxer, codec: CodecId) -> Vec<i16> {
353+ let stream = d
354+ .streams()
355+ .iter()
356+ .find(|s| s.params.codec == codec)
357+ .expect("an AMR-WB track")
358+ .clone();
359+ assert_eq!(codec, CodecId::AmrWb);
360+ let mut dec = AmrWbDecoder::from_parameters(stream.params.clone()).unwrap();
361+ let mut out = Vec::new();
362+ loop {
363+ match d.next_packet() {
364+ Ok(p) if p.stream != stream.index => continue,
365+ Ok(p) => out.extend_from_slice(dec.decode(&p.data).expect("decode")),
366+ Err(e) if e.is_eof() => return out,
367+ Err(e) => panic!("{e}"),
368+ }
369+ }
370+ }
371+
372+ fn have_tools() -> bool {
373+ ffmpeg(&[
374+ "-f",
375+ "lavfi",
376+ "-i",
377+ "anullsrc=r=16000:cl=mono",
378+ "-t",
379+ "0.1",
380+ "-c:a",
381+ "libvo_amrwbenc",
382+ "-f",
383+ "null",
384+ "-",
385+ ])
386+ .is_some()
387+ && ffmpeg(&["-decoders"])
388+ .is_some_and(|o| String::from_utf8_lossy(&o).contains("libopencore_amrwb"))
389+ }
390+
391+ #[test]
392+ fn every_mode_matches_the_reference_decoder_in_awb_and_mp4() {
393+ assert!(
394+ have_tools(),
395+ "ffmpeg lacks libvo_amrwbenc/libopencore_amrwb"
396+ );
397+ let dir = Dir::new("modes");
398+ for rate in RATES {
399+ let awb = dir.path(&format!("m{rate}.awb"));
400+ let mp4 = dir.path(&format!("m{rate}.3gp"));
401+ assert!(encode(&awb, rate, "amr"), "encode {rate} awb");
402+ assert!(encode(&mp4, rate, "3gp"), "encode {rate} 3gp");
403+ let want = reference(&awb).expect("reference decode");
404+ assert!(want.len() >= 48000, "{rate}: {} samples", want.len());
405+
406+ let mut d = AmrDemuxer::new(BufReader::new(File::open(&awb).unwrap())).unwrap();
407+ let got = decode_all(&mut d, CodecId::AmrWb);
408+ assert_eq!(got.len(), want.len(), "{rate} awb length");
409+ assert!(
410+ got == want,
411+ "{rate} awb: first difference at {:?}",
412+ got.iter().zip(&want).position(|(a, b)| a != b)
413+ );
414+
415+ let mut d = ec_mp4::Mp4Demuxer::new(BufReader::new(File::open(&mp4).unwrap())).unwrap();
416+ let got = decode_all(&mut d, CodecId::AmrWb);
417+ // the mp4 holds the same frames; ffmpeg may drop encoder delay, so compare the overlap
418+ assert!(
419+ got.len() >= want.len() - 640,
420+ "{rate} mp4 length {} vs {}",
421+ got.len(),
422+ want.len()
423+ );
424+ assert!(
425+ got[..want.len().min(got.len())] == want[..want.len().min(got.len())],
426+ "{rate} mp4 differs"
427+ );
428+ }
429+ }
430+
431+ /// Deterministic pseudo-random bytes.
432+ fn lcg(state: &mut u64) -> u8 {
433+ *state = state
434+ .wrapping_mul(6364136223846793005)
435+ .wrapping_add(1442695040888963407);
436+ (*state >> 33) as u8
437+ }
438+
439+ #[test]
440+ fn comfort_noise_lost_and_corrupted_frames_match_the_reference() {
441+ assert!(
442+ have_tools(),
443+ "ffmpeg lacks libvo_amrwbenc/libopencore_amrwb"
444+ );
445+ let dir = Dir::new("chaos");
446+ // Real frames of three modes, mixed with SID, lost and corrupted ones (quality bit kept set:
447+ // the reference wrapper ignores it).
448+ let mut frames: Vec<Vec<Vec<u8>>> = Vec::new();
449+ for rate in [6600, 12650, 23850] {
450+ let awb = dir.path(&format!("s{rate}.awb"));
451+ assert!(encode(&awb, rate, "amr"));
452+ let mut d = AmrDemuxer::new(BufReader::new(File::open(&awb).unwrap())).unwrap();
453+ let mut v = Vec::new();
454+ while let Ok(p) = d.next_packet() {
455+ v.push(p.data.to_vec());
456+ }
457+ frames.push(v);
458+ }
459+ let n = frames.iter().map(Vec::len).min().unwrap();
460+ let mut s = 0x1234_5678_9abc_def0u64;
461+ let mut seq: Vec<Vec<u8>> = Vec::new();
462+ for i in 0..n * 4 {
463+ let r = lcg(&mut s);
464+ let mut f = match r % 8 {
465+ 0 | 1 => {
466+ let mut sid = vec![(9 << 3) | 4];
467+ sid.extend((0..PAYLOAD[9]).map(|_| lcg(&mut s)));
468+ sid[5] &= 0xE0;
469+ sid
470+ }
471+ 2 => vec![(14 << 3) | 4],
472+ _ => frames[usize::from(lcg(&mut s)) % 3][i % n].clone(),
473+ };
474+ if r.is_multiple_of(5) {
475+ for b in f.iter_mut().skip(1) {
476+ *b ^= lcg(&mut s) & lcg(&mut s) & lcg(&mut s);
196477 }
197- _ => {}
198478 }
479+ seq.push(f);
480+ }
481+ let mut file = b"#!AMR-WB\n".to_vec();
482+ for f in &seq {
483+ file.extend_from_slice(f);
199484 }
200- let cpath = dir.join(format!("corrupt-{label}.amr"));
201- write_amr(&cpath, &frames);
202- let want = ffmpeg_decode(&cpath, "libopencore_amrnb");
203- let got = decode_all(&frames);
204- assert_eq!(first_diff(&got, &want), None, "{label}: corrupted stream differs from libopencore_amrnb");
485+ let path = dir.path("chaos.awb");
486+ std::fs::write(&path, &file).unwrap();
487+ let want = reference(&path).expect("reference decode");
488+ let mut d = AmrDemuxer::new(Cursor::new(file)).unwrap();
489+ let got = decode_all(&mut d, CodecId::AmrWb);
490+ assert_eq!(got.len(), want.len());
491+ assert!(
492+ got == want,
493+ "first difference at {:?}",
494+ got.iter().zip(&want).position(|(a, b)| a != b)
495+ );
496+ }
497+
498+ #[test]
499+ fn the_decoder_trait_yields_one_frame_per_packet() {
500+ use ec_core::frame::Frame;
501+ use ec_core::packet::{Buf, Packet};
502+ use ec_core::timebase::TimeBase;
503+ let mut dec = AmrWbDecoder::new();
504+ // mode 0 frame of zero bits, then a NO_DATA frame
505+ let mut data = vec![0x04u8];
506+ data.extend([0u8; 17]);
507+ let mut p = Packet::new(0, TimeBase::from_rate(16000), Buf::from_vec(data));
508+ p.pts = Some(0);
509+ dec.send_packet(&p).unwrap();
510+ match dec.receive_frame().unwrap() {
511+ Frame::Audio(a) => assert_eq!(a.samples, 320),
512+ _ => panic!("audio expected"),
513+ }
514+ assert!(dec.receive_frame().is_err());
515+ let p = Packet::new(0, TimeBase::from_rate(16000), Buf::from_vec(vec![0x7C]));
516+ dec.send_packet(&p).unwrap();
517+ assert!(dec.receive_frame().is_ok());
518+ // a truncated frame and a reserved type are errors, not panics
519+ assert!(dec.decode(&[0x04, 1, 2]).is_err());
520+ assert!(dec.decode(&[0x5C]).is_err());
205521 }
206-}
207522
208-#[test]
209-fn garbage_never_panics() {
210- let mut dec = AmrNbDecoder::new();
211- let mut seed = 0xdead_beef_cafe_f00du64;
212- for i in 0..4000usize {
213- let len = (rng(&mut seed) % 40) as usize;
214- let mut f: Vec<u8> = (0..len).map(|_| rng(&mut seed) as u8).collect();
215- if i % 3 == 0 && !f.is_empty() {
216- f[0] = ((rng(&mut seed) % 16) as u8) << 3 | 4;
217- }
218- let pcm = dec.decode(&f).expect("decode never errors");
219- assert_eq!(pcm.len(), 160);
220- }
221- // empty and truncated well-formed frames
222- assert!(dec.decode(&[]).is_ok());
223- assert!(dec.decode(&[7 << 3 | 4, 1, 2]).is_ok());
224- assert!(dec.decode(&[8 << 3 | 4]).is_ok());
225- // decoder keeps working afterwards
226- assert_eq!(dec.decode(&[15 << 3 | 4]).unwrap().len(), 160);
523+ #[test]
524+ fn arbitrary_bytes_never_panic() {
525+ let mut dec = AmrWbDecoder::new();
526+ let mut s = 0xdead_beef_u64;
527+ for _ in 0..4000 {
528+ let len = 1 + usize::from(lcg(&mut s)) % 70;
529+ let mut p: Vec<u8> = (0..len).map(|_| lcg(&mut s)).collect();
530+ // make most packets well formed so the speech paths run
531+ if !lcg(&mut s).is_multiple_of(4) {
532+ let ft = lcg(&mut s) % 10;
533+ p.truncate(1 + PAYLOAD[usize::from(ft)]);
534+ p[0] = (ft << 3) | 4;
535+ p.resize(1 + PAYLOAD[usize::from(ft)], 0x5a);
536+ }
537+ let _ = dec.decode(&p);
538+ }
539+ }
227540 }
crates/ec-amr/tests/wb_oracle.rsdeleted+0 -267
@@ -1,267 +0,0 @@
1-//! AMR-WB against ffmpeg's `libopencore_amrwb`, which wraps the fixed-point decoder derived from
2-//! the 3GPP TS 26.173 reference code: the output must match it sample for sample.
3-//!
4-//! Fixtures are made here with ffmpeg's `libvo_amrwbenc` from a synthetic source, one file per
5-
6-use std::fs::File;
7-use std::io::{BufReader, Cursor};
8-use std::path::{Path, PathBuf};
9-
10-use ec_amr::container::AmrDemuxer;
11-use ec_amr::wb::AmrWbDecoder;
12-use ec_core::registry::{CodecId, Decoder, Demuxer};
13-
14-const RATES: [u32; 9] = [6600, 8850, 12650, 14250, 15850, 18250, 19850, 23050, 23850];
15-const PAYLOAD: [usize; 10] = [17, 23, 32, 36, 40, 46, 50, 58, 60, 5];
16-
17-fn ffmpeg(args: &[&str]) -> Option<Vec<u8>> {
18- let out = ec_testkit::ffmpeg()
19- .args(["-nostdin", "-v", "error", "-y"])
20- .args(args)
21- .output()
22- .ok()?;
23- out.status.success().then_some(out.stdout)
24-}
25-
26-struct Dir(PathBuf);
27-impl Dir {
28- fn new(tag: &str) -> Dir {
29- let p = std::env::temp_dir().join(format!("ec-amr-wb-{tag}-{}", std::process::id()));
30- std::fs::create_dir_all(&p).unwrap();
31- Dir(p)
32- }
33- fn path(&self, name: &str) -> PathBuf {
34- self.0.join(name)
35- }
36-}
37-impl Drop for Dir {
38- fn drop(&mut self) {
39- let _ = std::fs::remove_dir_all(&self.0);
40- }
41-}
42-
43-const SOURCE: &str = "aevalsrc='0.3*sin(2*PI*(200+60*sin(2*PI*0.7*t))*t)*(0.6+0.4*sin(2*PI*2.3*t))\
44-+0.15*sin(2*PI*1700*t)*sin(2*PI*3*t)+0.04*(random(0)-0.5)':s=16000:d=3";
45-
46-/// Encode the synthetic source at `rate` into `path` (format chosen by `fmt`).
47-fn encode(path: &Path, rate: u32, fmt: &str) -> bool {
48- ffmpeg(&[
49- "-f",
50- "lavfi",
51- "-i",
52- SOURCE,
53- "-ac",
54- "1",
55- "-c:a",
56- "libvo_amrwbenc",
57- "-b:a",
58- &rate.to_string(),
59- "-f",
60- fmt,
61- path.to_str().unwrap(),
62- ])
63- .is_some()
64-}
65-
66-/// The reference decode of `path` as s16le.
67-fn reference(path: &Path) -> Option<Vec<i16>> {
68- let raw = ffmpeg(&[
69- "-c:a",
70- "libopencore_amrwb",
71- "-i",
72- path.to_str().unwrap(),
73- "-f",
74- "s16le",
75- "-",
76- ])?;
77- Some(
78- raw.as_chunks::<2>()
79- .0
80- .iter()
81- .map(|b| i16::from_le_bytes(*b))
82- .collect(),
83- )
84-}
85-
86-fn decode_all(d: &mut dyn Demuxer, codec: CodecId) -> Vec<i16> {
87- let stream = d
88- .streams()
89- .iter()
90- .find(|s| s.params.codec == codec)
91- .expect("an AMR-WB track")
92- .clone();
93- assert_eq!(codec, CodecId::AmrWb);
94- let mut dec = AmrWbDecoder::from_parameters(stream.params.clone()).unwrap();
95- let mut out = Vec::new();
96- loop {
97- match d.next_packet() {
98- Ok(p) if p.stream != stream.index => continue,
99- Ok(p) => out.extend_from_slice(dec.decode(&p.data).expect("decode")),
100- Err(e) if e.is_eof() => return out,
101- Err(e) => panic!("{e}"),
102- }
103- }
104-}
105-
106-fn have_tools() -> bool {
107- ffmpeg(&[
108- "-f",
109- "lavfi",
110- "-i",
111- "anullsrc=r=16000:cl=mono",
112- "-t",
113- "0.1",
114- "-c:a",
115- "libvo_amrwbenc",
116- "-f",
117- "null",
118- "-",
119- ])
120- .is_some()
121- && ffmpeg(&["-decoders"])
122- .is_some_and(|o| String::from_utf8_lossy(&o).contains("libopencore_amrwb"))
123-}
124-
125-#[test]
126-fn every_mode_matches_the_reference_decoder_in_awb_and_mp4() {
127- assert!(have_tools(), "ffmpeg lacks libvo_amrwbenc/libopencore_amrwb");
128- let dir = Dir::new("modes");
129- for rate in RATES {
130- let awb = dir.path(&format!("m{rate}.awb"));
131- let mp4 = dir.path(&format!("m{rate}.3gp"));
132- assert!(encode(&awb, rate, "amr"), "encode {rate} awb");
133- assert!(encode(&mp4, rate, "3gp"), "encode {rate} 3gp");
134- let want = reference(&awb).expect("reference decode");
135- assert!(want.len() >= 48000, "{rate}: {} samples", want.len());
136-
137- let mut d = AmrDemuxer::new(BufReader::new(File::open(&awb).unwrap())).unwrap();
138- let got = decode_all(&mut d, CodecId::AmrWb);
139- assert_eq!(got.len(), want.len(), "{rate} awb length");
140- assert!(
141- got == want,
142- "{rate} awb: first difference at {:?}",
143- got.iter().zip(&want).position(|(a, b)| a != b)
144- );
145-
146- let mut d = ec_mp4::Mp4Demuxer::new(BufReader::new(File::open(&mp4).unwrap())).unwrap();
147- let got = decode_all(&mut d, CodecId::AmrWb);
148- // the mp4 holds the same frames; ffmpeg may drop encoder delay, so compare the overlap
149- assert!(
150- got.len() >= want.len() - 640,
151- "{rate} mp4 length {} vs {}",
152- got.len(),
153- want.len()
154- );
155- assert!(
156- got[..want.len().min(got.len())] == want[..want.len().min(got.len())],
157- "{rate} mp4 differs"
158- );
159- }
160-}
161-
162-/// Deterministic pseudo-random bytes.
163-fn lcg(state: &mut u64) -> u8 {
164- *state = state
165- .wrapping_mul(6364136223846793005)
166- .wrapping_add(1442695040888963407);
167- (*state >> 33) as u8
168-}
169-
170-#[test]
171-fn comfort_noise_lost_and_corrupted_frames_match_the_reference() {
172- assert!(have_tools(), "ffmpeg lacks libvo_amrwbenc/libopencore_amrwb");
173- let dir = Dir::new("chaos");
174- // Real frames of three modes, mixed with SID, lost and corrupted ones (quality bit kept set:
175- // the reference wrapper ignores it).
176- let mut frames: Vec<Vec<Vec<u8>>> = Vec::new();
177- for rate in [6600, 12650, 23850] {
178- let awb = dir.path(&format!("s{rate}.awb"));
179- assert!(encode(&awb, rate, "amr"));
180- let mut d = AmrDemuxer::new(BufReader::new(File::open(&awb).unwrap())).unwrap();
181- let mut v = Vec::new();
182- while let Ok(p) = d.next_packet() {
183- v.push(p.data.to_vec());
184- }
185- frames.push(v);
186- }
187- let n = frames.iter().map(Vec::len).min().unwrap();
188- let mut s = 0x1234_5678_9abc_def0u64;
189- let mut seq: Vec<Vec<u8>> = Vec::new();
190- for i in 0..n * 4 {
191- let r = lcg(&mut s);
192- let mut f = match r % 8 {
193- 0 | 1 => {
194- let mut sid = vec![(9 << 3) | 4];
195- sid.extend((0..PAYLOAD[9]).map(|_| lcg(&mut s)));
196- sid[5] &= 0xE0;
197- sid
198- }
199- 2 => vec![(14 << 3) | 4],
200- _ => frames[usize::from(lcg(&mut s)) % 3][i % n].clone(),
201- };
202- if r.is_multiple_of(5) {
203- for b in f.iter_mut().skip(1) {
204- *b ^= lcg(&mut s) & lcg(&mut s) & lcg(&mut s);
205- }
206- }
207- seq.push(f);
208- }
209- let mut file = b"#!AMR-WB\n".to_vec();
210- for f in &seq {
211- file.extend_from_slice(f);
212- }
213- let path = dir.path("chaos.awb");
214- std::fs::write(&path, &file).unwrap();
215- let want = reference(&path).expect("reference decode");
216- let mut d = AmrDemuxer::new(Cursor::new(file)).unwrap();
217- let got = decode_all(&mut d, CodecId::AmrWb);
218- assert_eq!(got.len(), want.len());
219- assert!(
220- got == want,
221- "first difference at {:?}",
222- got.iter().zip(&want).position(|(a, b)| a != b)
223- );
224-}
225-
226-#[test]
227-fn the_decoder_trait_yields_one_frame_per_packet() {
228- use ec_core::frame::Frame;
229- use ec_core::packet::{Buf, Packet};
230- use ec_core::timebase::TimeBase;
231- let mut dec = AmrWbDecoder::new();
232- // mode 0 frame of zero bits, then a NO_DATA frame
233- let mut data = vec![0x04u8];
234- data.extend([0u8; 17]);
235- let mut p = Packet::new(0, TimeBase::from_rate(16000), Buf::from_vec(data));
236- p.pts = Some(0);
237- dec.send_packet(&p).unwrap();
238- match dec.receive_frame().unwrap() {
239- Frame::Audio(a) => assert_eq!(a.samples, 320),
240- _ => panic!("audio expected"),
241- }
242- assert!(dec.receive_frame().is_err());
243- let p = Packet::new(0, TimeBase::from_rate(16000), Buf::from_vec(vec![0x7C]));
244- dec.send_packet(&p).unwrap();
245- assert!(dec.receive_frame().is_ok());
246- // a truncated frame and a reserved type are errors, not panics
247- assert!(dec.decode(&[0x04, 1, 2]).is_err());
248- assert!(dec.decode(&[0x5C]).is_err());
249-}
250-
251-#[test]
252-fn arbitrary_bytes_never_panic() {
253- let mut dec = AmrWbDecoder::new();
254- let mut s = 0xdead_beef_u64;
255- for _ in 0..4000 {
256- let len = 1 + usize::from(lcg(&mut s)) % 70;
257- let mut p: Vec<u8> = (0..len).map(|_| lcg(&mut s)).collect();
258- // make most packets well formed so the speech paths run
259- if !lcg(&mut s).is_multiple_of(4) {
260- let ft = lcg(&mut s) % 10;
261- p.truncate(1 + PAYLOAD[usize::from(ft)]);
262- p[0] = (ft << 3) | 4;
263- p.resize(1 + PAYLOAD[usize::from(ft)], 0x5a);
264- }
265- let _ = dec.decode(&p);
266- }
267-}
crates/ec-mp3/src/encode.rsmodified+1 -17
@@ -1201,8 +1201,7 @@ fn quantise_granule(
12011201 // Short blocks carry twelve bands, long ones twenty-one.
12021202 let bands = if block_type == 2 { 12 } else { SFB_LONG };
12031203 let threshold = band_thresholds(threshold, block_type, sample_rate);
1204- let mut exit = ("cap", 19usize);
1205- for round in 0..20 {
1204+ for _ in 0..20 {
12061205 let (granule, noise) = code_with(xr, block_type, target_bits, &scalefac, sample_rate);
12071206 let ratios: Vec<f64> = (0..bands)
12081207 .map(|b| f64::from(noise[b]) / f64::from(threshold[b]).max(1e-30))
@@ -1218,7 +1217,6 @@ fn quantise_granule(
12181217 best = Some((granule, score, bands));
12191218 }
12201219 if score <= 0.0 {
1221- exit = ("mask", round);
12221220 break; // every band is already exactly at the mask; nothing left to buy
12231221 }
12241222 // Where to stop amplifying, as a fraction of the frame's budget. Swept
@@ -1241,7 +1239,6 @@ fn quantise_granule(
12411239 // the MSE optimum, so perceptual redistribution can only trade away
12421240 // what this gate scores. Don't re-run it: change the metric first.
12431241 if spent * 100 > target_bits * 85 {
1244- exit = ("budget", round);
12451242 break; // the budget is spent; amplifying now only coarsens
12461243 }
12471244 // Bands over their mask get the bits first, worst three per round so
@@ -1258,29 +1255,16 @@ fn quantise_granule(
12581255 .take(3)
12591256 .collect();
12601257 if chosen.is_empty() {
1261- exit = ("saturated", round);
12621258 break;
12631259 }
12641260 for band in chosen {
12651261 scalefac[band] += 1;
12661262 }
12671263 }
1268- census(exit);
12691264 let (granule, score, bands) = best.expect("at least one round runs");
12701265 (granule, score / bands as f64)
12711266 }
12721267
1273-/// Exit-reason census for the distortion loop: with `EC_MP3_LOOP_TRACE` set,
1274-/// one `mp3loop <reason> <round>` line per granule on stderr, so a sweep can be
1275-/// counted with `sort | uniq -c`. The loop's shape is the encoder's open
1276-/// question; without this the only evidence it ever iterates is indirect.
1277-fn census(exit: (&str, usize)) {
1278- static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1279- if *ON.get_or_init(|| std::env::var_os("EC_MP3_LOOP_TRACE").is_some()) {
1280- eprintln!("mp3loop {} {}", exit.0, exit.1);
1281- }
1282-}
1283-
12841268 /// Puts a spectrum into bitstream order in `out`.
12851269 ///
12861270 /// A short granule is coded band by band, window by window, line by line,
crates/ec-mp3/src/header.rsmodified+0 -18
@@ -247,24 +247,6 @@ impl FrameHeader {
247247 _ => 72 * bits / rate + pad,
248248 })
249249 }
250-
251- /// Bytes of main data this frame carries: everything after the header, the
252- /// optional CRC and the side info.
253- pub fn main_data_len(&self) -> Option<usize> {
254- let len = self.frame_len()?;
255- let overhead = 4 + usize::from(self.crc) * 2 + self.side_info_len();
256- Some(len.saturating_sub(overhead))
257- }
258-
259- /// True when two headers describe the same stream configuration — the test
260- /// a resync uses to tell a real frame from a byte pattern that looked like
261- /// one.
262- pub fn same_stream(&self, other: &FrameHeader) -> bool {
263- self.version == other.version
264- && self.layer == other.layer
265- && self.sample_rate == other.sample_rate
266- && self.mode.channels() == other.mode.channels()
267- }
268250 }
269251
270252 /// CRC-16 over a header and a run of protected *bits*, as Layers I and II
crates/ec-mp3/tests/encode_matrix.rsmodified+1 -331
@@ -1,44 +1,10 @@
11 //! Our encoder measured the only way a lossy one can be: encode, decode the
22 //! result with ffmpeg, correlate against the samples that went in.
3-//!
4-//! The bar is the incumbent MP3 encoder this crate replaces, 0.6.1, measured on
5-//! the same fixtures and the same metric (see `BAR`, and
6-//! `scripts/mp3-incumbent-bar.md` for how those numbers were produced).
7-//!
8-//! Run the table:
9-//! cargo test -p ec-mp3 --release --test encode_matrix -- --nocapture
103
114 use std::path::{Path, PathBuf};
125
13-use ec_mp3::{FrameHeader, Mp3Encoder, Mp3EncoderConfig};
6+use ec_mp3::{Mp3Encoder, Mp3EncoderConfig};
147
15-/// Correlation the incumbent MP3 encoder, 0.6.1, reaches on this corpus, measured with this
16-/// same alignment and metric (its own encoder, ffmpeg's decoder). The tone
17-/// fixtures reach 1.0 on both encoders and so cannot separate them; the
18-/// `mp3src-*` material — glide, broadband noise and a click every half second —
19-/// is what does.
20-const BAR: [(&str, [f64; 3]); 4] = [
21- ("mp3src-mono-44100", [0.99920, 0.99983, 0.99999]),
22- ("mp3src-stereo-44100", [0.99612, 0.99847, 0.99972]),
23- ("mp3src-mono-48000", [0.99867, 0.99972, 0.99998]),
24- ("mp3src-stereo-48000", [0.99461, 0.99787, 0.99956]),
25-];
26-const BITRATES: [u32; 3] = [128, 192, 320];
27-
28-/// The incumbent's number for this fixture and bitrate. Fixtures it was not
29-/// measured on (the tones, which both encoders code perfectly) fall back to its
30-/// worst result at that rate.
31-fn bar_for(name: &str, kbps: u32) -> f64 {
32- let index = BITRATES.iter().position(|k| *k == kbps).unwrap_or(0);
33- for (fixture, values) in BAR {
34- if name.starts_with(fixture) {
35- return values[index];
36- }
37- }
38- BAR.iter()
39- .map(|(_, v)| v[index])
40- .fold(f64::INFINITY, f64::min)
41-}
428
439 fn workdir(test: &str) -> PathBuf {
4410 let dir = std::env::temp_dir().join(format!("ec-mp3-{}-{test}", std::process::id()));
@@ -108,28 +74,6 @@ fn correlation(a: &[f32], b: &[f32]) -> f64 {
10874 ab / (aa * bb).sqrt()
10975 }
11076
111-/// Best correlation over the encoder delay, which no MP3 encoder avoids.
112-fn aligned(got: &[f32], want: &[f32], channels: usize) -> (f64, usize) {
113- let mut best = (f64::MIN, 0usize);
114- let mut offset = 0;
115- while offset + channels < got.len() && offset <= 3000 * channels {
116- let n = (got.len() - offset).min(want.len());
117- let skip = 1152 * channels;
118- if n <= 2 * skip {
119- break;
120- }
121- let corr = correlation(
122- &got[offset + skip..offset + n - skip],
123- &want[skip..n - skip],
124- );
125- if corr > best.0 {
126- best = (corr, offset);
127- }
128- offset += channels;
129- }
130- best
131-}
132-
13377 fn encode(pcm: &[f32], rate: u32, channels: usize, kbps: u32) -> Vec<u8> {
13478 let mut encoder = Mp3Encoder::new(Mp3EncoderConfig {
13579 bitrate_kbps: kbps,
@@ -192,277 +136,3 @@ fn decode(file: &Path) -> Vec<f32> {
192136 .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
193137 .collect()
194138 }
195-
196-fn encode_vbr(pcm: &[f32], rate: u32, channels: usize, quality: f32) -> Vec<u8> {
197- let mut encoder = Mp3Encoder::new(Mp3EncoderConfig {
198- bitrate_kbps: 0,
199- vbr_quality: Some(quality),
200- });
201- encoder
202- .push_pcm_f32(pcm, channels as u16, rate)
203- .expect("encoder accepts the fixture");
204- encoder.finish();
205- let mut out = Vec::new();
206- while let Ok(frame) = encoder.next_packet() {
207- out.extend_from_slice(&frame);
208- }
209- out
210-}
211-
212-/// Quality 0.5 asks for a 192 kbit/s mean; true VBR spends it unevenly across
213-/// frames, decodes at least as well as the incumbent's CBR-192, and announces
214-/// itself through a Xing tag ffprobe reads as VBR.
215-#[test]
216-fn vbr_frames_vary_their_bitrate_index() {
217- let name = "mp3src-stereo-48000";
218- let path = ec_testkit::fixture(&format!("audio/{name}.wav"));
219- let (pcm, rate, channels) = read_wav(&path);
220- let bytes = encode_vbr(&pcm, rate, channels, 0.5);
221- // Walk the frame headers (MPEG-1, Layer III), skipping the Xing frame.
222- let table = [
223- 0u32, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320,
224- ];
225- let mut indices = std::collections::BTreeSet::new();
226- let (mut pos, mut frames) = (0usize, 0usize);
227- while pos + 4 <= bytes.len() {
228- let h = &bytes[pos..pos + 4];
229- assert!(h[0] == 0xFF && (h[1] & 0xE0) == 0xE0, "sync lost at {pos}");
230- let index = usize::from(h[2] >> 4);
231- let kbps = table[index.min(14)] as usize;
232- assert!(kbps > 0, "free-format header at {pos}");
233- if frames > 0 {
234- indices.insert(index);
235- }
236- frames += 1;
237- pos += 144 * kbps * 1000 / rate as usize + usize::from((h[2] >> 1) & 1);
238- }
239- let seconds = pcm.len() as f64 / (rate as f64 * channels as f64);
240- let mean = bytes.len() as f64 * 8.0 / seconds / 1000.0;
241- let target = f64::from(ec_mp3::encode::bitrate_for_quality(0.5));
242- println!("vbr frames={frames} indices={indices:?} mean={mean:.1} kbit/s");
243- assert!(indices.len() >= 3, "only {indices:?}");
244- assert!(
245- (mean - target).abs() <= target * 0.25,
246- "mean {mean:.1} vs {target}"
247- );
248-
249- let work = workdir("vbr");
250- let file = work.join("vbr.mp3");
251- std::fs::write(&file, &bytes).unwrap();
252- let out = ec_testkit::ffmpeg()
253- .args(["-v", "warning", "-i"])
254- .arg(&file)
255- .args(["-f", "f32le", "-"])
256- .output()
257- .expect("run ffmpeg");
258- assert!(
259- out.stderr.is_empty(),
260- "ffmpeg: {}",
261- String::from_utf8_lossy(&out.stderr)
262- );
263- let decoded: Vec<f32> = out
264- .stdout
265- .as_chunks::<4>()
266- .0
267- .iter()
268- .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
269- .collect();
270- let corr = correlation(&decoded, &pcm);
271- let bar = bar_for(name, 192);
272- println!("vbr corr={corr:.5} bar={bar:.5}");
273- assert!(corr >= bar, "corr {corr:.5} < bar {bar:.5}");
274- let probe = ec_testkit::ffprobe()
275- .args(["-v", "error", "-show_format"])
276- .arg(&file)
277- .output()
278- .expect("run ffprobe");
279- let probe = String::from_utf8_lossy(&probe.stdout);
280- // "Xing" (not "Info") plus the VBR-method byte after the 9-byte version.
281- assert!(
282- &bytes[36..40] == b"Xing" && bytes[36 + 16 + 9] == 0x70,
283- "no VBR-flagged Xing tag"
284- );
285- assert!(probe.contains("format_name=mp3"), "{probe}");
286-}
287-
288-#[test]
289-fn vbr_mean_bitrate_tracks_quality_on_music() {
290- let path = ec_testkit::fixture("audio/wav16-stereo-48000.wav");
291- let (pcm, rate, channels) = read_wav(&path);
292- let mut previous = 0.0;
293- for q in [0.25f32, 0.5, 0.75] {
294- let bytes = encode_vbr(&pcm, rate, channels, q);
295- let seconds = pcm.len() as f64 / (rate as f64 * channels as f64);
296- let mean = bytes.len() as f64 * 8.0 / seconds / 1000.0;
297- let target = f64::from(ec_mp3::encode::bitrate_for_quality(q));
298- let tolerance = if q <= 0.5 { 0.70 } else { 0.25 };
299- println!("q={q:.2} mean={mean:.1} target={target:.1}");
300- assert!(
301- mean > previous,
302- "q={q:.2} mean {mean:.1} did not rise above {previous:.1}"
303- );
304- assert!(
305- (mean - target).abs() <= target * tolerance,
306- "fixture is sparse/tonal, so q={q:.2} allows {:.0}%: mean {mean:.1} vs {target:.1}",
307- tolerance * 100.0,
308- );
309- previous = mean;
310- }
311-}
312-
313-#[test]
314-fn encodes_above_the_incumbent_bar() {
315- let sources: Vec<PathBuf> = ec_testkit::fixtures("audio", "wav")
316- .into_iter()
317- .filter(|p| {
318- let name = p.file_name().unwrap().to_string_lossy().to_string();
319- (name.starts_with("wav16-") || name.starts_with("mp3src-"))
320- && (name.contains("mono") || name.contains("stereo"))
321- })
322- .collect();
323- // The corpus is eight committed WAVs (four `mp3src-*`, four `wav16-*`),
324- // all produced by `scripts/gen-fixtures.sh`. Fewer than all eight means
325- // the library drifted, not that the rows passed.
326- assert!(
327- sources.len() >= 8,
328- "only {} of the 8 mp3 encoder-matrix WAV fixtures are present",
329- sources.len()
330- );
331- let work = workdir("encode");
332- println!(
333- "{:<30} {:>5} {:>6} {:>3} {:>9} {:>8} {:>9}",
334- "fixture", "kbps", "rate", "ch", "corr", "bar", "kbit/s"
335- );
336- let mut failures = Vec::new();
337- for source in &sources {
338- let (pcm, rate, channels) = read_wav(source);
339- for kbps in BITRATES {
340- let bar = bar_for(&source.file_name().unwrap().to_string_lossy(), kbps);
341- let bytes = encode(&pcm, rate, channels, kbps);
342- let path = work.join(format!(
343- "{}-{kbps}.mp3",
344- source.file_stem().unwrap().to_string_lossy()
345- ));
346- std::fs::write(&path, &bytes).expect("write encoded file");
347- let out = ec_testkit::ffmpeg()
348- .args(["-v", "warning", "-i"])
349- .arg(&path)
350- .args(["-f", "f32le", "-"])
351- .output()
352- .expect("run ffmpeg");
353- let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
354- if !stderr.is_empty() {
355- failures.push(format!("{}: ffmpeg said {stderr}", path.display()));
356- }
357- let decoded: Vec<f32> = out
358- .stdout
359- .as_chunks::<4>()
360- .0
361- .iter()
362- .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
363- .collect();
364- // With the Info tag's delay and padding honoured, ffmpeg hands
365- // back exactly the samples that went in: same count, no shift. That
366- // is the gapless claim, so the correlation is measured at lag zero
367- // rather than at whatever lag looks best.
368- if decoded.len() != pcm.len() {
369- failures.push(format!(
370- "{}: decoded {} samples, pushed {}",
371- source.file_name().unwrap().to_string_lossy(),
372- decoded.len(),
373- pcm.len()
374- ));
375- }
376- let corr = correlation(&decoded, &pcm);
377- // A periodic fixture correlates equally well a whole period out,
378- // so a tie is not a misalignment; only a shift that is genuinely
379- // better than lag zero is.
380- let (searched, offset) = aligned(&decoded, &pcm, channels);
381- if offset != 0 && searched > corr + 1e-4 {
382- failures.push(format!(
383- "{}: lag {offset} correlates {searched:.6}, better than lag zero {corr:.6}",
384- source.file_name().unwrap().to_string_lossy(),
385- ));
386- }
387- let seconds = pcm.len() as f64 / (rate as f64 * channels as f64);
388- let measured = bytes.len() as f64 * 8.0 / seconds / 1000.0;
389- let name = source.file_name().unwrap().to_string_lossy();
390- println!(
391- "{name:<30} {kbps:>5} {rate:>6} {channels:>3} {corr:>9.5} {bar:>8.5} {measured:>9.1}"
392- );
393- // Matching counts as passing: at 320 kbit/s both encoders are
394- // within a part in 10^5 of the source and the difference between
395- // them is smaller than the metric resolves.
396- if corr < bar - 1e-5 {
397- failures.push(format!("{name} at {kbps} kbit/s: {corr:.5} < bar {bar:.5}"));
398- }
399- if (measured - kbps as f64).abs() > kbps as f64 * 0.05 {
400- failures.push(format!(
401- "{name} at {kbps} kbit/s: wrote {measured:.1} kbit/s"
402- ));
403- }
404- }
405- }
406- assert!(failures.is_empty(), "{failures:#?}");
407-}
408-
409-fn mode_exts(bytes: &[u8]) -> Vec<u8> {
410- let mut out = Vec::new();
411- let mut at = 0;
412- while at + 4 <= bytes.len() {
413- let Ok(header) = FrameHeader::parse(&bytes[at..]) else {
414- at += 1;
415- continue;
416- };
417- let Some(len) = header.frame_len() else { break };
418- out.push(header.mode_ext);
419- at += len;
420- }
421- out
422-}
423-
424-/// Mid/side is chosen for the signal it helps and declined for the one it
425-/// hurts. Two channels carrying the same waveform put everything in the sum
426-/// and nothing in the difference, which is the case mid/side exists for; two
427-/// carrying opposite waveforms are its worst case, where the difference is
428-/// the loud channel and coding it as such would spend the frame's bits on the
429-/// quiet one. Both roundtrip, because the decoder undoes whichever was
430-/// written.
431-#[test]
432-fn mid_side_follows_the_channel_correlation() {
433- let mut seed = 0x2545_f491_4f6c_dd1du64;
434- let mut noise = || {
435- seed ^= seed << 13;
436- seed ^= seed >> 7;
437- seed ^= seed << 17;
438- (seed >> 40) as f32 / 8388608.0 - 0.5
439- };
440- let n = 44100;
441- let (mut same, mut opposed) = (Vec::with_capacity(n * 2), Vec::with_capacity(n * 2));
442- for i in 0..n {
443- // Band-limited enough to be codeable: a slow tone under the noise.
444- let tone = (i as f32 * 0.03).sin() * 0.4;
445- let v = tone + noise() * 0.05;
446- same.push(v);
447- same.push(v);
448- opposed.push(v);
449- opposed.push(-v);
450- }
451- for (label, pcm, want_ms) in [("same", same, true), ("opposed", opposed, false)] {
452- let bytes = encode(&pcm, 44100, 2, 128);
453- let exts = mode_exts(&bytes);
454- assert!(exts.len() > 20, "{label}: only {} frames", exts.len());
455- let ms = exts.iter().filter(|e| *e & 2 != 0).count();
456- // The first and last frames carry priming and a tail, so judge the body.
457- let body = exts.len() - 2;
458- if want_ms {
459- assert!(
460- ms >= body,
461- "{label}: only {ms} of {} frames are mid/side",
462- exts.len()
463- );
464- } else {
465- assert_eq!(ms, 0, "{label}: {ms} frames chose mid/side");
466- }
467- }
468-}
crates/ec-mp3/tests/mp2_matrix.rsmodified+0 -219
@@ -6,7 +6,6 @@
66 //! mode, the joint-stereo bound, CRC-protected frames and Layer I -- things no
77 //! encoder here produces. The oracle is `ffmpeg -c:a mp2 -i x.mp2 -f f32le`.
88 //!
9-//!
109 //! cargo test -p ec-mp3 --release --test mp2_matrix -- --nocapture
1110
1211 use std::path::PathBuf;
@@ -110,58 +109,6 @@ impl Rng {
110109 }
111110 }
112111
113-#[test]
114-fn encoder_streams_match_ffmpeg() {
115- let dir = work_dir();
116- let sources = [
117- "sine=frequency=1000:sample_rate={R}:duration=1.5",
118- "anoisesrc=color=pink:amplitude=0.4:sample_rate={R}:duration=1.5:seed=7",
119- "aevalsrc=0.5*sin(2*PI*(100+3000*t)*t):s={R}:d=1.5",
120- ];
121- let cases: &[(&str, u32, u32, &str)] = &[
122- ("mp2", 32000, 1, "32k"),
123- ("mp2", 44100, 2, "128k"),
124- ("mp2", 48000, 2, "384k"),
125- ("mp2", 48000, 1, "64k"),
126- ("mp2", 44100, 1, "192k"),
127- ("mp2", 44100, 2, "64k"),
128- ("mp2", 32000, 2, "96k"),
129- ("mp2", 16000, 1, "32k"),
130- ("mp2", 22050, 2, "64k"),
131- ("mp2", 24000, 2, "128k"),
132- ("mp2", 24000, 1, "8k"),
133- ("mp2fixed", 44100, 2, "192k"),
134- ("mp2fixed", 22050, 1, "48k"),
135- ];
136- let mut worst_all = 0.0f32;
137- for (n, &(codec, rate, ch, br)) in cases.iter().enumerate() {
138- let src = sources[n % sources.len()].replace("{R}", &rate.to_string());
139- let path = dir.join(format!("enc-{n}.mp2"));
140- let st = ec_testkit::ffmpeg()
141- .args(["-v", "error", "-y", "-f", "lavfi", "-i", &src, "-ac"])
142- .arg(ch.to_string())
143- .args(["-c:a", codec, "-b:a", br])
144- .arg(&path)
145- .status()
146- .unwrap();
147- assert!(st.success(), "ffmpeg encode {codec} {rate} {ch} {br}");
148- let bytes = std::fs::read(&path).unwrap();
149- let want = ffmpeg_decode(&path, ch as usize, 2);
150- let (got, r, c) = our_decode(&bytes);
151- assert_eq!((r, c), (rate, ch as usize), "{codec} {rate} {ch} {br}");
152- assert_eq!(got.len(), want.len(), "{codec} {rate} {ch} {br}: length");
153- let (e, at) = max_err(&got, &want);
154- let (lsb, same) = s16_agreement(&got, &ffmpeg_decode_s16(&path, ch as usize, 2));
155- eprintln!(
156- "{codec} {rate} Hz ch={ch} {br}: max abs error {e:.3e} (at {at}); vs fixed-point s16: max {lsb} LSB, {:.2}% identical",
157- same * 100.0
158- );
159- worst_all = worst_all.max(e);
160- assert!(e <= 1e-5, "{codec} {rate} {ch} {br}: max error {e} at {at}");
161- }
162- eprintln!("worst over the encoder matrix: {worst_all:.3e}");
163-}
164-
165112 /// MSB-first bit writer for building frames.
166113 struct BitW {
167114 bytes: Vec<u8>,
@@ -465,169 +412,3 @@ fn random_frames_match_ffmpeg() {
465412 }
466413 eprintln!("{streams} random streams, worst error {worst:.3e}");
467414 }
468-
469-fn have_encoder(name: &str) -> bool {
470- ec_testkit::ffmpeg()
471- .args(["-hide_banner", "-encoders"])
472- .output()
473- .is_ok_and(|o| String::from_utf8_lossy(&o.stdout).contains(name))
474-}
475-
476-/// libtwolame writes what the ffmpeg encoder does not: joint stereo with every
477-/// intensity bound, dual channel, and CRC-protected frames.
478-#[test]
479-fn twolame_streams_match_ffmpeg() {
480- assert!(have_encoder("libtwolame"), "ffmpeg has no libtwolame");
481- let dir = work_dir();
482- let cases: &[(&str, u32, &str, u32, bool)] = &[
483- ("joint_stereo", 44100, "64k", 2, false),
484- ("joint_stereo", 48000, "96k", 2, true),
485- ("joint_stereo", 32000, "128k", 2, false),
486- ("joint_stereo", 24000, "48k", 2, true),
487- ("stereo", 44100, "192k", 2, true),
488- ("stereo", 22050, "64k", 2, false),
489- ("dual_channel", 48000, "128k", 2, false),
490- ("mono", 44100, "64k", 1, true),
491- ("mono", 16000, "32k", 1, false),
492- ("joint_stereo", 44100, "384k", 2, true),
493- ("joint_stereo", 44100, "112k", 2, false),
494- ("mono", 48000, "56k", 1, false),
495- ];
496- for (n, &(mode, rate, br, ch, crc)) in cases.iter().enumerate() {
497- let path = dir.join(format!("tl-{n}.mp2"));
498- let src = format!(
499- "aevalsrc=0.4*sin(2*PI*(300+1500*t)*t)|0.3*sin(2*PI*700*t)+0.05*random(1):s={rate}:d=2"
500- );
501- let st = ec_testkit::ffmpeg()
502- .args(["-v", "error", "-y", "-f", "lavfi", "-i", &src, "-ac"])
503- .arg(ch.to_string())
504- .args(["-c:a", "libtwolame", "-mode", mode, "-b:a", br])
505- .args(["-error_protection", if crc { "1" } else { "0" }])
506- .arg(&path)
507- .status()
508- .unwrap();
509- assert!(st.success(), "twolame {mode} {rate} {br}");
510- let bytes = std::fs::read(&path).unwrap();
511- let h = FrameHeader::parse(&bytes).unwrap();
512- assert_eq!(h.crc, crc, "{mode} {rate}: protection bit");
513- let want = ffmpeg_decode(&path, ch as usize, 2);
514- let (got, r, c) = our_decode(&bytes);
515- assert_eq!((r, c), (rate, ch as usize));
516- // ffmpeg's demuxer drops leading frames whose header differs from the
517- // ones after them (twolame flips the mode between frames): align on the
518- // tail, and skip the frame after the cut, whose filterbank history we
519- // have and ffmpeg does not.
520- let per = 1152 * ch as usize;
521- assert!(got.len() >= want.len() && (got.len() - want.len()).is_multiple_of(per));
522- let cut = got.len() - want.len();
523- let skip = if cut > 0 { per } else { 0 };
524- let (e, at) = max_err(&got[cut + skip..], &want[skip..]);
525- eprintln!("twolame {mode} {rate} Hz {br} crc={crc}: max abs error {e:.3e}");
526- assert!(e <= 1e-5, "twolame {mode} {rate} {br}: {e} at {at}");
527- }
528-}
529-
530-fn layer2_frame_with_crc() -> Vec<u8> {
531- let mut rng = Rng(77);
532- // MPEG-1 Layer II, 48 kHz, 128 kbit/s, stereo, CRC on.
533- let h = FrameHeader::parse(&[0xFF, 0xFC, 0x84, 0x00]).unwrap();
534- loop {
535- let f = structured_frame(&mut rng, &h, 40);
536- if let Some(f) = f {
537- return f;
538- }
539- }
540-}
541-
542-#[test]
543-fn crc_protects_allocation_and_scfsi() {
544- let frame = layer2_frame_with_crc();
545- assert!(FrameHeader::parse(&frame).unwrap().crc);
546- let mut reader = Mp3Reader::new();
547- reader.push(&frame);
548- assert!(reader.next_frame().is_ok(), "good CRC decodes");
549- // Flip one allocation bit.
550- let mut bad = frame.clone();
551- bad[7] ^= 0x10;
552- let mut reader = Mp3Reader::new();
553- reader.push(&bad);
554- let err = reader.next_frame().unwrap_err();
555- assert!(err.to_string().contains("CRC"), "{err}");
556- // A flip in the sample data is not covered by the CRC.
557- let mut late = frame.clone();
558- let n = late.len() - 3;
559- late[n] ^= 0xFF;
560- let mut reader = Mp3Reader::new();
561- reader.push(&late);
562- assert!(reader.next_frame().is_ok());
563-}
564-
565-#[test]
566-fn free_format_layer2_is_refused_by_name() {
567- // Bitrate index 0.
568- let mut f = vec![0xFF, 0xFD, 0x04, 0x00];
569- f.resize(600, 0);
570- let mut dec = ec_mp3::Mp3Decode::new();
571- let err = dec.decode_frame(&f).unwrap_err();
572- assert!(err.to_string().contains("free-format"), "{err}");
573-}
574-
575-#[test]
576-fn decoder_trait_takes_layer2_packets() {
577- use ec_core::packet::{Buf, Packet};
578- use ec_core::registry::{CodecId, Decoder};
579- let mut rng = Rng(5);
580- let h = FrameHeader::parse(&[0xFF, 0xFD, 0x94, 0x00]).unwrap(); // 44.1k 128k stereo
581- let params = ec_mp3::layer_codec_parameters(2, 44100, 2);
582- assert_eq!(params.codec, CodecId::Mp2);
583- let mut dec = ec_mp3::Mp3Decoder::new(params).unwrap();
584- let mut frames = 0;
585- for _ in 0..5 {
586- let f = loop {
587- if let Some(f) = structured_frame(&mut rng, &h, 30) {
588- break f;
589- }
590- };
591- let pkt = Packet::new(
592- 0,
593- ec_core::TimeBase::try_new(1, 44100).unwrap(),
594- Buf::from(f),
595- );
596- dec.send_packet(&pkt).unwrap();
597- while let Ok(frame) = dec.receive_frame() {
598- let ec_core::frame::Frame::Audio(a) = frame else {
599- panic!()
600- };
601- assert_eq!(a.samples, 1152);
602- frames += 1;
603- }
604- }
605- assert_eq!(frames, 5);
606-}
607-
608-#[test]
609-fn damaged_and_truncated_frames_never_panic() {
610- let mut rng = Rng(0xDEAD_BEEF);
611- for layer in [2u8, 1] {
612- for version in [3u8, 2, 0] {
613- for mode in [0u8, 1, 3] {
614- for _ in 0..40 {
615- let (ext, crc) = (rng.byte() % 4, rng.byte().is_multiple_of(2));
616- let h = random_header(&mut rng, layer, version, mode, ext, crc);
617- let len = h.frame_len().unwrap();
618- let mut f = h.to_bytes().to_vec();
619- f.extend((4..len).map(|_| rng.byte()));
620- // whole, then every truncation point class
621- let mut dec = ec_mp3::Mp3Decode::new();
622- let _ = dec.decode_frame(&f);
623- for cut in [5, 6, 20, len / 2, len - 1] {
624- let _ = dec.decode_frame(&f[..cut.min(len)]);
625- let mut r = Mp3Reader::new();
626- r.push(&f[..cut.min(len)]);
627- while r.next_frame().is_ok() {}
628- }
629- }
630- }
631- }
632- }
633-}