forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

encode_roundtrip.rs53 lines, 1.8 KiBHistoryRawDownload
1#![no_main]
2
3use ec_flac::decode::FlacReader;
4use ec_flac::encode::{EncoderConfig, encode};
5use libfuzzer_sys::fuzz_target;
6
7// Header bytes pick the shape: channels, bit depth, sample rate, block size. The
8// rest is i32 samples, each clamped into the bit depth's range. Lossless means the
9// decode equals the input.
10fuzz_target!(|data: &[u8]| {
11 if data.len() < 8 {
12 return;
13 }
14 let channels = usize::from(data[0] % 8) + 1;
15 let bits = u32::from(data[1] % 29) + 4;
16 let rate = u32::from(u16::from_le_bytes([data[2], data[3]])) % 655_350 + 1;
17 let block_size = usize::from(u16::from_le_bytes([data[4], data[5]])) % 4096 + 16;
18 let config = EncoderConfig {
19 block_size,
20 ..EncoderConfig::default()
21 };
22
23 let (low, high) = match bits {
24 32 => (i32::MIN as i64, i32::MAX as i64),
25 n => (-(1i64 << (n - 1)), (1i64 << (n - 1)) - 1),
26 };
27 let body = &data[6..];
28 let frames = body.len() / 4 / channels;
29 if frames == 0 {
30 return;
31 }
32 let samples: Vec<i32> = body
33 .chunks_exact(4)
34 .take(frames * channels)
35 .map(|b| i64::from(i32::from_le_bytes([b[0], b[1], b[2], b[3]])).clamp(low, high) as i32)
36 .collect();
37
38 let Ok(stream) = encode(&config, &samples, channels, bits, rate) else {
39 return;
40 };
41 let mut reader = FlacReader::new(&stream).expect("encoder output opens");
42 let decoded = reader.decode_all().expect("encoder output decodes");
43 assert_eq!(decoded.bits_per_sample, bits);
44 assert_eq!(decoded.sample_rate, rate);
45 assert_eq!(decoded.channels.len(), channels);
46 let mut got = Vec::with_capacity(samples.len());
47 for i in 0..frames {
48 for plane in &decoded.channels {
49 got.push(plane[i]);
50 }
51 }
52 assert!(got == samples, "FLAC roundtrip mismatch ({channels}ch {bits}bit {rate}Hz)");
53});