U11: ec-amr merge wb_oracle into oracle (one oracle test file, nb and wb modules); drop unused ec-riff dev-dependency
Browse files at this commit52a5142454cc1a5ac4fd2813323ca6412f27156fParent: 4bfe75e4 changed files +504 -460
- Cargo.lock +0 -1
- crates/ec-amr/Cargo.toml +0 -1
- crates/ec-amr/tests/oracle.rs +504 -191
- crates/ec-amr/tests/wb_oracle.rs +0 -267
Cargo.lockmodified+0 -1
| @@ -402,7 +402,6 @@ version = "0.1.0" | |||
| 402 | dependencies = [ | 402 | dependencies = [ |
| 403 | "ec-core", | 403 | "ec-core", |
| 404 | "ec-mp4", | 404 | "ec-mp4", |
| 405 | - "ec-riff", | ||
| 406 | "ec-testkit", | 405 | "ec-testkit", |
| 407 | ] | 406 | ] |
| 408 | 407 | ||
crates/ec-amr/Cargo.tomlmodified+0 -1
| @@ -11,5 +11,4 @@ ec-core = { workspace = true } | |||
| 11 | 11 | ||
| 12 | [dev-dependencies] | 12 | [dev-dependencies] |
| 13 | ec-mp4 = { workspace = true } | 13 | ec-mp4 = { workspace = true } |
| 14 | -ec-riff = { workspace = true } | ||
| 15 | ec-testkit.workspace = true | 14 | ec-testkit.workspace = true |
crates/ec-amr/tests/oracle.rsmodified+504 -191
| @@ -1,227 +1,540 @@ | |||
| 1 | -//! AMR-NB oracle: synthetic sources are encoded with ffmpeg's libopencore_amrnb (every mode, | 1 | +//! AMR-NB and AMR-WB against ffmpeg's libopencore decoders. |
| 2 | -//! DTX on/off), then decoded by this crate and by ffmpeg. Against libopencore_amrnb (the | ||
| 3 | -//! reference this port follows) the output must be bit-exact; against ffmpeg's native `amrnb` | ||
| 4 | -//! decoder the SNR is reported and must stay high. | ||
| 5 | //! | 2 | //! |
| 3 | +//! NB: synthetic sources encoded with libopencore_amrnb (every mode, DTX on/off), decoded here and by | ||
| 4 | +//! ffmpeg; bit-exact against libopencore_amrnb. WB: libopencore_amrwb / AWB and MP4 round trips, | ||
| 5 | +//! bit-exact against the reference decoder. | ||
| 6 | 6 | ||
| 7 | -use std::path::{Path, PathBuf}; | 7 | +mod nb { |
| 8 | - | 8 | + use std::path::{Path, PathBuf}; |
| 9 | -use ec_amr::nb::bitstream::frame_bytes; | 9 | + |
| 10 | -use ec_amr::nb::decoder::AmrNbDecoder; | 10 | + use ec_amr::nb::bitstream::frame_bytes; |
| 11 | - | 11 | + use ec_amr::nb::decoder::AmrNbDecoder; |
| 12 | -const MODES: [(u32, &str); 8] = [ | 12 | + |
| 13 | - (4750, "mr475"), | 13 | + const MODES: [(u32, &str); 8] = [ |
| 14 | - (5150, "mr515"), | 14 | + (4750, "mr475"), |
| 15 | - (5900, "mr59"), | 15 | + (5150, "mr515"), |
| 16 | - (6700, "mr67"), | 16 | + (5900, "mr59"), |
| 17 | - (7400, "mr74"), | 17 | + (6700, "mr67"), |
| 18 | - (7950, "mr795"), | 18 | + (7400, "mr74"), |
| 19 | - (10200, "mr102"), | 19 | + (7950, "mr795"), |
| 20 | - (12200, "mr122"), | 20 | + (10200, "mr102"), |
| 21 | -]; | 21 | + (12200, "mr122"), |
| 22 | - | 22 | + ]; |
| 23 | -const SPEECH: &str = "0.3*(sin(2*PI*140*t)+0.5*sin(2*PI*280*t)+0.3*sin(2*PI*420*t)+0.2*sin(2*PI*1100*t))*(0.5+0.5*sin(2*PI*3*t))"; | 23 | + |
| 24 | - | 24 | + const SPEECH: &str = "0.3*(sin(2*PI*140*t)+0.5*sin(2*PI*280*t)+0.3*sin(2*PI*420*t)+0.2*sin(2*PI*1100*t))*(0.5+0.5*sin(2*PI*3*t))"; |
| 25 | -fn sources() -> Vec<(&'static str, String)> { | 25 | + |
| 26 | - vec![ | 26 | + fn sources() -> Vec<(&'static str, String)> { |
| 27 | - ("sweep", "aevalsrc=0.5*sin(2*PI*(200+400*t)*t):s=8000:d=5".into()), | 27 | + vec![ |
| 28 | - ("noise", "anoisesrc=d=5:c=pink:r=8000:a=0.3".into()), | 28 | + ( |
| 29 | - ("speech", format!("aevalsrc={SPEECH}:s=8000:d=5")), | 29 | + "sweep", |
| 30 | - ( | 30 | + "aevalsrc=0.5*sin(2*PI*(200+400*t)*t):s=8000:d=5".into(), |
| 31 | - "gaps", | ||
| 32 | - format!( | ||
| 33 | - "aevalsrc=if(between(mod(t\\,4)\\,1\\,2.5)\\,{SPEECH}\\,0.001*(random(0)-0.5)):s=8000:d=12" | ||
| 34 | ), | 31 | ), |
| 35 | - ), | 32 | + ("noise", "anoisesrc=d=5:c=pink:r=8000:a=0.3".into()), |
| 36 | - ] | 33 | + ("speech", format!("aevalsrc={SPEECH}:s=8000:d=5")), |
| 37 | -} | 34 | + ( |
| 35 | + "gaps", | ||
| 36 | + format!( | ||
| 37 | + "aevalsrc=if(between(mod(t\\,4)\\,1\\,2.5)\\,{SPEECH}\\,0.001*(random(0)-0.5)):s=8000:d=12" | ||
| 38 | + ), | ||
| 39 | + ), | ||
| 40 | + ] | ||
| 41 | + } | ||
| 38 | 42 | ||
| 39 | -fn workdir() -> PathBuf { | 43 | + fn workdir() -> PathBuf { |
| 40 | - let d = std::env::temp_dir().join(format!("ec-amr-oracle-{}", std::process::id())); | 44 | + let d = std::env::temp_dir().join(format!("ec-amr-oracle-{}", std::process::id())); |
| 41 | - std::fs::create_dir_all(&d).unwrap(); | 45 | + std::fs::create_dir_all(&d).unwrap(); |
| 42 | - d | 46 | + d |
| 43 | -} | 47 | + } |
| 44 | 48 | ||
| 45 | -fn ffmpeg_ok() -> bool { | 49 | + fn ffmpeg_ok() -> bool { |
| 46 | - ec_testkit::ffmpeg() | 50 | + ec_testkit::ffmpeg() |
| 47 | - .args(["-hide_banner", "-h", "decoder=libopencore_amrnb"]) | 51 | + .args(["-hide_banner", "-h", "decoder=libopencore_amrnb"]) |
| 48 | - .output() | 52 | + .output() |
| 49 | - .map(|o| String::from_utf8_lossy(&o.stdout).contains("libopencore_amrnb")) | 53 | + .map(|o| String::from_utf8_lossy(&o.stdout).contains("libopencore_amrnb")) |
| 50 | - .unwrap_or(false) | 54 | + .unwrap_or(false) |
| 51 | -} | 55 | + } |
| 52 | 56 | ||
| 53 | -fn run(args: &[&str]) -> Option<Vec<u8>> { | 57 | + fn run(args: &[&str]) -> Option<Vec<u8>> { |
| 54 | - let out = ec_testkit::ffmpeg().args(["-nostdin", "-v", "error", "-y"]).args(args).output().ok()?; | 58 | + let out = ec_testkit::ffmpeg() |
| 55 | - out.status.success().then_some(out.stdout) | 59 | + .args(["-nostdin", "-v", "error", "-y"]) |
| 56 | -} | 60 | + .args(args) |
| 61 | + .output() | ||
| 62 | + .ok()?; | ||
| 63 | + out.status.success().then_some(out.stdout) | ||
| 64 | + } | ||
| 57 | 65 | ||
| 58 | -/// Encode `src` (lavfi) to a .amr file with libopencore_amrnb. | 66 | + /// Encode `src` (lavfi) to a .amr file with libopencore_amrnb. |
| 59 | -fn encode(dir: &Path, name: &str, src: &str, bitrate: u32, dtx: bool) -> Option<PathBuf> { | 67 | + fn encode(dir: &Path, name: &str, src: &str, bitrate: u32, dtx: bool) -> Option<PathBuf> { |
| 60 | - let path = dir.join(format!("{name}-{bitrate}-{}.amr", dtx as u8)); | 68 | + let path = dir.join(format!("{name}-{bitrate}-{}.amr", dtx as u8)); |
| 61 | - let br = bitrate.to_string(); | 69 | + let br = bitrate.to_string(); |
| 62 | - let p = path.to_str().unwrap(); | 70 | + let p = path.to_str().unwrap(); |
| 63 | - run(&[ | 71 | + run(&[ |
| 64 | - "-f", "lavfi", "-i", src, "-ar", "8000", "-ac", "1", "-c:a", "libopencore_amrnb", "-b:a", &br, "-dtx", | 72 | + "-f", |
| 65 | - if dtx { "1" } else { "0" }, "-f", "amr", p, | 73 | + "lavfi", |
| 66 | - ])?; | 74 | + "-i", |
| 67 | - Some(path) | 75 | + src, |
| 68 | -} | 76 | + "-ar", |
| 77 | + "8000", | ||
| 78 | + "-ac", | ||
| 79 | + "1", | ||
| 80 | + "-c:a", | ||
| 81 | + "libopencore_amrnb", | ||
| 82 | + "-b:a", | ||
| 83 | + &br, | ||
| 84 | + "-dtx", | ||
| 85 | + if dtx { "1" } else { "0" }, | ||
| 86 | + "-f", | ||
| 87 | + "amr", | ||
| 88 | + p, | ||
| 89 | + ])?; | ||
| 90 | + Some(path) | ||
| 91 | + } | ||
| 69 | 92 | ||
| 70 | -fn ffmpeg_decode(path: &Path, codec: &str) -> Vec<i16> { | 93 | + fn ffmpeg_decode(path: &Path, codec: &str) -> Vec<i16> { |
| 71 | - let out = run(&["-c:a", codec, "-i", path.to_str().unwrap(), "-f", "s16le", "-"]) | 94 | + let out = run(&[ |
| 95 | + "-c:a", | ||
| 96 | + codec, | ||
| 97 | + "-i", | ||
| 98 | + path.to_str().unwrap(), | ||
| 99 | + "-f", | ||
| 100 | + "s16le", | ||
| 101 | + "-", | ||
| 102 | + ]) | ||
| 72 | .unwrap_or_else(|| panic!("ffmpeg -c:a {codec} failed on {}", path.display())); | 103 | .unwrap_or_else(|| panic!("ffmpeg -c:a {codec} failed on {}", path.display())); |
| 73 | - out.as_chunks::<2>().0.iter().map(|b| i16::from_le_bytes(*b)).collect() | 104 | + out.as_chunks::<2>() |
| 74 | -} | 105 | + .0 |
| 106 | + .iter() | ||
| 107 | + .map(|b| i16::from_le_bytes(*b)) | ||
| 108 | + .collect() | ||
| 109 | + } | ||
| 75 | 110 | ||
| 76 | -/// Split a `.amr` file into frames (ToC byte + payload). | 111 | + /// Split a `.amr` file into frames (ToC byte + payload). |
| 77 | -fn parse_amr(data: &[u8]) -> Vec<Vec<u8>> { | 112 | + fn parse_amr(data: &[u8]) -> Vec<Vec<u8>> { |
| 78 | - let mut pos = if data.starts_with(b"#!AMR\n") { 6 } else { 0 }; | 113 | + let mut pos = if data.starts_with(b"#!AMR\n") { 6 } else { 0 }; |
| 79 | - let mut frames = Vec::new(); | 114 | + let mut frames = Vec::new(); |
| 80 | - while pos < data.len() { | 115 | + while pos < data.len() { |
| 81 | - let ft = (data[pos] >> 3) & 15; | 116 | + let ft = (data[pos] >> 3) & 15; |
| 82 | - let Some(n) = frame_bytes(ft) else { break }; | 117 | + let Some(n) = frame_bytes(ft) else { break }; |
| 83 | - if pos + 1 + n > data.len() { | 118 | + if pos + 1 + n > data.len() { |
| 84 | - break; | 119 | + break; |
| 120 | + } | ||
| 121 | + frames.push(data[pos..pos + 1 + n].to_vec()); | ||
| 122 | + pos += 1 + n; | ||
| 85 | } | 123 | } |
| 86 | - frames.push(data[pos..pos + 1 + n].to_vec()); | 124 | + frames |
| 87 | - pos += 1 + n; | ||
| 88 | } | 125 | } |
| 89 | - frames | ||
| 90 | -} | ||
| 91 | 126 | ||
| 92 | -fn write_amr(path: &Path, frames: &[Vec<u8>]) { | 127 | + fn write_amr(path: &Path, frames: &[Vec<u8>]) { |
| 93 | - let mut d = b"#!AMR\n".to_vec(); | 128 | + let mut d = b"#!AMR\n".to_vec(); |
| 94 | - for f in frames { | 129 | + for f in frames { |
| 95 | - d.extend_from_slice(f); | 130 | + d.extend_from_slice(f); |
| 131 | + } | ||
| 132 | + std::fs::write(path, d).unwrap(); | ||
| 96 | } | 133 | } |
| 97 | - std::fs::write(path, d).unwrap(); | ||
| 98 | -} | ||
| 99 | 134 | ||
| 100 | -fn decode_all(frames: &[Vec<u8>]) -> Vec<i16> { | 135 | + fn decode_all(frames: &[Vec<u8>]) -> Vec<i16> { |
| 101 | - let mut dec = AmrNbDecoder::new(); | 136 | + let mut dec = AmrNbDecoder::new(); |
| 102 | - let mut out = Vec::new(); | 137 | + let mut out = Vec::new(); |
| 103 | - for f in frames { | 138 | + for f in frames { |
| 104 | - out.extend_from_slice(&dec.decode(f).expect("decode")); | 139 | + out.extend_from_slice(&dec.decode(f).expect("decode")); |
| 140 | + } | ||
| 141 | + out | ||
| 105 | } | 142 | } |
| 106 | - out | ||
| 107 | -} | ||
| 108 | 143 | ||
| 109 | -fn snr_db(reference: &[i16], test: &[i16]) -> f64 { | 144 | + fn snr_db(reference: &[i16], test: &[i16]) -> f64 { |
| 110 | - let n = reference.len().min(test.len()); | 145 | + let n = reference.len().min(test.len()); |
| 111 | - let (mut sig, mut err) = (0f64, 0f64); | 146 | + let (mut sig, mut err) = (0f64, 0f64); |
| 112 | - for i in 0..n { | 147 | + for i in 0..n { |
| 113 | - let r = reference[i] as f64; | 148 | + let r = reference[i] as f64; |
| 114 | - sig += r * r; | 149 | + sig += r * r; |
| 115 | - let d = r - test[i] as f64; | 150 | + let d = r - test[i] as f64; |
| 116 | - err += d * d; | 151 | + err += d * d; |
| 152 | + } | ||
| 153 | + if err == 0.0 { | ||
| 154 | + return 200.0; | ||
| 155 | + } | ||
| 156 | + 10.0 * (sig.max(1.0) / err).log10() | ||
| 117 | } | 157 | } |
| 118 | - if err == 0.0 { | 158 | + |
| 119 | - return 200.0; | 159 | + fn first_diff(a: &[i16], b: &[i16]) -> Option<usize> { |
| 160 | + (0..a.len().min(b.len())) | ||
| 161 | + .find(|&i| a[i] != b[i]) | ||
| 162 | + .or((a.len() != b.len()).then_some(a.len().min(b.len()))) | ||
| 120 | } | 163 | } |
| 121 | - 10.0 * (sig.max(1.0) / err).log10() | ||
| 122 | -} | ||
| 123 | 164 | ||
| 124 | -fn first_diff(a: &[i16], b: &[i16]) -> Option<usize> { | 165 | + fn setup() -> PathBuf { |
| 125 | - (0..a.len().min(b.len())).find(|&i| a[i] != b[i]).or((a.len() != b.len()).then_some(a.len().min(b.len()))) | 166 | + assert!(ffmpeg_ok(), "ffmpeg with libopencore_amrnb is required"); |
| 126 | -} | 167 | + workdir() |
| 168 | + } | ||
| 127 | 169 | ||
| 128 | -fn setup() -> PathBuf { | 170 | + #[test] |
| 129 | - assert!(ffmpeg_ok(), "ffmpeg with libopencore_amrnb is required"); | 171 | + fn all_modes_bit_exact_vs_libopencore() { |
| 130 | - workdir() | 172 | + let dir = setup(); |
| 131 | -} | 173 | + let mut checked = 0; |
| 174 | + for dtx in [false, true] { | ||
| 175 | + for (rate, label) in MODES { | ||
| 176 | + for (sname, src) in sources() { | ||
| 177 | + if dtx && sname != "gaps" && sname != "speech" { | ||
| 178 | + continue; | ||
| 179 | + } | ||
| 180 | + let path = encode(&dir, sname, &src, rate, dtx).expect("encode"); | ||
| 181 | + let frames = parse_amr(&std::fs::read(&path).unwrap()); | ||
| 182 | + assert!(frames.len() > 100); | ||
| 183 | + let sids = frames.iter().filter(|f| (f[0] >> 3) & 15 == 8).count(); | ||
| 184 | + let nodata = frames.iter().filter(|f| (f[0] >> 3) & 15 == 15).count(); | ||
| 185 | + let want = ffmpeg_decode(&path, "libopencore_amrnb"); | ||
| 186 | + let got = decode_all(&frames); | ||
| 187 | + assert_eq!( | ||
| 188 | + first_diff(&got, &want), | ||
| 189 | + None, | ||
| 190 | + "{label} {sname} dtx={dtx}: differs from libopencore_amrnb ({} vs {} samples)", | ||
| 191 | + got.len(), | ||
| 192 | + want.len() | ||
| 193 | + ); | ||
| 194 | + let native = ffmpeg_decode(&path, "amrnb"); | ||
| 195 | + let snr = snr_db(&native, &got); | ||
| 196 | + eprintln!( | ||
| 197 | + "{label:6} {sname:7} dtx={} frames={} sid={sids} nodata={nodata}: bit-exact, SNR vs native amrnb = {snr:.1} dB", | ||
| 198 | + dtx as u8, | ||
| 199 | + frames.len() | ||
| 200 | + ); | ||
| 201 | + if sids == 0 { | ||
| 202 | + assert!(snr > 15.0, "{label} {sname}: SNR vs native {snr:.1} dB"); | ||
| 203 | + } | ||
| 204 | + checked += 1; | ||
| 205 | + } | ||
| 206 | + } | ||
| 207 | + } | ||
| 208 | + assert!(checked >= 8 * 6); | ||
| 209 | + } | ||
| 210 | + | ||
| 211 | + /// Deterministic xorshift for corruption patterns. | ||
| 212 | + fn rng(state: &mut u64) -> u64 { | ||
| 213 | + *state ^= *state << 13; | ||
| 214 | + *state ^= *state >> 7; | ||
| 215 | + *state ^= *state << 17; | ||
| 216 | + *state | ||
| 217 | + } | ||
| 132 | 218 | ||
| 133 | -#[test] | 219 | + #[test] |
| 134 | -fn all_modes_bit_exact_vs_libopencore() { | 220 | + fn lost_and_bit_flipped_frames_vs_libopencore() { |
| 135 | - let dir = setup(); | 221 | + let dir = setup(); |
| 136 | - let mut checked = 0; | 222 | + let mut seed = 0x1234_5678_9abc_def1u64; |
| 137 | - for dtx in [false, true] { | ||
| 138 | for (rate, label) in MODES { | 223 | for (rate, label) in MODES { |
| 139 | - for (sname, src) in sources() { | 224 | + let (sname, src) = &sources()[2]; |
| 140 | - if dtx && sname != "gaps" && sname != "speech" { | 225 | + let path = encode(&dir, sname, src, rate, false).expect("encode"); |
| 141 | - continue; | 226 | + let mut frames = parse_amr(&std::fs::read(&path).unwrap()); |
| 227 | + for f in frames.iter_mut() { | ||
| 228 | + match rng(&mut seed) % 10 { | ||
| 229 | + 0 => *f = vec![15 << 3 | 4], // NO_DATA | ||
| 230 | + 1 | 2 if f.len() > 2 => { | ||
| 231 | + let i = 1 + (rng(&mut seed) as usize % (f.len() - 1)); | ||
| 232 | + f[i] ^= 1 << (rng(&mut seed) % 8); | ||
| 233 | + } | ||
| 234 | + _ => {} | ||
| 142 | } | 235 | } |
| 143 | - let path = encode(&dir, sname, &src, rate, dtx).expect("encode"); | ||
| 144 | - let frames = parse_amr(&std::fs::read(&path).unwrap()); | ||
| 145 | - assert!(frames.len() > 100); | ||
| 146 | - let sids = frames.iter().filter(|f| (f[0] >> 3) & 15 == 8).count(); | ||
| 147 | - let nodata = frames.iter().filter(|f| (f[0] >> 3) & 15 == 15).count(); | ||
| 148 | - let want = ffmpeg_decode(&path, "libopencore_amrnb"); | ||
| 149 | - let got = decode_all(&frames); | ||
| 150 | - assert_eq!( | ||
| 151 | - first_diff(&got, &want), | ||
| 152 | - None, | ||
| 153 | - "{label} {sname} dtx={dtx}: differs from libopencore_amrnb ({} vs {} samples)", | ||
| 154 | - got.len(), | ||
| 155 | - want.len() | ||
| 156 | - ); | ||
| 157 | - let native = ffmpeg_decode(&path, "amrnb"); | ||
| 158 | - let snr = snr_db(&native, &got); | ||
| 159 | - eprintln!( | ||
| 160 | - "{label:6} {sname:7} dtx={} frames={} sid={sids} nodata={nodata}: bit-exact, SNR vs native amrnb = {snr:.1} dB", | ||
| 161 | - dtx as u8, | ||
| 162 | - frames.len() | ||
| 163 | - ); | ||
| 164 | - if sids == 0 { | ||
| 165 | - assert!(snr > 15.0, "{label} {sname}: SNR vs native {snr:.1} dB"); | ||
| 166 | - } | ||
| 167 | - checked += 1; | ||
| 168 | } | 236 | } |
| 237 | + let cpath = dir.join(format!("corrupt-{label}.amr")); | ||
| 238 | + write_amr(&cpath, &frames); | ||
| 239 | + let want = ffmpeg_decode(&cpath, "libopencore_amrnb"); | ||
| 240 | + let got = decode_all(&frames); | ||
| 241 | + assert_eq!( | ||
| 242 | + first_diff(&got, &want), | ||
| 243 | + None, | ||
| 244 | + "{label}: corrupted stream differs from libopencore_amrnb" | ||
| 245 | + ); | ||
| 169 | } | 246 | } |
| 170 | } | 247 | } |
| 171 | - assert!(checked >= 8 * 6); | ||
| 172 | -} | ||
| 173 | 248 | ||
| 174 | -/// Deterministic xorshift for corruption patterns. | 249 | + #[test] |
| 175 | -fn rng(state: &mut u64) -> u64 { | 250 | + fn garbage_never_panics() { |
| 176 | - *state ^= *state << 13; | 251 | + let mut dec = AmrNbDecoder::new(); |
| 177 | - *state ^= *state >> 7; | 252 | + let mut seed = 0xdead_beef_cafe_f00du64; |
| 178 | - *state ^= *state << 17; | 253 | + for i in 0..4000usize { |
| 179 | - *state | 254 | + let len = (rng(&mut seed) % 40) as usize; |
| 255 | + let mut f: Vec<u8> = (0..len).map(|_| rng(&mut seed) as u8).collect(); | ||
| 256 | + if i % 3 == 0 && !f.is_empty() { | ||
| 257 | + f[0] = ((rng(&mut seed) % 16) as u8) << 3 | 4; | ||
| 258 | + } | ||
| 259 | + let pcm = dec.decode(&f).expect("decode never errors"); | ||
| 260 | + assert_eq!(pcm.len(), 160); | ||
| 261 | + } | ||
| 262 | + // empty and truncated well-formed frames | ||
| 263 | + assert!(dec.decode(&[]).is_ok()); | ||
| 264 | + assert!(dec.decode(&[7 << 3 | 4, 1, 2]).is_ok()); | ||
| 265 | + assert!(dec.decode(&[8 << 3 | 4]).is_ok()); | ||
| 266 | + // decoder keeps working afterwards | ||
| 267 | + assert_eq!(dec.decode(&[15 << 3 | 4]).unwrap().len(), 160); | ||
| 268 | + } | ||
| 180 | } | 269 | } |
| 181 | 270 | ||
| 182 | -#[test] | 271 | +mod wb { |
| 183 | -fn lost_and_bit_flipped_frames_vs_libopencore() { | 272 | + use std::fs::File; |
| 184 | - let dir = setup(); | 273 | + use std::io::{BufReader, Cursor}; |
| 185 | - let mut seed = 0x1234_5678_9abc_def1u64; | 274 | + use std::path::{Path, PathBuf}; |
| 186 | - for (rate, label) in MODES { | 275 | + |
| 187 | - let (sname, src) = &sources()[2]; | 276 | + use ec_amr::container::AmrDemuxer; |
| 188 | - let path = encode(&dir, sname, src, rate, false).expect("encode"); | 277 | + use ec_amr::wb::AmrWbDecoder; |
| 189 | - let mut frames = parse_amr(&std::fs::read(&path).unwrap()); | 278 | + use ec_core::registry::{CodecId, Decoder, Demuxer}; |
| 190 | - for f in frames.iter_mut() { | 279 | + |
| 191 | - match rng(&mut seed) % 10 { | 280 | + const RATES: [u32; 9] = [6600, 8850, 12650, 14250, 15850, 18250, 19850, 23050, 23850]; |
| 192 | - 0 => *f = vec![15 << 3 | 4], // NO_DATA | 281 | + const PAYLOAD: [usize; 10] = [17, 23, 32, 36, 40, 46, 50, 58, 60, 5]; |
| 193 | - 1 | 2 if f.len() > 2 => { | 282 | + |
| 194 | - let i = 1 + (rng(&mut seed) as usize % (f.len() - 1)); | 283 | + fn ffmpeg(args: &[&str]) -> Option<Vec<u8>> { |
| 195 | - f[i] ^= 1 << (rng(&mut seed) % 8); | 284 | + let out = ec_testkit::ffmpeg() |
| 285 | + .args(["-nostdin", "-v", "error", "-y"]) | ||
| 286 | + .args(args) | ||
| 287 | + .output() | ||
| 288 | + .ok()?; | ||
| 289 | + out.status.success().then_some(out.stdout) | ||
| 290 | + } | ||
| 291 | + | ||
| 292 | + struct Dir(PathBuf); | ||
| 293 | + impl Dir { | ||
| 294 | + fn new(tag: &str) -> Dir { | ||
| 295 | + let p = std::env::temp_dir().join(format!("ec-amr-wb-{tag}-{}", std::process::id())); | ||
| 296 | + std::fs::create_dir_all(&p).unwrap(); | ||
| 297 | + Dir(p) | ||
| 298 | + } | ||
| 299 | + fn path(&self, name: &str) -> PathBuf { | ||
| 300 | + self.0.join(name) | ||
| 301 | + } | ||
| 302 | + } | ||
| 303 | + impl Drop for Dir { | ||
| 304 | + fn drop(&mut self) { | ||
| 305 | + let _ = std::fs::remove_dir_all(&self.0); | ||
| 306 | + } | ||
| 307 | + } | ||
| 308 | + | ||
| 309 | + const SOURCE: &str = "aevalsrc='0.3*sin(2*PI*(200+60*sin(2*PI*0.7*t))*t)*(0.6+0.4*sin(2*PI*2.3*t))\ | ||
| 310 | ++0.15*sin(2*PI*1700*t)*sin(2*PI*3*t)+0.04*(random(0)-0.5)':s=16000:d=3"; | ||
| 311 | + | ||
| 312 | + /// Encode the synthetic source at `rate` into `path` (format chosen by `fmt`). | ||
| 313 | + fn encode(path: &Path, rate: u32, fmt: &str) -> bool { | ||
| 314 | + ffmpeg(&[ | ||
| 315 | + "-f", | ||
| 316 | + "lavfi", | ||
| 317 | + "-i", | ||
| 318 | + SOURCE, | ||
| 319 | + "-ac", | ||
| 320 | + "1", | ||
| 321 | + "-c:a", | ||
| 322 | + "libvo_amrwbenc", | ||
| 323 | + "-b:a", | ||
| 324 | + &rate.to_string(), | ||
| 325 | + "-f", | ||
| 326 | + fmt, | ||
| 327 | + path.to_str().unwrap(), | ||
| 328 | + ]) | ||
| 329 | + .is_some() | ||
| 330 | + } | ||
| 331 | + | ||
| 332 | + /// The reference decode of `path` as s16le. | ||
| 333 | + fn reference(path: &Path) -> Option<Vec<i16>> { | ||
| 334 | + let raw = ffmpeg(&[ | ||
| 335 | + "-c:a", | ||
| 336 | + "libopencore_amrwb", | ||
| 337 | + "-i", | ||
| 338 | + path.to_str().unwrap(), | ||
| 339 | + "-f", | ||
| 340 | + "s16le", | ||
| 341 | + "-", | ||
| 342 | + ])?; | ||
| 343 | + Some( | ||
| 344 | + raw.as_chunks::<2>() | ||
| 345 | + .0 | ||
| 346 | + .iter() | ||
| 347 | + .map(|b| i16::from_le_bytes(*b)) | ||
| 348 | + .collect(), | ||
| 349 | + ) | ||
| 350 | + } | ||
| 351 | + | ||
| 352 | + fn decode_all(d: &mut dyn Demuxer, codec: CodecId) -> Vec<i16> { | ||
| 353 | + let stream = d | ||
| 354 | + .streams() | ||
| 355 | + .iter() | ||
| 356 | + .find(|s| s.params.codec == codec) | ||
| 357 | + .expect("an AMR-WB track") | ||
| 358 | + .clone(); | ||
| 359 | + assert_eq!(codec, CodecId::AmrWb); | ||
| 360 | + let mut dec = AmrWbDecoder::from_parameters(stream.params.clone()).unwrap(); | ||
| 361 | + let mut out = Vec::new(); | ||
| 362 | + loop { | ||
| 363 | + match d.next_packet() { | ||
| 364 | + Ok(p) if p.stream != stream.index => continue, | ||
| 365 | + Ok(p) => out.extend_from_slice(dec.decode(&p.data).expect("decode")), | ||
| 366 | + Err(e) if e.is_eof() => return out, | ||
| 367 | + Err(e) => panic!("{e}"), | ||
| 368 | + } | ||
| 369 | + } | ||
| 370 | + } | ||
| 371 | + | ||
| 372 | + fn have_tools() -> bool { | ||
| 373 | + ffmpeg(&[ | ||
| 374 | + "-f", | ||
| 375 | + "lavfi", | ||
| 376 | + "-i", | ||
| 377 | + "anullsrc=r=16000:cl=mono", | ||
| 378 | + "-t", | ||
| 379 | + "0.1", | ||
| 380 | + "-c:a", | ||
| 381 | + "libvo_amrwbenc", | ||
| 382 | + "-f", | ||
| 383 | + "null", | ||
| 384 | + "-", | ||
| 385 | + ]) | ||
| 386 | + .is_some() | ||
| 387 | + && ffmpeg(&["-decoders"]) | ||
| 388 | + .is_some_and(|o| String::from_utf8_lossy(&o).contains("libopencore_amrwb")) | ||
| 389 | + } | ||
| 390 | + | ||
| 391 | + #[test] | ||
| 392 | + fn every_mode_matches_the_reference_decoder_in_awb_and_mp4() { | ||
| 393 | + assert!( | ||
| 394 | + have_tools(), | ||
| 395 | + "ffmpeg lacks libvo_amrwbenc/libopencore_amrwb" | ||
| 396 | + ); | ||
| 397 | + let dir = Dir::new("modes"); | ||
| 398 | + for rate in RATES { | ||
| 399 | + let awb = dir.path(&format!("m{rate}.awb")); | ||
| 400 | + let mp4 = dir.path(&format!("m{rate}.3gp")); | ||
| 401 | + assert!(encode(&awb, rate, "amr"), "encode {rate} awb"); | ||
| 402 | + assert!(encode(&mp4, rate, "3gp"), "encode {rate} 3gp"); | ||
| 403 | + let want = reference(&awb).expect("reference decode"); | ||
| 404 | + assert!(want.len() >= 48000, "{rate}: {} samples", want.len()); | ||
| 405 | + | ||
| 406 | + let mut d = AmrDemuxer::new(BufReader::new(File::open(&awb).unwrap())).unwrap(); | ||
| 407 | + let got = decode_all(&mut d, CodecId::AmrWb); | ||
| 408 | + assert_eq!(got.len(), want.len(), "{rate} awb length"); | ||
| 409 | + assert!( | ||
| 410 | + got == want, | ||
| 411 | + "{rate} awb: first difference at {:?}", | ||
| 412 | + got.iter().zip(&want).position(|(a, b)| a != b) | ||
| 413 | + ); | ||
| 414 | + | ||
| 415 | + let mut d = ec_mp4::Mp4Demuxer::new(BufReader::new(File::open(&mp4).unwrap())).unwrap(); | ||
| 416 | + let got = decode_all(&mut d, CodecId::AmrWb); | ||
| 417 | + // the mp4 holds the same frames; ffmpeg may drop encoder delay, so compare the overlap | ||
| 418 | + assert!( | ||
| 419 | + got.len() >= want.len() - 640, | ||
| 420 | + "{rate} mp4 length {} vs {}", | ||
| 421 | + got.len(), | ||
| 422 | + want.len() | ||
| 423 | + ); | ||
| 424 | + assert!( | ||
| 425 | + got[..want.len().min(got.len())] == want[..want.len().min(got.len())], | ||
| 426 | + "{rate} mp4 differs" | ||
| 427 | + ); | ||
| 428 | + } | ||
| 429 | + } | ||
| 430 | + | ||
| 431 | + /// Deterministic pseudo-random bytes. | ||
| 432 | + fn lcg(state: &mut u64) -> u8 { | ||
| 433 | + *state = state | ||
| 434 | + .wrapping_mul(6364136223846793005) | ||
| 435 | + .wrapping_add(1442695040888963407); | ||
| 436 | + (*state >> 33) as u8 | ||
| 437 | + } | ||
| 438 | + | ||
| 439 | + #[test] | ||
| 440 | + fn comfort_noise_lost_and_corrupted_frames_match_the_reference() { | ||
| 441 | + assert!( | ||
| 442 | + have_tools(), | ||
| 443 | + "ffmpeg lacks libvo_amrwbenc/libopencore_amrwb" | ||
| 444 | + ); | ||
| 445 | + let dir = Dir::new("chaos"); | ||
| 446 | + // Real frames of three modes, mixed with SID, lost and corrupted ones (quality bit kept set: | ||
| 447 | + // the reference wrapper ignores it). | ||
| 448 | + let mut frames: Vec<Vec<Vec<u8>>> = Vec::new(); | ||
| 449 | + for rate in [6600, 12650, 23850] { | ||
| 450 | + let awb = dir.path(&format!("s{rate}.awb")); | ||
| 451 | + assert!(encode(&awb, rate, "amr")); | ||
| 452 | + let mut d = AmrDemuxer::new(BufReader::new(File::open(&awb).unwrap())).unwrap(); | ||
| 453 | + let mut v = Vec::new(); | ||
| 454 | + while let Ok(p) = d.next_packet() { | ||
| 455 | + v.push(p.data.to_vec()); | ||
| 456 | + } | ||
| 457 | + frames.push(v); | ||
| 458 | + } | ||
| 459 | + let n = frames.iter().map(Vec::len).min().unwrap(); | ||
| 460 | + let mut s = 0x1234_5678_9abc_def0u64; | ||
| 461 | + let mut seq: Vec<Vec<u8>> = Vec::new(); | ||
| 462 | + for i in 0..n * 4 { | ||
| 463 | + let r = lcg(&mut s); | ||
| 464 | + let mut f = match r % 8 { | ||
| 465 | + 0 | 1 => { | ||
| 466 | + let mut sid = vec![(9 << 3) | 4]; | ||
| 467 | + sid.extend((0..PAYLOAD[9]).map(|_| lcg(&mut s))); | ||
| 468 | + sid[5] &= 0xE0; | ||
| 469 | + sid | ||
| 470 | + } | ||
| 471 | + 2 => vec![(14 << 3) | 4], | ||
| 472 | + _ => frames[usize::from(lcg(&mut s)) % 3][i % n].clone(), | ||
| 473 | + }; | ||
| 474 | + if r.is_multiple_of(5) { | ||
| 475 | + for b in f.iter_mut().skip(1) { | ||
| 476 | + *b ^= lcg(&mut s) & lcg(&mut s) & lcg(&mut s); | ||
| 196 | } | 477 | } |
| 197 | - _ => {} | ||
| 198 | } | 478 | } |
| 479 | + seq.push(f); | ||
| 480 | + } | ||
| 481 | + let mut file = b"#!AMR-WB\n".to_vec(); | ||
| 482 | + for f in &seq { | ||
| 483 | + file.extend_from_slice(f); | ||
| 199 | } | 484 | } |
| 200 | - let cpath = dir.join(format!("corrupt-{label}.amr")); | 485 | + let path = dir.path("chaos.awb"); |
| 201 | - write_amr(&cpath, &frames); | 486 | + std::fs::write(&path, &file).unwrap(); |
| 202 | - let want = ffmpeg_decode(&cpath, "libopencore_amrnb"); | 487 | + let want = reference(&path).expect("reference decode"); |
| 203 | - let got = decode_all(&frames); | 488 | + let mut d = AmrDemuxer::new(Cursor::new(file)).unwrap(); |
| 204 | - assert_eq!(first_diff(&got, &want), None, "{label}: corrupted stream differs from libopencore_amrnb"); | 489 | + let got = decode_all(&mut d, CodecId::AmrWb); |
| 490 | + assert_eq!(got.len(), want.len()); | ||
| 491 | + assert!( | ||
| 492 | + got == want, | ||
| 493 | + "first difference at {:?}", | ||
| 494 | + got.iter().zip(&want).position(|(a, b)| a != b) | ||
| 495 | + ); | ||
| 496 | + } | ||
| 497 | + | ||
| 498 | + #[test] | ||
| 499 | + fn the_decoder_trait_yields_one_frame_per_packet() { | ||
| 500 | + use ec_core::frame::Frame; | ||
| 501 | + use ec_core::packet::{Buf, Packet}; | ||
| 502 | + use ec_core::timebase::TimeBase; | ||
| 503 | + let mut dec = AmrWbDecoder::new(); | ||
| 504 | + // mode 0 frame of zero bits, then a NO_DATA frame | ||
| 505 | + let mut data = vec![0x04u8]; | ||
| 506 | + data.extend([0u8; 17]); | ||
| 507 | + let mut p = Packet::new(0, TimeBase::from_rate(16000), Buf::from_vec(data)); | ||
| 508 | + p.pts = Some(0); | ||
| 509 | + dec.send_packet(&p).unwrap(); | ||
| 510 | + match dec.receive_frame().unwrap() { | ||
| 511 | + Frame::Audio(a) => assert_eq!(a.samples, 320), | ||
| 512 | + _ => panic!("audio expected"), | ||
| 513 | + } | ||
| 514 | + assert!(dec.receive_frame().is_err()); | ||
| 515 | + let p = Packet::new(0, TimeBase::from_rate(16000), Buf::from_vec(vec![0x7C])); | ||
| 516 | + dec.send_packet(&p).unwrap(); | ||
| 517 | + assert!(dec.receive_frame().is_ok()); | ||
| 518 | + // a truncated frame and a reserved type are errors, not panics | ||
| 519 | + assert!(dec.decode(&[0x04, 1, 2]).is_err()); | ||
| 520 | + assert!(dec.decode(&[0x5C]).is_err()); | ||
| 205 | } | 521 | } |
| 206 | -} | ||
| 207 | 522 | ||
| 208 | -#[test] | 523 | + #[test] |
| 209 | -fn garbage_never_panics() { | 524 | + fn arbitrary_bytes_never_panic() { |
| 210 | - let mut dec = AmrNbDecoder::new(); | 525 | + let mut dec = AmrWbDecoder::new(); |
| 211 | - let mut seed = 0xdead_beef_cafe_f00du64; | 526 | + let mut s = 0xdead_beef_u64; |
| 212 | - for i in 0..4000usize { | 527 | + for _ in 0..4000 { |
| 213 | - let len = (rng(&mut seed) % 40) as usize; | 528 | + let len = 1 + usize::from(lcg(&mut s)) % 70; |
| 214 | - let mut f: Vec<u8> = (0..len).map(|_| rng(&mut seed) as u8).collect(); | 529 | + let mut p: Vec<u8> = (0..len).map(|_| lcg(&mut s)).collect(); |
| 215 | - if i % 3 == 0 && !f.is_empty() { | 530 | + // make most packets well formed so the speech paths run |
| 216 | - f[0] = ((rng(&mut seed) % 16) as u8) << 3 | 4; | 531 | + if !lcg(&mut s).is_multiple_of(4) { |
| 217 | - } | 532 | + let ft = lcg(&mut s) % 10; |
| 218 | - let pcm = dec.decode(&f).expect("decode never errors"); | 533 | + p.truncate(1 + PAYLOAD[usize::from(ft)]); |
| 219 | - assert_eq!(pcm.len(), 160); | 534 | + p[0] = (ft << 3) | 4; |
| 220 | - } | 535 | + p.resize(1 + PAYLOAD[usize::from(ft)], 0x5a); |
| 221 | - // empty and truncated well-formed frames | 536 | + } |
| 222 | - assert!(dec.decode(&[]).is_ok()); | 537 | + let _ = dec.decode(&p); |
| 223 | - assert!(dec.decode(&[7 << 3 | 4, 1, 2]).is_ok()); | 538 | + } |
| 224 | - assert!(dec.decode(&[8 << 3 | 4]).is_ok()); | 539 | + } |
| 225 | - // decoder keeps working afterwards | ||
| 226 | - assert_eq!(dec.decode(&[15 << 3 | 4]).unwrap().len(), 160); | ||
| 227 | } | 540 | } |
crates/ec-amr/tests/wb_oracle.rsdeleted+0 -267
| @@ -1,267 +0,0 @@ | |||
| 1 | -//! AMR-WB against ffmpeg's `libopencore_amrwb`, which wraps the fixed-point decoder derived from | ||
| 2 | -//! the 3GPP TS 26.173 reference code: the output must match it sample for sample. | ||
| 3 | -//! | ||
| 4 | -//! Fixtures are made here with ffmpeg's `libvo_amrwbenc` from a synthetic source, one file per | ||
| 5 | - | ||
| 6 | -use std::fs::File; | ||
| 7 | -use std::io::{BufReader, Cursor}; | ||
| 8 | -use std::path::{Path, PathBuf}; | ||
| 9 | - | ||
| 10 | -use ec_amr::container::AmrDemuxer; | ||
| 11 | -use ec_amr::wb::AmrWbDecoder; | ||
| 12 | -use ec_core::registry::{CodecId, Decoder, Demuxer}; | ||
| 13 | - | ||
| 14 | -const RATES: [u32; 9] = [6600, 8850, 12650, 14250, 15850, 18250, 19850, 23050, 23850]; | ||
| 15 | -const PAYLOAD: [usize; 10] = [17, 23, 32, 36, 40, 46, 50, 58, 60, 5]; | ||
| 16 | - | ||
| 17 | -fn ffmpeg(args: &[&str]) -> Option<Vec<u8>> { | ||
| 18 | - let out = ec_testkit::ffmpeg() | ||
| 19 | - .args(["-nostdin", "-v", "error", "-y"]) | ||
| 20 | - .args(args) | ||
| 21 | - .output() | ||
| 22 | - .ok()?; | ||
| 23 | - out.status.success().then_some(out.stdout) | ||
| 24 | -} | ||
| 25 | - | ||
| 26 | -struct Dir(PathBuf); | ||
| 27 | -impl Dir { | ||
| 28 | - fn new(tag: &str) -> Dir { | ||
| 29 | - let p = std::env::temp_dir().join(format!("ec-amr-wb-{tag}-{}", std::process::id())); | ||
| 30 | - std::fs::create_dir_all(&p).unwrap(); | ||
| 31 | - Dir(p) | ||
| 32 | - } | ||
| 33 | - fn path(&self, name: &str) -> PathBuf { | ||
| 34 | - self.0.join(name) | ||
| 35 | - } | ||
| 36 | -} | ||
| 37 | -impl Drop for Dir { | ||
| 38 | - fn drop(&mut self) { | ||
| 39 | - let _ = std::fs::remove_dir_all(&self.0); | ||
| 40 | - } | ||
| 41 | -} | ||
| 42 | - | ||
| 43 | -const SOURCE: &str = "aevalsrc='0.3*sin(2*PI*(200+60*sin(2*PI*0.7*t))*t)*(0.6+0.4*sin(2*PI*2.3*t))\ | ||
| 44 | -+0.15*sin(2*PI*1700*t)*sin(2*PI*3*t)+0.04*(random(0)-0.5)':s=16000:d=3"; | ||
| 45 | - | ||
| 46 | -/// Encode the synthetic source at `rate` into `path` (format chosen by `fmt`). | ||
| 47 | -fn encode(path: &Path, rate: u32, fmt: &str) -> bool { | ||
| 48 | - ffmpeg(&[ | ||
| 49 | - "-f", | ||
| 50 | - "lavfi", | ||
| 51 | - "-i", | ||
| 52 | - SOURCE, | ||
| 53 | - "-ac", | ||
| 54 | - "1", | ||
| 55 | - "-c:a", | ||
| 56 | - "libvo_amrwbenc", | ||
| 57 | - "-b:a", | ||
| 58 | - &rate.to_string(), | ||
| 59 | - "-f", | ||
| 60 | - fmt, | ||
| 61 | - path.to_str().unwrap(), | ||
| 62 | - ]) | ||
| 63 | - .is_some() | ||
| 64 | -} | ||
| 65 | - | ||
| 66 | -/// The reference decode of `path` as s16le. | ||
| 67 | -fn reference(path: &Path) -> Option<Vec<i16>> { | ||
| 68 | - let raw = ffmpeg(&[ | ||
| 69 | - "-c:a", | ||
| 70 | - "libopencore_amrwb", | ||
| 71 | - "-i", | ||
| 72 | - path.to_str().unwrap(), | ||
| 73 | - "-f", | ||
| 74 | - "s16le", | ||
| 75 | - "-", | ||
| 76 | - ])?; | ||
| 77 | - Some( | ||
| 78 | - raw.as_chunks::<2>() | ||
| 79 | - .0 | ||
| 80 | - .iter() | ||
| 81 | - .map(|b| i16::from_le_bytes(*b)) | ||
| 82 | - .collect(), | ||
| 83 | - ) | ||
| 84 | -} | ||
| 85 | - | ||
| 86 | -fn decode_all(d: &mut dyn Demuxer, codec: CodecId) -> Vec<i16> { | ||
| 87 | - let stream = d | ||
| 88 | - .streams() | ||
| 89 | - .iter() | ||
| 90 | - .find(|s| s.params.codec == codec) | ||
| 91 | - .expect("an AMR-WB track") | ||
| 92 | - .clone(); | ||
| 93 | - assert_eq!(codec, CodecId::AmrWb); | ||
| 94 | - let mut dec = AmrWbDecoder::from_parameters(stream.params.clone()).unwrap(); | ||
| 95 | - let mut out = Vec::new(); | ||
| 96 | - loop { | ||
| 97 | - match d.next_packet() { | ||
| 98 | - Ok(p) if p.stream != stream.index => continue, | ||
| 99 | - Ok(p) => out.extend_from_slice(dec.decode(&p.data).expect("decode")), | ||
| 100 | - Err(e) if e.is_eof() => return out, | ||
| 101 | - Err(e) => panic!("{e}"), | ||
| 102 | - } | ||
| 103 | - } | ||
| 104 | -} | ||
| 105 | - | ||
| 106 | -fn have_tools() -> bool { | ||
| 107 | - ffmpeg(&[ | ||
| 108 | - "-f", | ||
| 109 | - "lavfi", | ||
| 110 | - "-i", | ||
| 111 | - "anullsrc=r=16000:cl=mono", | ||
| 112 | - "-t", | ||
| 113 | - "0.1", | ||
| 114 | - "-c:a", | ||
| 115 | - "libvo_amrwbenc", | ||
| 116 | - "-f", | ||
| 117 | - "null", | ||
| 118 | - "-", | ||
| 119 | - ]) | ||
| 120 | - .is_some() | ||
| 121 | - && ffmpeg(&["-decoders"]) | ||
| 122 | - .is_some_and(|o| String::from_utf8_lossy(&o).contains("libopencore_amrwb")) | ||
| 123 | -} | ||
| 124 | - | ||
| 125 | -#[test] | ||
| 126 | -fn every_mode_matches_the_reference_decoder_in_awb_and_mp4() { | ||
| 127 | - assert!(have_tools(), "ffmpeg lacks libvo_amrwbenc/libopencore_amrwb"); | ||
| 128 | - let dir = Dir::new("modes"); | ||
| 129 | - for rate in RATES { | ||
| 130 | - let awb = dir.path(&format!("m{rate}.awb")); | ||
| 131 | - let mp4 = dir.path(&format!("m{rate}.3gp")); | ||
| 132 | - assert!(encode(&awb, rate, "amr"), "encode {rate} awb"); | ||
| 133 | - assert!(encode(&mp4, rate, "3gp"), "encode {rate} 3gp"); | ||
| 134 | - let want = reference(&awb).expect("reference decode"); | ||
| 135 | - assert!(want.len() >= 48000, "{rate}: {} samples", want.len()); | ||
| 136 | - | ||
| 137 | - let mut d = AmrDemuxer::new(BufReader::new(File::open(&awb).unwrap())).unwrap(); | ||
| 138 | - let got = decode_all(&mut d, CodecId::AmrWb); | ||
| 139 | - assert_eq!(got.len(), want.len(), "{rate} awb length"); | ||
| 140 | - assert!( | ||
| 141 | - got == want, | ||
| 142 | - "{rate} awb: first difference at {:?}", | ||
| 143 | - got.iter().zip(&want).position(|(a, b)| a != b) | ||
| 144 | - ); | ||
| 145 | - | ||
| 146 | - let mut d = ec_mp4::Mp4Demuxer::new(BufReader::new(File::open(&mp4).unwrap())).unwrap(); | ||
| 147 | - let got = decode_all(&mut d, CodecId::AmrWb); | ||
| 148 | - // the mp4 holds the same frames; ffmpeg may drop encoder delay, so compare the overlap | ||
| 149 | - assert!( | ||
| 150 | - got.len() >= want.len() - 640, | ||
| 151 | - "{rate} mp4 length {} vs {}", | ||
| 152 | - got.len(), | ||
| 153 | - want.len() | ||
| 154 | - ); | ||
| 155 | - assert!( | ||
| 156 | - got[..want.len().min(got.len())] == want[..want.len().min(got.len())], | ||
| 157 | - "{rate} mp4 differs" | ||
| 158 | - ); | ||
| 159 | - } | ||
| 160 | -} | ||
| 161 | - | ||
| 162 | -/// Deterministic pseudo-random bytes. | ||
| 163 | -fn lcg(state: &mut u64) -> u8 { | ||
| 164 | - *state = state | ||
| 165 | - .wrapping_mul(6364136223846793005) | ||
| 166 | - .wrapping_add(1442695040888963407); | ||
| 167 | - (*state >> 33) as u8 | ||
| 168 | -} | ||
| 169 | - | ||
| 170 | -#[test] | ||
| 171 | -fn comfort_noise_lost_and_corrupted_frames_match_the_reference() { | ||
| 172 | - assert!(have_tools(), "ffmpeg lacks libvo_amrwbenc/libopencore_amrwb"); | ||
| 173 | - let dir = Dir::new("chaos"); | ||
| 174 | - // Real frames of three modes, mixed with SID, lost and corrupted ones (quality bit kept set: | ||
| 175 | - // the reference wrapper ignores it). | ||
| 176 | - let mut frames: Vec<Vec<Vec<u8>>> = Vec::new(); | ||
| 177 | - for rate in [6600, 12650, 23850] { | ||
| 178 | - let awb = dir.path(&format!("s{rate}.awb")); | ||
| 179 | - assert!(encode(&awb, rate, "amr")); | ||
| 180 | - let mut d = AmrDemuxer::new(BufReader::new(File::open(&awb).unwrap())).unwrap(); | ||
| 181 | - let mut v = Vec::new(); | ||
| 182 | - while let Ok(p) = d.next_packet() { | ||
| 183 | - v.push(p.data.to_vec()); | ||
| 184 | - } | ||
| 185 | - frames.push(v); | ||
| 186 | - } | ||
| 187 | - let n = frames.iter().map(Vec::len).min().unwrap(); | ||
| 188 | - let mut s = 0x1234_5678_9abc_def0u64; | ||
| 189 | - let mut seq: Vec<Vec<u8>> = Vec::new(); | ||
| 190 | - for i in 0..n * 4 { | ||
| 191 | - let r = lcg(&mut s); | ||
| 192 | - let mut f = match r % 8 { | ||
| 193 | - 0 | 1 => { | ||
| 194 | - let mut sid = vec![(9 << 3) | 4]; | ||
| 195 | - sid.extend((0..PAYLOAD[9]).map(|_| lcg(&mut s))); | ||
| 196 | - sid[5] &= 0xE0; | ||
| 197 | - sid | ||
| 198 | - } | ||
| 199 | - 2 => vec![(14 << 3) | 4], | ||
| 200 | - _ => frames[usize::from(lcg(&mut s)) % 3][i % n].clone(), | ||
| 201 | - }; | ||
| 202 | - if r.is_multiple_of(5) { | ||
| 203 | - for b in f.iter_mut().skip(1) { | ||
| 204 | - *b ^= lcg(&mut s) & lcg(&mut s) & lcg(&mut s); | ||
| 205 | - } | ||
| 206 | - } | ||
| 207 | - seq.push(f); | ||
| 208 | - } | ||
| 209 | - let mut file = b"#!AMR-WB\n".to_vec(); | ||
| 210 | - for f in &seq { | ||
| 211 | - file.extend_from_slice(f); | ||
| 212 | - } | ||
| 213 | - let path = dir.path("chaos.awb"); | ||
| 214 | - std::fs::write(&path, &file).unwrap(); | ||
| 215 | - let want = reference(&path).expect("reference decode"); | ||
| 216 | - let mut d = AmrDemuxer::new(Cursor::new(file)).unwrap(); | ||
| 217 | - let got = decode_all(&mut d, CodecId::AmrWb); | ||
| 218 | - assert_eq!(got.len(), want.len()); | ||
| 219 | - assert!( | ||
| 220 | - got == want, | ||
| 221 | - "first difference at {:?}", | ||
| 222 | - got.iter().zip(&want).position(|(a, b)| a != b) | ||
| 223 | - ); | ||
| 224 | -} | ||
| 225 | - | ||
| 226 | -#[test] | ||
| 227 | -fn the_decoder_trait_yields_one_frame_per_packet() { | ||
| 228 | - use ec_core::frame::Frame; | ||
| 229 | - use ec_core::packet::{Buf, Packet}; | ||
| 230 | - use ec_core::timebase::TimeBase; | ||
| 231 | - let mut dec = AmrWbDecoder::new(); | ||
| 232 | - // mode 0 frame of zero bits, then a NO_DATA frame | ||
| 233 | - let mut data = vec![0x04u8]; | ||
| 234 | - data.extend([0u8; 17]); | ||
| 235 | - let mut p = Packet::new(0, TimeBase::from_rate(16000), Buf::from_vec(data)); | ||
| 236 | - p.pts = Some(0); | ||
| 237 | - dec.send_packet(&p).unwrap(); | ||
| 238 | - match dec.receive_frame().unwrap() { | ||
| 239 | - Frame::Audio(a) => assert_eq!(a.samples, 320), | ||
| 240 | - _ => panic!("audio expected"), | ||
| 241 | - } | ||
| 242 | - assert!(dec.receive_frame().is_err()); | ||
| 243 | - let p = Packet::new(0, TimeBase::from_rate(16000), Buf::from_vec(vec![0x7C])); | ||
| 244 | - dec.send_packet(&p).unwrap(); | ||
| 245 | - assert!(dec.receive_frame().is_ok()); | ||
| 246 | - // a truncated frame and a reserved type are errors, not panics | ||
| 247 | - assert!(dec.decode(&[0x04, 1, 2]).is_err()); | ||
| 248 | - assert!(dec.decode(&[0x5C]).is_err()); | ||
| 249 | -} | ||
| 250 | - | ||
| 251 | -#[test] | ||
| 252 | -fn arbitrary_bytes_never_panic() { | ||
| 253 | - let mut dec = AmrWbDecoder::new(); | ||
| 254 | - let mut s = 0xdead_beef_u64; | ||
| 255 | - for _ in 0..4000 { | ||
| 256 | - let len = 1 + usize::from(lcg(&mut s)) % 70; | ||
| 257 | - let mut p: Vec<u8> = (0..len).map(|_| lcg(&mut s)).collect(); | ||
| 258 | - // make most packets well formed so the speech paths run | ||
| 259 | - if !lcg(&mut s).is_multiple_of(4) { | ||
| 260 | - let ft = lcg(&mut s) % 10; | ||
| 261 | - p.truncate(1 + PAYLOAD[usize::from(ft)]); | ||
| 262 | - p[0] = (ft << 3) | 4; | ||
| 263 | - p.resize(1 + PAYLOAD[usize::from(ft)], 0x5a); | ||
| 264 | - } | ||
| 265 | - let _ = dec.decode(&p); | ||
| 266 | - } | ||
| 267 | -} | ||