forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

robust.rs214 lines, 7.4 KiBHistoryRawDownload
1//! Robustness: truncated, corrupted and hostile streams must never panic and
2//! must keep the output queue bounded.
3#![allow(clippy::needless_range_loop, clippy::field_reassign_with_default, clippy::too_many_arguments, clippy::type_complexity)]
4
5mod common;
6use common::synth::{SynthCfg, generate};
7use common::*;
8use ec_core::registry::{CodecId, CodecParameters};
9use ec_mpeg2::Mpeg2Decoder;
10
11const MAX_QUEUE: usize = 64;
12
13struct Rng(u64);
14impl Rng {
15 fn next(&mut self) -> u64 {
16 self.0 ^= self.0 << 13;
17 self.0 ^= self.0 >> 7;
18 self.0 ^= self.0 << 17;
19 self.0
20 }
21 fn below(&mut self, n: usize) -> usize {
22 (self.next() % n.max(1) as u64) as usize
23 }
24}
25
26fn streams() -> Vec<Vec<u8>> {
27 [(1u64, false, false), (2, true, false), (3, false, true), (4, true, true)]
28 .into_iter()
29 .map(|(seed, fields, p422)| {
30 generate(&SynthCfg {
31 mb_w: 3,
32 mb_h: 2,
33 chroma422: p422,
34 progressive_sequence: false,
35 frames: 5,
36 seed,
37 fields,
38 heavy: fields,
39 load_matrices: seed % 2 == 0,
40 })
41 })
42 .collect()
43}
44
45/// Decode `data` in chunks of `chunk`; return the frame count. Errors are ignored.
46fn run(data: &[u8], chunk: usize) -> usize {
47 let mut dec = Mpeg2Decoder::new(CodecParameters::new(CodecId::Mpeg2Video)).unwrap();
48 let mut n = 0;
49 for c in data.chunks(chunk.max(1)) {
50 let _ = dec.send_bytes(c, None);
51 while dec.pop_picture().is_some() {
52 n += 1;
53 }
54 }
55 let _ = dec.flush_stream();
56 while dec.pop_picture().is_some() {
57 n += 1;
58 }
59 n
60}
61
62/// Like `run` but never drains until the end: the queue must stay bounded.
63fn run_undrained(data: &[u8], chunk: usize) {
64 let mut dec = Mpeg2Decoder::new(CodecParameters::new(CodecId::Mpeg2Video)).unwrap();
65 for c in data.chunks(chunk.max(1)) {
66 let _ = dec.send_bytes(c, None);
67 }
68 let _ = dec.flush_stream();
69 let mut n = 0;
70 while dec.pop_picture().is_some() {
71 n += 1;
72 }
73 assert!(n <= MAX_QUEUE, "queued {n} frames");
74}
75
76#[test]
77fn truncation_prefixes() {
78 for es in streams() {
79 assert!(run(&es, es.len()) > 0, "clean stream decodes nothing");
80 let step = (es.len() / 40).max(1);
81 for cut in (0..es.len()).step_by(step).chain([es.len() - 1, es.len() - 2]) {
82 run(&es[..cut], 97);
83 run_undrained(&es[..cut], usize::MAX);
84 }
85 }
86}
87
88#[test]
89fn chunking_is_invariant() {
90 for es in streams() {
91 let mk = |chunk: usize| {
92 let a = decode_ours(&es, chunk).expect("clean stream");
93 a.iter().map(|(f, _)| frame_bytes(f)).collect::<Vec<_>>()
94 };
95 let whole = mk(es.len());
96 assert!(!whole.is_empty());
97 assert_eq!(whole, mk(1), "1-byte chunks differ");
98 assert_eq!(whole, mk(7), "7-byte chunks differ");
99 }
100}
101
102#[test]
103fn random_corruptions() {
104 let mut rng = Rng(0x1234_5678_9ABC_DEF1);
105 let all = streams();
106 for i in 0..300 {
107 let mut es = all[i % all.len()].clone();
108 for _ in 0..1 + rng.below(6) {
109 if es.is_empty() {
110 break;
111 }
112 let p = rng.below(es.len());
113 match rng.below(4) {
114 0 => es[p] ^= 1 << rng.below(8),
115 1 => es[p] = rng.next() as u8,
116 2 => {
117 let n = 1 + rng.below(8);
118 es.drain(p..(p + n).min(es.len()));
119 }
120 _ => {
121 for _ in 0..1 + rng.below(8) {
122 es.insert(p, rng.next() as u8);
123 }
124 }
125 }
126 }
127 run(&es, 1 + rng.below(300));
128 run_undrained(&es, usize::MAX);
129 }
130}
131
132#[test]
133fn garbage_is_refused() {
134 let mut rng = Rng(0xDEAD_BEEF_CAFE_F00D);
135 for len in [0usize, 1, 3, 4, 100, 5000, 200_000] {
136 let g: Vec<u8> = (0..len).map(|_| rng.next() as u8).collect();
137 run(&g, 1000);
138 run_undrained(&g, usize::MAX);
139 }
140 // Garbage dense with start codes.
141 let mut g = Vec::new();
142 for _ in 0..2000 {
143 g.extend_from_slice(&[0, 0, 1, rng.next() as u8]);
144 for _ in 0..rng.below(20) {
145 g.push(rng.next() as u8);
146 }
147 }
148 run(&g, 333);
149 run_undrained(&g, usize::MAX);
150}
151
152#[test]
153fn huge_dimensions_are_bounded() {
154 // Sequence header 4095x4095 + sequence_extension adding 3<<12 to both: 16383x16383.
155 let mut es = vec![0, 0, 1, 0xB3, 0xFF, 0xFF, 0xFF, 0x13, 0xFF, 0xFF, 0xE0, 0x18];
156 // sequence_extension: id=1, profile/level, progressive, chroma 4:2:0, size ext 3/3.
157 es.extend_from_slice(&[0, 0, 1, 0xB5, 0x14, 0x8A, 0x00, 0x01, 0x00, 0x00]);
158 es.extend_from_slice(&[0, 0, 1, 0xB5, 0x14, 0x8F, 0xFF, 0x01, 0x00, 0x00]);
159 // GOP + picture header (I) + a slice, repeated.
160 for _ in 0..3 {
161 es.extend_from_slice(&[0, 0, 1, 0xB8, 0, 0x08, 0, 0x40]);
162 es.extend_from_slice(&[0, 0, 1, 0x00, 0x00, 0x0F, 0xFF, 0xF8]);
163 es.extend_from_slice(&[0, 0, 1, 0xB5, 0x8F, 0xFF, 0xF3, 0x41, 0x00]);
164 es.extend_from_slice(&[0, 0, 1, 0x01, 0x10, 0x00, 0x00, 0x00]);
165 }
166 let mut dec = Mpeg2Decoder::new(CodecParameters::new(CodecId::Mpeg2Video)).unwrap();
167 let r = dec.send_bytes(&es, None);
168 let _ = dec.flush_stream();
169 let mut n = 0;
170 while let Some((f, _)) = dec.pop_picture() {
171 assert!(u64::from(f.width) * u64::from(f.height) <= 8192 * 4352);
172 n += 1;
173 }
174 assert!(n <= MAX_QUEUE);
175 if let Some(seq) = dec.sequence() {
176 eprintln!("sequence {}x{} (send: {:?})", seq.width, seq.height, r.is_ok());
177 }
178 // Also at the 12-bit maximum without an extension, and with the max-dimension edge.
179 for (w, h) in [(4095u32, 4095u32), (8192, 8192), (16383, 1), (1, 16383)] {
180 let mut s = vec![0, 0, 1, 0xB3, (w >> 4) as u8, (((w & 15) << 4) | (h >> 8)) as u8, h as u8, 0x13, 0xFF, 0xFF, 0xE0, 0x18];
181 s.extend_from_slice(&[0, 0, 1, 0x00, 0x00, 0x0F, 0xFF, 0xF8, 0, 0, 1, 0x01, 0x10, 0, 0]);
182 run(&s, usize::MAX);
183 run_undrained(&s, 5);
184 }
185}
186
187/// `decode_mpeg2` panic: a sequence extension changed the MB-row count (9 to 10 at 176x144)
188/// without changing the size, so pictures allocated under the old geometry were decoded under
189/// the new one and a macroblock row was written past the end of the plane. The decoder must
190/// refuse the damage or conceal it and mark the frame corrupt, never panic.
191#[test]
192fn mb_height_change_without_resize_is_concealed() {
193 let data = include_bytes!("data/fuzz/decode_mpeg2-mb-height-change.m2v");
194 let mut dec = Mpeg2Decoder::new(CodecParameters::new(CodecId::Mpeg2Video)).unwrap();
195 let mut failed = dec.send_bytes(data, None).is_err();
196 failed |= dec.flush_stream().is_err();
197 let mut corrupt = false;
198 while let Some((_, info)) = dec.pop_picture() {
199 corrupt |= info.corrupt;
200 }
201 assert!(failed || corrupt, "damage must surface as an error or a corrupt frame");
202}
203
204/// Writes the synthetic streams as fuzz seeds:
205/// `EC_SEED_DIR=crates/ec-mpeg2/fuzz/corpus/decode_mpeg2 cargo test --test robust -- --ignored dump_seeds`
206#[test]
207#[ignore]
208fn dump_seeds() {
209 let Some(dir) = std::env::var_os("EC_SEED_DIR") else { return };
210 std::fs::create_dir_all(&dir).unwrap();
211 for (i, s) in streams().iter().enumerate() {
212 std::fs::write(std::path::Path::new(&dir).join(format!("syn{i}.m2v")), s).unwrap();
213 }
214}