forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

malformed_input.rs86 lines, 2.8 KiBHistoryRawDownload
1//! Malformed input must surface as `Err`, never as a panic.
2//!
3//! The packets here are random byte strings and truncations of them, generated from
4//! a fixed-seed LCG so a failure reproduces exactly. The TOC byte is random too, so the
5//! SILK, CELT and hybrid paths, every bandwidth and every frame-count code are reached.
6
7use std::panic::{catch_unwind, AssertUnwindSafe};
8
9use ec_opus::Decoder;
10
11/// Fixed-seed 64-bit LCG (Knuth's MMIX constants).
12struct Lcg(u64);
13
14impl Lcg {
15 fn next_u32(&mut self) -> u32 {
16 self.0 = self
17 .0
18 .wrapping_mul(6_364_136_223_846_793_005)
19 .wrapping_add(1_442_695_040_888_963_407);
20 (self.0 >> 33) as u32
21 }
22
23 /// Uniform-ish value in `lo..=hi`.
24 fn range(&mut self, lo: usize, hi: usize) -> usize {
25 lo + (self.next_u32() as usize) % (hi - lo + 1)
26 }
27
28 fn bytes(&mut self, len: usize) -> Vec<u8> {
29 (0..len).map(|_| self.next_u32() as u8).collect()
30 }
31}
32
33fn hex(data: &[u8]) -> String {
34 data.iter().map(|b| format!("{b:02x}")).collect()
35}
36
37/// Decodes `packet` on a fresh decoder and reports whether it panicked.
38fn decode_must_not_panic(sample_rate: u32, channels: usize, packet: &[u8]) {
39 let outcome = catch_unwind(AssertUnwindSafe(|| {
40 let mut dec = Decoder::new(sample_rate, channels).expect("decoder construction");
41 // 120 ms at 48 kHz is the largest possible output per packet.
42 let mut out = vec![0f32; 5760 * channels];
43 let _ = dec.decode_float(packet, &mut out);
44 }));
45 assert!(
46 outcome.is_ok(),
47 "decoder panicked on {sample_rate} Hz / {channels} ch packet: {}",
48 hex(packet)
49 );
50}
51
52#[test]
53fn random_packets_never_panic() {
54 let mut rng = Lcg(0x5eed_0bad_cafe_f00d);
55 let rates = [48_000u32, 24_000, 16_000, 12_000, 8_000];
56 for _ in 0..1000 {
57 let len = rng.range(1, 1500);
58 let packet = rng.bytes(len);
59 let rate = rates[rng.range(0, rates.len() - 1)];
60 let channels = rng.range(1, 2);
61 decode_must_not_panic(rate, channels, &packet);
62 }
63}
64
65#[test]
66fn truncated_packets_never_panic() {
67 let mut rng = Lcg(0x7247_4e43_4154_4544);
68 for _ in 0..1000 {
69 let len = rng.range(1, 1500);
70 let packet = rng.bytes(len);
71 // Every prefix length of a shorter random packet, so the cut lands on each
72 // header and range-coded boundary the decoder reads.
73 let cut = rng.range(0, len - 1);
74 decode_must_not_panic(48_000, 2, &packet[..cut]);
75 decode_must_not_panic(48_000, 1, &packet[..cut]);
76 }
77}
78
79#[test]
80fn empty_and_single_byte_packets_never_panic() {
81 decode_must_not_panic(48_000, 2, &[]);
82 for toc in 0..=255u8 {
83 decode_must_not_panic(48_000, 1, &[toc]);
84 decode_must_not_panic(48_000, 2, &[toc]);
85 }
86}