-
Notifications
You must be signed in to change notification settings - Fork 611
/
reference_images.rs
351 lines (308 loc) · 12.1 KB
/
reference_images.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
//! Compares the decoding results with reference renderings.
extern crate crc32fast;
extern crate glob;
extern crate image;
use std::fs;
use std::io;
use std::path::PathBuf;
use std::u32;
use crc32fast::Hasher as Crc32;
const BASE_PATH: [&str; 2] = [".", "tests"];
const IMAGE_DIR: &str = "images";
const OUTPUT_DIR: &str = "output";
const REFERENCE_DIR: &str = "reference";
fn process_images<F>(dir: &str, input_decoder: Option<&str>, func: F)
where
F: Fn(&PathBuf, PathBuf, &str),
{
let base: PathBuf = BASE_PATH.iter().collect();
let decoders = &["tga", "tiff", "png", "gif", "bmp", "ico", "jpg", "hdr", "pbm", "webp"];
for decoder in decoders {
let mut path = base.clone();
path.push(dir);
path.push(decoder);
path.push("**");
path.push(
"*.".to_string() + match input_decoder {
Some(val) => val,
None => decoder,
},
);
let pattern = &*format!("{}", path.display());
for path in glob::glob(pattern).unwrap().filter_map(Result::ok) {
func(&base, path, decoder)
}
}
}
#[cfg(feature = "png")]
#[test]
fn render_images() {
process_images(IMAGE_DIR, None, |base, path, decoder| {
println!("render_images {}", path.display());
let img = match image::open(&path) {
Ok(img) => img.to_rgba8(),
// Do not fail on unsupported error
// This might happen because the testsuite contains unsupported images
// or because a specific decoder included via a feature.
Err(image::ImageError::Unsupported(e)) => {
println!("UNSUPPORTED {}: {}", path.display(), e);
return;
}
Err(err) => panic!(format!("decoding of {:?} failed with: {}", path, err)),
};
let mut crc = Crc32::new();
crc.update(&*img);
let (filename, testsuite) = {
let mut path: Vec<_> = path.components().collect();
(path.pop().unwrap(), path.pop().unwrap())
};
let mut out_path = base.clone();
out_path.push(OUTPUT_DIR);
out_path.push(decoder);
out_path.push(testsuite.as_os_str());
fs::create_dir_all(&out_path).unwrap();
out_path.push(format!(
"{}.{}.{}",
filename.as_os_str().to_str().unwrap(),
format!("{:x}", crc.finalize()),
"png"
));
img.save(out_path).unwrap();
})
}
/// Describes a single test case of `check_references`.
struct ReferenceTestCase {
orig_filename: String,
crc: u32,
kind: ReferenceTestKind,
}
enum ReferenceTestKind {
/// The test image is loaded using `image::open`, and the result is compared
/// against the reference image.
SingleImage,
/// From the test image file, a single frame is extracted using a fitting animation decoder and
/// the result is compared against the reference image.
AnimatedFrame {
/// A zero-based frame number.
frame: usize,
},
}
impl std::str::FromStr for ReferenceTestCase {
type Err = &'static str;
/// Construct `ReferenceTestCase` from the file name of a reference
/// image.
fn from_str(filename: &str) -> Result<Self, Self::Err> {
let mut filename_parts = filename.rsplitn(3, '.');
// Ignore the file extension
filename_parts.next().unwrap();
// The penultimate part of `filename_parts` represents the metadata,
// describing the test type and other details.
let meta_str = filename_parts.next().ok_or("missing metadata part")?;
let meta = meta_str.split('_').collect::<Vec<_>>();
let (crc, kind);
if meta.len() == 1 {
// `CRC`
crc = parse_crc(&meta[0]).ok_or("malformed CRC")?;
kind = ReferenceTestKind::SingleImage;
} else if meta.len() == 3 && meta[0] == "anim" {
// `anim_FRAME_CRC`
crc = parse_crc(&meta[2]).ok_or("malformed CRC")?;
let frame: usize = meta[1].parse().map_err(|_| "malformed frame number")?;
kind = ReferenceTestKind::AnimatedFrame {
frame: frame.checked_sub(1).ok_or("frame number must be 1-based")?,
};
} else {
return Err("unrecognized reference image metadata format");
}
// The remaining part represents the original file name
let orig_filename = filename_parts
.next()
.ok_or("missing original file name")?
.to_owned();
Ok(Self {
orig_filename,
crc,
kind,
})
}
}
/// Parse the given string as a hexadecimal CRC hash, used by `check_references`.
fn parse_crc(src: &str) -> Option<u32> {
u32::from_str_radix(src, 16).ok()
}
#[test]
fn check_references() {
process_images(REFERENCE_DIR, Some("png"), |base, path, decoder| {
println!("check_references {}", path.display());
let ref_img = match image::open(&path) {
Ok(img) => img.to_rgba8(),
// Do not fail on unsupported error
// This might happen because the testsuite contains unsupported images
// or because a specific decoder included via a feature.
Err(image::ImageError::Unsupported(_)) => return,
Err(err) => panic!(format!("{}", err)),
};
let (filename, testsuite) = {
let mut path: Vec<_> = path.components().collect();
(path.pop().unwrap(), path.pop().unwrap())
};
// Parse the file name to obtain the test case information
let filename_str = filename.as_os_str().to_str().unwrap();
let case: ReferenceTestCase = filename_str.parse().unwrap();
let mut img_path = base.clone();
img_path.push(IMAGE_DIR);
img_path.push(decoder);
img_path.push(testsuite.as_os_str());
img_path.push(case.orig_filename);
// Load the test image
let mut test_img = None;
match case.kind {
ReferenceTestKind::AnimatedFrame { frame: frame_num } => {
let format = image::io::Reader::open(&img_path)
.unwrap()
.with_guessed_format()
.unwrap()
.format();
#[cfg(feature = "gif")]
if format == Some(image::ImageFormat::Gif) {
// Interpret the input file as an animation file
use image::AnimationDecoder;
let stream = io::BufReader::new(fs::File::open(&img_path).unwrap());
let decoder = match image::gif::GifDecoder::new(stream) {
Ok(decoder) => decoder,
Err(image::ImageError::Unsupported(_)) => return,
Err(err) => {
panic!(format!("decoding of {:?} failed with: {}", img_path, err))
}
};
let mut frames = match decoder.into_frames().collect_frames() {
Ok(frames) => frames,
Err(image::ImageError::Unsupported(_)) => return,
Err(err) => panic!(format!(
"collecting frames of {:?} failed with: {}",
img_path, err
)),
};
// Select a single frame
let frame = frames.drain(frame_num..).nth(0).unwrap();
// Convert the frame to a`RgbaImage`
test_img = Some(frame.into_buffer());
}
#[cfg(feature = "png")]
if format == Some(image::ImageFormat::Png) {
// Interpret the input file as an animation file
use image::AnimationDecoder;
let stream = io::BufReader::new(fs::File::open(&img_path).unwrap());
let decoder = match image::png::PngDecoder::new(stream) {
Ok(decoder) => decoder.apng(),
Err(image::ImageError::Unsupported(_)) => return,
Err(err) => {
panic!(format!("decoding of {:?} failed with: {}", img_path, err))
}
};
let mut frames = match decoder.into_frames().collect_frames() {
Ok(frames) => frames,
Err(image::ImageError::Unsupported(_)) => return,
Err(err) => panic!(format!(
"collecting frames of {:?} failed with: {}",
img_path, err
)),
};
// Select a single frame
let frame = frames.drain(frame_num..).nth(0).unwrap();
// Convert the frame to a`RgbaImage`
test_img = Some(frame.into_buffer());
}
if test_img.is_none() {
println!("Skipping - GIF codec is not enabled");
return;
}
}
ReferenceTestKind::SingleImage => {
// Read the input file as a single image
match image::open(&img_path) {
Ok(img) => test_img = Some(img.to_rgba8()),
// Do not fail on unsupported error
// This might happen because the testsuite contains unsupported images
// or because a specific decoder included via a feature.
Err(image::ImageError::Unsupported(_)) => return,
Err(err) => panic!(format!("decoding of {:?} failed with: {}", img_path, err)),
};
}
}
let test_img = match test_img.as_ref() {
Some(img) => img,
None => return,
};
let test_crc_actual = {
let mut hasher = Crc32::new();
hasher.update(&*test_img);
hasher.finalize()
};
if test_crc_actual != case.crc {
panic!(
"The decoded image's hash does not match (expected = {:08x}, actual = {:08x}).",
case.crc, test_crc_actual
);
}
if *ref_img != **test_img {
panic!("Reference rendering does not match.");
}
})
}
#[cfg(feature = "hdr")]
#[test]
fn check_hdr_references() {
let mut ref_path: PathBuf = BASE_PATH.iter().collect();
ref_path.push(REFERENCE_DIR);
ref_path.push("hdr");
let mut path: PathBuf = BASE_PATH.iter().collect();
path.push(IMAGE_DIR);
path.push("hdr");
path.push("*");
path.push("*.hdr");
let pattern = &*format!("{}", path.display());
for path in glob::glob(pattern).unwrap().filter_map(Result::ok) {
use std::path::Component::Normal;
let mut ref_path = ref_path.clone();
// append 2 last components of image path to reference path
for c in path.components()
.rev()
.take(2)
.collect::<Vec<_>>()
.iter()
.rev()
{
match *c {
Normal(name) => ref_path.push(name),
_ => panic!(),
}
}
ref_path.set_extension("raw");
println!("{}", ref_path.display());
println!("{}", path.display());
let decoder = image::hdr::HdrDecoder::new(io::BufReader::new(
fs::File::open(&path).unwrap(),
)).unwrap();
let decoded = decoder.read_image_hdr().unwrap();
let reference = image::hdr::read_raw_file(&ref_path).unwrap();
assert_eq!(decoded, reference);
}
}
/// Check that BMP files with large values could cause OOM issues are rejected.
///
/// The images are postfixed with `bad_bmp` to not be loaded by the other test.
#[test]
fn bad_bmps() {
let path: PathBuf = BASE_PATH
.iter()
.collect::<PathBuf>()
.join(IMAGE_DIR)
.join("bmp/images")
.join("*.bad_bmp");
let pattern = &*format!("{}", path.display());
for path in glob::glob(pattern).unwrap().filter_map(Result::ok) {
let im = image::open(path);
assert!(im.is_err());
}
}