diff --git a/Cargo.lock b/Cargo.lock index 1e4dca36..e7301fb0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -390,7 +390,6 @@ version = "0.1.0" dependencies = [ "ec-core", "ec-mp4", - "ec-riff", "ec-testkit", ] diff --git a/crates/ec-amr/Cargo.toml b/crates/ec-amr/Cargo.toml index ea247b46..b2e8f073 100644 --- a/crates/ec-amr/Cargo.toml +++ b/crates/ec-amr/Cargo.toml @@ -11,5 +11,4 @@ ec-core = { workspace = true } [dev-dependencies] ec-mp4 = { workspace = true } -ec-riff = { workspace = true } ec-testkit.workspace = true diff --git a/crates/ec-amr/src/nb/basic.rs b/crates/ec-amr/src/nb/basic.rs index 2b08e15c..797075b4 100644 --- a/crates/ec-amr/src/nb/basic.rs +++ b/crates/ec-amr/src/nb/basic.rs @@ -2,7 +2,6 @@ //! opencore-amr C-equivalent basic_op. Word16 = i16, Word32 = i32. //! Plain functions have no overflow flag; `*_o` variants additionally set `*ovf = true` //! when the result saturated. `round_` is C `round`/`pv_round`. -#![allow(dead_code)] pub const MAX_16: i16 = 0x7fff; pub const MIN_16: i16 = -0x8000; @@ -13,38 +12,10 @@ use super::tables::{INV_SQRT_TBL, LOG2_TBL, POW2_TBL, SQRT_L_TBL}; // ---------------------------------------------------------------- 16-bit -/// C add (add_16). Saturating. -#[inline] -pub fn add_o(a: i16, b: i16, ovf: &mut bool) -> i16 { - let s = a as i32 + b as i32; - if s > 0x7fff { - *ovf = true; - MAX_16 - } else if s < -32768 { - *ovf = true; - MIN_16 - } else { - s as i16 - } -} #[inline] pub fn add(a: i16, b: i16) -> i16 { (a as i32 + b as i32).clamp(-32768, 32767) as i16 } -/// C sub. Saturating. -#[inline] -pub fn sub_o(a: i16, b: i16, ovf: &mut bool) -> i16 { - let s = a as i32 - b as i32; - if s > 0x7fff { - *ovf = true; - MAX_16 - } else if s < -32768 { - *ovf = true; - MIN_16 - } else { - s as i16 - } -} #[inline] pub fn sub(a: i16, b: i16) -> i16 { (a as i32 - b as i32).clamp(-32768, 32767) as i16 @@ -77,24 +48,6 @@ pub fn mult(a: i16, b: i16) -> i16 { p as i16 } } -/// (a*b + 0x4000)>>15 saturated. -#[inline] -pub fn mult_r_o(a: i16, b: i16, ovf: &mut bool) -> i16 { - let p = (a as i32 * b as i32 + 0x4000) >> 15; - if p > 0x7fff { - *ovf = true; - MAX_16 - } else if p < -32768 { - *ovf = true; - MIN_16 - } else { - p as i16 - } -} -#[inline] -pub fn mult_r(a: i16, b: i16) -> i16 { - mult_r_o(a, b, &mut false) -} /// C shl (left shift with saturation; negative count shifts right, count <= -15 gives 0). #[inline] @@ -159,18 +112,6 @@ pub fn shr_r(var1: i16, var2: i16) -> i16 { out } } -#[inline] -pub fn shr_r_o(var1: i16, var2: i16, ovf: &mut bool) -> i16 { - if var2 > 15 { - 0 - } else { - let mut out = shr_o(var1, var2, ovf); - if var2 > 0 && (var1 as i32 & (1 << (var2 - 1))) != 0 { - out = out.wrapping_add(1); - } - out - } -} // ---------------------------------------------------------------- 32-bit @@ -189,16 +130,6 @@ pub fn l_add(a: i32, b: i32) -> i32 { a.saturating_add(b) } #[inline] -pub fn l_sub_o(a: i32, b: i32, ovf: &mut bool) -> i32 { - match a.checked_sub(b) { - Some(v) => v, - None => { - *ovf = true; - if a < 0 { MIN_32 } else { MAX_32 } - } - } -} -#[inline] pub fn l_sub(a: i32, b: i32) -> i32 { a.saturating_sub(b) } @@ -212,11 +143,6 @@ pub fn l_mult(a: i16, b: i16) -> i32 { MAX_32 } } -/// Plain 16x16 product, no doubling or saturation. -#[inline] -pub fn l_mult0(a: i16, b: i16) -> i32 { - (a as i32).wrapping_mul(b as i32) -} /// C L_mac: opencore semantics (0x4000_0000 product gives MAX_32). #[inline] 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 { pub fn l_mac(acc: i32, a: i16, b: i16) -> i32 { l_mac_o(acc, a, b, &mut false) } -/// C L_msu = L_sub(acc, L_mult(a,b)). -#[inline] -pub fn l_msu_o(acc: i32, a: i16, b: i16, ovf: &mut bool) -> i32 { - l_sub_o(acc, l_mult(a, b), ovf) -} #[inline] pub fn l_msu(acc: i32, a: i16, b: i16) -> i32 { l_sub(acc, l_mult(a, b)) } -#[inline] -pub fn l_negate(a: i32) -> i32 { - if a == MIN_32 { MAX_32 } else { -a } -} -#[inline] -pub fn l_abs(a: i32) -> i32 { - if a == MIN_32 { MAX_32 } else { a.abs() } -} -#[inline] -pub fn l_deposit_h(a: i16) -> i32 { - (a as i32) << 16 -} -#[inline] -pub fn l_deposit_l(a: i16) -> i32 { - a as i32 -} -#[inline] -pub fn extract_h(a: i32) -> i16 { - (a >> 16) as i16 -} -#[inline] -pub fn extract_l(a: i32) -> i16 { - a as i16 -} /// C L_shl: left shift with saturation (negative count: arithmetic right, count <= -31 gives 0). #[inline] 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 { pub fn round_(x: i32) -> i16 { (l_add(x, 0x8000) >> 16) as i16 } -/// L_mac then round. -#[inline] -pub fn mac_r(acc: i32, a: i16, b: i16) -> i16 { - round_(l_mac(acc, a, b)) -} -/// L_msu then round. -#[inline] -pub fn msu_r(acc: i32, a: i16, b: i16) -> i16 { - round_(l_msu(acc, a, b)) -} /// Normalisation shift count for 16-bit (0 for 0 input). #[inline] @@ -395,37 +282,6 @@ pub fn div_s(var1: i16, var2: i16) -> i16 { // ---------------------------------------------------------------- 32-bit via hi/lo -/// C L_Extract: split into (hi, lo) with lo in 0..0x7fff. -#[inline] -pub fn l_extract(x: i32, hi: &mut i16, lo: &mut i16) { - let h = (x >> 16) as i16; - *hi = h; - *lo = ((x >> 1) - ((h as i32) << 15)) as i16; -} -/// C L_Comp: inverse of l_extract. -#[inline] -pub fn l_comp(hi: i16, lo: i16) -> i32 { - l_mac(l_deposit_h(hi), lo, 1) -} -/// C Mpy_32: (hi1/lo1) * (hi2/lo2), result in Q31 (saturating as in C). -#[inline] -pub fn mpy_32(h1: i16, l1: i16, h2: i16, l2: i16) -> i32 { - let mut p = h1 as i32 * h2 as i32; - p = if p != 0x4000_0000 { p << 1 } else { MAX_32 }; - let p32 = (h1 as i32 * l2 as i32) >> 15; - let s = p.wrapping_add(p32 << 1); - let mut sum = s; - if (p ^ p32) > 0 && ((s ^ p) >> 31) != 0 { - sum = if (p >> 31) != 0 { MIN_32 } else { MAX_32 }; - } - let p = sum; - let p32 = (l1 as i32 * h2 as i32) >> 15; - let s = p.wrapping_add(p32 << 1); - if (p ^ p32) > 0 && ((s ^ p) >> 31) != 0 { - return if (p >> 31) != 0 { MIN_32 } else { MAX_32 }; - } - s -} /// C Mpy_32_16: (hi/lo) * var2. #[inline] 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 { } s } -/// C Mac_32: acc + (h1/l1)*(h2/l2). -#[inline] -pub fn mac_32(acc: i32, h1: i16, l1: i16, h2: i16, l2: i16) -> i32 { - let mut a = l_mac(acc, h1, h2); - a = l_mac(a, mult(h1, l2), 1); - l_mac(a, mult(l1, h2), 1) -} -/// C Mac_32_16: acc + (hi/lo)*var2. -#[inline] -pub fn mac_32_16(acc: i32, hi: i16, lo: i16, v: i16) -> i32 { - let a = l_mac(acc, hi, v); - l_mac(a, mult(lo, v), 1) -} -/// C Div_32: L_num / (denom_hi/denom_lo), result Q31. -#[inline] -pub fn div_32(l_num: i32, d_hi: i16, d_lo: i16) -> i32 { - let approx = div_s(0x3fff, d_hi); - let mut r = mpy_32_16(d_hi, d_lo, approx); - r = 0x7fff_ffff - r; - let hi = (r >> 16) as i16; - let lo = ((r >> 1) - ((hi as i32) << 15)) as i16; - r = mpy_32_16(hi, lo, approx); - let hi = (r >> 16) as i16; - let lo = ((r >> 1) - ((hi as i32) << 15)) as i16; - let n_hi = (l_num >> 16) as i16; - let n_lo = ((l_num >> 1) - ((n_hi as i32) << 15)) as i16; - r = mpy_32(n_hi, n_lo, hi, lo); - l_shl(r, 2) -} // ---------------------------------------------------------------- math functions @@ -492,7 +319,7 @@ pub fn log2_norm(x: i32, exp: i16, exponent: &mut i16, fraction: &mut i16) { *exponent = 30i16.wrapping_sub(exp); let x = x >> 10; let i = ((x >> 15) as i16).wrapping_sub(32) as usize; - let a = (x & 0x7fff) as i32; + let a = x & 0x7fff; let mut y = (LOG2_TBL[i] as i32) << 16; let tmp = LOG2_TBL[i].wrapping_sub(LOG2_TBL[i + 1]) as i32; y = y.wrapping_sub((tmp * a) << 1); @@ -540,7 +367,7 @@ pub fn sqrt_l_exp(l_x: i32, exp: &mut i16) -> i32 { *exp = e; let x = x >> 10; let mut i = ((x >> 15) & 63) as usize; - let a = (x as i16 & 0x7fff) as i16; + let a = x as i16 & 0x7fff; if i > 15 { i -= 16; } @@ -584,7 +411,6 @@ mod tests { assert_eq!(l_mult(-32768, -32768), i32::MAX); assert_eq!(l_mac(5, -32768, -32768), i32::MAX); assert_eq!(mult(-32768, -32768), 32767); - assert_eq!(mult_r(-32768, -32768), 32767); assert_eq!(shl(0x4000, 1), 32767); assert_eq!(shl(-0x4001, 1), -32768); assert_eq!(shl(3, 2), 12); @@ -596,9 +422,6 @@ mod tests { assert_eq!(l_shl(-0x4000_0001, 1), i32::MIN); assert_eq!(l_shr_r(5, 1), 3); assert_eq!(l_shr(1, -31), i32::MAX); - let mut o = false; - add_o(32767, 1, &mut o); - assert!(o); } #[test] @@ -619,9 +442,5 @@ mod tests { log2(1 << 20, &mut e, &mut f); assert_eq!((e, f), (20, 0)); assert_eq!(gmed_n(&[5, 1, 9, 3, 7], 5), 5); - let (mut h, mut l) = (0, 0); - l_extract(0x1234_5678, &mut h, &mut l); - assert_eq!(l_comp(h, l), 0x1234_5678); } } - diff --git a/crates/ec-amr/src/nb/bitstream.rs b/crates/ec-amr/src/nb/bitstream.rs index c06b6eaa..281bb8ce 100644 --- a/crates/ec-amr/src/nb/bitstream.rs +++ b/crates/ec-amr/src/nb/bitstream.rs @@ -1,6 +1,5 @@ //! AMR-NB bitstream: RFC 4867 / 3GPP TS 26.101 IF1 (octet-aligned, "MIME/IETF storage") frame //! parsing into decoder parameters (wmf_to_ets + bits2prm of opencore-amr). -#![allow(dead_code)] use super::tables::*; @@ -178,7 +177,7 @@ mod tests { assert_eq!(frame_bytes(10), None); // (bits + 7) / 8 for each mode for ft in 0..8usize { - assert_eq!((NUMOFBITS[ft] as usize + 7) / 8, WMFDECBYTESPERFRAME[ft] as usize); + assert_eq!((NUMOFBITS[ft] as usize).div_ceil(8), WMFDECBYTESPERFRAME[ft] as usize); } } diff --git a/crates/ec-amr/src/nb/decoder.rs b/crates/ec-amr/src/nb/decoder.rs index 49e01b73..cb240147 100644 --- a/crates/ec-amr/src/nb/decoder.rs +++ b/crates/ec-amr/src/nb/decoder.rs @@ -1,6 +1,5 @@ //! AMR-NB decoder: port of opencore-amr `dec_amr.cpp` (Decoder_amr) and `sp_dec.cpp` //! (GSMFrameDecode), plus the `AMRDecode` frame-type handling of the libopencore-amrnb wrapper. -#![allow(clippy::all)] use super::basic::*; use super::bitstream::{parse_frame, BitstreamError, RxFrameType}; @@ -49,9 +48,9 @@ fn agc2(sig_in: &[i16], sig_out: &mut [i16]) { let mut exp = norm_l(s) - 1; let gain_out = round_(l_shl(s, exp)); s = energy_new(&sig_in[..l]); - let g0: i16; - if s == 0 { - g0 = 0; + + let g0: i16 = if s == 0 { + 0 } else { let i = norm_l(s); let gain_in = round_(l_shl(s, i)); @@ -74,8 +73,8 @@ fn agc2(sig_in: &[i16], sig_out: &mut [i16]) { } else { s << 9 }; - g0 = round_(lt); - } + round_(lt) + }; for i in (0..l).rev() { let lt = l_mult(sig_out[i], g0); sig_out[i] = if lt > 0x0FFF_FFFF { diff --git a/crates/ec-amr/src/nb/dtx.rs b/crates/ec-amr/src/nb/dtx.rs index bd75d486..116a5428 100644 --- a/crates/ec-amr/src/nb/dtx.rs +++ b/crates/ec-amr/src/nb/dtx.rs @@ -1,6 +1,5 @@ //! Decoder-side DTX / error-concealment helpers: dtx_dec, lsp_avg, bgnscd, c_g_aver, //! ec_gains, ex_ctrl, pseudonoise / build_CN_code. -#![allow(clippy::too_many_arguments, clippy::needless_range_loop)] use super::basic::*; use super::bitstream::RxFrameType; @@ -659,7 +658,7 @@ pub fn dtx_dec( lsf_state.past_r_q = [0; M]; let log_en_index = parm[4]; - if log_en_index > 63 || log_en_index < -64 { + if !(-64..=63).contains(&log_en_index) { st.log_en = if log_en_index > 0 { i16::MAX } else { i16::MIN }; } else { st.log_en = log_en_index << (11 - 2); diff --git a/crates/ec-amr/src/nb/excitation.rs b/crates/ec-amr/src/nb/excitation.rs index ed209bf8..371bf581 100644 --- a/crates/ec-amr/src/nb/excitation.rs +++ b/crates/ec-amr/src/nb/excitation.rs @@ -1,6 +1,5 @@ //! AMR-NB excitation decoding: pitch lag, algebraic codebooks, gains, phase dispersion. //! Bit-exact port of the 3GPP TS 26.073 reference (opencore-amr flavour). -#![allow(clippy::all, dead_code, unused_imports, unused_variables, unused_assignments)] use super::basic::*; use super::tables::*; @@ -192,10 +191,10 @@ fn pulse_val(sign: i32) -> i16 { /// C `dec_10i40_35bits` (MR122 codebook). `index` has 10 entries; `cod` 40 samples. #[inline] pub fn dec_10i40_35bits(index: &[i16], cod: &mut [i16]) { - for c in cod[..L_CODE as usize].iter_mut() { + for c in cod[..L_CODE].iter_mut() { *c = 0; } - for j in 0..NB_TRACK as usize { + for j in 0..NB_TRACK { let tmp = index[j] as i32; let i = DGRAY[(tmp & 7) as usize] as i32; let pos1 = (i * 5) as usize + j; @@ -327,7 +326,7 @@ fn decompress10(msbs: i32, lsbs: i32, index1: usize, index2: usize, index3: usiz #[inline] pub fn dec_8i40_31bits(index: &[i16], cod: &mut [i16]) { const NT: usize = 4; - for c in cod[..L_CODE as usize].iter_mut() { + for c in cod[..L_CODE].iter_mut() { *c = 0; } let mut signs = [0i32; NT]; @@ -433,7 +432,7 @@ pub fn gc_pred( let mut exp = 0i16; let mut frac = 0i16; log2(ener_code, &mut exp, &mut frac); - let l1 = ((exp as i32 - 30) as i32).wrapping_shl(16); + let l1 = (exp as i32 - 30).wrapping_shl(16); ener_code = l1.wrapping_add((frac as i32) << 1); let mut ener = MEAN_ENER_MR122; for i in 0..NPRED { @@ -487,7 +486,7 @@ pub fn gc_pred( l_tmp <<= 10; } for i in 0..4 { - let l2 = ((PRED[i] * st.past_qua_en[i] as i32)) << 1; + let l2 = (PRED[i] * st.past_qua_en[i] as i32) << 1; l_tmp = l_add(l_tmp, l2); } 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: & ); let index = (index & 31) as usize; let p = &QUA_GAIN_CODE[index + (index << 1)..]; - let gain_code: i16; - if mode == Mode::Mr122 { + + let gain_code: i16 = if mode == Mode::Mr122 { let mut gcode0 = pow2(exp, frac) as i16; gcode0 = shl(gcode0, 4); - gain_code = shl(mult(gcode0, p[0]), 1); + shl(mult(gcode0, p[0]), 1) } else { let gcode0 = pow2(14, frac) as i16; let l = l_mult(p[0], gcode0); let l = l_shr(l, sub(9, exp)); - gain_code = (l >> 16) as i16; - } + (l >> 16) as i16 + }; let qua_ener_mr122 = p[1]; let qua_ener = p[2]; gc_pred_update(pred_state, qua_ener_mr122, qua_ener); diff --git a/crates/ec-amr/src/nb/lpc.rs b/crates/ec-amr/src/nb/lpc.rs index b875f54f..ece4c217 100644 --- a/crates/ec-amr/src/nb/lpc.rs +++ b/crates/ec-amr/src/nb/lpc.rs @@ -1,6 +1,5 @@ //! LSF/LSP decoding, conversion and interpolation (d_plsf*, int_lsf, lsp_lsf, //! lsp_az, int_lpc, reorder). Bit-exact port of the 3GPP reference. -#![allow(dead_code)] use super::basic::{add, mult, negate, shl, sub}; use super::tables::{ @@ -305,15 +304,6 @@ pub fn int_lpc_1and3(lsp_old: &[i16], lsp_mid: &[i16], lsp_new: &[i16], az: &mut lsp_az(lsp_new, &mut az[3 * MP1..]); } -/// C `Int_lpc_1and3_2`: writes Az[0..11] (subframe 1) and Az[22..33] (subframe 3). -pub fn int_lpc_1and3_2(lsp_old: &[i16], lsp_mid: &[i16], lsp_new: &[i16], az: &mut [i16]) { - let mut lsp = [0i16; M]; - half_sum(lsp_old, lsp_mid, &mut lsp); - lsp_az(&lsp, &mut az[0..]); - half_sum(lsp_mid, lsp_new, &mut lsp); - lsp_az(&lsp, &mut az[2 * MP1..]); -} - /// C `Int_lpc_1to3`: 4 subframes from old/new LSPs; writes Az[0..44]. pub fn int_lpc_1to3(lsp_old: &[i16], lsp_new: &[i16], az: &mut [i16]) { let mut lsp = [0i16; M]; @@ -329,18 +319,3 @@ pub fn int_lpc_1to3(lsp_old: &[i16], lsp_new: &[i16], az: &mut [i16]) { lsp_az(&lsp, &mut az[2 * MP1..]); lsp_az(lsp_new, &mut az[3 * MP1..]); } - -/// C `Int_lpc_1to3_2`: like `int_lpc_1to3` but only Az[0..33] (first 3 subframes). -pub fn int_lpc_1to3_2(lsp_old: &[i16], lsp_new: &[i16], az: &mut [i16]) { - let mut lsp = [0i16; M]; - for i in 0..M { - lsp[i] = (lsp_old[i].wrapping_sub(lsp_old[i] >> 2)).wrapping_add(lsp_new[i] >> 2); - } - lsp_az(&lsp, &mut az[0..]); - half_sum(lsp_new, lsp_old, &mut lsp); - lsp_az(&lsp, &mut az[MP1..]); - for i in 0..M { - lsp[i] = (lsp_new[i].wrapping_sub(lsp_new[i] >> 2)).wrapping_add(lsp_old[i] >> 2); - } - lsp_az(&lsp, &mut az[2 * MP1..]); -} diff --git a/crates/ec-amr/src/nb/mod.rs b/crates/ec-amr/src/nb/mod.rs index f5797edc..032dae7f 100644 --- a/crates/ec-amr/src/nb/mod.rs +++ b/crates/ec-amr/src/nb/mod.rs @@ -1,11 +1,11 @@ //! AMR-NB decoder (fixed-point, bit-exact port of the 3GPP TS 26.073 reference as //! carried by the Apache-2.0 opencore-amr sources). -#![allow(clippy::all)] -pub mod basic; +#![allow(clippy::needless_range_loop, clippy::too_many_arguments, clippy::manual_memcpy, clippy::manual_clamp)] pub mod bitstream; pub mod decoder; -pub mod dtx; -pub mod excitation; -pub mod lpc; -pub mod post; -pub mod tables; +pub(crate) mod basic; +pub(crate) mod dtx; +pub(crate) mod excitation; +pub(crate) mod lpc; +pub(crate) mod post; +pub(crate) mod tables; diff --git a/crates/ec-amr/src/nb/post.rs b/crates/ec-amr/src/nb/post.rs index 02ddee4f..80c9ac67 100644 --- a/crates/ec-amr/src/nb/post.rs +++ b/crates/ec-amr/src/nb/post.rs @@ -1,7 +1,5 @@ //! AMR-NB post-processing chain: syn_filt, residu, weight_ai, a_refl, preemphasis, //! agc, post_filter, post_process (bit-exact port of opencore-amr). -#![allow(clippy::all)] -#![allow(dead_code)] use super::basic::*; use super::tables::Mode; @@ -128,9 +126,6 @@ impl PreemphasisState { pub fn new() -> Self { Self { mem_pre: 0 } } - pub fn reset(&mut self) { - self.mem_pre = 0; - } } /// C preemphasis: in-place signal[0..l] -= g*signal[i-1] (mem for i=0). @@ -155,9 +150,6 @@ impl AgcState { pub fn new() -> Self { Self { past_gain: 4096 } } - pub fn reset(&mut self) { - self.past_gain = 4096; - } } 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, let l_temp = l_shl(s, exp); let gain_out = round_(l_temp); s = energy_new(&sig_in[..l], l); - let g0: i16; - if s == 0 { - g0 = 0; + + let g0: i16 = if s == 0 { + 0 } else { let i = norm_l(s); 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, let l_temp = s.wrapping_shl(9); let i = (l_temp.wrapping_add(0x8000) >> 16) as i16; let temp = 32767 - agc_fac; - g0 = (((i as i32) * (temp as i32)) >> 15) as i16; - } + (((i as i32) * (temp as i32)) >> 15) as i16 + }; let mut gain = st.past_gain; for i in 0..l { gain = (((gain as i32) * (agc_fac as i32)) >> 15) as i16; @@ -236,9 +228,6 @@ impl PostFilterState { synth_buf: [0; M + L_FRAME], } } - pub fn reset(&mut self) { - *self = Self::new(); - } } /// C Post_Filter: syn[0..160] is the synthesis speech, replaced by the postfiltered @@ -337,9 +326,6 @@ impl PostProcessState { pub fn new() -> Self { Self::default() } - pub fn reset(&mut self) { - *self = Self::default(); - } } /// C Post_Process: in-place high-pass filter and upscale of signal[0..lg]. diff --git a/crates/ec-amr/src/nb/tables.rs b/crates/ec-amr/src/nb/tables.rs index 9ece769a..c6ac48fa 100644 --- a/crates/ec-amr/src/nb/tables.rs +++ b/crates/ec-amr/src/nb/tables.rs @@ -1,98 +1,24 @@ //! Constant tables for the AMR-NB decoder. GENERATED by /tmp/amrsrc/gen/gen.py from the C sources; do not edit. -#![allow(dead_code)] // ---- constants (cnst.h / mode.h / bitno_tab.h / table sizes) ---- -pub const L_TOTAL: usize = 320; -pub const L_WINDOW: usize = 240; pub const L_FRAME: usize = 160; pub const L_FRAME_BY2: usize = 80; pub const L_SUBFR: usize = 40; pub const L_CODE: usize = 40; pub const NB_TRACK: usize = 5; -pub const STEP: usize = 5; -pub const NB_TRACK_MR102: usize = 4; -pub const STEP_MR102: usize = 4; pub const M: usize = 10; pub const MP1: usize = 11; pub const LSF_GAP: i16 = 205; -pub const LSP_PRED_FAC_MR122: i16 = 21299; pub const AZ_SIZE: usize = 44; pub const PIT_MIN_MR122: i16 = 18; pub const PIT_MIN: i16 = 20; pub const PIT_MAX: i16 = 143; pub const L_INTERPOL: usize = 11; -pub const L_INTER_SRCH: usize = 4; -pub const MU: i16 = 26214; -pub const AGC_FAC: i16 = 29491; -pub const L_NEXT: usize = 40; pub const SHARPMAX: i16 = 13017; pub const SHARPMIN: i16 = 0; pub const MAX_PRM_SIZE: usize = 57; pub const MAX_SERIAL_SIZE: usize = 244; -pub const GP_CLIP: i16 = 15565; -pub const N_FRAME: usize = 7; -pub const EHF_MASK: i16 = 8; -pub const MR795_1_SIZE: usize = 512; -pub const PAST_RQ_INIT_SIZE: usize = 8; -pub const DICO1_SIZE: usize = 256; -pub const DICO2_SIZE: usize = 512; -pub const DICO3_SIZE: usize = 512; -pub const MR515_3_SIZE: usize = 128; -pub const VQ_SIZE_HIGHRATES: usize = 128; -pub const VQ_SIZE_LOWRATES: usize = 64; pub const MR475_VQ_SIZE: usize = 256; -pub const NB_QUA_PITCH: usize = 16; -pub const NB_QUA_CODE: usize = 32; -pub const BIT_0: i16 = 0; -pub const BIT_1: i16 = 1; -pub const DICO1_5_SIZE: usize = 128; -pub const DICO2_5_SIZE: usize = 256; -pub const DICO3_5_SIZE: usize = 256; -pub const DICO4_5_SIZE: usize = 256; -pub const DICO5_5_SIZE: usize = 64; -pub const DTX_MAX_EMPTY_THRESH: usize = 50; -pub const DTX_HIST_SIZE: usize = 8; -pub const DTX_ELAPSED_FRAMES_THRESH: usize = 30; -pub const DTX_HANG_CONST: usize = 7; -pub const PRMNO_MR475: usize = 17; -pub const PRMNO_MR515: usize = 19; -pub const PRMNO_MR59: usize = 19; -pub const PRMNO_MR67: usize = 19; -pub const PRMNO_MR74: usize = 19; -pub const PRMNO_MR795: usize = 23; -pub const PRMNO_MR102: usize = 39; -pub const PRMNO_MR122: usize = 57; -pub const PRMNO_MRDTX: usize = 5; -pub const PRMNOFSF_MR475: usize = 7; -pub const PRMNOFSF_MR515: usize = 7; -pub const PRMNOFSF_MR59: usize = 7; -pub const PRMNOFSF_MR67: usize = 7; -pub const PRMNOFSF_MR74: usize = 7; -pub const PRMNOFSF_MR795: usize = 8; -pub const PRMNOFSF_MR102: usize = 12; -pub const PRMNOFSF_MR122: usize = 18; -pub const NPRED: usize = 4; -pub const UP_SAMP_MAX: usize = 6; -pub const FIR_SIZE: usize = 61; -pub const NUM_MODES: usize = 16; -pub const NUMBIT_MR475: usize = 95; -pub const NUMBIT_MR515: usize = 103; -pub const NUMBIT_MR59: usize = 118; -pub const NUMBIT_MR67: usize = 134; -pub const NUMBIT_MR74: usize = 148; -pub const NUMBIT_MR795: usize = 159; -pub const NUMBIT_MR102: usize = 204; -pub const NUMBIT_MR122: usize = 244; -pub const NUMBIT_AMR_SID: usize = 39; -pub const NUMBIT_GSMEFR_SID: usize = 43; -pub const NUMBIT_TDMAEFR_SID: usize = 38; -pub const NUMBIT_PDCEFR_SID: usize = 37; -pub const NUMBIT_UNUSED1: usize = 0; -pub const NUMBIT_UNUSED2: usize = 0; -pub const NUMBIT_UNUSED3: usize = 0; -pub const NUMBIT_NO_DATA: usize = 0; -pub const LTP_GAIN_HISTORY_LEN: usize = 9; -pub const GRID_POINTS: usize = 60; #[derive(Clone, Copy, PartialEq, Eq, Debug)] 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 } pub static PRMNO: [i16; 9] = [ 17, 19, 19, 19, 19, 23, 39, 57, 5, ]; -pub static PRMNOFSF: [i16; 8] = [ - 7, 7, 7, 7, 7, 8, 12, 18, -]; pub static BITNO_MR475: [i16; 17] = [ 8, 8, 7, 8, 7, 2, 8, 4, 7, 2, 4, 7, 2, 8, 4, 7, 2, @@ -267,10 +190,6 @@ pub static REORDERBITS_MR122: [i16; 244] = [ 225, 224, 229, 228, 227, 232, 231, 230, 235, 234, 233, 238, 237, 236, 96, 199, ]; -pub static NUMCOMPRESSEDBYTES: [i16; 16] = [ - 13, 14, 16, 18, 19, 21, 26, 31, 6, 6, 6, 6, - 0, 0, 0, 1, -]; pub static STARTPOS: [i16; 16] = [ // 2 cols 0, 2, 0, 3, 0, 2, 0, 3, 1, 3, 2, 4, 1, 4, 1, 4, @@ -290,20 +209,9 @@ pub static QUA_GAIN_CODE: [i16; 99] = [ // 3 cols 12510, 2673, 16096, 16263, 3060, 18429, 21142, 3448, 20763, 27485, 3836, 23097, 27485, 3836, 23097, ]; -pub static GRAY: [i16; 8] = [ - 0, 1, 3, 2, 6, 4, 5, 7, -]; pub static DGRAY: [i16; 8] = [ 0, 1, 3, 2, 5, 6, 4, 7, ]; -pub static GRID: [i16; 61] = [ - 32760, 32723, 32588, 32364, 32051, 31651, 31164, 30591, 29935, 29196, 28377, 27481, - 26509, 25465, 24351, 23170, 21926, 20621, 19260, 17846, 16384, 14876, 13327, 11743, - 10125, 8480, 6812, 5126, 3425, 1714, 0, -1714, -3425, -5126, -6812, -8480, - -10125, -11743, -13327, -14876, -16384, -17846, -19260, -20621, -21926, -23170, -24351, -25465, - -26509, -27481, -28377, -29196, -29935, -30591, -31164, -31651, -32051, -32364, -32588, -32723, - -32760, -]; pub static INV_SQRT_TBL: [i16; 49] = [ 32767, 31790, 30894, 30070, 29309, 28602, 27945, 27330, 26755, 26214, 25705, 25225, 24770, 24339, 23930, 23541, 23170, 22817, 22479, 22155, 21845, 21548, 21263, 20988, @@ -332,9 +240,6 @@ pub static SLOPE: [i16; 64] = [ -946, -998, -1059, -1132, -1219, -1322, -1450, -1608, -1811, -2081, -2444, -2979, -3813, -5323, -8812, -26887, ]; -pub static LSP_INIT_DATA: [i16; 10] = [ - 30000, 26000, 21000, 15000, 8000, 0, -8000, -15000, -21000, -26000, -]; pub static PH_IMP_LOW_MR795: [i16; 40] = [ 26777, 801, 2505, -683, -1382, 582, 604, -1274, 3511, -5894, 4534, -499, -1940, 3011, -5058, 5614, -1990, -1061, -1459, 4442, -700, -5335, 4609, 452, @@ -1335,22 +1240,10 @@ pub static SQRT_L_TBL: [i16; 50] = [ 29537, 29819, 30099, 30377, 30652, 30924, 31194, 31462, 31727, 31991, 32252, 32511, 32767, 32767, ]; -pub static INTER_6_PRED_LT: [i16; 61] = [ - 29443, 28346, 25207, 20449, 14701, 8693, 3143, -1352, -4402, -5865, -5850, -4673, - -2783, -672, 1211, 2536, 3130, 2991, 2259, 1170, 0, -1001, -1652, -1868, - -1666, -1147, -464, 218, 756, 1060, 1099, 904, 550, 135, -245, -514, - -634, -602, -451, -231, 0, 191, 308, 340, 296, 198, 78, -36, - -120, -163, -165, -132, -79, -19, 34, 73, 91, 89, 70, 38, - 0, -]; pub static WMFDECBYTESPERFRAME: [i16; 16] = [ 12, 13, 15, 17, 19, 20, 26, 31, 5, 6, 5, 5, 0, 0, 0, 0, ]; -pub static IF2DECBYTESPERFRAME: [i16; 16] = [ - 13, 14, 16, 18, 19, 21, 26, 31, 6, 6, 6, 6, - 0, 0, 0, 1, -]; pub static TABLE_GAIN_MR475: [i16; 1024] = [ // 4 cols 812, 128, 542, 140, 2873, 1135, 2266, 3402, 2067, 563, 12677, 647, 4132, 1798, 5601, 5285, 7689, 374, 3735, 441, 10912, 2638, 11807, 2494, diff --git a/crates/ec-amr/src/wb/bits.rs b/crates/ec-amr/src/wb/bits.rs index 5a98a8ea..ec0d6e9f 100644 --- a/crates/ec-amr/src/wb/bits.rs +++ b/crates/ec-amr/src/wb/bits.rs @@ -1,19 +1,9 @@ //! Bit reading (get_amr_wb_bits.cpp), MIME unsorting (mime_io.cpp) and decoder homing frame test (homing_amr_wb_dec.cpp). -#![allow(dead_code)] use super::ops::*; -pub const BIT_0: i16 = -127; pub const BIT_1: i16 = 127; -pub const MODE_7K: i16 = 0; -pub const MODE_9K: i16 = 1; -pub const MODE_12K: i16 = 2; -pub const MODE_14K: i16 = 3; -pub const MODE_16K: i16 = 4; -pub const MODE_18K: i16 = 5; -pub const MODE_20K: i16 = 6; -pub const MODE_23K: i16 = 7; pub const MODE_24K: i16 = 8; pub const MRDTX: i16 = 9; pub const MRSID: i16 = 9; @@ -66,14 +56,9 @@ pub fn Serial_parm_1bit(prms: &mut Prms) -> i16 { // ---------------- mime_io.cpp ---------------- -pub static toc_byte: [u8; 16] = [ - 0x04, 0x0C, 0x14, 0x1C, 0x24, 0x2C, 0x34, 0x3C, 0x44, 0x4C, 0x54, 0x5C, 0x64, 0x6C, 0x74, 0x7C, -]; pub static unpacked_size: [i16; 16] = [ 132, 177, 253, 285, 317, 365, 397, 461, 477, 35, 0, 0, 0, 0, 0, 0, ]; -pub static packed_size: [i16; 16] = [17, 23, 32, 36, 40, 46, 50, 58, 60, 5, 0, 0, 0, 0, 0, 0]; -pub static unused_size: [i16; 16] = [4, 7, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0]; pub static sort_660: [i16; 132] = [ 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] = [ /// RX_State of mime_io. #[derive(Clone, Copy, Default)] pub struct RxState { - pub prev_ft: i16, pub prev_mode: i16, } @@ -268,6 +252,7 @@ fn sorting_table(mode: i16) -> Option<&'static [i16]> { } /// Port of `mime_unsorting`. `mode` must be 0..=15. +#[allow(unused_assignments)] pub fn mime_unsorting( unsorted_bits: &[u8], sorted_bits_into_int16: &mut [i16], @@ -400,6 +385,7 @@ fn dhf_table(mode: i32) -> &'static [i16] { } /// Port of `dhf_test`. +#[allow(unused_assignments)] pub fn dhf_test(input_frame: &[i16], mode: i32, nparms: i16) -> i16 { let dhf = dhf_table(mode); let mut param = [0i16; DHF_PARMS_MAX + 1]; @@ -453,8 +439,8 @@ pub fn dhf_test(input_frame: &[i16], mode: i32, nparms: i16) -> i16 { let mut tmp: i16 = 0x7fff; tmp >>= shift; tmp = shl_int16(tmp, shift); - tmp = dhf[i] & tmp; - tmp = param[i] ^ tmp; + tmp &= dhf[i]; + tmp ^= param[i]; j |= tmp; } else { j = 1; diff --git a/crates/ec-amr/src/wb/core.rs b/crates/ec-amr/src/wb/core.rs index ef79f80e..24b6e5a8 100644 --- a/crates/ec-amr/src/wb/core.rs +++ b/crates/ec-amr/src/wb/core.rs @@ -115,6 +115,7 @@ impl DecoderState { /// `pvDecoder_AmrWb`: decode one frame of parameters (`prms`, one bit per i16 in /// the decoder's serial order) into 320 samples. +#[allow(unused_assignments)] pub fn decode_frame( mode: i16, prms_buf: &[i16], diff --git a/crates/ec-amr/src/wb/dtx.rs b/crates/ec-amr/src/wb/dtx.rs index 472ebaba..f0062117 100644 --- a/crates/ec-amr/src/wb/dtx.rs +++ b/crates/ec-amr/src/wb/dtx.rs @@ -1,31 +1,22 @@ //! AMR-WB decoder DTX / comfort noise (port of dtx_decoder_amr_wb.cpp and dtx.h). -#![allow(dead_code)] use super::bits::{Prms, Serial_parm, Serial_parm_1bit}; use super::ops::*; pub const DTX_MAX_EMPTY_THRESH: i16 = 50; pub const DTX_HIST_SIZE: usize = 8; -pub const DTX_HIST_SIZE_MIN_ONE: usize = 7; pub const DTX_ELAPSED_FRAMES_THRESH: i16 = 24 + 7 - 1; pub const DTX_HANG_CONST: i16 = 7; -pub const INV_MED_THRESH: i16 = 14564; pub const ISF_GAP: i16 = 128; pub const ISF_DITH_GAP: i16 = 448; pub const ISF_FACTOR_LOW: i16 = 256; pub const ISF_FACTOR_STEP: i16 = 2; -pub const GAIN_THR: i16 = 180; pub const GAIN_FACTOR: i16 = 75; pub const SPEECH: i16 = 0; pub const DTX: i16 = 1; pub const DTX_MUTE: i16 = 2; -pub const TX_SPEECH: i16 = 0; -pub const TX_SID_FIRST: i16 = 1; -pub const TX_SID_UPDATE: i16 = 2; -pub const TX_NO_DATA: i16 = 3; - pub const RX_SPEECH_GOOD: i16 = 0; pub const RX_SPEECH_PROBABLY_DEGRADED: i16 = 1; pub const RX_SPEECH_LOST: i16 = 2; @@ -35,26 +26,12 @@ pub const RX_SID_UPDATE: i16 = 5; pub const RX_SID_BAD: i16 = 6; pub const RX_NO_DATA: i16 = 7; -#[derive(Clone)] -pub struct DtxEncState { - pub isf_hist: [i16; M * DTX_HIST_SIZE], - pub log_en_hist: [i16; DTX_HIST_SIZE], - pub hist_ptr: i16, - pub log_en_index: i16, - pub cng_seed: i16, - pub dtxHangoverCount: i16, - pub decAnaElapsedCount: i16, - pub D: [i32; 28], - pub sumD: [i32; DTX_HIST_SIZE], -} - #[derive(Clone)] pub struct DtxDecState { pub since_last_sid: i16, pub true_sid_period_inv: i16, pub log_en: i16, pub old_log_en: i16, - pub level: i16, pub isf: [i16; M], pub isf_old: [i16; M], pub cng_seed: i16, @@ -79,7 +56,6 @@ impl Default for DtxDecState { true_sid_period_inv: 0, log_en: 0, old_log_en: 0, - level: 0, isf: [0; M], isf_old: [0; M], cng_seed: 0, @@ -192,7 +168,7 @@ pub fn dtx_dec_amr_wb( ind[2] = Serial_parm(6, prms); ind[3] = Serial_parm(5, prms); ind[4] = Serial_parm(5, prms); - super::isf::disf_ns(&mut ind, &mut st.isf); + super::isf::disf_ns(&ind, &mut st.isf); let log_en_index = Serial_parm(6, prms); st.CN_dith = Serial_parm_1bit(prms); 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: &[ /// Port of `rx_amr_wb_dtx_handler`. pub fn rx_amr_wb_dtx_handler(st: &mut DtxDecState, frame_type: i16) -> i16 { let mut new_state: i16; - let enc_state: i16; + if frame_type == RX_SID_FIRST || frame_type == RX_SID_UPDATE @@ -339,15 +315,15 @@ pub fn rx_amr_wb_dtx_handler(st: &mut DtxDecState, frame_type: i16) -> i16 { st.decAnaElapsedCount = add_int16(st.decAnaElapsedCount, 1); st.dtxHangoverAdded = 0; - if frame_type == RX_SID_FIRST + let enc_state: i16 = if frame_type == RX_SID_FIRST || frame_type == RX_SID_UPDATE || frame_type == RX_SID_BAD || frame_type == RX_NO_DATA { - enc_state = DTX; + DTX } else { - enc_state = SPEECH; - } + SPEECH + }; if enc_state == SPEECH { st.dtxHangoverCount = DTX_HANG_CONST; @@ -377,149 +353,6 @@ pub fn rx_amr_wb_dtx_handler(st: &mut DtxDecState, frame_type: i16) -> i16 { new_state } -/// Port of `aver_isf_history`. -pub fn aver_isf_history(isf_old: &mut [i16], indices: &[i16], isf_aver: &mut [i32]) { - let mut isf_tmp = [0i16; 2 * M]; - for k in 0..2 { - if indices[k] as i32 + 1 != 0 { - let ik = indices[k] as usize * M; - let i2 = indices[2] as usize * M; - for i in 0..M { - isf_tmp[k * M + i] = isf_old[ik + i]; - isf_old[ik + i] = isf_old[i2 + i]; - } - } - } - for j in 0..M { - let mut l_tmp: i32 = 0; - for i in 0..DTX_HIST_SIZE { - l_tmp = add_int32(l_tmp, isf_old[i * M + j] as i32); - } - isf_aver[j] = l_tmp; - } - for k in 0..2 { - if indices[k] as i32 + 1 != 0 { - let ik = indices[k] as usize * M; - for i in 0..M { - isf_old[ik + i] = isf_tmp[k * M + i]; - } - } - } -} - -/// Port of `find_frame_indices`. -pub fn find_frame_indices(isf_old_tx: &[i16], indices: &mut [i16], st: &mut DtxEncState) { - let mut tmp: i32 = DTX_HIST_SIZE_MIN_ONE as i32; - let mut j: i32 = -1; - for i in 0..DTX_HIST_SIZE_MIN_ONE { - j += tmp; - st.sumD[i] = sub_int32(st.sumD[i], st.D[j as usize]); - tmp -= 1; - } - for i in (1..=DTX_HIST_SIZE_MIN_ONE).rev() { - st.sumD[i] = st.sumD[i - 1]; - } - st.sumD[0] = 0; - - tmp = 0; - let mut i: i32 = 27; - while i >= 12 { - tmp += 1; - let mut jj = tmp; - while jj > 0 { - st.D[(i - jj + 1) as usize] = st.D[(i - jj - tmp) as usize]; - jj -= 1; - } - i -= tmp; - } - - let mut ptr = st.hist_ptr as i32; - let hp = st.hist_ptr as usize; - for i in 1..DTX_HIST_SIZE { - ptr -= 1; - if ptr < 0 { - ptr = DTX_HIST_SIZE_MIN_ONE as i32; - } - let mut l_tmp: i32 = 0; - for j in 0..M { - let t = sub_int16(isf_old_tx[hp * M + j], isf_old_tx[ptr as usize * M + j]); - l_tmp = mac_16by16_to_int32(l_tmp, t, t); - } - st.D[i - 1] = l_tmp; - st.sumD[0] = add_int32(st.sumD[0], st.D[i - 1]); - st.sumD[i] = add_int32(st.sumD[i], st.D[i - 1]); - } - - let mut summax = st.sumD[0]; - let mut summin = st.sumD[0]; - indices[0] = 0; - indices[2] = 0; - for i in 1..DTX_HIST_SIZE { - if st.sumD[i] > summax { - indices[0] = i as i16; - summax = st.sumD[i]; - } - if st.sumD[i] < summin { - indices[2] = i as i16; - summin = st.sumD[i]; - } - } - - let mut summax2nd: i32 = -2147483647; - indices[1] = -1; - for i in 0..DTX_HIST_SIZE { - if st.sumD[i] > summax2nd && i as i16 != indices[0] { - indices[1] = i as i16; - summax2nd = st.sumD[i]; - } - } - - for i in 0..3 { - indices[i] = sub_int16(st.hist_ptr, indices[i]); - if indices[i] < 0 { - indices[i] = add_int16(indices[i], DTX_HIST_SIZE as i16); - } - } - - let t = normalize_amr_wb(summax); - summax = summax.wrapping_shl(t as u32); - summin = summin.wrapping_shl(t as u32); - let mut l_tmp = mul_16by16_to_int32(amr_wb_round(summax), INV_MED_THRESH); - if l_tmp <= summin { - indices[0] = -1; - } - summax2nd = shl_int32(summax2nd, t); - l_tmp = mul_16by16_to_int32(amr_wb_round(summax2nd), INV_MED_THRESH); - if l_tmp <= summin { - indices[1] = -1; - } -} - -/// Port of `dithering_control`. -pub fn dithering_control(st: &DtxEncState) -> i16 { - let mut isf_diff: i32 = 0; - for i in 0..8 { - isf_diff = add_int32(isf_diff, st.sumD[i]); - } - let mut cn_dith: i16 = if (isf_diff >> 26) > 0 { 1 } else { 0 }; - - let mut mean: i16 = 0; - for i in 0..DTX_HIST_SIZE { - mean = add_int16(mean, st.log_en_hist[i]); - } - mean >>= 3; - let mut gain_diff: i16 = 0; - for i in 0..DTX_HIST_SIZE { - let mut tmp = sub_int16(st.log_en_hist[i], mean); - tmp = tmp.wrapping_sub((tmp < 0) as i16); - gain_diff = gain_diff.wrapping_add(tmp ^ (tmp >> 15)); - } - if gain_diff > GAIN_THR { - cn_dith = 1; - } - cn_dith -} - /// Port of `CN_dithering`. pub fn CN_dithering(isf: &mut [i16], l_log_en_int: &mut i32, dither_seed: &mut i16) { use super::exc::noise_gen_amrwb; diff --git a/crates/ec-amr/src/wb/exc.rs b/crates/ec-amr/src/wb/exc.rs index 30f26f3a..15342723 100644 --- a/crates/ec-amr/src/wb/exc.rs +++ b/crates/ec-amr/src/wb/exc.rs @@ -478,9 +478,9 @@ pub fn agc2_amr_wb(sig_in: &[i16], sig_out: &mut [i16], l_trm: i16) { temp = sig_in[i] >> 2; s = mac_16by16_to_int32(s, temp, temp); } - let g0: i16; - if s == 0 { - g0 = 0; + + let g0: i16 = if s == 0 { + 0 } else { let i = normalize_amr_wb(s); 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) { s2 = shl_int32(s2, 7); s2 = shr_int32(s2, exp); s2 = super::math::one_ov_sqrt(s2); - g0 = amr_wb_round(shl_int32(s2, 9)); - } + amr_wb_round(shl_int32(s2, 9)) + }; for i in 0..l { sig_out[i] = super::math::extract_h(shl_int32(fxp_mul_16by16(sig_out[i], g0), 3)); } @@ -513,7 +513,6 @@ pub fn scale_signal(x: &mut [i16], lg: i16, exp: i16) { } /// Ports `median5`. `x[c]` is the C `x[0]` (reads `x[c-2..=c+2]`). -#[allow(unused_assignments)] pub fn median5(x: &[i16], c: usize) -> i16 { let mut x1 = x[c - 2]; let mut x2 = x[c - 1]; @@ -706,6 +705,7 @@ pub fn dec_gain2_amr_wb_init(mem: &mut [i16]) { } /// Ports `dec_gain2_amr_wb`. `mem` has 23 words (see init). +#[allow(unused_assignments)] pub fn dec_gain2_amr_wb( index: i16, nbits: i16, diff --git a/crates/ec-amr/src/wb/math.rs b/crates/ec-amr/src/wb/math.rs index ff417e4c..ab5d19b5 100644 --- a/crates/ec-amr/src/wb/math.rs +++ b/crates/ec-amr/src/wb/math.rs @@ -6,17 +6,9 @@ pub fn extract_h(x: i32) -> i16 { (x >> 16) as i16 } #[inline] -pub fn extract_l(x: i32) -> i16 { - x as i16 -} -#[inline] pub fn l_deposit_h(x: i16) -> i32 { (x as i32).wrapping_shl(16) } -#[inline] -pub fn l_deposit_l(x: i16) -> i32 { - x as i32 -} /// Ports `mult_int16_r`. pub fn mult_int16_r(var1: i16, var2: i16) -> i16 { diff --git a/crates/ec-amr/src/wb/mod.rs b/crates/ec-amr/src/wb/mod.rs index e62d0051..b395a035 100644 --- a/crates/ec-amr/src/wb/mod.rs +++ b/crates/ec-amr/src/wb/mod.rs @@ -1,23 +1,17 @@ //! AMR-WB (3GPP TS 26.173) fixed-point decoder. -#![allow( - clippy::all, - clippy::pedantic, - dead_code, - unused_assignments, - non_snake_case, - non_upper_case_globals -)] - -pub mod bits; -pub mod core; -pub mod dtx; -pub mod exc; -pub mod exc_tab; -pub mod isf; -pub mod isf_tab; -pub mod math; -pub mod ops; -pub mod synth; +#![allow(non_snake_case, non_upper_case_globals, clippy::if_same_then_else)] +#![allow(clippy::needless_range_loop, clippy::too_many_arguments, clippy::manual_memcpy, clippy::manual_clamp)] + +pub(crate) mod bits; +pub(crate) mod core; +pub(crate) mod dtx; +pub(crate) mod exc; +pub(crate) mod exc_tab; +pub(crate) mod isf; +pub(crate) mod isf_tab; +pub(crate) mod math; +pub(crate) mod ops; +pub(crate) mod synth; use ec_core::error::{Error, Result}; use ec_core::frame::{AudioFrame, ChannelLayout, Frame, SampleFormat}; @@ -34,16 +28,6 @@ use self::dtx::{RX_NO_DATA, RX_SPEECH_GOOD, RX_SPEECH_LOST}; /// Samples in one decoded AMR-WB frame (20 ms at 16 kHz). pub const FRAME_SAMPLES: usize = 320; -/// Payload bytes (after the ToC byte) of an AMR-WB frame type, `None` for reserved types. -fn payload_len(ft: u8) -> Option { - const SIZES: [usize; 10] = [17, 23, 32, 36, 40, 46, 50, 58, 60, 5]; - match ft { - 0..=9 => Some(SIZES[usize::from(ft)]), - 14 | 15 => Some(0), - _ => None, - } -} - /// A fixed-point AMR-WB decoder (3GPP TS 26.173), bit-exact with the reference decoder's /// 14-bit output. Packets are one or more frames, each a ToC byte followed by the speech bits /// (the `sawb` sample layout and the `.awb` frame layout). @@ -78,7 +62,6 @@ impl AmrWbDecoder { AmrWbDecoder { st: DecoderState::new(), rx: RxState { - prev_ft: RX_SPEECH_GOOD, prev_mode: 0, }, mode_old: 0, @@ -101,7 +84,6 @@ impl AmrWbDecoder { fn reset_state(&mut self) { self.st = DecoderState::new(); self.rx = RxState { - prev_ft: RX_SPEECH_GOOD, prev_mode: 0, }; self.mode_old = 0; @@ -117,8 +99,7 @@ impl AmrWbDecoder { while at < data.len() { let toc = data[at]; let ft = (toc >> 3) & 0x0F; - let n = payload_len(ft) - .ok_or_else(|| Error::corrupt(format!("AMR-WB frame type {ft} is reserved")))?; + let n = crate::container::wb_frame_size(ft)?; if at + 1 + n > data.len() { return Err(Error::corrupt("AMR-WB frame is truncated")); } diff --git a/crates/ec-amr/src/wb/ops.rs b/crates/ec-amr/src/wb/ops.rs index dc8b34a5..334584d5 100644 --- a/crates/ec-amr/src/wb/ops.rs +++ b/crates/ec-amr/src/wb/ops.rs @@ -1,10 +1,8 @@ //! ETSI-style saturating basic operators (port of the 3GPP TS 26.173 basic_op set). -#![allow(dead_code)] pub const MAX_16: i16 = 32767; pub const MIN_16: i16 = -32768; pub const MAX_32: i32 = 0x7fff_ffff; -pub const MIN_32: i32 = i32::MIN; #[inline] pub fn sat16(x: i32) -> i16 { @@ -71,7 +69,7 @@ pub fn amr_wb_shl1_round(l: i32) -> i16 { } #[inline] pub fn mul_32by16(hi: i16, lo: i16, n: i16) -> i32 { - (((hi as i32 * n as i32) + ((lo as i32 * n as i32) >> 15)) as i32).wrapping_shl(1) + ((hi as i32 * n as i32) + ((lo as i32 * n as i32) >> 15)).wrapping_shl(1) } /// plain (non saturating) 16x16 -> 32 multiply-accumulate #[inline] @@ -97,7 +95,7 @@ pub fn shl_int16(v: i16, s: i16) -> i16 { let s = (s & 0xf) as u32; let out = ((v as i32) << s) as i16; if ((out as i32) >> s) != v as i32 { - ((v >> 15) ^ MAX_16) as i16 + (v >> 15) ^ MAX_16 } else { out } @@ -158,10 +156,6 @@ pub fn normalize_amr_wb(x: i32) -> i16 { i as i16 } #[inline] -pub fn norm_l(x: i32) -> i16 { - normalize_amr_wb(x) -} -#[inline] pub fn norm_s(x: i16) -> i16 { normalize_amr_wb(x as i32) - 16 } @@ -175,7 +169,6 @@ pub const M: usize = 16; pub const M16K: usize = 20; pub const L_FILT16K: usize = 15; pub const L_FILT: usize = 12; -pub const GP_CLIP: i16 = 15565; pub const PIT_SHARP: i16 = 27853; pub const PIT_MIN: i16 = 34; pub const PIT_FR2: i16 = 128; @@ -184,14 +177,10 @@ pub const PIT_FR1_8B: i16 = 92; pub const PIT_MAX: i16 = 231; pub const L_INTERPOL: usize = 17; pub const PREEMPH_FAC: i16 = 22282; -pub const GAMMA1: i16 = 30147; -pub const TILT_FAC: i16 = 22282; pub const Q_MAX: i16 = 8; pub const RANDOM_INITSEED: i16 = 21845; pub const L_MEANBUF: usize = 3; -pub const ONE_PER_MEANBUF: i16 = 10923; pub const EHF_MASK: i16 = 0x0008; -pub const AMR_WB_PCM_FRAME: usize = 320; pub const NBBITS_7K: i16 = 132; pub const NBBITS_9K: i16 = 177; pub const NBBITS_12K: i16 = 253; @@ -199,7 +188,5 @@ pub const NBBITS_14K: i16 = 285; pub const NBBITS_16K: i16 = 317; pub const NBBITS_18K: i16 = 365; pub const NBBITS_20K: i16 = 397; -pub const NBBITS_23K: i16 = 461; pub const NBBITS_24K: i16 = 477; -pub const NBBITS_SID: i16 = 35; pub const AMR_WB_COMPRESSED: [i16; 10] = [132, 177, 253, 285, 317, 365, 397, 461, 477, 35]; diff --git a/crates/ec-amr/src/wb/synth.rs b/crates/ec-amr/src/wb/synth.rs index 6a3f1d90..0b4322e3 100644 --- a/crates/ec-amr/src/wb/synth.rs +++ b/crates/ec-amr/src/wb/synth.rs @@ -1,13 +1,11 @@ //! AMR-WB synthesis stage: ports of wb_syn_filt.cpp, synthesis_amr_wb.cpp, //! oversamp_12k8_to_16k.cpp, highpass_50hz_at_12k8.cpp, highpass_400hz_at_12k8.cpp, //! band_pass_6k_7k.cpp, low_pass_filt_7k.cpp, deemphasis_32.cpp, isf_extrapolation.cpp. -#![allow(dead_code)] use super::ops::*; const L_FIR_BP: usize = 30; const L_FIR_LP: usize = 30; -const L_FILT16K_: usize = 15; const SPEECH: i16 = 0; pub static HP_GAIN: [i16; 16] = [ diff --git a/crates/ec-amr/tests/oracle.rs b/crates/ec-amr/tests/oracle.rs index 070cf2bb..823b45f6 100644 --- a/crates/ec-amr/tests/oracle.rs +++ b/crates/ec-amr/tests/oracle.rs @@ -1,227 +1,540 @@ -//! AMR-NB oracle: synthetic sources are encoded with ffmpeg's libopencore_amrnb (every mode, -//! DTX on/off), then decoded by this crate and by ffmpeg. Against libopencore_amrnb (the -//! reference this port follows) the output must be bit-exact; against ffmpeg's native `amrnb` -//! decoder the SNR is reported and must stay high. +//! AMR-NB and AMR-WB against ffmpeg's libopencore decoders. //! +//! NB: synthetic sources encoded with libopencore_amrnb (every mode, DTX on/off), decoded here and by +//! ffmpeg; bit-exact against libopencore_amrnb. WB: libopencore_amrwb / AWB and MP4 round trips, +//! bit-exact against the reference decoder. -use std::path::{Path, PathBuf}; - -use ec_amr::nb::bitstream::frame_bytes; -use ec_amr::nb::decoder::AmrNbDecoder; - -const MODES: [(u32, &str); 8] = [ - (4750, "mr475"), - (5150, "mr515"), - (5900, "mr59"), - (6700, "mr67"), - (7400, "mr74"), - (7950, "mr795"), - (10200, "mr102"), - (12200, "mr122"), -]; - -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))"; - -fn sources() -> Vec<(&'static str, String)> { - vec![ - ("sweep", "aevalsrc=0.5*sin(2*PI*(200+400*t)*t):s=8000:d=5".into()), - ("noise", "anoisesrc=d=5:c=pink:r=8000:a=0.3".into()), - ("speech", format!("aevalsrc={SPEECH}:s=8000:d=5")), - ( - "gaps", - format!( - "aevalsrc=if(between(mod(t\\,4)\\,1\\,2.5)\\,{SPEECH}\\,0.001*(random(0)-0.5)):s=8000:d=12" +mod nb { + use std::path::{Path, PathBuf}; + + use ec_amr::nb::bitstream::frame_bytes; + use ec_amr::nb::decoder::AmrNbDecoder; + + const MODES: [(u32, &str); 8] = [ + (4750, "mr475"), + (5150, "mr515"), + (5900, "mr59"), + (6700, "mr67"), + (7400, "mr74"), + (7950, "mr795"), + (10200, "mr102"), + (12200, "mr122"), + ]; + + 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))"; + + fn sources() -> Vec<(&'static str, String)> { + vec![ + ( + "sweep", + "aevalsrc=0.5*sin(2*PI*(200+400*t)*t):s=8000:d=5".into(), ), - ), - ] -} + ("noise", "anoisesrc=d=5:c=pink:r=8000:a=0.3".into()), + ("speech", format!("aevalsrc={SPEECH}:s=8000:d=5")), + ( + "gaps", + format!( + "aevalsrc=if(between(mod(t\\,4)\\,1\\,2.5)\\,{SPEECH}\\,0.001*(random(0)-0.5)):s=8000:d=12" + ), + ), + ] + } -fn workdir() -> PathBuf { - let d = std::env::temp_dir().join(format!("ec-amr-oracle-{}", std::process::id())); - std::fs::create_dir_all(&d).unwrap(); - d -} + fn workdir() -> PathBuf { + let d = std::env::temp_dir().join(format!("ec-amr-oracle-{}", std::process::id())); + std::fs::create_dir_all(&d).unwrap(); + d + } -fn ffmpeg_ok() -> bool { - ec_testkit::ffmpeg() - .args(["-hide_banner", "-h", "decoder=libopencore_amrnb"]) - .output() - .map(|o| String::from_utf8_lossy(&o.stdout).contains("libopencore_amrnb")) - .unwrap_or(false) -} + fn ffmpeg_ok() -> bool { + ec_testkit::ffmpeg() + .args(["-hide_banner", "-h", "decoder=libopencore_amrnb"]) + .output() + .map(|o| String::from_utf8_lossy(&o.stdout).contains("libopencore_amrnb")) + .unwrap_or(false) + } -fn run(args: &[&str]) -> Option> { - let out = ec_testkit::ffmpeg().args(["-nostdin", "-v", "error", "-y"]).args(args).output().ok()?; - out.status.success().then_some(out.stdout) -} + fn run(args: &[&str]) -> Option> { + let out = ec_testkit::ffmpeg() + .args(["-nostdin", "-v", "error", "-y"]) + .args(args) + .output() + .ok()?; + out.status.success().then_some(out.stdout) + } -/// Encode `src` (lavfi) to a .amr file with libopencore_amrnb. -fn encode(dir: &Path, name: &str, src: &str, bitrate: u32, dtx: bool) -> Option { - let path = dir.join(format!("{name}-{bitrate}-{}.amr", dtx as u8)); - let br = bitrate.to_string(); - let p = path.to_str().unwrap(); - run(&[ - "-f", "lavfi", "-i", src, "-ar", "8000", "-ac", "1", "-c:a", "libopencore_amrnb", "-b:a", &br, "-dtx", - if dtx { "1" } else { "0" }, "-f", "amr", p, - ])?; - Some(path) -} + /// Encode `src` (lavfi) to a .amr file with libopencore_amrnb. + fn encode(dir: &Path, name: &str, src: &str, bitrate: u32, dtx: bool) -> Option { + let path = dir.join(format!("{name}-{bitrate}-{}.amr", dtx as u8)); + let br = bitrate.to_string(); + let p = path.to_str().unwrap(); + run(&[ + "-f", + "lavfi", + "-i", + src, + "-ar", + "8000", + "-ac", + "1", + "-c:a", + "libopencore_amrnb", + "-b:a", + &br, + "-dtx", + if dtx { "1" } else { "0" }, + "-f", + "amr", + p, + ])?; + Some(path) + } -fn ffmpeg_decode(path: &Path, codec: &str) -> Vec { - let out = run(&["-c:a", codec, "-i", path.to_str().unwrap(), "-f", "s16le", "-"]) + fn ffmpeg_decode(path: &Path, codec: &str) -> Vec { + let out = run(&[ + "-c:a", + codec, + "-i", + path.to_str().unwrap(), + "-f", + "s16le", + "-", + ]) .unwrap_or_else(|| panic!("ffmpeg -c:a {codec} failed on {}", path.display())); - out.as_chunks::<2>().0.iter().map(|b| i16::from_le_bytes(*b)).collect() -} + out.as_chunks::<2>() + .0 + .iter() + .map(|b| i16::from_le_bytes(*b)) + .collect() + } -/// Split a `.amr` file into frames (ToC byte + payload). -fn parse_amr(data: &[u8]) -> Vec> { - let mut pos = if data.starts_with(b"#!AMR\n") { 6 } else { 0 }; - let mut frames = Vec::new(); - while pos < data.len() { - let ft = (data[pos] >> 3) & 15; - let Some(n) = frame_bytes(ft) else { break }; - if pos + 1 + n > data.len() { - break; + /// Split a `.amr` file into frames (ToC byte + payload). + fn parse_amr(data: &[u8]) -> Vec> { + let mut pos = if data.starts_with(b"#!AMR\n") { 6 } else { 0 }; + let mut frames = Vec::new(); + while pos < data.len() { + let ft = (data[pos] >> 3) & 15; + let Some(n) = frame_bytes(ft) else { break }; + if pos + 1 + n > data.len() { + break; + } + frames.push(data[pos..pos + 1 + n].to_vec()); + pos += 1 + n; } - frames.push(data[pos..pos + 1 + n].to_vec()); - pos += 1 + n; + frames } - frames -} -fn write_amr(path: &Path, frames: &[Vec]) { - let mut d = b"#!AMR\n".to_vec(); - for f in frames { - d.extend_from_slice(f); + fn write_amr(path: &Path, frames: &[Vec]) { + let mut d = b"#!AMR\n".to_vec(); + for f in frames { + d.extend_from_slice(f); + } + std::fs::write(path, d).unwrap(); } - std::fs::write(path, d).unwrap(); -} -fn decode_all(frames: &[Vec]) -> Vec { - let mut dec = AmrNbDecoder::new(); - let mut out = Vec::new(); - for f in frames { - out.extend_from_slice(&dec.decode(f).expect("decode")); + fn decode_all(frames: &[Vec]) -> Vec { + let mut dec = AmrNbDecoder::new(); + let mut out = Vec::new(); + for f in frames { + out.extend_from_slice(&dec.decode(f).expect("decode")); + } + out } - out -} -fn snr_db(reference: &[i16], test: &[i16]) -> f64 { - let n = reference.len().min(test.len()); - let (mut sig, mut err) = (0f64, 0f64); - for i in 0..n { - let r = reference[i] as f64; - sig += r * r; - let d = r - test[i] as f64; - err += d * d; + fn snr_db(reference: &[i16], test: &[i16]) -> f64 { + let n = reference.len().min(test.len()); + let (mut sig, mut err) = (0f64, 0f64); + for i in 0..n { + let r = reference[i] as f64; + sig += r * r; + let d = r - test[i] as f64; + err += d * d; + } + if err == 0.0 { + return 200.0; + } + 10.0 * (sig.max(1.0) / err).log10() } - if err == 0.0 { - return 200.0; + + fn first_diff(a: &[i16], b: &[i16]) -> Option { + (0..a.len().min(b.len())) + .find(|&i| a[i] != b[i]) + .or((a.len() != b.len()).then_some(a.len().min(b.len()))) } - 10.0 * (sig.max(1.0) / err).log10() -} -fn first_diff(a: &[i16], b: &[i16]) -> Option { - (0..a.len().min(b.len())).find(|&i| a[i] != b[i]).or((a.len() != b.len()).then_some(a.len().min(b.len()))) -} + fn setup() -> PathBuf { + assert!(ffmpeg_ok(), "ffmpeg with libopencore_amrnb is required"); + workdir() + } -fn setup() -> PathBuf { - assert!(ffmpeg_ok(), "ffmpeg with libopencore_amrnb is required"); - workdir() -} + #[test] + fn all_modes_bit_exact_vs_libopencore() { + let dir = setup(); + let mut checked = 0; + for dtx in [false, true] { + for (rate, label) in MODES { + for (sname, src) in sources() { + if dtx && sname != "gaps" && sname != "speech" { + continue; + } + let path = encode(&dir, sname, &src, rate, dtx).expect("encode"); + let frames = parse_amr(&std::fs::read(&path).unwrap()); + assert!(frames.len() > 100); + let sids = frames.iter().filter(|f| (f[0] >> 3) & 15 == 8).count(); + let nodata = frames.iter().filter(|f| (f[0] >> 3) & 15 == 15).count(); + let want = ffmpeg_decode(&path, "libopencore_amrnb"); + let got = decode_all(&frames); + assert_eq!( + first_diff(&got, &want), + None, + "{label} {sname} dtx={dtx}: differs from libopencore_amrnb ({} vs {} samples)", + got.len(), + want.len() + ); + let native = ffmpeg_decode(&path, "amrnb"); + let snr = snr_db(&native, &got); + eprintln!( + "{label:6} {sname:7} dtx={} frames={} sid={sids} nodata={nodata}: bit-exact, SNR vs native amrnb = {snr:.1} dB", + dtx as u8, + frames.len() + ); + if sids == 0 { + assert!(snr > 15.0, "{label} {sname}: SNR vs native {snr:.1} dB"); + } + checked += 1; + } + } + } + assert!(checked >= 8 * 6); + } + + /// Deterministic xorshift for corruption patterns. + fn rng(state: &mut u64) -> u64 { + *state ^= *state << 13; + *state ^= *state >> 7; + *state ^= *state << 17; + *state + } -#[test] -fn all_modes_bit_exact_vs_libopencore() { - let dir = setup(); - let mut checked = 0; - for dtx in [false, true] { + #[test] + fn lost_and_bit_flipped_frames_vs_libopencore() { + let dir = setup(); + let mut seed = 0x1234_5678_9abc_def1u64; for (rate, label) in MODES { - for (sname, src) in sources() { - if dtx && sname != "gaps" && sname != "speech" { - continue; + let (sname, src) = &sources()[2]; + let path = encode(&dir, sname, src, rate, false).expect("encode"); + let mut frames = parse_amr(&std::fs::read(&path).unwrap()); + for f in frames.iter_mut() { + match rng(&mut seed) % 10 { + 0 => *f = vec![15 << 3 | 4], // NO_DATA + 1 | 2 if f.len() > 2 => { + let i = 1 + (rng(&mut seed) as usize % (f.len() - 1)); + f[i] ^= 1 << (rng(&mut seed) % 8); + } + _ => {} } - let path = encode(&dir, sname, &src, rate, dtx).expect("encode"); - let frames = parse_amr(&std::fs::read(&path).unwrap()); - assert!(frames.len() > 100); - let sids = frames.iter().filter(|f| (f[0] >> 3) & 15 == 8).count(); - let nodata = frames.iter().filter(|f| (f[0] >> 3) & 15 == 15).count(); - let want = ffmpeg_decode(&path, "libopencore_amrnb"); - let got = decode_all(&frames); - assert_eq!( - first_diff(&got, &want), - None, - "{label} {sname} dtx={dtx}: differs from libopencore_amrnb ({} vs {} samples)", - got.len(), - want.len() - ); - let native = ffmpeg_decode(&path, "amrnb"); - let snr = snr_db(&native, &got); - eprintln!( - "{label:6} {sname:7} dtx={} frames={} sid={sids} nodata={nodata}: bit-exact, SNR vs native amrnb = {snr:.1} dB", - dtx as u8, - frames.len() - ); - if sids == 0 { - assert!(snr > 15.0, "{label} {sname}: SNR vs native {snr:.1} dB"); - } - checked += 1; } + let cpath = dir.join(format!("corrupt-{label}.amr")); + write_amr(&cpath, &frames); + let want = ffmpeg_decode(&cpath, "libopencore_amrnb"); + let got = decode_all(&frames); + assert_eq!( + first_diff(&got, &want), + None, + "{label}: corrupted stream differs from libopencore_amrnb" + ); } } - assert!(checked >= 8 * 6); -} -/// Deterministic xorshift for corruption patterns. -fn rng(state: &mut u64) -> u64 { - *state ^= *state << 13; - *state ^= *state >> 7; - *state ^= *state << 17; - *state + #[test] + fn garbage_never_panics() { + let mut dec = AmrNbDecoder::new(); + let mut seed = 0xdead_beef_cafe_f00du64; + for i in 0..4000usize { + let len = (rng(&mut seed) % 40) as usize; + let mut f: Vec = (0..len).map(|_| rng(&mut seed) as u8).collect(); + if i % 3 == 0 && !f.is_empty() { + f[0] = ((rng(&mut seed) % 16) as u8) << 3 | 4; + } + let pcm = dec.decode(&f).expect("decode never errors"); + assert_eq!(pcm.len(), 160); + } + // empty and truncated well-formed frames + assert!(dec.decode(&[]).is_ok()); + assert!(dec.decode(&[7 << 3 | 4, 1, 2]).is_ok()); + assert!(dec.decode(&[8 << 3 | 4]).is_ok()); + // decoder keeps working afterwards + assert_eq!(dec.decode(&[15 << 3 | 4]).unwrap().len(), 160); + } } -#[test] -fn lost_and_bit_flipped_frames_vs_libopencore() { - let dir = setup(); - let mut seed = 0x1234_5678_9abc_def1u64; - for (rate, label) in MODES { - let (sname, src) = &sources()[2]; - let path = encode(&dir, sname, src, rate, false).expect("encode"); - let mut frames = parse_amr(&std::fs::read(&path).unwrap()); - for f in frames.iter_mut() { - match rng(&mut seed) % 10 { - 0 => *f = vec![15 << 3 | 4], // NO_DATA - 1 | 2 if f.len() > 2 => { - let i = 1 + (rng(&mut seed) as usize % (f.len() - 1)); - f[i] ^= 1 << (rng(&mut seed) % 8); +mod wb { + use std::fs::File; + use std::io::{BufReader, Cursor}; + use std::path::{Path, PathBuf}; + + use ec_amr::container::AmrDemuxer; + use ec_amr::wb::AmrWbDecoder; + use ec_core::registry::{CodecId, Decoder, Demuxer}; + + const RATES: [u32; 9] = [6600, 8850, 12650, 14250, 15850, 18250, 19850, 23050, 23850]; + const PAYLOAD: [usize; 10] = [17, 23, 32, 36, 40, 46, 50, 58, 60, 5]; + + fn ffmpeg(args: &[&str]) -> Option> { + let out = ec_testkit::ffmpeg() + .args(["-nostdin", "-v", "error", "-y"]) + .args(args) + .output() + .ok()?; + out.status.success().then_some(out.stdout) + } + + struct Dir(PathBuf); + impl Dir { + fn new(tag: &str) -> Dir { + let p = std::env::temp_dir().join(format!("ec-amr-wb-{tag}-{}", std::process::id())); + std::fs::create_dir_all(&p).unwrap(); + Dir(p) + } + fn path(&self, name: &str) -> PathBuf { + self.0.join(name) + } + } + impl Drop for Dir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + 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))\ ++0.15*sin(2*PI*1700*t)*sin(2*PI*3*t)+0.04*(random(0)-0.5)':s=16000:d=3"; + + /// Encode the synthetic source at `rate` into `path` (format chosen by `fmt`). + fn encode(path: &Path, rate: u32, fmt: &str) -> bool { + ffmpeg(&[ + "-f", + "lavfi", + "-i", + SOURCE, + "-ac", + "1", + "-c:a", + "libvo_amrwbenc", + "-b:a", + &rate.to_string(), + "-f", + fmt, + path.to_str().unwrap(), + ]) + .is_some() + } + + /// The reference decode of `path` as s16le. + fn reference(path: &Path) -> Option> { + let raw = ffmpeg(&[ + "-c:a", + "libopencore_amrwb", + "-i", + path.to_str().unwrap(), + "-f", + "s16le", + "-", + ])?; + Some( + raw.as_chunks::<2>() + .0 + .iter() + .map(|b| i16::from_le_bytes(*b)) + .collect(), + ) + } + + fn decode_all(d: &mut dyn Demuxer, codec: CodecId) -> Vec { + let stream = d + .streams() + .iter() + .find(|s| s.params.codec == codec) + .expect("an AMR-WB track") + .clone(); + assert_eq!(codec, CodecId::AmrWb); + let mut dec = AmrWbDecoder::from_parameters(stream.params.clone()).unwrap(); + let mut out = Vec::new(); + loop { + match d.next_packet() { + Ok(p) if p.stream != stream.index => continue, + Ok(p) => out.extend_from_slice(dec.decode(&p.data).expect("decode")), + Err(e) if e.is_eof() => return out, + Err(e) => panic!("{e}"), + } + } + } + + fn have_tools() -> bool { + ffmpeg(&[ + "-f", + "lavfi", + "-i", + "anullsrc=r=16000:cl=mono", + "-t", + "0.1", + "-c:a", + "libvo_amrwbenc", + "-f", + "null", + "-", + ]) + .is_some() + && ffmpeg(&["-decoders"]) + .is_some_and(|o| String::from_utf8_lossy(&o).contains("libopencore_amrwb")) + } + + #[test] + fn every_mode_matches_the_reference_decoder_in_awb_and_mp4() { + assert!( + have_tools(), + "ffmpeg lacks libvo_amrwbenc/libopencore_amrwb" + ); + let dir = Dir::new("modes"); + for rate in RATES { + let awb = dir.path(&format!("m{rate}.awb")); + let mp4 = dir.path(&format!("m{rate}.3gp")); + assert!(encode(&awb, rate, "amr"), "encode {rate} awb"); + assert!(encode(&mp4, rate, "3gp"), "encode {rate} 3gp"); + let want = reference(&awb).expect("reference decode"); + assert!(want.len() >= 48000, "{rate}: {} samples", want.len()); + + let mut d = AmrDemuxer::new(BufReader::new(File::open(&awb).unwrap())).unwrap(); + let got = decode_all(&mut d, CodecId::AmrWb); + assert_eq!(got.len(), want.len(), "{rate} awb length"); + assert!( + got == want, + "{rate} awb: first difference at {:?}", + got.iter().zip(&want).position(|(a, b)| a != b) + ); + + let mut d = ec_mp4::Mp4Demuxer::new(BufReader::new(File::open(&mp4).unwrap())).unwrap(); + let got = decode_all(&mut d, CodecId::AmrWb); + // the mp4 holds the same frames; ffmpeg may drop encoder delay, so compare the overlap + assert!( + got.len() >= want.len() - 640, + "{rate} mp4 length {} vs {}", + got.len(), + want.len() + ); + assert!( + got[..want.len().min(got.len())] == want[..want.len().min(got.len())], + "{rate} mp4 differs" + ); + } + } + + /// Deterministic pseudo-random bytes. + fn lcg(state: &mut u64) -> u8 { + *state = state + .wrapping_mul(6364136223846793005) + .wrapping_add(1442695040888963407); + (*state >> 33) as u8 + } + + #[test] + fn comfort_noise_lost_and_corrupted_frames_match_the_reference() { + assert!( + have_tools(), + "ffmpeg lacks libvo_amrwbenc/libopencore_amrwb" + ); + let dir = Dir::new("chaos"); + // Real frames of three modes, mixed with SID, lost and corrupted ones (quality bit kept set: + // the reference wrapper ignores it). + let mut frames: Vec>> = Vec::new(); + for rate in [6600, 12650, 23850] { + let awb = dir.path(&format!("s{rate}.awb")); + assert!(encode(&awb, rate, "amr")); + let mut d = AmrDemuxer::new(BufReader::new(File::open(&awb).unwrap())).unwrap(); + let mut v = Vec::new(); + while let Ok(p) = d.next_packet() { + v.push(p.data.to_vec()); + } + frames.push(v); + } + let n = frames.iter().map(Vec::len).min().unwrap(); + let mut s = 0x1234_5678_9abc_def0u64; + let mut seq: Vec> = Vec::new(); + for i in 0..n * 4 { + let r = lcg(&mut s); + let mut f = match r % 8 { + 0 | 1 => { + let mut sid = vec![(9 << 3) | 4]; + sid.extend((0..PAYLOAD[9]).map(|_| lcg(&mut s))); + sid[5] &= 0xE0; + sid + } + 2 => vec![(14 << 3) | 4], + _ => frames[usize::from(lcg(&mut s)) % 3][i % n].clone(), + }; + if r.is_multiple_of(5) { + for b in f.iter_mut().skip(1) { + *b ^= lcg(&mut s) & lcg(&mut s) & lcg(&mut s); } - _ => {} } + seq.push(f); + } + let mut file = b"#!AMR-WB\n".to_vec(); + for f in &seq { + file.extend_from_slice(f); } - let cpath = dir.join(format!("corrupt-{label}.amr")); - write_amr(&cpath, &frames); - let want = ffmpeg_decode(&cpath, "libopencore_amrnb"); - let got = decode_all(&frames); - assert_eq!(first_diff(&got, &want), None, "{label}: corrupted stream differs from libopencore_amrnb"); + let path = dir.path("chaos.awb"); + std::fs::write(&path, &file).unwrap(); + let want = reference(&path).expect("reference decode"); + let mut d = AmrDemuxer::new(Cursor::new(file)).unwrap(); + let got = decode_all(&mut d, CodecId::AmrWb); + assert_eq!(got.len(), want.len()); + assert!( + got == want, + "first difference at {:?}", + got.iter().zip(&want).position(|(a, b)| a != b) + ); + } + + #[test] + fn the_decoder_trait_yields_one_frame_per_packet() { + use ec_core::frame::Frame; + use ec_core::packet::{Buf, Packet}; + use ec_core::timebase::TimeBase; + let mut dec = AmrWbDecoder::new(); + // mode 0 frame of zero bits, then a NO_DATA frame + let mut data = vec![0x04u8]; + data.extend([0u8; 17]); + let mut p = Packet::new(0, TimeBase::from_rate(16000), Buf::from_vec(data)); + p.pts = Some(0); + dec.send_packet(&p).unwrap(); + match dec.receive_frame().unwrap() { + Frame::Audio(a) => assert_eq!(a.samples, 320), + _ => panic!("audio expected"), + } + assert!(dec.receive_frame().is_err()); + let p = Packet::new(0, TimeBase::from_rate(16000), Buf::from_vec(vec![0x7C])); + dec.send_packet(&p).unwrap(); + assert!(dec.receive_frame().is_ok()); + // a truncated frame and a reserved type are errors, not panics + assert!(dec.decode(&[0x04, 1, 2]).is_err()); + assert!(dec.decode(&[0x5C]).is_err()); } -} -#[test] -fn garbage_never_panics() { - let mut dec = AmrNbDecoder::new(); - let mut seed = 0xdead_beef_cafe_f00du64; - for i in 0..4000usize { - let len = (rng(&mut seed) % 40) as usize; - let mut f: Vec = (0..len).map(|_| rng(&mut seed) as u8).collect(); - if i % 3 == 0 && !f.is_empty() { - f[0] = ((rng(&mut seed) % 16) as u8) << 3 | 4; - } - let pcm = dec.decode(&f).expect("decode never errors"); - assert_eq!(pcm.len(), 160); - } - // empty and truncated well-formed frames - assert!(dec.decode(&[]).is_ok()); - assert!(dec.decode(&[7 << 3 | 4, 1, 2]).is_ok()); - assert!(dec.decode(&[8 << 3 | 4]).is_ok()); - // decoder keeps working afterwards - assert_eq!(dec.decode(&[15 << 3 | 4]).unwrap().len(), 160); + #[test] + fn arbitrary_bytes_never_panic() { + let mut dec = AmrWbDecoder::new(); + let mut s = 0xdead_beef_u64; + for _ in 0..4000 { + let len = 1 + usize::from(lcg(&mut s)) % 70; + let mut p: Vec = (0..len).map(|_| lcg(&mut s)).collect(); + // make most packets well formed so the speech paths run + if !lcg(&mut s).is_multiple_of(4) { + let ft = lcg(&mut s) % 10; + p.truncate(1 + PAYLOAD[usize::from(ft)]); + p[0] = (ft << 3) | 4; + p.resize(1 + PAYLOAD[usize::from(ft)], 0x5a); + } + let _ = dec.decode(&p); + } + } } diff --git a/crates/ec-amr/tests/wb_oracle.rs b/crates/ec-amr/tests/wb_oracle.rs deleted file mode 100644 index 24d791d5..00000000 --- a/crates/ec-amr/tests/wb_oracle.rs +++ /dev/null @@ -1,267 +0,0 @@ -//! AMR-WB against ffmpeg's `libopencore_amrwb`, which wraps the fixed-point decoder derived from -//! the 3GPP TS 26.173 reference code: the output must match it sample for sample. -//! -//! Fixtures are made here with ffmpeg's `libvo_amrwbenc` from a synthetic source, one file per - -use std::fs::File; -use std::io::{BufReader, Cursor}; -use std::path::{Path, PathBuf}; - -use ec_amr::container::AmrDemuxer; -use ec_amr::wb::AmrWbDecoder; -use ec_core::registry::{CodecId, Decoder, Demuxer}; - -const RATES: [u32; 9] = [6600, 8850, 12650, 14250, 15850, 18250, 19850, 23050, 23850]; -const PAYLOAD: [usize; 10] = [17, 23, 32, 36, 40, 46, 50, 58, 60, 5]; - -fn ffmpeg(args: &[&str]) -> Option> { - let out = ec_testkit::ffmpeg() - .args(["-nostdin", "-v", "error", "-y"]) - .args(args) - .output() - .ok()?; - out.status.success().then_some(out.stdout) -} - -struct Dir(PathBuf); -impl Dir { - fn new(tag: &str) -> Dir { - let p = std::env::temp_dir().join(format!("ec-amr-wb-{tag}-{}", std::process::id())); - std::fs::create_dir_all(&p).unwrap(); - Dir(p) - } - fn path(&self, name: &str) -> PathBuf { - self.0.join(name) - } -} -impl Drop for Dir { - fn drop(&mut self) { - let _ = std::fs::remove_dir_all(&self.0); - } -} - -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))\ -+0.15*sin(2*PI*1700*t)*sin(2*PI*3*t)+0.04*(random(0)-0.5)':s=16000:d=3"; - -/// Encode the synthetic source at `rate` into `path` (format chosen by `fmt`). -fn encode(path: &Path, rate: u32, fmt: &str) -> bool { - ffmpeg(&[ - "-f", - "lavfi", - "-i", - SOURCE, - "-ac", - "1", - "-c:a", - "libvo_amrwbenc", - "-b:a", - &rate.to_string(), - "-f", - fmt, - path.to_str().unwrap(), - ]) - .is_some() -} - -/// The reference decode of `path` as s16le. -fn reference(path: &Path) -> Option> { - let raw = ffmpeg(&[ - "-c:a", - "libopencore_amrwb", - "-i", - path.to_str().unwrap(), - "-f", - "s16le", - "-", - ])?; - Some( - raw.as_chunks::<2>() - .0 - .iter() - .map(|b| i16::from_le_bytes(*b)) - .collect(), - ) -} - -fn decode_all(d: &mut dyn Demuxer, codec: CodecId) -> Vec { - let stream = d - .streams() - .iter() - .find(|s| s.params.codec == codec) - .expect("an AMR-WB track") - .clone(); - assert_eq!(codec, CodecId::AmrWb); - let mut dec = AmrWbDecoder::from_parameters(stream.params.clone()).unwrap(); - let mut out = Vec::new(); - loop { - match d.next_packet() { - Ok(p) if p.stream != stream.index => continue, - Ok(p) => out.extend_from_slice(dec.decode(&p.data).expect("decode")), - Err(e) if e.is_eof() => return out, - Err(e) => panic!("{e}"), - } - } -} - -fn have_tools() -> bool { - ffmpeg(&[ - "-f", - "lavfi", - "-i", - "anullsrc=r=16000:cl=mono", - "-t", - "0.1", - "-c:a", - "libvo_amrwbenc", - "-f", - "null", - "-", - ]) - .is_some() - && ffmpeg(&["-decoders"]) - .is_some_and(|o| String::from_utf8_lossy(&o).contains("libopencore_amrwb")) -} - -#[test] -fn every_mode_matches_the_reference_decoder_in_awb_and_mp4() { - assert!(have_tools(), "ffmpeg lacks libvo_amrwbenc/libopencore_amrwb"); - let dir = Dir::new("modes"); - for rate in RATES { - let awb = dir.path(&format!("m{rate}.awb")); - let mp4 = dir.path(&format!("m{rate}.3gp")); - assert!(encode(&awb, rate, "amr"), "encode {rate} awb"); - assert!(encode(&mp4, rate, "3gp"), "encode {rate} 3gp"); - let want = reference(&awb).expect("reference decode"); - assert!(want.len() >= 48000, "{rate}: {} samples", want.len()); - - let mut d = AmrDemuxer::new(BufReader::new(File::open(&awb).unwrap())).unwrap(); - let got = decode_all(&mut d, CodecId::AmrWb); - assert_eq!(got.len(), want.len(), "{rate} awb length"); - assert!( - got == want, - "{rate} awb: first difference at {:?}", - got.iter().zip(&want).position(|(a, b)| a != b) - ); - - let mut d = ec_mp4::Mp4Demuxer::new(BufReader::new(File::open(&mp4).unwrap())).unwrap(); - let got = decode_all(&mut d, CodecId::AmrWb); - // the mp4 holds the same frames; ffmpeg may drop encoder delay, so compare the overlap - assert!( - got.len() >= want.len() - 640, - "{rate} mp4 length {} vs {}", - got.len(), - want.len() - ); - assert!( - got[..want.len().min(got.len())] == want[..want.len().min(got.len())], - "{rate} mp4 differs" - ); - } -} - -/// Deterministic pseudo-random bytes. -fn lcg(state: &mut u64) -> u8 { - *state = state - .wrapping_mul(6364136223846793005) - .wrapping_add(1442695040888963407); - (*state >> 33) as u8 -} - -#[test] -fn comfort_noise_lost_and_corrupted_frames_match_the_reference() { - assert!(have_tools(), "ffmpeg lacks libvo_amrwbenc/libopencore_amrwb"); - let dir = Dir::new("chaos"); - // Real frames of three modes, mixed with SID, lost and corrupted ones (quality bit kept set: - // the reference wrapper ignores it). - let mut frames: Vec>> = Vec::new(); - for rate in [6600, 12650, 23850] { - let awb = dir.path(&format!("s{rate}.awb")); - assert!(encode(&awb, rate, "amr")); - let mut d = AmrDemuxer::new(BufReader::new(File::open(&awb).unwrap())).unwrap(); - let mut v = Vec::new(); - while let Ok(p) = d.next_packet() { - v.push(p.data.to_vec()); - } - frames.push(v); - } - let n = frames.iter().map(Vec::len).min().unwrap(); - let mut s = 0x1234_5678_9abc_def0u64; - let mut seq: Vec> = Vec::new(); - for i in 0..n * 4 { - let r = lcg(&mut s); - let mut f = match r % 8 { - 0 | 1 => { - let mut sid = vec![(9 << 3) | 4]; - sid.extend((0..PAYLOAD[9]).map(|_| lcg(&mut s))); - sid[5] &= 0xE0; - sid - } - 2 => vec![(14 << 3) | 4], - _ => frames[usize::from(lcg(&mut s)) % 3][i % n].clone(), - }; - if r.is_multiple_of(5) { - for b in f.iter_mut().skip(1) { - *b ^= lcg(&mut s) & lcg(&mut s) & lcg(&mut s); - } - } - seq.push(f); - } - let mut file = b"#!AMR-WB\n".to_vec(); - for f in &seq { - file.extend_from_slice(f); - } - let path = dir.path("chaos.awb"); - std::fs::write(&path, &file).unwrap(); - let want = reference(&path).expect("reference decode"); - let mut d = AmrDemuxer::new(Cursor::new(file)).unwrap(); - let got = decode_all(&mut d, CodecId::AmrWb); - assert_eq!(got.len(), want.len()); - assert!( - got == want, - "first difference at {:?}", - got.iter().zip(&want).position(|(a, b)| a != b) - ); -} - -#[test] -fn the_decoder_trait_yields_one_frame_per_packet() { - use ec_core::frame::Frame; - use ec_core::packet::{Buf, Packet}; - use ec_core::timebase::TimeBase; - let mut dec = AmrWbDecoder::new(); - // mode 0 frame of zero bits, then a NO_DATA frame - let mut data = vec![0x04u8]; - data.extend([0u8; 17]); - let mut p = Packet::new(0, TimeBase::from_rate(16000), Buf::from_vec(data)); - p.pts = Some(0); - dec.send_packet(&p).unwrap(); - match dec.receive_frame().unwrap() { - Frame::Audio(a) => assert_eq!(a.samples, 320), - _ => panic!("audio expected"), - } - assert!(dec.receive_frame().is_err()); - let p = Packet::new(0, TimeBase::from_rate(16000), Buf::from_vec(vec![0x7C])); - dec.send_packet(&p).unwrap(); - assert!(dec.receive_frame().is_ok()); - // a truncated frame and a reserved type are errors, not panics - assert!(dec.decode(&[0x04, 1, 2]).is_err()); - assert!(dec.decode(&[0x5C]).is_err()); -} - -#[test] -fn arbitrary_bytes_never_panic() { - let mut dec = AmrWbDecoder::new(); - let mut s = 0xdead_beef_u64; - for _ in 0..4000 { - let len = 1 + usize::from(lcg(&mut s)) % 70; - let mut p: Vec = (0..len).map(|_| lcg(&mut s)).collect(); - // make most packets well formed so the speech paths run - if !lcg(&mut s).is_multiple_of(4) { - let ft = lcg(&mut s) % 10; - p.truncate(1 + PAYLOAD[usize::from(ft)]); - p[0] = (ft << 3) | 4; - p.resize(1 + PAYLOAD[usize::from(ft)], 0x5a); - } - let _ = dec.decode(&p); - } -} diff --git a/crates/ec-mp3/src/encode.rs b/crates/ec-mp3/src/encode.rs index 2eea5984..14502707 100644 --- a/crates/ec-mp3/src/encode.rs +++ b/crates/ec-mp3/src/encode.rs @@ -1201,8 +1201,7 @@ fn quantise_granule( // Short blocks carry twelve bands, long ones twenty-one. let bands = if block_type == 2 { 12 } else { SFB_LONG }; let threshold = band_thresholds(threshold, block_type, sample_rate); - let mut exit = ("cap", 19usize); - for round in 0..20 { + for _ in 0..20 { let (granule, noise) = code_with(xr, block_type, target_bits, &scalefac, sample_rate); let ratios: Vec = (0..bands) .map(|b| f64::from(noise[b]) / f64::from(threshold[b]).max(1e-30)) @@ -1218,7 +1217,6 @@ fn quantise_granule( best = Some((granule, score, bands)); } if score <= 0.0 { - exit = ("mask", round); break; // every band is already exactly at the mask; nothing left to buy } // Where to stop amplifying, as a fraction of the frame's budget. Swept @@ -1241,7 +1239,6 @@ fn quantise_granule( // the MSE optimum, so perceptual redistribution can only trade away // what this gate scores. Don't re-run it: change the metric first. if spent * 100 > target_bits * 85 { - exit = ("budget", round); break; // the budget is spent; amplifying now only coarsens } // Bands over their mask get the bits first, worst three per round so @@ -1258,29 +1255,16 @@ fn quantise_granule( .take(3) .collect(); if chosen.is_empty() { - exit = ("saturated", round); break; } for band in chosen { scalefac[band] += 1; } } - census(exit); let (granule, score, bands) = best.expect("at least one round runs"); (granule, score / bands as f64) } -/// Exit-reason census for the distortion loop: with `EC_MP3_LOOP_TRACE` set, -/// one `mp3loop ` line per granule on stderr, so a sweep can be -/// counted with `sort | uniq -c`. The loop's shape is the encoder's open -/// question; without this the only evidence it ever iterates is indirect. -fn census(exit: (&str, usize)) { - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - if *ON.get_or_init(|| std::env::var_os("EC_MP3_LOOP_TRACE").is_some()) { - eprintln!("mp3loop {} {}", exit.0, exit.1); - } -} - /// Puts a spectrum into bitstream order in `out`. /// /// A short granule is coded band by band, window by window, line by line, diff --git a/crates/ec-mp3/src/header.rs b/crates/ec-mp3/src/header.rs index bb01e15c..4780da9b 100644 --- a/crates/ec-mp3/src/header.rs +++ b/crates/ec-mp3/src/header.rs @@ -247,24 +247,6 @@ impl FrameHeader { _ => 72 * bits / rate + pad, }) } - - /// Bytes of main data this frame carries: everything after the header, the - /// optional CRC and the side info. - pub fn main_data_len(&self) -> Option { - let len = self.frame_len()?; - let overhead = 4 + usize::from(self.crc) * 2 + self.side_info_len(); - Some(len.saturating_sub(overhead)) - } - - /// True when two headers describe the same stream configuration — the test - /// a resync uses to tell a real frame from a byte pattern that looked like - /// one. - pub fn same_stream(&self, other: &FrameHeader) -> bool { - self.version == other.version - && self.layer == other.layer - && self.sample_rate == other.sample_rate - && self.mode.channels() == other.mode.channels() - } } /// CRC-16 over a header and a run of protected *bits*, as Layers I and II diff --git a/crates/ec-mp3/tests/encode_matrix.rs b/crates/ec-mp3/tests/encode_matrix.rs index 79388850..ddb93504 100644 --- a/crates/ec-mp3/tests/encode_matrix.rs +++ b/crates/ec-mp3/tests/encode_matrix.rs @@ -1,44 +1,10 @@ //! Our encoder measured the only way a lossy one can be: encode, decode the //! result with ffmpeg, correlate against the samples that went in. -//! -//! The bar is the incumbent MP3 encoder this crate replaces, 0.6.1, measured on -//! the same fixtures and the same metric (see `BAR`, and -//! `scripts/mp3-incumbent-bar.md` for how those numbers were produced). -//! -//! Run the table: -//! cargo test -p ec-mp3 --release --test encode_matrix -- --nocapture use std::path::{Path, PathBuf}; -use ec_mp3::{FrameHeader, Mp3Encoder, Mp3EncoderConfig}; +use ec_mp3::{Mp3Encoder, Mp3EncoderConfig}; -/// Correlation the incumbent MP3 encoder, 0.6.1, reaches on this corpus, measured with this -/// same alignment and metric (its own encoder, ffmpeg's decoder). The tone -/// fixtures reach 1.0 on both encoders and so cannot separate them; the -/// `mp3src-*` material — glide, broadband noise and a click every half second — -/// is what does. -const BAR: [(&str, [f64; 3]); 4] = [ - ("mp3src-mono-44100", [0.99920, 0.99983, 0.99999]), - ("mp3src-stereo-44100", [0.99612, 0.99847, 0.99972]), - ("mp3src-mono-48000", [0.99867, 0.99972, 0.99998]), - ("mp3src-stereo-48000", [0.99461, 0.99787, 0.99956]), -]; -const BITRATES: [u32; 3] = [128, 192, 320]; - -/// The incumbent's number for this fixture and bitrate. Fixtures it was not -/// measured on (the tones, which both encoders code perfectly) fall back to its -/// worst result at that rate. -fn bar_for(name: &str, kbps: u32) -> f64 { - let index = BITRATES.iter().position(|k| *k == kbps).unwrap_or(0); - for (fixture, values) in BAR { - if name.starts_with(fixture) { - return values[index]; - } - } - BAR.iter() - .map(|(_, v)| v[index]) - .fold(f64::INFINITY, f64::min) -} fn workdir(test: &str) -> PathBuf { 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 { ab / (aa * bb).sqrt() } -/// Best correlation over the encoder delay, which no MP3 encoder avoids. -fn aligned(got: &[f32], want: &[f32], channels: usize) -> (f64, usize) { - let mut best = (f64::MIN, 0usize); - let mut offset = 0; - while offset + channels < got.len() && offset <= 3000 * channels { - let n = (got.len() - offset).min(want.len()); - let skip = 1152 * channels; - if n <= 2 * skip { - break; - } - let corr = correlation( - &got[offset + skip..offset + n - skip], - &want[skip..n - skip], - ); - if corr > best.0 { - best = (corr, offset); - } - offset += channels; - } - best -} - fn encode(pcm: &[f32], rate: u32, channels: usize, kbps: u32) -> Vec { let mut encoder = Mp3Encoder::new(Mp3EncoderConfig { bitrate_kbps: kbps, @@ -192,277 +136,3 @@ fn decode(file: &Path) -> Vec { .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) .collect() } - -fn encode_vbr(pcm: &[f32], rate: u32, channels: usize, quality: f32) -> Vec { - let mut encoder = Mp3Encoder::new(Mp3EncoderConfig { - bitrate_kbps: 0, - vbr_quality: Some(quality), - }); - encoder - .push_pcm_f32(pcm, channels as u16, rate) - .expect("encoder accepts the fixture"); - encoder.finish(); - let mut out = Vec::new(); - while let Ok(frame) = encoder.next_packet() { - out.extend_from_slice(&frame); - } - out -} - -/// Quality 0.5 asks for a 192 kbit/s mean; true VBR spends it unevenly across -/// frames, decodes at least as well as the incumbent's CBR-192, and announces -/// itself through a Xing tag ffprobe reads as VBR. -#[test] -fn vbr_frames_vary_their_bitrate_index() { - let name = "mp3src-stereo-48000"; - let path = ec_testkit::fixture(&format!("audio/{name}.wav")); - let (pcm, rate, channels) = read_wav(&path); - let bytes = encode_vbr(&pcm, rate, channels, 0.5); - // Walk the frame headers (MPEG-1, Layer III), skipping the Xing frame. - let table = [ - 0u32, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, - ]; - let mut indices = std::collections::BTreeSet::new(); - let (mut pos, mut frames) = (0usize, 0usize); - while pos + 4 <= bytes.len() { - let h = &bytes[pos..pos + 4]; - assert!(h[0] == 0xFF && (h[1] & 0xE0) == 0xE0, "sync lost at {pos}"); - let index = usize::from(h[2] >> 4); - let kbps = table[index.min(14)] as usize; - assert!(kbps > 0, "free-format header at {pos}"); - if frames > 0 { - indices.insert(index); - } - frames += 1; - pos += 144 * kbps * 1000 / rate as usize + usize::from((h[2] >> 1) & 1); - } - let seconds = pcm.len() as f64 / (rate as f64 * channels as f64); - let mean = bytes.len() as f64 * 8.0 / seconds / 1000.0; - let target = f64::from(ec_mp3::encode::bitrate_for_quality(0.5)); - println!("vbr frames={frames} indices={indices:?} mean={mean:.1} kbit/s"); - assert!(indices.len() >= 3, "only {indices:?}"); - assert!( - (mean - target).abs() <= target * 0.25, - "mean {mean:.1} vs {target}" - ); - - let work = workdir("vbr"); - let file = work.join("vbr.mp3"); - std::fs::write(&file, &bytes).unwrap(); - let out = ec_testkit::ffmpeg() - .args(["-v", "warning", "-i"]) - .arg(&file) - .args(["-f", "f32le", "-"]) - .output() - .expect("run ffmpeg"); - assert!( - out.stderr.is_empty(), - "ffmpeg: {}", - String::from_utf8_lossy(&out.stderr) - ); - let decoded: Vec = out - .stdout - .as_chunks::<4>() - .0 - .iter() - .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) - .collect(); - let corr = correlation(&decoded, &pcm); - let bar = bar_for(name, 192); - println!("vbr corr={corr:.5} bar={bar:.5}"); - assert!(corr >= bar, "corr {corr:.5} < bar {bar:.5}"); - let probe = ec_testkit::ffprobe() - .args(["-v", "error", "-show_format"]) - .arg(&file) - .output() - .expect("run ffprobe"); - let probe = String::from_utf8_lossy(&probe.stdout); - // "Xing" (not "Info") plus the VBR-method byte after the 9-byte version. - assert!( - &bytes[36..40] == b"Xing" && bytes[36 + 16 + 9] == 0x70, - "no VBR-flagged Xing tag" - ); - assert!(probe.contains("format_name=mp3"), "{probe}"); -} - -#[test] -fn vbr_mean_bitrate_tracks_quality_on_music() { - let path = ec_testkit::fixture("audio/wav16-stereo-48000.wav"); - let (pcm, rate, channels) = read_wav(&path); - let mut previous = 0.0; - for q in [0.25f32, 0.5, 0.75] { - let bytes = encode_vbr(&pcm, rate, channels, q); - let seconds = pcm.len() as f64 / (rate as f64 * channels as f64); - let mean = bytes.len() as f64 * 8.0 / seconds / 1000.0; - let target = f64::from(ec_mp3::encode::bitrate_for_quality(q)); - let tolerance = if q <= 0.5 { 0.70 } else { 0.25 }; - println!("q={q:.2} mean={mean:.1} target={target:.1}"); - assert!( - mean > previous, - "q={q:.2} mean {mean:.1} did not rise above {previous:.1}" - ); - assert!( - (mean - target).abs() <= target * tolerance, - "fixture is sparse/tonal, so q={q:.2} allows {:.0}%: mean {mean:.1} vs {target:.1}", - tolerance * 100.0, - ); - previous = mean; - } -} - -#[test] -fn encodes_above_the_incumbent_bar() { - let sources: Vec = ec_testkit::fixtures("audio", "wav") - .into_iter() - .filter(|p| { - let name = p.file_name().unwrap().to_string_lossy().to_string(); - (name.starts_with("wav16-") || name.starts_with("mp3src-")) - && (name.contains("mono") || name.contains("stereo")) - }) - .collect(); - // The corpus is eight committed WAVs (four `mp3src-*`, four `wav16-*`), - // all produced by `scripts/gen-fixtures.sh`. Fewer than all eight means - // the library drifted, not that the rows passed. - assert!( - sources.len() >= 8, - "only {} of the 8 mp3 encoder-matrix WAV fixtures are present", - sources.len() - ); - let work = workdir("encode"); - println!( - "{:<30} {:>5} {:>6} {:>3} {:>9} {:>8} {:>9}", - "fixture", "kbps", "rate", "ch", "corr", "bar", "kbit/s" - ); - let mut failures = Vec::new(); - for source in &sources { - let (pcm, rate, channels) = read_wav(source); - for kbps in BITRATES { - let bar = bar_for(&source.file_name().unwrap().to_string_lossy(), kbps); - let bytes = encode(&pcm, rate, channels, kbps); - let path = work.join(format!( - "{}-{kbps}.mp3", - source.file_stem().unwrap().to_string_lossy() - )); - std::fs::write(&path, &bytes).expect("write encoded file"); - let out = ec_testkit::ffmpeg() - .args(["-v", "warning", "-i"]) - .arg(&path) - .args(["-f", "f32le", "-"]) - .output() - .expect("run ffmpeg"); - let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string(); - if !stderr.is_empty() { - failures.push(format!("{}: ffmpeg said {stderr}", path.display())); - } - let decoded: Vec = out - .stdout - .as_chunks::<4>() - .0 - .iter() - .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) - .collect(); - // With the Info tag's delay and padding honoured, ffmpeg hands - // back exactly the samples that went in: same count, no shift. That - // is the gapless claim, so the correlation is measured at lag zero - // rather than at whatever lag looks best. - if decoded.len() != pcm.len() { - failures.push(format!( - "{}: decoded {} samples, pushed {}", - source.file_name().unwrap().to_string_lossy(), - decoded.len(), - pcm.len() - )); - } - let corr = correlation(&decoded, &pcm); - // A periodic fixture correlates equally well a whole period out, - // so a tie is not a misalignment; only a shift that is genuinely - // better than lag zero is. - let (searched, offset) = aligned(&decoded, &pcm, channels); - if offset != 0 && searched > corr + 1e-4 { - failures.push(format!( - "{}: lag {offset} correlates {searched:.6}, better than lag zero {corr:.6}", - source.file_name().unwrap().to_string_lossy(), - )); - } - let seconds = pcm.len() as f64 / (rate as f64 * channels as f64); - let measured = bytes.len() as f64 * 8.0 / seconds / 1000.0; - let name = source.file_name().unwrap().to_string_lossy(); - println!( - "{name:<30} {kbps:>5} {rate:>6} {channels:>3} {corr:>9.5} {bar:>8.5} {measured:>9.1}" - ); - // Matching counts as passing: at 320 kbit/s both encoders are - // within a part in 10^5 of the source and the difference between - // them is smaller than the metric resolves. - if corr < bar - 1e-5 { - failures.push(format!("{name} at {kbps} kbit/s: {corr:.5} < bar {bar:.5}")); - } - if (measured - kbps as f64).abs() > kbps as f64 * 0.05 { - failures.push(format!( - "{name} at {kbps} kbit/s: wrote {measured:.1} kbit/s" - )); - } - } - } - assert!(failures.is_empty(), "{failures:#?}"); -} - -fn mode_exts(bytes: &[u8]) -> Vec { - let mut out = Vec::new(); - let mut at = 0; - while at + 4 <= bytes.len() { - let Ok(header) = FrameHeader::parse(&bytes[at..]) else { - at += 1; - continue; - }; - let Some(len) = header.frame_len() else { break }; - out.push(header.mode_ext); - at += len; - } - out -} - -/// Mid/side is chosen for the signal it helps and declined for the one it -/// hurts. Two channels carrying the same waveform put everything in the sum -/// and nothing in the difference, which is the case mid/side exists for; two -/// carrying opposite waveforms are its worst case, where the difference is -/// the loud channel and coding it as such would spend the frame's bits on the -/// quiet one. Both roundtrip, because the decoder undoes whichever was -/// written. -#[test] -fn mid_side_follows_the_channel_correlation() { - let mut seed = 0x2545_f491_4f6c_dd1du64; - let mut noise = || { - seed ^= seed << 13; - seed ^= seed >> 7; - seed ^= seed << 17; - (seed >> 40) as f32 / 8388608.0 - 0.5 - }; - let n = 44100; - let (mut same, mut opposed) = (Vec::with_capacity(n * 2), Vec::with_capacity(n * 2)); - for i in 0..n { - // Band-limited enough to be codeable: a slow tone under the noise. - let tone = (i as f32 * 0.03).sin() * 0.4; - let v = tone + noise() * 0.05; - same.push(v); - same.push(v); - opposed.push(v); - opposed.push(-v); - } - for (label, pcm, want_ms) in [("same", same, true), ("opposed", opposed, false)] { - let bytes = encode(&pcm, 44100, 2, 128); - let exts = mode_exts(&bytes); - assert!(exts.len() > 20, "{label}: only {} frames", exts.len()); - let ms = exts.iter().filter(|e| *e & 2 != 0).count(); - // The first and last frames carry priming and a tail, so judge the body. - let body = exts.len() - 2; - if want_ms { - assert!( - ms >= body, - "{label}: only {ms} of {} frames are mid/side", - exts.len() - ); - } else { - assert_eq!(ms, 0, "{label}: {ms} frames chose mid/side"); - } - } -} diff --git a/crates/ec-mp3/tests/mp2_matrix.rs b/crates/ec-mp3/tests/mp2_matrix.rs index f8e2f5f1..d63f9f49 100644 --- a/crates/ec-mp3/tests/mp2_matrix.rs +++ b/crates/ec-mp3/tests/mp2_matrix.rs @@ -6,7 +6,6 @@ //! mode, the joint-stereo bound, CRC-protected frames and Layer I -- things no //! encoder here produces. The oracle is `ffmpeg -c:a mp2 -i x.mp2 -f f32le`. //! -//! //! cargo test -p ec-mp3 --release --test mp2_matrix -- --nocapture use std::path::PathBuf; @@ -110,58 +109,6 @@ impl Rng { } } -#[test] -fn encoder_streams_match_ffmpeg() { - let dir = work_dir(); - let sources = [ - "sine=frequency=1000:sample_rate={R}:duration=1.5", - "anoisesrc=color=pink:amplitude=0.4:sample_rate={R}:duration=1.5:seed=7", - "aevalsrc=0.5*sin(2*PI*(100+3000*t)*t):s={R}:d=1.5", - ]; - let cases: &[(&str, u32, u32, &str)] = &[ - ("mp2", 32000, 1, "32k"), - ("mp2", 44100, 2, "128k"), - ("mp2", 48000, 2, "384k"), - ("mp2", 48000, 1, "64k"), - ("mp2", 44100, 1, "192k"), - ("mp2", 44100, 2, "64k"), - ("mp2", 32000, 2, "96k"), - ("mp2", 16000, 1, "32k"), - ("mp2", 22050, 2, "64k"), - ("mp2", 24000, 2, "128k"), - ("mp2", 24000, 1, "8k"), - ("mp2fixed", 44100, 2, "192k"), - ("mp2fixed", 22050, 1, "48k"), - ]; - let mut worst_all = 0.0f32; - for (n, &(codec, rate, ch, br)) in cases.iter().enumerate() { - let src = sources[n % sources.len()].replace("{R}", &rate.to_string()); - let path = dir.join(format!("enc-{n}.mp2")); - let st = ec_testkit::ffmpeg() - .args(["-v", "error", "-y", "-f", "lavfi", "-i", &src, "-ac"]) - .arg(ch.to_string()) - .args(["-c:a", codec, "-b:a", br]) - .arg(&path) - .status() - .unwrap(); - assert!(st.success(), "ffmpeg encode {codec} {rate} {ch} {br}"); - let bytes = std::fs::read(&path).unwrap(); - let want = ffmpeg_decode(&path, ch as usize, 2); - let (got, r, c) = our_decode(&bytes); - assert_eq!((r, c), (rate, ch as usize), "{codec} {rate} {ch} {br}"); - assert_eq!(got.len(), want.len(), "{codec} {rate} {ch} {br}: length"); - let (e, at) = max_err(&got, &want); - let (lsb, same) = s16_agreement(&got, &ffmpeg_decode_s16(&path, ch as usize, 2)); - eprintln!( - "{codec} {rate} Hz ch={ch} {br}: max abs error {e:.3e} (at {at}); vs fixed-point s16: max {lsb} LSB, {:.2}% identical", - same * 100.0 - ); - worst_all = worst_all.max(e); - assert!(e <= 1e-5, "{codec} {rate} {ch} {br}: max error {e} at {at}"); - } - eprintln!("worst over the encoder matrix: {worst_all:.3e}"); -} - /// MSB-first bit writer for building frames. struct BitW { bytes: Vec, @@ -465,169 +412,3 @@ fn random_frames_match_ffmpeg() { } eprintln!("{streams} random streams, worst error {worst:.3e}"); } - -fn have_encoder(name: &str) -> bool { - ec_testkit::ffmpeg() - .args(["-hide_banner", "-encoders"]) - .output() - .is_ok_and(|o| String::from_utf8_lossy(&o.stdout).contains(name)) -} - -/// libtwolame writes what the ffmpeg encoder does not: joint stereo with every -/// intensity bound, dual channel, and CRC-protected frames. -#[test] -fn twolame_streams_match_ffmpeg() { - assert!(have_encoder("libtwolame"), "ffmpeg has no libtwolame"); - let dir = work_dir(); - let cases: &[(&str, u32, &str, u32, bool)] = &[ - ("joint_stereo", 44100, "64k", 2, false), - ("joint_stereo", 48000, "96k", 2, true), - ("joint_stereo", 32000, "128k", 2, false), - ("joint_stereo", 24000, "48k", 2, true), - ("stereo", 44100, "192k", 2, true), - ("stereo", 22050, "64k", 2, false), - ("dual_channel", 48000, "128k", 2, false), - ("mono", 44100, "64k", 1, true), - ("mono", 16000, "32k", 1, false), - ("joint_stereo", 44100, "384k", 2, true), - ("joint_stereo", 44100, "112k", 2, false), - ("mono", 48000, "56k", 1, false), - ]; - for (n, &(mode, rate, br, ch, crc)) in cases.iter().enumerate() { - let path = dir.join(format!("tl-{n}.mp2")); - let src = format!( - "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" - ); - let st = ec_testkit::ffmpeg() - .args(["-v", "error", "-y", "-f", "lavfi", "-i", &src, "-ac"]) - .arg(ch.to_string()) - .args(["-c:a", "libtwolame", "-mode", mode, "-b:a", br]) - .args(["-error_protection", if crc { "1" } else { "0" }]) - .arg(&path) - .status() - .unwrap(); - assert!(st.success(), "twolame {mode} {rate} {br}"); - let bytes = std::fs::read(&path).unwrap(); - let h = FrameHeader::parse(&bytes).unwrap(); - assert_eq!(h.crc, crc, "{mode} {rate}: protection bit"); - let want = ffmpeg_decode(&path, ch as usize, 2); - let (got, r, c) = our_decode(&bytes); - assert_eq!((r, c), (rate, ch as usize)); - // ffmpeg's demuxer drops leading frames whose header differs from the - // ones after them (twolame flips the mode between frames): align on the - // tail, and skip the frame after the cut, whose filterbank history we - // have and ffmpeg does not. - let per = 1152 * ch as usize; - assert!(got.len() >= want.len() && (got.len() - want.len()).is_multiple_of(per)); - let cut = got.len() - want.len(); - let skip = if cut > 0 { per } else { 0 }; - let (e, at) = max_err(&got[cut + skip..], &want[skip..]); - eprintln!("twolame {mode} {rate} Hz {br} crc={crc}: max abs error {e:.3e}"); - assert!(e <= 1e-5, "twolame {mode} {rate} {br}: {e} at {at}"); - } -} - -fn layer2_frame_with_crc() -> Vec { - let mut rng = Rng(77); - // MPEG-1 Layer II, 48 kHz, 128 kbit/s, stereo, CRC on. - let h = FrameHeader::parse(&[0xFF, 0xFC, 0x84, 0x00]).unwrap(); - loop { - let f = structured_frame(&mut rng, &h, 40); - if let Some(f) = f { - return f; - } - } -} - -#[test] -fn crc_protects_allocation_and_scfsi() { - let frame = layer2_frame_with_crc(); - assert!(FrameHeader::parse(&frame).unwrap().crc); - let mut reader = Mp3Reader::new(); - reader.push(&frame); - assert!(reader.next_frame().is_ok(), "good CRC decodes"); - // Flip one allocation bit. - let mut bad = frame.clone(); - bad[7] ^= 0x10; - let mut reader = Mp3Reader::new(); - reader.push(&bad); - let err = reader.next_frame().unwrap_err(); - assert!(err.to_string().contains("CRC"), "{err}"); - // A flip in the sample data is not covered by the CRC. - let mut late = frame.clone(); - let n = late.len() - 3; - late[n] ^= 0xFF; - let mut reader = Mp3Reader::new(); - reader.push(&late); - assert!(reader.next_frame().is_ok()); -} - -#[test] -fn free_format_layer2_is_refused_by_name() { - // Bitrate index 0. - let mut f = vec![0xFF, 0xFD, 0x04, 0x00]; - f.resize(600, 0); - let mut dec = ec_mp3::Mp3Decode::new(); - let err = dec.decode_frame(&f).unwrap_err(); - assert!(err.to_string().contains("free-format"), "{err}"); -} - -#[test] -fn decoder_trait_takes_layer2_packets() { - use ec_core::packet::{Buf, Packet}; - use ec_core::registry::{CodecId, Decoder}; - let mut rng = Rng(5); - let h = FrameHeader::parse(&[0xFF, 0xFD, 0x94, 0x00]).unwrap(); // 44.1k 128k stereo - let params = ec_mp3::layer_codec_parameters(2, 44100, 2); - assert_eq!(params.codec, CodecId::Mp2); - let mut dec = ec_mp3::Mp3Decoder::new(params).unwrap(); - let mut frames = 0; - for _ in 0..5 { - let f = loop { - if let Some(f) = structured_frame(&mut rng, &h, 30) { - break f; - } - }; - let pkt = Packet::new( - 0, - ec_core::TimeBase::try_new(1, 44100).unwrap(), - Buf::from(f), - ); - dec.send_packet(&pkt).unwrap(); - while let Ok(frame) = dec.receive_frame() { - let ec_core::frame::Frame::Audio(a) = frame else { - panic!() - }; - assert_eq!(a.samples, 1152); - frames += 1; - } - } - assert_eq!(frames, 5); -} - -#[test] -fn damaged_and_truncated_frames_never_panic() { - let mut rng = Rng(0xDEAD_BEEF); - for layer in [2u8, 1] { - for version in [3u8, 2, 0] { - for mode in [0u8, 1, 3] { - for _ in 0..40 { - let (ext, crc) = (rng.byte() % 4, rng.byte().is_multiple_of(2)); - let h = random_header(&mut rng, layer, version, mode, ext, crc); - let len = h.frame_len().unwrap(); - let mut f = h.to_bytes().to_vec(); - f.extend((4..len).map(|_| rng.byte())); - // whole, then every truncation point class - let mut dec = ec_mp3::Mp3Decode::new(); - let _ = dec.decode_frame(&f); - for cut in [5, 6, 20, len / 2, len - 1] { - let _ = dec.decode_frame(&f[..cut.min(len)]); - let mut r = Mp3Reader::new(); - r.push(&f[..cut.min(len)]); - while r.next_frame().is_ok() {} - } - } - } - } - } -}