authoravatarclover caruso<git@paperclover.net>2026-12-01 16:13:53-08:00
committeravatarclover caruso<git@paperclover.net>2026-12-01 16:27:14-08:00
log200ab32029f147f893c3b65597794ffbf072ffd2
treeab698c628d9c882a66c27e6409a2b2bb3c065b87
parentf80b0ebc6787471689dc60d888ce6ebb3bcf5b8f
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

fix(engine): fix media lookahead throttle, EXR thread oversubscription, av_decode EOF hold, and selective Cryptomatte


4 files changed, 710 insertions(+), 153 deletions(-)

crates/engine/src/av_decode.m+29-8
......@@ -431,14 +431,17 @@ AvVideoDecoder *av_video_open(
431431static CMSampleBufferRef read_target_sample(
432432 AvVideoDecoderObj *obj,
433433 double targetPts,
434 double halfFrame
434 double halfFrame,
435 BOOL *outHitEof
435436) {
436437 CMSampleBufferRef chosen = NULL;
437438 CMSampleBufferRef lastSeen = NULL;
439 BOOL hitEof = NO;
438440
439441 while (obj.reader.status == AVAssetReaderStatusReading) {
440442 CMSampleBufferRef sb = [obj.output copyNextSampleBuffer];
441443 if (!sb) {
444 hitEof = (obj.reader.status == AVAssetReaderStatusCompleted);
442445 break;
443446 }
444447 CMTime ptsTime = CMSampleBufferGetPresentationTimeStamp(sb);
......@@ -457,10 +460,14 @@ static CMSampleBufferRef read_target_sample(
457460 if (!chosen && lastSeen) {
458461 chosen = lastSeen;
459462 lastSeen = NULL;
463 hitEof = YES;
460464 }
461465 if (lastSeen) {
462466 CFRelease(lastSeen);
463467 }
468 if (outHitEof) {
469 *outHitEof = hitEof || (obj.reader.status == AVAssetReaderStatusCompleted);
470 }
464471 return chosen;
465472}
466473
......@@ -493,6 +500,7 @@ int av_video_decode_frame(
493500 (obj.lastFrameIdx >= 0 && frame_idx > obj.lastFrameIdx &&
494501 frame_idx <= obj.lastFrameIdx + 8));
495502
503 int64_t prevLastFrameIdx = obj.lastFrameIdx;
496504 double seekSec = 0.0;
497505 if (!canAdvance) {
498506 seekSec = (frame_idx == 0) ? 0.0 : fmax(0.0, targetPts - (1.5 / fps));
......@@ -501,15 +509,28 @@ int av_video_decode_frame(
501509 }
502510 }
503511
504 CMSampleBufferRef chosen = read_target_sample(obj, targetPts, halfFrame);
512 BOOL hitEof = NO;
513 CMSampleBufferRef chosen = read_target_sample(obj, targetPts, halfFrame, &hitEof);
505514
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) {
509519 double endAnchor = obj.durSec > 0.0 ? fmin(targetPts, obj.trackStartSec + obj.durSec) : targetPts;
510520 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 }
513534 }
514535 }
515536
......@@ -530,7 +551,7 @@ int av_video_decode_frame(
530551 CFRelease(chosen);
531552
532553 if (ok) {
533 if (obj.nbFrames <= 0 || frame_idx >= obj.nbFrames - 4) {
554 if (hitEof || obj.nbFrames <= 0 || frame_idx >= obj.nbFrames - 4) {
534555 if (!obj.lastFrameRgba || obj.lastFrameRgba.length < required) {
535556 obj.lastFrameRgba = [NSMutableData dataWithLength:required];
536557 }
crates/engine/src/cryptomatte.rs+247-32
......@@ -392,19 +392,23 @@ fn parse_hex_literal_token(token: &str) -> Option<u32> {
392392#[cfg(not(target_arch = "wasm32"))]
393393const CRYPTO_PARALLEL_THRESHOLD_PIXELS: usize = 512 * 512;
394394
395fn accumulate_cryptomatte_chunk(
395#[inline]
396fn accumulate_chunk_with<F: Fn(u32) -> bool>(
396397 out: &mut [f32],
397398 start: usize,
398399 pairs: &[(&[f32], &[f32])],
399 target_ids: &HashSet<u32>,
400 contains_id: F,
400401) {
401402 let len = out.len();
402403 for &(ids, covs) in pairs {
403404 let ids_slice = &ids[start..start + len];
404405 let covs_slice = &covs[start..start + len];
405406 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 }
408412 }
409413 }
410414 }
......@@ -413,6 +417,26 @@ fn accumulate_cryptomatte_chunk(
413417 }
414418}
415419
420fn 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
416440fn accumulate_cryptomatte_scalar(
417441 pairs: &[(&[f32], &[f32])],
418442 target_ids: &HashSet<u32>,
......@@ -499,8 +523,8 @@ pub fn list_cryptomatte_layers(exr_path: &Path) -> Vec<String> {
499523
500524/// Extracts a Cryptomatte coverage matte from a multi-channel OpenEXR file.
501525///
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`.
504528/// - Resolves `cryptomatte/<id>/name`, `cryptomatte/<id>/manifest`, and sidecar
505529/// `cryptomatte/<id>/manif_file` relative to `exr_path.parent()`.
506530/// - Matches `layer_name` by exact name, suffix (e.g. `"CryptoObject"` -> `"ViewLayer.CryptoObject"`),
......@@ -512,15 +536,19 @@ pub fn extract_cryptomatte(
512536 layer_name: Option<&str>,
513537 matte_list: &str,
514538) -> Option<CryptomatteResult> {
539 use exr::block::reader::ChunksReader;
540 use exr::meta::attribute::SampleType;
515541 use exr::prelude::*;
516542
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()?;
518546
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.
520548 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);
524552 }
525553
526554 // 2. Select target Cryptomatte layer and manifest.
......@@ -545,11 +573,14 @@ pub fn extract_cryptomatte(
545573 } else if let Some(req) = req_layer {
546574 req.to_string()
547575 } else {
548 // Fallback: infer first rank-00 prefix from channels.
576 // Fallback: infer first rank-00 prefix from headers.
549577 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 {
553584 let full = full_channel_name(lname.as_deref(), &ch.name.to_string());
554585 if let Some((prefix, 0, 0)) = split_crypto_rank_channel(&full) {
555586 inferred = Some(prefix.to_string());
......@@ -601,18 +632,26 @@ pub fn extract_cryptomatte(
601632 target_ids.insert(crypto_hash_to_float(direct_hash).to_bits());
602633 }
603634
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.
605636 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();
607640
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();
611647 if lw == 0 || lh == 0 {
612648 continue;
613649 }
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 }
616655 let full = full_channel_name(lname.as_deref(), &ch.name.to_string());
617656 let Some((prefix, rank, comp_idx)) = split_crypto_rank_channel(&full) else {
618657 continue;
......@@ -627,12 +666,13 @@ pub fn extract_cryptomatte(
627666 } else {
628667 dims = Some((lw, lh));
629668 }
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);
636676 }
637677 }
638678 }
......@@ -646,14 +686,75 @@ pub fn extract_cryptomatte(
646686 });
647687 }
648688
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
649745 // 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 }
650751 let mut pairs: Vec<(&[f32], &[f32])> = Vec::with_capacity(ranks.len() * 2);
651752 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));
654755 }
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));
657758 }
658759 }
659760 let matte = accumulate_cryptomatte_matte(&pairs, &target_ids, pixel_count);
......@@ -987,4 +1088,118 @@ mod tests {
9871088 );
9881089 }
9891090 }
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 }
9901205}
crates/engine/src/media.rs+366-63
......@@ -28,7 +28,7 @@ use std::process::Command;
2828#[cfg(not(target_arch = "wasm32"))]
2929use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
3030#[cfg(not(target_arch = "wasm32"))]
31use std::sync::{Condvar, mpsc};
31use std::sync::{Condvar, Weak, mpsc};
3232use std::sync::{Arc, Mutex, RwLock};
3333
3434#[derive(Clone)]
......@@ -214,6 +214,14 @@ struct MediaState {
214214 opening_videos: HashSet<PathBuf>,
215215 #[cfg(not(target_arch = "wasm32"))]
216216 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>,
217225}
218226
219227impl MediaState {
......@@ -232,6 +240,14 @@ impl MediaState {
232240 opening_videos: HashSet::new(),
233241 #[cfg(not(target_arch = "wasm32"))]
234242 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,
235251 }
236252 }
237253
......@@ -255,8 +271,34 @@ impl MediaState {
255271 }
256272
257273 #[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
260302 }
261303
262304 fn insert_cached(&mut self, cache_key: ImageCacheKey, decoded: DecodedImage) {
......@@ -320,26 +362,70 @@ struct MediaShared {
320362 #[cfg(not(target_arch = "wasm32"))]
321363 cv: Condvar,
322364 #[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>>>,
324368}
325369
326370impl MediaShared {
327371 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();
328375 Self {
329 state: Mutex::new(MediaState::new(budget_bytes)),
376 state: Mutex::new(initial_state),
330377 #[cfg(not(target_arch = "wasm32"))]
331378 cv: Condvar::new(),
332379 #[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()),
334383 }
335384 }
336385
337 fn sync_soft_budget(&self, state: &MediaState) {
386 fn sync_lookahead_throttle(&self, state: &MediaState) -> bool {
338387 #[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 }
341394 #[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 }
343429 }
344430
345431 fn insert_cached_locked(
......@@ -347,9 +433,9 @@ impl MediaShared {
347433 state: &mut MediaState,
348434 cache_key: ImageCacheKey,
349435 decoded: DecodedImage,
350 ) {
436 ) -> bool {
351437 state.insert_cached(cache_key, decoded);
352 self.sync_soft_budget(state);
438 self.sync_lookahead_throttle(state)
353439 }
354440
355441 fn path_exists_cached(&self, path: &Path) -> bool {
......@@ -467,9 +553,16 @@ struct InFlightGuard<'a> {
467553impl Drop for InFlightGuard<'_> {
468554 fn drop(&mut self) {
469555 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() {
471557 state.in_flight.remove(&key);
558 let unthrottled = self.shared.sync_lookahead_throttle(&state);
472559 self.shared.cv.notify_all();
560 unthrottled
561 } else {
562 false
563 };
564 if unthrottled {
565 self.shared.notify_prefetch_waiters();
473566 }
474567 }
475568 }
......@@ -672,8 +765,19 @@ impl MediaCache {
672765 state.total_bytes = 0;
673766 state.generation = state.generation.wrapping_add(1);
674767 #[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();
677781 }
678782 drop(cleared_decoders);
679783 #[cfg(not(target_arch = "wasm32"))]
......@@ -715,18 +819,25 @@ impl MediaCache {
715819 }
716820
717821 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 }
727833 }
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();
728840 }
729 self.shared.sync_soft_budget(&state);
730841 }
731842
732843 pub fn entry_count(&self) -> usize {
......@@ -787,7 +898,10 @@ impl MediaCache {
787898 continue;
788899 }
789900 #[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 }
791905 break state.generation;
792906 }
793907 };
......@@ -812,19 +926,30 @@ impl MediaCache {
812926 rgba_f32: None,
813927 };
814928
815 if let Ok(mut state) = self.shared.state.lock() {
929 let unthrottled = if let Ok(mut state) = self.shared.state.lock() {
816930 #[cfg(not(target_arch = "wasm32"))]
817931 {
818932 state.in_flight.remove(&cache_key);
819933 in_flight_guard.key = None;
820934 }
821 if state.generation == cache_gen {
935 let unthrottled = if state.generation == cache_gen {
822936 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 };
825941 #[cfg(not(target_arch = "wasm32"))]
826942 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();
827950 }
951 #[cfg(target_arch = "wasm32")]
952 let _ = unthrottled;
828953 return Some((base_buf, idx, decoded, true));
829954 }
830955
......@@ -862,7 +987,10 @@ impl MediaCache {
862987 continue;
863988 }
864989 #[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 }
866994 break state.generation;
867995 }
868996 };
......@@ -885,6 +1013,7 @@ impl MediaCache {
8851013 exr_channels[2],
8861014 exr_channels[3],
8871015 false,
1016 true,
8881017 )
8891018 } else {
8901019 decode_raster_image(&resolved, post_multiply, true)
......@@ -896,20 +1025,31 @@ impl MediaCache {
8961025 return None;
8971026 };
8981027
899 if let Ok(mut state) = self.shared.state.lock() {
1028 let unthrottled = if let Ok(mut state) = self.shared.state.lock() {
9001029 #[cfg(not(target_arch = "wasm32"))]
9011030 {
9021031 state.in_flight.remove(&cache_key);
9031032 in_flight_guard.key = None;
9041033 }
905 if state.generation == cache_gen {
1034 let unthrottled = if state.generation == cache_gen {
9061035 state.record_existing_path(&resolved);
9071036 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 };
9101041 #[cfg(not(target_arch = "wasm32"))]
9111042 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();
9121050 }
1051 #[cfg(target_arch = "wasm32")]
1052 let _ = unthrottled;
9131053 Some((resolved, -1, decoded, true))
9141054 }
9151055
......@@ -1016,6 +1156,7 @@ impl MediaCache {
10161156 return;
10171157 }
10181158 state.in_flight.insert(job.cache_key.clone());
1159 self.shared.sync_lookahead_throttle(&state);
10191160 state.generation
10201161 };
10211162 let mut guard = InFlightGuard {
......@@ -1023,7 +1164,7 @@ impl MediaCache {
10231164 key: Some(job.cache_key.clone()),
10241165 };
10251166 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);
10271168 return;
10281169 }
10291170 self.decode_jobs_parallel(jobs);
......@@ -1093,6 +1234,7 @@ impl MediaCache {
10931234 None
10941235 } else {
10951236 state.in_flight.insert(key.clone());
1237 self.shared.sync_lookahead_throttle(&state);
10961238 Some(state.generation)
10971239 }
10981240 });
......@@ -1115,14 +1257,22 @@ impl MediaCache {
11151257 rgba_f16: None,
11161258 rgba_f32: None,
11171259 };
1118 if let Ok(mut state) = self.shared.state.lock() {
1260 let unthrottled = if let Ok(mut state) = self.shared.state.lock() {
11191261 state.in_flight.remove(&key);
11201262 guard.key = None;
1121 if state.generation == cache_gen {
1263 let unthrottled = if state.generation == cache_gen {
11221264 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 };
11251269 self.shared.cv.notify_all();
1270 unthrottled
1271 } else {
1272 false
1273 };
1274 if unthrottled {
1275 self.shared.notify_prefetch_waiters();
11261276 }
11271277 }
11281278 }
......@@ -1138,6 +1288,7 @@ impl MediaCache {
11381288 None
11391289 } else {
11401290 state.in_flight.insert(job.cache_key.clone());
1291 self.shared.sync_lookahead_throttle(&state);
11411292 Some(state.generation)
11421293 }
11431294 });
......@@ -1153,6 +1304,7 @@ impl MediaCache {
11531304 cache_gen,
11541305 &mut guard,
11551306 decoded,
1307 false,
11561308 );
11571309 }
11581310 });
......@@ -1168,19 +1320,32 @@ fn finish_raster_job(
11681320 cache_gen: u64,
11691321 guard: &mut InFlightGuard<'_>,
11701322 decoded: Option<DecodedImage>,
1323 is_speculative: bool,
11711324) {
1172 if let Ok(mut state) = shared.state.lock() {
1325 let unthrottled = if let Ok(mut state) = shared.state.lock() {
11731326 state.in_flight.remove(&key);
11741327 guard.key = None;
1175 if let Some(decoded) = decoded {
1328 let unthrottled = if let Some(decoded) = decoded {
11761329 if state.generation == cache_gen {
11771330 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)
11791337 }
11801338 } else {
11811339 state.evict_existing_path(&key.path);
1182 }
1340 shared.sync_lookahead_throttle(&state)
1341 };
11831342 shared.cv.notify_all();
1343 unthrottled
1344 } else {
1345 false
1346 };
1347 if unthrottled {
1348 shared.notify_prefetch_waiters();
11841349 }
11851350}
11861351
......@@ -1225,8 +1390,8 @@ struct PrefetchQueue {
12251390
12261391#[cfg(not(target_arch = "wasm32"))]
12271392enum PrefetchWorkItem {
1228 Raster(PreloadJob),
1229 Video(PathBuf, VideoFrameRequest),
1393 Raster(usize, usize, PreloadJob),
1394 Video(usize, usize, PathBuf, VideoFrameRequest),
12301395}
12311396
12321397/// Cancellable background read-ahead handle returned by [`MediaCache::start_frame_prefetch`].
......@@ -1255,6 +1420,7 @@ impl MediaPrefetchHandle {
12551420 }),
12561421 cv: Condvar::new(),
12571422 });
1423 shared.register_prefetch_queue(&queue);
12581424 let worker_count = std::thread::available_parallelism()
12591425 .map(|n| n.get().clamp(2, 12))
12601426 .unwrap_or(4);
......@@ -1275,6 +1441,10 @@ impl MediaPrefetchHandle {
12751441
12761442 /// Updates the active render sequence index so read-ahead stays synchronized with playback/export.
12771443 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 }
12781448 if let Ok(mut q) = self.queue.state.lock() {
12791449 q.current_seq = seq_idx;
12801450 q.prune_stale();
......@@ -1407,7 +1577,7 @@ impl MediaPrefetchHandle {
14071577 }
14081578
14091579 if chosen_seq > q.current_seq.saturating_add(1)
1410 && shared.soft_budget_exceeded.load(Ordering::Relaxed)
1580 && shared.lookahead_throttled.load(Ordering::Acquire)
14111581 {
14121582 q = match queue.cv.wait(q) {
14131583 Ok(g) => g,
......@@ -1416,30 +1586,31 @@ impl MediaPrefetchHandle {
14161586 continue;
14171587 }
14181588
1589 let cur_seq = q.current_seq;
14191590 let chosen_video = best_video
14201591 .filter(|&(_, _, vs)| best_raster.is_none_or(|(_, rs)| vs <= rs))
14211592 .map(|(path, v_idx, _)| (path.clone(), v_idx));
14221593
14231594 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)) {
14251596 if q.videos.get(&path).is_some_and(VecDeque::is_empty) {
14261597 q.videos.remove(&path);
14271598 }
14281599 q.active_videos.insert(path.clone());
1429 break PrefetchWorkItem::Video(path, req);
1600 break PrefetchWorkItem::Video(seq, cur_seq, path, req);
14301601 }
14311602 }
14321603 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) {
14341605 q.queued_raster_keys.remove(&job.cache_key);
1435 break PrefetchWorkItem::Raster(job);
1606 break PrefetchWorkItem::Raster(seq, cur_seq, job);
14361607 }
14371608 }
14381609 }
14391610 };
14401611
14411612 match item {
1442 PrefetchWorkItem::Raster(job) => {
1613 PrefetchWorkItem::Raster(item_seq, cur_seq, job) => {
14431614 let cache_gen_opt = shared.state.lock().ok().and_then(|mut state| {
14441615 if state.images.contains_key(&job.cache_key)
14451616 || state.in_flight.contains(&job.cache_key)
......@@ -1447,6 +1618,7 @@ impl MediaPrefetchHandle {
14471618 None
14481619 } else {
14491620 state.in_flight.insert(job.cache_key.clone());
1621 shared.sync_lookahead_throttle(&state);
14501622 Some(state.generation)
14511623 }
14521624 });
......@@ -1456,9 +1628,16 @@ impl MediaPrefetchHandle {
14561628 key: Some(job.cache_key.clone()),
14571629 };
14581630 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 );
14601639 }
1461 PrefetchWorkItem::Video(path, req) => {
1640 PrefetchWorkItem::Video(item_seq, cur_seq, path, req) => {
14621641 struct ActiveVideoGuard<'a> {
14631642 queue: &'a PrefetchQueue,
14641643 path: PathBuf,
......@@ -1467,9 +1646,7 @@ impl MediaPrefetchHandle {
14671646 fn drop(&mut self) {
14681647 if let Ok(mut q) = self.queue.state.lock() {
14691648 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();
14731650 }
14741651 }
14751652 }
......@@ -1494,6 +1671,7 @@ impl MediaPrefetchHandle {
14941671 None
14951672 } else {
14961673 state.in_flight.insert(key.clone());
1674 shared.sync_lookahead_throttle(&state);
14971675 Some(state.generation)
14981676 }
14991677 });
......@@ -1516,13 +1694,24 @@ impl MediaPrefetchHandle {
15161694 rgba_f16: None,
15171695 rgba_f32: None,
15181696 };
1519 if let Ok(mut state) = shared.state.lock() {
1697 let unthrottled = if let Ok(mut state) = shared.state.lock() {
15201698 state.in_flight.remove(&key);
15211699 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 };
15251708 shared.cv.notify_all();
1709 unthrottled
1710 } else {
1711 false
1712 };
1713 if unthrottled {
1714 shared.notify_prefetch_waiters();
15261715 }
15271716 }
15281717 }
......@@ -2040,7 +2229,7 @@ struct PreloadJob {
20402229}
20412230
20422231#[cfg(not(target_arch = "wasm32"))]
2043fn decode_job(job: &PreloadJob, allow_parallel_premult: bool) -> Option<DecodedImage> {
2232fn decode_job(job: &PreloadJob, allow_parallel: bool) -> Option<DecodedImage> {
20442233 if job.is_exr {
20452234 decode_exr_rgba(
20462235 &job.cache_key.path,
......@@ -2049,12 +2238,13 @@ fn decode_job(job: &PreloadJob, allow_parallel_premult: bool) -> Option<DecodedI
20492238 job.cache_key.exr_channels[2].as_deref(),
20502239 job.cache_key.exr_channels[3].as_deref(),
20512240 false,
2241 allow_parallel,
20522242 )
20532243 } else {
20542244 decode_raster_image(
20552245 &job.cache_key.path,
20562246 job.cache_key.post_multiply,
2057 allow_parallel_premult,
2247 allow_parallel,
20582248 )
20592249 }
20602250}
......@@ -3261,4 +3451,117 @@ mod tests {
32613451 handle.cancel();
32623452 let _ = std::fs::remove_dir_all(&dir);
32633453 }
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 }
32643567}
crates/engine/src/media/exr.rs+68-50
......@@ -186,14 +186,16 @@ pub(super) fn decode_exr_rgba(
186186 blue_name: Option<&str>,
187187 alpha_name: Option<&str>,
188188 post_multiply: bool,
189 allow_parallel: bool,
189190) -> Option<DecodedImage> {
190191 let names = [red_name, green_name, blue_name, alpha_name];
191192 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),
193194 None => decode_exr_from(
194195 std::io::BufReader::with_capacity(256 * 1024, std::fs::File::open(path).ok()?),
195196 names,
196197 post_multiply,
198 allow_parallel,
197199 ),
198200 }
199201}
......@@ -256,12 +258,13 @@ fn convert_exr_rgba_buffers(
256258 has_b: bool,
257259 has_a: bool,
258260 post_multiply: bool,
261 allow_parallel: bool,
259262) {
260263 #[cfg(not(target_arch = "wasm32"))]
261264 {
262265 const PARALLEL_THRESHOLD_PIXELS: usize = 512 * 512;
263266 let total_px = raw_f32.len() / 4;
264 if total_px >= PARALLEL_THRESHOLD_PIXELS {
267 if allow_parallel && total_px >= PARALLEL_THRESHOLD_PIXELS {
265268 let workers = std::thread::available_parallelism()
266269 .map(|n| n.get().clamp(2, 12))
267270 .unwrap_or(4)
......@@ -289,6 +292,8 @@ fn convert_exr_rgba_buffers(
289292 return;
290293 }
291294 }
295 #[cfg(target_arch = "wasm32")]
296 let _ = allow_parallel;
292297 convert_exr_rgba_slice(
293298 raw_f32,
294299 raw_f16,
......@@ -304,8 +309,11 @@ fn decode_exr_from<R: std::io::Read + std::io::Seek + Send>(
304309 reader: R,
305310 [red_name, green_name, blue_name, alpha_name]: [Option<&str>; 4],
306311 post_multiply: bool,
312 allow_parallel: bool,
307313) -> Option<DecodedImage> {
308314 use ::exr::block::reader::ChunksReader;
315 use ::exr::block::UncompressedBlock;
316 use ::exr::error::UnitResult;
309317 use ::exr::meta::attribute::SampleType;
310318 use ::exr::prelude::*;
311319
......@@ -332,63 +340,67 @@ fn decode_exr_from<R: std::io::Read + std::io::Seek + Send>(
332340 let mut line_f16 = Vec::<f16>::new();
333341 let mut line_u32 = Vec::<u32>::new();
334342
335 chunks_reader
343 let filtered = chunks_reader
336344 .filter_chunks(false, |_, tile, block| {
337345 tile.is_largest_resolution_level() && needed_layers.contains(&block.layer)
338346 })
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;
349356 }
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)?;
352373 }
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()));
358378 }
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));
376383 }
384 }
377385
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;
386393 }
387394 }
388395 }
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 }
392404
393405 let mut raw = vec![0u8; w * h * 4];
394406 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>(
400412 b_loc.is_some(),
401413 a_loc.is_some(),
402414 post_multiply,
415 allow_parallel,
403416 );
404417 Some(DecodedImage {
405418 size: [w as u32, h as u32],
......@@ -421,9 +434,12 @@ mod tests {
421434 image::DynamicImage::ImageRgba32F(pixels).write_to(&mut out, image::ImageFormat::OpenExr).unwrap();
422435 assert!(MediaCache::insert_virtual_bytes("vexr_drop/frame.exr", out.into_inner()));
423436
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();
425438 assert_eq!(decoded.size, [2, 1]);
426439 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]);
427443 }
428444
429445 #[test]
......@@ -469,12 +485,13 @@ mod tests {
469485 has_b,
470486 has_a,
471487 post_multiply,
488 true,
472489 );
473490
474491 let mut seq_f32 = base.clone();
475492 let mut seq_f16 = vec![0u16; pixels * 4];
476493 let mut seq_u8 = vec![0u8; pixels * 4];
477 convert_exr_rgba_slice(
494 convert_exr_rgba_buffers(
478495 &mut seq_f32,
479496 &mut seq_f16,
480497 &mut seq_u8,
......@@ -482,6 +499,7 @@ mod tests {
482499 has_b,
483500 has_a,
484501 post_multiply,
502 false,
485503 );
486504
487505 assert_eq!(par_f16, seq_f16, "f16 mismatch for ({has_g},{has_b},{has_a},{post_multiply})");