diff --git a/crates/engine/src/bin/render_check.rs b/crates/engine/src/bin/render_check.rs index 6574ed3bc9adc6813daa86865a5b284880be7db5..394d5d4d958eabb8e866c397209a5d607e4a4802 100644 --- a/crates/engine/src/bin/render_check.rs +++ b/crates/engine/src/bin/render_check.rs @@ -243,19 +243,38 @@ fn run_batch_render( } let mut loop_err: Option = None; - const PREFETCH_WINDOW: usize = 8; + const PREFETCH_LOOKAHEAD: usize = 12; + engine.media.preload_frame_loaders_with_proxy( + &comp, + target, + start as f64, + &engine.expr, + engine.use_proxy_clips, + ); + let prefetch = engine.media.start_frame_prefetch(PREFETCH_LOOKAHEAD); + let seed_end = (start + PREFETCH_LOOKAHEAD as i64 - 1).min(end); + for (k, f) in ((start + 1)..=seed_end).enumerate() { + prefetch.enqueue_frame( + &comp, + target, + k + 1, + f as f64, + &engine.expr, + engine.use_proxy_clips, + ); + } for (idx, f) in (start..=end).enumerate() { if failed.load(Ordering::Acquire) { break; } - if idx % PREFETCH_WINDOW == 0 { - let win_end = (idx + PREFETCH_WINDOW).min(total); - let window: Vec = - (idx..win_end).map(|k| (start + k as i64) as f64).collect(); - engine.media.prefetch_frames_with_proxy( + prefetch.set_current_seq(idx); + let ahead_frame = f + PREFETCH_LOOKAHEAD as i64; + if ahead_frame <= end { + prefetch.enqueue_frame( &comp, target, - &window, + idx + PREFETCH_LOOKAHEAD, + ahead_frame as f64, &engine.expr, engine.use_proxy_clips, ); @@ -292,6 +311,7 @@ fn run_batch_render( } } + drop(prefetch); drop(tx); for h in handles { let _ = h.join(); diff --git a/crates/engine/src/eval/io.rs b/crates/engine/src/eval/io.rs index 3ecba1decd26a2f90502255e7fd2ce7a27a3fe88..f53ce5d5eb4b69d3932b78e2223054061abeccaf 100644 --- a/crates/engine/src/eval/io.rs +++ b/crates/engine/src/eval/io.rs @@ -86,6 +86,95 @@ impl Engine { } } + fn upload_loader_texture( + &self, + enc: &mut wgpu::CommandEncoder, + tex: &CachedTexture, + data: &[u8], + bytes_per_pixel: u32, + size: [u32; 2], + ) { + #[cfg(target_arch = "wasm32")] + { + let _ = enc; + self.queue.write_texture( + tex.texture.as_image_copy(), + data, + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(size[0] * bytes_per_pixel), + rows_per_image: Some(size[1]), + }, + wgpu::Extent3d { + width: size[0], + height: size[1], + depth_or_array_layers: 1, + }, + ); + } + #[cfg(not(target_arch = "wasm32"))] + { + let [w, h] = size; + if w == 0 || h == 0 { + return; + } + let unpadded_bpr = w * bytes_per_pixel; + let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; + let padded_bpr = unpadded_bpr.div_ceil(align) * align; + let needed = u64::from(padded_bpr) * u64::from(h); + if let Some(buf) = self.media.acquire_upload_staging(&self.device, needed) { + if let Ok(mut view) = buf.slice(..needed).get_mapped_range_mut() { + if padded_bpr == unpadded_bpr { + let total = (unpadded_bpr as usize) * (h as usize); + view.slice(..total).copy_from_slice(&data[..total]); + } else { + let src_stride = unpadded_bpr as usize; + let dst_stride = padded_bpr as usize; + let mut wo = view.slice(..needed as usize); + for (row_idx, src_row) in data.chunks_exact(src_stride).enumerate() { + let off = row_idx * dst_stride; + wo.slice(off..off + src_stride).copy_from_slice(src_row); + } + } + drop(view); + buf.unmap(); + enc.copy_buffer_to_texture( + wgpu::TexelCopyBufferInfo { + buffer: &buf, + layout: wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(padded_bpr), + rows_per_image: Some(h), + }, + }, + tex.texture.as_image_copy(), + wgpu::Extent3d { + width: w, + height: h, + depth_or_array_layers: 1, + }, + ); + self.media.recycle_upload_staging(buf); + return; + } + } + self.queue.write_texture( + tex.texture.as_image_copy(), + data, + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(unpadded_bpr), + rows_per_image: Some(h), + }, + wgpu::Extent3d { + width: w, + height: h, + depth_or_array_layers: 1, + }, + ); + } + } + pub(super) fn eval_loader( &mut self, comp: &Comp, @@ -120,9 +209,7 @@ impl Engine { if let Some(proxy_name) = proxy_candidate { let mut proxy_clip = effective_clip.clone(); proxy_clip.filename = proxy_name.to_owned(); - if crate::media::resolve_clip_path(&proxy_clip, frame_i) - .is_some_and(|p| p.exists()) - { + if self.media.resolve_clip_path_cached(&proxy_clip, frame_i).is_some() { effective_clip = proxy_clip; } } @@ -236,54 +323,15 @@ impl Engine { let f32_px = img.rgba_f32.as_ref().expect("checked is_some"); let tex = self.alloc_tex(img.size, dst_depth, if need_post { 0 } else { key }); if tex.format == wgpu::TextureFormat::Rgba32Float { - self.queue.write_texture( - tex.texture.as_image_copy(), - bytemuck::cast_slice(f32_px), - wgpu::TexelCopyBufferLayout { - offset: 0, - bytes_per_row: Some(img.size[0] * 16), - rows_per_image: Some(img.size[1]), - }, - wgpu::Extent3d { - width: img.size[0], - height: img.size[1], - depth_or_array_layers: 1, - }, - ); + self.upload_loader_texture(enc, &tex, bytemuck::cast_slice(f32_px), 16, img.size); } else { let f16_bits = img.rgba_f16.as_ref().expect("EXR populates rgba_f16"); - self.queue.write_texture( - tex.texture.as_image_copy(), - bytemuck::cast_slice(f16_bits), - wgpu::TexelCopyBufferLayout { - offset: 0, - bytes_per_row: Some(img.size[0] * 8), - rows_per_image: Some(img.size[1]), - }, - wgpu::Extent3d { - width: img.size[0], - height: img.size[1], - depth_or_array_layers: 1, - }, - ); + self.upload_loader_texture(enc, &tex, bytemuck::cast_slice(f16_bits), 8, img.size); } tex } else { let tex = self.alloc_tex(img.size, BitDepth::Int8, if need_post { 0 } else { key }); - self.queue.write_texture( - tex.texture.as_image_copy(), - &img.rgba, - wgpu::TexelCopyBufferLayout { - offset: 0, - bytes_per_row: Some(img.size[0] * 4), - rows_per_image: Some(img.size[1]), - }, - wgpu::Extent3d { - width: img.size[0], - height: img.size[1], - depth_or_array_layers: 1, - }, - ); + self.upload_loader_texture(enc, &tex, &img.rgba, 4, img.size); tex }; let work_depth = if use_float_upload { dst_depth } else { BitDepth::Int8 }; diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index bad4f528f89556079a50898e5dd001b228c03fd9..06a4718af190d368a0218a9e47e02ff972d17e71 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -306,7 +306,26 @@ pub fn export_saver_png_sequence_with_progress( } let mut loop_err: Option = None; - const PREFETCH_WINDOW: usize = 8; + const PREFETCH_LOOKAHEAD: usize = 12; + engine.media.preload_frame_loaders_with_proxy( + comp, + target, + start as f64, + &engine.expr, + engine.use_proxy_clips, + ); + let prefetch = engine.media.start_frame_prefetch(PREFETCH_LOOKAHEAD); + let seed_end = (start + PREFETCH_LOOKAHEAD as i64 - 1).min(end); + for (k, f) in ((start + 1)..=seed_end).enumerate() { + prefetch.enqueue_frame( + comp, + target, + k + 1, + f as f64, + &engine.expr, + engine.use_proxy_clips, + ); + } for (idx, frame) in (start..=end).enumerate() { if failed.load(Ordering::Acquire) { break; @@ -315,13 +334,14 @@ pub fn export_saver_png_sequence_with_progress( cancelled.store(true, Ordering::Release); break; } - if idx % PREFETCH_WINDOW == 0 { - let win_end = (idx + PREFETCH_WINDOW).min(total); - let window: Vec = (idx..win_end).map(|k| (start + k as i64) as f64).collect(); - engine.media.prefetch_frames_with_proxy( + prefetch.set_current_seq(idx); + let ahead_frame = frame + PREFETCH_LOOKAHEAD as i64; + if ahead_frame <= end { + prefetch.enqueue_frame( comp, target, - &window, + idx + PREFETCH_LOOKAHEAD, + ahead_frame as f64, &engine.expr, engine.use_proxy_clips, ); @@ -379,6 +399,7 @@ pub fn export_saver_png_sequence_with_progress( frames_written += 1; } + drop(prefetch); drop(tx); for h in handles { let _ = h.join(); @@ -901,8 +922,19 @@ pub fn export_node_video_ffmpeg_with_progress( } on_progress(first_prog); - const PREFETCH_WINDOW: usize = 8; - let remaining = total.saturating_sub(1); + const PREFETCH_LOOKAHEAD: usize = 12; + let prefetch = engine.media.start_frame_prefetch(PREFETCH_LOOKAHEAD); + let seed_end = (start + PREFETCH_LOOKAHEAD as i64).min(end); + for (k, f) in ((start + 1)..=seed_end).enumerate() { + prefetch.enqueue_frame( + comp, + opts.target, + k, + f as f64, + &engine.expr, + engine.use_proxy_clips, + ); + } for (idx, frame) in ((start + 1)..=end).enumerate() { if writer_failed.load(Ordering::Acquire) { break; @@ -911,13 +943,14 @@ pub fn export_node_video_ffmpeg_with_progress( cancelled = true; break; } - if idx % PREFETCH_WINDOW == 0 { - let win_end = (idx + PREFETCH_WINDOW).min(remaining); - let window: Vec = (idx..win_end).map(|k| (start + 1 + k as i64) as f64).collect(); - engine.media.prefetch_frames_with_proxy( + prefetch.set_current_seq(idx); + let ahead_frame = frame + PREFETCH_LOOKAHEAD as i64; + if ahead_frame <= end { + prefetch.enqueue_frame( comp, opts.target, - &window, + idx + PREFETCH_LOOKAHEAD, + ahead_frame as f64, &engine.expr, engine.use_proxy_clips, ); @@ -951,6 +984,7 @@ pub fn export_node_video_ffmpeg_with_progress( } on_progress(prog); } + drop(prefetch); } drop(tx); diff --git a/crates/engine/src/media.rs b/crates/engine/src/media.rs index 6484b73f776cc58fceac2b601b862404cb5aefd1..043f33af370a1ac756ed42ed850c9b11ac043770 100644 --- a/crates/engine/src/media.rs +++ b/crates/engine/src/media.rs @@ -21,15 +21,15 @@ use crate::text_engine; use model::{Node, default_main_input_port}; use model::{ClipSpec, ClsEntry, Comp, NodeId, PolyPoint}; #[cfg(not(target_arch = "wasm32"))] -use std::collections::HashSet; -use std::collections::HashMap; +use std::collections::VecDeque; +use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; use std::process::Command; #[cfg(not(target_arch = "wasm32"))] -use std::sync::Mutex; -use std::sync::{Arc, RwLock}; -#[cfg(not(target_arch = "wasm32"))] use std::sync::atomic::{AtomicUsize, Ordering}; +#[cfg(not(target_arch = "wasm32"))] +use std::sync::{Condvar, mpsc}; +use std::sync::{Arc, Mutex, RwLock}; #[derive(Clone)] pub struct DecodedImage { @@ -134,10 +134,14 @@ fn open_image(path: &Path) -> Option { return image::load_from_memory(&bytes).ok(); } // Read file contents in one contiguous pass to avoid tiny buffered syscalls over SMB/network shares. - if let Ok(bytes) = std::fs::read(path) { - if let Ok(img) = image::load_from_memory(&bytes) { - return Some(img); + match std::fs::read(path) { + Ok(bytes) => { + if let Ok(img) = image::load_from_memory(&bytes) { + return Some(img); + } } + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return None, + Err(_) => {} } image::open(path).ok() } @@ -190,87 +194,45 @@ struct ImageCacheKey { exr_channels: [Option; 4], } -struct VideoDecoderEntry { - decoder: Option>, +struct VideoDecoderSlot { + info: Option, + decoder: Arc>>>, last_used: u64, } -pub struct MediaCache { +struct MediaState { images: HashMap, - video_decoders: HashMap, + video_decoders: HashMap, total_bytes: u64, budget_bytes: u64, lru: HashMap, tick: u64, + generation: u64, + #[cfg(not(target_arch = "wasm32"))] + in_flight: HashSet, + #[cfg(not(target_arch = "wasm32"))] + opening_videos: HashSet, + known_existing_paths: HashSet, } -impl Default for MediaCache { - fn default() -> Self { - Self::new(default_media_cache_budget_mb()) - } -} - -impl MediaCache { - pub fn new(budget_mb: u64) -> Self { +impl MediaState { + fn new(budget_bytes: u64) -> Self { Self { images: HashMap::new(), video_decoders: HashMap::new(), total_bytes: 0, - budget_bytes: budget_mb.saturating_mul(1024 * 1024), + budget_bytes, lru: HashMap::new(), tick: 0, + generation: 0, + #[cfg(not(target_arch = "wasm32"))] + in_flight: HashSet::new(), + #[cfg(not(target_arch = "wasm32"))] + opening_videos: HashSet::new(), + known_existing_paths: HashSet::new(), } } - pub fn with_budget_mb(budget_mb: u64) -> Self { - Self::new(budget_mb) - } - - /// Registers `bytes` as the file at `path` for every `MediaCache` in the process. `false` - /// when the files held would pass [`MAX_VIRTUAL_BYTES`], leaving the registry unchanged. - pub fn insert_virtual_bytes(path: impl AsRef, bytes: impl Into>) -> bool { - let Ok(mut files) = VIRTUAL_FILES.write() else { return false }; - insert_capped(&mut files, MAX_VIRTUAL_BYTES, path_parts(path.as_ref()), bytes.into()) - } - - pub fn clear_virtual_bytes() { - if let Ok(mut files) = VIRTUAL_FILES.write() { - files.clear(); - } - } - - pub fn clear(&mut self) { - self.images.clear(); - self.lru.clear(); - self.video_decoders.clear(); - self.total_bytes = 0; - } - - pub fn set_budget_mb(&mut self, budget_mb: u64) { - self.budget_bytes = budget_mb.saturating_mul(1024 * 1024); - while self.total_bytes > self.budget_bytes && self.images.len() > 1 { - let Some((oldest_key, _)) = self.lru.iter().min_by_key(|(_, t)| **t).map(|(k, t)| (k.clone(), *t)) else { - break; - }; - self.lru.remove(&oldest_key); - if let Some(removed) = self.images.remove(&oldest_key) { - self.total_bytes = self.total_bytes.saturating_sub(removed.byte_size()); - } - } - } - - pub fn entry_count(&self) -> usize { - self.images.len() - } - - pub fn video_decoder_count(&self) -> usize { - self.video_decoders.len() - } - - pub fn total_mb(&self) -> f64 { - self.total_bytes as f64 / (1024.0 * 1024.0) - } - fn insert_cached(&mut self, cache_key: ImageCacheKey, decoded: DecodedImage) { let bytes = decoded.byte_size(); self.tick += 1; @@ -291,12 +253,18 @@ impl MediaCache { } } - fn put_video_decoder(&mut self, path: PathBuf, decoder: Option>) { + fn put_video_decoder( + &mut self, + path: PathBuf, + info: Option, + decoder: Arc>>>, + ) { self.tick += 1; let now_tick = self.tick; - if let Some(entry) = self.video_decoders.get_mut(&path) { - entry.decoder = decoder; - entry.last_used = now_tick; + if let Some(slot) = self.video_decoders.get_mut(&path) { + slot.info = info; + slot.decoder = decoder; + slot.last_used = now_tick; return; } while self.video_decoders.len() >= MAX_VIDEO_DECODERS { @@ -312,24 +280,378 @@ impl MediaCache { } self.video_decoders.insert( path, - VideoDecoderEntry { + VideoDecoderSlot { + info, decoder, last_used: now_tick, }, ); } +} - fn get_or_open_video_decoder(&mut self, path: &Path) -> Option { - self.tick += 1; - let now_tick = self.tick; - if let Some(entry) = self.video_decoders.get_mut(path) { - entry.last_used = now_tick; - return entry.decoder.as_ref().map(|d| d.info()); +struct MediaShared { + state: Mutex, + #[cfg(not(target_arch = "wasm32"))] + cv: Condvar, +} + +impl MediaShared { + fn new(budget_bytes: u64) -> Self { + Self { + state: Mutex::new(MediaState::new(budget_bytes)), + #[cfg(not(target_arch = "wasm32"))] + cv: Condvar::new(), + } + } + + fn path_exists_cached(&self, path: &Path) -> bool { + if virtual_bytes(path).is_some() { + return true; + } + if let Ok(state) = self.state.lock() { + if state.known_existing_paths.contains(path) || state.video_decoders.contains_key(path) { + return true; + } + } + if path.exists() { + if let Ok(mut state) = self.state.lock() { + state.known_existing_paths.insert(path.to_path_buf()); + } + true + } else { + false + } + } + + fn resolve_clip_path_cached(&self, clip: &ClipSpec, frame: i64) -> Option { + let candidate = resolve_clip_candidate_path(clip, frame)?; + self.path_exists_cached(&candidate).then_some(candidate) + } + + fn get_or_open_video_decoder( + &self, + path: &Path, + ) -> Option<(VideoInfo, Arc>>>)> { + let mut guard = self.state.lock().ok()?; + #[cfg(not(target_arch = "wasm32"))] + while guard.opening_videos.contains(path) { + guard = self.cv.wait(guard).ok()?; } + guard.tick += 1; + let now_tick = guard.tick; + if let Some(slot) = guard.video_decoders.get_mut(path) { + slot.last_used = now_tick; + return slot.info.map(|info| (info, Arc::clone(&slot.decoder))); + } + + #[cfg(not(target_arch = "wasm32"))] + { + guard.opening_videos.insert(path.to_path_buf()); + } + let cache_gen = guard.generation; + drop(guard); + + struct OpenGuard<'a> { + shared: &'a MediaShared, + path: PathBuf, + } + impl Drop for OpenGuard<'_> { + fn drop(&mut self) { + #[cfg(not(target_arch = "wasm32"))] + if let Ok(mut state) = self.shared.state.lock() { + state.opening_videos.remove(&self.path); + self.shared.cv.notify_all(); + } + #[cfg(target_arch = "wasm32")] + let _ = (&self.shared, &self.path); + } + } + let _open_guard = OpenGuard { + shared: self, + path: path.to_path_buf(), + }; + let decoder = open_video_decoder(path); let info = decoder.as_ref().map(|d| d.info()); - self.put_video_decoder(path.to_path_buf(), decoder); - info + let slot_arc = Arc::new(Mutex::new(decoder)); + + if let Ok(mut state) = self.state.lock() { + #[cfg(not(target_arch = "wasm32"))] + state.opening_videos.remove(path); + if state.generation == cache_gen { + state.put_video_decoder(path.to_path_buf(), info, Arc::clone(&slot_arc)); + } + #[cfg(not(target_arch = "wasm32"))] + self.cv.notify_all(); + } + info.map(|i| (i, slot_arc)) + } +} + +#[cfg(not(target_arch = "wasm32"))] +struct InFlightGuard<'a> { + shared: &'a MediaShared, + key: Option, +} + +#[cfg(not(target_arch = "wasm32"))] +impl Drop for InFlightGuard<'_> { + fn drop(&mut self) { + if let Some(key) = self.key.take() { + if let Ok(mut state) = self.shared.state.lock() { + state.in_flight.remove(&key); + self.shared.cv.notify_all(); + } + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +struct StagingBufferEntry { + buffer: wgpu::Buffer, + capacity: u64, + rx: Option>>, +} + +#[cfg(not(target_arch = "wasm32"))] +pub(crate) struct UploadStagingPool { + ready: Vec, + pending_submit: Vec, + mapping: Vec, + total_bytes: u64, + max_bytes: u64, + needs_begin_frame: bool, +} + +#[cfg(not(target_arch = "wasm32"))] +impl UploadStagingPool { + fn new(max_bytes: u64) -> Self { + Self { + ready: Vec::new(), + pending_submit: Vec::new(), + mapping: Vec::new(), + total_bytes: 0, + max_bytes, + needs_begin_frame: false, + } + } + + fn mark_frame_start(&mut self) { + self.needs_begin_frame = true; + } + + fn clear(&mut self) { + self.ready.clear(); + self.pending_submit.clear(); + self.mapping.clear(); + self.total_bytes = 0; + self.needs_begin_frame = false; + } + + fn flush_pending_if_needed(&mut self, device: &wgpu::Device) { + if !self.needs_begin_frame { + return; + } + self.needs_begin_frame = false; + if !self.pending_submit.is_empty() { + for mut entry in self.pending_submit.drain(..) { + let (tx, rx) = mpsc::channel(); + entry.buffer.slice(..).map_async(wgpu::MapMode::Write, move |res| { + let _ = tx.send(res); + }); + entry.rx = Some(rx); + self.mapping.push(entry); + } + } + self.harvest_ready(device, false); + } + + fn harvest_ready(&mut self, device: &wgpu::Device, wait: bool) { + if self.mapping.is_empty() { + return; + } + let poll_mode = if wait { + wgpu::PollType::Wait { + submission_index: None, + timeout: Some(std::time::Duration::from_secs(5)), + } + } else { + wgpu::PollType::Poll + }; + let _ = device.poll(poll_mode); + let mut i = 0; + while i < self.mapping.len() { + let status = match self.mapping[i].rx.as_ref() { + Some(rx) => rx.try_recv(), + None => Ok(Ok(())), + }; + match status { + Ok(Ok(())) => { + let mut entry = self.mapping.swap_remove(i); + entry.rx = None; + self.ready.push(entry); + } + Ok(Err(_)) | Err(mpsc::TryRecvError::Disconnected) => { + let entry = self.mapping.swap_remove(i); + self.total_bytes = self.total_bytes.saturating_sub(entry.capacity); + } + Err(mpsc::TryRecvError::Empty) => { + i += 1; + } + } + } + } + + fn take_ready(&mut self, needed: u64) -> Option { + let max_acceptable = needed.saturating_mul(2).max(needed.saturating_add(4 * 1024 * 1024)); + let mut best_idx = None; + let mut best_cap = u64::MAX; + for (i, entry) in self.ready.iter().enumerate() { + if entry.capacity >= needed && entry.capacity <= max_acceptable && entry.capacity < best_cap { + best_cap = entry.capacity; + best_idx = Some(i); + } + } + best_idx.map(|idx| self.ready.swap_remove(idx).buffer) + } + + pub(crate) fn acquire(&mut self, device: &wgpu::Device, needed: u64) -> Option { + self.flush_pending_if_needed(device); + if let Some(buf) = self.take_ready(needed) { + return Some(buf); + } + self.harvest_ready(device, false); + if let Some(buf) = self.take_ready(needed) { + return Some(buf); + } + while self.total_bytes.saturating_add(needed) > self.max_bytes && !self.ready.is_empty() { + let evicted = self.ready.remove(0); + self.total_bytes = self.total_bytes.saturating_sub(evicted.capacity); + } + if self.total_bytes.saturating_add(needed) > self.max_bytes { + return None; + } + let alloc_size = needed.max(4096); + let buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("loader-upload-staging"), + size: alloc_size, + usage: wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::MAP_WRITE, + mapped_at_creation: true, + }); + self.total_bytes = self.total_bytes.saturating_add(alloc_size); + Some(buffer) + } + + pub(crate) fn finish_upload(&mut self, buffer: wgpu::Buffer) { + let capacity = buffer.size(); + self.pending_submit.push(StagingBufferEntry { + buffer, + capacity, + rx: None, + }); + } +} + +pub struct MediaCache { + shared: Arc, + #[cfg(not(target_arch = "wasm32"))] + staging_pool: Mutex, +} + +impl Default for MediaCache { + fn default() -> Self { + Self::new(default_media_cache_budget_mb()) + } +} + +impl MediaCache { + pub fn new(budget_mb: u64) -> Self { + Self { + shared: Arc::new(MediaShared::new(budget_mb.saturating_mul(1024 * 1024))), + #[cfg(not(target_arch = "wasm32"))] + staging_pool: Mutex::new(UploadStagingPool::new(320 * 1024 * 1024)), + } + } + + pub fn with_budget_mb(budget_mb: u64) -> Self { + Self::new(budget_mb) + } + + /// Registers `bytes` as the file at `path` for every `MediaCache` in the process. `false` + /// when the files held would pass [`MAX_VIRTUAL_BYTES`], leaving the registry unchanged. + pub fn insert_virtual_bytes(path: impl AsRef, bytes: impl Into>) -> bool { + let Ok(mut files) = VIRTUAL_FILES.write() else { return false }; + insert_capped(&mut files, MAX_VIRTUAL_BYTES, path_parts(path.as_ref()), bytes.into()) + } + + pub fn clear_virtual_bytes() { + if let Ok(mut files) = VIRTUAL_FILES.write() { + files.clear(); + } + } + + pub fn clear(&mut self) { + if let Ok(mut state) = self.shared.state.lock() { + state.images.clear(); + state.lru.clear(); + state.video_decoders.clear(); + state.total_bytes = 0; + state.generation = state.generation.wrapping_add(1); + state.known_existing_paths.clear(); + } + #[cfg(not(target_arch = "wasm32"))] + if let Ok(mut pool) = self.staging_pool.lock() { + pool.clear(); + } + } + + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn acquire_upload_staging(&self, device: &wgpu::Device, needed: u64) -> Option { + self.staging_pool + .lock() + .expect("staging pool lock") + .acquire(device, needed) + } + + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn recycle_upload_staging(&self, buffer: wgpu::Buffer) { + self.staging_pool + .lock() + .expect("staging pool lock") + .finish_upload(buffer); + } + + 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()); + } + } + } + + pub fn entry_count(&self) -> usize { + self.shared.state.lock().map_or(0, |s| s.images.len()) + } + + pub fn video_decoder_count(&self) -> usize { + self.shared.state.lock().map_or(0, |s| s.video_decoders.len()) + } + + pub fn total_mb(&self) -> f64 { + self.shared + .state + .lock() + .map_or(0.0, |s| s.total_bytes as f64 / (1024.0 * 1024.0)) + } + + pub(crate) fn resolve_clip_path_cached(&self, clip: &ClipSpec, frame: i64) -> Option { + self.shared.resolve_clip_path_cached(clip, frame) } /// Loads a Fusion `ClipSpec` (still image, numbered sequence, OpenEXR, or `.mov`/`.mp4` video) at `frame`. @@ -343,11 +665,11 @@ impl MediaCache { ) -> Option<(PathBuf, i64, DecodedImage, bool)> { let base = Path::new(&clip.filename); if is_video_path(base) { - if !base.exists() || !video_frame_in_range(clip, frame) { + if !video_frame_in_range(clip, frame) || !self.shared.path_exists_cached(base) { return None; } let base_buf = base.to_path_buf(); - let info = self.get_or_open_video_decoder(base)?; + let (info, decoder_arc) = self.shared.get_or_open_video_decoder(base)?; let idx = compute_video_frame_idx(clip, frame, info.nb_frames); let cache_key = ImageCacheKey { path: base_buf.clone(), @@ -355,16 +677,37 @@ impl MediaCache { post_multiply, exr_channels: [None, None, None, None], }; - if let Some(img) = self.images.get(&cache_key).cloned() { - self.tick += 1; - self.lru.insert(cache_key, self.tick); - return Some((base_buf, idx, img, false)); - } - let mut raw = self - .video_decoders - .get_mut(&base_buf) - .and_then(|e| e.decoder.as_mut())? - .decode_frame(idx)?; + + let cache_gen = { + let mut state = self.shared.state.lock().ok()?; + loop { + if let Some(img) = state.images.get(&cache_key).cloned() { + state.tick += 1; + let t = state.tick; + state.lru.insert(cache_key, t); + return Some((base_buf, idx, img, false)); + } + #[cfg(not(target_arch = "wasm32"))] + if state.in_flight.contains(&cache_key) { + state = self.shared.cv.wait(state).ok()?; + continue; + } + #[cfg(not(target_arch = "wasm32"))] + state.in_flight.insert(cache_key.clone()); + break state.generation; + } + }; + + #[cfg(not(target_arch = "wasm32"))] + let mut in_flight_guard = InFlightGuard { + shared: &self.shared, + key: Some(cache_key.clone()), + }; + + let mut raw = { + let mut dec_guard = decoder_arc.lock().ok()?; + dec_guard.as_mut()?.decode_frame(idx)? + }; if post_multiply { apply_post_multiply_rgba8(&mut raw); } @@ -374,11 +717,23 @@ impl MediaCache { rgba_f16: None, rgba_f32: None, }; - self.insert_cached(cache_key, decoded.clone()); + + 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 { + state.insert_cached(cache_key, decoded.clone()); + } + #[cfg(not(target_arch = "wasm32"))] + self.shared.cv.notify_all(); + } return Some((base_buf, idx, decoded, true)); } - let resolved = resolve_clip_path(clip, frame)?; + let resolved = resolve_clip_candidate_path(clip, frame)?; let is_exr = is_exr_path(&resolved); let key_channels = if is_exr { [ @@ -396,13 +751,37 @@ impl MediaCache { post_multiply: post_multiply && !is_exr, exr_channels: key_channels, }; - if let Some(img) = self.images.get(&cache_key).cloned() { - self.tick += 1; - self.lru.insert(cache_key, self.tick); - return Some((resolved, -1, img, false)); - } + + let cache_gen = { + let mut state = self.shared.state.lock().ok()?; + loop { + if let Some(img) = state.images.get(&cache_key).cloned() { + state.tick += 1; + let t = state.tick; + state.lru.insert(cache_key, t); + return Some((resolved, -1, img, false)); + } + #[cfg(not(target_arch = "wasm32"))] + if state.in_flight.contains(&cache_key) { + state = self.shared.cv.wait(state).ok()?; + continue; + } + #[cfg(not(target_arch = "wasm32"))] + state.in_flight.insert(cache_key.clone()); + break state.generation; + } + }; + + #[cfg(not(target_arch = "wasm32"))] + let mut in_flight_guard = InFlightGuard { + shared: &self.shared, + key: Some(cache_key.clone()), + }; let decoded = if is_exr { + if !self.shared.path_exists_cached(&resolved) { + return None; + } // OpenEXR is already premultiplied in Blender/Fusion; never double-premultiply! decode_exr_rgba( &resolved, @@ -415,7 +794,20 @@ impl MediaCache { } else { decode_raster_image(&resolved, post_multiply, true)? }; - self.insert_cached(cache_key, decoded.clone()); + + 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 { + state.known_existing_paths.insert(resolved.clone()); + state.insert_cached(cache_key, decoded.clone()); + } + #[cfg(not(target_arch = "wasm32"))] + self.shared.cv.notify_all(); + } Some((resolved, -1, decoded, true)) } @@ -446,9 +838,13 @@ impl MediaCache { } #[cfg(not(target_arch = "wasm32"))] { + if let Ok(mut pool) = self.staging_pool.lock() { + pool.mark_frame_start(); + } let mut visited = HashSet::new(); let mut jobs = MissingJobs::default(); - self.collect_missing_loader_jobs( + collect_missing_loader_jobs_shared( + &self.shared, comp, target, time, @@ -496,7 +892,8 @@ impl MediaCache { let mut visited = HashSet::new(); let mut jobs = MissingJobs::default(); for &time in frames { - self.collect_missing_loader_jobs( + collect_missing_loader_jobs_shared( + &self.shared, comp, target, time, @@ -512,8 +909,30 @@ impl MediaCache { } if total == 1 && jobs.raster.len() == 1 { let job = jobs.raster.pop().expect("len == 1"); + let cache_gen = { + let Ok(mut state) = self.shared.state.lock() else { return }; + if state.images.contains_key(&job.cache_key) + || state.in_flight.contains(&job.cache_key) + { + return; + } + state.in_flight.insert(job.cache_key.clone()); + state.generation + }; + let mut guard = InFlightGuard { + shared: &self.shared, + key: Some(job.cache_key.clone()), + }; if let Some(decoded) = decode_job(&job, true) { - self.insert_cached(job.cache_key, decoded); + if let Ok(mut state) = self.shared.state.lock() { + state.in_flight.remove(&job.cache_key); + guard.key = None; + if state.generation == cache_gen { + state.known_existing_paths.insert(job.cache_key.path.clone()); + state.insert_cached(job.cache_key, decoded); + } + self.shared.cv.notify_all(); + } } return; } @@ -521,22 +940,19 @@ impl MediaCache { } } + /// Starts a non-blocking, cancellable background read-ahead worker pool that pre-decodes + /// upcoming frames into `MediaCache` while the GPU renders the current frame. + #[cfg(not(target_arch = "wasm32"))] + pub fn start_frame_prefetch(&self, lookahead: usize) -> MediaPrefetchHandle { + MediaPrefetchHandle::spawn(Arc::clone(&self.shared), lookahead.max(1)) + } + #[cfg(not(target_arch = "wasm32"))] fn decode_jobs_parallel(&mut self, mut jobs: MissingJobs) { let mut video_tasks: Vec = jobs .videos .drain() - .map(|(path, requests)| { - let decoder = self - .video_decoders - .get_mut(&path) - .and_then(|entry| entry.decoder.take()); - VideoDecodeTask { - path, - decoder, - requests, - } - }) + .map(|(path, requests)| VideoDecodeTask { path, requests }) .collect(); let video_count = video_tasks.len(); let raster_jobs = jobs.raster; @@ -550,12 +966,6 @@ impl MediaCache { .min(total_units); let next_idx = AtomicUsize::new(0); - let video_slots: Vec< - Mutex>, Vec<(ImageCacheKey, DecodedImage)>)>>, - > = (0..video_count).map(|_| Mutex::new(None)).collect(); - let raster_slots: Vec>> = - (0..raster_jobs.len()).map(|_| Mutex::new(None)).collect(); - let video_inputs: Vec>> = video_tasks.drain(..).map(|t| Mutex::new(Some(t))).collect(); @@ -568,12 +978,8 @@ impl MediaCache { } if idx < video_count { let task = video_inputs[idx].lock().ok().and_then(|mut g| g.take()); - if let Some(mut task) = task { - let mut dec_opt = - task.decoder.take().or_else(|| open_video_decoder(&task.path)); - let mut decoded_frames = Vec::new(); - if let Some(ref mut dec) = dec_opt { - let info = dec.info(); + if let Some(task) = task { + if let Some((info, dec_arc)) = self.shared.get_or_open_video_decoder(&task.path) { let mut seen_local = HashSet::new(); for req in &task.requests { let frame_idx = compute_video_frame_idx( @@ -584,260 +990,640 @@ impl MediaCache { if !seen_local.insert((frame_idx, req.post_multiply)) { continue; } - if let Some(mut raw) = dec.decode_frame(frame_idx) { + let key = ImageCacheKey { + path: task.path.clone(), + frame_idx, + post_multiply: req.post_multiply, + exr_channels: [None, None, None, None], + }; + let cache_gen_opt = self.shared.state.lock().ok().and_then(|mut state| { + if state.images.contains_key(&key) + || state.in_flight.contains(&key) + { + None + } else { + state.in_flight.insert(key.clone()); + Some(state.generation) + } + }); + let Some(cache_gen) = cache_gen_opt else { continue }; + let mut guard = InFlightGuard { + shared: &self.shared, + key: Some(key.clone()), + }; + let decoded_raw = dec_arc + .lock() + .ok() + .and_then(|mut g| g.as_mut()?.decode_frame(frame_idx)); + if let Some(mut raw) = decoded_raw { if req.post_multiply { apply_post_multiply_rgba8_parallel(&mut raw, false); } - let key = ImageCacheKey { - path: task.path.clone(), - frame_idx, - post_multiply: req.post_multiply, - exr_channels: [None, None, None, None], + let decoded = DecodedImage { + size: [info.width, info.height], + rgba: Arc::new(raw), + rgba_f16: None, + rgba_f32: None, }; - decoded_frames.push(( - key, - DecodedImage { - size: [info.width, info.height], - rgba: Arc::new(raw), - rgba_f16: None, - rgba_f32: None, - }, - )); + if let Ok(mut state) = self.shared.state.lock() { + state.in_flight.remove(&key); + guard.key = None; + if state.generation == cache_gen { + state.insert_cached(key, decoded); + } + self.shared.cv.notify_all(); + } } } } - if let Ok(mut slot) = video_slots[idx].lock() { - *slot = Some((task.path, dec_opt, decoded_frames)); - } } } else { let r_idx = idx - video_count; - let decoded = decode_job(&raster_jobs[r_idx], false); - if let Ok(mut slot) = raster_slots[r_idx].lock() { - *slot = decoded; + let job = &raster_jobs[r_idx]; + let cache_gen_opt = self.shared.state.lock().ok().and_then(|mut state| { + if state.images.contains_key(&job.cache_key) + || state.in_flight.contains(&job.cache_key) + { + None + } else { + state.in_flight.insert(job.cache_key.clone()); + Some(state.generation) + } + }); + let Some(cache_gen) = cache_gen_opt else { continue }; + let mut guard = InFlightGuard { + shared: &self.shared, + key: Some(job.cache_key.clone()), + }; + if let Some(decoded) = decode_job(job, false) { + if let Ok(mut state) = self.shared.state.lock() { + state.in_flight.remove(&job.cache_key); + guard.key = None; + if state.generation == cache_gen { + state.known_existing_paths.insert(job.cache_key.path.clone()); + state.insert_cached(job.cache_key.clone(), decoded); + } + self.shared.cv.notify_all(); + } } } }); } }); + } +} + +#[cfg(not(target_arch = "wasm32"))] +struct PrefetchQueueState { + raster: VecDeque<(usize, PreloadJob)>, + videos: HashMap>, + active_videos: HashSet, + queued_raster_keys: HashSet, + current_seq: usize, + lookahead: usize, + cancelled: bool, +} + +#[cfg(not(target_arch = "wasm32"))] +struct PrefetchQueue { + state: Mutex, + cv: Condvar, +} + +#[cfg(not(target_arch = "wasm32"))] +enum PrefetchWorkItem { + Raster(PreloadJob), + Video(PathBuf, VideoFrameRequest), +} - for slot in video_slots { - if let Ok(mut guard) = slot.into_inner() { - if let Some((path, dec_opt, frames)) = guard.take() { - self.put_video_decoder(path, dec_opt); - for (key, img) in frames { - self.insert_cached(key, img); - } - } - } +/// Cancellable background read-ahead handle returned by [`MediaCache::start_frame_prefetch`]. +/// +/// Continuously pre-decodes upcoming frames into [`MediaCache`] while the GPU renders the +/// current frame, and cancels and joins all worker threads cleanly on drop. +#[cfg(not(target_arch = "wasm32"))] +pub struct MediaPrefetchHandle { + shared: Arc, + queue: Arc, + workers: Vec>, +} + +#[cfg(not(target_arch = "wasm32"))] +impl MediaPrefetchHandle { + fn spawn(shared: Arc, lookahead: usize) -> Self { + let queue = Arc::new(PrefetchQueue { + state: Mutex::new(PrefetchQueueState { + raster: VecDeque::new(), + videos: HashMap::new(), + active_videos: HashSet::new(), + queued_raster_keys: HashSet::new(), + current_seq: 0, + lookahead, + cancelled: false, + }), + cv: Condvar::new(), + }); + let worker_count = std::thread::available_parallelism() + .map(|n| n.get().clamp(2, 6)) + .unwrap_or(4); + let mut workers = Vec::with_capacity(worker_count); + for _ in 0..worker_count { + let s = Arc::clone(&shared); + let q = Arc::clone(&queue); + workers.push(std::thread::spawn(move || { + Self::worker_loop(s, q); + })); + } + Self { + shared, + queue, + workers, } - for (job, slot) in raster_jobs.into_iter().zip(raster_slots) { - if let Ok(mut guard) = slot.into_inner() { - if let Some(decoded) = guard.take() { - self.insert_cached(job.cache_key, decoded); - } - } + } + + /// 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 q) = self.queue.state.lock() { + q.current_seq = seq_idx; + self.queue.cv.notify_all(); } } - #[cfg(not(target_arch = "wasm32"))] - #[allow(clippy::too_many_arguments)] - fn collect_missing_loader_jobs( + /// Enqueues missing `Loader` decodes for `time` at sequence index `seq_idx`. + pub fn enqueue_frame( &self, comp: &Comp, - node_id: NodeId, + target: NodeId, + seq_idx: usize, time: f64, expr: &model::ExprEngine, use_proxy_clips: bool, - visited: &mut HashSet<(NodeId, i64)>, - jobs: &mut MissingJobs, ) { - if node_id.0 >= comp.nodes.len() { + let mut visited = HashSet::new(); + let mut jobs = MissingJobs::default(); + collect_missing_loader_jobs_shared( + &self.shared, + comp, + target, + time, + expr, + use_proxy_clips, + &mut visited, + &mut jobs, + ); + if jobs.total_units() == 0 { return; } - let time_key = (if time == 0.0 { 0.0 } else { time }).to_bits() as i64; - if !visited.insert((node_id, time_key)) { - return; - } - let node = comp.node(node_id); - - if node.bypassed - || matches!( - node.kind.as_str(), - "Saver" - | "PipeRouter" - | "Fuse.Wireless" - | "Tracker" - | "Dimension.OpticalFlow" - | "OpticalFlow" - | "Dimension.CopyAux" - ) - { - let port = default_main_input_port(&node.kind); - if let Some(src_id) = node.connected_node(port).and_then(|s| comp.find_node(s)) { - self.collect_missing_loader_jobs( - comp, - src_id, - time, - expr, - use_proxy_clips, - visited, - jobs, - ); + if let Ok(mut q) = self.queue.state.lock() { + if q.cancelled { + return; } - return; + for job in jobs.raster { + if q.queued_raster_keys.insert(job.cache_key.clone()) { + q.raster.push_back((seq_idx, job)); + } + } + for (path, reqs) in jobs.videos { + let vq = q.videos.entry(path).or_default(); + for req in reqs { + vq.push_back((seq_idx, req)); + } + } + self.queue.cv.notify_all(); } + } - if matches!(node.kind.as_str(), "MacroOperator" | "GroupOperator") { - let next_id = node.macro_output.or_else(|| { - node.connected_node("Input") - .or_else(|| node.connected_node("MainInput1")) - .and_then(|s| comp.find_node(s)) - }); - if let Some(src_id) = next_id { - self.collect_missing_loader_jobs( - comp, - src_id, - time, - expr, - use_proxy_clips, - visited, - jobs, - ); - } - return; + /// Cancels pending read-ahead work and joins all background worker threads. + pub fn cancel(&mut self) { + if let Ok(mut q) = self.queue.state.lock() { + q.cancelled = true; + q.raster.clear(); + q.videos.clear(); + q.queued_raster_keys.clear(); + self.queue.cv.notify_all(); } + for handle in self.workers.drain(..) { + let _ = handle.join(); + } + } - if matches!(node.kind.as_str(), "TimeStretcher" | "TimeSpeed") { - let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { - return; - }; - let remapped = match node.kind.as_str() { - "TimeStretcher" => comp.eval_number(node, "SourceTime", time, 0.0, expr), - "TimeSpeed" => { - let speed = comp.eval_number(node, "Speed", time, 1.0, expr); - let delay = comp.eval_number(node, "Delay", time, 0.0, expr); - let g_start = comp.global_range[0] as f64; - let g_end = comp.global_range[1] as f64; - if speed < 0.0 { - ((g_end + 1.0) + (time - delay - g_start) * speed).min(g_end) - } else { - g_start + (time - delay - g_start) * speed + fn worker_loop(shared: Arc, queue: Arc) { + loop { + let item = { + let Ok(mut q) = queue.state.lock() else { return }; + loop { + if q.cancelled { + return; + } + let raster_seq = q.raster.front().map(|(seq, _)| *seq); + let mut best_video: Option<(PathBuf, usize)> = None; + for (path, vq) in &q.videos { + if q.active_videos.contains(path) { + continue; + } + if let Some(&(seq, _)) = vq.front() { + if best_video.as_ref().is_none_or(|&(_, bseq)| seq < bseq) { + best_video = Some((path.clone(), seq)); + } + } + } + + let chosen_seq = match (raster_seq, &best_video) { + (Some(rs), Some((_, vs))) => rs.min(*vs), + (Some(rs), None) => rs, + (None, Some((_, vs))) => *vs, + (None, None) => { + q = match queue.cv.wait(q) { + Ok(g) => g, + Err(_) => return, + }; + continue; + } + }; + + if chosen_seq > q.current_seq.saturating_add(q.lookahead) { + q = match queue.cv.wait(q) { + Ok(g) => g, + Err(_) => return, + }; + continue; + } + + if chosen_seq > q.current_seq.saturating_add(1) { + let over_soft_budget = shared.state.lock().is_ok_and(|s| { + s.budget_bytes > 0 && s.total_bytes >= (s.budget_bytes * 3) / 4 + }); + if over_soft_budget { + q = match queue.cv.wait(q) { + Ok(g) => g, + Err(_) => return, + }; + continue; + } + } + + if let Some((path, vs)) = best_video { + if raster_seq.is_none_or(|rs| vs <= rs) { + if let Some((_, req)) = q.videos.get_mut(&path).and_then(|vq| vq.pop_front()) { + 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); + } + } + } + if let Some((_, job)) = q.raster.pop_front() { + q.queued_raster_keys.remove(&job.cache_key); + break PrefetchWorkItem::Raster(job); } } - _ => time, }; - let interp = comp - .eval_number(node, "InterpolateBetweenFrames", time, 1.0, expr) - .round() as i32; - if interp <= 0 { - let snapped = (remapped + 0.5).floor(); - self.collect_missing_loader_jobs( - comp, - src_id, - snapped, - expr, - use_proxy_clips, - visited, - jobs, - ); - return; + + match item { + PrefetchWorkItem::Raster(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) + { + None + } else { + state.in_flight.insert(job.cache_key.clone()); + Some(state.generation) + } + }); + let Some(cache_gen) = cache_gen_opt else { continue }; + let mut guard = InFlightGuard { + shared: &shared, + key: Some(job.cache_key.clone()), + }; + if let Some(decoded) = decode_job(&job, false) { + if let Ok(mut state) = shared.state.lock() { + state.in_flight.remove(&job.cache_key); + guard.key = None; + if state.generation == cache_gen { + state.known_existing_paths.insert(job.cache_key.path.clone()); + state.insert_cached(job.cache_key, decoded); + } + shared.cv.notify_all(); + } + } + } + PrefetchWorkItem::Video(path, req) => { + struct ActiveVideoGuard<'a> { + queue: &'a PrefetchQueue, + path: PathBuf, + } + impl Drop for ActiveVideoGuard<'_> { + fn drop(&mut self) { + if let Ok(mut q) = self.queue.state.lock() { + q.active_videos.remove(&self.path); + self.queue.cv.notify_all(); + } + } + } + let _active_guard = ActiveVideoGuard { + queue: &queue, + path: path.clone(), + }; + + let Some((info, dec_arc)) = shared.get_or_open_video_decoder(&path) else { + continue; + }; + let frame_idx = + compute_video_frame_idx(&req.clip, req.frame_i, info.nb_frames); + let key = ImageCacheKey { + path: path.clone(), + frame_idx, + post_multiply: req.post_multiply, + exr_channels: [None, None, None, None], + }; + let cache_gen_opt = shared.state.lock().ok().and_then(|mut state| { + if state.images.contains_key(&key) || state.in_flight.contains(&key) { + None + } else { + state.in_flight.insert(key.clone()); + Some(state.generation) + } + }); + let Some(cache_gen) = cache_gen_opt else { continue }; + let mut guard = InFlightGuard { + shared: &shared, + key: Some(key.clone()), + }; + let decoded_raw = dec_arc + .lock() + .ok() + .and_then(|mut g| g.as_mut()?.decode_frame(frame_idx)); + if let Some(mut raw) = decoded_raw { + if req.post_multiply { + apply_post_multiply_rgba8_parallel(&mut raw, false); + } + let decoded = DecodedImage { + size: [info.width, info.height], + rgba: Arc::new(raw), + rgba_f16: None, + rgba_f32: None, + }; + if let Ok(mut state) = shared.state.lock() { + state.in_flight.remove(&key); + guard.key = None; + if state.generation == cache_gen { + state.insert_cached(key, decoded); + } + shared.cv.notify_all(); + } + } + } } - let f0 = remapped.floor(); - let frac = (remapped - f0) as f32; - if frac > 1e-3 && frac < 1.0 - 1e-3 { - let src_node = comp.node(src_id); - let has_optflow = matches!(src_node.kind.as_str(), "Dimension.OpticalFlow" | "OpticalFlow"); - let eval_src_id = if has_optflow { - src_node - .connected_node("Input") - .and_then(|s| comp.find_node(s)) - .unwrap_or(src_id) + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +impl Drop for MediaPrefetchHandle { + fn drop(&mut self) { + self.cancel(); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[allow(clippy::too_many_arguments)] +fn collect_missing_loader_jobs_shared( + shared: &MediaShared, + comp: &Comp, + node_id: NodeId, + time: f64, + expr: &model::ExprEngine, + use_proxy_clips: bool, + visited: &mut HashSet<(NodeId, i64)>, + jobs: &mut MissingJobs, +) { + if node_id.0 >= comp.nodes.len() { + return; + } + let time_key = (if time == 0.0 { 0.0 } else { time }).to_bits() as i64; + if !visited.insert((node_id, time_key)) { + return; + } + let node = comp.node(node_id); + + if node.bypassed + || matches!( + node.kind.as_str(), + "Saver" + | "PipeRouter" + | "Fuse.Wireless" + | "Tracker" + | "Dimension.OpticalFlow" + | "OpticalFlow" + | "Dimension.CopyAux" + ) + { + let port = default_main_input_port(&node.kind); + if let Some(src_id) = node.connected_node(port).and_then(|s| comp.find_node(s)) { + collect_missing_loader_jobs_shared( + shared, + comp, + src_id, + time, + expr, + use_proxy_clips, + visited, + jobs, + ); + } + return; + } + + if matches!(node.kind.as_str(), "MacroOperator" | "GroupOperator") { + let next_id = node.macro_output.or_else(|| { + node.connected_node("Input") + .or_else(|| node.connected_node("MainInput1")) + .and_then(|s| comp.find_node(s)) + }); + if let Some(src_id) = next_id { + collect_missing_loader_jobs_shared( + shared, + comp, + src_id, + time, + expr, + use_proxy_clips, + visited, + jobs, + ); + } + return; + } + + if matches!(node.kind.as_str(), "TimeStretcher" | "TimeSpeed") { + let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { + return; + }; + let remapped = match node.kind.as_str() { + "TimeStretcher" => comp.eval_number(node, "SourceTime", time, 0.0, expr), + "TimeSpeed" => { + let speed = comp.eval_number(node, "Speed", time, 1.0, expr); + let delay = comp.eval_number(node, "Delay", time, 0.0, expr); + let g_start = comp.global_range[0] as f64; + let g_end = comp.global_range[1] as f64; + if speed < 0.0 { + ((g_end + 1.0) + (time - delay - g_start) * speed).min(g_end) } else { - src_id - }; - self.collect_missing_loader_jobs( - comp, - eval_src_id, - f0, - expr, - use_proxy_clips, - visited, - jobs, - ); - self.collect_missing_loader_jobs( - comp, - eval_src_id, - f0 + 1.0, - expr, - use_proxy_clips, - visited, - jobs, - ); - } else { - self.collect_missing_loader_jobs( - comp, - src_id, - remapped, - expr, - use_proxy_clips, - visited, - jobs, - ); + g_start + (time - delay - g_start) * speed + } } + _ => time, + }; + let interp = comp + .eval_number(node, "InterpolateBetweenFrames", time, 1.0, expr) + .round() as i32; + if interp <= 0 { + let snapped = (remapped + 0.5).floor(); + collect_missing_loader_jobs_shared( + shared, + comp, + src_id, + snapped, + expr, + use_proxy_clips, + visited, + jobs, + ); return; } - - if node.kind == "Switch" || node.kind == "Fuse.Switch" { - let is_native_zero_indexed = node.kind == "Switch" - && (node.inputs.contains_key("Source") - || node.inputs.contains_key("Input0") - || !node.inputs.contains_key("Which")); - let src_name = if is_native_zero_indexed { - let source = comp - .eval_number(node, "Source", time, 0.0, expr) - .round() - .max(0.0) as usize; - let port = format!("Input{source}"); - node.connected_node(&port) - .or_else(|| node.connected_node("Input0")) - } else { - let which = comp - .eval_number(node, "Which", time, 1.0, expr) - .round() - .max(1.0) as usize; - let port = format!("Input{which}"); - node.connected_node(&port) - .or_else(|| node.connected_node("Input1")) - }; - if let Some(src_id) = src_name.and_then(|s| comp.find_node(s)) { - self.collect_missing_loader_jobs( - comp, - src_id, - time, - expr, - use_proxy_clips, - visited, - jobs, - ); - } - return; - } - - if node.kind == "Fuse.SwitchElse" { - let index = |name: &str, default: f64| { - comp.eval_number(node, name, time, default, expr) - .round() - .max(1.0) as usize - }; - let picked = [index("Switch", 1.0), index("Else", 2.0)].into_iter().find_map(|i| { - node.connected_node(&format!("Input{i}")) + let f0 = remapped.floor(); + let frac = (remapped - f0) as f32; + if frac > 1e-3 && frac < 1.0 - 1e-3 { + let src_node = comp.node(src_id); + let has_optflow = matches!(src_node.kind.as_str(), "Dimension.OpticalFlow" | "OpticalFlow"); + let eval_src_id = if has_optflow { + src_node + .connected_node("Input") .and_then(|s| comp.find_node(s)) - }); - if let Some(src_id) = picked { - self.collect_missing_loader_jobs( + .unwrap_or(src_id) + } else { + src_id + }; + collect_missing_loader_jobs_shared( + shared, + comp, + eval_src_id, + f0, + expr, + use_proxy_clips, + visited, + jobs, + ); + collect_missing_loader_jobs_shared( + shared, + comp, + eval_src_id, + f0 + 1.0, + expr, + use_proxy_clips, + visited, + jobs, + ); + } else { + collect_missing_loader_jobs_shared( + shared, + comp, + src_id, + remapped, + expr, + use_proxy_clips, + visited, + jobs, + ); + } + return; + } + + if node.kind == "Switch" || node.kind == "Fuse.Switch" { + let is_native_zero_indexed = node.kind == "Switch" + && (node.inputs.contains_key("Source") + || node.inputs.contains_key("Input0") + || !node.inputs.contains_key("Which")); + let src_name = if is_native_zero_indexed { + let source = comp + .eval_number(node, "Source", time, 0.0, expr) + .round() + .max(0.0) as usize; + let port = format!("Input{source}"); + node.connected_node(&port) + .or_else(|| node.connected_node("Input0")) + } else { + let which = comp + .eval_number(node, "Which", time, 1.0, expr) + .round() + .max(1.0) as usize; + let port = format!("Input{which}"); + node.connected_node(&port) + .or_else(|| node.connected_node("Input1")) + }; + if let Some(src_id) = src_name.and_then(|s| comp.find_node(s)) { + collect_missing_loader_jobs_shared( + shared, + comp, + src_id, + time, + expr, + use_proxy_clips, + visited, + jobs, + ); + } + return; + } + + if node.kind == "Fuse.SwitchElse" { + let index = |name: &str, default: f64| { + comp.eval_number(node, name, time, default, expr) + .round() + .max(1.0) as usize + }; + let picked = [index("Switch", 1.0), index("Else", 2.0)].into_iter().find_map(|i| { + node.connected_node(&format!("Input{i}")) + .and_then(|s| comp.find_node(s)) + }); + if let Some(src_id) = picked { + collect_missing_loader_jobs_shared( + shared, + comp, + src_id, + time, + expr, + use_proxy_clips, + visited, + jobs, + ); + } + return; + } + + if node.kind == "Merge" { + if let Some(bg_id) = node.connected_node("Background").and_then(|s| comp.find_node(s)) { + collect_missing_loader_jobs_shared( + shared, + comp, + bg_id, + time, + expr, + use_proxy_clips, + visited, + jobs, + ); + } + let blend = comp.eval_number(node, "Blend", time, 1.0, expr) as f32; + let mbm = comp.eval_number(node, "MultiplyByMask", time, 0.0, expr) > 0.5; + let mask_id = resolve_effect_mask_id_for_node(comp, node); + if !(blend <= 1e-6 && !(mbm && node.connected_node("EffectMask").is_some())) { + if let Some(fg_id) = node.connected_node("Foreground").and_then(|s| comp.find_node(s)) { + collect_missing_loader_jobs_shared( + shared, comp, - src_id, + fg_id, time, expr, use_proxy_clips, @@ -845,117 +1631,91 @@ impl MediaCache { jobs, ); } - return; } + if let Some(mid) = mask_id { + collect_missing_loader_jobs_shared( + shared, + comp, + mid, + time, + expr, + use_proxy_clips, + visited, + jobs, + ); + } + return; + } - if node.kind == "Merge" { - if let Some(bg_id) = node.connected_node("Background").and_then(|s| comp.find_node(s)) { - self.collect_missing_loader_jobs( - comp, - bg_id, + if node.kind == "Loader" { + if let Some(clip) = node.clips.first() { + let frame_i = time.round() as i64; + let post_mult = node.static_number("Clip1.PNGFormat.PostMultiply").unwrap_or(0.0) > 0.5; + let exr_channels = [ + node.static_str("Clip1.OpenEXRFormat.RedName"), + node.static_str("Clip1.OpenEXRFormat.GreenName"), + node.static_str("Clip1.OpenEXRFormat.BlueName"), + node.static_str("Clip1.OpenEXRFormat.AlphaName"), + ]; + let mut effective_clip = clip.clone(); + if node.inputs.contains_key("GlobalIn") { + effective_clip.global_start = comp + .eval_number(node, "GlobalIn", time, effective_clip.global_start as f64, expr) + .round() as i64; + } + if node.inputs.contains_key("GlobalOut") { + effective_clip.global_end = comp + .eval_number(node, "GlobalOut", time, effective_clip.global_end as f64, expr) + .round() as i64; + } + if node.inputs.contains_key("Loop") { + effective_clip.loop_clip = comp.eval_number( + node, + "Loop", time, + if effective_clip.loop_clip { 1.0 } else { 0.0 }, expr, - use_proxy_clips, - visited, - jobs, - ); + ) > 0.5; } - let blend = comp.eval_number(node, "Blend", time, 1.0, expr) as f32; - let mbm = comp.eval_number(node, "MultiplyByMask", time, 0.0, expr) > 0.5; - let mask_id = resolve_effect_mask_id_for_node(comp, node); - if !(blend <= 1e-6 && !(mbm && node.connected_node("EffectMask").is_some())) { - if let Some(fg_id) = node.connected_node("Foreground").and_then(|s| comp.find_node(s)) { - self.collect_missing_loader_jobs( - comp, - fg_id, - time, - expr, - use_proxy_clips, - visited, - jobs, - ); - } - } - if let Some(mid) = mask_id { - self.collect_missing_loader_jobs( - comp, - mid, + if node.inputs.contains_key("Reverse") { + effective_clip.reverse = comp.eval_number( + node, + "Reverse", time, + if effective_clip.reverse { 1.0 } else { 0.0 }, expr, - use_proxy_clips, - visited, - jobs, - ); + ) > 0.5; } - return; - } - - if node.kind == "Loader" { - if let Some(clip) = node.clips.first() { - let frame_i = time.round() as i64; - let post_mult = node.static_number("Clip1.PNGFormat.PostMultiply").unwrap_or(0.0) > 0.5; - let exr_channels = [ - node.static_str("Clip1.OpenEXRFormat.RedName"), - node.static_str("Clip1.OpenEXRFormat.GreenName"), - node.static_str("Clip1.OpenEXRFormat.BlueName"), - node.static_str("Clip1.OpenEXRFormat.AlphaName"), - ]; - let mut effective_clip = clip.clone(); - if node.inputs.contains_key("GlobalIn") { - effective_clip.global_start = comp - .eval_number(node, "GlobalIn", time, effective_clip.global_start as f64, expr) - .round() as i64; - } - if node.inputs.contains_key("GlobalOut") { - effective_clip.global_end = comp - .eval_number(node, "GlobalOut", time, effective_clip.global_end as f64, expr) - .round() as i64; - } - if node.inputs.contains_key("Loop") { - effective_clip.loop_clip = comp.eval_number( - node, - "Loop", - time, - if effective_clip.loop_clip { 1.0 } else { 0.0 }, - expr, - ) > 0.5; - } - if node.inputs.contains_key("Reverse") { - effective_clip.reverse = comp.eval_number( - node, - "Reverse", - time, - if effective_clip.reverse { 1.0 } else { 0.0 }, - expr, - ) > 0.5; - } - if use_proxy_clips { - let proxy_candidate = node - .static_str("ProxyFilename") - .filter(|s| !s.trim().is_empty()) - .or_else(|| clip.alternate_filename.as_deref().filter(|s| !s.trim().is_empty())); - if let Some(proxy_name) = proxy_candidate { - let mut proxy_clip = effective_clip.clone(); - proxy_clip.filename = proxy_name.to_owned(); - if resolve_clip_path(&proxy_clip, frame_i).is_some_and(|p| path_exists(&p)) { - effective_clip = proxy_clip; - } + if use_proxy_clips { + let proxy_candidate = node + .static_str("ProxyFilename") + .filter(|s| !s.trim().is_empty()) + .or_else(|| clip.alternate_filename.as_deref().filter(|s| !s.trim().is_empty())); + if let Some(proxy_name) = proxy_candidate { + let mut proxy_clip = effective_clip.clone(); + proxy_clip.filename = proxy_name.to_owned(); + if shared.resolve_clip_path_cached(&proxy_clip, frame_i).is_some() { + effective_clip = proxy_clip; } } - let out_of_range = effective_clip.global_end >= effective_clip.global_start - && (frame_i < effective_clip.global_start - effective_clip.extend_first.max(0) - || (!effective_clip.loop_clip - && frame_i > effective_clip.global_end + effective_clip.extend_last.max(0))); - if !out_of_range { - let base = Path::new(&effective_clip.filename); - if is_video_path(base) { - if base.exists() && video_frame_in_range(&effective_clip, frame_i) { - let need_decode = match self.video_decoders.get(base) { - Some(entry) => entry.decoder.as_ref().is_some_and(|dec| { + } + let out_of_range = effective_clip.global_end >= effective_clip.global_start + && (frame_i < effective_clip.global_start - effective_clip.extend_first.max(0) + || (!effective_clip.loop_clip + && frame_i > effective_clip.global_end + effective_clip.extend_last.max(0))); + if !out_of_range { + let base = Path::new(&effective_clip.filename); + if is_video_path(base) { + if video_frame_in_range(&effective_clip, frame_i) + && shared.path_exists_cached(base) + { + let need_decode = shared.state.lock().is_ok_and(|state| { + match state.video_decoders.get(base) { + Some(slot) => slot.info.is_some_and(|info| { let idx = compute_video_frame_idx( &effective_clip, frame_i, - dec.info().nb_frames, + info.nb_frames, ); let cache_key = ImageCacheKey { path: base.to_path_buf(), @@ -963,81 +1723,60 @@ impl MediaCache { post_multiply: post_mult, exr_channels: [None, None, None, None], }; - !self.images.contains_key(&cache_key) + !state.images.contains_key(&cache_key) + && !state.in_flight.contains(&cache_key) }), None => true, - }; - if need_decode { - jobs.videos - .entry(base.to_path_buf()) - .or_default() - .push(VideoFrameRequest { - clip: effective_clip, - frame_i, - post_multiply: post_mult, - }); } - } - } else if let Some(resolved) = resolve_clip_path(&effective_clip, frame_i) { - let is_exr = is_exr_path(&resolved); - let key_channels = if is_exr { - [ - normalize_channel_opt(exr_channels[0]), - normalize_channel_opt(exr_channels[1]), - normalize_channel_opt(exr_channels[2]), - normalize_channel_opt(exr_channels[3]), - ] - } else { - [None, None, None, None] - }; - let cache_key = ImageCacheKey { - path: resolved, - frame_idx: -1, - post_multiply: post_mult && !is_exr, - exr_channels: key_channels, - }; - if !self.images.contains_key(&cache_key) - && jobs.seen_raster.insert(cache_key.clone()) - { - jobs.raster.push(PreloadJob { cache_key, is_exr }); + }); + if need_decode { + jobs.videos + .entry(base.to_path_buf()) + .or_default() + .push(VideoFrameRequest { + clip: effective_clip, + frame_i, + post_multiply: post_mult, + }); } } - } - } - if let Some(mid) = resolve_effect_mask_id_for_node(comp, node) { - self.collect_missing_loader_jobs( - comp, - mid, - time, - expr, - use_proxy_clips, - visited, - jobs, - ); - } - return; - } - - // General node: traverse all wired upstream node inputs and inherited EffectMask. - let mut child_ids = Vec::new(); - for binding in node.inputs.values() { - if let Some(src) = binding.source_op.as_deref() { - if let Some(cid) = comp.find_node(src) { - if !child_ids.contains(&cid) { - child_ids.push(cid); + } else if let Some(resolved) = resolve_clip_candidate_path(&effective_clip, frame_i) { + let is_exr = is_exr_path(&resolved); + let key_channels = if is_exr { + [ + normalize_channel_opt(exr_channels[0]), + normalize_channel_opt(exr_channels[1]), + normalize_channel_opt(exr_channels[2]), + normalize_channel_opt(exr_channels[3]), + ] + } else { + [None, None, None, None] + }; + let cache_key = ImageCacheKey { + path: resolved.clone(), + frame_idx: -1, + post_multiply: post_mult && !is_exr, + exr_channels: key_channels, + }; + let missing = shared.state.lock().is_ok_and(|state| { + !state.images.contains_key(&cache_key) + && !state.in_flight.contains(&cache_key) + }); + if missing + && !jobs.seen_raster.contains(&cache_key) + && shared.path_exists_cached(&resolved) + { + jobs.seen_raster.insert(cache_key.clone()); + jobs.raster.push(PreloadJob { cache_key, is_exr }); } } } } if let Some(mid) = resolve_effect_mask_id_for_node(comp, node) { - if !child_ids.contains(&mid) { - child_ids.push(mid); - } - } - for cid in child_ids { - self.collect_missing_loader_jobs( + collect_missing_loader_jobs_shared( + shared, comp, - cid, + mid, time, expr, use_proxy_clips, @@ -1045,6 +1784,36 @@ impl MediaCache { jobs, ); } + return; + } + + // General node: traverse all wired upstream node inputs and inherited EffectMask. + let mut child_ids = Vec::new(); + for binding in node.inputs.values() { + if let Some(src) = binding.source_op.as_deref() { + if let Some(cid) = comp.find_node(src) { + if !child_ids.contains(&cid) { + child_ids.push(cid); + } + } + } + } + if let Some(mid) = resolve_effect_mask_id_for_node(comp, node) { + if !child_ids.contains(&mid) { + child_ids.push(mid); + } + } + for cid in child_ids { + collect_missing_loader_jobs_shared( + shared, + comp, + cid, + time, + expr, + use_proxy_clips, + visited, + jobs, + ); } } @@ -1103,7 +1872,6 @@ struct VideoFrameRequest { #[cfg(not(target_arch = "wasm32"))] struct VideoDecodeTask { path: PathBuf, - decoder: Option>, requests: Vec, } @@ -1168,8 +1936,7 @@ fn resolve_effect_mask_id_for_node(comp: &Comp, node: &Node) -> Option { None } -/// Resolves a Fusion `ClipSpec` (still image or numbered image sequence) at `frame`. -pub fn resolve_clip_path(clip: &ClipSpec, frame: i64) -> Option { +fn resolve_clip_candidate_path(clip: &ClipSpec, frame: i64) -> Option { let base = Path::new(&clip.filename); let len = clip.length.unwrap_or(1); let stem = base.file_stem()?.to_str()?; @@ -1179,7 +1946,7 @@ pub fn resolve_clip_path(clip: &ClipSpec, frame: i64) -> Option { let digits = &stem[digit_start..]; let is_seq = len > 1 && (clip.start_frame >= 0 || !digits.is_empty()); if !is_seq || digits.is_empty() { - return path_exists(base).then(|| base.to_path_buf()); + return Some(base.to_path_buf()); } let seq_start = if clip.start_frame >= 0 { clip.start_frame } else { 0 }; @@ -1206,7 +1973,12 @@ pub fn resolve_clip_path(clip: &ClipSpec, frame: i64) -> Option { } else { format!("{prefix}{idx:0width$}.{ext}") }; - let candidate = base.with_file_name(new_name); + Some(base.with_file_name(new_name)) +} + +/// Resolves a Fusion `ClipSpec` (still image or numbered image sequence) at `frame`. +pub fn resolve_clip_path(clip: &ClipSpec, frame: i64) -> Option { + let candidate = resolve_clip_candidate_path(clip, frame)?; path_exists(&candidate).then_some(candidate) } #[cfg(test)] @@ -1823,11 +2595,14 @@ mod tests { assert_eq!(media_cache_budget_mb_for_total_bytes(128 * GIB), 8192); let default_cache = MediaCache::default(); assert_eq!( - default_cache.budget_bytes, + default_cache.shared.state.lock().unwrap().budget_bytes, default_media_cache_budget_mb().saturating_mul(1024 * 1024) ); let explicit = MediaCache::with_budget_mb(32); - assert_eq!(explicit.budget_bytes, 32 * 1024 * 1024); + assert_eq!( + explicit.shared.state.lock().unwrap().budget_bytes, + 32 * 1024 * 1024 + ); } #[test] @@ -2061,4 +2836,68 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn background_frame_prefetch_populates_and_cancels_cleanly() { + let dir = std::env::temp_dir().join(format!("fission_bg_prefetch_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + + for i in 0..4 { + let p = dir.join(format!("seq_{i:04}.png")); + image::RgbaImage::from_pixel(4, 4, image::Rgba([i as u8 * 50, 10, 200, 255])) + .save(&p) + .unwrap(); + } + let esc = |p: &Path| p.to_string_lossy().replace('\\', "\\\\"); + let p0 = dir.join("seq_0000.png"); + let comp_src = format!( + r#"Composition {{ + CurrentTime = 0, + RenderRange = {{ 0, 3 }}, + GlobalRange = {{ 0, 3 }}, + Tools = ordered() {{ + LD = Loader {{ + Clips = {{ + Clip {{ + ID = "Clip1", + Filename = "{}", + FormatID = "PNGFormat", + StartFrame = 0, + Length = 4, + GlobalStart = 0, + GlobalEnd = 3, + }}, + }}, + }}, + }}, +}}"#, + esc(&p0) + ); + let comp = Comp::from_fusion_str(&comp_src).expect("parse bg prefetch comp"); + let target = comp.find_node("LD").unwrap(); + let clip = comp.node(target).clips[0].clone(); + let expr = model::ExprEngine::new(); + let mut cache = MediaCache::new(64); + + let mut handle = cache.start_frame_prefetch(4); + for f in 0..=3 { + handle.enqueue_frame(&comp, target, f, f as f64, &expr, false); + } + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + while cache.entry_count() < 4 && std::time::Instant::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert_eq!(cache.entry_count(), 4); + for f in 0..=3 { + let (_, _, img, from_disk) = cache.load_clip(&clip, f, false, [None; 4]).unwrap(); + assert!(!from_disk, "frame {f} should already be in MediaCache"); + assert_eq!(img.rgba[0], (f as u8) * 50); + } + handle.cancel(); + drop(handle); + + let _ = std::fs::remove_dir_all(&dir); + } }