forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

oracle.rs245 lines, 8.2 KiBHistoryRawDownload
1//! Bit-exact oracle: fixtures are generated with ffmpeg from synthetic lavfi
2//! sources, decoded here and by ffmpeg (`-f s16le`), and must match exactly.
3//!
4//! Without ffmpeg the tests skip loudly; with `EC_REQUIRE_FIXTURES=1` a
5//! missing ffmpeg is a failure.
6
7use std::fs::File;
8use std::io::BufReader;
9use std::path::{Path, PathBuf};
10use std::process::Command;
11
12use ec_core::registry::{AudioParameters, CodecId, CodecParameters, Demuxer, MediaParameters};
13use ec_core::frame::{ChannelLayout, SampleFormat};
14use ec_core::packet::Buf;
15use ec_pcm_ext::PcmExtDecoder;
16
17fn have_ffmpeg() -> bool {
18 let ok = Command::new("ffmpeg").arg("-version").output().is_ok();
19 if !ok {
20 assert!(
21 std::env::var_os("EC_REQUIRE_FIXTURES").is_none(),
22 "EC_REQUIRE_FIXTURES=1 but ffmpeg is not installed"
23 );
24 eprintln!("ffmpeg absent - skipping");
25 }
26 ok
27}
28
29fn tmpdir(tag: &str) -> PathBuf {
30 let d = std::env::temp_dir().join(format!("ec-pcm-ext-{tag}-{}", std::process::id()));
31 std::fs::create_dir_all(&d).expect("tmp");
32 d
33}
34
35/// Synthetic source: `kind` 0 = tones with a chirp, 1 = noise.
36fn source(kind: u32, channels: u32, rate: u32) -> String {
37 match (kind, channels) {
38 (0, 1) => format!(
39 "aevalsrc='0.6*sin(2*PI*440*t)+0.25*sin(2*PI*1234*t*t)':s={rate}:d=1.3"
40 ),
41 (0, _) => format!(
42 "aevalsrc='0.6*sin(2*PI*440*t)+0.25*sin(2*PI*1234*t*t)|0.5*sin(2*PI*660*t)':s={rate}:d=1.3"
43 ),
44 (_, 1) => format!("anoisesrc=d=1.3:r={rate}:a=0.9:seed=7"),
45 _ => format!(
46 "anoisesrc=d=1.3:r={rate}:a=0.9:seed=7[a];anoisesrc=d=1.3:r={rate}:a=0.5:seed=9[b];[a][b]amerge"
47 ),
48 }
49}
50
51fn make(dir: &Path, name: &str, codec: &str, kind: u32, channels: u32, rate: u32) -> PathBuf {
52 let out = dir.join(name);
53 let src = source(kind, channels, rate);
54 let mut cmd = Command::new("ffmpeg");
55 cmd.args(["-nostdin", "-y", "-v", "error", "-f", "lavfi"]);
56 if src.contains(';') {
57 cmd.args(["-i", "anullsrc=d=0.01", "-filter_complex"]).arg(&src);
58 } else {
59 cmd.arg("-i").arg(&src);
60 }
61 cmd.args(["-ac", &channels.to_string(), "-c:a", codec]).arg(&out);
62 let o = cmd.output().expect("ffmpeg");
63 assert!(o.status.success(), "{name}: {}", String::from_utf8_lossy(&o.stderr));
64 out
65}
66
67fn ffmpeg_pcm(path: &Path) -> Vec<u8> {
68 let o = Command::new("ffmpeg")
69 .args(["-nostdin", "-v", "error", "-i"])
70 .arg(path)
71 .args(["-f", "s16le", "-"])
72 .output()
73 .expect("ffmpeg");
74 assert!(o.status.success(), "{}", String::from_utf8_lossy(&o.stderr));
75 o.stdout
76}
77
78fn params(codec: CodecId, channels: usize, rate: u32, extra: &[u8]) -> CodecParameters {
79 let mut p = CodecParameters::new(codec);
80 p.media = MediaParameters::Audio(AudioParameters {
81 sample_rate: rate,
82 layout: ChannelLayout::from_count(channels),
83 format: Some(SampleFormat::S16),
84 bits_per_sample: Some(16),
85 });
86 if !extra.is_empty() {
87 p.extradata = Some(Buf::copy_from_slice(extra));
88 }
89 p
90}
91
92fn to_bytes(s: &[i16]) -> Vec<u8> {
93 s.iter().flat_map(|v| v.to_le_bytes()).collect()
94}
95
96fn decode_demuxer(mut d: impl Demuxer, want: CodecId) -> Vec<u8> {
97 let st = d
98 .streams()
99 .iter()
100 .find(|s| s.params.codec == want)
101 .unwrap_or_else(|| panic!("no {want:?} stream"))
102 .clone();
103 let mut dec = PcmExtDecoder::from_parameters(st.params.clone()).expect("decoder");
104 let mut out = Vec::new();
105 loop {
106 match d.next_packet() {
107 Ok(p) if p.stream != st.index => {}
108 Ok(p) => out.extend(to_bytes(dec.decode(&p.data).expect("decode"))),
109 Err(e) if e.is_eof() => break,
110 Err(e) => panic!("{e}"),
111 }
112 }
113 out
114}
115
116fn decode_wav(path: &Path) -> Vec<u8> {
117 let mut r = ec_riff::WavReader::new(BufReader::new(File::open(path).expect("open"))).expect("wav");
118 let c = r.compressed().expect("compressed wav").clone();
119 let spec = r.spec();
120 let codec = ec_riff::WavCompressed::codec_of(c.tag).expect("codec");
121 let mut dec = PcmExtDecoder::from_parameters(params(
122 codec,
123 usize::from(spec.channels),
124 spec.sample_rate,
125 &c.extra,
126 ))
127 .expect("decoder");
128 let data = r.read_data_bytes().expect("data");
129 let step = match c.tag {
130 0x0006 | 0x0007 => 4096,
131 _ => usize::from(c.block_align),
132 };
133 let mut out = Vec::new();
134 for chunk in data.chunks(step) {
135 out.extend(to_bytes(dec.decode(chunk).expect("decode")));
136 }
137 out
138}
139
140fn decode_avi(path: &Path, want: CodecId) -> Vec<u8> {
141 let d = ec_riff::AviDemuxer::new(BufReader::new(File::open(path).expect("open"))).expect("avi");
142 decode_demuxer(d, want)
143}
144
145fn decode_mov(path: &Path, want: CodecId) -> Vec<u8> {
146 let d = ec_mp4::Mp4Demuxer::new(BufReader::new(File::open(path).expect("open"))).expect("mov");
147 decode_demuxer(d, want)
148}
149
150fn check(name: &str, got: Vec<u8>, path: &Path) {
151 let want = ffmpeg_pcm(path);
152 assert_eq!(got.len(), want.len(), "{name}: byte count");
153 let bad = got.chunks(2).zip(want.chunks(2)).position(|(a, b)| a != b);
154 assert_eq!(bad, None, "{name}: first differing sample");
155 assert!(!got.is_empty(), "{name}: empty");
156}
157
158#[test]
159fn every_format_is_bit_exact_against_ffmpeg() {
160 if !have_ffmpeg() {
161 return;
162 }
163 let dir = tmpdir("oracle");
164 let mut n = 0;
165 // (ffmpeg encoder, codec id, containers)
166 let cases: [(&str, CodecId, &[&str]); 5] = [
167 ("adpcm_ima_wav", CodecId::ImaAdpcmWav, &["wav", "avi"]),
168 ("adpcm_ms", CodecId::MsAdpcm, &["wav", "avi"]),
169 ("adpcm_ima_qt", CodecId::ImaAdpcmQt, &["mov"]),
170 ("pcm_alaw", CodecId::PcmAlaw, &["wav", "avi", "mov"]),
171 ("pcm_mulaw", CodecId::PcmMulaw, &["wav", "avi", "mov"]),
172 ];
173 for (enc, codec, containers) in cases {
174 for ext in containers {
175 for channels in [1u32, 2] {
176 for (kind, rate) in [(0u32, 22050u32), (1, 44100), (0, 8000)] {
177 let name = format!("{enc}-{ext}-{channels}ch-{kind}-{rate}.{ext}");
178 let path = make(&dir, &name, enc, kind, channels, rate);
179 let got = match *ext {
180 "wav" => decode_wav(&path),
181 "avi" => decode_avi(&path, codec),
182 _ => decode_mov(&path, codec),
183 };
184 check(&name, got, &path);
185 n += 1;
186 }
187 }
188 }
189 }
190 std::fs::remove_dir_all(&dir).ok();
191 eprintln!("pcm-ext oracle: {n} fixtures bit-exact vs ffmpeg");
192}
193
194/// All 256 G.711 code points decode like ffmpeg's tables.
195#[test]
196fn g711_tables_match_ffmpeg() {
197 if !have_ffmpeg() {
198 return;
199 }
200 let dir = tmpdir("g711");
201 let raw: Vec<u8> = (0..=255u8).collect();
202 for (fmt, codec) in [("alaw", CodecId::PcmAlaw), ("mulaw", CodecId::PcmMulaw)] {
203 let p = dir.join(format!("all.{fmt}"));
204 std::fs::write(&p, &raw).expect("write");
205 let o = Command::new("ffmpeg")
206 .args(["-nostdin", "-v", "error", "-f", fmt, "-ar", "8000", "-ac", "1", "-i"])
207 .arg(&p)
208 .args(["-f", "s16le", "-"])
209 .output()
210 .expect("ffmpeg");
211 assert!(o.status.success());
212 let mut dec = PcmExtDecoder::from_parameters(params(codec, 1, 8000, &[])).expect("dec");
213 assert_eq!(to_bytes(dec.decode(&raw).expect("decode")), o.stdout, "{fmt}");
214 }
215 std::fs::remove_dir_all(&dir).ok();
216}
217
218/// Garbage and truncation are errors or short output, never a panic.
219#[test]
220fn garbage_does_not_panic() {
221 let mut seed = 0x1234_5678u32;
222 let mut next = || {
223 seed ^= seed << 13;
224 seed ^= seed >> 17;
225 seed ^= seed << 5;
226 seed
227 };
228 for codec in [
229 CodecId::ImaAdpcmWav,
230 CodecId::MsAdpcm,
231 CodecId::ImaAdpcmQt,
232 CodecId::PcmAlaw,
233 CodecId::PcmMulaw,
234 ] {
235 for ch in [1usize, 2, 3] {
236 let Ok(mut d) = PcmExtDecoder::from_parameters(params(codec, ch, 8000, &[])) else {
237 continue;
238 };
239 for len in 0..600 {
240 let data: Vec<u8> = (0..len).map(|_| next() as u8).collect();
241 let _ = d.decode(&data);
242 }
243 }
244 }
245}