forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

oracle.rs174 lines, 6.1 KiBHistoryRawDownload
1//! ALAC is lossless, so the oracle is exact: every fixture must decode to the
2//! same bytes ffmpeg's decoder produces, sample for sample, in the same channel
3//! order.
4//!
5//! Fixtures come from `scripts/gen-fixtures.sh`; a missing one skips its row
6//! rather than failing, so a checkout without generated fixtures still builds.
7
8use std::fs::File;
9use std::io::BufReader;
10use std::path::{Path, PathBuf};
11use std::process::Command;
12
13use ec_alac::{AlacDecoder, MagicCookie};
14use ec_core::registry::{CodecId, Demuxer};
15
16fn fixtures() -> PathBuf {
17 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/audio")
18}
19
20/// Every sample of `path`'s ALAC track, interleaved, as this crate decodes it.
21fn decode(path: &Path) -> (MagicCookie, Vec<i32>) {
22 let mut demuxer =
23 ec_mp4::Mp4Demuxer::new(BufReader::new(File::open(path).expect("open"))).expect("mp4");
24 let stream = demuxer
25 .streams()
26 .iter()
27 .find(|s| s.params.codec == CodecId::Alac)
28 .expect("an ALAC track")
29 .clone();
30 let mut decoder = AlacDecoder::from_parameters(stream.params.clone()).expect("cookie");
31 let cookie = *decoder.cookie();
32 let mut out = Vec::new();
33 loop {
34 match demuxer.next_packet() {
35 Ok(packet) if packet.stream != stream.index => continue,
36 Ok(packet) => out.extend_from_slice(decoder.decode(&packet.data).expect("decode")),
37 Err(e) if e.is_eof() => break,
38 Err(e) => panic!("{}: {e}", path.display()),
39 }
40 }
41 (cookie, out)
42}
43
44/// ffmpeg's own decode of the same file, in the raw format `fmt` names.
45fn ffmpeg(path: &Path, fmt: &str) -> Vec<u8> {
46 let out = Command::new("ffmpeg")
47 .args(["-nostdin", "-v", "error", "-i"])
48 .arg(path)
49 .args(["-f", fmt, "-"])
50 .output()
51 .expect("ffmpeg");
52 assert!(
53 out.status.success(),
54 "ffmpeg {}: {}",
55 path.display(),
56 String::from_utf8_lossy(&out.stderr)
57 );
58 out.stdout
59}
60
61#[test]
62fn every_alac_fixture_decodes_bit_exactly() {
63 let mut checked = 0;
64 for name in [
65 "alac-mp4-mono-44100.m4a",
66 "alac-mp4-mono-48000.m4a",
67 "alac-mp4-stereo-44100.m4a",
68 "alac-mp4-stereo-48000.m4a",
69 "alac-mp4-5.1-44100.m4a",
70 "alac-mp4-5.1-48000.m4a",
71 "alac24-mp4-stereo-48000.m4a",
72 "alac24-mp4-5.1-48000.m4a",
73 ] {
74 let path = fixtures().join(name);
75 if !path.exists() {
76 continue;
77 }
78 let (cookie, got) = decode(&path);
79 let (fmt, width) = match cookie.bit_depth <= 16 {
80 true => ("s16le", 2),
81 false => ("s32le", 4),
82 };
83 let want = ffmpeg(&path, fmt);
84 assert_eq!(
85 got.len(),
86 want.len() / width,
87 "{name}: {} samples decoded, ffmpeg says {}",
88 got.len(),
89 want.len() / width
90 );
91 let mine: Vec<u8> = got
92 .iter()
93 .flat_map(|&s| match width {
94 2 => (s as i16).to_le_bytes().to_vec(),
95 _ => s.to_le_bytes().to_vec(),
96 })
97 .collect();
98 let bad = mine
99 .chunks_exact(width)
100 .zip(want.chunks_exact(width))
101 .position(|(a, b)| a != b);
102 assert_eq!(bad, None, "{name}: first differing sample");
103 checked += 1;
104 }
105 assert!(checked > 0, "no ALAC fixtures found — run gen-fixtures.sh");
106 eprintln!("alac oracle: {checked} fixtures bit-exact vs ffmpeg");
107}
108
109/// A truncated frame is an error, not a panic — the fuzz floor in miniature.
110#[test]
111fn truncated_frames_are_refused_without_panicking() {
112 let path = fixtures().join("alac-mp4-stereo-44100.m4a");
113 if !path.exists() {
114 return;
115 }
116 let mut demuxer =
117 ec_mp4::Mp4Demuxer::new(BufReader::new(File::open(&path).expect("open"))).expect("mp4");
118 let stream = demuxer.streams()[0].clone();
119 let mut decoder = AlacDecoder::from_parameters(stream.params).expect("cookie");
120 let packet = demuxer.next_packet().expect("a packet");
121 for len in 0..packet.data.len().min(64) {
122 let _ = decoder.decode(&packet.data[..len]);
123 }
124 // And it still decodes the whole frame afterwards.
125 assert!(
126 !decoder
127 .decode(&packet.data)
128 .expect("whole frame")
129 .is_empty()
130 );
131}
132
133/// A 24-bit tone with a dithered low byte, encoded by the reference encoder:
134/// its first residuals escape to raw 24-bit values — a Golomb shape none of
135/// the checked-in fixtures (16-bit, or 24-bit with a shifted low byte) carry.
136#[test]
137fn reference_encoded_24_bit_tone_decodes_bit_exactly() {
138 if Command::new("ffmpeg").arg("-version").output().is_err() {
139 eprintln!("ffmpeg absent — skipping");
140 return;
141 }
142 let dir = std::env::temp_dir().join(format!("ec-alac-tone-{}", std::process::id()));
143 std::fs::create_dir_all(&dir).expect("tmp");
144 let raw = dir.join("tone.raw");
145 let m4a = dir.join("tone.m4a");
146 let mut seed = 0x0bad_cafeu32;
147 let pcm: Vec<u8> = (0..48_000 * 2)
148 .flat_map(|i| {
149 seed ^= seed << 13;
150 seed ^= seed >> 17;
151 seed ^= seed << 5;
152 let s = ((2000.0 * (i as f64 / 64.0).sin()) as i32) << 8 | (seed & 0xff) as i32;
153 s.to_le_bytes()
154 })
155 .collect();
156 std::fs::write(&raw, &pcm).expect("raw");
157 let enc = Command::new("ffmpeg")
158 .args(["-nostdin", "-y", "-v", "error", "-f", "s32le", "-ar", "48000", "-ac", "2", "-i"])
159 .arg(&raw)
160 .args(["-c:a", "alac", "-sample_fmt", "s32p"])
161 .arg(&m4a)
162 .output()
163 .expect("ffmpeg");
164 assert!(enc.status.success(), "{}", String::from_utf8_lossy(&enc.stderr));
165
166 let (cookie, got) = decode(&m4a);
167 assert_eq!(cookie.bit_depth, 24);
168 let shift = cookie.container_shift();
169 let got: Vec<u8> = got.iter().flat_map(|&s| (s >> shift << 8).to_le_bytes()).collect();
170 let want = ffmpeg(&m4a, "s32le");
171 std::fs::remove_dir_all(&dir).ok();
172 assert_eq!(got.len(), want.len());
173 assert!(got == want, "reference-encoded 24-bit tone: our decode differs from the reference decode");
174}