| 1 | //! OpenEXR Cryptomatte (`Fuse.Cryptomatte`) matte extraction following the |
| 2 | //! Psyop Cryptomatte 1.2 specification. |
| 3 | |
| 4 | use std::collections::{BTreeMap, HashMap, HashSet}; |
| 5 | use std::path::Path; |
| 6 | |
| 7 | /// Extracted single-channel Cryptomatte coverage mask (`[0.0, 1.0]`, top-down). |
| 8 | #[derive(Clone, Debug)] |
| 9 | pub struct CryptomatteResult { |
| 10 | pub size: [u32; 2], |
| 11 | pub matte: Vec<f32>, |
| 12 | } |
| 13 | |
| 14 | /// Exact MurmurHash3 32-bit x86 (`c1 = 0xcc9e2d51`, `c2 = 0x1b873593`, `fmix32`). |
| 15 | pub fn murmur3_32(bytes: &[u8], seed: u32) -> u32 { |
| 16 | const C1: u32 = 0xcc9e_2d51; |
| 17 | const C2: u32 = 0x1b87_3593; |
| 18 | |
| 19 | let mut hash = seed; |
| 20 | let chunks = bytes.chunks_exact(4); |
| 21 | let remainder = chunks.remainder(); |
| 22 | |
| 23 | for chunk in chunks { |
| 24 | let mut k = u32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]); |
| 25 | k = k.wrapping_mul(C1); |
| 26 | k = k.rotate_left(15); |
| 27 | k = k.wrapping_mul(C2); |
| 28 | |
| 29 | hash ^= k; |
| 30 | hash = hash.rotate_left(13); |
| 31 | hash = hash.wrapping_mul(5).wrapping_add(0xe654_6b64); |
| 32 | } |
| 33 | |
| 34 | if !remainder.is_empty() { |
| 35 | let mut k1 = 0u32; |
| 36 | for (i, &b) in remainder.iter().enumerate() { |
| 37 | k1 |= u32::from(b) << (i * 8); |
| 38 | } |
| 39 | k1 = k1.wrapping_mul(C1); |
| 40 | k1 = k1.rotate_left(15); |
| 41 | k1 = k1.wrapping_mul(C2); |
| 42 | hash ^= k1; |
| 43 | } |
| 44 | |
| 45 | hash ^= bytes.len() as u32; |
| 46 | hash ^= hash >> 16; |
| 47 | hash = hash.wrapping_mul(0x85eb_ca6b); |
| 48 | hash ^= hash >> 13; |
| 49 | hash = hash.wrapping_mul(0xc2b2_ae35); |
| 50 | hash ^= hash >> 16; |
| 51 | hash |
| 52 | } |
| 53 | |
| 54 | /// Converts a 32-bit Cryptomatte hash into its IEEE-754 `f32` ID representation, |
| 55 | /// flipping bit 23 when exponent is 0 (subnormal/zero) or 255 (inf/NaN). |
| 56 | pub fn crypto_hash_to_float(hash: u32) -> f32 { |
| 57 | let exp = (hash >> 23) & 0xFF; |
| 58 | let adjusted = if exp == 0 || exp == 255 { |
| 59 | hash ^ (1 << 23) |
| 60 | } else { |
| 61 | hash |
| 62 | }; |
| 63 | f32::from_bits(adjusted) |
| 64 | } |
| 65 | |
| 66 | /// Parses a Fusion `Fuse.Cryptomatte` `MatteList` string such as |
| 67 | /// `"\"floor\", \"Armature\", \"floor.001\""` or `"Hero, Tree"`. |
| 68 | /// |
| 69 | /// Handles double-quoted tokens (including escaped quotes/backslashes and embedded commas), |
| 70 | /// unquoted comma- or newline-separated tokens, trims whitespace, and ignores empty entries. |
| 71 | pub fn parse_matte_list(matte_list: &str) -> Vec<String> { |
| 72 | let mut out = Vec::new(); |
| 73 | let mut chars = matte_list.chars().peekable(); |
| 74 | |
| 75 | while let Some(&ch) = chars.peek() { |
| 76 | if ch.is_whitespace() || ch == ',' { |
| 77 | chars.next(); |
| 78 | continue; |
| 79 | } |
| 80 | |
| 81 | if ch == '"' { |
| 82 | chars.next(); // consume opening quote |
| 83 | let mut token = String::new(); |
| 84 | while let Some(c) = chars.next() { |
| 85 | if c == '\\' { |
| 86 | if let Some(escaped) = chars.next() { |
| 87 | match escaped { |
| 88 | 'n' => token.push('\n'), |
| 89 | 'r' => token.push('\r'), |
| 90 | 't' => token.push('\t'), |
| 91 | other => token.push(other), |
| 92 | } |
| 93 | } |
| 94 | } else if c == '"' { |
| 95 | break; |
| 96 | } else { |
| 97 | token.push(c); |
| 98 | } |
| 99 | } |
| 100 | if !token.is_empty() { |
| 101 | out.push(token); |
| 102 | } |
| 103 | // Skip trailing whitespace / separator after closing quote |
| 104 | while let Some(&next_ch) = chars.peek() { |
| 105 | if next_ch == ',' || next_ch == '\n' || next_ch == '\r' { |
| 106 | chars.next(); |
| 107 | break; |
| 108 | } else if next_ch.is_whitespace() { |
| 109 | chars.next(); |
| 110 | } else { |
| 111 | break; |
| 112 | } |
| 113 | } |
| 114 | } else { |
| 115 | let mut token = String::new(); |
| 116 | while let Some(&c) = chars.peek() { |
| 117 | if c == ',' || c == '\n' || c == '\r' { |
| 118 | chars.next(); |
| 119 | break; |
| 120 | } |
| 121 | token.push(c); |
| 122 | chars.next(); |
| 123 | } |
| 124 | let trimmed = token.trim(); |
| 125 | if !trimmed.is_empty() { |
| 126 | out.push(trimmed.to_string()); |
| 127 | } |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | out |
| 132 | } |
| 133 | |
| 134 | /// Lightweight zero-dependency parser for flat Cryptomatte JSON manifest objects |
| 135 | /// (`{"object_name": "a1b2c3d4", ...}`), handling JSON string escapes (`\"`, `\\`, `\uXXXX`) |
| 136 | /// and parsing the 8-hex-digit hash string into `u32`. |
| 137 | pub fn parse_manifest_json(json: &str) -> HashMap<String, u32> { |
| 138 | let mut map = HashMap::new(); |
| 139 | let bytes = json.as_bytes(); |
| 140 | let len = bytes.len(); |
| 141 | let mut pos = 0usize; |
| 142 | |
| 143 | let skip_ws = |p: &mut usize| { |
| 144 | while *p < len && matches!(bytes[*p], b' ' | b'\t' | b'\r' | b'\n') { |
| 145 | *p += 1; |
| 146 | } |
| 147 | }; |
| 148 | |
| 149 | skip_ws(&mut pos); |
| 150 | if pos >= len || bytes[pos] != b'{' { |
| 151 | return map; |
| 152 | } |
| 153 | pos += 1; // consume '{' |
| 154 | |
| 155 | loop { |
| 156 | skip_ws(&mut pos); |
| 157 | if pos >= len || bytes[pos] == b'}' { |
| 158 | break; |
| 159 | } |
| 160 | if bytes[pos] == b',' { |
| 161 | pos += 1; |
| 162 | continue; |
| 163 | } |
| 164 | let Some(key) = parse_json_string(json, &mut pos) else { |
| 165 | break; |
| 166 | }; |
| 167 | skip_ws(&mut pos); |
| 168 | if pos >= len || bytes[pos] != b':' { |
| 169 | break; |
| 170 | } |
| 171 | pos += 1; // consume ':' |
| 172 | skip_ws(&mut pos); |
| 173 | let Some(val_str) = parse_json_string(json, &mut pos) else { |
| 174 | break; |
| 175 | }; |
| 176 | let hex = val_str |
| 177 | .trim() |
| 178 | .trim_start_matches("0x") |
| 179 | .trim_start_matches("0X"); |
| 180 | if let Ok(hash) = u32::from_str_radix(hex, 16) { |
| 181 | map.insert(key, hash); |
| 182 | } |
| 183 | skip_ws(&mut pos); |
| 184 | if pos < len && bytes[pos] == b',' { |
| 185 | pos += 1; |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | map |
| 190 | } |
| 191 | |
| 192 | fn parse_json_string(src: &str, pos: &mut usize) -> Option<String> { |
| 193 | let bytes = src.as_bytes(); |
| 194 | if *pos >= bytes.len() || bytes[*pos] != b'"' { |
| 195 | return None; |
| 196 | } |
| 197 | *pos += 1; // consume opening '"' |
| 198 | let mut out = String::new(); |
| 199 | while *pos < bytes.len() { |
| 200 | let ch = src.get(*pos..)?.chars().next()?; |
| 201 | *pos += ch.len_utf8(); |
| 202 | match ch { |
| 203 | '"' => return Some(out), |
| 204 | '\\' => { |
| 205 | let esc = src.get(*pos..)?.chars().next()?; |
| 206 | *pos += esc.len_utf8(); |
| 207 | match esc { |
| 208 | '"' => out.push('"'), |
| 209 | '\\' => out.push('\\'), |
| 210 | '/' => out.push('/'), |
| 211 | 'b' => out.push('\u{0008}'), |
| 212 | 'f' => out.push('\u{000C}'), |
| 213 | 'n' => out.push('\n'), |
| 214 | 'r' => out.push('\r'), |
| 215 | 't' => out.push('\t'), |
| 216 | 'u' => { |
| 217 | let code_unit = parse_hex4(src, pos)?; |
| 218 | if (0xD800..=0xDBFF).contains(&code_unit) { |
| 219 | // UTF-16 surrogate pair |
| 220 | if src.get(*pos..).is_some_and(|s| s.starts_with("\\u")) { |
| 221 | *pos += 2; |
| 222 | let low = parse_hex4(src, pos)?; |
| 223 | if (0xDC00..=0xDFFF).contains(&low) { |
| 224 | let combined = 0x10000 |
| 225 | + ((u32::from(code_unit - 0xD800)) << 10) |
| 226 | + u32::from(low - 0xDC00); |
| 227 | if let Some(c) = char::from_u32(combined) { |
| 228 | out.push(c); |
| 229 | } |
| 230 | } |
| 231 | } |
| 232 | } else if let Some(c) = char::from_u32(u32::from(code_unit)) { |
| 233 | out.push(c); |
| 234 | } |
| 235 | } |
| 236 | other => out.push(other), |
| 237 | } |
| 238 | } |
| 239 | other => out.push(other), |
| 240 | } |
| 241 | } |
| 242 | None |
| 243 | } |
| 244 | |
| 245 | fn parse_hex4(src: &str, pos: &mut usize) -> Option<u16> { |
| 246 | let end = pos.checked_add(4)?; |
| 247 | let slice = src.get(*pos..end)?; |
| 248 | let val = u16::from_str_radix(slice, 16).ok()?; |
| 249 | *pos = end; |
| 250 | Some(val) |
| 251 | } |
| 252 | |
| 253 | #[derive(Default)] |
| 254 | struct CryptoLayerMeta { |
| 255 | name: Option<String>, |
| 256 | manifest: Option<String>, |
| 257 | manif_file: Option<String>, |
| 258 | } |
| 259 | |
| 260 | fn attr_value_to_string(val: &exr::meta::attribute::AttributeValue) -> Option<String> { |
| 261 | use exr::meta::attribute::AttributeValue; |
| 262 | match val { |
| 263 | AttributeValue::Text(t) => Some(t.to_string()), |
| 264 | AttributeValue::Bytes { bytes, .. } => { |
| 265 | Some(String::from_utf8_lossy(bytes.as_slice()).into_owned()) |
| 266 | } |
| 267 | AttributeValue::Custom { bytes, .. } => { |
| 268 | Some(String::from_utf8_lossy(bytes.as_slice()).into_owned()) |
| 269 | } |
| 270 | _ => None, |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | fn collect_crypto_metadata_from_map( |
| 275 | other: &HashMap<exr::meta::attribute::Text, exr::meta::attribute::AttributeValue>, |
| 276 | out: &mut BTreeMap<String, CryptoLayerMeta>, |
| 277 | ) { |
| 278 | for (k, v) in other { |
| 279 | let key = k.to_string(); |
| 280 | let Some(rest) = key.strip_prefix("cryptomatte/") else { |
| 281 | continue; |
| 282 | }; |
| 283 | let Some((id, field)) = rest.split_once('/') else { |
| 284 | continue; |
| 285 | }; |
| 286 | if id.is_empty() { |
| 287 | continue; |
| 288 | } |
| 289 | let Some(val_str) = attr_value_to_string(v) else { |
| 290 | continue; |
| 291 | }; |
| 292 | let entry = out.entry(id.to_string()).or_default(); |
| 293 | match field { |
| 294 | "name" => entry.name = Some(val_str), |
| 295 | "manifest" => entry.manifest = Some(val_str), |
| 296 | "manif_file" => entry.manif_file = Some(val_str), |
| 297 | _ => {} |
| 298 | } |
| 299 | } |
| 300 | } |
| 301 | |
| 302 | fn parse_channel_component(comp: &str) -> Option<usize> { |
| 303 | match comp.to_ascii_lowercase().as_str() { |
| 304 | "r" | "red" => Some(0), |
| 305 | "g" | "green" => Some(1), |
| 306 | "b" | "blue" => Some(2), |
| 307 | "a" | "alpha" => Some(3), |
| 308 | _ => None, |
| 309 | } |
| 310 | } |
| 311 | |
| 312 | /// Splits a full EXR channel name such as `"ViewLayer.CryptoObject00.R"` into |
| 313 | /// `("ViewLayer.CryptoObject", 0, 0)` (prefix, rank, rgba component index). |
| 314 | fn split_crypto_rank_channel(full_name: &str) -> Option<(&str, u8, usize)> { |
| 315 | let (chan_layer, comp_name) = full_name.rsplit_once('.')?; |
| 316 | let comp_idx = parse_channel_component(comp_name)?; |
| 317 | if chan_layer.len() < 3 { |
| 318 | return None; |
| 319 | } |
| 320 | let split_at = chan_layer.len() - 2; |
| 321 | let digits = chan_layer.get(split_at..)?; |
| 322 | if !digits.bytes().all(|b| b.is_ascii_digit()) { |
| 323 | return None; |
| 324 | } |
| 325 | let rank: u8 = digits.parse().ok()?; |
| 326 | let prefix = &chan_layer[..split_at]; |
| 327 | if prefix.is_empty() { |
| 328 | return None; |
| 329 | } |
| 330 | Some((prefix, rank, comp_idx)) |
| 331 | } |
| 332 | |
| 333 | fn full_channel_name(layer_name: Option<&str>, ch_name: &str) -> String { |
| 334 | if let Some(ln) = layer_name.filter(|s| !s.is_empty()) { |
| 335 | if ch_name == ln || ch_name.starts_with(&format!("{ln}.")) { |
| 336 | ch_name.to_string() |
| 337 | } else { |
| 338 | format!("{ln}.{ch_name}") |
| 339 | } |
| 340 | } else { |
| 341 | ch_name.to_string() |
| 342 | } |
| 343 | } |
| 344 | |
| 345 | fn prefix_matches(candidate_prefix: &str, requested: &str) -> bool { |
| 346 | candidate_prefix == requested |
| 347 | || candidate_prefix.ends_with(&format!(".{requested}")) |
| 348 | || candidate_prefix.eq_ignore_ascii_case(requested) |
| 349 | || candidate_prefix |
| 350 | .to_ascii_lowercase() |
| 351 | .ends_with(&format!(".{}", requested.to_ascii_lowercase())) |
| 352 | } |
| 353 | |
| 354 | fn glob_match(pattern: &str, text: &str) -> bool { |
| 355 | let p: Vec<char> = pattern.chars().collect(); |
| 356 | let t: Vec<char> = text.chars().collect(); |
| 357 | let (mut pi, mut ti) = (0usize, 0usize); |
| 358 | let mut star_pi: Option<usize> = None; |
| 359 | let mut star_ti = 0usize; |
| 360 | |
| 361 | while ti < t.len() { |
| 362 | if pi < p.len() && (p[pi] == '?' || p[pi] == t[ti]) { |
| 363 | pi += 1; |
| 364 | ti += 1; |
| 365 | } else if pi < p.len() && p[pi] == '*' { |
| 366 | star_pi = Some(pi); |
| 367 | star_ti = ti; |
| 368 | pi += 1; |
| 369 | } else if let Some(sp) = star_pi { |
| 370 | pi = sp + 1; |
| 371 | star_ti += 1; |
| 372 | ti = star_ti; |
| 373 | } else { |
| 374 | return false; |
| 375 | } |
| 376 | } |
| 377 | |
| 378 | while pi < p.len() && p[pi] == '*' { |
| 379 | pi += 1; |
| 380 | } |
| 381 | pi == p.len() |
| 382 | } |
| 383 | |
| 384 | fn parse_hex_literal_token(token: &str) -> Option<u32> { |
| 385 | let inner = token.strip_prefix('<')?.strip_suffix('>')?.trim(); |
| 386 | let hex = inner |
| 387 | .strip_prefix("0x") |
| 388 | .or_else(|| inner.strip_prefix("0X"))?; |
| 389 | u32::from_str_radix(hex, 16).ok() |
| 390 | } |
| 391 | |
| 392 | #[cfg(not(target_arch = "wasm32"))] |
| 393 | const CRYPTO_PARALLEL_THRESHOLD_PIXELS: usize = 512 * 512; |
| 394 | |
| 395 | #[inline] |
| 396 | fn accumulate_chunk_with<F: Fn(u32) -> bool>( |
| 397 | out: &mut [f32], |
| 398 | start: usize, |
| 399 | pairs: &[(&[f32], &[f32])], |
| 400 | contains_id: F, |
| 401 | ) { |
| 402 | let len = out.len(); |
| 403 | for &(ids, covs) in pairs { |
| 404 | let ids_slice = &ids[start..start + len]; |
| 405 | let covs_slice = &covs[start..start + len]; |
| 406 | for i in 0..len { |
| 407 | if contains_id(ids_slice[i].to_bits()) { |
| 408 | let cov = covs_slice[i]; |
| 409 | if cov.is_finite() { |
| 410 | out[i] += cov; |
| 411 | } |
| 412 | } |
| 413 | } |
| 414 | } |
| 415 | for v in out { |
| 416 | *v = if v.is_nan() { 0.0 } else { v.clamp(0.0, 1.0) }; |
| 417 | } |
| 418 | } |
| 419 | |
| 420 | fn accumulate_cryptomatte_chunk( |
| 421 | out: &mut [f32], |
| 422 | start: usize, |
| 423 | pairs: &[(&[f32], &[f32])], |
| 424 | target_ids: &HashSet<u32>, |
| 425 | ) { |
| 426 | if target_ids.len() <= 8 { |
| 427 | let mut stack_ids = [0u32; 8]; |
| 428 | let mut count = 0usize; |
| 429 | for &id in target_ids { |
| 430 | stack_ids[count] = id; |
| 431 | count += 1; |
| 432 | } |
| 433 | let ids_slice = &stack_ids[..count]; |
| 434 | accumulate_chunk_with(out, start, pairs, |bits| ids_slice.contains(&bits)); |
| 435 | } else { |
| 436 | accumulate_chunk_with(out, start, pairs, |bits| target_ids.contains(&bits)); |
| 437 | } |
| 438 | } |
| 439 | |
| 440 | fn accumulate_cryptomatte_scalar( |
| 441 | pairs: &[(&[f32], &[f32])], |
| 442 | target_ids: &HashSet<u32>, |
| 443 | pixel_count: usize, |
| 444 | ) -> Vec<f32> { |
| 445 | let mut matte = vec![0.0_f32; pixel_count]; |
| 446 | if !target_ids.is_empty() && !pairs.is_empty() { |
| 447 | accumulate_cryptomatte_chunk(&mut matte, 0, pairs, target_ids); |
| 448 | } |
| 449 | matte |
| 450 | } |
| 451 | |
| 452 | /// Accumulates Cryptomatte `(id, coverage)` rank pairs into a clamped `[0.0, 1.0]` matte, |
| 453 | /// splitting across bounded worker threads for `>= 512 * 512` images on native targets. |
| 454 | fn accumulate_cryptomatte_matte( |
| 455 | pairs: &[(&[f32], &[f32])], |
| 456 | target_ids: &HashSet<u32>, |
| 457 | pixel_count: usize, |
| 458 | ) -> Vec<f32> { |
| 459 | if target_ids.is_empty() || pairs.is_empty() { |
| 460 | return vec![0.0_f32; pixel_count]; |
| 461 | } |
| 462 | #[cfg(not(target_arch = "wasm32"))] |
| 463 | if pixel_count >= CRYPTO_PARALLEL_THRESHOLD_PIXELS { |
| 464 | let workers = std::thread::available_parallelism() |
| 465 | .map(|n| n.get().clamp(2, 8)) |
| 466 | .unwrap_or(4); |
| 467 | let chunk_len = pixel_count.div_ceil(workers).max(1); |
| 468 | let mut matte = vec![0.0_f32; pixel_count]; |
| 469 | std::thread::scope(|scope| { |
| 470 | let mut offset = 0usize; |
| 471 | for chunk in matte.chunks_mut(chunk_len) { |
| 472 | let start = offset; |
| 473 | offset += chunk.len(); |
| 474 | scope.spawn(move || accumulate_cryptomatte_chunk(chunk, start, pairs, target_ids)); |
| 475 | } |
| 476 | }); |
| 477 | return matte; |
| 478 | } |
| 479 | accumulate_cryptomatte_scalar(pairs, target_ids, pixel_count) |
| 480 | } |
| 481 | |
| 482 | /// Lists Cryptomatte layer names discovered in an OpenEXR file's header metadata |
| 483 | /// (falling back to rank-00 channel prefix discovery when metadata is absent). |
| 484 | pub fn list_cryptomatte_layers(exr_path: &Path) -> Vec<String> { |
| 485 | let Ok(meta) = exr::meta::MetaData::read_from_file(exr_path, false) else { |
| 486 | return Vec::new(); |
| 487 | }; |
| 488 | let mut crypto_meta: BTreeMap<String, CryptoLayerMeta> = BTreeMap::new(); |
| 489 | for header in &meta.headers { |
| 490 | collect_crypto_metadata_from_map(&header.shared_attributes.other, &mut crypto_meta); |
| 491 | collect_crypto_metadata_from_map(&header.own_attributes.other, &mut crypto_meta); |
| 492 | } |
| 493 | |
| 494 | let mut layers = Vec::new(); |
| 495 | for entry in crypto_meta.values() { |
| 496 | if let Some(name) = entry.name.as_ref().filter(|s| !s.is_empty()) { |
| 497 | if !layers.contains(name) { |
| 498 | layers.push(name.clone()); |
| 499 | } |
| 500 | } |
| 501 | } |
| 502 | |
| 503 | if !layers.is_empty() { |
| 504 | return layers; |
| 505 | } |
| 506 | |
| 507 | // Fallback: infer Cryptomatte layer prefixes from `00.R` channels. |
| 508 | for header in &meta.headers { |
| 509 | let lname = header.own_attributes.layer_name.as_ref().map(|t| t.to_string()); |
| 510 | for ch in &header.channels.list { |
| 511 | let full = full_channel_name(lname.as_deref(), &ch.name.to_string()); |
| 512 | if let Some((prefix, 0, 0)) = split_crypto_rank_channel(&full) { |
| 513 | let p = prefix.to_string(); |
| 514 | if !layers.contains(&p) { |
| 515 | layers.push(p); |
| 516 | } |
| 517 | } |
| 518 | } |
| 519 | } |
| 520 | |
| 521 | layers |
| 522 | } |
| 523 | |
| 524 | /// Extracts a Cryptomatte coverage matte from a multi-channel OpenEXR file. |
| 525 | /// |
| 526 | /// - Reads header metadata first and selectively decompresses only the layers containing |
| 527 | /// matched Cryptomatte rank channels via `exr::block::read` + `filter_chunks`. |
| 528 | /// - Resolves `cryptomatte/<id>/name`, `cryptomatte/<id>/manifest`, and sidecar |
| 529 | /// `cryptomatte/<id>/manif_file` relative to `exr_path.parent()`. |
| 530 | /// - Matches `layer_name` by exact name, suffix (e.g. `"CryptoObject"` -> `"ViewLayer.CryptoObject"`), |
| 531 | /// or falls back to the first Cryptomatte layer when `layer_name` is `None`/empty. |
| 532 | /// - Accumulates coverage across all rank channel groups (`<prefix>00`..`<prefix>09`) |
| 533 | /// for `(R, G)` and `(B, A)` pairs and clamps the final matte to `[0.0, 1.0]`. |
| 534 | pub fn extract_cryptomatte( |
| 535 | exr_path: &Path, |
| 536 | layer_name: Option<&str>, |
| 537 | matte_list: &str, |
| 538 | ) -> Option<CryptomatteResult> { |
| 539 | use exr::block::reader::ChunksReader; |
| 540 | use exr::meta::attribute::SampleType; |
| 541 | use exr::prelude::*; |
| 542 | |
| 543 | let file = std::fs::File::open(exr_path).ok()?; |
| 544 | let reader = std::io::BufReader::with_capacity(256 * 1024, file); |
| 545 | let chunks_reader = exr::block::read(reader, false).ok()?; |
| 546 | |
| 547 | // 1. Collect Cryptomatte header metadata from shared and layer-level `other` attributes. |
| 548 | let mut crypto_meta: BTreeMap<String, CryptoLayerMeta> = BTreeMap::new(); |
| 549 | for header in chunks_reader.headers() { |
| 550 | collect_crypto_metadata_from_map(&header.shared_attributes.other, &mut crypto_meta); |
| 551 | collect_crypto_metadata_from_map(&header.own_attributes.other, &mut crypto_meta); |
| 552 | } |
| 553 | |
| 554 | // 2. Select target Cryptomatte layer and manifest. |
| 555 | let req_layer = layer_name.map(str::trim).filter(|s| !s.is_empty()); |
| 556 | let selected_meta: Option<&CryptoLayerMeta> = if let Some(req) = req_layer { |
| 557 | crypto_meta |
| 558 | .values() |
| 559 | .find(|m| m.name.as_deref() == Some(req)) |
| 560 | .or_else(|| { |
| 561 | crypto_meta |
| 562 | .values() |
| 563 | .find(|m| m.name.as_deref().is_some_and(|n| prefix_matches(n, req))) |
| 564 | }) |
| 565 | } else { |
| 566 | crypto_meta |
| 567 | .values() |
| 568 | .find(|m| m.name.as_deref().is_some_and(|n| !n.is_empty())) |
| 569 | }; |
| 570 | |
| 571 | let selected_prefix: String = if let Some(name) = selected_meta.and_then(|m| m.name.clone()) { |
| 572 | name |
| 573 | } else if let Some(req) = req_layer { |
| 574 | req.to_string() |
| 575 | } else { |
| 576 | // Fallback: infer first rank-00 prefix from headers. |
| 577 | let mut inferred = None; |
| 578 | 'outer: for header in chunks_reader.headers() { |
| 579 | if header.deep { |
| 580 | continue; |
| 581 | } |
| 582 | let lname = header.own_attributes.layer_name.as_ref().map(|t| t.to_string()); |
| 583 | for ch in &header.channels.list { |
| 584 | let full = full_channel_name(lname.as_deref(), &ch.name.to_string()); |
| 585 | if let Some((prefix, 0, 0)) = split_crypto_rank_channel(&full) { |
| 586 | inferred = Some(prefix.to_string()); |
| 587 | break 'outer; |
| 588 | } |
| 589 | } |
| 590 | } |
| 591 | inferred? |
| 592 | }; |
| 593 | |
| 594 | let mut manifest: HashMap<String, u32> = HashMap::new(); |
| 595 | if let Some(meta) = selected_meta { |
| 596 | if let Some(inline_json) = &meta.manifest { |
| 597 | manifest.extend(parse_manifest_json(inline_json)); |
| 598 | } |
| 599 | if let Some(sidecar) = meta.manif_file.as_deref().filter(|s| !s.is_empty()) { |
| 600 | let sidecar_path = exr_path |
| 601 | .parent() |
| 602 | .map(|p| p.join(sidecar)) |
| 603 | .unwrap_or_else(|| Path::new(sidecar).to_path_buf()); |
| 604 | if let Ok(sidecar_json) = std::fs::read_to_string(&sidecar_path) { |
| 605 | for (k, v) in parse_manifest_json(&sidecar_json) { |
| 606 | manifest.entry(k).or_insert(v); |
| 607 | } |
| 608 | } |
| 609 | } |
| 610 | } |
| 611 | |
| 612 | // 3. Build target f32 bit-pattern ID set from matte_list. |
| 613 | let mut target_ids: HashSet<u32> = HashSet::new(); |
| 614 | for token in parse_matte_list(matte_list) { |
| 615 | if let Some(hex_val) = parse_hex_literal_token(&token) { |
| 616 | target_ids.insert(hex_val); |
| 617 | target_ids.insert(crypto_hash_to_float(hex_val).to_bits()); |
| 618 | continue; |
| 619 | } |
| 620 | if token.contains('*') || token.contains('?') { |
| 621 | for (name, &h) in &manifest { |
| 622 | if glob_match(&token, name) { |
| 623 | target_ids.insert(crypto_hash_to_float(h).to_bits()); |
| 624 | } |
| 625 | } |
| 626 | continue; |
| 627 | } |
| 628 | if let Some(&h) = manifest.get(&token) { |
| 629 | target_ids.insert(crypto_hash_to_float(h).to_bits()); |
| 630 | } |
| 631 | let direct_hash = murmur3_32(token.as_bytes(), 0); |
| 632 | target_ids.insert(crypto_hash_to_float(direct_hash).to_bits()); |
| 633 | } |
| 634 | |
| 635 | // 4. Identify matching rank channel groups (<prefix>00 .. <prefix>09) from headers first. |
| 636 | let mut dims: Option<(usize, usize)> = None; |
| 637 | let mut seen_slots = [[false; 4]; 10]; |
| 638 | let mut matched_channels: Vec<((usize, usize), u8, usize)> = Vec::new(); |
| 639 | let mut needed_layers: Vec<usize> = Vec::new(); |
| 640 | |
| 641 | for (li, header) in chunks_reader.headers().iter().enumerate() { |
| 642 | if header.deep { |
| 643 | continue; |
| 644 | } |
| 645 | let lw = header.layer_size.width(); |
| 646 | let lh = header.layer_size.height(); |
| 647 | if lw == 0 || lh == 0 { |
| 648 | continue; |
| 649 | } |
| 650 | let lname = header.own_attributes.layer_name.as_ref().map(|t| t.to_string()); |
| 651 | for (ci, ch) in header.channels.list.iter().enumerate() { |
| 652 | if ch.sampling != Vec2(1, 1) { |
| 653 | continue; |
| 654 | } |
| 655 | let full = full_channel_name(lname.as_deref(), &ch.name.to_string()); |
| 656 | let Some((prefix, rank, comp_idx)) = split_crypto_rank_channel(&full) else { |
| 657 | continue; |
| 658 | }; |
| 659 | if rank > 9 || !prefix_matches(prefix, &selected_prefix) { |
| 660 | continue; |
| 661 | } |
| 662 | if let Some((w, h)) = dims { |
| 663 | if lw != w || lh != h { |
| 664 | continue; |
| 665 | } |
| 666 | } else { |
| 667 | dims = Some((lw, lh)); |
| 668 | } |
| 669 | if seen_slots[rank as usize][comp_idx] { |
| 670 | continue; |
| 671 | } |
| 672 | seen_slots[rank as usize][comp_idx] = true; |
| 673 | matched_channels.push(((li, ci), rank, comp_idx)); |
| 674 | if !needed_layers.contains(&li) { |
| 675 | needed_layers.push(li); |
| 676 | } |
| 677 | } |
| 678 | } |
| 679 | |
| 680 | let (w, h) = dims?; |
| 681 | const MAX_CRYPTO_PIXELS: usize = 64 * 1024 * 1024; |
| 682 | const MAX_CRYPTO_BYTES: usize = 512 * 1024 * 1024; |
| 683 | let pixel_count = w.checked_mul(h)?; |
| 684 | if w > u32::MAX as usize || h > u32::MAX as usize || pixel_count > MAX_CRYPTO_PIXELS { |
| 685 | return None; |
| 686 | } |
| 687 | let total_slot_bytes = pixel_count |
| 688 | .checked_mul(matched_channels.len().max(1))? |
| 689 | .checked_mul(std::mem::size_of::<f32>())?; |
| 690 | if total_slot_bytes > MAX_CRYPTO_BYTES { |
| 691 | return None; |
| 692 | } |
| 693 | if target_ids.is_empty() { |
| 694 | let mut matte = Vec::new(); |
| 695 | matte.try_reserve_exact(pixel_count).ok()?; |
| 696 | matte.resize(pixel_count, 0.0_f32); |
| 697 | return Some(CryptomatteResult { |
| 698 | size: [w as u32, h as u32], |
| 699 | matte, |
| 700 | }); |
| 701 | } |
| 702 | |
| 703 | let mut slot_buffers: Vec<(u8, usize, Vec<f32>)> = Vec::with_capacity(matched_channels.len()); |
| 704 | let mut loc_to_slot: HashMap<(usize, usize), usize> = |
| 705 | HashMap::with_capacity(matched_channels.len()); |
| 706 | for (loc, rank, comp_idx) in matched_channels { |
| 707 | let idx = slot_buffers.len(); |
| 708 | let mut buf = Vec::new(); |
| 709 | buf.try_reserve_exact(pixel_count).ok()?; |
| 710 | buf.resize(pixel_count, 0.0_f32); |
| 711 | slot_buffers.push((rank, comp_idx, buf)); |
| 712 | loc_to_slot.insert(loc, idx); |
| 713 | } |
| 714 | |
| 715 | let mut line_f16 = Vec::<f16>::new(); |
| 716 | let mut line_u32 = Vec::<u32>::new(); |
| 717 | chunks_reader |
| 718 | .filter_chunks(false, |_, tile, block| { |
| 719 | tile.is_largest_resolution_level() && needed_layers.contains(&block.layer) |
| 720 | }) |
| 721 | .ok()? |
| 722 | .decompress_parallel(false, |meta, block| { |
| 723 | let header = &meta.headers[block.index.layer]; |
| 724 | for line in block.lines(&header.channels) { |
| 725 | let Some(&slot_idx) = |
| 726 | loc_to_slot.get(&(line.location.layer, line.location.channel)) |
| 727 | else { |
| 728 | continue; |
| 729 | }; |
| 730 | let y = line.location.position.y(); |
| 731 | let x0 = line.location.position.x(); |
| 732 | let len = line.location.sample_count; |
| 733 | if y >= h || x0.saturating_add(len) > w { |
| 734 | continue; |
| 735 | } |
| 736 | let row_base = y * w + x0; |
| 737 | let dst = &mut slot_buffers[slot_idx].2[row_base..row_base + len]; |
| 738 | match header.channels.list[line.location.channel].sample_type { |
| 739 | SampleType::F32 => { |
| 740 | line.read_samples_into_slice(dst)?; |
| 741 | } |
| 742 | SampleType::F16 => { |
| 743 | line_f16.resize(len, f16::ZERO); |
| 744 | line.read_samples_into_slice(&mut line_f16)?; |
| 745 | for (d, &s) in dst.iter_mut().zip(line_f16.iter()) { |
| 746 | *d = s.to_f32(); |
| 747 | } |
| 748 | } |
| 749 | SampleType::U32 => { |
| 750 | line_u32.resize(len, 0); |
| 751 | line.read_samples_into_slice(&mut line_u32)?; |
| 752 | for (d, &s) in dst.iter_mut().zip(line_u32.iter()) { |
| 753 | *d = s as f32; |
| 754 | } |
| 755 | } |
| 756 | } |
| 757 | } |
| 758 | Ok(()) |
| 759 | }) |
| 760 | .ok()?; |
| 761 | |
| 762 | // 5. Accumulate coverage across all rank (ID, coverage) pairs. |
| 763 | let mut ranks: BTreeMap<u8, [Option<&[f32]>; 4]> = BTreeMap::new(); |
| 764 | for (rank, comp_idx, buf) in &slot_buffers { |
| 765 | let slots = ranks.entry(*rank).or_insert([None, None, None, None]); |
| 766 | slots[*comp_idx] = Some(buf.as_slice()); |
| 767 | } |
| 768 | let mut pairs: Vec<(&[f32], &[f32])> = Vec::with_capacity(ranks.len() * 2); |
| 769 | for slots in ranks.values() { |
| 770 | if let (Some(ids), Some(covs)) = (slots[0], slots[1]) { |
| 771 | pairs.push((ids, covs)); |
| 772 | } |
| 773 | if let (Some(ids), Some(covs)) = (slots[2], slots[3]) { |
| 774 | pairs.push((ids, covs)); |
| 775 | } |
| 776 | } |
| 777 | let matte = accumulate_cryptomatte_matte(&pairs, &target_ids, pixel_count); |
| 778 | |
| 779 | Some(CryptomatteResult { |
| 780 | size: [w as u32, h as u32], |
| 781 | matte, |
| 782 | }) |
| 783 | } |
| 784 | |
| 785 | #[cfg(test)] |
| 786 | mod tests { |
| 787 | use super::*; |
| 788 | use crate::media::MediaCache; |
| 789 | use model::ClipSpec; |
| 790 | |
| 791 | #[test] |
| 792 | fn test_murmur3_and_crypto_hash_to_float() { |
| 793 | // Known MurmurHash3-32 (seed = 0) test vectors from the Cryptomatte / SMHasher specs. |
| 794 | assert_eq!(murmur3_32(b"", 0), 0x0000_0000); |
| 795 | assert_eq!(murmur3_32(b"hello", 0), 0x248b_fa47); |
| 796 | assert_eq!(murmur3_32(b"bunny", 0), 0x1385_1a76); |
| 797 | assert_eq!( |
| 798 | murmur3_32(b"The quick brown fox jumps over the lazy dog", 0), |
| 799 | 0x2e4f_f723 |
| 800 | ); |
| 801 | |
| 802 | // Normal exponent (not 0 and not 255) is preserved bit-for-bit. |
| 803 | let hello_hash = murmur3_32(b"hello", 0); |
| 804 | assert_eq!(crypto_hash_to_float(hello_hash).to_bits(), hello_hash); |
| 805 | |
| 806 | let bunny_hash = murmur3_32(b"bunny", 0); |
| 807 | assert_eq!(crypto_hash_to_float(bunny_hash).to_bits(), bunny_hash); |
| 808 | |
| 809 | // Exponent == 0 (subnormal / zero) must flip bit 23 so exponent becomes 1. |
| 810 | let zero_exp_pos: u32 = 0x0012_3456; |
| 811 | let f_pos = crypto_hash_to_float(zero_exp_pos); |
| 812 | assert_eq!(f_pos.to_bits(), zero_exp_pos ^ (1 << 23)); |
| 813 | assert_eq!((f_pos.to_bits() >> 23) & 0xFF, 1); |
| 814 | assert!(f_pos.is_normal()); |
| 815 | |
| 816 | let zero_exp_neg: u32 = 0x8000_0000; |
| 817 | let f_neg = crypto_hash_to_float(zero_exp_neg); |
| 818 | assert_eq!(f_neg.to_bits(), zero_exp_neg ^ (1 << 23)); |
| 819 | assert_eq!((f_neg.to_bits() >> 23) & 0xFF, 1); |
| 820 | |
| 821 | // Exponent == 255 (inf / NaN) must flip bit 23 so exponent becomes 254. |
| 822 | let nan_exp: u32 = 0x7f80_1234; |
| 823 | let f_nan = crypto_hash_to_float(nan_exp); |
| 824 | assert_eq!(f_nan.to_bits(), nan_exp ^ (1 << 23)); |
| 825 | assert_eq!((f_nan.to_bits() >> 23) & 0xFF, 254); |
| 826 | assert!(f_nan.is_finite()); |
| 827 | } |
| 828 | |
| 829 | #[test] |
| 830 | fn test_parse_matte_list_and_manifest() { |
| 831 | let parsed = parse_matte_list("\"floor\", \"Armature\", \"floor.001\""); |
| 832 | assert_eq!(parsed, vec!["floor", "Armature", "floor.001"]); |
| 833 | |
| 834 | let unquoted = parse_matte_list("Hero, Tree\n Rock , "); |
| 835 | assert_eq!(unquoted, vec!["Hero", "Tree", "Rock"]); |
| 836 | |
| 837 | let escaped = parse_matte_list("\"obj, with, commas\", \"quote \\\"inside\\\"\""); |
| 838 | assert_eq!(escaped, vec!["obj, with, commas", "quote \"inside\""]); |
| 839 | |
| 840 | let manifest_json = r#"{ |
| 841 | "Hero": "a1b2c3d4", |
| 842 | "Tree \"Oak\"": "00112233", |
| 843 | "Path\\Node": "deadbeef", |
| 844 | "Unicode\u0041": "01020304" |
| 845 | }"#; |
| 846 | let manifest = parse_manifest_json(manifest_json); |
| 847 | assert_eq!(manifest.len(), 4); |
| 848 | assert_eq!(manifest.get("Hero"), Some(&0xa1b2_c3d4)); |
| 849 | assert_eq!(manifest.get("Tree \"Oak\""), Some(&0x0011_2233)); |
| 850 | assert_eq!(manifest.get("Path\\Node"), Some(&0xdead_beef)); |
| 851 | assert_eq!(manifest.get("UnicodeA"), Some(&0x0102_0304)); |
| 852 | } |
| 853 | |
| 854 | #[test] |
| 855 | fn test_synthetic_hdr_exr_and_cryptomatte() { |
| 856 | use exr::prelude::*; |
| 857 | |
| 858 | let w = 4usize; |
| 859 | let h = 2usize; |
| 860 | let n = w * h; |
| 861 | |
| 862 | let hero_hash = murmur3_32(b"Hero", 0); |
| 863 | let tree_hash = murmur3_32(b"Tree", 0); |
| 864 | let hero_id = crypto_hash_to_float(hero_hash); |
| 865 | let tree_id = crypto_hash_to_float(tree_hash); |
| 866 | |
| 867 | // HDR combined channels: pixel 0 has HDR highlight 3.75, negative value -0.25, and NaN in pixel 1. |
| 868 | let mut comb_r = vec![0.5_f32; n]; |
| 869 | let mut comb_g = vec![0.25_f32; n]; |
| 870 | let mut comb_b = vec![0.125_f32; n]; |
| 871 | let comb_a = vec![1.0_f32; n]; |
| 872 | comb_r[0] = 3.75; |
| 873 | comb_g[0] = -0.25; |
| 874 | comb_b[1] = f32::NAN; |
| 875 | |
| 876 | // Cryptomatte rank 00 (R/G = rank 0, B/A = rank 1) and rank 01 (R/G = rank 2, B/A = rank 3). |
| 877 | // Pixel 0: anti-aliased edge with Hero (0.7 in rank 0) + Tree (0.3 in rank 1). |
| 878 | // Pixel 1: Hero (1.0 in rank 0). |
| 879 | // Pixel 2: Tree (0.4 in rank 0) + Hero (0.6 in rank 2 inside CryptoObject01.R/G). |
| 880 | let mut c00_r = vec![0.0_f32; n]; |
| 881 | let mut c00_g = vec![0.0_f32; n]; |
| 882 | let mut c00_b = vec![0.0_f32; n]; |
| 883 | let mut c00_a = vec![0.0_f32; n]; |
| 884 | |
| 885 | let mut c01_r = vec![0.0_f32; n]; |
| 886 | let mut c01_g = vec![0.0_f32; n]; |
| 887 | let c01_b = vec![0.0_f32; n]; |
| 888 | let c01_a = vec![0.0_f32; n]; |
| 889 | |
| 890 | // Pixel 0: Hero 0.7 (rank 0), Tree 0.3 (rank 1) |
| 891 | c00_r[0] = hero_id; |
| 892 | c00_g[0] = 0.7; |
| 893 | c00_b[0] = tree_id; |
| 894 | c00_a[0] = 0.3; |
| 895 | |
| 896 | // Pixel 1: Hero 1.0 (rank 0) |
| 897 | c00_r[1] = hero_id; |
| 898 | c00_g[1] = 1.0; |
| 899 | |
| 900 | // Pixel 2: Tree 0.4 (rank 0), Hero 0.6 (rank 2 in CryptoObject01) |
| 901 | c00_r[2] = tree_id; |
| 902 | c00_g[2] = 0.4; |
| 903 | c01_r[2] = hero_id; |
| 904 | c01_g[2] = 0.6; |
| 905 | |
| 906 | let channels = AnyChannels::sort(SmallVec::from_vec(vec![ |
| 907 | AnyChannel::new("ViewLayer.Combined.R", FlatSamples::F32(comb_r)), |
| 908 | AnyChannel::new("ViewLayer.Combined.G", FlatSamples::F32(comb_g)), |
| 909 | AnyChannel::new("ViewLayer.Combined.B", FlatSamples::F32(comb_b)), |
| 910 | AnyChannel::new("ViewLayer.Combined.A", FlatSamples::F32(comb_a)), |
| 911 | AnyChannel::new("ViewLayer.CryptoObject00.R", FlatSamples::F32(c00_r)), |
| 912 | AnyChannel::new("ViewLayer.CryptoObject00.G", FlatSamples::F32(c00_g)), |
| 913 | AnyChannel::new("ViewLayer.CryptoObject00.B", FlatSamples::F32(c00_b)), |
| 914 | AnyChannel::new("ViewLayer.CryptoObject00.A", FlatSamples::F32(c00_a)), |
| 915 | AnyChannel::new("ViewLayer.CryptoObject01.R", FlatSamples::F32(c01_r)), |
| 916 | AnyChannel::new("ViewLayer.CryptoObject01.G", FlatSamples::F32(c01_g)), |
| 917 | AnyChannel::new("ViewLayer.CryptoObject01.B", FlatSamples::F32(c01_b)), |
| 918 | AnyChannel::new("ViewLayer.CryptoObject01.A", FlatSamples::F32(c01_a)), |
| 919 | ])); |
| 920 | |
| 921 | let manifest_json = format!( |
| 922 | r#"{{"Hero":"{:08x}","Tree":"{:08x}"}}"#, |
| 923 | hero_hash, tree_hash |
| 924 | ); |
| 925 | |
| 926 | let mut layer_attrs = LayerAttributes::default(); |
| 927 | layer_attrs.other.insert( |
| 928 | Text::new_or_panic("cryptomatte/abcdef0/name"), |
| 929 | AttributeValue::Text(Text::new_or_panic("ViewLayer.CryptoObject")), |
| 930 | ); |
| 931 | layer_attrs.other.insert( |
| 932 | Text::new_or_panic("cryptomatte/abcdef0/manifest"), |
| 933 | AttributeValue::Text(Text::new_or_panic(&manifest_json)), |
| 934 | ); |
| 935 | |
| 936 | let layer = Layer::new( |
| 937 | (w, h), |
| 938 | layer_attrs, |
| 939 | Encoding::FAST_LOSSLESS, |
| 940 | channels, |
| 941 | ); |
| 942 | let image = Image::from_layer(layer); |
| 943 | |
| 944 | let tmp_path = std::env::temp_dir().join(format!( |
| 945 | "engine_test_hdr_crypto_{}.exr", |
| 946 | std::process::id() |
| 947 | )); |
| 948 | image |
| 949 | .write() |
| 950 | .to_file(&tmp_path) |
| 951 | .expect("failed to write synthetic EXR"); |
| 952 | |
| 953 | // 1. Verify MediaCache::load_clip preserves unclamped HDR f32 values & sanitizes NaN. |
| 954 | let mut cache = MediaCache::new(64); |
| 955 | let clip = ClipSpec { |
| 956 | filename: tmp_path.to_string_lossy().into_owned(), |
| 957 | alternate_filename: None, |
| 958 | start_frame: 0, |
| 959 | length: Some(1), |
| 960 | trim_in: 0, |
| 961 | trim_out: 0, |
| 962 | global_start: 0, |
| 963 | global_end: 0, |
| 964 | extend_first: 0, |
| 965 | extend_last: 0, |
| 966 | loop_clip: false, |
| 967 | reverse: false, |
| 968 | }; |
| 969 | let (_, _, decoded, loaded_from_disk) = cache |
| 970 | .load_clip(&clip, 0, false, [None, None, None, None]) |
| 971 | .expect("MediaCache::load_clip failed on synthetic EXR"); |
| 972 | assert!(loaded_from_disk); |
| 973 | assert_eq!(decoded.size, [w as u32, h as u32]); |
| 974 | |
| 975 | let f32_px = decoded |
| 976 | .rgba_f32 |
| 977 | .as_ref() |
| 978 | .expect("EXR must populate rgba_f32"); |
| 979 | assert_eq!(f32_px.len(), n * 4); |
| 980 | assert!((f32_px[0] - 3.75).abs() < 1e-6, "expected HDR 3.75, got {}", f32_px[0]); |
| 981 | assert!((f32_px[1] - (-0.25)).abs() < 1e-6, "expected -0.25, got {}", f32_px[1]); |
| 982 | assert!((f32_px[2] - 0.125).abs() < 1e-6); |
| 983 | assert!((f32_px[3] - 1.0).abs() < 1e-6); |
| 984 | // Pixel 1 blue was NaN -> must be sanitized to 0.0. |
| 985 | assert_eq!(f32_px[4 + 2], 0.0); |
| 986 | // 8-bit preview should clamp 3.75 -> 255 and -0.25 -> 0. |
| 987 | assert_eq!(decoded.rgba[0], 255); |
| 988 | assert_eq!(decoded.rgba[1], 0); |
| 989 | |
| 990 | // 2. Verify list_cryptomatte_layers. |
| 991 | let layers = list_cryptomatte_layers(&tmp_path); |
| 992 | assert_eq!(layers, vec!["ViewLayer.CryptoObject"]); |
| 993 | |
| 994 | // 3. Verify extract_cryptomatte for Hero, Tree, and both (also testing suffix layer match). |
| 995 | let res_hero = extract_cryptomatte(&tmp_path, Some("CryptoObject"), "\"Hero\"") |
| 996 | .expect("extract_cryptomatte Hero failed"); |
| 997 | assert_eq!(res_hero.size, [w as u32, h as u32]); |
| 998 | assert!((res_hero.matte[0] - 0.7).abs() < 1e-6); |
| 999 | assert!((res_hero.matte[1] - 1.0).abs() < 1e-6); |
| 1000 | assert!((res_hero.matte[2] - 0.6).abs() < 1e-6); |
| 1001 | assert!((res_hero.matte[3] - 0.0).abs() < 1e-6); |
| 1002 | |
| 1003 | let res_tree = extract_cryptomatte(&tmp_path, Some("ViewLayer.CryptoObject"), "\"Tree\"") |
| 1004 | .expect("extract_cryptomatte Tree failed"); |
| 1005 | assert!((res_tree.matte[0] - 0.3).abs() < 1e-6); |
| 1006 | assert!((res_tree.matte[1] - 0.0).abs() < 1e-6); |
| 1007 | assert!((res_tree.matte[2] - 0.4).abs() < 1e-6); |
| 1008 | |
| 1009 | let res_both = extract_cryptomatte(&tmp_path, None, "\"Hero\", \"Tree\"") |
| 1010 | .expect("extract_cryptomatte both failed"); |
| 1011 | assert!((res_both.matte[0] - 1.0).abs() < 1e-6); |
| 1012 | assert!((res_both.matte[1] - 1.0).abs() < 1e-6); |
| 1013 | assert!((res_both.matte[2] - 1.0).abs() < 1e-6); |
| 1014 | assert!((res_both.matte[3] - 0.0).abs() < 1e-6); |
| 1015 | |
| 1016 | // Wildcard matching against manifest keys. |
| 1017 | let res_wild = extract_cryptomatte(&tmp_path, None, "Her*") |
| 1018 | .expect("extract_cryptomatte wildcard failed"); |
| 1019 | assert!((res_wild.matte[0] - 0.7).abs() < 1e-6); |
| 1020 | |
| 1021 | let _ = std::fs::remove_file(&tmp_path); |
| 1022 | } |
| 1023 | |
| 1024 | #[test] |
| 1025 | fn parse_manifest_json_handles_multibyte_utf8_after_u_escape_without_panicking() { |
| 1026 | // Malformed \u escapes whose 4-byte window would split multi-byte UTF-8 sequences |
| 1027 | // must return cleanly instead of panicking on non-char-boundary slicing. |
| 1028 | let malformed = r#"{"\u00é": "12345678", "\u🦀a": "deadbeef", "日本語": "a1b2c3d4"}"#; |
| 1029 | let parsed = parse_manifest_json(malformed); |
| 1030 | assert!(parsed.is_empty()); |
| 1031 | |
| 1032 | let valid_utf8 = r#"{"Hero_日本語": "a1b2c3d4", "élan_\u0041": "0x00ff00ff"}"#; |
| 1033 | let parsed_valid = parse_manifest_json(valid_utf8); |
| 1034 | assert_eq!(parsed_valid.get("Hero_日本語"), Some(&0xa1b2_c3d4)); |
| 1035 | assert_eq!(parsed_valid.get("élan_A"), Some(&0x00ff_00ff)); |
| 1036 | } |
| 1037 | |
| 1038 | #[test] |
| 1039 | fn parallel_cryptomatte_matches_scalar_bit_for_bit() { |
| 1040 | let pixel_count = 520 * 520; |
| 1041 | let hero_id = crypto_hash_to_float(murmur3_32(b"Hero", 0)); |
| 1042 | let prop_id = crypto_hash_to_float(murmur3_32(b"Prop", 0)); |
| 1043 | let other_id = crypto_hash_to_float(murmur3_32(b"Other", 0)); |
| 1044 | let target_ids: HashSet<u32> = [hero_id.to_bits(), prop_id.to_bits()].into_iter().collect(); |
| 1045 | |
| 1046 | let mut id0 = vec![0.0_f32; pixel_count]; |
| 1047 | let mut cov0 = vec![0.0_f32; pixel_count]; |
| 1048 | let mut id1 = vec![0.0_f32; pixel_count]; |
| 1049 | let mut cov1 = vec![0.0_f32; pixel_count]; |
| 1050 | let mut id2 = vec![0.0_f32; pixel_count]; |
| 1051 | let mut cov2 = vec![0.0_f32; pixel_count]; |
| 1052 | |
| 1053 | for i in 0..pixel_count { |
| 1054 | match i % 7 { |
| 1055 | 0 => { |
| 1056 | id0[i] = hero_id; |
| 1057 | cov0[i] = 0.65; |
| 1058 | id1[i] = prop_id; |
| 1059 | cov1[i] = 0.25; |
| 1060 | } |
| 1061 | 1 => { |
| 1062 | id0[i] = other_id; |
| 1063 | cov0[i] = 0.9; |
| 1064 | id1[i] = hero_id; |
| 1065 | cov1[i] = 0.1; |
| 1066 | } |
| 1067 | 2 => { |
| 1068 | // Clamping > 1.0 across multiple matching ranks |
| 1069 | id0[i] = hero_id; |
| 1070 | cov0[i] = 0.75; |
| 1071 | id1[i] = prop_id; |
| 1072 | cov1[i] = 0.5; |
| 1073 | } |
| 1074 | 3 => { |
| 1075 | // NaN coverage must sanitize to 0.0 identically |
| 1076 | id0[i] = hero_id; |
| 1077 | cov0[i] = f32::NAN; |
| 1078 | } |
| 1079 | 4 => { |
| 1080 | id0[i] = other_id; |
| 1081 | cov0[i] = 1.0; |
| 1082 | id2[i] = prop_id; |
| 1083 | cov2[i] = 0.375; |
| 1084 | } |
| 1085 | _ => {} |
| 1086 | } |
| 1087 | } |
| 1088 | |
| 1089 | let pairs: Vec<(&[f32], &[f32])> = vec![ |
| 1090 | (&id0, &cov0), |
| 1091 | (&id1, &cov1), |
| 1092 | (&id2, &cov2), |
| 1093 | ]; |
| 1094 | let scalar = accumulate_cryptomatte_scalar(&pairs, &target_ids, pixel_count); |
| 1095 | let parallel = accumulate_cryptomatte_matte(&pairs, &target_ids, pixel_count); |
| 1096 | |
| 1097 | assert_eq!(parallel.len(), scalar.len()); |
| 1098 | for (i, (&p, &s)) in parallel.iter().zip(scalar.iter()).enumerate() { |
| 1099 | assert_eq!( |
| 1100 | p.to_bits(), |
| 1101 | s.to_bits(), |
| 1102 | "bit mismatch at pixel {i}: parallel={p} ({:#x}) vs scalar={s} ({:#x})", |
| 1103 | p.to_bits(), |
| 1104 | s.to_bits() |
| 1105 | ); |
| 1106 | } |
| 1107 | } |
| 1108 | |
| 1109 | #[test] |
| 1110 | fn secondary_rank_nan_and_inf_do_not_poison_rank0_and_selective_load_matches() { |
| 1111 | use exr::prelude::*; |
| 1112 | |
| 1113 | let hero_id = crypto_hash_to_float(murmur3_32(b"Hero", 0)); |
| 1114 | let prop_id = crypto_hash_to_float(murmur3_32(b"Prop", 0)); |
| 1115 | let target_ids: HashSet<u32> = [hero_id.to_bits(), prop_id.to_bits()].into_iter().collect(); |
| 1116 | |
| 1117 | // Pixel 0: valid rank-0 (0.65) + NaN in rank-1 -> must preserve 0.65 (not wipe to 0.0). |
| 1118 | // Pixel 1: NaN in rank-0 + valid rank-1 (0.4) -> must preserve 0.4. |
| 1119 | // Pixel 2: valid rank-0 (0.3) + -Inf in rank-1 -> must preserve 0.3. |
| 1120 | // Pixel 3: valid rank-0 (0.25) + +Inf in rank-1 -> non-finite skipped, preserves 0.25. |
| 1121 | let id0 = [hero_id, hero_id, hero_id, hero_id]; |
| 1122 | let cov0 = [0.65_f32, f32::NAN, 0.3_f32, 0.25_f32]; |
| 1123 | let id1 = [hero_id, prop_id, hero_id, prop_id]; |
| 1124 | let cov1 = [f32::NAN, 0.4_f32, f32::NEG_INFINITY, f32::INFINITY]; |
| 1125 | let pairs: Vec<(&[f32], &[f32])> = vec![(&id0, &cov0), (&id1, &cov1)]; |
| 1126 | |
| 1127 | let matte = accumulate_cryptomatte_scalar(&pairs, &target_ids, 4); |
| 1128 | assert_eq!(matte[0].to_bits(), 0.65_f32.to_bits()); |
| 1129 | assert_eq!(matte[1].to_bits(), 0.4_f32.to_bits()); |
| 1130 | assert_eq!(matte[2].to_bits(), 0.3_f32.to_bits()); |
| 1131 | assert_eq!(matte[3].to_bits(), 0.25_f32.to_bits()); |
| 1132 | |
| 1133 | // Large-set (>8 IDs) HashSet path must match small-set (<=8 IDs) stack linear scan. |
| 1134 | let mut large_ids = target_ids.clone(); |
| 1135 | for extra in 0..10u32 { |
| 1136 | large_ids.insert(crypto_hash_to_float(murmur3_32(&extra.to_le_bytes(), 0)).to_bits()); |
| 1137 | } |
| 1138 | let matte_large = accumulate_cryptomatte_scalar(&pairs, &large_ids, 4); |
| 1139 | assert_eq!( |
| 1140 | matte.iter().map(|v| v.to_bits()).collect::<Vec<_>>(), |
| 1141 | matte_large.iter().map(|v| v.to_bits()).collect::<Vec<_>>() |
| 1142 | ); |
| 1143 | |
| 1144 | // Multi-part EXR with separate Beauty layer and ViewLayer.CryptoObject layer: |
| 1145 | // selective filter_chunks must skip Beauty and decode CryptoObject bit-for-bit. |
| 1146 | let w = 4usize; |
| 1147 | let h = 2usize; |
| 1148 | let n = w * h; |
| 1149 | let hero_hash = murmur3_32(b"Hero", 0); |
| 1150 | let tree_hash = murmur3_32(b"Tree", 0); |
| 1151 | let tree_id = crypto_hash_to_float(tree_hash); |
| 1152 | |
| 1153 | let beauty_layer = Layer::new( |
| 1154 | (w, h), |
| 1155 | LayerAttributes::named("Beauty"), |
| 1156 | Encoding::FAST_LOSSLESS, |
| 1157 | AnyChannels::sort(SmallVec::from_vec(vec![ |
| 1158 | AnyChannel::new("R", FlatSamples::F32(vec![1.0; n])), |
| 1159 | AnyChannel::new("G", FlatSamples::F32(vec![0.5; n])), |
| 1160 | AnyChannel::new("B", FlatSamples::F32(vec![0.25; n])), |
| 1161 | ])), |
| 1162 | ); |
| 1163 | |
| 1164 | let mut c00_r = vec![0.0_f32; n]; |
| 1165 | let mut c00_g = vec![0.0_f32; n]; |
| 1166 | let mut c00_b = vec![0.0_f32; n]; |
| 1167 | let mut c00_a = vec![0.0_f32; n]; |
| 1168 | c00_r[0] = hero_id; |
| 1169 | c00_g[0] = 0.7; |
| 1170 | c00_b[0] = tree_id; |
| 1171 | c00_a[0] = 0.3; |
| 1172 | c00_r[1] = hero_id; |
| 1173 | c00_g[1] = 1.0; |
| 1174 | |
| 1175 | let manifest_json = format!( |
| 1176 | r#"{{"Hero":"{:08x}","Tree":"{:08x}"}}"#, |
| 1177 | hero_hash, tree_hash |
| 1178 | ); |
| 1179 | let mut crypto_attrs = LayerAttributes::named("ViewLayer.CryptoObject00"); |
| 1180 | crypto_attrs.other.insert( |
| 1181 | Text::new_or_panic("cryptomatte/abcdef0/name"), |
| 1182 | AttributeValue::Text(Text::new_or_panic("ViewLayer.CryptoObject")), |
| 1183 | ); |
| 1184 | crypto_attrs.other.insert( |
| 1185 | Text::new_or_panic("cryptomatte/abcdef0/manifest"), |
| 1186 | AttributeValue::Text(Text::new_or_panic(&manifest_json)), |
| 1187 | ); |
| 1188 | let crypto_layer = Layer::new( |
| 1189 | (w, h), |
| 1190 | crypto_attrs, |
| 1191 | Encoding::FAST_LOSSLESS, |
| 1192 | AnyChannels::sort(SmallVec::from_vec(vec![ |
| 1193 | AnyChannel::new("R", FlatSamples::F32(c00_r)), |
| 1194 | AnyChannel::new("G", FlatSamples::F32(c00_g)), |
| 1195 | AnyChannel::new("B", FlatSamples::F32(c00_b)), |
| 1196 | AnyChannel::new("A", FlatSamples::F32(c00_a)), |
| 1197 | ])), |
| 1198 | ); |
| 1199 | |
| 1200 | let image = Image::from_layers( |
| 1201 | ImageAttributes::with_size((w, h)), |
| 1202 | SmallVec::from_vec(vec![beauty_layer, crypto_layer]), |
| 1203 | ); |
| 1204 | let tmp_path = std::env::temp_dir().join(format!( |
| 1205 | "engine_test_selective_crypto_{}.exr", |
| 1206 | std::process::id() |
| 1207 | )); |
| 1208 | image |
| 1209 | .write() |
| 1210 | .to_file(&tmp_path) |
| 1211 | .expect("failed to write multi-part EXR"); |
| 1212 | |
| 1213 | let res = extract_cryptomatte(&tmp_path, Some("CryptoObject"), "\"Hero\"") |
| 1214 | .expect("selective extract_cryptomatte failed"); |
| 1215 | assert_eq!(res.size, [w as u32, h as u32]); |
| 1216 | assert_eq!(res.matte[0].to_bits(), 0.7_f32.to_bits()); |
| 1217 | assert_eq!(res.matte[1].to_bits(), 1.0_f32.to_bits()); |
| 1218 | assert_eq!(res.matte[2].to_bits(), 0.0_f32.to_bits()); |
| 1219 | |
| 1220 | let _ = std::fs::remove_file(&tmp_path); |
| 1221 | } |
| 1222 | } |