Debian Codegraph @

tests/roundtrip.rs

raw symbols ◀ ▶ SCIP
2 Debian patches touch this file
1 extern crate exr;
2
3 extern crate smallvec;
4
5 use std::{panic};
6 use std::io::{Cursor};
7 use std::panic::catch_unwind;
8 use std::path::{PathBuf, Path};
9 use std::ffi::OsStr;
10
11 use exr::prelude::*;
12 use exr::error::{Error, UnitResult};
13 use exr::prelude::pixel_vec::PixelVec;
14 use exr::image::validate_results::ValidateResult;
15 use rayon::prelude::IntoParallelIterator;
16 use rayon::iter::ParallelIterator;
17 use exr::block::samples::IntoNativeSample;
18
•19 #[ignore]
20 #[test]
21 fn roundtrip_all_files_in_repository_x4(){
22 check_all_files_in_repo(|path|{
23 let file = std::fs::read(path).expect("cannot open file");
24
25 round_trip_simple(&file)?;
26 round_trip_full(&file)?;
27 round_trip_rgba_file(path, &file)?;
28 round_trip_parallel_file(&file)?;
29
30 Ok(())
31 });
32 }
33
34
35 fn round_trip_full(file: &[u8]) -> Result<()> {
36 let read_image = read()
37 .no_deep_data().all_resolution_levels().all_channels().all_layers().all_attributes()
38 .non_parallel();
39
40 let image = read_image.clone().from_buffered(Cursor::new(file))?;
41
42 let mut tmp_bytes = Vec::with_capacity(file.len());
43 image.write().non_parallel().to_buffered(Cursor::new(&mut tmp_bytes))?;
44
45 let image2 = read_image.from_buffered(Cursor::new(tmp_bytes))?;
46
47 image.assert_equals_result(&image2);
48 Ok(())
49 }
50
51 fn round_trip_simple(file: &[u8]) -> Result<()> {
52 let read_image = read()
53 .no_deep_data().largest_resolution_level().all_channels().all_layers().all_attributes()
54 .non_parallel();
55
56 let image = read_image.clone().from_buffered(Cursor::new(file))?;
57
58 let mut tmp_bytes = Vec::with_capacity(file.len());
59 image.write().non_parallel().to_buffered(&mut Cursor::new(&mut tmp_bytes))?;
60
61 let image2 = read_image.from_buffered(Cursor::new(&tmp_bytes))?;
62
63 image.assert_equals_result(&image2);
64 Ok(())
65 }
66
67 fn round_trip_rgba_file(path: &Path, file: &[u8]) -> Result<()> {
68 // these files are known to be invalid, because they do not contain any rgb channels
69 let blacklist = [
70 Path::new("tests/images/valid/openexr/LuminanceChroma/Garden.exr"),
71 Path::new("tests/images/valid/openexr/MultiView/Fog.exr"),
72 Path::new("tests/images/valid/openexr/TestImages/GrayRampsDiagonal.exr"),
73 Path::new("tests/images/valid/openexr/TestImages/GrayRampsHorizontal.exr"),
74 Path::new("tests/images/valid/openexr/TestImages/WideFloatRange.exr"),
75 Path::new("tests/images/valid/openexr/IlmfmlmflmTest/v1.7.test.tiled.exr")
76 ];
77
78 if blacklist.contains(&path) { return Ok(()) }
79
80 let image_reader = read()
81 .no_deep_data()
82 .largest_resolution_level() // TODO all levels
83 .rgba_channels(PixelVec::<(f32,f32,f32,f32)>::constructor, PixelVec::set_pixel)
84 .first_valid_layer()
85 .all_attributes()
86 .non_parallel();
87
88 let image = image_reader.clone().from_buffered(Cursor::new(file))?;
89
90 let mut tmp_bytes = Vec::with_capacity(file.len());
91
92 image.write().non_parallel()
93 .to_buffered(&mut Cursor::new(&mut tmp_bytes))?;
94
95 let image2 = image_reader.from_buffered(Cursor::new(&tmp_bytes))?;
96
97 image.assert_equals_result(&image2);
98 Ok(())
99 }
100
101 // TODO compare rgba vs rgb images for color content, and rgb vs rgb(a?)
102
103
104 fn round_trip_parallel_file(file: &[u8]) -> Result<()> {
105 let image = read()
106 .no_deep_data().all_resolution_levels().all_channels().all_layers().all_attributes()
107 .from_buffered(Cursor::new(file))?;
108
109 let mut tmp_bytes = Vec::with_capacity(file.len());
110 image.write().to_buffered(Cursor::new(&mut tmp_bytes))?;
111
112 let image2 = read()
113 .no_deep_data().all_resolution_levels().all_channels().all_layers().all_attributes()
114 .pedantic()
115 .from_buffered(Cursor::new(tmp_bytes.as_slice()))?;
116
117 image.assert_equals_result(&image2);
118 Ok(())
119 }
120
121 /// read all images in a directory.
122 /// does not check any content, just checks whether a read error or panic happened.
123 fn check_all_files_in_repo<T>(
124 operation: impl Sync + std::panic::RefUnwindSafe + Fn(&Path) -> exr::error::Result<T>
125 ) {
126 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
127 enum Result { Ok, Unsupported(String), Error(String) }
128
129 let files: Vec<PathBuf> = all_exr_files_in_repo().collect();
130 let mut results: Vec<(PathBuf, Result)> = files.into_par_iter()
131 .map(|file| {
132 let result = catch_unwind(||{
133 let prev_hook = panic::take_hook();
134 panic::set_hook(Box::new(|_| (/* do not println panics */)));
135 let result = operation(&file);
136 panic::set_hook(prev_hook);
137
138 result
139 });
140
141 let result = match result {
142 Ok(Ok(_)) => Result::Ok,
143 Ok(Err(Error::NotSupported(message))) => Result::Unsupported(message.to_string()),
144
145 Ok(Err(Error::Io(io))) => Result::Error(format!("IoError: {:?}", io)),
146 Ok(Err(Error::Invalid(message))) => Result::Error(format!("Invalid: {:?}", message)),
147 Ok(Err(Error::Aborted)) => panic!("a test produced `Error::Abort`"),
148
149 Err(_) => Result::Error("Panic".to_owned()),
150 };
151
152 match &result {
153 Result::Error(_) => println!("✗ Error when processing {:?}", file),
154 _ => println!("✓ No error when processing {:?}", file)
155 };
156
157 (file, result)
158 })
159 .collect();
160
161 results.sort_by(|(_, a), (_, b)| a.cmp(b));
162
163 println!("{:#?}", results.iter().map(|(path, result)| {
164 format!("{:?}: {}", result, path.to_str().unwrap())
165 }).collect::<Vec<_>>());
166
167 assert!(results.len() > 80, "Not enough files were tested!");
168
169 if let Result::Error(_) = results.last().unwrap().1 {
170 panic!("A file triggered a panic");
171 }
172 }
173
174 fn all_exr_files_in_repo() -> impl Iterator<Item=PathBuf> {
175 walkdir::WalkDir::new("tests/images/valid").into_iter().map(std::result::Result::unwrap)
176 .filter(|entry| entry.path().extension() == Some(OsStr::new("exr")))
177 .map(walkdir::DirEntry::into_path)
178 }
179
180 #[test]
181 fn roundtrip_unusual_2() -> UnitResult {
182 let random_pixels: Vec<(f16, u32)> = vec![
183 ( f16::from_f32(-5.0), 4),
184 ( f16::from_f32(4.0), 9),
185 ( f16::from_f32(2.0), 6),
186 ( f16::from_f32(21.0), 8),
187 ( f16::from_f32(64.0), 7),
188 ];
189
190 let size = Vec2(3, 2);
191 let pixels = (0..size.area())
192 .zip(random_pixels.into_iter().cycle())
193 .map(|(_index, color)| color).collect::<Vec<_>>();
194
195 let pixels = PixelVec { resolution: size, pixels };
196
197 let channels = SpecificChannels::build()
198 .with_channel("N")
199 .with_channel("Ploppalori Taranos")
200 .with_pixels(pixels.clone()
201 );
202
203 let image = Image::from_channels(size, channels);
204
205 let mut tmp_bytes = Vec::new();
206 image.write().non_parallel().to_buffered(&mut Cursor::new(&mut tmp_bytes))?;
207
208 let image_reader = read()
209 .no_deep_data()
210 .largest_resolution_level() // TODO all levels
211 .specific_channels().required("N").required("Ploppalori Taranos")
212 .collect_pixels(PixelVec::<(f16,u32)>::constructor, PixelVec::set_pixel)
213 .first_valid_layer()
214 .all_attributes()
215 .non_parallel();
216
217 let image2 = image_reader.from_buffered(Cursor::new(&tmp_bytes))?;
218
219 // custom compare function: considers nan equal to nan
220 assert_eq!(image.layer_data.size, size, "test is buggy");
221 let pixels1 = &image.layer_data.channel_data.pixels;
222 let pixels2 = &image2.layer_data.channel_data.pixels;
223
224 assert_eq!(pixels1.pixels, pixels2.pixels);
225
226 Ok(())
227 }
228
229 // TODO test optional reader
230 // TODO dedup
231 #[test]
232 fn roundtrip_unusual_7() -> UnitResult {
233
234 let random_pixels: Vec<(f16, u32, f32,f32,f32,f32,f32)> = vec![
235 ( f16::from_f32(-5.0), 4, 1.0,2.0,3.0,4.0,5.0),
236 ( f16::from_f32(4.0), 8, 2.0,3.0,4.0,5.0,1.0),
237 ( f16::from_f32(2.0), 9, 3.0,4.0,5.0,1.0,2.0),
238 ( f16::from_f32(21.0), 6, 4.0,5.0,1.0,2.0,3.0),
239 ( f16::from_f32(64.0), 5, 5.0,1.0,2.0,3.0,4.0),
240 ];
241
242 let size = Vec2(3, 2);
243 let pixels = (0..size.area())
244 .zip(random_pixels.into_iter().cycle())
245 .map(|(_index, color)| color).collect::<Vec<_>>();
246
247 let pixels = PixelVec { resolution: size, pixels };
248
249 let channels = SpecificChannels::build()
250 .with_channel("N")
251 .with_channel("Ploppalori Taranos")
252 .with_channel("4")
253 .with_channel(".")
254 .with_channel("____")
255 .with_channel(" ")
256 .with_channel(" ")
257 .with_pixels(pixels.clone()
258 );
259
260 let image = Image::from_channels(size, channels);
261
262 let mut tmp_bytes = Vec::new();
263 image.write().non_parallel().to_buffered(&mut Cursor::new(&mut tmp_bytes))?;
264
265 let image_reader = read()
266 .no_deep_data()
267 .largest_resolution_level() // TODO all levels
268 .specific_channels()
269 .required("N")
270 .required("Ploppalori Taranos")
271 .required("4")
272 .required(".")
273 .required("____")
274 .required(" ")
275 .required(" ")
276 .collect_pixels(PixelVec::<(f16, u32, f32,f32,f32,f32,f32)>::constructor, PixelVec::set_pixel)
277 .first_valid_layer()
278 .all_attributes()
279 .non_parallel();
280
281 let image2 = image_reader.from_buffered(Cursor::new(&tmp_bytes))?;
282
283 // custom compare function: considers nan equal to nan
284 assert_eq!(image.layer_data.size, size, "test is buggy");
285 let pixels1 = &image.layer_data.channel_data.pixels;
286 let pixels2 = &image2.layer_data.channel_data.pixels;
287
288 assert_eq!(pixels1.pixels, pixels2.pixels);
289 Ok(())
290 }
291
•292 #[ignore]
293 #[test]
294 fn roundtrip_pxr24() {
295 test_mixed_roundtrip_with_compression(Compression::PXR24)
296 }
297
298 #[test]
299 fn roundtrip_rle() {
300 test_mixed_roundtrip_with_compression(Compression::RLE)
301 }
302
303 #[test]
304 fn roundtrip_zip1() {
305 test_mixed_roundtrip_with_compression(Compression::ZIP1)
306 }
307
308 #[test]
309 fn roundtrip_zip16() {
310 test_mixed_roundtrip_with_compression(Compression::ZIP16)
311 }
312
313 #[test]
314 fn roundtrip_b44() {
315 test_mixed_roundtrip_with_compression(Compression::B44)
316 }
317
318 #[test]
319 fn roundtrip_b44a() {
320 test_mixed_roundtrip_with_compression(Compression::B44A)
321 }
322
323 #[test]
324 fn roundtrip_piz() {
325 test_mixed_roundtrip_with_compression(Compression::PIZ)
326 }
327
328 #[test]
329 fn roundtrip_uncompressed() {
330 test_mixed_roundtrip_with_compression(Compression::Uncompressed)
331 }
332
333 fn test_mixed_roundtrip_with_compression(compression: Compression) {
334
335 let original_pixels: [(f16,f32,f32); 4] = [
336 (0.0.to_f16(), -1.1, std::f32::consts::PI),
337 (9.1.to_f16(), -3.1, std::f32::consts::TAU),
•338 ((-10.0).to_f16(), -11.1, f32::EPSILON),
339 (half::f16::NAN, 10000.1, -1024.009),
340 ];
341
342 let mut file_bytes = Vec::new();
343 let original_image = Image::from_encoded_channels(
344 (2,2),
345 Encoding {
346 compression,
347 .. Encoding::default()
348 },
349 SpecificChannels::rgb(
350 PixelVec::new(Vec2(2,2), original_pixels.to_vec())
351 )
352 );
353
354 original_image.write().to_buffered(Cursor::new(&mut file_bytes)).unwrap();
355
356 let lossy_image = read().no_deep_data().largest_resolution_level()
357 .rgb_channels(PixelVec::<(f16,f32,f32)>::constructor, PixelVec::set_pixel)
358 .first_valid_layer().all_attributes().from_buffered(Cursor::new(&file_bytes)).unwrap();
359
360 // use automatic lossy detection by compression method
361 original_image.assert_equals_result(&original_image);
362 lossy_image.assert_equals_result(&lossy_image);
363 original_image.assert_equals_result(&lossy_image);
364 }