| author | |
| committer | |
| log | 200ab32029f147f893c3b65597794ffbf072ffd2 |
| tree | ab698c628d9c882a66c27e6409a2b2bb3c065b87 |
| parent | f80b0ebc6787471689dc60d888ce6ebb3bcf5b8f |
| signature | Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU |
4 files changed, 710 insertions(+), 153 deletions(-)
crates/engine/src/av_decode.m+29-8| ... | ... | @@ -431,14 +431,17 @@ AvVideoDecoder *av_video_open( |
| 431 | 431 | static CMSampleBufferRef read_target_sample( |
| 432 | 432 | AvVideoDecoderObj *obj, |
| 433 | 433 | double targetPts, |
| 434 | double halfFrame | |
| 434 | double halfFrame, | |
| 435 | BOOL *outHitEof | |
| 435 | 436 | ) { |
| 436 | 437 | CMSampleBufferRef chosen = NULL; |
| 437 | 438 | CMSampleBufferRef lastSeen = NULL; |
| 439 | BOOL hitEof = NO; | |
| 438 | 440 | |
| 439 | 441 | while (obj.reader.status == AVAssetReaderStatusReading) { |
| 440 | 442 | CMSampleBufferRef sb = [obj.output copyNextSampleBuffer]; |
| 441 | 443 | if (!sb) { |
| 444 | hitEof = (obj.reader.status == AVAssetReaderStatusCompleted); | |
| 442 | 445 | break; |
| 443 | 446 | } |
| 444 | 447 | CMTime ptsTime = CMSampleBufferGetPresentationTimeStamp(sb); |
| ... | ... | @@ -457,10 +460,14 @@ static CMSampleBufferRef read_target_sample( |
| 457 | 460 | if (!chosen && lastSeen) { |
| 458 | 461 | chosen = lastSeen; |
| 459 | 462 | lastSeen = NULL; |
| 463 | hitEof = YES; | |
| 460 | 464 | } |
| 461 | 465 | if (lastSeen) { |
| 462 | 466 | CFRelease(lastSeen); |
| 463 | 467 | } |
| 468 | if (outHitEof) { | |
| 469 | *outHitEof = hitEof || (obj.reader.status == AVAssetReaderStatusCompleted); | |
| 470 | } | |
| 464 | 471 | return chosen; |
| 465 | 472 | } |
| 466 | 473 | |
| ... | ... | @@ -493,6 +500,7 @@ int av_video_decode_frame( |
| 493 | 500 | (obj.lastFrameIdx >= 0 && frame_idx > obj.lastFrameIdx && |
| 494 | 501 | frame_idx <= obj.lastFrameIdx + 8)); |
| 495 | 502 | |
| 503 | int64_t prevLastFrameIdx = obj.lastFrameIdx; | |
| 496 | 504 | double seekSec = 0.0; |
| 497 | 505 | if (!canAdvance) { |
| 498 | 506 | seekSec = (frame_idx == 0) ? 0.0 : fmax(0.0, targetPts - (1.5 / fps)); |
| ... | ... | @@ -501,15 +509,28 @@ int av_video_decode_frame( |
| 501 | 509 | } |
| 502 | 510 | } |
| 503 | 511 | |
| 504 | CMSampleBufferRef chosen = read_target_sample(obj, targetPts, halfFrame); | |
| 512 | BOOL hitEof = NO; | |
| 513 | CMSampleBufferRef chosen = read_target_sample(obj, targetPts, halfFrame, &hitEof); | |
| 505 | 514 | |
| 506 | // If requesting a frame slightly past EOF (e.g., llround(durSec * fps) rounding up by 1), | |
| 507 | // retry once from slightly before end if we didn't hit a sample, or hold the last valid frame. | |
| 508 | if (!chosen && !canAdvance && frame_idx > 0) { | |
| 515 | // If requesting a frame past EOF (including sequential advance stepping past EOF or | |
| 516 | // container duration overestimating the last video sample by > 4 frames), retry from | |
| 517 | // endAnchor - 1.0 and, if that still misses, from the last known decoded frame timestamp. | |
| 518 | if (!chosen && !obj.hasLastFrame && frame_idx > 0) { | |
| 509 | 519 | double endAnchor = obj.durSec > 0.0 ? fmin(targetPts, obj.trackStartSec + obj.durSec) : targetPts; |
| 510 | 520 | double fallbackSec = fmax(0.0, endAnchor - 1.0); |
| 511 | if (fallbackSec < seekSec - 0.05 && [obj openReaderAtSeconds:fallbackSec]) { | |
| 512 | chosen = read_target_sample(obj, targetPts, halfFrame); | |
| 521 | if ((canAdvance || fallbackSec < seekSec - 0.05) && [obj openReaderAtSeconds:fallbackSec]) { | |
| 522 | chosen = read_target_sample(obj, targetPts, halfFrame, &hitEof); | |
| 523 | } | |
| 524 | if (!chosen) { | |
| 525 | double lastIdxSec = fmax( | |
| 526 | 0.0, | |
| 527 | prevLastFrameIdx >= 0 | |
| 528 | ? obj.trackStartSec + (double)prevLastFrameIdx / fps - 0.1 | |
| 529 | : 0.0 | |
| 530 | ); | |
| 531 | if ([obj openReaderAtSeconds:lastIdxSec]) { | |
| 532 | chosen = read_target_sample(obj, targetPts, halfFrame, &hitEof); | |
| 533 | } | |
| 513 | 534 | } |
| 514 | 535 | } |
| 515 | 536 | |
| ... | ... | @@ -530,7 +551,7 @@ int av_video_decode_frame( |
| 530 | 551 | CFRelease(chosen); |
| 531 | 552 | |
| 532 | 553 | if (ok) { |
| 533 | if (obj.nbFrames <= 0 || frame_idx >= obj.nbFrames - 4) { | |
| 554 | if (hitEof || obj.nbFrames <= 0 || frame_idx >= obj.nbFrames - 4) { | |
| 534 | 555 | if (!obj.lastFrameRgba || obj.lastFrameRgba.length < required) { |
| 535 | 556 | obj.lastFrameRgba = [NSMutableData dataWithLength:required]; |
| 536 | 557 | } |
crates/engine/src/cryptomatte.rs+247-32| ... | ... | @@ -392,19 +392,23 @@ fn parse_hex_literal_token(token: &str) -> Option<u32> { |
| 392 | 392 | #[cfg(not(target_arch = "wasm32"))] |
| 393 | 393 | const CRYPTO_PARALLEL_THRESHOLD_PIXELS: usize = 512 * 512; |
| 394 | 394 | |
| 395 | fn accumulate_cryptomatte_chunk( | |
| 395 | #[inline] | |
| 396 | fn accumulate_chunk_with<F: Fn(u32) -> bool>( | |
| 396 | 397 | out: &mut [f32], |
| 397 | 398 | start: usize, |
| 398 | 399 | pairs: &[(&[f32], &[f32])], |
| 399 | target_ids: &HashSet<u32>, | |
| 400 | contains_id: F, | |
| 400 | 401 | ) { |
| 401 | 402 | let len = out.len(); |
| 402 | 403 | for &(ids, covs) in pairs { |
| 403 | 404 | let ids_slice = &ids[start..start + len]; |
| 404 | 405 | let covs_slice = &covs[start..start + len]; |
| 405 | 406 | for i in 0..len { |
| 406 | if target_ids.contains(&ids_slice[i].to_bits()) { | |
| 407 | out[i] += covs_slice[i]; | |
| 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 | } | |
| 408 | 412 | } |
| 409 | 413 | } |
| 410 | 414 | } |
| ... | ... | @@ -413,6 +417,26 @@ fn accumulate_cryptomatte_chunk( |
| 413 | 417 | } |
| 414 | 418 | } |
| 415 | 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 | ||
| 416 | 440 | fn accumulate_cryptomatte_scalar( |
| 417 | 441 | pairs: &[(&[f32], &[f32])], |
| 418 | 442 | target_ids: &HashSet<u32>, |
| ... | ... | @@ -499,8 +523,8 @@ pub fn list_cryptomatte_layers(exr_path: &Path) -> Vec<String> { |
| 499 | 523 | |
| 500 | 524 | /// Extracts a Cryptomatte coverage matte from a multi-channel OpenEXR file. |
| 501 | 525 | /// |
| 502 | /// - Reads all flat layers and custom header `other` attributes via | |
| 503 | /// `exr::prelude::read_all_flat_layers_from_file`. | |
| 526 | /// - Reads header metadata first and selectively decompresses only the layers containing | |
| 527 | /// matched Cryptomatte rank channels via `exr::block::read` + `filter_chunks`. | |
| 504 | 528 | /// - Resolves `cryptomatte/<id>/name`, `cryptomatte/<id>/manifest`, and sidecar |
| 505 | 529 | /// `cryptomatte/<id>/manif_file` relative to `exr_path.parent()`. |
| 506 | 530 | /// - Matches `layer_name` by exact name, suffix (e.g. `"CryptoObject"` -> `"ViewLayer.CryptoObject"`), |
| ... | ... | @@ -512,15 +536,19 @@ pub fn extract_cryptomatte( |
| 512 | 536 | layer_name: Option<&str>, |
| 513 | 537 | matte_list: &str, |
| 514 | 538 | ) -> Option<CryptomatteResult> { |
| 539 | use exr::block::reader::ChunksReader; | |
| 540 | use exr::meta::attribute::SampleType; | |
| 515 | 541 | use exr::prelude::*; |
| 516 | 542 | |
| 517 | let img = read_all_flat_layers_from_file(exr_path).ok()?; | |
| 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()?; | |
| 518 | 546 | |
| 519 | // 1. Collect Cryptomatte header metadata from image-level and layer-level `other` attributes. | |
| 547 | // 1. Collect Cryptomatte header metadata from shared and layer-level `other` attributes. | |
| 520 | 548 | let mut crypto_meta: BTreeMap<String, CryptoLayerMeta> = BTreeMap::new(); |
| 521 | collect_crypto_metadata_from_map(&img.attributes.other, &mut crypto_meta); | |
| 522 | for layer in &img.layer_data { | |
| 523 | collect_crypto_metadata_from_map(&layer.attributes.other, &mut crypto_meta); | |
| 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); | |
| 524 | 552 | } |
| 525 | 553 | |
| 526 | 554 | // 2. Select target Cryptomatte layer and manifest. |
| ... | ... | @@ -545,11 +573,14 @@ pub fn extract_cryptomatte( |
| 545 | 573 | } else if let Some(req) = req_layer { |
| 546 | 574 | req.to_string() |
| 547 | 575 | } else { |
| 548 | // Fallback: infer first rank-00 prefix from channels. | |
| 576 | // Fallback: infer first rank-00 prefix from headers. | |
| 549 | 577 | let mut inferred = None; |
| 550 | 'outer: for layer in &img.layer_data { | |
| 551 | let lname = layer.attributes.layer_name.as_ref().map(|t| t.to_string()); | |
| 552 | for ch in &layer.channel_data.list { | |
| 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 { | |
| 553 | 584 | let full = full_channel_name(lname.as_deref(), &ch.name.to_string()); |
| 554 | 585 | if let Some((prefix, 0, 0)) = split_crypto_rank_channel(&full) { |
| 555 | 586 | inferred = Some(prefix.to_string()); |
| ... | ... | @@ -601,18 +632,26 @@ pub fn extract_cryptomatte( |
| 601 | 632 | target_ids.insert(crypto_hash_to_float(direct_hash).to_bits()); |
| 602 | 633 | } |
| 603 | 634 | |
| 604 | // 4. Gather rank channel groups (<prefix>00 .. <prefix>09) across all flat layers. | |
| 635 | // 4. Identify matching rank channel groups (<prefix>00 .. <prefix>09) from headers first. | |
| 605 | 636 | let mut dims: Option<(usize, usize)> = None; |
| 606 | let mut ranks: BTreeMap<u8, [Option<Vec<f32>>; 4]> = BTreeMap::new(); | |
| 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(); | |
| 607 | 640 | |
| 608 | for layer in &img.layer_data { | |
| 609 | let lw = layer.size.width(); | |
| 610 | let lh = layer.size.height(); | |
| 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(); | |
| 611 | 647 | if lw == 0 || lh == 0 { |
| 612 | 648 | continue; |
| 613 | 649 | } |
| 614 | let lname = layer.attributes.layer_name.as_ref().map(|t| t.to_string()); | |
| 615 | for ch in &layer.channel_data.list { | |
| 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 | } | |
| 616 | 655 | let full = full_channel_name(lname.as_deref(), &ch.name.to_string()); |
| 617 | 656 | let Some((prefix, rank, comp_idx)) = split_crypto_rank_channel(&full) else { |
| 618 | 657 | continue; |
| ... | ... | @@ -627,12 +666,13 @@ pub fn extract_cryptomatte( |
| 627 | 666 | } else { |
| 628 | 667 | dims = Some((lw, lh)); |
| 629 | 668 | } |
| 630 | let vals: Vec<f32> = ch.sample_data.values_as_f32().collect(); | |
| 631 | if vals.len() == lw * lh { | |
| 632 | let slots = ranks.entry(rank).or_insert_with(|| [None, None, None, None]); | |
| 633 | if slots[comp_idx].is_none() { | |
| 634 | slots[comp_idx] = Some(vals); | |
| 635 | } | |
| 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); | |
| 636 | 676 | } |
| 637 | 677 | } |
| 638 | 678 | } |
| ... | ... | @@ -646,14 +686,75 @@ pub fn extract_cryptomatte( |
| 646 | 686 | }); |
| 647 | 687 | } |
| 648 | 688 | |
| 689 | let mut slot_buffers: Vec<(u8, usize, Vec<f32>)> = Vec::with_capacity(matched_channels.len()); | |
| 690 | let mut loc_to_slot: HashMap<(usize, usize), usize> = | |
| 691 | HashMap::with_capacity(matched_channels.len()); | |
| 692 | for (loc, rank, comp_idx) in matched_channels { | |
| 693 | let idx = slot_buffers.len(); | |
| 694 | slot_buffers.push((rank, comp_idx, vec![0.0_f32; pixel_count])); | |
| 695 | loc_to_slot.insert(loc, idx); | |
| 696 | } | |
| 697 | ||
| 698 | let mut line_f16 = Vec::<f16>::new(); | |
| 699 | let mut line_u32 = Vec::<u32>::new(); | |
| 700 | chunks_reader | |
| 701 | .filter_chunks(false, |_, tile, block| { | |
| 702 | tile.is_largest_resolution_level() && needed_layers.contains(&block.layer) | |
| 703 | }) | |
| 704 | .ok()? | |
| 705 | .decompress_parallel(false, |meta, block| { | |
| 706 | let header = &meta.headers[block.index.layer]; | |
| 707 | for line in block.lines(&header.channels) { | |
| 708 | let Some(&slot_idx) = | |
| 709 | loc_to_slot.get(&(line.location.layer, line.location.channel)) | |
| 710 | else { | |
| 711 | continue; | |
| 712 | }; | |
| 713 | let y = line.location.position.y(); | |
| 714 | let x0 = line.location.position.x(); | |
| 715 | let len = line.location.sample_count; | |
| 716 | if y >= h || x0 + len > w { | |
| 717 | continue; | |
| 718 | } | |
| 719 | let row_base = y * w + x0; | |
| 720 | let dst = &mut slot_buffers[slot_idx].2[row_base..row_base + len]; | |
| 721 | match header.channels.list[line.location.channel].sample_type { | |
| 722 | SampleType::F32 => { | |
| 723 | line.read_samples_into_slice(dst)?; | |
| 724 | } | |
| 725 | SampleType::F16 => { | |
| 726 | line_f16.resize(len, f16::ZERO); | |
| 727 | line.read_samples_into_slice(&mut line_f16)?; | |
| 728 | for (d, &s) in dst.iter_mut().zip(line_f16.iter()) { | |
| 729 | *d = s.to_f32(); | |
| 730 | } | |
| 731 | } | |
| 732 | SampleType::U32 => { | |
| 733 | line_u32.resize(len, 0); | |
| 734 | line.read_samples_into_slice(&mut line_u32)?; | |
| 735 | for (d, &s) in dst.iter_mut().zip(line_u32.iter()) { | |
| 736 | *d = s as f32; | |
| 737 | } | |
| 738 | } | |
| 739 | } | |
| 740 | } | |
| 741 | Ok(()) | |
| 742 | }) | |
| 743 | .ok()?; | |
| 744 | ||
| 649 | 745 | // 5. Accumulate coverage across all rank (ID, coverage) pairs. |
| 746 | let mut ranks: BTreeMap<u8, [Option<&[f32]>; 4]> = BTreeMap::new(); | |
| 747 | for (rank, comp_idx, buf) in &slot_buffers { | |
| 748 | let slots = ranks.entry(*rank).or_insert([None, None, None, None]); | |
| 749 | slots[*comp_idx] = Some(buf.as_slice()); | |
| 750 | } | |
| 650 | 751 | let mut pairs: Vec<(&[f32], &[f32])> = Vec::with_capacity(ranks.len() * 2); |
| 651 | 752 | for slots in ranks.values() { |
| 652 | if let (Some(ids), Some(covs)) = (&slots[0], &slots[1]) { | |
| 653 | pairs.push((ids.as_slice(), covs.as_slice())); | |
| 753 | if let (Some(ids), Some(covs)) = (slots[0], slots[1]) { | |
| 754 | pairs.push((ids, covs)); | |
| 654 | 755 | } |
| 655 | if let (Some(ids), Some(covs)) = (&slots[2], &slots[3]) { | |
| 656 | pairs.push((ids.as_slice(), covs.as_slice())); | |
| 756 | if let (Some(ids), Some(covs)) = (slots[2], slots[3]) { | |
| 757 | pairs.push((ids, covs)); | |
| 657 | 758 | } |
| 658 | 759 | } |
| 659 | 760 | let matte = accumulate_cryptomatte_matte(&pairs, &target_ids, pixel_count); |
| ... | ... | @@ -987,4 +1088,118 @@ mod tests { |
| 987 | 1088 | ); |
| 988 | 1089 | } |
| 989 | 1090 | } |
| 1091 | ||
| 1092 | #[test] | |
| 1093 | fn secondary_rank_nan_and_inf_do_not_poison_rank0_and_selective_load_matches() { | |
| 1094 | use exr::prelude::*; | |
| 1095 | ||
| 1096 | let hero_id = crypto_hash_to_float(murmur3_32(b"Hero", 0)); | |
| 1097 | let prop_id = crypto_hash_to_float(murmur3_32(b"Prop", 0)); | |
| 1098 | let target_ids: HashSet<u32> = [hero_id.to_bits(), prop_id.to_bits()].into_iter().collect(); | |
| 1099 | ||
| 1100 | // Pixel 0: valid rank-0 (0.65) + NaN in rank-1 -> must preserve 0.65 (not wipe to 0.0). | |
| 1101 | // Pixel 1: NaN in rank-0 + valid rank-1 (0.4) -> must preserve 0.4. | |
| 1102 | // Pixel 2: valid rank-0 (0.3) + -Inf in rank-1 -> must preserve 0.3. | |
| 1103 | // Pixel 3: valid rank-0 (0.25) + +Inf in rank-1 -> non-finite skipped, preserves 0.25. | |
| 1104 | let id0 = [hero_id, hero_id, hero_id, hero_id]; | |
| 1105 | let cov0 = [0.65_f32, f32::NAN, 0.3_f32, 0.25_f32]; | |
| 1106 | let id1 = [hero_id, prop_id, hero_id, prop_id]; | |
| 1107 | let cov1 = [f32::NAN, 0.4_f32, f32::NEG_INFINITY, f32::INFINITY]; | |
| 1108 | let pairs: Vec<(&[f32], &[f32])> = vec![(&id0, &cov0), (&id1, &cov1)]; | |
| 1109 | ||
| 1110 | let matte = accumulate_cryptomatte_scalar(&pairs, &target_ids, 4); | |
| 1111 | assert_eq!(matte[0].to_bits(), 0.65_f32.to_bits()); | |
| 1112 | assert_eq!(matte[1].to_bits(), 0.4_f32.to_bits()); | |
| 1113 | assert_eq!(matte[2].to_bits(), 0.3_f32.to_bits()); | |
| 1114 | assert_eq!(matte[3].to_bits(), 0.25_f32.to_bits()); | |
| 1115 | ||
| 1116 | // Large-set (>8 IDs) HashSet path must match small-set (<=8 IDs) stack linear scan. | |
| 1117 | let mut large_ids = target_ids.clone(); | |
| 1118 | for extra in 0..10u32 { | |
| 1119 | large_ids.insert(crypto_hash_to_float(murmur3_32(&extra.to_le_bytes(), 0)).to_bits()); | |
| 1120 | } | |
| 1121 | let matte_large = accumulate_cryptomatte_scalar(&pairs, &large_ids, 4); | |
| 1122 | assert_eq!( | |
| 1123 | matte.iter().map(|v| v.to_bits()).collect::<Vec<_>>(), | |
| 1124 | matte_large.iter().map(|v| v.to_bits()).collect::<Vec<_>>() | |
| 1125 | ); | |
| 1126 | ||
| 1127 | // Multi-part EXR with separate Beauty layer and ViewLayer.CryptoObject layer: | |
| 1128 | // selective filter_chunks must skip Beauty and decode CryptoObject bit-for-bit. | |
| 1129 | let w = 4usize; | |
| 1130 | let h = 2usize; | |
| 1131 | let n = w * h; | |
| 1132 | let hero_hash = murmur3_32(b"Hero", 0); | |
| 1133 | let tree_hash = murmur3_32(b"Tree", 0); | |
| 1134 | let tree_id = crypto_hash_to_float(tree_hash); | |
| 1135 | ||
| 1136 | let beauty_layer = Layer::new( | |
| 1137 | (w, h), | |
| 1138 | LayerAttributes::named("Beauty"), | |
| 1139 | Encoding::FAST_LOSSLESS, | |
| 1140 | AnyChannels::sort(SmallVec::from_vec(vec![ | |
| 1141 | AnyChannel::new("R", FlatSamples::F32(vec![1.0; n])), | |
| 1142 | AnyChannel::new("G", FlatSamples::F32(vec![0.5; n])), | |
| 1143 | AnyChannel::new("B", FlatSamples::F32(vec![0.25; n])), | |
| 1144 | ])), | |
| 1145 | ); | |
| 1146 | ||
| 1147 | let mut c00_r = vec![0.0_f32; n]; | |
| 1148 | let mut c00_g = vec![0.0_f32; n]; | |
| 1149 | let mut c00_b = vec![0.0_f32; n]; | |
| 1150 | let mut c00_a = vec![0.0_f32; n]; | |
| 1151 | c00_r[0] = hero_id; | |
| 1152 | c00_g[0] = 0.7; | |
| 1153 | c00_b[0] = tree_id; | |
| 1154 | c00_a[0] = 0.3; | |
| 1155 | c00_r[1] = hero_id; | |
| 1156 | c00_g[1] = 1.0; | |
| 1157 | ||
| 1158 | let manifest_json = format!( | |
| 1159 | r#"{{"Hero":"{:08x}","Tree":"{:08x}"}}"#, | |
| 1160 | hero_hash, tree_hash | |
| 1161 | ); | |
| 1162 | let mut crypto_attrs = LayerAttributes::named("ViewLayer.CryptoObject00"); | |
| 1163 | crypto_attrs.other.insert( | |
| 1164 | Text::new_or_panic("cryptomatte/abcdef0/name"), | |
| 1165 | AttributeValue::Text(Text::new_or_panic("ViewLayer.CryptoObject")), | |
| 1166 | ); | |
| 1167 | crypto_attrs.other.insert( | |
| 1168 | Text::new_or_panic("cryptomatte/abcdef0/manifest"), | |
| 1169 | AttributeValue::Text(Text::new_or_panic(&manifest_json)), | |
| 1170 | ); | |
| 1171 | let crypto_layer = Layer::new( | |
| 1172 | (w, h), | |
| 1173 | crypto_attrs, | |
| 1174 | Encoding::FAST_LOSSLESS, | |
| 1175 | AnyChannels::sort(SmallVec::from_vec(vec![ | |
| 1176 | AnyChannel::new("R", FlatSamples::F32(c00_r)), | |
| 1177 | AnyChannel::new("G", FlatSamples::F32(c00_g)), | |
| 1178 | AnyChannel::new("B", FlatSamples::F32(c00_b)), | |
| 1179 | AnyChannel::new("A", FlatSamples::F32(c00_a)), | |
| 1180 | ])), | |
| 1181 | ); | |
| 1182 | ||
| 1183 | let image = Image::from_layers( | |
| 1184 | ImageAttributes::with_size((w, h)), | |
| 1185 | SmallVec::from_vec(vec![beauty_layer, crypto_layer]), | |
| 1186 | ); | |
| 1187 | let tmp_path = std::env::temp_dir().join(format!( | |
| 1188 | "engine_test_selective_crypto_{}.exr", | |
| 1189 | std::process::id() | |
| 1190 | )); | |
| 1191 | image | |
| 1192 | .write() | |
| 1193 | .to_file(&tmp_path) | |
| 1194 | .expect("failed to write multi-part EXR"); | |
| 1195 | ||
| 1196 | let res = extract_cryptomatte(&tmp_path, Some("CryptoObject"), "\"Hero\"") | |
| 1197 | .expect("selective extract_cryptomatte failed"); | |
| 1198 | assert_eq!(res.size, [w as u32, h as u32]); | |
| 1199 | assert_eq!(res.matte[0].to_bits(), 0.7_f32.to_bits()); | |
| 1200 | assert_eq!(res.matte[1].to_bits(), 1.0_f32.to_bits()); | |
| 1201 | assert_eq!(res.matte[2].to_bits(), 0.0_f32.to_bits()); | |
| 1202 | ||
| 1203 | let _ = std::fs::remove_file(&tmp_path); | |
| 1204 | } | |
| 990 | 1205 | } |
crates/engine/src/media.rs+366-63| ... | ... | @@ -28,7 +28,7 @@ use std::process::Command; |
| 28 | 28 | #[cfg(not(target_arch = "wasm32"))] |
| 29 | 29 | use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; |
| 30 | 30 | #[cfg(not(target_arch = "wasm32"))] |
| 31 | use std::sync::{Condvar, mpsc}; | |
| 31 | use std::sync::{Condvar, Weak, mpsc}; | |
| 32 | 32 | use std::sync::{Arc, Mutex, RwLock}; |
| 33 | 33 | |
| 34 | 34 | #[derive(Clone)] |
| ... | ... | @@ -214,6 +214,14 @@ struct MediaState { |
| 214 | 214 | opening_videos: HashSet<PathBuf>, |
| 215 | 215 | #[cfg(not(target_arch = "wasm32"))] |
| 216 | 216 | known_existing_paths: HashSet<PathBuf>, |
| 217 | #[cfg(not(target_arch = "wasm32"))] | |
| 218 | speculative_bytes_since_seq: u64, | |
| 219 | #[cfg(not(target_arch = "wasm32"))] | |
| 220 | speculative_count_since_seq: u64, | |
| 221 | #[cfg(not(target_arch = "wasm32"))] | |
| 222 | last_speculative_bytes: u64, | |
| 223 | #[cfg(not(target_arch = "wasm32"))] | |
| 224 | last_prefetch_seq: Option<usize>, | |
| 217 | 225 | } |
| 218 | 226 | |
| 219 | 227 | impl MediaState { |
| ... | ... | @@ -232,6 +240,14 @@ impl MediaState { |
| 232 | 240 | opening_videos: HashSet::new(), |
| 233 | 241 | #[cfg(not(target_arch = "wasm32"))] |
| 234 | 242 | known_existing_paths: HashSet::new(), |
| 243 | #[cfg(not(target_arch = "wasm32"))] | |
| 244 | speculative_bytes_since_seq: 0, | |
| 245 | #[cfg(not(target_arch = "wasm32"))] | |
| 246 | speculative_count_since_seq: 0, | |
| 247 | #[cfg(not(target_arch = "wasm32"))] | |
| 248 | last_speculative_bytes: 0, | |
| 249 | #[cfg(not(target_arch = "wasm32"))] | |
| 250 | last_prefetch_seq: None, | |
| 235 | 251 | } |
| 236 | 252 | } |
| 237 | 253 | |
| ... | ... | @@ -255,8 +271,34 @@ impl MediaState { |
| 255 | 271 | } |
| 256 | 272 | |
| 257 | 273 | #[cfg(not(target_arch = "wasm32"))] |
| 258 | fn is_over_soft_budget(&self) -> bool { | |
| 259 | self.budget_bytes > 0 && self.total_bytes >= (self.budget_bytes * 3) / 4 | |
| 274 | fn record_speculative_decode(&mut self, bytes: u64) { | |
| 275 | self.speculative_bytes_since_seq = self.speculative_bytes_since_seq.saturating_add(bytes); | |
| 276 | self.speculative_count_since_seq = self.speculative_count_since_seq.saturating_add(1); | |
| 277 | self.last_speculative_bytes = bytes; | |
| 278 | } | |
| 279 | ||
| 280 | #[cfg(not(target_arch = "wasm32"))] | |
| 281 | fn reset_speculative_window(&mut self, seq_idx: usize) { | |
| 282 | if self.last_prefetch_seq != Some(seq_idx) { | |
| 283 | self.last_prefetch_seq = Some(seq_idx); | |
| 284 | self.speculative_bytes_since_seq = 0; | |
| 285 | self.speculative_count_since_seq = 0; | |
| 286 | } | |
| 287 | } | |
| 288 | ||
| 289 | #[cfg(not(target_arch = "wasm32"))] | |
| 290 | fn should_throttle_lookahead(&self) -> bool { | |
| 291 | const MIN_LOOKAHEAD_BUDGET_BYTES: u64 = 64 * 1024 * 1024; | |
| 292 | if self.budget_bytes < MIN_LOOKAHEAD_BUDGET_BYTES { | |
| 293 | return true; | |
| 294 | } | |
| 295 | let avg_item_bytes = if self.speculative_count_since_seq > 0 { | |
| 296 | self.speculative_bytes_since_seq / self.speculative_count_since_seq | |
| 297 | } else { | |
| 298 | self.last_speculative_bytes | |
| 299 | }; | |
| 300 | let in_flight_est = (self.in_flight.len() as u64).saturating_mul(avg_item_bytes); | |
| 301 | self.speculative_bytes_since_seq.saturating_add(in_flight_est) >= self.budget_bytes / 2 | |
| 260 | 302 | } |
| 261 | 303 | |
| 262 | 304 | fn insert_cached(&mut self, cache_key: ImageCacheKey, decoded: DecodedImage) { |
| ... | ... | @@ -320,26 +362,70 @@ struct MediaShared { |
| 320 | 362 | #[cfg(not(target_arch = "wasm32"))] |
| 321 | 363 | cv: Condvar, |
| 322 | 364 | #[cfg(not(target_arch = "wasm32"))] |
| 323 | soft_budget_exceeded: AtomicBool, | |
| 365 | lookahead_throttled: AtomicBool, | |
| 366 | #[cfg(not(target_arch = "wasm32"))] | |
| 367 | prefetch_queues: Mutex<Vec<Weak<PrefetchQueue>>>, | |
| 324 | 368 | } |
| 325 | 369 | |
| 326 | 370 | impl MediaShared { |
| 327 | 371 | fn new(budget_bytes: u64) -> Self { |
| 372 | let initial_state = MediaState::new(budget_bytes); | |
| 373 | #[cfg(not(target_arch = "wasm32"))] | |
| 374 | let initial_throttle = initial_state.should_throttle_lookahead(); | |
| 328 | 375 | Self { |
| 329 | state: Mutex::new(MediaState::new(budget_bytes)), | |
| 376 | state: Mutex::new(initial_state), | |
| 330 | 377 | #[cfg(not(target_arch = "wasm32"))] |
| 331 | 378 | cv: Condvar::new(), |
| 332 | 379 | #[cfg(not(target_arch = "wasm32"))] |
| 333 | soft_budget_exceeded: AtomicBool::new(false), | |
| 380 | lookahead_throttled: AtomicBool::new(initial_throttle), | |
| 381 | #[cfg(not(target_arch = "wasm32"))] | |
| 382 | prefetch_queues: Mutex::new(Vec::new()), | |
| 334 | 383 | } |
| 335 | 384 | } |
| 336 | 385 | |
| 337 | fn sync_soft_budget(&self, state: &MediaState) { | |
| 386 | fn sync_lookahead_throttle(&self, state: &MediaState) -> bool { | |
| 338 | 387 | #[cfg(not(target_arch = "wasm32"))] |
| 339 | self.soft_budget_exceeded | |
| 340 | .store(state.is_over_soft_budget(), Ordering::Relaxed); | |
| 388 | { | |
| 389 | let throttled = state.should_throttle_lookahead(); | |
| 390 | let was_throttled = self.lookahead_throttled.load(Ordering::Acquire); | |
| 391 | self.lookahead_throttled.store(throttled, Ordering::Release); | |
| 392 | was_throttled && !throttled | |
| 393 | } | |
| 341 | 394 | #[cfg(target_arch = "wasm32")] |
| 342 | let _ = state; | |
| 395 | { | |
| 396 | let _ = state; | |
| 397 | false | |
| 398 | } | |
| 399 | } | |
| 400 | ||
| 401 | #[cfg(not(target_arch = "wasm32"))] | |
| 402 | fn register_prefetch_queue(&self, queue: &Arc<PrefetchQueue>) { | |
| 403 | if let Ok(mut queues) = self.prefetch_queues.lock() { | |
| 404 | queues.retain(|w| w.strong_count() > 0); | |
| 405 | queues.push(Arc::downgrade(queue)); | |
| 406 | } | |
| 407 | } | |
| 408 | ||
| 409 | #[cfg(not(target_arch = "wasm32"))] | |
| 410 | fn notify_prefetch_waiters(&self) { | |
| 411 | let live: Vec<Arc<PrefetchQueue>> = { | |
| 412 | let Ok(mut queues) = self.prefetch_queues.lock() else { return }; | |
| 413 | let mut out = Vec::with_capacity(queues.len()); | |
| 414 | queues.retain(|w| { | |
| 415 | if let Some(q) = w.upgrade() { | |
| 416 | out.push(q); | |
| 417 | true | |
| 418 | } else { | |
| 419 | false | |
| 420 | } | |
| 421 | }); | |
| 422 | out | |
| 423 | }; | |
| 424 | for q in live { | |
| 425 | if let Ok(_guard) = q.state.lock() { | |
| 426 | q.cv.notify_all(); | |
| 427 | } | |
| 428 | } | |
| 343 | 429 | } |
| 344 | 430 | |
| 345 | 431 | fn insert_cached_locked( |
| ... | ... | @@ -347,9 +433,9 @@ impl MediaShared { |
| 347 | 433 | state: &mut MediaState, |
| 348 | 434 | cache_key: ImageCacheKey, |
| 349 | 435 | decoded: DecodedImage, |
| 350 | ) { | |
| 436 | ) -> bool { | |
| 351 | 437 | state.insert_cached(cache_key, decoded); |
| 352 | self.sync_soft_budget(state); | |
| 438 | self.sync_lookahead_throttle(state) | |
| 353 | 439 | } |
| 354 | 440 | |
| 355 | 441 | fn path_exists_cached(&self, path: &Path) -> bool { |
| ... | ... | @@ -467,9 +553,16 @@ struct InFlightGuard<'a> { |
| 467 | 553 | impl Drop for InFlightGuard<'_> { |
| 468 | 554 | fn drop(&mut self) { |
| 469 | 555 | if let Some(key) = self.key.take() { |
| 470 | if let Ok(mut state) = self.shared.state.lock() { | |
| 556 | let unthrottled = if let Ok(mut state) = self.shared.state.lock() { | |
| 471 | 557 | state.in_flight.remove(&key); |
| 558 | let unthrottled = self.shared.sync_lookahead_throttle(&state); | |
| 472 | 559 | self.shared.cv.notify_all(); |
| 560 | unthrottled | |
| 561 | } else { | |
| 562 | false | |
| 563 | }; | |
| 564 | if unthrottled { | |
| 565 | self.shared.notify_prefetch_waiters(); | |
| 473 | 566 | } |
| 474 | 567 | } |
| 475 | 568 | } |
| ... | ... | @@ -672,8 +765,19 @@ impl MediaCache { |
| 672 | 765 | state.total_bytes = 0; |
| 673 | 766 | state.generation = state.generation.wrapping_add(1); |
| 674 | 767 | #[cfg(not(target_arch = "wasm32"))] |
| 675 | state.known_existing_paths.clear(); | |
| 676 | self.shared.sync_soft_budget(&state); | |
| 768 | { | |
| 769 | state.known_existing_paths.clear(); | |
| 770 | state.speculative_bytes_since_seq = 0; | |
| 771 | state.speculative_count_since_seq = 0; | |
| 772 | state.last_speculative_bytes = 0; | |
| 773 | state.last_prefetch_seq = None; | |
| 774 | } | |
| 775 | self.shared.sync_lookahead_throttle(&state); | |
| 776 | } | |
| 777 | #[cfg(not(target_arch = "wasm32"))] | |
| 778 | { | |
| 779 | self.shared.cv.notify_all(); | |
| 780 | self.shared.notify_prefetch_waiters(); | |
| 677 | 781 | } |
| 678 | 782 | drop(cleared_decoders); |
| 679 | 783 | #[cfg(not(target_arch = "wasm32"))] |
| ... | ... | @@ -715,18 +819,25 @@ impl MediaCache { |
| 715 | 819 | } |
| 716 | 820 | |
| 717 | 821 | pub fn set_budget_mb(&mut self, budget_mb: u64) { |
| 718 | let Ok(mut state) = self.shared.state.lock() else { return }; | |
| 719 | state.budget_bytes = budget_mb.saturating_mul(1024 * 1024); | |
| 720 | while state.total_bytes > state.budget_bytes && state.images.len() > 1 { | |
| 721 | let Some((oldest_key, _)) = state.lru.iter().min_by_key(|(_, t)| **t).map(|(k, t)| (k.clone(), *t)) else { | |
| 722 | break; | |
| 723 | }; | |
| 724 | state.lru.remove(&oldest_key); | |
| 725 | if let Some(removed) = state.images.remove(&oldest_key) { | |
| 726 | state.total_bytes = state.total_bytes.saturating_sub(removed.byte_size()); | |
| 822 | { | |
| 823 | let Ok(mut state) = self.shared.state.lock() else { return }; | |
| 824 | state.budget_bytes = budget_mb.saturating_mul(1024 * 1024); | |
| 825 | while state.total_bytes > state.budget_bytes && state.images.len() > 1 { | |
| 826 | let Some((oldest_key, _)) = state.lru.iter().min_by_key(|(_, t)| **t).map(|(k, t)| (k.clone(), *t)) else { | |
| 827 | break; | |
| 828 | }; | |
| 829 | state.lru.remove(&oldest_key); | |
| 830 | if let Some(removed) = state.images.remove(&oldest_key) { | |
| 831 | state.total_bytes = state.total_bytes.saturating_sub(removed.byte_size()); | |
| 832 | } | |
| 727 | 833 | } |
| 834 | self.shared.sync_lookahead_throttle(&state); | |
| 835 | } | |
| 836 | #[cfg(not(target_arch = "wasm32"))] | |
| 837 | { | |
| 838 | self.shared.cv.notify_all(); | |
| 839 | self.shared.notify_prefetch_waiters(); | |
| 728 | 840 | } |
| 729 | self.shared.sync_soft_budget(&state); | |
| 730 | 841 | } |
| 731 | 842 | |
| 732 | 843 | pub fn entry_count(&self) -> usize { |
| ... | ... | @@ -787,7 +898,10 @@ impl MediaCache { |
| 787 | 898 | continue; |
| 788 | 899 | } |
| 789 | 900 | #[cfg(not(target_arch = "wasm32"))] |
| 790 | state.in_flight.insert(cache_key.clone()); | |
| 901 | { | |
| 902 | state.in_flight.insert(cache_key.clone()); | |
| 903 | self.shared.sync_lookahead_throttle(&state); | |
| 904 | } | |
| 791 | 905 | break state.generation; |
| 792 | 906 | } |
| 793 | 907 | }; |
| ... | ... | @@ -812,19 +926,30 @@ impl MediaCache { |
| 812 | 926 | rgba_f32: None, |
| 813 | 927 | }; |
| 814 | 928 | |
| 815 | if let Ok(mut state) = self.shared.state.lock() { | |
| 929 | let unthrottled = if let Ok(mut state) = self.shared.state.lock() { | |
| 816 | 930 | #[cfg(not(target_arch = "wasm32"))] |
| 817 | 931 | { |
| 818 | 932 | state.in_flight.remove(&cache_key); |
| 819 | 933 | in_flight_guard.key = None; |
| 820 | 934 | } |
| 821 | if state.generation == cache_gen { | |
| 935 | let unthrottled = if state.generation == cache_gen { | |
| 822 | 936 | self.shared |
| 823 | .insert_cached_locked(&mut state, cache_key, decoded.clone()); | |
| 824 | } | |
| 937 | .insert_cached_locked(&mut state, cache_key, decoded.clone()) | |
| 938 | } else { | |
| 939 | self.shared.sync_lookahead_throttle(&state) | |
| 940 | }; | |
| 825 | 941 | #[cfg(not(target_arch = "wasm32"))] |
| 826 | 942 | self.shared.cv.notify_all(); |
| 943 | unthrottled | |
| 944 | } else { | |
| 945 | false | |
| 946 | }; | |
| 947 | #[cfg(not(target_arch = "wasm32"))] | |
| 948 | if unthrottled { | |
| 949 | self.shared.notify_prefetch_waiters(); | |
| 827 | 950 | } |
| 951 | #[cfg(target_arch = "wasm32")] | |
| 952 | let _ = unthrottled; | |
| 828 | 953 | return Some((base_buf, idx, decoded, true)); |
| 829 | 954 | } |
| 830 | 955 | |
| ... | ... | @@ -862,7 +987,10 @@ impl MediaCache { |
| 862 | 987 | continue; |
| 863 | 988 | } |
| 864 | 989 | #[cfg(not(target_arch = "wasm32"))] |
| 865 | state.in_flight.insert(cache_key.clone()); | |
| 990 | { | |
| 991 | state.in_flight.insert(cache_key.clone()); | |
| 992 | self.shared.sync_lookahead_throttle(&state); | |
| 993 | } | |
| 866 | 994 | break state.generation; |
| 867 | 995 | } |
| 868 | 996 | }; |
| ... | ... | @@ -885,6 +1013,7 @@ impl MediaCache { |
| 885 | 1013 | exr_channels[2], |
| 886 | 1014 | exr_channels[3], |
| 887 | 1015 | false, |
| 1016 | true, | |
| 888 | 1017 | ) |
| 889 | 1018 | } else { |
| 890 | 1019 | decode_raster_image(&resolved, post_multiply, true) |
| ... | ... | @@ -896,20 +1025,31 @@ impl MediaCache { |
| 896 | 1025 | return None; |
| 897 | 1026 | }; |
| 898 | 1027 | |
| 899 | if let Ok(mut state) = self.shared.state.lock() { | |
| 1028 | let unthrottled = if let Ok(mut state) = self.shared.state.lock() { | |
| 900 | 1029 | #[cfg(not(target_arch = "wasm32"))] |
| 901 | 1030 | { |
| 902 | 1031 | state.in_flight.remove(&cache_key); |
| 903 | 1032 | in_flight_guard.key = None; |
| 904 | 1033 | } |
| 905 | if state.generation == cache_gen { | |
| 1034 | let unthrottled = if state.generation == cache_gen { | |
| 906 | 1035 | state.record_existing_path(&resolved); |
| 907 | 1036 | self.shared |
| 908 | .insert_cached_locked(&mut state, cache_key, decoded.clone()); | |
| 909 | } | |
| 1037 | .insert_cached_locked(&mut state, cache_key, decoded.clone()) | |
| 1038 | } else { | |
| 1039 | self.shared.sync_lookahead_throttle(&state) | |
| 1040 | }; | |
| 910 | 1041 | #[cfg(not(target_arch = "wasm32"))] |
| 911 | 1042 | self.shared.cv.notify_all(); |
| 1043 | unthrottled | |
| 1044 | } else { | |
| 1045 | false | |
| 1046 | }; | |
| 1047 | #[cfg(not(target_arch = "wasm32"))] | |
| 1048 | if unthrottled { | |
| 1049 | self.shared.notify_prefetch_waiters(); | |
| 912 | 1050 | } |
| 1051 | #[cfg(target_arch = "wasm32")] | |
| 1052 | let _ = unthrottled; | |
| 913 | 1053 | Some((resolved, -1, decoded, true)) |
| 914 | 1054 | } |
| 915 | 1055 | |
| ... | ... | @@ -1016,6 +1156,7 @@ impl MediaCache { |
| 1016 | 1156 | return; |
| 1017 | 1157 | } |
| 1018 | 1158 | state.in_flight.insert(job.cache_key.clone()); |
| 1159 | self.shared.sync_lookahead_throttle(&state); | |
| 1019 | 1160 | state.generation |
| 1020 | 1161 | }; |
| 1021 | 1162 | let mut guard = InFlightGuard { |
| ... | ... | @@ -1023,7 +1164,7 @@ impl MediaCache { |
| 1023 | 1164 | key: Some(job.cache_key.clone()), |
| 1024 | 1165 | }; |
| 1025 | 1166 | let decoded = decode_job(&job, true); |
| 1026 | finish_raster_job(&self.shared, job.cache_key, cache_gen, &mut guard, decoded); | |
| 1167 | finish_raster_job(&self.shared, job.cache_key, cache_gen, &mut guard, decoded, false); | |
| 1027 | 1168 | return; |
| 1028 | 1169 | } |
| 1029 | 1170 | self.decode_jobs_parallel(jobs); |
| ... | ... | @@ -1093,6 +1234,7 @@ impl MediaCache { |
| 1093 | 1234 | None |
| 1094 | 1235 | } else { |
| 1095 | 1236 | state.in_flight.insert(key.clone()); |
| 1237 | self.shared.sync_lookahead_throttle(&state); | |
| 1096 | 1238 | Some(state.generation) |
| 1097 | 1239 | } |
| 1098 | 1240 | }); |
| ... | ... | @@ -1115,14 +1257,22 @@ impl MediaCache { |
| 1115 | 1257 | rgba_f16: None, |
| 1116 | 1258 | rgba_f32: None, |
| 1117 | 1259 | }; |
| 1118 | if let Ok(mut state) = self.shared.state.lock() { | |
| 1260 | let unthrottled = if let Ok(mut state) = self.shared.state.lock() { | |
| 1119 | 1261 | state.in_flight.remove(&key); |
| 1120 | 1262 | guard.key = None; |
| 1121 | if state.generation == cache_gen { | |
| 1263 | let unthrottled = if state.generation == cache_gen { | |
| 1122 | 1264 | self.shared |
| 1123 | .insert_cached_locked(&mut state, key, decoded); | |
| 1124 | } | |
| 1265 | .insert_cached_locked(&mut state, key, decoded) | |
| 1266 | } else { | |
| 1267 | self.shared.sync_lookahead_throttle(&state) | |
| 1268 | }; | |
| 1125 | 1269 | self.shared.cv.notify_all(); |
| 1270 | unthrottled | |
| 1271 | } else { | |
| 1272 | false | |
| 1273 | }; | |
| 1274 | if unthrottled { | |
| 1275 | self.shared.notify_prefetch_waiters(); | |
| 1126 | 1276 | } |
| 1127 | 1277 | } |
| 1128 | 1278 | } |
| ... | ... | @@ -1138,6 +1288,7 @@ impl MediaCache { |
| 1138 | 1288 | None |
| 1139 | 1289 | } else { |
| 1140 | 1290 | state.in_flight.insert(job.cache_key.clone()); |
| 1291 | self.shared.sync_lookahead_throttle(&state); | |
| 1141 | 1292 | Some(state.generation) |
| 1142 | 1293 | } |
| 1143 | 1294 | }); |
| ... | ... | @@ -1153,6 +1304,7 @@ impl MediaCache { |
| 1153 | 1304 | cache_gen, |
| 1154 | 1305 | &mut guard, |
| 1155 | 1306 | decoded, |
| 1307 | false, | |
| 1156 | 1308 | ); |
| 1157 | 1309 | } |
| 1158 | 1310 | }); |
| ... | ... | @@ -1168,19 +1320,32 @@ fn finish_raster_job( |
| 1168 | 1320 | cache_gen: u64, |
| 1169 | 1321 | guard: &mut InFlightGuard<'_>, |
| 1170 | 1322 | decoded: Option<DecodedImage>, |
| 1323 | is_speculative: bool, | |
| 1171 | 1324 | ) { |
| 1172 | if let Ok(mut state) = shared.state.lock() { | |
| 1325 | let unthrottled = if let Ok(mut state) = shared.state.lock() { | |
| 1173 | 1326 | state.in_flight.remove(&key); |
| 1174 | 1327 | guard.key = None; |
| 1175 | if let Some(decoded) = decoded { | |
| 1328 | let unthrottled = if let Some(decoded) = decoded { | |
| 1176 | 1329 | if state.generation == cache_gen { |
| 1177 | 1330 | state.record_existing_path(&key.path); |
| 1178 | shared.insert_cached_locked(&mut state, key, decoded); | |
| 1331 | if is_speculative { | |
| 1332 | state.record_speculative_decode(decoded.byte_size()); | |
| 1333 | } | |
| 1334 | shared.insert_cached_locked(&mut state, key, decoded) | |
| 1335 | } else { | |
| 1336 | shared.sync_lookahead_throttle(&state) | |
| 1179 | 1337 | } |
| 1180 | 1338 | } else { |
| 1181 | 1339 | state.evict_existing_path(&key.path); |
| 1182 | } | |
| 1340 | shared.sync_lookahead_throttle(&state) | |
| 1341 | }; | |
| 1183 | 1342 | shared.cv.notify_all(); |
| 1343 | unthrottled | |
| 1344 | } else { | |
| 1345 | false | |
| 1346 | }; | |
| 1347 | if unthrottled { | |
| 1348 | shared.notify_prefetch_waiters(); | |
| 1184 | 1349 | } |
| 1185 | 1350 | } |
| 1186 | 1351 | |
| ... | ... | @@ -1225,8 +1390,8 @@ struct PrefetchQueue { |
| 1225 | 1390 | |
| 1226 | 1391 | #[cfg(not(target_arch = "wasm32"))] |
| 1227 | 1392 | enum PrefetchWorkItem { |
| 1228 | Raster(PreloadJob), | |
| 1229 | Video(PathBuf, VideoFrameRequest), | |
| 1393 | Raster(usize, usize, PreloadJob), | |
| 1394 | Video(usize, usize, PathBuf, VideoFrameRequest), | |
| 1230 | 1395 | } |
| 1231 | 1396 | |
| 1232 | 1397 | /// Cancellable background read-ahead handle returned by [`MediaCache::start_frame_prefetch`]. |
| ... | ... | @@ -1255,6 +1420,7 @@ impl MediaPrefetchHandle { |
| 1255 | 1420 | }), |
| 1256 | 1421 | cv: Condvar::new(), |
| 1257 | 1422 | }); |
| 1423 | shared.register_prefetch_queue(&queue); | |
| 1258 | 1424 | let worker_count = std::thread::available_parallelism() |
| 1259 | 1425 | .map(|n| n.get().clamp(2, 12)) |
| 1260 | 1426 | .unwrap_or(4); |
| ... | ... | @@ -1275,6 +1441,10 @@ impl MediaPrefetchHandle { |
| 1275 | 1441 | |
| 1276 | 1442 | /// Updates the active render sequence index so read-ahead stays synchronized with playback/export. |
| 1277 | 1443 | pub fn set_current_seq(&self, seq_idx: usize) { |
| 1444 | if let Ok(mut state) = self.shared.state.lock() { | |
| 1445 | state.reset_speculative_window(seq_idx); | |
| 1446 | self.shared.sync_lookahead_throttle(&state); | |
| 1447 | } | |
| 1278 | 1448 | if let Ok(mut q) = self.queue.state.lock() { |
| 1279 | 1449 | q.current_seq = seq_idx; |
| 1280 | 1450 | q.prune_stale(); |
| ... | ... | @@ -1407,7 +1577,7 @@ impl MediaPrefetchHandle { |
| 1407 | 1577 | } |
| 1408 | 1578 | |
| 1409 | 1579 | if chosen_seq > q.current_seq.saturating_add(1) |
| 1410 | && shared.soft_budget_exceeded.load(Ordering::Relaxed) | |
| 1580 | && shared.lookahead_throttled.load(Ordering::Acquire) | |
| 1411 | 1581 | { |
| 1412 | 1582 | q = match queue.cv.wait(q) { |
| 1413 | 1583 | Ok(g) => g, |
| ... | ... | @@ -1416,30 +1586,31 @@ impl MediaPrefetchHandle { |
| 1416 | 1586 | continue; |
| 1417 | 1587 | } |
| 1418 | 1588 | |
| 1589 | let cur_seq = q.current_seq; | |
| 1419 | 1590 | let chosen_video = best_video |
| 1420 | 1591 | .filter(|&(_, _, vs)| best_raster.is_none_or(|(_, rs)| vs <= rs)) |
| 1421 | 1592 | .map(|(path, v_idx, _)| (path.clone(), v_idx)); |
| 1422 | 1593 | |
| 1423 | 1594 | if let Some((path, v_idx)) = chosen_video { |
| 1424 | if let Some((_, req)) = q.videos.get_mut(&path).and_then(|vq| vq.remove(v_idx)) { | |
| 1595 | if let Some((seq, req)) = q.videos.get_mut(&path).and_then(|vq| vq.remove(v_idx)) { | |
| 1425 | 1596 | if q.videos.get(&path).is_some_and(VecDeque::is_empty) { |
| 1426 | 1597 | q.videos.remove(&path); |
| 1427 | 1598 | } |
| 1428 | 1599 | q.active_videos.insert(path.clone()); |
| 1429 | break PrefetchWorkItem::Video(path, req); | |
| 1600 | break PrefetchWorkItem::Video(seq, cur_seq, path, req); | |
| 1430 | 1601 | } |
| 1431 | 1602 | } |
| 1432 | 1603 | if let Some((r_idx, _)) = best_raster { |
| 1433 | if let Some((_, job)) = q.raster.remove(r_idx) { | |
| 1604 | if let Some((seq, job)) = q.raster.remove(r_idx) { | |
| 1434 | 1605 | q.queued_raster_keys.remove(&job.cache_key); |
| 1435 | break PrefetchWorkItem::Raster(job); | |
| 1606 | break PrefetchWorkItem::Raster(seq, cur_seq, job); | |
| 1436 | 1607 | } |
| 1437 | 1608 | } |
| 1438 | 1609 | } |
| 1439 | 1610 | }; |
| 1440 | 1611 | |
| 1441 | 1612 | match item { |
| 1442 | PrefetchWorkItem::Raster(job) => { | |
| 1613 | PrefetchWorkItem::Raster(item_seq, cur_seq, job) => { | |
| 1443 | 1614 | let cache_gen_opt = shared.state.lock().ok().and_then(|mut state| { |
| 1444 | 1615 | if state.images.contains_key(&job.cache_key) |
| 1445 | 1616 | || state.in_flight.contains(&job.cache_key) |
| ... | ... | @@ -1447,6 +1618,7 @@ impl MediaPrefetchHandle { |
| 1447 | 1618 | None |
| 1448 | 1619 | } else { |
| 1449 | 1620 | state.in_flight.insert(job.cache_key.clone()); |
| 1621 | shared.sync_lookahead_throttle(&state); | |
| 1450 | 1622 | Some(state.generation) |
| 1451 | 1623 | } |
| 1452 | 1624 | }); |
| ... | ... | @@ -1456,9 +1628,16 @@ impl MediaPrefetchHandle { |
| 1456 | 1628 | key: Some(job.cache_key.clone()), |
| 1457 | 1629 | }; |
| 1458 | 1630 | let decoded = decode_job(&job, false); |
| 1459 | finish_raster_job(&shared, job.cache_key, cache_gen, &mut guard, decoded); | |
| 1631 | finish_raster_job( | |
| 1632 | &shared, | |
| 1633 | job.cache_key, | |
| 1634 | cache_gen, | |
| 1635 | &mut guard, | |
| 1636 | decoded, | |
| 1637 | item_seq > cur_seq, | |
| 1638 | ); | |
| 1460 | 1639 | } |
| 1461 | PrefetchWorkItem::Video(path, req) => { | |
| 1640 | PrefetchWorkItem::Video(item_seq, cur_seq, path, req) => { | |
| 1462 | 1641 | struct ActiveVideoGuard<'a> { |
| 1463 | 1642 | queue: &'a PrefetchQueue, |
| 1464 | 1643 | path: PathBuf, |
| ... | ... | @@ -1467,9 +1646,7 @@ impl MediaPrefetchHandle { |
| 1467 | 1646 | fn drop(&mut self) { |
| 1468 | 1647 | if let Ok(mut q) = self.queue.state.lock() { |
| 1469 | 1648 | q.active_videos.remove(&self.path); |
| 1470 | if q.videos.contains_key(&self.path) || !q.raster.is_empty() { | |
| 1471 | self.queue.cv.notify_one(); | |
| 1472 | } | |
| 1649 | self.queue.cv.notify_all(); | |
| 1473 | 1650 | } |
| 1474 | 1651 | } |
| 1475 | 1652 | } |
| ... | ... | @@ -1494,6 +1671,7 @@ impl MediaPrefetchHandle { |
| 1494 | 1671 | None |
| 1495 | 1672 | } else { |
| 1496 | 1673 | state.in_flight.insert(key.clone()); |
| 1674 | shared.sync_lookahead_throttle(&state); | |
| 1497 | 1675 | Some(state.generation) |
| 1498 | 1676 | } |
| 1499 | 1677 | }); |
| ... | ... | @@ -1516,13 +1694,24 @@ impl MediaPrefetchHandle { |
| 1516 | 1694 | rgba_f16: None, |
| 1517 | 1695 | rgba_f32: None, |
| 1518 | 1696 | }; |
| 1519 | if let Ok(mut state) = shared.state.lock() { | |
| 1697 | let unthrottled = if let Ok(mut state) = shared.state.lock() { | |
| 1520 | 1698 | state.in_flight.remove(&key); |
| 1521 | 1699 | guard.key = None; |
| 1522 | if state.generation == cache_gen { | |
| 1523 | shared.insert_cached_locked(&mut state, key, decoded); | |
| 1524 | } | |
| 1700 | let unthrottled = if state.generation == cache_gen { | |
| 1701 | if item_seq > cur_seq { | |
| 1702 | state.record_speculative_decode(decoded.byte_size()); | |
| 1703 | } | |
| 1704 | shared.insert_cached_locked(&mut state, key, decoded) | |
| 1705 | } else { | |
| 1706 | shared.sync_lookahead_throttle(&state) | |
| 1707 | }; | |
| 1525 | 1708 | shared.cv.notify_all(); |
| 1709 | unthrottled | |
| 1710 | } else { | |
| 1711 | false | |
| 1712 | }; | |
| 1713 | if unthrottled { | |
| 1714 | shared.notify_prefetch_waiters(); | |
| 1526 | 1715 | } |
| 1527 | 1716 | } |
| 1528 | 1717 | } |
| ... | ... | @@ -2040,7 +2229,7 @@ struct PreloadJob { |
| 2040 | 2229 | } |
| 2041 | 2230 | |
| 2042 | 2231 | #[cfg(not(target_arch = "wasm32"))] |
| 2043 | fn decode_job(job: &PreloadJob, allow_parallel_premult: bool) -> Option<DecodedImage> { | |
| 2232 | fn decode_job(job: &PreloadJob, allow_parallel: bool) -> Option<DecodedImage> { | |
| 2044 | 2233 | if job.is_exr { |
| 2045 | 2234 | decode_exr_rgba( |
| 2046 | 2235 | &job.cache_key.path, |
| ... | ... | @@ -2049,12 +2238,13 @@ fn decode_job(job: &PreloadJob, allow_parallel_premult: bool) -> Option<DecodedI |
| 2049 | 2238 | job.cache_key.exr_channels[2].as_deref(), |
| 2050 | 2239 | job.cache_key.exr_channels[3].as_deref(), |
| 2051 | 2240 | false, |
| 2241 | allow_parallel, | |
| 2052 | 2242 | ) |
| 2053 | 2243 | } else { |
| 2054 | 2244 | decode_raster_image( |
| 2055 | 2245 | &job.cache_key.path, |
| 2056 | 2246 | job.cache_key.post_multiply, |
| 2057 | allow_parallel_premult, | |
| 2247 | allow_parallel, | |
| 2058 | 2248 | ) |
| 2059 | 2249 | } |
| 2060 | 2250 | } |
| ... | ... | @@ -3261,4 +3451,117 @@ mod tests { |
| 3261 | 3451 | handle.cancel(); |
| 3262 | 3452 | let _ = std::fs::remove_dir_all(&dir); |
| 3263 | 3453 | } |
| 3454 | ||
| 3455 | #[cfg(not(target_arch = "wasm32"))] | |
| 3456 | #[test] | |
| 3457 | fn warm_cache_over_75_percent_keeps_full_lookahead() { | |
| 3458 | let dir = std::env::temp_dir().join(format!("fission_warm_lookahead_{}", std::process::id())); | |
| 3459 | let _ = std::fs::remove_dir_all(&dir); | |
| 3460 | std::fs::create_dir_all(&dir).unwrap(); | |
| 3461 | ||
| 3462 | for i in 0..=4 { | |
| 3463 | let p = dir.join(format!("seq_{i:04}.png")); | |
| 3464 | image::RgbaImage::from_pixel(512, 512, image::Rgba([i as u8 * 40, 20, 180, 255])) | |
| 3465 | .save(&p) | |
| 3466 | .unwrap(); | |
| 3467 | } | |
| 3468 | let esc = |p: &Path| p.to_string_lossy().replace('\\', "\\\\"); | |
| 3469 | let p0 = dir.join("seq_0000.png"); | |
| 3470 | let comp_src = format!( | |
| 3471 | r#"Composition {{ | |
| 3472 | CurrentTime = 0, | |
| 3473 | RenderRange = {{ 0, 4 }}, | |
| 3474 | GlobalRange = {{ 0, 4 }}, | |
| 3475 | Tools = ordered() {{ | |
| 3476 | LD = Loader {{ | |
| 3477 | Clips = {{ | |
| 3478 | Clip {{ | |
| 3479 | ID = "Clip1", | |
| 3480 | Filename = "{}", | |
| 3481 | FormatID = "PNGFormat", | |
| 3482 | StartFrame = 0, | |
| 3483 | Length = 5, | |
| 3484 | GlobalStart = 0, | |
| 3485 | GlobalEnd = 4, | |
| 3486 | }}, | |
| 3487 | }}, | |
| 3488 | }}, | |
| 3489 | }}, | |
| 3490 | }}"#, | |
| 3491 | esc(&p0) | |
| 3492 | ); | |
| 3493 | let comp = Comp::from_fusion_str(&comp_src).expect("parse warm lookahead comp"); | |
| 3494 | let target = comp.find_node("LD").unwrap(); | |
| 3495 | let clip = comp.node(target).clips[0].clone(); | |
| 3496 | let expr = model::ExprEngine::new(); | |
| 3497 | let mut cache = MediaCache::new(64); | |
| 3498 | ||
| 3499 | // Warm the cache past 75% of its 64 MiB budget (13 x 4 MiB = 52 MiB = 81.25%). | |
| 3500 | let four_mb = Arc::new(vec![128u8; 1024 * 1024 * 4]); | |
| 3501 | { | |
| 3502 | let mut state = cache.shared.state.lock().unwrap(); | |
| 3503 | for i in 0..13 { | |
| 3504 | let key = ImageCacheKey { | |
| 3505 | path: dir.join(format!("warm_{i:04}.png")), | |
| 3506 | frame_idx: -1, | |
| 3507 | post_multiply: false, | |
| 3508 | exr_channels: [None, None, None, None], | |
| 3509 | }; | |
| 3510 | let img = DecodedImage { | |
| 3511 | size: [1024, 1024], | |
| 3512 | rgba: Arc::clone(&four_mb), | |
| 3513 | rgba_f16: None, | |
| 3514 | rgba_f32: None, | |
| 3515 | }; | |
| 3516 | cache.shared.insert_cached_locked(&mut state, key, img); | |
| 3517 | } | |
| 3518 | } | |
| 3519 | assert!( | |
| 3520 | cache.total_mb() > 48.0, | |
| 3521 | "cache must be >75% of 64 MiB, got {:.2} MiB", | |
| 3522 | cache.total_mb() | |
| 3523 | ); | |
| 3524 | ||
| 3525 | let mut handle = cache.start_frame_prefetch(4); | |
| 3526 | handle.set_current_seq(0); | |
| 3527 | for seq in 1..=4 { | |
| 3528 | handle.enqueue_frame(&comp, target, seq, seq as f64, &expr, false); | |
| 3529 | } | |
| 3530 | ||
| 3531 | // All 4 lookahead frames (through current_seq + 4) must be prefetched without collapsing | |
| 3532 | // to current_seq + 1. | |
| 3533 | let expected_keys: Vec<ImageCacheKey> = (1..=4) | |
| 3534 | .map(|i| ImageCacheKey { | |
| 3535 | path: dir.join(format!("seq_{i:04}.png")), | |
| 3536 | frame_idx: -1, | |
| 3537 | post_multiply: false, | |
| 3538 | exr_channels: [None, None, None, None], | |
| 3539 | }) | |
| 3540 | .collect(); | |
| 3541 | let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); | |
| 3542 | loop { | |
| 3543 | let all_cached = cache | |
| 3544 | .shared | |
| 3545 | .state | |
| 3546 | .lock() | |
| 3547 | .map(|s| expected_keys.iter().all(|k| s.images.contains_key(k))) | |
| 3548 | .unwrap_or(false); | |
| 3549 | if all_cached || std::time::Instant::now() >= deadline { | |
| 3550 | break; | |
| 3551 | } | |
| 3552 | std::thread::sleep(std::time::Duration::from_millis(5)); | |
| 3553 | } | |
| 3554 | ||
| 3555 | for i in 1..=4 { | |
| 3556 | let (_, _, img, from_disk) = cache.load_clip(&clip, i, false, [None; 4]).unwrap(); | |
| 3557 | assert!( | |
| 3558 | !from_disk, | |
| 3559 | "frame {i} (current_seq + {i}) should have been prefetched while >75% warm" | |
| 3560 | ); | |
| 3561 | assert_eq!(img.rgba[0], (i as u8) * 40); | |
| 3562 | } | |
| 3563 | ||
| 3564 | handle.cancel(); | |
| 3565 | let _ = std::fs::remove_dir_all(&dir); | |
| 3566 | } | |
| 3264 | 3567 | } |
crates/engine/src/media/exr.rs+68-50| ... | ... | @@ -186,14 +186,16 @@ pub(super) fn decode_exr_rgba( |
| 186 | 186 | blue_name: Option<&str>, |
| 187 | 187 | alpha_name: Option<&str>, |
| 188 | 188 | post_multiply: bool, |
| 189 | allow_parallel: bool, | |
| 189 | 190 | ) -> Option<DecodedImage> { |
| 190 | 191 | let names = [red_name, green_name, blue_name, alpha_name]; |
| 191 | 192 | match super::virtual_bytes(path) { |
| 192 | Some(bytes) => decode_exr_from(std::io::Cursor::new(bytes), names, post_multiply), | |
| 193 | Some(bytes) => decode_exr_from(std::io::Cursor::new(bytes), names, post_multiply, allow_parallel), | |
| 193 | 194 | None => decode_exr_from( |
| 194 | 195 | std::io::BufReader::with_capacity(256 * 1024, std::fs::File::open(path).ok()?), |
| 195 | 196 | names, |
| 196 | 197 | post_multiply, |
| 198 | allow_parallel, | |
| 197 | 199 | ), |
| 198 | 200 | } |
| 199 | 201 | } |
| ... | ... | @@ -256,12 +258,13 @@ fn convert_exr_rgba_buffers( |
| 256 | 258 | has_b: bool, |
| 257 | 259 | has_a: bool, |
| 258 | 260 | post_multiply: bool, |
| 261 | allow_parallel: bool, | |
| 259 | 262 | ) { |
| 260 | 263 | #[cfg(not(target_arch = "wasm32"))] |
| 261 | 264 | { |
| 262 | 265 | const PARALLEL_THRESHOLD_PIXELS: usize = 512 * 512; |
| 263 | 266 | let total_px = raw_f32.len() / 4; |
| 264 | if total_px >= PARALLEL_THRESHOLD_PIXELS { | |
| 267 | if allow_parallel && total_px >= PARALLEL_THRESHOLD_PIXELS { | |
| 265 | 268 | let workers = std::thread::available_parallelism() |
| 266 | 269 | .map(|n| n.get().clamp(2, 12)) |
| 267 | 270 | .unwrap_or(4) |
| ... | ... | @@ -289,6 +292,8 @@ fn convert_exr_rgba_buffers( |
| 289 | 292 | return; |
| 290 | 293 | } |
| 291 | 294 | } |
| 295 | #[cfg(target_arch = "wasm32")] | |
| 296 | let _ = allow_parallel; | |
| 292 | 297 | convert_exr_rgba_slice( |
| 293 | 298 | raw_f32, |
| 294 | 299 | raw_f16, |
| ... | ... | @@ -304,8 +309,11 @@ fn decode_exr_from<R: std::io::Read + std::io::Seek + Send>( |
| 304 | 309 | reader: R, |
| 305 | 310 | [red_name, green_name, blue_name, alpha_name]: [Option<&str>; 4], |
| 306 | 311 | post_multiply: bool, |
| 312 | allow_parallel: bool, | |
| 307 | 313 | ) -> Option<DecodedImage> { |
| 308 | 314 | use ::exr::block::reader::ChunksReader; |
| 315 | use ::exr::block::UncompressedBlock; | |
| 316 | use ::exr::error::UnitResult; | |
| 309 | 317 | use ::exr::meta::attribute::SampleType; |
| 310 | 318 | use ::exr::prelude::*; |
| 311 | 319 | |
| ... | ... | @@ -332,63 +340,67 @@ fn decode_exr_from<R: std::io::Read + std::io::Seek + Send>( |
| 332 | 340 | let mut line_f16 = Vec::<f16>::new(); |
| 333 | 341 | let mut line_u32 = Vec::<u32>::new(); |
| 334 | 342 | |
| 335 | chunks_reader | |
| 343 | let filtered = chunks_reader | |
| 336 | 344 | .filter_chunks(false, |_, tile, block| { |
| 337 | 345 | tile.is_largest_resolution_level() && needed_layers.contains(&block.layer) |
| 338 | 346 | }) |
| 339 | .ok()? | |
| 340 | .decompress_parallel(false, |meta, block| { | |
| 341 | let header = &meta.headers[block.index.layer]; | |
| 342 | for line in block.lines(&header.channels) { | |
| 343 | let loc = (line.location.layer, line.location.channel); | |
| 344 | let mut comp_mask = [false; 4]; | |
| 345 | for (c, t) in target_locs.iter().enumerate() { | |
| 346 | if *t == Some(loc) { | |
| 347 | comp_mask[c] = true; | |
| 348 | } | |
| 347 | .ok()?; | |
| 348 | let insert_block = |meta: &MetaData, block: UncompressedBlock| -> UnitResult { | |
| 349 | let header = &meta.headers[block.index.layer]; | |
| 350 | for line in block.lines(&header.channels) { | |
| 351 | let loc = (line.location.layer, line.location.channel); | |
| 352 | let mut comp_mask = [false; 4]; | |
| 353 | for (c, t) in target_locs.iter().enumerate() { | |
| 354 | if *t == Some(loc) { | |
| 355 | comp_mask[c] = true; | |
| 349 | 356 | } |
| 350 | if !comp_mask.iter().any(|&m| m) { | |
| 351 | continue; | |
| 357 | } | |
| 358 | if !comp_mask.iter().any(|&m| m) { | |
| 359 | continue; | |
| 360 | } | |
| 361 | let y = line.location.position.y(); | |
| 362 | let x0 = line.location.position.x(); | |
| 363 | let len = line.location.sample_count; | |
| 364 | if y >= h || x0 + len > w { | |
| 365 | continue; | |
| 366 | } | |
| 367 | ||
| 368 | line_f32.clear(); | |
| 369 | match header.channels.list[line.location.channel].sample_type { | |
| 370 | SampleType::F32 => { | |
| 371 | line_f32.resize(len, 0.0); | |
| 372 | line.read_samples_into_slice(&mut line_f32)?; | |
| 352 | 373 | } |
| 353 | let y = line.location.position.y(); | |
| 354 | let x0 = line.location.position.x(); | |
| 355 | let len = line.location.sample_count; | |
| 356 | if y >= h || x0 + len > w { | |
| 357 | continue; | |
| 374 | SampleType::F16 => { | |
| 375 | line_f16.resize(len, f16::ZERO); | |
| 376 | line.read_samples_into_slice(&mut line_f16)?; | |
| 377 | line_f32.extend(line_f16.iter().map(|v| v.to_f32())); | |
| 358 | 378 | } |
| 359 | ||
| 360 | line_f32.clear(); | |
| 361 | match header.channels.list[line.location.channel].sample_type { | |
| 362 | SampleType::F32 => { | |
| 363 | line_f32.resize(len, 0.0); | |
| 364 | line.read_samples_into_slice(&mut line_f32)?; | |
| 365 | } | |
| 366 | SampleType::F16 => { | |
| 367 | line_f16.resize(len, f16::ZERO); | |
| 368 | line.read_samples_into_slice(&mut line_f16)?; | |
| 369 | line_f32.extend(line_f16.iter().map(|v| v.to_f32())); | |
| 370 | } | |
| 371 | SampleType::U32 => { | |
| 372 | line_u32.resize(len, 0); | |
| 373 | line.read_samples_into_slice(&mut line_u32)?; | |
| 374 | line_f32.extend(line_u32.iter().map(|&v| v as f32)); | |
| 375 | } | |
| 379 | SampleType::U32 => { | |
| 380 | line_u32.resize(len, 0); | |
| 381 | line.read_samples_into_slice(&mut line_u32)?; | |
| 382 | line_f32.extend(line_u32.iter().map(|&v| v as f32)); | |
| 376 | 383 | } |
| 384 | } | |
| 377 | 385 | |
| 378 | let row_base = (y * w + x0) * 4; | |
| 379 | for (dx, &sample) in line_f32.iter().enumerate() { | |
| 380 | let val = if sample.is_nan() { 0.0 } else { sample }; | |
| 381 | let px_off = row_base + dx * 4; | |
| 382 | for (c, &enabled) in comp_mask.iter().enumerate() { | |
| 383 | if enabled { | |
| 384 | raw_f32[px_off + c] = val; | |
| 385 | } | |
| 386 | let row_base = (y * w + x0) * 4; | |
| 387 | for (dx, &sample) in line_f32.iter().enumerate() { | |
| 388 | let val = if sample.is_nan() { 0.0 } else { sample }; | |
| 389 | let px_off = row_base + dx * 4; | |
| 390 | for (c, &enabled) in comp_mask.iter().enumerate() { | |
| 391 | if enabled { | |
| 392 | raw_f32[px_off + c] = val; | |
| 386 | 393 | } |
| 387 | 394 | } |
| 388 | 395 | } |
| 389 | Ok(()) | |
| 390 | }) | |
| 391 | .ok()?; | |
| 396 | } | |
| 397 | Ok(()) | |
| 398 | }; | |
| 399 | if allow_parallel { | |
| 400 | filtered.decompress_parallel(false, insert_block).ok()?; | |
| 401 | } else { | |
| 402 | filtered.decompress_sequential(false, insert_block).ok()?; | |
| 403 | } | |
| 392 | 404 | |
| 393 | 405 | let mut raw = vec![0u8; w * h * 4]; |
| 394 | 406 | let mut raw_f16 = vec![0u16; w * h * 4]; |
| ... | ... | @@ -400,6 +412,7 @@ fn decode_exr_from<R: std::io::Read + std::io::Seek + Send>( |
| 400 | 412 | b_loc.is_some(), |
| 401 | 413 | a_loc.is_some(), |
| 402 | 414 | post_multiply, |
| 415 | allow_parallel, | |
| 403 | 416 | ); |
| 404 | 417 | Some(DecodedImage { |
| 405 | 418 | size: [w as u32, h as u32], |
| ... | ... | @@ -421,9 +434,12 @@ mod tests { |
| 421 | 434 | image::DynamicImage::ImageRgba32F(pixels).write_to(&mut out, image::ImageFormat::OpenExr).unwrap(); |
| 422 | 435 | assert!(MediaCache::insert_virtual_bytes("vexr_drop/frame.exr", out.into_inner())); |
| 423 | 436 | |
| 424 | let decoded = decode_exr_rgba(Path::new("/not/on/disk/vexr_drop/frame.exr"), None, None, None, None, false).unwrap(); | |
| 437 | let decoded = decode_exr_rgba(Path::new("/not/on/disk/vexr_drop/frame.exr"), None, None, None, None, false, true).unwrap(); | |
| 425 | 438 | assert_eq!(decoded.size, [2, 1]); |
| 426 | 439 | assert_eq!(&decoded.rgba_f32.unwrap()[..4], &[2.5, 0.5, 0.0, 1.0]); |
| 440 | let decoded_seq = decode_exr_rgba(Path::new("/not/on/disk/vexr_drop/frame.exr"), None, None, None, None, false, false).unwrap(); | |
| 441 | assert_eq!(decoded_seq.size, [2, 1]); | |
| 442 | assert_eq!(&decoded_seq.rgba_f32.unwrap()[..4], &[2.5, 0.5, 0.0, 1.0]); | |
| 427 | 443 | } |
| 428 | 444 | |
| 429 | 445 | #[test] |
| ... | ... | @@ -469,12 +485,13 @@ mod tests { |
| 469 | 485 | has_b, |
| 470 | 486 | has_a, |
| 471 | 487 | post_multiply, |
| 488 | true, | |
| 472 | 489 | ); |
| 473 | 490 | |
| 474 | 491 | let mut seq_f32 = base.clone(); |
| 475 | 492 | let mut seq_f16 = vec![0u16; pixels * 4]; |
| 476 | 493 | let mut seq_u8 = vec![0u8; pixels * 4]; |
| 477 | convert_exr_rgba_slice( | |
| 494 | convert_exr_rgba_buffers( | |
| 478 | 495 | &mut seq_f32, |
| 479 | 496 | &mut seq_f16, |
| 480 | 497 | &mut seq_u8, |
| ... | ... | @@ -482,6 +499,7 @@ mod tests { |
| 482 | 499 | has_b, |
| 483 | 500 | has_a, |
| 484 | 501 | post_multiply, |
| 502 | false, | |
| 485 | 503 | ); |
| 486 | 504 | |
| 487 | 505 | assert_eq!(par_f16, seq_f16, "f16 mismatch for ({has_g},{has_b},{has_a},{post_multiply})"); |