forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

no_panic.rs166 lines, 5.6 KiBHistoryRawDownload
1//! No-panic gate for the decode path: malformed input must come back as `Err`,
2//! never as a panic. Covers truncated and byte-corrupted copies of the committed
3//! ADTS fixtures, plus random ADTS-looking frames (valid sync header, random payload).
4//!
5//! Every input is decoded inside `catch_unwind` so a panic reports which input
6//! produced it instead of aborting the whole run.
7
8use std::panic::{catch_unwind, AssertUnwindSafe};
9use std::path::{Path, PathBuf};
10
11use ec_aac::AacDecoder;
12
13const ADTS_FIXTURES: [&str; 6] = [
14 "aac-adts-mono-44100.aac",
15 "aac-adts-mono-48000.aac",
16 "aac-adts-stereo-44100.aac",
17 "aac-adts-stereo-48000.aac",
18 "aac-adts-5.1-44100.aac",
19 "aac-adts-5.1-48000.aac",
20];
21
22/// Fixed seed so a failure reproduces exactly.
23const SEED: u64 = 0x5EED_AAC0_0D15_EA5E;
24
25/// Small xorshift64 generator; the crate has no RNG dev-dependency.
26struct Rng(u64);
27
28impl Rng {
29 fn next_u64(&mut self) -> u64 {
30 let mut x = self.0;
31 x ^= x << 13;
32 x ^= x >> 7;
33 x ^= x << 17;
34 self.0 = x;
35 x
36 }
37
38 fn below(&mut self, n: u64) -> u64 {
39 self.next_u64() % n
40 }
41}
42
43fn audio_dir() -> PathBuf {
44 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/audio")
45}
46
47/// Decodes one packet with a fresh decoder. Returns false if it panicked.
48fn decode_no_panic(label: &str, packet: &[u8]) -> bool {
49 let outcome = catch_unwind(AssertUnwindSafe(|| {
50 let mut dec = AacDecoder::new();
51 let _ = dec.decode(packet, None);
52 }));
53 if outcome.is_err() {
54 eprintln!("PANIC: {label} ({} bytes)", packet.len());
55 return false;
56 }
57 true
58}
59
60/// Byte offsets of ADTS frame starts, walked with each header's frame_length.
61fn adts_frame_starts(data: &[u8]) -> Vec<usize> {
62 let mut starts = Vec::new();
63 let mut at = 0usize;
64 while at + 7 <= data.len() && data[at] == 0xFF && data[at + 1] & 0xF6 == 0xF0 {
65 starts.push(at);
66 let len = (((data[at + 3] & 0x03) as usize) << 11)
67 | ((data[at + 4] as usize) << 3)
68 | ((data[at + 5] as usize) >> 5);
69 if len < 7 {
70 break;
71 }
72 at += len;
73 }
74 starts
75}
76
77#[test]
78fn fixtures_truncated_and_corrupted_never_panic() {
79 let dir = audio_dir();
80 let mut found = 0usize;
81 let mut failures: Vec<String> = Vec::new();
82 let mut rng = Rng(SEED);
83
84 for name in ADTS_FIXTURES {
85 let path = dir.join(name);
86 let data = match std::fs::read(&path) {
87 Ok(d) => d,
88 Err(_) => {
89 if std::env::var_os("EC_REQUIRE_FIXTURES").is_some() {
90 panic!(
91 "EC_REQUIRE_FIXTURES=1 but fixture {} is absent -- regenerate with: scripts/gen-fixtures.sh",
92 path.display()
93 );
94 }
95 eprintln!("SKIP: fixture {} absent", path.display());
96 continue;
97 }
98 };
99 found += 1;
100 assert!(!adts_frame_starts(&data).is_empty(), "{name} is not an ADTS stream");
101
102 // Ten truncation points spread across the file (never the full length).
103 for i in 1..=10usize {
104 let cut = data.len() * i / 11;
105 let label = format!("{name} truncated at {cut}");
106 if !decode_no_panic(&label, &data[..cut]) {
107 failures.push(label);
108 }
109 }
110
111 // Fifty single-byte corruptions at seeded positions with seeded values.
112 for i in 0..50 {
113 let pos = rng.below(data.len() as u64) as usize;
114 let mut value = rng.below(256) as u8;
115 if value == data[pos] {
116 value = value.wrapping_add(1);
117 }
118 let mut copy = data.clone();
119 copy[pos] = value;
120 let label = format!("{name} corruption #{i} at byte {pos} -> {value:#04x}");
121 if !decode_no_panic(&label, &copy) {
122 failures.push(label);
123 }
124 }
125 }
126
127 if found == 0 {
128 if std::env::var_os("EC_REQUIRE_FIXTURES").is_some() {
129 panic!("no ADTS fixtures found under {}", dir.display());
130 }
131 eprintln!("SKIP: no ADTS fixtures under {}", dir.display());
132 }
133 assert!(failures.is_empty(), "{} inputs panicked: {:?}", failures.len(), failures);
134}
135
136#[test]
137fn random_adts_frames_never_panic() {
138 let mut rng = Rng(SEED ^ 0xAD75);
139 let mut failures: Vec<String> = Vec::new();
140
141 for i in 0..500usize {
142 // Valid syncword, MPEG-4, layer 0, protection absent (7-byte header).
143 let sf_index = rng.below(13) as u8; // 13..=15 are reserved; keep the rate table in range
144 let channel_config = rng.below(8) as u8;
145 let payload_len = rng.below(600) as usize;
146 let frame_length = 7 + payload_len;
147 let object_type_bits = rng.below(4) as u8; // profile field; decoder maps it to object type
148 let mut frame = vec![0u8; frame_length];
149 frame[0] = 0xFF;
150 frame[1] = 0xF1;
151 frame[2] = (object_type_bits << 6) | (sf_index << 2) | ((channel_config >> 2) & 0x01);
152 frame[3] = ((channel_config & 0x03) << 6) | ((frame_length >> 11) as u8 & 0x03);
153 frame[4] = (frame_length >> 3) as u8;
154 frame[5] = (((frame_length & 0x07) as u8) << 5) | 0x1F;
155 frame[6] = 0xFC;
156 for b in frame.iter_mut().skip(7) {
157 *b = rng.below(256) as u8;
158 }
159 let label = format!("random ADTS frame #{i} (sf {sf_index}, ch {channel_config}, {frame_length} bytes)");
160 if !decode_no_panic(&label, &frame) {
161 failures.push(label);
162 }
163 }
164
165 assert!(failures.is_empty(), "{} random frames panicked: {:?}", failures.len(), failures);
166}