| 1 | use super::*; |
| 2 | |
| 3 | /// Converts IEEE-754 `f32` to IEEE-754 binary16 (`f16`) bits for direct `Rgba16Float` GPU upload. |
| 4 | #[inline] |
| 5 | pub fn f32_to_f16_bits(val: f32) -> u16 { |
| 6 | let bits = val.to_bits(); |
| 7 | let sign = ((bits >> 16) & 0x8000) as u16; |
| 8 | let exp = ((bits >> 23) & 0xFF) as i32; |
| 9 | let frac = bits & 0x007F_FFFF; |
| 10 | |
| 11 | if exp == 0xFF { |
| 12 | return if frac != 0 { 0 } else { sign | 0x7C00 }; |
| 13 | } |
| 14 | let new_exp = exp - 127 + 15; |
| 15 | if new_exp >= 31 { |
| 16 | return sign | 0x7BFF; |
| 17 | } |
| 18 | if new_exp <= 0 { |
| 19 | if new_exp < -10 { |
| 20 | return sign; |
| 21 | } |
| 22 | let m = (frac | 0x0080_0000) >> (1 - new_exp + 13); |
| 23 | return sign | (m as u16); |
| 24 | } |
| 25 | let rounded = frac + 0x1000; |
| 26 | if rounded >= 0x0080_0000 { |
| 27 | let e = new_exp + 1; |
| 28 | return if e >= 31 { sign | 0x7BFF } else { sign | ((e as u16) << 10) }; |
| 29 | } |
| 30 | sign | ((new_exp as u16) << 10) | ((rounded >> 13) as u16) |
| 31 | } |
| 32 | |
| 33 | pub(super) fn is_exr_path(path: &Path) -> bool { |
| 34 | path.extension() |
| 35 | .and_then(|e| e.to_str()) |
| 36 | .is_some_and(|e| e.eq_ignore_ascii_case("exr")) |
| 37 | } |
| 38 | |
| 39 | pub(super) fn full_exr_channel_name(layer_name: Option<&str>, ch_name: &str) -> String { |
| 40 | match layer_name { |
| 41 | Some(ln) if !ln.is_empty() && !ch_name.starts_with(&format!("{ln}.")) => { |
| 42 | format!("{ln}.{ch_name}") |
| 43 | } |
| 44 | _ => ch_name.to_owned(), |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | pub(super) fn normalize_channel_opt(opt: Option<&str>) -> Option<String> { |
| 49 | opt.map(str::trim) |
| 50 | .filter(|s| !s.is_empty()) |
| 51 | .map(str::to_owned) |
| 52 | } |
| 53 | |
| 54 | fn apply_post_multiply_rgba8_slice(raw: &mut [u8]) { |
| 55 | for px in raw.chunks_exact_mut(4) { |
| 56 | let a = px[3]; |
| 57 | if a == 255 { |
| 58 | continue; |
| 59 | } |
| 60 | if a == 0 { |
| 61 | px[0] = 0; |
| 62 | px[1] = 0; |
| 63 | px[2] = 0; |
| 64 | continue; |
| 65 | } |
| 66 | let a16 = u16::from(a); |
| 67 | px[0] = ((u16::from(px[0]) * a16 + 127) / 255) as u8; |
| 68 | px[1] = ((u16::from(px[1]) * a16 + 127) / 255) as u8; |
| 69 | px[2] = ((u16::from(px[2]) * a16 + 127) / 255) as u8; |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | pub(super) fn apply_post_multiply_rgba8(raw: &mut [u8]) { |
| 74 | apply_post_multiply_rgba8_parallel(raw, true); |
| 75 | } |
| 76 | |
| 77 | pub(super) fn apply_post_multiply_rgba8_parallel(raw: &mut [u8], allow_parallel: bool) { |
| 78 | #[cfg(not(target_arch = "wasm32"))] |
| 79 | { |
| 80 | // Parallelize across worker slices for > 4 MP images (e.g. 15 MP plates) when not |
| 81 | // already running inside a multi-image worker pool. |
| 82 | const PARALLEL_THRESHOLD_BYTES: usize = 4 * 1024 * 1024 * 4; |
| 83 | if allow_parallel && raw.len() >= PARALLEL_THRESHOLD_BYTES { |
| 84 | let workers = std::thread::available_parallelism() |
| 85 | .map(|n| n.get().clamp(2, 8)) |
| 86 | .unwrap_or(4); |
| 87 | let total_px = raw.len() / 4; |
| 88 | let chunk_bytes = total_px.div_ceil(workers).max(1) * 4; |
| 89 | std::thread::scope(|scope| { |
| 90 | for chunk in raw.chunks_mut(chunk_bytes) { |
| 91 | scope.spawn(move || apply_post_multiply_rgba8_slice(chunk)); |
| 92 | } |
| 93 | }); |
| 94 | return; |
| 95 | } |
| 96 | } |
| 97 | let _ = allow_parallel; |
| 98 | apply_post_multiply_rgba8_slice(raw); |
| 99 | } |
| 100 | |
| 101 | pub(super) fn find_exr_channel_loc( |
| 102 | headers: &[::exr::meta::header::Header], |
| 103 | w: usize, |
| 104 | h: usize, |
| 105 | preferred: Option<&str>, |
| 106 | beauty_upper: &str, |
| 107 | beauty_lower: &str, |
| 108 | ) -> Option<(usize, usize)> { |
| 109 | let valid_layer = |header: &::exr::meta::header::Header| { |
| 110 | !header.deep && header.layer_size.width() == w && header.layer_size.height() == h |
| 111 | }; |
| 112 | |
| 113 | if let Some(pref) = preferred.map(str::trim).filter(|s| !s.is_empty()) { |
| 114 | for (li, header) in headers.iter().enumerate() { |
| 115 | if !valid_layer(header) { |
| 116 | continue; |
| 117 | } |
| 118 | let lname = header.own_attributes.layer_name.as_ref().map(|t| t.to_string()); |
| 119 | for (ci, ch) in header.channels.list.iter().enumerate() { |
| 120 | if ch.sampling != ::exr::math::Vec2(1, 1) { |
| 121 | continue; |
| 122 | } |
| 123 | let full = full_exr_channel_name(lname.as_deref(), &ch.name.to_string()); |
| 124 | if full == pref { |
| 125 | return Some((li, ci)); |
| 126 | } |
| 127 | } |
| 128 | } |
| 129 | let suffix = format!(".{pref}"); |
| 130 | for (li, header) in headers.iter().enumerate() { |
| 131 | if !valid_layer(header) { |
| 132 | continue; |
| 133 | } |
| 134 | let lname = header.own_attributes.layer_name.as_ref().map(|t| t.to_string()); |
| 135 | for (ci, ch) in header.channels.list.iter().enumerate() { |
| 136 | if ch.sampling != ::exr::math::Vec2(1, 1) { |
| 137 | continue; |
| 138 | } |
| 139 | let full = full_exr_channel_name(lname.as_deref(), &ch.name.to_string()); |
| 140 | if full.ends_with(&suffix) { |
| 141 | return Some((li, ci)); |
| 142 | } |
| 143 | } |
| 144 | } |
| 145 | return None; |
| 146 | } |
| 147 | |
| 148 | // Beauty pass fallback: check ViewLayer.Combined.<C>, Combined.<C>, *.Combined.<C>, |
| 149 | // then exact bare <C>/<c>. Never match non-beauty layers such as CryptoObject00.R! |
| 150 | let view_combined = format!("ViewLayer.Combined.{beauty_upper}"); |
| 151 | let combined = format!("Combined.{beauty_upper}"); |
| 152 | let any_combined = format!(".Combined.{beauty_upper}"); |
| 153 | let matcher_passes: [&dyn Fn(&str) -> bool; 4] = [ |
| 154 | &|full: &str| full == view_combined, |
| 155 | &|full: &str| full == combined || full.ends_with(&any_combined), |
| 156 | &|full: &str| full == beauty_upper, |
| 157 | &|full: &str| full == beauty_lower, |
| 158 | ]; |
| 159 | for pred in matcher_passes { |
| 160 | for (li, header) in headers.iter().enumerate() { |
| 161 | if !valid_layer(header) { |
| 162 | continue; |
| 163 | } |
| 164 | let lname = header.own_attributes.layer_name.as_ref().map(|t| t.to_string()); |
| 165 | for (ci, ch) in header.channels.list.iter().enumerate() { |
| 166 | if ch.sampling != ::exr::math::Vec2(1, 1) { |
| 167 | continue; |
| 168 | } |
| 169 | let full = full_exr_channel_name(lname.as_deref(), &ch.name.to_string()); |
| 170 | if pred(&full) { |
| 171 | return Some((li, ci)); |
| 172 | } |
| 173 | } |
| 174 | } |
| 175 | } |
| 176 | None |
| 177 | } |
| 178 | |
| 179 | /// Finds a `Z` depth channel (`"Z"`, `"z"`, or ending in `".Z"`/`".z"`, e.g. `"depth.Z"`) |
| 180 | /// in a layer matching `(w, h)`. Exact `"Z"`/`"z"` takes priority over suffixed channels. |
| 181 | fn find_exr_z_loc( |
| 182 | headers: &[::exr::meta::header::Header], |
| 183 | w: usize, |
| 184 | h: usize, |
| 185 | ) -> Option<(usize, usize)> { |
| 186 | let valid_layer = |header: &::exr::meta::header::Header| { |
| 187 | !header.deep && header.layer_size.width() == w && header.layer_size.height() == h |
| 188 | }; |
| 189 | let is_suffixed_z = |full: &str| { |
| 190 | full.contains('.') |
| 191 | && full |
| 192 | .rsplit('.') |
| 193 | .next() |
| 194 | .is_some_and(|s| s.eq_ignore_ascii_case("z")) |
| 195 | }; |
| 196 | let matchers: [&dyn Fn(&str) -> bool; 2] = [ |
| 197 | &|full: &str| full.eq_ignore_ascii_case("z"), |
| 198 | &is_suffixed_z, |
| 199 | ]; |
| 200 | for pred in matchers { |
| 201 | for (li, header) in headers.iter().enumerate() { |
| 202 | if !valid_layer(header) { |
| 203 | continue; |
| 204 | } |
| 205 | let lname = header.own_attributes.layer_name.as_ref().map(|t| t.to_string()); |
| 206 | for (ci, ch) in header.channels.list.iter().enumerate() { |
| 207 | if ch.sampling != ::exr::math::Vec2(1, 1) { |
| 208 | continue; |
| 209 | } |
| 210 | let full = full_exr_channel_name(lname.as_deref(), &ch.name.to_string()); |
| 211 | if pred(&full) { |
| 212 | return Some((li, ci)); |
| 213 | } |
| 214 | } |
| 215 | } |
| 216 | } |
| 217 | None |
| 218 | } |
| 219 | |
| 220 | /// Decodes a single-layer or multi-layer (Blender `ViewLayer.Combined.R/G/B/A`) OpenEXR |
| 221 | /// selectively for only the matched RGBA channels, producing clamped RGBA8 and linear HDR |
| 222 | /// RGBA16F/RGBA32F buffers without decoding unrelated AOV/Cryptomatte layers. |
| 223 | pub(super) fn decode_exr_rgba( |
| 224 | path: &Path, |
| 225 | red_name: Option<&str>, |
| 226 | green_name: Option<&str>, |
| 227 | blue_name: Option<&str>, |
| 228 | alpha_name: Option<&str>, |
| 229 | post_multiply: bool, |
| 230 | allow_parallel: bool, |
| 231 | ) -> Option<DecodedImage> { |
| 232 | let names = [red_name, green_name, blue_name, alpha_name]; |
| 233 | match super::virtual_bytes(path) { |
| 234 | Some(bytes) => decode_exr_from(std::io::Cursor::new(bytes), names, post_multiply, allow_parallel), |
| 235 | None => decode_exr_from( |
| 236 | std::io::BufReader::with_capacity(256 * 1024, std::fs::File::open(path).ok()?), |
| 237 | names, |
| 238 | post_multiply, |
| 239 | allow_parallel, |
| 240 | ), |
| 241 | } |
| 242 | } |
| 243 | |
| 244 | fn convert_exr_rgba_slice( |
| 245 | raw_f32: &mut [f32], |
| 246 | raw_f16: &mut [u16], |
| 247 | raw: &mut [u8], |
| 248 | has_g: bool, |
| 249 | has_b: bool, |
| 250 | has_a: bool, |
| 251 | post_multiply: bool, |
| 252 | ) { |
| 253 | debug_assert_eq!(raw_f32.len(), raw_f16.len()); |
| 254 | debug_assert_eq!(raw_f32.len(), raw.len()); |
| 255 | debug_assert_eq!(raw_f32.len() % 4, 0); |
| 256 | |
| 257 | for ((px_f32, px_f16), px_u8) in raw_f32 |
| 258 | .chunks_exact_mut(4) |
| 259 | .zip(raw_f16.chunks_exact_mut(4)) |
| 260 | .zip(raw.chunks_exact_mut(4)) |
| 261 | { |
| 262 | let mut r_raw = px_f32[0]; |
| 263 | let mut g_raw = if has_g { px_f32[1] } else { r_raw }; |
| 264 | let mut b_raw = if has_b { px_f32[2] } else { r_raw }; |
| 265 | let a_raw = if has_a { px_f32[3] } else { 1.0 }; |
| 266 | |
| 267 | if post_multiply && a_raw < 1.0 { |
| 268 | let a_mul = a_raw.clamp(0.0, 1.0); |
| 269 | r_raw *= a_mul; |
| 270 | g_raw *= a_mul; |
| 271 | b_raw *= a_mul; |
| 272 | } |
| 273 | px_f32[0] = r_raw; |
| 274 | px_f32[1] = g_raw; |
| 275 | px_f32[2] = b_raw; |
| 276 | px_f32[3] = a_raw; |
| 277 | |
| 278 | px_f16[0] = f32_to_f16_bits(r_raw); |
| 279 | px_f16[1] = f32_to_f16_bits(g_raw); |
| 280 | px_f16[2] = f32_to_f16_bits(b_raw); |
| 281 | px_f16[3] = f32_to_f16_bits(a_raw); |
| 282 | |
| 283 | let a = a_raw.clamp(0.0, 1.0); |
| 284 | let r = r_raw.clamp(0.0, 1.0); |
| 285 | let g = g_raw.clamp(0.0, 1.0); |
| 286 | let b = b_raw.clamp(0.0, 1.0); |
| 287 | px_u8[0] = (r * 255.0 + 0.5) as u8; |
| 288 | px_u8[1] = (g * 255.0 + 0.5) as u8; |
| 289 | px_u8[2] = (b * 255.0 + 0.5) as u8; |
| 290 | px_u8[3] = (a * 255.0 + 0.5) as u8; |
| 291 | } |
| 292 | } |
| 293 | |
| 294 | fn convert_exr_rgba_buffers( |
| 295 | raw_f32: &mut [f32], |
| 296 | raw_f16: &mut [u16], |
| 297 | raw: &mut [u8], |
| 298 | has_g: bool, |
| 299 | has_b: bool, |
| 300 | has_a: bool, |
| 301 | post_multiply: bool, |
| 302 | allow_parallel: bool, |
| 303 | ) { |
| 304 | #[cfg(not(target_arch = "wasm32"))] |
| 305 | { |
| 306 | const PARALLEL_THRESHOLD_PIXELS: usize = 512 * 512; |
| 307 | let total_px = raw_f32.len() / 4; |
| 308 | if allow_parallel && total_px >= PARALLEL_THRESHOLD_PIXELS { |
| 309 | let workers = std::thread::available_parallelism() |
| 310 | .map(|n| n.get().clamp(2, 12)) |
| 311 | .unwrap_or(4) |
| 312 | .min(total_px); |
| 313 | let chunk_elems = total_px.div_ceil(workers).max(1) * 4; |
| 314 | std::thread::scope(|scope| { |
| 315 | for ((f32_chunk, f16_chunk), u8_chunk) in raw_f32 |
| 316 | .chunks_mut(chunk_elems) |
| 317 | .zip(raw_f16.chunks_mut(chunk_elems)) |
| 318 | .zip(raw.chunks_mut(chunk_elems)) |
| 319 | { |
| 320 | scope.spawn(move || { |
| 321 | convert_exr_rgba_slice( |
| 322 | f32_chunk, |
| 323 | f16_chunk, |
| 324 | u8_chunk, |
| 325 | has_g, |
| 326 | has_b, |
| 327 | has_a, |
| 328 | post_multiply, |
| 329 | ); |
| 330 | }); |
| 331 | } |
| 332 | }); |
| 333 | return; |
| 334 | } |
| 335 | } |
| 336 | #[cfg(target_arch = "wasm32")] |
| 337 | let _ = allow_parallel; |
| 338 | convert_exr_rgba_slice( |
| 339 | raw_f32, |
| 340 | raw_f16, |
| 341 | raw, |
| 342 | has_g, |
| 343 | has_b, |
| 344 | has_a, |
| 345 | post_multiply, |
| 346 | ); |
| 347 | } |
| 348 | |
| 349 | fn decode_exr_from<R: std::io::Read + std::io::Seek + Send>( |
| 350 | reader: R, |
| 351 | [red_name, green_name, blue_name, alpha_name]: [Option<&str>; 4], |
| 352 | post_multiply: bool, |
| 353 | allow_parallel: bool, |
| 354 | ) -> Option<DecodedImage> { |
| 355 | use ::exr::block::reader::ChunksReader; |
| 356 | use ::exr::block::UncompressedBlock; |
| 357 | use ::exr::error::UnitResult; |
| 358 | use ::exr::meta::attribute::SampleType; |
| 359 | use ::exr::prelude::*; |
| 360 | |
| 361 | let chunks_reader = ::exr::block::read(reader, false).ok()?; |
| 362 | let first_header = chunks_reader.headers().first()?; |
| 363 | let w = first_header.layer_size.width(); |
| 364 | let h = first_header.layer_size.height(); |
| 365 | const MAX_EXR_PIXELS: usize = 64 * 1024 * 1024; |
| 366 | let pixel_count = w.checked_mul(h)?; |
| 367 | if w == 0 || h == 0 || w > u32::MAX as usize || h > u32::MAX as usize || pixel_count > MAX_EXR_PIXELS { |
| 368 | return None; |
| 369 | } |
| 370 | let elem_count = pixel_count.checked_mul(4)?; |
| 371 | |
| 372 | let r_loc = find_exr_channel_loc(chunks_reader.headers(), w, h, red_name, "R", "r")?; |
| 373 | let g_loc = find_exr_channel_loc(chunks_reader.headers(), w, h, green_name, "G", "g"); |
| 374 | let b_loc = find_exr_channel_loc(chunks_reader.headers(), w, h, blue_name, "B", "b"); |
| 375 | let a_loc = find_exr_channel_loc(chunks_reader.headers(), w, h, alpha_name, "A", "a"); |
| 376 | let z_loc = find_exr_z_loc(chunks_reader.headers(), w, h); |
| 377 | |
| 378 | let target_locs = [Some(r_loc), g_loc, b_loc, a_loc]; |
| 379 | let mut needed_layers: Vec<usize> = target_locs |
| 380 | .iter() |
| 381 | .chain(std::iter::once(&z_loc)) |
| 382 | .flatten() |
| 383 | .map(|(l, _)| *l) |
| 384 | .collect(); |
| 385 | needed_layers.sort_unstable(); |
| 386 | needed_layers.dedup(); |
| 387 | |
| 388 | let mut raw_f32 = Vec::new(); |
| 389 | raw_f32.try_reserve_exact(elem_count).ok()?; |
| 390 | raw_f32.resize(elem_count, 0.0_f32); |
| 391 | let mut z_raw_f32 = if z_loc.is_some() { |
| 392 | let mut v = Vec::new(); |
| 393 | v.try_reserve_exact(pixel_count).ok()?; |
| 394 | v.resize(pixel_count, crate::cache::EMPTY_Z_SENTINEL); |
| 395 | Some(v) |
| 396 | } else { |
| 397 | None |
| 398 | }; |
| 399 | let mut line_f32 = Vec::<f32>::new(); |
| 400 | let mut line_f16 = Vec::<f16>::new(); |
| 401 | let mut line_u32 = Vec::<u32>::new(); |
| 402 | |
| 403 | let filtered = chunks_reader |
| 404 | .filter_chunks(false, |_, tile, block| { |
| 405 | tile.is_largest_resolution_level() && needed_layers.contains(&block.layer) |
| 406 | }) |
| 407 | .ok()?; |
| 408 | let insert_block = |meta: &MetaData, block: UncompressedBlock| -> UnitResult { |
| 409 | let header = &meta.headers[block.index.layer]; |
| 410 | for line in block.lines(&header.channels) { |
| 411 | let loc = (line.location.layer, line.location.channel); |
| 412 | let mut comp_mask = [false; 4]; |
| 413 | for (c, t) in target_locs.iter().enumerate() { |
| 414 | if *t == Some(loc) { |
| 415 | comp_mask[c] = true; |
| 416 | } |
| 417 | } |
| 418 | let write_z = z_loc == Some(loc); |
| 419 | if !comp_mask.iter().any(|&m| m) && !write_z { |
| 420 | continue; |
| 421 | } |
| 422 | let y = line.location.position.y(); |
| 423 | let x0 = line.location.position.x(); |
| 424 | let len = line.location.sample_count; |
| 425 | if y >= h || x0.saturating_add(len) > w { |
| 426 | continue; |
| 427 | } |
| 428 | |
| 429 | line_f32.clear(); |
| 430 | match header.channels.list[line.location.channel].sample_type { |
| 431 | SampleType::F32 => { |
| 432 | line_f32.resize(len, 0.0); |
| 433 | line.read_samples_into_slice(&mut line_f32)?; |
| 434 | } |
| 435 | SampleType::F16 => { |
| 436 | line_f16.resize(len, f16::ZERO); |
| 437 | line.read_samples_into_slice(&mut line_f16)?; |
| 438 | line_f32.extend(line_f16.iter().map(|v| v.to_f32())); |
| 439 | } |
| 440 | SampleType::U32 => { |
| 441 | line_u32.resize(len, 0); |
| 442 | line.read_samples_into_slice(&mut line_u32)?; |
| 443 | line_f32.extend(line_u32.iter().map(|&v| v as f32)); |
| 444 | } |
| 445 | } |
| 446 | |
| 447 | if comp_mask.iter().any(|&m| m) { |
| 448 | let row_base = (y * w + x0) * 4; |
| 449 | for (dx, &sample) in line_f32.iter().enumerate() { |
| 450 | let val = if sample.is_nan() { 0.0 } else { sample }; |
| 451 | let px_off = row_base + dx * 4; |
| 452 | for (c, &enabled) in comp_mask.iter().enumerate() { |
| 453 | if enabled { |
| 454 | raw_f32[px_off + c] = val; |
| 455 | } |
| 456 | } |
| 457 | } |
| 458 | } |
| 459 | if write_z { |
| 460 | if let Some(ref mut z_vec) = z_raw_f32 { |
| 461 | let z_row_base = y * w + x0; |
| 462 | for (dx, &sample) in line_f32.iter().enumerate() { |
| 463 | z_vec[z_row_base + dx] = if sample.is_nan() { |
| 464 | crate::cache::EMPTY_Z_SENTINEL |
| 465 | } else { |
| 466 | sample |
| 467 | }; |
| 468 | } |
| 469 | } |
| 470 | } |
| 471 | } |
| 472 | Ok(()) |
| 473 | }; |
| 474 | if allow_parallel { |
| 475 | filtered.decompress_parallel(false, insert_block).ok()?; |
| 476 | } else { |
| 477 | filtered.decompress_sequential(false, insert_block).ok()?; |
| 478 | } |
| 479 | |
| 480 | let mut raw = Vec::new(); |
| 481 | raw.try_reserve_exact(elem_count).ok()?; |
| 482 | raw.resize(elem_count, 0u8); |
| 483 | let mut raw_f16 = Vec::new(); |
| 484 | raw_f16.try_reserve_exact(elem_count).ok()?; |
| 485 | raw_f16.resize(elem_count, 0u16); |
| 486 | convert_exr_rgba_buffers( |
| 487 | &mut raw_f32, |
| 488 | &mut raw_f16, |
| 489 | &mut raw, |
| 490 | g_loc.is_some(), |
| 491 | b_loc.is_some(), |
| 492 | a_loc.is_some(), |
| 493 | post_multiply, |
| 494 | allow_parallel, |
| 495 | ); |
| 496 | Some(DecodedImage { |
| 497 | size: [w as u32, h as u32], |
| 498 | rgba: Arc::new(raw), |
| 499 | rgba_f16: Some(Arc::new(raw_f16)), |
| 500 | rgba_f32: Some(Arc::new(raw_f32)), |
| 501 | z_f32: z_raw_f32.map(Arc::new), |
| 502 | }) |
| 503 | } |
| 504 | |
| 505 | #[cfg(test)] |
| 506 | mod tests { |
| 507 | use super::*; |
| 508 | use crate::media::MediaCache; |
| 509 | |
| 510 | #[test] |
| 511 | fn dropped_exr_bytes_decode_without_a_file_on_disk() { |
| 512 | let pixels = image::Rgba32FImage::from_pixel(2, 1, image::Rgba([2.5, 0.5, 0.0, 1.0])); |
| 513 | let mut out = std::io::Cursor::new(Vec::new()); |
| 514 | image::DynamicImage::ImageRgba32F(pixels).write_to(&mut out, image::ImageFormat::OpenExr).unwrap(); |
| 515 | assert!(MediaCache::insert_virtual_bytes("vexr_drop/frame.exr", out.into_inner())); |
| 516 | |
| 517 | let decoded = decode_exr_rgba(Path::new("/not/on/disk/vexr_drop/frame.exr"), None, None, None, None, false, true).unwrap(); |
| 518 | assert_eq!(decoded.size, [2, 1]); |
| 519 | assert_eq!(&decoded.rgba_f32.unwrap()[..4], &[2.5, 0.5, 0.0, 1.0]); |
| 520 | let decoded_seq = decode_exr_rgba(Path::new("/not/on/disk/vexr_drop/frame.exr"), None, None, None, None, false, false).unwrap(); |
| 521 | assert_eq!(decoded_seq.size, [2, 1]); |
| 522 | assert_eq!(&decoded_seq.rgba_f32.unwrap()[..4], &[2.5, 0.5, 0.0, 1.0]); |
| 523 | } |
| 524 | |
| 525 | #[test] |
| 526 | fn parallel_exr_conversion_matches_scalar_bit_for_bit() { |
| 527 | let pixels = 512 * 512 + 17; |
| 528 | let special: [[f32; 4]; 10] = [ |
| 529 | [0.0, 0.25, 0.5, 1.0], |
| 530 | [12.5, 1.0001, 65504.0, 0.5], |
| 531 | [100000.0, -0.5, -12.25, 0.25], |
| 532 | [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, 0.75], |
| 533 | [1.0e-7, -1.0e-7, 5.960_464_5e-8, 0.0], |
| 534 | [0.3333, 0.6667, 0.9999, 1.5], |
| 535 | [-0.0, 0.0, f32::from_bits(0x7fc0_0123), -0.25], |
| 536 | [2.0, 4.0, 8.0, f32::NAN], |
| 537 | [6.103_515_6e-5, 3.051_757_8e-5, 1.525_878_9e-5, 0.999], |
| 538 | [0.5, 0.25, 0.125, f32::INFINITY], |
| 539 | ]; |
| 540 | let mut base = Vec::with_capacity(pixels * 4); |
| 541 | for i in 0..pixels { |
| 542 | let s = special[i % special.len()]; |
| 543 | let scale = if (i % 7) == 0 { 1.0 } else { ((i % 23) as f32) * 0.125 }; |
| 544 | if s[0].is_finite() && s[1].is_finite() && s[2].is_finite() && s[3].is_finite() { |
| 545 | base.extend_from_slice(&[s[0] * scale, s[1], s[2] + 0.001 * (i % 5) as f32, s[3]]); |
| 546 | } else { |
| 547 | base.extend_from_slice(&s); |
| 548 | } |
| 549 | } |
| 550 | |
| 551 | for &(has_g, has_b, has_a, post_multiply) in &[ |
| 552 | (true, true, true, false), |
| 553 | (true, true, true, true), |
| 554 | (false, false, false, true), |
| 555 | (true, false, true, true), |
| 556 | ] { |
| 557 | let mut par_f32 = base.clone(); |
| 558 | let mut par_f16 = vec![0u16; pixels * 4]; |
| 559 | let mut par_u8 = vec![0u8; pixels * 4]; |
| 560 | convert_exr_rgba_buffers( |
| 561 | &mut par_f32, |
| 562 | &mut par_f16, |
| 563 | &mut par_u8, |
| 564 | has_g, |
| 565 | has_b, |
| 566 | has_a, |
| 567 | post_multiply, |
| 568 | true, |
| 569 | ); |
| 570 | |
| 571 | let mut seq_f32 = base.clone(); |
| 572 | let mut seq_f16 = vec![0u16; pixels * 4]; |
| 573 | let mut seq_u8 = vec![0u8; pixels * 4]; |
| 574 | convert_exr_rgba_buffers( |
| 575 | &mut seq_f32, |
| 576 | &mut seq_f16, |
| 577 | &mut seq_u8, |
| 578 | has_g, |
| 579 | has_b, |
| 580 | has_a, |
| 581 | post_multiply, |
| 582 | false, |
| 583 | ); |
| 584 | |
| 585 | assert_eq!(par_f16, seq_f16, "f16 mismatch for ({has_g},{has_b},{has_a},{post_multiply})"); |
| 586 | assert_eq!(par_u8, seq_u8, "u8 mismatch for ({has_g},{has_b},{has_a},{post_multiply})"); |
| 587 | let par_bits: Vec<u32> = par_f32.iter().map(|v| v.to_bits()).collect(); |
| 588 | let seq_bits: Vec<u32> = seq_f32.iter().map(|v| v.to_bits()).collect(); |
| 589 | assert_eq!(par_bits, seq_bits, "f32 bits mismatch for ({has_g},{has_b},{has_a},{post_multiply})"); |
| 590 | } |
| 591 | } |
| 592 | |
| 593 | #[test] |
| 594 | fn exr_decodes_z_channel_and_suffixed_z_with_nan_fallback() { |
| 595 | use ::exr::prelude::*; |
| 596 | |
| 597 | let write_exr = |z_chan_name: Option<&str>, z_vals: &[f32]| -> Vec<u8> { |
| 598 | let size = Vec2(3usize, 2usize); |
| 599 | let mut channels = SmallVec::<[AnyChannel<FlatSamples>; 4]>::new(); |
| 600 | let rgba = [1.0_f32, 0.5, 0.25, 1.0]; |
| 601 | for (name, val) in [("R", rgba[0]), ("G", rgba[1]), ("B", rgba[2]), ("A", rgba[3])] { |
| 602 | channels.push(AnyChannel::new(name, FlatSamples::F32(vec![val; 6]))); |
| 603 | } |
| 604 | if let Some(zn) = z_chan_name { |
| 605 | channels.push(AnyChannel::new(zn, FlatSamples::F32(z_vals.to_vec()))); |
| 606 | } |
| 607 | let image = Image::from_layer(Layer::new( |
| 608 | size, |
| 609 | LayerAttributes::default(), |
| 610 | Encoding::UNCOMPRESSED, |
| 611 | AnyChannels::sort(channels), |
| 612 | )); |
| 613 | let mut buf = std::io::Cursor::new(Vec::new()); |
| 614 | image.write().to_buffered(&mut buf).unwrap(); |
| 615 | buf.into_inner() |
| 616 | }; |
| 617 | |
| 618 | // 1. EXR without Z channel -> z_f32 is None. |
| 619 | let no_z = write_exr(None, &[]); |
| 620 | assert!(MediaCache::insert_virtual_bytes("vexr_z/no_z.exr", no_z)); |
| 621 | let dec_no_z = decode_exr_rgba(Path::new("vexr_z/no_z.exr"), None, None, None, None, false, true).unwrap(); |
| 622 | assert!(dec_no_z.z_f32.is_none()); |
| 623 | |
| 624 | // 2. EXR with bare "Z" channel including NaN -> NaN mapped to EMPTY_Z_SENTINEL. |
| 625 | let z_expected = [-2.5_f32, -3.0, -4.25, f32::NAN, -10.0, crate::cache::EMPTY_Z_SENTINEL]; |
| 626 | let with_z = write_exr(Some("Z"), &z_expected); |
| 627 | assert!(MediaCache::insert_virtual_bytes("vexr_z/with_z.exr", with_z)); |
| 628 | let dec_z = decode_exr_rgba(Path::new("vexr_z/with_z.exr"), None, None, None, None, false, true).unwrap(); |
| 629 | let got_z = dec_z.z_f32.expect("z_f32 populated"); |
| 630 | assert_eq!( |
| 631 | got_z.as_slice(), |
| 632 | &[-2.5_f32, -3.0, -4.25, crate::cache::EMPTY_Z_SENTINEL, -10.0, crate::cache::EMPTY_Z_SENTINEL] |
| 633 | ); |
| 634 | |
| 635 | // 3. EXR with suffixed "depth.Z" channel -> also decoded into z_f32. |
| 636 | let depth_z = write_exr(Some("depth.Z"), &[-1.5, -2.0, -2.5, -3.0, -3.5, -4.0]); |
| 637 | assert!(MediaCache::insert_virtual_bytes("vexr_z/depth_z.exr", depth_z)); |
| 638 | let dec_dz = decode_exr_rgba(Path::new("vexr_z/depth_z.exr"), None, None, None, None, false, false).unwrap(); |
| 639 | assert_eq!( |
| 640 | dec_dz.z_f32.expect("depth.Z populated").as_slice(), |
| 641 | &[-1.5, -2.0, -2.5, -3.0, -3.5, -4.0] |
| 642 | ); |
| 643 | } |
| 644 | } |