| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | use std::panic::{catch_unwind, AssertUnwindSafe}; |
| 8 | |
| 9 | use ec_opus::Decoder; |
| 10 | |
| 11 | |
| 12 | struct Lcg(u64); |
| 13 | |
| 14 | impl 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 | |
| 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 | |
| 33 | fn hex(data: &[u8]) -> String { |
| 34 | data.iter().map(|b| format!("{b:02x}")).collect() |
| 35 | } |
| 36 | |
| 37 | |
| 38 | fn 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 | |
| 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] |
| 53 | fn 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] |
| 66 | fn 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 | |
| 72 | |
| 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] |
| 80 | fn 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 | } |