diff --git a/crates/engine/src/av_decode.m b/crates/engine/src/av_decode.m index 4021863e72c5ffd1d633ca596f88b6e84d4caf64..9cbbf3e1b5083df301dd205d79f110fdba8ba1ab 100644 --- a/crates/engine/src/av_decode.m +++ b/crates/engine/src/av_decode.m @@ -431,14 +431,17 @@ AvVideoDecoder *av_video_open( static CMSampleBufferRef read_target_sample( AvVideoDecoderObj *obj, double targetPts, - double halfFrame + double halfFrame, + BOOL *outHitEof ) { CMSampleBufferRef chosen = NULL; CMSampleBufferRef lastSeen = NULL; + BOOL hitEof = NO; while (obj.reader.status == AVAssetReaderStatusReading) { CMSampleBufferRef sb = [obj.output copyNextSampleBuffer]; if (!sb) { + hitEof = (obj.reader.status == AVAssetReaderStatusCompleted); break; } CMTime ptsTime = CMSampleBufferGetPresentationTimeStamp(sb); @@ -457,10 +460,14 @@ static CMSampleBufferRef read_target_sample( if (!chosen && lastSeen) { chosen = lastSeen; lastSeen = NULL; + hitEof = YES; } if (lastSeen) { CFRelease(lastSeen); } + if (outHitEof) { + *outHitEof = hitEof || (obj.reader.status == AVAssetReaderStatusCompleted); + } return chosen; } @@ -493,6 +500,7 @@ int av_video_decode_frame( (obj.lastFrameIdx >= 0 && frame_idx > obj.lastFrameIdx && frame_idx <= obj.lastFrameIdx + 8)); + int64_t prevLastFrameIdx = obj.lastFrameIdx; double seekSec = 0.0; if (!canAdvance) { seekSec = (frame_idx == 0) ? 0.0 : fmax(0.0, targetPts - (1.5 / fps)); @@ -501,15 +509,28 @@ int av_video_decode_frame( } } - CMSampleBufferRef chosen = read_target_sample(obj, targetPts, halfFrame); + BOOL hitEof = NO; + CMSampleBufferRef chosen = read_target_sample(obj, targetPts, halfFrame, &hitEof); - // If requesting a frame slightly past EOF (e.g., llround(durSec * fps) rounding up by 1), - // retry once from slightly before end if we didn't hit a sample, or hold the last valid frame. - if (!chosen && !canAdvance && frame_idx > 0) { + // If requesting a frame past EOF (including sequential advance stepping past EOF or + // container duration overestimating the last video sample by > 4 frames), retry from + // endAnchor - 1.0 and, if that still misses, from the last known decoded frame timestamp. + if (!chosen && !obj.hasLastFrame && frame_idx > 0) { double endAnchor = obj.durSec > 0.0 ? fmin(targetPts, obj.trackStartSec + obj.durSec) : targetPts; double fallbackSec = fmax(0.0, endAnchor - 1.0); - if (fallbackSec < seekSec - 0.05 && [obj openReaderAtSeconds:fallbackSec]) { - chosen = read_target_sample(obj, targetPts, halfFrame); + if ((canAdvance || fallbackSec < seekSec - 0.05) && [obj openReaderAtSeconds:fallbackSec]) { + chosen = read_target_sample(obj, targetPts, halfFrame, &hitEof); + } + if (!chosen) { + double lastIdxSec = fmax( + 0.0, + prevLastFrameIdx >= 0 + ? obj.trackStartSec + (double)prevLastFrameIdx / fps - 0.1 + : 0.0 + ); + if ([obj openReaderAtSeconds:lastIdxSec]) { + chosen = read_target_sample(obj, targetPts, halfFrame, &hitEof); + } } } @@ -530,7 +551,7 @@ int av_video_decode_frame( CFRelease(chosen); if (ok) { - if (obj.nbFrames <= 0 || frame_idx >= obj.nbFrames - 4) { + if (hitEof || obj.nbFrames <= 0 || frame_idx >= obj.nbFrames - 4) { if (!obj.lastFrameRgba || obj.lastFrameRgba.length < required) { obj.lastFrameRgba = [NSMutableData dataWithLength:required]; } diff --git a/crates/engine/src/cryptomatte.rs b/crates/engine/src/cryptomatte.rs index 9efed30bb0b9de85219a2d27fe97d5515410798e..15463625d6fd55eedaa53163db86c2aab9413ef6 100644 --- a/crates/engine/src/cryptomatte.rs +++ b/crates/engine/src/cryptomatte.rs @@ -392,19 +392,23 @@ fn parse_hex_literal_token(token: &str) -> Option { #[cfg(not(target_arch = "wasm32"))] const CRYPTO_PARALLEL_THRESHOLD_PIXELS: usize = 512 * 512; -fn accumulate_cryptomatte_chunk( +#[inline] +fn accumulate_chunk_with bool>( out: &mut [f32], start: usize, pairs: &[(&[f32], &[f32])], - target_ids: &HashSet, + contains_id: F, ) { let len = out.len(); for &(ids, covs) in pairs { let ids_slice = &ids[start..start + len]; let covs_slice = &covs[start..start + len]; for i in 0..len { - if target_ids.contains(&ids_slice[i].to_bits()) { - out[i] += covs_slice[i]; + if contains_id(ids_slice[i].to_bits()) { + let cov = covs_slice[i]; + if cov.is_finite() { + out[i] += cov; + } } } } @@ -413,6 +417,26 @@ fn accumulate_cryptomatte_chunk( } } +fn accumulate_cryptomatte_chunk( + out: &mut [f32], + start: usize, + pairs: &[(&[f32], &[f32])], + target_ids: &HashSet, +) { + if target_ids.len() <= 8 { + let mut stack_ids = [0u32; 8]; + let mut count = 0usize; + for &id in target_ids { + stack_ids[count] = id; + count += 1; + } + let ids_slice = &stack_ids[..count]; + accumulate_chunk_with(out, start, pairs, |bits| ids_slice.contains(&bits)); + } else { + accumulate_chunk_with(out, start, pairs, |bits| target_ids.contains(&bits)); + } +} + fn accumulate_cryptomatte_scalar( pairs: &[(&[f32], &[f32])], target_ids: &HashSet, @@ -499,8 +523,8 @@ pub fn list_cryptomatte_layers(exr_path: &Path) -> Vec { /// Extracts a Cryptomatte coverage matte from a multi-channel OpenEXR file. /// -/// - Reads all flat layers and custom header `other` attributes via -/// `exr::prelude::read_all_flat_layers_from_file`. +/// - Reads header metadata first and selectively decompresses only the layers containing +/// matched Cryptomatte rank channels via `exr::block::read` + `filter_chunks`. /// - Resolves `cryptomatte//name`, `cryptomatte//manifest`, and sidecar /// `cryptomatte//manif_file` relative to `exr_path.parent()`. /// - Matches `layer_name` by exact name, suffix (e.g. `"CryptoObject"` -> `"ViewLayer.CryptoObject"`), @@ -512,15 +536,19 @@ pub fn extract_cryptomatte( layer_name: Option<&str>, matte_list: &str, ) -> Option { + use exr::block::reader::ChunksReader; + use exr::meta::attribute::SampleType; use exr::prelude::*; - let img = read_all_flat_layers_from_file(exr_path).ok()?; + let file = std::fs::File::open(exr_path).ok()?; + let reader = std::io::BufReader::with_capacity(256 * 1024, file); + let chunks_reader = exr::block::read(reader, false).ok()?; - // 1. Collect Cryptomatte header metadata from image-level and layer-level `other` attributes. + // 1. Collect Cryptomatte header metadata from shared and layer-level `other` attributes. let mut crypto_meta: BTreeMap = BTreeMap::new(); - collect_crypto_metadata_from_map(&img.attributes.other, &mut crypto_meta); - for layer in &img.layer_data { - collect_crypto_metadata_from_map(&layer.attributes.other, &mut crypto_meta); + for header in chunks_reader.headers() { + collect_crypto_metadata_from_map(&header.shared_attributes.other, &mut crypto_meta); + collect_crypto_metadata_from_map(&header.own_attributes.other, &mut crypto_meta); } // 2. Select target Cryptomatte layer and manifest. @@ -545,11 +573,14 @@ pub fn extract_cryptomatte( } else if let Some(req) = req_layer { req.to_string() } else { - // Fallback: infer first rank-00 prefix from channels. + // Fallback: infer first rank-00 prefix from headers. let mut inferred = None; - 'outer: for layer in &img.layer_data { - let lname = layer.attributes.layer_name.as_ref().map(|t| t.to_string()); - for ch in &layer.channel_data.list { + 'outer: for header in chunks_reader.headers() { + if header.deep { + continue; + } + let lname = header.own_attributes.layer_name.as_ref().map(|t| t.to_string()); + for ch in &header.channels.list { let full = full_channel_name(lname.as_deref(), &ch.name.to_string()); if let Some((prefix, 0, 0)) = split_crypto_rank_channel(&full) { inferred = Some(prefix.to_string()); @@ -601,18 +632,26 @@ pub fn extract_cryptomatte( target_ids.insert(crypto_hash_to_float(direct_hash).to_bits()); } - // 4. Gather rank channel groups (00 .. 09) across all flat layers. + // 4. Identify matching rank channel groups (00 .. 09) from headers first. let mut dims: Option<(usize, usize)> = None; - let mut ranks: BTreeMap>; 4]> = BTreeMap::new(); + let mut seen_slots = [[false; 4]; 10]; + let mut matched_channels: Vec<((usize, usize), u8, usize)> = Vec::new(); + let mut needed_layers: Vec = Vec::new(); - for layer in &img.layer_data { - let lw = layer.size.width(); - let lh = layer.size.height(); + for (li, header) in chunks_reader.headers().iter().enumerate() { + if header.deep { + continue; + } + let lw = header.layer_size.width(); + let lh = header.layer_size.height(); if lw == 0 || lh == 0 { continue; } - let lname = layer.attributes.layer_name.as_ref().map(|t| t.to_string()); - for ch in &layer.channel_data.list { + let lname = header.own_attributes.layer_name.as_ref().map(|t| t.to_string()); + for (ci, ch) in header.channels.list.iter().enumerate() { + if ch.sampling != Vec2(1, 1) { + continue; + } let full = full_channel_name(lname.as_deref(), &ch.name.to_string()); let Some((prefix, rank, comp_idx)) = split_crypto_rank_channel(&full) else { continue; @@ -627,12 +666,13 @@ pub fn extract_cryptomatte( } else { dims = Some((lw, lh)); } - let vals: Vec = ch.sample_data.values_as_f32().collect(); - if vals.len() == lw * lh { - let slots = ranks.entry(rank).or_insert_with(|| [None, None, None, None]); - if slots[comp_idx].is_none() { - slots[comp_idx] = Some(vals); - } + if seen_slots[rank as usize][comp_idx] { + continue; + } + seen_slots[rank as usize][comp_idx] = true; + matched_channels.push(((li, ci), rank, comp_idx)); + if !needed_layers.contains(&li) { + needed_layers.push(li); } } } @@ -646,14 +686,75 @@ pub fn extract_cryptomatte( }); } + let mut slot_buffers: Vec<(u8, usize, Vec)> = Vec::with_capacity(matched_channels.len()); + let mut loc_to_slot: HashMap<(usize, usize), usize> = + HashMap::with_capacity(matched_channels.len()); + for (loc, rank, comp_idx) in matched_channels { + let idx = slot_buffers.len(); + slot_buffers.push((rank, comp_idx, vec![0.0_f32; pixel_count])); + loc_to_slot.insert(loc, idx); + } + + let mut line_f16 = Vec::::new(); + let mut line_u32 = Vec::::new(); + chunks_reader + .filter_chunks(false, |_, tile, block| { + tile.is_largest_resolution_level() && needed_layers.contains(&block.layer) + }) + .ok()? + .decompress_parallel(false, |meta, block| { + let header = &meta.headers[block.index.layer]; + for line in block.lines(&header.channels) { + let Some(&slot_idx) = + loc_to_slot.get(&(line.location.layer, line.location.channel)) + else { + continue; + }; + let y = line.location.position.y(); + let x0 = line.location.position.x(); + let len = line.location.sample_count; + if y >= h || x0 + len > w { + continue; + } + let row_base = y * w + x0; + let dst = &mut slot_buffers[slot_idx].2[row_base..row_base + len]; + match header.channels.list[line.location.channel].sample_type { + SampleType::F32 => { + line.read_samples_into_slice(dst)?; + } + SampleType::F16 => { + line_f16.resize(len, f16::ZERO); + line.read_samples_into_slice(&mut line_f16)?; + for (d, &s) in dst.iter_mut().zip(line_f16.iter()) { + *d = s.to_f32(); + } + } + SampleType::U32 => { + line_u32.resize(len, 0); + line.read_samples_into_slice(&mut line_u32)?; + for (d, &s) in dst.iter_mut().zip(line_u32.iter()) { + *d = s as f32; + } + } + } + } + Ok(()) + }) + .ok()?; + // 5. Accumulate coverage across all rank (ID, coverage) pairs. + let mut ranks: BTreeMap; 4]> = BTreeMap::new(); + for (rank, comp_idx, buf) in &slot_buffers { + let slots = ranks.entry(*rank).or_insert([None, None, None, None]); + slots[*comp_idx] = Some(buf.as_slice()); + } let mut pairs: Vec<(&[f32], &[f32])> = Vec::with_capacity(ranks.len() * 2); for slots in ranks.values() { - if let (Some(ids), Some(covs)) = (&slots[0], &slots[1]) { - pairs.push((ids.as_slice(), covs.as_slice())); + if let (Some(ids), Some(covs)) = (slots[0], slots[1]) { + pairs.push((ids, covs)); } - if let (Some(ids), Some(covs)) = (&slots[2], &slots[3]) { - pairs.push((ids.as_slice(), covs.as_slice())); + if let (Some(ids), Some(covs)) = (slots[2], slots[3]) { + pairs.push((ids, covs)); } } let matte = accumulate_cryptomatte_matte(&pairs, &target_ids, pixel_count); @@ -987,4 +1088,118 @@ mod tests { ); } } + + #[test] + fn secondary_rank_nan_and_inf_do_not_poison_rank0_and_selective_load_matches() { + use exr::prelude::*; + + let hero_id = crypto_hash_to_float(murmur3_32(b"Hero", 0)); + let prop_id = crypto_hash_to_float(murmur3_32(b"Prop", 0)); + let target_ids: HashSet = [hero_id.to_bits(), prop_id.to_bits()].into_iter().collect(); + + // Pixel 0: valid rank-0 (0.65) + NaN in rank-1 -> must preserve 0.65 (not wipe to 0.0). + // Pixel 1: NaN in rank-0 + valid rank-1 (0.4) -> must preserve 0.4. + // Pixel 2: valid rank-0 (0.3) + -Inf in rank-1 -> must preserve 0.3. + // Pixel 3: valid rank-0 (0.25) + +Inf in rank-1 -> non-finite skipped, preserves 0.25. + let id0 = [hero_id, hero_id, hero_id, hero_id]; + let cov0 = [0.65_f32, f32::NAN, 0.3_f32, 0.25_f32]; + let id1 = [hero_id, prop_id, hero_id, prop_id]; + let cov1 = [f32::NAN, 0.4_f32, f32::NEG_INFINITY, f32::INFINITY]; + let pairs: Vec<(&[f32], &[f32])> = vec![(&id0, &cov0), (&id1, &cov1)]; + + let matte = accumulate_cryptomatte_scalar(&pairs, &target_ids, 4); + assert_eq!(matte[0].to_bits(), 0.65_f32.to_bits()); + assert_eq!(matte[1].to_bits(), 0.4_f32.to_bits()); + assert_eq!(matte[2].to_bits(), 0.3_f32.to_bits()); + assert_eq!(matte[3].to_bits(), 0.25_f32.to_bits()); + + // Large-set (>8 IDs) HashSet path must match small-set (<=8 IDs) stack linear scan. + let mut large_ids = target_ids.clone(); + for extra in 0..10u32 { + large_ids.insert(crypto_hash_to_float(murmur3_32(&extra.to_le_bytes(), 0)).to_bits()); + } + let matte_large = accumulate_cryptomatte_scalar(&pairs, &large_ids, 4); + assert_eq!( + matte.iter().map(|v| v.to_bits()).collect::>(), + matte_large.iter().map(|v| v.to_bits()).collect::>() + ); + + // Multi-part EXR with separate Beauty layer and ViewLayer.CryptoObject layer: + // selective filter_chunks must skip Beauty and decode CryptoObject bit-for-bit. + let w = 4usize; + let h = 2usize; + let n = w * h; + let hero_hash = murmur3_32(b"Hero", 0); + let tree_hash = murmur3_32(b"Tree", 0); + let tree_id = crypto_hash_to_float(tree_hash); + + let beauty_layer = Layer::new( + (w, h), + LayerAttributes::named("Beauty"), + Encoding::FAST_LOSSLESS, + AnyChannels::sort(SmallVec::from_vec(vec![ + AnyChannel::new("R", FlatSamples::F32(vec![1.0; n])), + AnyChannel::new("G", FlatSamples::F32(vec![0.5; n])), + AnyChannel::new("B", FlatSamples::F32(vec![0.25; n])), + ])), + ); + + let mut c00_r = vec![0.0_f32; n]; + let mut c00_g = vec![0.0_f32; n]; + let mut c00_b = vec![0.0_f32; n]; + let mut c00_a = vec![0.0_f32; n]; + c00_r[0] = hero_id; + c00_g[0] = 0.7; + c00_b[0] = tree_id; + c00_a[0] = 0.3; + c00_r[1] = hero_id; + c00_g[1] = 1.0; + + let manifest_json = format!( + r#"{{"Hero":"{:08x}","Tree":"{:08x}"}}"#, + hero_hash, tree_hash + ); + let mut crypto_attrs = LayerAttributes::named("ViewLayer.CryptoObject00"); + crypto_attrs.other.insert( + Text::new_or_panic("cryptomatte/abcdef0/name"), + AttributeValue::Text(Text::new_or_panic("ViewLayer.CryptoObject")), + ); + crypto_attrs.other.insert( + Text::new_or_panic("cryptomatte/abcdef0/manifest"), + AttributeValue::Text(Text::new_or_panic(&manifest_json)), + ); + let crypto_layer = Layer::new( + (w, h), + crypto_attrs, + Encoding::FAST_LOSSLESS, + AnyChannels::sort(SmallVec::from_vec(vec![ + AnyChannel::new("R", FlatSamples::F32(c00_r)), + AnyChannel::new("G", FlatSamples::F32(c00_g)), + AnyChannel::new("B", FlatSamples::F32(c00_b)), + AnyChannel::new("A", FlatSamples::F32(c00_a)), + ])), + ); + + let image = Image::from_layers( + ImageAttributes::with_size((w, h)), + SmallVec::from_vec(vec![beauty_layer, crypto_layer]), + ); + let tmp_path = std::env::temp_dir().join(format!( + "engine_test_selective_crypto_{}.exr", + std::process::id() + )); + image + .write() + .to_file(&tmp_path) + .expect("failed to write multi-part EXR"); + + let res = extract_cryptomatte(&tmp_path, Some("CryptoObject"), "\"Hero\"") + .expect("selective extract_cryptomatte failed"); + assert_eq!(res.size, [w as u32, h as u32]); + assert_eq!(res.matte[0].to_bits(), 0.7_f32.to_bits()); + assert_eq!(res.matte[1].to_bits(), 1.0_f32.to_bits()); + assert_eq!(res.matte[2].to_bits(), 0.0_f32.to_bits()); + + let _ = std::fs::remove_file(&tmp_path); + } } diff --git a/crates/engine/src/media.rs b/crates/engine/src/media.rs index 754b5e753c8411d53ac8b353dc00195c5bb72ecf..482eb70e149083d307a0cf5bd6cd05d28d37aa68 100644 --- a/crates/engine/src/media.rs +++ b/crates/engine/src/media.rs @@ -28,7 +28,7 @@ use std::process::Command; #[cfg(not(target_arch = "wasm32"))] use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; #[cfg(not(target_arch = "wasm32"))] -use std::sync::{Condvar, mpsc}; +use std::sync::{Condvar, Weak, mpsc}; use std::sync::{Arc, Mutex, RwLock}; #[derive(Clone)] @@ -214,6 +214,14 @@ struct MediaState { opening_videos: HashSet, #[cfg(not(target_arch = "wasm32"))] known_existing_paths: HashSet, + #[cfg(not(target_arch = "wasm32"))] + speculative_bytes_since_seq: u64, + #[cfg(not(target_arch = "wasm32"))] + speculative_count_since_seq: u64, + #[cfg(not(target_arch = "wasm32"))] + last_speculative_bytes: u64, + #[cfg(not(target_arch = "wasm32"))] + last_prefetch_seq: Option, } impl MediaState { @@ -232,6 +240,14 @@ impl MediaState { opening_videos: HashSet::new(), #[cfg(not(target_arch = "wasm32"))] known_existing_paths: HashSet::new(), + #[cfg(not(target_arch = "wasm32"))] + speculative_bytes_since_seq: 0, + #[cfg(not(target_arch = "wasm32"))] + speculative_count_since_seq: 0, + #[cfg(not(target_arch = "wasm32"))] + last_speculative_bytes: 0, + #[cfg(not(target_arch = "wasm32"))] + last_prefetch_seq: None, } } @@ -255,8 +271,34 @@ impl MediaState { } #[cfg(not(target_arch = "wasm32"))] - fn is_over_soft_budget(&self) -> bool { - self.budget_bytes > 0 && self.total_bytes >= (self.budget_bytes * 3) / 4 + fn record_speculative_decode(&mut self, bytes: u64) { + self.speculative_bytes_since_seq = self.speculative_bytes_since_seq.saturating_add(bytes); + self.speculative_count_since_seq = self.speculative_count_since_seq.saturating_add(1); + self.last_speculative_bytes = bytes; + } + + #[cfg(not(target_arch = "wasm32"))] + fn reset_speculative_window(&mut self, seq_idx: usize) { + if self.last_prefetch_seq != Some(seq_idx) { + self.last_prefetch_seq = Some(seq_idx); + self.speculative_bytes_since_seq = 0; + self.speculative_count_since_seq = 0; + } + } + + #[cfg(not(target_arch = "wasm32"))] + fn should_throttle_lookahead(&self) -> bool { + const MIN_LOOKAHEAD_BUDGET_BYTES: u64 = 64 * 1024 * 1024; + if self.budget_bytes < MIN_LOOKAHEAD_BUDGET_BYTES { + return true; + } + let avg_item_bytes = if self.speculative_count_since_seq > 0 { + self.speculative_bytes_since_seq / self.speculative_count_since_seq + } else { + self.last_speculative_bytes + }; + let in_flight_est = (self.in_flight.len() as u64).saturating_mul(avg_item_bytes); + self.speculative_bytes_since_seq.saturating_add(in_flight_est) >= self.budget_bytes / 2 } fn insert_cached(&mut self, cache_key: ImageCacheKey, decoded: DecodedImage) { @@ -320,26 +362,70 @@ struct MediaShared { #[cfg(not(target_arch = "wasm32"))] cv: Condvar, #[cfg(not(target_arch = "wasm32"))] - soft_budget_exceeded: AtomicBool, + lookahead_throttled: AtomicBool, + #[cfg(not(target_arch = "wasm32"))] + prefetch_queues: Mutex>>, } impl MediaShared { fn new(budget_bytes: u64) -> Self { + let initial_state = MediaState::new(budget_bytes); + #[cfg(not(target_arch = "wasm32"))] + let initial_throttle = initial_state.should_throttle_lookahead(); Self { - state: Mutex::new(MediaState::new(budget_bytes)), + state: Mutex::new(initial_state), #[cfg(not(target_arch = "wasm32"))] cv: Condvar::new(), #[cfg(not(target_arch = "wasm32"))] - soft_budget_exceeded: AtomicBool::new(false), + lookahead_throttled: AtomicBool::new(initial_throttle), + #[cfg(not(target_arch = "wasm32"))] + prefetch_queues: Mutex::new(Vec::new()), } } - fn sync_soft_budget(&self, state: &MediaState) { + fn sync_lookahead_throttle(&self, state: &MediaState) -> bool { #[cfg(not(target_arch = "wasm32"))] - self.soft_budget_exceeded - .store(state.is_over_soft_budget(), Ordering::Relaxed); + { + let throttled = state.should_throttle_lookahead(); + let was_throttled = self.lookahead_throttled.load(Ordering::Acquire); + self.lookahead_throttled.store(throttled, Ordering::Release); + was_throttled && !throttled + } #[cfg(target_arch = "wasm32")] - let _ = state; + { + let _ = state; + false + } + } + + #[cfg(not(target_arch = "wasm32"))] + fn register_prefetch_queue(&self, queue: &Arc) { + if let Ok(mut queues) = self.prefetch_queues.lock() { + queues.retain(|w| w.strong_count() > 0); + queues.push(Arc::downgrade(queue)); + } + } + + #[cfg(not(target_arch = "wasm32"))] + fn notify_prefetch_waiters(&self) { + let live: Vec> = { + let Ok(mut queues) = self.prefetch_queues.lock() else { return }; + let mut out = Vec::with_capacity(queues.len()); + queues.retain(|w| { + if let Some(q) = w.upgrade() { + out.push(q); + true + } else { + false + } + }); + out + }; + for q in live { + if let Ok(_guard) = q.state.lock() { + q.cv.notify_all(); + } + } } fn insert_cached_locked( @@ -347,9 +433,9 @@ impl MediaShared { state: &mut MediaState, cache_key: ImageCacheKey, decoded: DecodedImage, - ) { + ) -> bool { state.insert_cached(cache_key, decoded); - self.sync_soft_budget(state); + self.sync_lookahead_throttle(state) } fn path_exists_cached(&self, path: &Path) -> bool { @@ -467,9 +553,16 @@ struct InFlightGuard<'a> { impl Drop for InFlightGuard<'_> { fn drop(&mut self) { if let Some(key) = self.key.take() { - if let Ok(mut state) = self.shared.state.lock() { + let unthrottled = if let Ok(mut state) = self.shared.state.lock() { state.in_flight.remove(&key); + let unthrottled = self.shared.sync_lookahead_throttle(&state); self.shared.cv.notify_all(); + unthrottled + } else { + false + }; + if unthrottled { + self.shared.notify_prefetch_waiters(); } } } @@ -672,8 +765,19 @@ impl MediaCache { state.total_bytes = 0; state.generation = state.generation.wrapping_add(1); #[cfg(not(target_arch = "wasm32"))] - state.known_existing_paths.clear(); - self.shared.sync_soft_budget(&state); + { + state.known_existing_paths.clear(); + state.speculative_bytes_since_seq = 0; + state.speculative_count_since_seq = 0; + state.last_speculative_bytes = 0; + state.last_prefetch_seq = None; + } + self.shared.sync_lookahead_throttle(&state); + } + #[cfg(not(target_arch = "wasm32"))] + { + self.shared.cv.notify_all(); + self.shared.notify_prefetch_waiters(); } drop(cleared_decoders); #[cfg(not(target_arch = "wasm32"))] @@ -715,18 +819,25 @@ impl MediaCache { } pub fn set_budget_mb(&mut self, budget_mb: u64) { - let Ok(mut state) = self.shared.state.lock() else { return }; - state.budget_bytes = budget_mb.saturating_mul(1024 * 1024); - while state.total_bytes > state.budget_bytes && state.images.len() > 1 { - let Some((oldest_key, _)) = state.lru.iter().min_by_key(|(_, t)| **t).map(|(k, t)| (k.clone(), *t)) else { - break; - }; - state.lru.remove(&oldest_key); - if let Some(removed) = state.images.remove(&oldest_key) { - state.total_bytes = state.total_bytes.saturating_sub(removed.byte_size()); + { + let Ok(mut state) = self.shared.state.lock() else { return }; + state.budget_bytes = budget_mb.saturating_mul(1024 * 1024); + while state.total_bytes > state.budget_bytes && state.images.len() > 1 { + let Some((oldest_key, _)) = state.lru.iter().min_by_key(|(_, t)| **t).map(|(k, t)| (k.clone(), *t)) else { + break; + }; + state.lru.remove(&oldest_key); + if let Some(removed) = state.images.remove(&oldest_key) { + state.total_bytes = state.total_bytes.saturating_sub(removed.byte_size()); + } } + self.shared.sync_lookahead_throttle(&state); + } + #[cfg(not(target_arch = "wasm32"))] + { + self.shared.cv.notify_all(); + self.shared.notify_prefetch_waiters(); } - self.shared.sync_soft_budget(&state); } pub fn entry_count(&self) -> usize { @@ -787,7 +898,10 @@ impl MediaCache { continue; } #[cfg(not(target_arch = "wasm32"))] - state.in_flight.insert(cache_key.clone()); + { + state.in_flight.insert(cache_key.clone()); + self.shared.sync_lookahead_throttle(&state); + } break state.generation; } }; @@ -812,19 +926,30 @@ impl MediaCache { rgba_f32: None, }; - if let Ok(mut state) = self.shared.state.lock() { + let unthrottled = if let Ok(mut state) = self.shared.state.lock() { #[cfg(not(target_arch = "wasm32"))] { state.in_flight.remove(&cache_key); in_flight_guard.key = None; } - if state.generation == cache_gen { + let unthrottled = if state.generation == cache_gen { self.shared - .insert_cached_locked(&mut state, cache_key, decoded.clone()); - } + .insert_cached_locked(&mut state, cache_key, decoded.clone()) + } else { + self.shared.sync_lookahead_throttle(&state) + }; #[cfg(not(target_arch = "wasm32"))] self.shared.cv.notify_all(); + unthrottled + } else { + false + }; + #[cfg(not(target_arch = "wasm32"))] + if unthrottled { + self.shared.notify_prefetch_waiters(); } + #[cfg(target_arch = "wasm32")] + let _ = unthrottled; return Some((base_buf, idx, decoded, true)); } @@ -862,7 +987,10 @@ impl MediaCache { continue; } #[cfg(not(target_arch = "wasm32"))] - state.in_flight.insert(cache_key.clone()); + { + state.in_flight.insert(cache_key.clone()); + self.shared.sync_lookahead_throttle(&state); + } break state.generation; } }; @@ -885,6 +1013,7 @@ impl MediaCache { exr_channels[2], exr_channels[3], false, + true, ) } else { decode_raster_image(&resolved, post_multiply, true) @@ -896,20 +1025,31 @@ impl MediaCache { return None; }; - if let Ok(mut state) = self.shared.state.lock() { + let unthrottled = if let Ok(mut state) = self.shared.state.lock() { #[cfg(not(target_arch = "wasm32"))] { state.in_flight.remove(&cache_key); in_flight_guard.key = None; } - if state.generation == cache_gen { + let unthrottled = if state.generation == cache_gen { state.record_existing_path(&resolved); self.shared - .insert_cached_locked(&mut state, cache_key, decoded.clone()); - } + .insert_cached_locked(&mut state, cache_key, decoded.clone()) + } else { + self.shared.sync_lookahead_throttle(&state) + }; #[cfg(not(target_arch = "wasm32"))] self.shared.cv.notify_all(); + unthrottled + } else { + false + }; + #[cfg(not(target_arch = "wasm32"))] + if unthrottled { + self.shared.notify_prefetch_waiters(); } + #[cfg(target_arch = "wasm32")] + let _ = unthrottled; Some((resolved, -1, decoded, true)) } @@ -1016,6 +1156,7 @@ impl MediaCache { return; } state.in_flight.insert(job.cache_key.clone()); + self.shared.sync_lookahead_throttle(&state); state.generation }; let mut guard = InFlightGuard { @@ -1023,7 +1164,7 @@ impl MediaCache { key: Some(job.cache_key.clone()), }; let decoded = decode_job(&job, true); - finish_raster_job(&self.shared, job.cache_key, cache_gen, &mut guard, decoded); + finish_raster_job(&self.shared, job.cache_key, cache_gen, &mut guard, decoded, false); return; } self.decode_jobs_parallel(jobs); @@ -1093,6 +1234,7 @@ impl MediaCache { None } else { state.in_flight.insert(key.clone()); + self.shared.sync_lookahead_throttle(&state); Some(state.generation) } }); @@ -1115,14 +1257,22 @@ impl MediaCache { rgba_f16: None, rgba_f32: None, }; - if let Ok(mut state) = self.shared.state.lock() { + let unthrottled = if let Ok(mut state) = self.shared.state.lock() { state.in_flight.remove(&key); guard.key = None; - if state.generation == cache_gen { + let unthrottled = if state.generation == cache_gen { self.shared - .insert_cached_locked(&mut state, key, decoded); - } + .insert_cached_locked(&mut state, key, decoded) + } else { + self.shared.sync_lookahead_throttle(&state) + }; self.shared.cv.notify_all(); + unthrottled + } else { + false + }; + if unthrottled { + self.shared.notify_prefetch_waiters(); } } } @@ -1138,6 +1288,7 @@ impl MediaCache { None } else { state.in_flight.insert(job.cache_key.clone()); + self.shared.sync_lookahead_throttle(&state); Some(state.generation) } }); @@ -1153,6 +1304,7 @@ impl MediaCache { cache_gen, &mut guard, decoded, + false, ); } }); @@ -1168,19 +1320,32 @@ fn finish_raster_job( cache_gen: u64, guard: &mut InFlightGuard<'_>, decoded: Option, + is_speculative: bool, ) { - if let Ok(mut state) = shared.state.lock() { + let unthrottled = if let Ok(mut state) = shared.state.lock() { state.in_flight.remove(&key); guard.key = None; - if let Some(decoded) = decoded { + let unthrottled = if let Some(decoded) = decoded { if state.generation == cache_gen { state.record_existing_path(&key.path); - shared.insert_cached_locked(&mut state, key, decoded); + if is_speculative { + state.record_speculative_decode(decoded.byte_size()); + } + shared.insert_cached_locked(&mut state, key, decoded) + } else { + shared.sync_lookahead_throttle(&state) } } else { state.evict_existing_path(&key.path); - } + shared.sync_lookahead_throttle(&state) + }; shared.cv.notify_all(); + unthrottled + } else { + false + }; + if unthrottled { + shared.notify_prefetch_waiters(); } } @@ -1225,8 +1390,8 @@ struct PrefetchQueue { #[cfg(not(target_arch = "wasm32"))] enum PrefetchWorkItem { - Raster(PreloadJob), - Video(PathBuf, VideoFrameRequest), + Raster(usize, usize, PreloadJob), + Video(usize, usize, PathBuf, VideoFrameRequest), } /// Cancellable background read-ahead handle returned by [`MediaCache::start_frame_prefetch`]. @@ -1255,6 +1420,7 @@ impl MediaPrefetchHandle { }), cv: Condvar::new(), }); + shared.register_prefetch_queue(&queue); let worker_count = std::thread::available_parallelism() .map(|n| n.get().clamp(2, 12)) .unwrap_or(4); @@ -1275,6 +1441,10 @@ impl MediaPrefetchHandle { /// Updates the active render sequence index so read-ahead stays synchronized with playback/export. pub fn set_current_seq(&self, seq_idx: usize) { + if let Ok(mut state) = self.shared.state.lock() { + state.reset_speculative_window(seq_idx); + self.shared.sync_lookahead_throttle(&state); + } if let Ok(mut q) = self.queue.state.lock() { q.current_seq = seq_idx; q.prune_stale(); @@ -1407,7 +1577,7 @@ impl MediaPrefetchHandle { } if chosen_seq > q.current_seq.saturating_add(1) - && shared.soft_budget_exceeded.load(Ordering::Relaxed) + && shared.lookahead_throttled.load(Ordering::Acquire) { q = match queue.cv.wait(q) { Ok(g) => g, @@ -1416,30 +1586,31 @@ impl MediaPrefetchHandle { continue; } + let cur_seq = q.current_seq; let chosen_video = best_video .filter(|&(_, _, vs)| best_raster.is_none_or(|(_, rs)| vs <= rs)) .map(|(path, v_idx, _)| (path.clone(), v_idx)); if let Some((path, v_idx)) = chosen_video { - if let Some((_, req)) = q.videos.get_mut(&path).and_then(|vq| vq.remove(v_idx)) { + if let Some((seq, req)) = q.videos.get_mut(&path).and_then(|vq| vq.remove(v_idx)) { if q.videos.get(&path).is_some_and(VecDeque::is_empty) { q.videos.remove(&path); } q.active_videos.insert(path.clone()); - break PrefetchWorkItem::Video(path, req); + break PrefetchWorkItem::Video(seq, cur_seq, path, req); } } if let Some((r_idx, _)) = best_raster { - if let Some((_, job)) = q.raster.remove(r_idx) { + if let Some((seq, job)) = q.raster.remove(r_idx) { q.queued_raster_keys.remove(&job.cache_key); - break PrefetchWorkItem::Raster(job); + break PrefetchWorkItem::Raster(seq, cur_seq, job); } } } }; match item { - PrefetchWorkItem::Raster(job) => { + PrefetchWorkItem::Raster(item_seq, cur_seq, job) => { let cache_gen_opt = shared.state.lock().ok().and_then(|mut state| { if state.images.contains_key(&job.cache_key) || state.in_flight.contains(&job.cache_key) @@ -1447,6 +1618,7 @@ impl MediaPrefetchHandle { None } else { state.in_flight.insert(job.cache_key.clone()); + shared.sync_lookahead_throttle(&state); Some(state.generation) } }); @@ -1456,9 +1628,16 @@ impl MediaPrefetchHandle { key: Some(job.cache_key.clone()), }; let decoded = decode_job(&job, false); - finish_raster_job(&shared, job.cache_key, cache_gen, &mut guard, decoded); + finish_raster_job( + &shared, + job.cache_key, + cache_gen, + &mut guard, + decoded, + item_seq > cur_seq, + ); } - PrefetchWorkItem::Video(path, req) => { + PrefetchWorkItem::Video(item_seq, cur_seq, path, req) => { struct ActiveVideoGuard<'a> { queue: &'a PrefetchQueue, path: PathBuf, @@ -1467,9 +1646,7 @@ impl MediaPrefetchHandle { fn drop(&mut self) { if let Ok(mut q) = self.queue.state.lock() { q.active_videos.remove(&self.path); - if q.videos.contains_key(&self.path) || !q.raster.is_empty() { - self.queue.cv.notify_one(); - } + self.queue.cv.notify_all(); } } } @@ -1494,6 +1671,7 @@ impl MediaPrefetchHandle { None } else { state.in_flight.insert(key.clone()); + shared.sync_lookahead_throttle(&state); Some(state.generation) } }); @@ -1516,13 +1694,24 @@ impl MediaPrefetchHandle { rgba_f16: None, rgba_f32: None, }; - if let Ok(mut state) = shared.state.lock() { + let unthrottled = if let Ok(mut state) = shared.state.lock() { state.in_flight.remove(&key); guard.key = None; - if state.generation == cache_gen { - shared.insert_cached_locked(&mut state, key, decoded); - } + let unthrottled = if state.generation == cache_gen { + if item_seq > cur_seq { + state.record_speculative_decode(decoded.byte_size()); + } + shared.insert_cached_locked(&mut state, key, decoded) + } else { + shared.sync_lookahead_throttle(&state) + }; shared.cv.notify_all(); + unthrottled + } else { + false + }; + if unthrottled { + shared.notify_prefetch_waiters(); } } } @@ -2040,7 +2229,7 @@ struct PreloadJob { } #[cfg(not(target_arch = "wasm32"))] -fn decode_job(job: &PreloadJob, allow_parallel_premult: bool) -> Option { +fn decode_job(job: &PreloadJob, allow_parallel: bool) -> Option { if job.is_exr { decode_exr_rgba( &job.cache_key.path, @@ -2049,12 +2238,13 @@ fn decode_job(job: &PreloadJob, allow_parallel_premult: bool) -> Option 48.0, + "cache must be >75% of 64 MiB, got {:.2} MiB", + cache.total_mb() + ); + + let mut handle = cache.start_frame_prefetch(4); + handle.set_current_seq(0); + for seq in 1..=4 { + handle.enqueue_frame(&comp, target, seq, seq as f64, &expr, false); + } + + // All 4 lookahead frames (through current_seq + 4) must be prefetched without collapsing + // to current_seq + 1. + let expected_keys: Vec = (1..=4) + .map(|i| ImageCacheKey { + path: dir.join(format!("seq_{i:04}.png")), + frame_idx: -1, + post_multiply: false, + exr_channels: [None, None, None, None], + }) + .collect(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + loop { + let all_cached = cache + .shared + .state + .lock() + .map(|s| expected_keys.iter().all(|k| s.images.contains_key(k))) + .unwrap_or(false); + if all_cached || std::time::Instant::now() >= deadline { + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + + for i in 1..=4 { + let (_, _, img, from_disk) = cache.load_clip(&clip, i, false, [None; 4]).unwrap(); + assert!( + !from_disk, + "frame {i} (current_seq + {i}) should have been prefetched while >75% warm" + ); + assert_eq!(img.rgba[0], (i as u8) * 40); + } + + handle.cancel(); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/crates/engine/src/media/exr.rs b/crates/engine/src/media/exr.rs index 38149c10f09a6f42a238f66aea6f5cd71a2a93ef..40840d072e927826d139f4cac84079e46cb498fb 100644 --- a/crates/engine/src/media/exr.rs +++ b/crates/engine/src/media/exr.rs @@ -186,14 +186,16 @@ pub(super) fn decode_exr_rgba( blue_name: Option<&str>, alpha_name: Option<&str>, post_multiply: bool, + allow_parallel: bool, ) -> Option { let names = [red_name, green_name, blue_name, alpha_name]; match super::virtual_bytes(path) { - Some(bytes) => decode_exr_from(std::io::Cursor::new(bytes), names, post_multiply), + Some(bytes) => decode_exr_from(std::io::Cursor::new(bytes), names, post_multiply, allow_parallel), None => decode_exr_from( std::io::BufReader::with_capacity(256 * 1024, std::fs::File::open(path).ok()?), names, post_multiply, + allow_parallel, ), } } @@ -256,12 +258,13 @@ fn convert_exr_rgba_buffers( has_b: bool, has_a: bool, post_multiply: bool, + allow_parallel: bool, ) { #[cfg(not(target_arch = "wasm32"))] { const PARALLEL_THRESHOLD_PIXELS: usize = 512 * 512; let total_px = raw_f32.len() / 4; - if total_px >= PARALLEL_THRESHOLD_PIXELS { + if allow_parallel && total_px >= PARALLEL_THRESHOLD_PIXELS { let workers = std::thread::available_parallelism() .map(|n| n.get().clamp(2, 12)) .unwrap_or(4) @@ -289,6 +292,8 @@ fn convert_exr_rgba_buffers( return; } } + #[cfg(target_arch = "wasm32")] + let _ = allow_parallel; convert_exr_rgba_slice( raw_f32, raw_f16, @@ -304,8 +309,11 @@ fn decode_exr_from( reader: R, [red_name, green_name, blue_name, alpha_name]: [Option<&str>; 4], post_multiply: bool, + allow_parallel: bool, ) -> Option { use ::exr::block::reader::ChunksReader; + use ::exr::block::UncompressedBlock; + use ::exr::error::UnitResult; use ::exr::meta::attribute::SampleType; use ::exr::prelude::*; @@ -332,63 +340,67 @@ fn decode_exr_from( let mut line_f16 = Vec::::new(); let mut line_u32 = Vec::::new(); - chunks_reader + let filtered = chunks_reader .filter_chunks(false, |_, tile, block| { tile.is_largest_resolution_level() && needed_layers.contains(&block.layer) }) - .ok()? - .decompress_parallel(false, |meta, block| { - let header = &meta.headers[block.index.layer]; - for line in block.lines(&header.channels) { - let loc = (line.location.layer, line.location.channel); - let mut comp_mask = [false; 4]; - for (c, t) in target_locs.iter().enumerate() { - if *t == Some(loc) { - comp_mask[c] = true; - } - } - if !comp_mask.iter().any(|&m| m) { - continue; - } - let y = line.location.position.y(); - let x0 = line.location.position.x(); - let len = line.location.sample_count; - if y >= h || x0 + len > w { - continue; - } - - line_f32.clear(); - match header.channels.list[line.location.channel].sample_type { - SampleType::F32 => { - line_f32.resize(len, 0.0); - line.read_samples_into_slice(&mut line_f32)?; - } - SampleType::F16 => { - line_f16.resize(len, f16::ZERO); - line.read_samples_into_slice(&mut line_f16)?; - line_f32.extend(line_f16.iter().map(|v| v.to_f32())); - } - SampleType::U32 => { - line_u32.resize(len, 0); - line.read_samples_into_slice(&mut line_u32)?; - line_f32.extend(line_u32.iter().map(|&v| v as f32)); - } - } - - let row_base = (y * w + x0) * 4; - for (dx, &sample) in line_f32.iter().enumerate() { - let val = if sample.is_nan() { 0.0 } else { sample }; - let px_off = row_base + dx * 4; - for (c, &enabled) in comp_mask.iter().enumerate() { - if enabled { - raw_f32[px_off + c] = val; - } - } - } - } - Ok(()) - }) .ok()?; + let insert_block = |meta: &MetaData, block: UncompressedBlock| -> UnitResult { + let header = &meta.headers[block.index.layer]; + for line in block.lines(&header.channels) { + let loc = (line.location.layer, line.location.channel); + let mut comp_mask = [false; 4]; + for (c, t) in target_locs.iter().enumerate() { + if *t == Some(loc) { + comp_mask[c] = true; + } + } + if !comp_mask.iter().any(|&m| m) { + continue; + } + let y = line.location.position.y(); + let x0 = line.location.position.x(); + let len = line.location.sample_count; + if y >= h || x0 + len > w { + continue; + } + + line_f32.clear(); + match header.channels.list[line.location.channel].sample_type { + SampleType::F32 => { + line_f32.resize(len, 0.0); + line.read_samples_into_slice(&mut line_f32)?; + } + SampleType::F16 => { + line_f16.resize(len, f16::ZERO); + line.read_samples_into_slice(&mut line_f16)?; + line_f32.extend(line_f16.iter().map(|v| v.to_f32())); + } + SampleType::U32 => { + line_u32.resize(len, 0); + line.read_samples_into_slice(&mut line_u32)?; + line_f32.extend(line_u32.iter().map(|&v| v as f32)); + } + } + + let row_base = (y * w + x0) * 4; + for (dx, &sample) in line_f32.iter().enumerate() { + let val = if sample.is_nan() { 0.0 } else { sample }; + let px_off = row_base + dx * 4; + for (c, &enabled) in comp_mask.iter().enumerate() { + if enabled { + raw_f32[px_off + c] = val; + } + } + } + } + Ok(()) + }; + if allow_parallel { + filtered.decompress_parallel(false, insert_block).ok()?; + } else { + filtered.decompress_sequential(false, insert_block).ok()?; + } let mut raw = vec![0u8; w * h * 4]; let mut raw_f16 = vec![0u16; w * h * 4]; @@ -400,6 +412,7 @@ fn decode_exr_from( b_loc.is_some(), a_loc.is_some(), post_multiply, + allow_parallel, ); Some(DecodedImage { size: [w as u32, h as u32], @@ -421,9 +434,12 @@ mod tests { image::DynamicImage::ImageRgba32F(pixels).write_to(&mut out, image::ImageFormat::OpenExr).unwrap(); assert!(MediaCache::insert_virtual_bytes("vexr_drop/frame.exr", out.into_inner())); - let decoded = decode_exr_rgba(Path::new("/not/on/disk/vexr_drop/frame.exr"), None, None, None, None, false).unwrap(); + let decoded = decode_exr_rgba(Path::new("/not/on/disk/vexr_drop/frame.exr"), None, None, None, None, false, true).unwrap(); assert_eq!(decoded.size, [2, 1]); assert_eq!(&decoded.rgba_f32.unwrap()[..4], &[2.5, 0.5, 0.0, 1.0]); + let decoded_seq = decode_exr_rgba(Path::new("/not/on/disk/vexr_drop/frame.exr"), None, None, None, None, false, false).unwrap(); + assert_eq!(decoded_seq.size, [2, 1]); + assert_eq!(&decoded_seq.rgba_f32.unwrap()[..4], &[2.5, 0.5, 0.0, 1.0]); } #[test] @@ -469,12 +485,13 @@ mod tests { has_b, has_a, post_multiply, + true, ); let mut seq_f32 = base.clone(); let mut seq_f16 = vec![0u16; pixels * 4]; let mut seq_u8 = vec![0u8; pixels * 4]; - convert_exr_rgba_slice( + convert_exr_rgba_buffers( &mut seq_f32, &mut seq_f16, &mut seq_u8, @@ -482,6 +499,7 @@ mod tests { has_b, has_a, post_multiply, + false, ); assert_eq!(par_f16, seq_f16, "f16 mismatch for ({has_g},{has_b},{has_a},{post_multiply})");