| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | use std::path::{Path, PathBuf}; |
| 10 | use std::process::Command; |
| 11 | |
| 12 | use ec_amr::nb::bitstream::frame_bytes; |
| 13 | use ec_amr::nb::decoder::AmrNbDecoder; |
| 14 | |
| 15 | const MODES: [(u32, &str); 8] = [ |
| 16 | (4750, "mr475"), |
| 17 | (5150, "mr515"), |
| 18 | (5900, "mr59"), |
| 19 | (6700, "mr67"), |
| 20 | (7400, "mr74"), |
| 21 | (7950, "mr795"), |
| 22 | (10200, "mr102"), |
| 23 | (12200, "mr122"), |
| 24 | ]; |
| 25 | |
| 26 | 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))"; |
| 27 | |
| 28 | fn sources() -> Vec<(&'static str, String)> { |
| 29 | vec![ |
| 30 | ("sweep", "aevalsrc=0.5*sin(2*PI*(200+400*t)*t):s=8000:d=5".into()), |
| 31 | ("noise", "anoisesrc=d=5:c=pink:r=8000:a=0.3".into()), |
| 32 | ("speech", format!("aevalsrc={SPEECH}:s=8000:d=5")), |
| 33 | ( |
| 34 | "gaps", |
| 35 | format!( |
| 36 | "aevalsrc=if(between(mod(t\\,4)\\,1\\,2.5)\\,{SPEECH}\\,0.001*(random(0)-0.5)):s=8000:d=12" |
| 37 | ), |
| 38 | ), |
| 39 | ] |
| 40 | } |
| 41 | |
| 42 | fn require() -> bool { |
| 43 | std::env::var("EC_REQUIRE_FIXTURES").map(|v| v == "1").unwrap_or(false) |
| 44 | } |
| 45 | |
| 46 | fn workdir() -> PathBuf { |
| 47 | let d = std::env::temp_dir().join(format!("ec-amr-oracle-{}", std::process::id())); |
| 48 | std::fs::create_dir_all(&d).unwrap(); |
| 49 | d |
| 50 | } |
| 51 | |
| 52 | fn ffmpeg_ok() -> bool { |
| 53 | Command::new("ffmpeg") |
| 54 | .args(["-hide_banner", "-h", "decoder=libopencore_amrnb"]) |
| 55 | .output() |
| 56 | .map(|o| String::from_utf8_lossy(&o.stdout).contains("libopencore_amrnb")) |
| 57 | .unwrap_or(false) |
| 58 | } |
| 59 | |
| 60 | fn run(args: &[&str]) -> Option<Vec<u8>> { |
| 61 | let out = Command::new("ffmpeg").args(["-nostdin", "-v", "error", "-y"]).args(args).output().ok()?; |
| 62 | out.status.success().then_some(out.stdout) |
| 63 | } |
| 64 | |
| 65 | |
| 66 | fn encode(dir: &Path, name: &str, src: &str, bitrate: u32, dtx: bool) -> Option<PathBuf> { |
| 67 | let path = dir.join(format!("{name}-{bitrate}-{}.amr", dtx as u8)); |
| 68 | let br = bitrate.to_string(); |
| 69 | let p = path.to_str().unwrap(); |
| 70 | run(&[ |
| 71 | "-f", "lavfi", "-i", src, "-ar", "8000", "-ac", "1", "-c:a", "libopencore_amrnb", "-b:a", &br, "-dtx", |
| 72 | if dtx { "1" } else { "0" }, "-f", "amr", p, |
| 73 | ])?; |
| 74 | Some(path) |
| 75 | } |
| 76 | |
| 77 | fn ffmpeg_decode(path: &Path, codec: &str) -> Vec<i16> { |
| 78 | let out = run(&["-c:a", codec, "-i", path.to_str().unwrap(), "-f", "s16le", "-"]) |
| 79 | .unwrap_or_else(|| panic!("ffmpeg -c:a {codec} failed on {}", path.display())); |
| 80 | out.as_chunks::<2>().0.iter().map(|b| i16::from_le_bytes(*b)).collect() |
| 81 | } |
| 82 | |
| 83 | |
| 84 | fn parse_amr(data: &[u8]) -> Vec<Vec<u8>> { |
| 85 | let mut pos = if data.starts_with(b"#!AMR\n") { 6 } else { 0 }; |
| 86 | let mut frames = Vec::new(); |
| 87 | while pos < data.len() { |
| 88 | let ft = (data[pos] >> 3) & 15; |
| 89 | let Some(n) = frame_bytes(ft) else { break }; |
| 90 | if pos + 1 + n > data.len() { |
| 91 | break; |
| 92 | } |
| 93 | frames.push(data[pos..pos + 1 + n].to_vec()); |
| 94 | pos += 1 + n; |
| 95 | } |
| 96 | frames |
| 97 | } |
| 98 | |
| 99 | fn write_amr(path: &Path, frames: &[Vec<u8>]) { |
| 100 | let mut d = b"#!AMR\n".to_vec(); |
| 101 | for f in frames { |
| 102 | d.extend_from_slice(f); |
| 103 | } |
| 104 | std::fs::write(path, d).unwrap(); |
| 105 | } |
| 106 | |
| 107 | fn decode_all(frames: &[Vec<u8>]) -> Vec<i16> { |
| 108 | let mut dec = AmrNbDecoder::new(); |
| 109 | let mut out = Vec::new(); |
| 110 | for f in frames { |
| 111 | out.extend_from_slice(&dec.decode(f).expect("decode")); |
| 112 | } |
| 113 | out |
| 114 | } |
| 115 | |
| 116 | fn snr_db(reference: &[i16], test: &[i16]) -> f64 { |
| 117 | let n = reference.len().min(test.len()); |
| 118 | let (mut sig, mut err) = (0f64, 0f64); |
| 119 | for i in 0..n { |
| 120 | let r = reference[i] as f64; |
| 121 | sig += r * r; |
| 122 | let d = r - test[i] as f64; |
| 123 | err += d * d; |
| 124 | } |
| 125 | if err == 0.0 { |
| 126 | return 200.0; |
| 127 | } |
| 128 | 10.0 * (sig.max(1.0) / err).log10() |
| 129 | } |
| 130 | |
| 131 | fn first_diff(a: &[i16], b: &[i16]) -> Option<usize> { |
| 132 | (0..a.len().min(b.len())).find(|&i| a[i] != b[i]).or((a.len() != b.len()).then_some(a.len().min(b.len()))) |
| 133 | } |
| 134 | |
| 135 | fn setup() -> Option<PathBuf> { |
| 136 | if !ffmpeg_ok() { |
| 137 | assert!(!require(), "EC_REQUIRE_FIXTURES=1 but ffmpeg with libopencore_amrnb is unavailable"); |
| 138 | eprintln!("skipping: ffmpeg/libopencore_amrnb not available"); |
| 139 | return None; |
| 140 | } |
| 141 | Some(workdir()) |
| 142 | } |
| 143 | |
| 144 | #[test] |
| 145 | fn all_modes_bit_exact_vs_libopencore() { |
| 146 | let Some(dir) = setup() else { return }; |
| 147 | let mut checked = 0; |
| 148 | for dtx in [false, true] { |
| 149 | for (rate, label) in MODES { |
| 150 | for (sname, src) in sources() { |
| 151 | if dtx && sname != "gaps" && sname != "speech" { |
| 152 | continue; |
| 153 | } |
| 154 | let path = encode(&dir, sname, &src, rate, dtx).expect("encode"); |
| 155 | let frames = parse_amr(&std::fs::read(&path).unwrap()); |
| 156 | assert!(frames.len() > 100); |
| 157 | let sids = frames.iter().filter(|f| (f[0] >> 3) & 15 == 8).count(); |
| 158 | let nodata = frames.iter().filter(|f| (f[0] >> 3) & 15 == 15).count(); |
| 159 | let want = ffmpeg_decode(&path, "libopencore_amrnb"); |
| 160 | let got = decode_all(&frames); |
| 161 | assert_eq!( |
| 162 | first_diff(&got, &want), |
| 163 | None, |
| 164 | "{label} {sname} dtx={dtx}: differs from libopencore_amrnb ({} vs {} samples)", |
| 165 | got.len(), |
| 166 | want.len() |
| 167 | ); |
| 168 | let native = ffmpeg_decode(&path, "amrnb"); |
| 169 | let snr = snr_db(&native, &got); |
| 170 | eprintln!( |
| 171 | "{label:6} {sname:7} dtx={} frames={} sid={sids} nodata={nodata}: bit-exact, SNR vs native amrnb = {snr:.1} dB", |
| 172 | dtx as u8, |
| 173 | frames.len() |
| 174 | ); |
| 175 | if sids == 0 { |
| 176 | assert!(snr > 15.0, "{label} {sname}: SNR vs native {snr:.1} dB"); |
| 177 | } |
| 178 | checked += 1; |
| 179 | } |
| 180 | } |
| 181 | } |
| 182 | assert!(checked >= 8 * 6); |
| 183 | } |
| 184 | |
| 185 | |
| 186 | fn rng(state: &mut u64) -> u64 { |
| 187 | *state ^= *state << 13; |
| 188 | *state ^= *state >> 7; |
| 189 | *state ^= *state << 17; |
| 190 | *state |
| 191 | } |
| 192 | |
| 193 | #[test] |
| 194 | fn lost_and_bit_flipped_frames_vs_libopencore() { |
| 195 | let Some(dir) = setup() else { return }; |
| 196 | let mut seed = 0x1234_5678_9abc_def1u64; |
| 197 | for (rate, label) in MODES { |
| 198 | let (sname, src) = &sources()[2]; |
| 199 | let path = encode(&dir, sname, src, rate, false).expect("encode"); |
| 200 | let mut frames = parse_amr(&std::fs::read(&path).unwrap()); |
| 201 | for f in frames.iter_mut() { |
| 202 | match rng(&mut seed) % 10 { |
| 203 | 0 => *f = vec![15 << 3 | 4], |
| 204 | 1 | 2 if f.len() > 2 => { |
| 205 | let i = 1 + (rng(&mut seed) as usize % (f.len() - 1)); |
| 206 | f[i] ^= 1 << (rng(&mut seed) % 8); |
| 207 | } |
| 208 | _ => {} |
| 209 | } |
| 210 | } |
| 211 | let cpath = dir.join(format!("corrupt-{label}.amr")); |
| 212 | write_amr(&cpath, &frames); |
| 213 | let want = ffmpeg_decode(&cpath, "libopencore_amrnb"); |
| 214 | let got = decode_all(&frames); |
| 215 | assert_eq!(first_diff(&got, &want), None, "{label}: corrupted stream differs from libopencore_amrnb"); |
| 216 | } |
| 217 | } |
| 218 | |
| 219 | #[test] |
| 220 | fn garbage_never_panics() { |
| 221 | let mut dec = AmrNbDecoder::new(); |
| 222 | let mut seed = 0xdead_beef_cafe_f00du64; |
| 223 | for i in 0..4000usize { |
| 224 | let len = (rng(&mut seed) % 40) as usize; |
| 225 | let mut f: Vec<u8> = (0..len).map(|_| rng(&mut seed) as u8).collect(); |
| 226 | if i % 3 == 0 && !f.is_empty() { |
| 227 | f[0] = ((rng(&mut seed) % 16) as u8) << 3 | 4; |
| 228 | } |
| 229 | let pcm = dec.decode(&f).expect("decode never errors"); |
| 230 | assert_eq!(pcm.len(), 160); |
| 231 | } |
| 232 | |
| 233 | assert!(dec.decode(&[]).is_ok()); |
| 234 | assert!(dec.decode(&[7 << 3 | 4, 1, 2]).is_ok()); |
| 235 | assert!(dec.decode(&[8 << 3 | 4]).is_ok()); |
| 236 | |
| 237 | assert_eq!(dec.decode(&[15 << 3 | 4]).unwrap().len(), 160); |
| 238 | } |