diff --git a/crates/engine/src/media.rs b/crates/engine/src/media.rs index 834ad35ba3e2d72c732aa8f209afa8e203be4165..5dc06c93abb5a4de47b03d5d548a5888a20573f2 100644 --- a/crates/engine/src/media.rs +++ b/crates/engine/src/media.rs @@ -2,10 +2,16 @@ //! CPU rasterizers (`TextPlus` via `text_engine`, `PolylineMask` via `zeno`). mod exr; +mod png; +mod prefetch; mod raster; +#[cfg(test)] +mod tests; mod video; pub use exr::f32_to_f16_bits; +#[cfg(not(target_arch = "wasm32"))] +pub use prefetch::MediaPrefetchHandle; pub use raster::{TextPlusParams, rasterize_polyline_mask, rasterize_text_plus}; #[cfg(target_os = "macos")] pub use video::AvFoundationDecoder; @@ -14,6 +20,11 @@ use exr::{ apply_post_multiply_rgba8, apply_post_multiply_rgba8_parallel, decode_exr_rgba, is_exr_path, normalize_channel_opt, }; +use png::decode_raster_image; +#[cfg(test)] +use png::{PngDecodeOutcome, decode_png_bytes, decode_raster_bytes}; +#[cfg(not(target_arch = "wasm32"))] +use prefetch::PrefetchQueue; use video::is_video_path; use crate::text_engine; @@ -129,254 +140,6 @@ fn path_exists(path: &Path) -> bool { virtual_bytes(path).is_some() || path.exists() } -#[inline(always)] -fn u16_be_to_u8_rounded(hi: u8, lo: u8) -> u8 { - ((u16::from_be_bytes([hi, lo]) as u32 + 128) / 257) as u8 -} - -const MAX_PNG_OUTPUT_BYTES: usize = 512 * 1024 * 1024; - -enum PngDecodeOutcome { - Decoded(([u32; 2], Vec, bool)), - Fallback, - Reject, -} - -fn decode_png_rows( - reader: &mut png::Reader, - line_size: usize, - out_len: usize, - row_out_bytes: usize, - mut convert_row: F, -) -> Option> -where - F: FnMut(&[u8], &mut [u8]), -{ - let mut rgba = Vec::new(); - rgba.try_reserve_exact(out_len).ok()?; - rgba.resize(out_len, 0); - let mut row_buf = Vec::new(); - row_buf.try_reserve_exact(line_size).ok()?; - row_buf.resize(line_size, 0); - for dst_row in rgba.chunks_exact_mut(row_out_bytes) { - reader.read_row(&mut row_buf).ok()??; - convert_row(&row_buf, dst_row); - } - Some(rgba) -} - -/// Fast direct PNG decoder matching `image::load_from_memory().into_rgba8()` bit-for-bit. -/// Returns `Fallback` for non-PNG, interlaced, animated, ICC-tagged, or unusual formats so the -/// caller falls back cleanly to `image::load_from_memory`, and `Reject` for corrupt or -/// oversized PNGs so callers fail immediately without double-decoding or OOM. -fn decode_png_bytes(bytes: &[u8]) -> PngDecodeOutcome { - const PNG_SIGNATURE: [u8; 8] = [137, 80, 78, 71, 13, 10, 26, 10]; - if !bytes.starts_with(&PNG_SIGNATURE) { - return PngDecodeOutcome::Fallback; - } - - let mut decoder = png::Decoder::new_with_limits( - std::io::Cursor::new(bytes), - png::Limits { - bytes: MAX_PNG_OUTPUT_BYTES, - }, - ); - decoder.set_ignore_text_chunk(true); - decoder.set_transformations(png::Transformations::EXPAND); - - let Ok(mut reader) = decoder.read_info() else { - return PngDecodeOutcome::Reject; - }; - let info = reader.info(); - let (w, h) = info.size(); - if w == 0 || h == 0 { - return PngDecodeOutcome::Reject; - } - - let Some(pixel_count) = (w as usize).checked_mul(h as usize) else { - return PngDecodeOutcome::Reject; - }; - let Some(out_len) = pixel_count.checked_mul(4) else { - return PngDecodeOutcome::Reject; - }; - if out_len > MAX_PNG_OUTPUT_BYTES { - return PngDecodeOutcome::Reject; - } - - if info.interlaced - || info.icc_profile.is_some() - || info.animation_control.is_some() - || info.frame_control.is_some() - { - return PngDecodeOutcome::Fallback; - } - - let (color_type, bit_depth) = reader.output_color_type(); - let Some(row_out_bytes) = (w as usize).checked_mul(4) else { - return PngDecodeOutcome::Reject; - }; - let Some(line_size) = reader.output_line_size(w) else { - return PngDecodeOutcome::Reject; - }; - - match (color_type, bit_depth) { - (png::ColorType::Rgba, png::BitDepth::Eight) => { - let mut rgba = Vec::new(); - if rgba.try_reserve_exact(out_len).is_err() { - return PngDecodeOutcome::Reject; - } - rgba.resize(out_len, 0); - if reader.next_frame(&mut rgba).is_err() { - return PngDecodeOutcome::Reject; - } - PngDecodeOutcome::Decoded(([w, h], rgba, true)) - } - (png::ColorType::Rgb, png::BitDepth::Eight) => { - let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| { - let (src_chunks, _) = src.as_chunks::<3>(); - let (dst_chunks, _) = dst.as_chunks_mut::<4>(); - for (&[r, g, b], dst_px) in src_chunks.iter().zip(dst_chunks) { - *dst_px = [r, g, b, 255]; - } - }) else { - return PngDecodeOutcome::Reject; - }; - PngDecodeOutcome::Decoded(([w, h], rgba, false)) - } - (png::ColorType::Grayscale, png::BitDepth::Eight) => { - let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| { - let (dst_chunks, _) = dst.as_chunks_mut::<4>(); - for (&g, dst_px) in src.iter().zip(dst_chunks) { - *dst_px = [g, g, g, 255]; - } - }) else { - return PngDecodeOutcome::Reject; - }; - PngDecodeOutcome::Decoded(([w, h], rgba, false)) - } - (png::ColorType::GrayscaleAlpha, png::BitDepth::Eight) => { - let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| { - let (src_chunks, _) = src.as_chunks::<2>(); - let (dst_chunks, _) = dst.as_chunks_mut::<4>(); - for (&[g, a], dst_px) in src_chunks.iter().zip(dst_chunks) { - *dst_px = [g, g, g, a]; - } - }) else { - return PngDecodeOutcome::Reject; - }; - PngDecodeOutcome::Decoded(([w, h], rgba, true)) - } - (png::ColorType::Rgba, png::BitDepth::Sixteen) => { - let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| { - let (src_chunks, _) = src.as_chunks::<8>(); - let (dst_chunks, _) = dst.as_chunks_mut::<4>(); - for (&s, dst_px) in src_chunks.iter().zip(dst_chunks) { - *dst_px = [ - u16_be_to_u8_rounded(s[0], s[1]), - u16_be_to_u8_rounded(s[2], s[3]), - u16_be_to_u8_rounded(s[4], s[5]), - u16_be_to_u8_rounded(s[6], s[7]), - ]; - } - }) else { - return PngDecodeOutcome::Reject; - }; - PngDecodeOutcome::Decoded(([w, h], rgba, true)) - } - (png::ColorType::Rgb, png::BitDepth::Sixteen) => { - let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| { - let (src_chunks, _) = src.as_chunks::<6>(); - let (dst_chunks, _) = dst.as_chunks_mut::<4>(); - for (&s, dst_px) in src_chunks.iter().zip(dst_chunks) { - *dst_px = [ - u16_be_to_u8_rounded(s[0], s[1]), - u16_be_to_u8_rounded(s[2], s[3]), - u16_be_to_u8_rounded(s[4], s[5]), - 255, - ]; - } - }) else { - return PngDecodeOutcome::Reject; - }; - PngDecodeOutcome::Decoded(([w, h], rgba, false)) - } - (png::ColorType::Grayscale, png::BitDepth::Sixteen) => { - let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| { - let (src_chunks, _) = src.as_chunks::<2>(); - let (dst_chunks, _) = dst.as_chunks_mut::<4>(); - for (&[hi, lo], dst_px) in src_chunks.iter().zip(dst_chunks) { - let g = u16_be_to_u8_rounded(hi, lo); - *dst_px = [g, g, g, 255]; - } - }) else { - return PngDecodeOutcome::Reject; - }; - PngDecodeOutcome::Decoded(([w, h], rgba, false)) - } - (png::ColorType::GrayscaleAlpha, png::BitDepth::Sixteen) => { - let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| { - let (src_chunks, _) = src.as_chunks::<4>(); - let (dst_chunks, _) = dst.as_chunks_mut::<4>(); - for (&s, dst_px) in src_chunks.iter().zip(dst_chunks) { - let g = u16_be_to_u8_rounded(s[0], s[1]); - *dst_px = [g, g, g, u16_be_to_u8_rounded(s[2], s[3])]; - } - }) else { - return PngDecodeOutcome::Reject; - }; - PngDecodeOutcome::Decoded(([w, h], rgba, true)) - } - _ => PngDecodeOutcome::Fallback, - } -} - -fn decode_raster_bytes(bytes: &[u8]) -> Option<([u32; 2], Vec, bool)> { - match decode_png_bytes(bytes) { - PngDecodeOutcome::Decoded(decoded) => return Some(decoded), - PngDecodeOutcome::Reject => return None, - PngDecodeOutcome::Fallback => {} - } - let dyn_img = image::load_from_memory(bytes).ok()?; - let has_alpha = dyn_img.color().has_alpha(); - let size = [dyn_img.width(), dyn_img.height()]; - let raw = dyn_img.into_rgba8().into_raw(); - Some((size, raw, has_alpha)) -} - -fn open_raster_rgba(path: &Path) -> Option<([u32; 2], Vec, bool)> { - if let Some(bytes) = virtual_bytes(path) { - return decode_raster_bytes(&bytes); - } - // Read file contents in one contiguous pass to avoid tiny buffered syscalls over SMB/network shares. - match std::fs::read(path) { - Ok(bytes) => return decode_raster_bytes(&bytes), - Err(e) if e.kind() == std::io::ErrorKind::NotFound => return None, - Err(_) => {} - } - let dyn_img = image::open(path).ok()?; - let has_alpha = dyn_img.color().has_alpha(); - let size = [dyn_img.width(), dyn_img.height()]; - let raw = dyn_img.into_rgba8().into_raw(); - Some((size, raw, has_alpha)) -} - -fn decode_raster_image( - path: &Path, - post_multiply: bool, - allow_parallel_premult: bool, -) -> Option { - let (size, mut raw, has_alpha) = open_raster_rgba(path)?; - if post_multiply && has_alpha { - apply_post_multiply_rgba8_parallel(&mut raw, allow_parallel_premult); - } - Some(DecodedImage { - size, - rgba: Arc::new(raw), - rgba_f16: None, - rgba_f32: None, - }) -} - pub(crate) fn media_cache_budget_mb_for_total_bytes(total_bytes: u64) -> u64 { let gib = total_bytes / (1024 * 1024 * 1024); if gib >= 128 { @@ -481,37 +244,6 @@ impl MediaState { let _ = path; } - #[cfg(not(target_arch = "wasm32"))] - 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) { let bytes = decoded.byte_size(); self.tick += 1; @@ -594,51 +326,6 @@ impl MediaShared { } } - fn sync_lookahead_throttle(&self, state: &MediaState) -> bool { - #[cfg(not(target_arch = "wasm32"))] - { - 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; - 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( &self, state: &mut MediaState, @@ -1263,1142 +950,6 @@ impl MediaCache { let _ = unthrottled; Some((resolved, -1, decoded, true)) } - - /// Walks reachable `Loader` nodes upstream of `target` at `time` and decodes any missing - /// still/sequence/EXR frames into RAM in parallel when 2 or more distinct files are uncached. - pub fn preload_frame_loaders( - &mut self, - comp: &Comp, - target: NodeId, - time: f64, - expr: &model::ExprEngine, - ) { - self.preload_frame_loaders_with_proxy(comp, target, time, expr, false); - } - - /// Variant of [`Self::preload_frame_loaders`] honoring `use_proxy_clips`. - pub fn preload_frame_loaders_with_proxy( - &mut self, - comp: &Comp, - target: NodeId, - time: f64, - expr: &model::ExprEngine, - use_proxy_clips: bool, - ) { - #[cfg(target_arch = "wasm32")] - { - let _ = (comp, target, time, expr, use_proxy_clips); - } - #[cfg(not(target_arch = "wasm32"))] - { - 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() < 2 { - return; - } - self.decode_jobs_parallel(jobs); - } - } - - /// Pre-decodes reachable `Loader` files for upcoming `frames` in parallel into `MediaCache`. - pub fn prefetch_frames( - &mut self, - comp: &Comp, - target: NodeId, - frames: &[f64], - expr: &model::ExprEngine, - ) { - self.prefetch_frames_with_proxy(comp, target, frames, expr, false); - } - - /// Variant of [`Self::prefetch_frames`] honoring `use_proxy_clips`. - pub fn prefetch_frames_with_proxy( - &mut self, - comp: &Comp, - target: NodeId, - frames: &[f64], - expr: &model::ExprEngine, - use_proxy_clips: bool, - ) { - #[cfg(target_arch = "wasm32")] - { - let _ = (comp, target, frames, expr, use_proxy_clips); - } - #[cfg(not(target_arch = "wasm32"))] - { - if frames.is_empty() { - return; - } - let mut visited = HashSet::new(); - let mut jobs = MissingJobs::default(); - for &time in frames { - collect_missing_loader_jobs_shared( - &self.shared, - comp, - target, - time, - expr, - use_proxy_clips, - &mut visited, - &mut jobs, - ); - } - let total = jobs.total_units(); - if total == 0 { - return; - } - 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()); - self.shared.sync_lookahead_throttle(&state); - state.generation - }; - let mut guard = InFlightGuard { - shared: &self.shared, - 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, false); - return; - } - self.decode_jobs_parallel(jobs); - } - } - - /// 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)| VideoDecodeTask { path, requests }) - .collect(); - let video_count = video_tasks.len(); - let raster_jobs = jobs.raster; - let total_units = video_count + raster_jobs.len(); - if total_units == 0 { - return; - } - let workers = std::thread::available_parallelism() - .map(|n| n.get().clamp(2, 12)) - .unwrap_or(4) - .min(total_units); - - let next_idx = AtomicUsize::new(0); - let video_inputs: Vec>> = - video_tasks.drain(..).map(|t| Mutex::new(Some(t))).collect(); - - std::thread::scope(|scope| { - for _ in 0..workers { - scope.spawn(|| loop { - let idx = next_idx.fetch_add(1, Ordering::Relaxed); - if idx >= total_units { - break; - } - if idx < video_count { - let task = video_inputs[idx].lock().ok().and_then(|mut g| g.take()); - 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( - &req.clip, - req.frame_i, - info.nb_frames, - ); - if !seen_local.insert((frame_idx, req.post_multiply)) { - continue; - } - 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()); - self.shared.sync_lookahead_throttle(&state); - 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 decoded = DecodedImage { - size: [info.width, info.height], - rgba: Arc::new(raw), - rgba_f16: None, - rgba_f32: None, - }; - let unthrottled = if let Ok(mut state) = self.shared.state.lock() { - state.in_flight.remove(&key); - guard.key = None; - let unthrottled = if state.generation == cache_gen { - self.shared - .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(); - } - } - } - } - } - } else { - let r_idx = idx - video_count; - 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()); - self.shared.sync_lookahead_throttle(&state); - 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()), - }; - let decoded = decode_job(job, false); - finish_raster_job( - &self.shared, - job.cache_key.clone(), - cache_gen, - &mut guard, - decoded, - false, - ); - } - }); - } - }); - } -} - -#[cfg(not(target_arch = "wasm32"))] -fn finish_raster_job( - shared: &MediaShared, - key: ImageCacheKey, - cache_gen: u64, - guard: &mut InFlightGuard<'_>, - decoded: Option, - is_speculative: bool, -) { - let unthrottled = if let Ok(mut state) = shared.state.lock() { - state.in_flight.remove(&key); - guard.key = None; - let unthrottled = if let Some(decoded) = decoded { - if state.generation == cache_gen { - state.record_existing_path(&key.path); - 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(); - } -} - -#[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"))] -impl PrefetchQueueState { - fn prune_stale(&mut self) { - let cur = self.current_seq; - if self.raster.iter().any(|&(seq, _)| seq < cur) { - let mut kept = VecDeque::with_capacity(self.raster.len()); - while let Some((seq, job)) = self.raster.pop_front() { - if seq >= cur { - kept.push_back((seq, job)); - } else { - self.queued_raster_keys.remove(&job.cache_key); - } - } - self.raster = kept; - } - self.videos.retain(|_, vq| { - vq.retain(|&(seq, _)| seq >= cur); - !vq.is_empty() - }); - } -} - -#[cfg(not(target_arch = "wasm32"))] -struct PrefetchQueue { - state: Mutex, - cv: Condvar, -} - -#[cfg(not(target_arch = "wasm32"))] -enum PrefetchWorkItem { - Raster(usize, usize, PreloadJob), - Video(usize, usize, PathBuf, VideoFrameRequest), -} - -/// 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(), - }); - shared.register_prefetch_queue(&queue); - let worker_count = std::thread::available_parallelism() - .map(|n| n.get().clamp(2, 12)) - .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, - } - } - - /// 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(); - self.queue.cv.notify_all(); - } - } - - /// Enqueues missing `Loader` decodes for `time` at sequence index `seq_idx`. - pub fn enqueue_frame( - &self, - comp: &Comp, - target: NodeId, - seq_idx: usize, - time: f64, - expr: &model::ExprEngine, - use_proxy_clips: bool, - ) { - 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; - } - if let Ok(mut q) = self.queue.state.lock() { - if q.cancelled || seq_idx < q.current_seq { - 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 { - if let Some((existing_seq, _)) = vq.iter_mut().find(|(_, existing)| { - existing.post_multiply == req.post_multiply - && match (existing.resolved_frame_idx, req.resolved_frame_idx) { - (Some(a), Some(b)) => a == b, - _ => { - existing.frame_i == req.frame_i - && existing.clip.global_start == req.clip.global_start - && existing.clip.trim_in == req.clip.trim_in - && existing.clip.trim_out == req.clip.trim_out - && existing.clip.reverse == req.clip.reverse - && existing.clip.loop_clip == req.clip.loop_clip - } - } - }) { - *existing_seq = (*existing_seq).min(seq_idx); - } else { - vq.push_back((seq_idx, req)); - } - } - } - self.queue.cv.notify_all(); - } - } - - /// 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(); - } - } - - 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 best_raster = q - .raster - .iter() - .enumerate() - .min_by_key(|&(_, (seq, _))| *seq) - .map(|(idx, (seq, _))| (idx, *seq)); - let mut best_video: Option<(&PathBuf, usize, usize)> = None; - for (path, vq) in &q.videos { - if q.active_videos.contains(path) { - continue; - } - if let Some((v_idx, &(seq, _))) = - vq.iter().enumerate().min_by_key(|&(_, (seq, _))| *seq) - { - if best_video.as_ref().is_none_or(|&(_, _, bseq)| seq < bseq) { - best_video = Some((path, v_idx, seq)); - } - } - } - - let chosen_seq = match (best_raster, &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) - && shared.lookahead_throttled.load(Ordering::Acquire) - { - q = match queue.cv.wait(q) { - Ok(g) => g, - Err(_) => return, - }; - 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((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(seq, cur_seq, path, req); - } - } - if let Some((r_idx, _)) = best_raster { - if let Some((seq, job)) = q.raster.remove(r_idx) { - q.queued_raster_keys.remove(&job.cache_key); - break PrefetchWorkItem::Raster(seq, cur_seq, job); - } - } - } - }; - - match item { - 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) - { - None - } else { - state.in_flight.insert(job.cache_key.clone()); - shared.sync_lookahead_throttle(&state); - Some(state.generation) - } - }); - let Some(cache_gen) = cache_gen_opt else { continue }; - let mut guard = InFlightGuard { - shared: &shared, - key: Some(job.cache_key.clone()), - }; - let decoded = decode_job(&job, false); - finish_raster_job( - &shared, - job.cache_key, - cache_gen, - &mut guard, - decoded, - item_seq > cur_seq, - ); - } - PrefetchWorkItem::Video(item_seq, cur_seq, 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()); - shared.sync_lookahead_throttle(&state); - 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, - }; - let unthrottled = if let Ok(mut state) = shared.state.lock() { - state.in_flight.remove(&key); - guard.key = None; - 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(); - } - } - } - } - } - } -} - -#[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, -) { - const MAX_PRELOAD_DEPTH: usize = 256; - if node_id.0 >= comp.nodes.len() || jobs.depth >= MAX_PRELOAD_DEPTH { - return; - } - let time_key = (if time == 0.0 { 0.0 } else { time }).to_bits() as i64; - if !visited.insert((node_id, time_key)) { - return; - } - jobs.depth += 1; - collect_missing_loader_jobs_inner( - shared, - comp, - node_id, - time, - expr, - use_proxy_clips, - visited, - jobs, - ); - jobs.depth -= 1; -} - -#[cfg(not(target_arch = "wasm32"))] -#[allow(clippy::too_many_arguments)] -fn collect_missing_loader_jobs_inner( - shared: &MediaShared, - comp: &Comp, - node_id: NodeId, - time: f64, - expr: &model::ExprEngine, - use_proxy_clips: bool, - visited: &mut HashSet<(NodeId, i64)>, - jobs: &mut MissingJobs, -) { - 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 { - 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; - } - 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) - } 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, - fg_id, - time, - expr, - use_proxy_clips, - visited, - jobs, - ); - } - } - 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 == "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 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.saturating_sub(effective_clip.extend_first.max(0)) - || (!effective_clip.loop_clip - && frame_i > effective_clip.global_end.saturating_add(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 mut resolved_frame_idx = effective_clip - .length - .map(|_| compute_video_frame_idx(&effective_clip, frame_i, 1)); - let need_decode = shared.state.lock().is_ok_and(|state| { - match state.video_decoders.get(base) { - Some(slot) => { - let idx = compute_video_frame_idx( - &effective_clip, - frame_i, - slot.info.nb_frames, - ); - resolved_frame_idx = Some(idx); - let cache_key = ImageCacheKey { - path: base.to_path_buf(), - frame_idx: idx, - post_multiply: post_mult, - exr_channels: [None, None, None, None], - }; - !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, - resolved_frame_idx, - }); - } - } - } 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) { - collect_missing_loader_jobs_shared( - shared, - 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); - } - } - } - } - 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, - ); - } } fn video_frame_in_range(clip: &ClipSpec, frame: i64) -> bool { @@ -2432,98 +983,6 @@ fn compute_video_frame_idx(clip: &ClipSpec, frame: i64, nb_frames: i64) -> i64 { if clip.reverse { trim_out.saturating_sub(rel) } else { trim_in.saturating_add(rel) } } -#[cfg(not(target_arch = "wasm32"))] -#[derive(Default)] -struct MissingJobs { - raster: Vec, - seen_raster: HashSet, - videos: HashMap>, - depth: usize, -} - -#[cfg(not(target_arch = "wasm32"))] -impl MissingJobs { - fn total_units(&self) -> usize { - self.raster.len() + self.videos.len() - } -} - -#[cfg(not(target_arch = "wasm32"))] -struct VideoFrameRequest { - clip: ClipSpec, - frame_i: i64, - post_multiply: bool, - resolved_frame_idx: Option, -} - -#[cfg(not(target_arch = "wasm32"))] -struct VideoDecodeTask { - path: PathBuf, - requests: Vec, -} - -#[cfg(not(target_arch = "wasm32"))] -struct PreloadJob { - cache_key: ImageCacheKey, - is_exr: bool, -} - -#[cfg(not(target_arch = "wasm32"))] -fn decode_job(job: &PreloadJob, allow_parallel: bool) -> Option { - if job.is_exr { - decode_exr_rgba( - &job.cache_key.path, - job.cache_key.exr_channels[0].as_deref(), - job.cache_key.exr_channels[1].as_deref(), - job.cache_key.exr_channels[2].as_deref(), - job.cache_key.exr_channels[3].as_deref(), - false, - allow_parallel, - ) - } else { - decode_raster_image( - &job.cache_key.path, - job.cache_key.post_multiply, - allow_parallel, - ) - } -} - -#[cfg(not(target_arch = "wasm32"))] -fn resolve_effect_mask_id_for_node(comp: &Comp, node: &Node) -> Option { - if let Some(id) = node.connected_node("EffectMask").and_then(|s| comp.find_node(s)) { - return Some(id); - } - let has_explicit_mask_entry = |n: &Node| -> bool { - n.raw - .get_table("Inputs") - .and_then(|t| t.get("EffectMask")) - .is_some() - }; - if has_explicit_mask_entry(node) { - return None; - } - let mut visited = HashSet::new(); - visited.insert(node.id); - let mut cur = node; - for _ in 0..8 { - let master_name = cur.raw.get_str("SourceOp")?; - let mid = comp.find_node(master_name)?; - if !visited.insert(mid) { - break; - } - let master = comp.node(mid); - if let Some(mask_id) = master.connected_node("EffectMask").and_then(|s| comp.find_node(s)) { - return Some(mask_id); - } - if has_explicit_mask_entry(master) { - return None; - } - cur = master; - } - None -} - fn resolve_clip_candidate_path(clip: &ClipSpec, frame: i64) -> Option { let base = Path::new(&clip.filename); let len = clip.length.unwrap_or(1); @@ -2569,1457 +1028,3 @@ 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)] -mod tests { - use super::*; - use std::time::Instant; - - #[test] - fn decoded_image_cache_separates_post_multiply() { - let dir = std::env::temp_dir().join("fission_media_post_multiply_key_test"); - std::fs::create_dir_all(&dir).unwrap(); - let png = dir.join("half.png"); - image::RgbaImage::from_pixel(2, 2, image::Rgba([200, 100, 50, 128])).save(&png).unwrap(); - let clip = ClipSpec { - filename: png.to_string_lossy().into_owned(), - alternate_filename: None, - start_frame: 0, - length: Some(1), - trim_in: 0, - trim_out: 0, - global_start: 0, - global_end: 0, - extend_first: 0, - extend_last: 0, - loop_clip: false, - reverse: false, - }; - let mut cache = MediaCache::new(64); - let mut first_px = |post_multiply| { - let (_, _, img, from_disk) = cache.load_clip(&clip, 0, post_multiply, [None; 4]).unwrap(); - (img.rgba[..4].to_vec(), from_disk) - }; - assert_eq!(first_px(false), (vec![200, 100, 50, 128], true)); - assert_eq!(first_px(true), (vec![100, 50, 25, 128], true)); - assert_eq!(first_px(false), (vec![200, 100, 50, 128], false)); - assert_eq!(first_px(true), (vec![100, 50, 25, 128], false)); - assert_eq!(cache.entry_count(), 2); - let _ = std::fs::remove_dir_all(&dir); - } - - fn mean_abs_error_rgb(a: &[u8], b: &[u8]) -> f64 { - assert_eq!(a.len(), b.len()); - let mut sum = 0u64; - let mut count = 0u64; - for (pa, pb) in a.chunks_exact(4).zip(b.chunks_exact(4)) { - sum += pa[0].abs_diff(pb[0]) as u64; - sum += pa[1].abs_diff(pb[1]) as u64; - sum += pa[2].abs_diff(pb[2]) as u64; - count += 3; - } - if count == 0 { - 0.0 - } else { - sum as f64 / count as f64 - } - } - - fn verify_clip_matches_ffmpeg(path: &Path) { - let mut dec = open_video_decoder(path).expect("open_video_decoder failed"); - let mut ff = FfmpegDecoder::open(path).expect("FfmpegDecoder::open failed"); - - #[cfg(target_os = "macos")] - assert_eq!( - dec.backend_name(), - "AVFoundation/VideoToolbox", - "expected AVFoundation backend for {}", - path.display() - ); - - let av_info = dec.info(); - let ff_info = ff.info(); - assert_eq!(av_info.width, ff_info.width, "width mismatch for {}", path.display()); - assert_eq!(av_info.height, ff_info.height, "height mismatch for {}", path.display()); - assert!( - (av_info.fps - ff_info.fps).abs() < 0.2, - "fps mismatch for {}: av={} ff={}", - path.display(), - av_info.fps, - ff_info.fps - ); - - let frames = [0_i64, 1, 2, 10, 0]; - let mut total_ms = 0.0; - for &f in &frames { - let t0 = Instant::now(); - let av_px = dec - .decode_frame(f) - .unwrap_or_else(|| panic!("av decode frame {f} failed for {}", path.display())); - let elapsed_ms = t0.elapsed().as_secs_f64() * 1000.0; - total_ms += elapsed_ms; - - let ff_px = ff - .decode_frame(f) - .unwrap_or_else(|| panic!("ffmpeg decode frame {f} failed for {}", path.display())); - let mae = mean_abs_error_rgb(&av_px, &ff_px); - eprintln!( - "[video-test] {} ({}x{} @{:.2}fps) frame {}: {:.2} ms, MAE vs ffmpeg = {:.2}", - path.file_name().and_then(|s| s.to_str()).unwrap_or("clip"), - av_info.width, - av_info.height, - av_info.fps, - f, - elapsed_ms, - mae - ); - // Allow small YUV->RGB matrix/rounding differences between VideoToolbox and swscale. - assert!( - mae < 12.0, - "high MAE ({mae:.2}) on {} frame {f} (possible orientation or PTS mismatch)", - path.display() - ); - } - eprintln!( - "[video-test] {} avg decode: {:.2} ms/frame", - path.file_name().and_then(|s| s.to_str()).unwrap_or("clip"), - total_ms / frames.len() as f64 - ); - } - - #[test] - fn test_video_decoder_real_mov_clips() { - let clips = [ - Path::new("/Volumes/Project/trees/EncodedMedia/A001_11071331_C002_4873-4988_d8716e17.mov"), - Path::new("/Volumes/Project/trees/EncodedMedia/IMG_1767_2395-2547_7efe6416.mov"), - ]; - for clip in clips { - if clip.exists() { - verify_clip_matches_ffmpeg(clip); - } - } - } - - #[test] - fn test_video_decoder_synthetic_mp4() { - let tmp = std::env::temp_dir().join("engine_test_synth_video.mp4"); - let status = Command::new("ffmpeg") - .args([ - "-y", - "-v", - "error", - "-f", - "lavfi", - "-i", - "testsrc2=size=320x180:rate=24:duration=1.0", - "-c:v", - "libx264", - "-pix_fmt", - "yuv420p", - ]) - .arg(&tmp) - .status(); - if let Ok(st) = status { - if st.success() { - verify_clip_matches_ffmpeg(&tmp); - let _ = std::fs::remove_file(&tmp); - } - } - } - - fn alpha_y_bounds(size: [u32; 2], origin: [i32; 2], rgba: &[u8]) -> (i32, i32) { - let [w, h] = size; - let mut min_y = i32::MAX; - let mut max_y = i32::MIN; - for y in 0..h as usize { - let row = y * w as usize * 4; - for x in 0..w as usize { - if rgba[row + x * 4 + 3] > 32 { - let cy = origin[1] + y as i32; - min_y = min_y.min(cy); - max_y = max_y.max(cy); - break; - } - } - } - (min_y, max_y) - } - - #[test] - fn test_text_plus_calibrated_metrics_and_anchoring() { - let base = |text: &str, v_tcb: f32, line_spacing: f32, dims: [u32; 2]| { - rasterize_text_plus( - dims, - &TextPlusParams { - text, - font_family: "Helvetica Neue", - font_style: "Regular", - size_norm: 0.08, - tracking: 1.0, - line_spacing, - center: [0.5, 0.5], - h_lcr: 0.0, - v_tcb, - fill_rgba: [1.0, 1.0, 1.0, 1.0], - write_on_start: 0.0, - write_on_end: 1.0, - shear_x: 0.0, - cls: &[], - outline_rgba: [0.0; 4], - outline_width_px: 0.0, - }, - 0, - ) - }; - - // 1. VerticalTopCenterBottom: -1 anchors top below cy=270, 0 centers around cy=270, - // +1 anchors bottom baseline at cy=270 (so glyphs sit above cy=270). - let (s_top, o_top, p_top) = base("HHHH", -1.0, 1.0, [960, 540]); - let (s_ctr, o_ctr, p_ctr) = base("HHHH", 0.0, 1.0, [960, 540]); - let (s_bot, o_bot, p_bot) = base("HHHH", 1.0, 1.0, [960, 540]); - let (top_y0, top_y1) = alpha_y_bounds(s_top, o_top, &p_top); - let (ctr_y0, ctr_y1) = alpha_y_bounds(s_ctr, o_ctr, &p_ctr); - let (bot_y0, bot_y1) = alpha_y_bounds(s_bot, o_bot, &p_bot); - assert!(top_y0 >= 268 && top_y1 > 300, "top-aligned should sit below cy=270: ({top_y0}, {top_y1})"); - assert!(ctr_y0 < 270 && ctr_y1 > 270, "center-aligned should straddle cy=270: ({ctr_y0}, {ctr_y1})"); - assert!(bot_y0 < 240 && bot_y1 <= 272, "bottom-aligned should sit above cy=270: ({bot_y0}, {bot_y1})"); - - // 2. LineSpacing=1.5 widens a 2-line block by 0.5 * (0.8 * 0.08 * 960 = 61.44px) = ~30.7px. - let (s_ls1, o_ls1, p_ls1) = base("HHHH\nHHHH", 0.0, 1.0, [960, 540]); - let (s_ls15, o_ls15, p_ls15) = base("HHHH\nHHHH", 0.0, 1.5, [960, 540]); - let (ls1_y0, ls1_y1) = alpha_y_bounds(s_ls1, o_ls1, &p_ls1); - let (ls15_y0, ls15_y1) = alpha_y_bounds(s_ls15, o_ls15, &p_ls15); - let span_diff = (ls15_y1 - ls15_y0) - (ls1_y1 - ls1_y0); - assert!( - (28..=34).contains(&span_diff), - "LineSpacing 1.5 vs 1.0 on 960x540 Size=0.08 should add ~31px span, got {span_diff}" - ); - - // 3. Size scales with canvas width W, independent of height H. - let (s_wide, o_wide, p_wide) = base("HHHH", 0.0, 1.0, [960, 540]); - let (s_tall, o_tall, p_tall) = base("HHHH", 0.0, 1.0, [540, 960]); - let (wy0, wy1) = alpha_y_bounds(s_wide, o_wide, &p_wide); - let (ty0, ty1) = alpha_y_bounds(s_tall, o_tall, &p_tall); - let wide_h = (wy1 - wy0) as f32; - let tall_h = (ty1 - ty0) as f32; - let ratio = wide_h / tall_h; - assert!( - (ratio - (960.0 / 540.0)).abs() < 0.15, - "glyph pixel height should scale with W (expected ~1.78, got {ratio:.2}: {wide_h}/{tall_h})" - ); - } - - #[test] - fn exr_channel_cache_isolation_and_non_beauty_guard() { - use ::exr::prelude::*; - let dir = std::env::temp_dir().join(format!("fission_exr_chan_test_{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - - let multi_exr = dir.join("multi_aov.exr"); - let w = 4usize; - let h = 4usize; - let n = w * h; - let mut channels = SmallVec::<[AnyChannel; 4]>::new(); - for (name, val) in [ - ("ViewLayer.Combined.R", 0.9_f32), - ("ViewLayer.Combined.G", 0.2), - ("ViewLayer.Combined.B", 0.1), - ("ViewLayer.Combined.A", 1.0), - ("ViewLayer.Specular.R", 0.1), - ("ViewLayer.Specular.G", 0.8), - ("ViewLayer.Specular.B", 0.7), - ("ViewLayer.Specular.A", 1.0), - ("ViewLayer.CryptoObject00.R", 0.5), - ] { - channels.push(AnyChannel::new(name, FlatSamples::F32(vec![val; n]))); - } - Image::from_layer(Layer::new( - (w, h), - LayerAttributes::named("main"), - Encoding::FAST_LOSSLESS, - AnyChannels::sort(channels), - )) - .write() - .to_file(&multi_exr) - .expect("write multi-layer EXR"); - - let clip = ClipSpec { - filename: multi_exr.to_string_lossy().into_owned(), - alternate_filename: None, - start_frame: 0, - length: Some(1), - trim_in: 0, - trim_out: 0, - global_start: 0, - global_end: 0, - extend_first: 0, - extend_last: 0, - loop_clip: false, - reverse: false, - }; - let mut cache = MediaCache::new(64); - let (_, _, beauty, beauty_disk) = cache.load_clip(&clip, 0, false, [None; 4]).unwrap(); - assert!(beauty_disk); - let (_, _, spec, spec_disk) = cache - .load_clip( - &clip, - 0, - false, - [ - Some("Specular.R"), - Some("Specular.G"), - Some("Specular.B"), - Some("Specular.A"), - ], - ) - .unwrap(); - assert!(spec_disk); - assert_eq!(cache.entry_count(), 2); - - let b_px = beauty.rgba_f32.as_ref().unwrap(); - let s_px = spec.rgba_f32.as_ref().unwrap(); - assert!((b_px[0] - 0.9).abs() < 1e-4 && (b_px[1] - 0.2).abs() < 1e-4); - assert!((s_px[0] - 0.1).abs() < 1e-4 && (s_px[1] - 0.8).abs() < 1e-4); - - // Warm hits keep both AOVs isolated. - let (_, _, beauty_warm, beauty_disk2) = cache.load_clip(&clip, 0, false, [None; 4]).unwrap(); - assert!(!beauty_disk2); - assert!((beauty_warm.rgba_f32.as_ref().unwrap()[0] - 0.9).abs() < 1e-4); - - // EXR containing ONLY CryptoObject00.R (no bare R or Combined.R) must NOT match beauty fallback. - let crypto_only_exr = dir.join("crypto_only.exr"); - let mut crypto_channels = SmallVec::<[AnyChannel; 4]>::new(); - for (name, val) in [ - ("CryptoObject00.R", 0.42_f32), - ("CryptoObject00.G", 0.0), - ("CryptoObject00.B", 0.0), - ("CryptoObject00.A", 1.0), - ] { - crypto_channels.push(AnyChannel::new(name, FlatSamples::F32(vec![val; n]))); - } - Image::from_layer(Layer::new( - (w, h), - LayerAttributes::named("crypto"), - Encoding::FAST_LOSSLESS, - AnyChannels::sort(crypto_channels), - )) - .write() - .to_file(&crypto_only_exr) - .expect("write crypto-only EXR"); - - let crypto_clip = ClipSpec { - filename: crypto_only_exr.to_string_lossy().into_owned(), - ..clip - }; - assert!(cache.load_clip(&crypto_clip, 0, false, [None; 4]).is_none()); - let (_, _, explicit, _) = cache - .load_clip( - &crypto_clip, - 0, - false, - [ - Some("CryptoObject00.R"), - Some("CryptoObject00.G"), - Some("CryptoObject00.B"), - Some("CryptoObject00.A"), - ], - ) - .expect("explicit CryptoObject00 channel selection should succeed"); - assert!((explicit.rgba_f32.as_ref().unwrap()[0] - 0.42).abs() < 1e-4); - - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn video_decoder_clear_lru_cap_post_multiply_and_loop() { - let dir = std::env::temp_dir().join(format!("fission_media_video_lru_{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - - let base_mp4 = dir.join("clip_00.mp4"); - let ok = Command::new("ffmpeg") - .args([ - "-y", - "-v", - "error", - "-f", - "lavfi", - "-i", - "color=c=red:size=32x32:rate=24:duration=0.25", - "-c:v", - "libx264", - "-pix_fmt", - "yuv420p", - ]) - .arg(&base_mp4) - .status() - .is_ok_and(|s| s.success()); - assert!(ok, "ffmpeg failed to create tiny mp4"); - - let mut cache = MediaCache::new(64); - for i in 0..15 { - let p = if i == 0 { - base_mp4.clone() - } else { - let dst = dir.join(format!("clip_{i:02}.mp4")); - std::fs::copy(&base_mp4, &dst).unwrap(); - dst - }; - let clip = ClipSpec { - filename: p.to_string_lossy().into_owned(), - alternate_filename: None, - start_frame: 0, - length: Some(6), - trim_in: 0, - trim_out: 5, - global_start: 10, - global_end: 15, - extend_first: 5, - extend_last: 0, - loop_clip: true, - reverse: false, - }; - // Frame 9 with global_start = 10, extend_first = 5 -> inside [5, 15]: ExtendFirst holds frame 0. - let (_, local_idx, _, _) = cache - .load_clip(&clip, 9, false, [None; 4]) - .expect("loop_clip inside ExtendFirst should resolve"); - assert_eq!(local_idx, 0); - // Looping clips ignore GlobalEnd + ExtendLast: frame 20 -> rel 10 -> 10 % 6 = 4. - let (_, local_idx, _, _) = cache - .load_clip(&clip, 20, false, [None; 4]) - .expect("loop_clip past GlobalEnd should keep looping"); - assert_eq!(local_idx, 4); - let once = ClipSpec { loop_clip: false, ..clip }; - assert!(cache.load_clip(&once, 20, false, [None; 4]).is_none()); - } - assert!( - cache.video_decoder_count() <= MAX_VIDEO_DECODERS, - "expected LRU cap <= {MAX_VIDEO_DECODERS}, got {}", - cache.video_decoder_count() - ); - assert_eq!(cache.video_decoder_count(), MAX_VIDEO_DECODERS); - - // Straight-alpha ProRes 4444 MOV test for post_multiply separation. - let alpha_png = dir.join("straight_half.png"); - image::RgbaImage::from_pixel(32, 32, image::Rgba([200, 100, 50, 128])) - .save(&alpha_png) - .unwrap(); - let alpha_mov = dir.join("straight_half.mov"); - let mov_ok = Command::new("ffmpeg") - .args([ - "-y", - "-v", - "error", - "-loop", - "1", - "-i", - ]) - .arg(&alpha_png) - .args([ - "-t", - "0.1", - "-r", - "24", - "-c:v", - "prores_ks", - "-profile:v", - "4", - "-pix_fmt", - "yuva444p10le", - ]) - .arg(&alpha_mov) - .status() - .is_ok_and(|s| s.success()); - if mov_ok { - let mov_clip = ClipSpec { - filename: alpha_mov.to_string_lossy().into_owned(), - alternate_filename: None, - start_frame: 0, - length: Some(2), - trim_in: 0, - trim_out: 1, - global_start: 0, - global_end: 1, - extend_first: 0, - extend_last: 0, - loop_clip: false, - reverse: false, - }; - let (_, _, raw_vid, _) = cache.load_clip(&mov_clip, 0, false, [None; 4]).unwrap(); - let (_, _, pm_vid, _) = cache.load_clip(&mov_clip, 0, true, [None; 4]).unwrap(); - assert!( - pm_vid.rgba[0] < raw_vid.rgba[0], - "post_multiply should darken straight-alpha RGB ({} vs {})", - pm_vid.rgba[0], - raw_vid.rgba[0] - ); - } - - cache.clear(); - assert_eq!(cache.entry_count(), 0); - assert_eq!(cache.video_decoder_count(), 0); - - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn resolve_clip_path_missing_mid_sequence_returns_none() { - let dir = std::env::temp_dir().join(format!("fission_seq_missing_{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - - let f0 = dir.join("shot_0000.png"); - let f2 = dir.join("shot_0002.png"); - image::RgbaImage::from_pixel(2, 2, image::Rgba([255, 0, 0, 255])).save(&f0).unwrap(); - image::RgbaImage::from_pixel(2, 2, image::Rgba([0, 255, 0, 255])).save(&f2).unwrap(); - - let clip = ClipSpec { - filename: f0.to_string_lossy().into_owned(), - alternate_filename: None, - start_frame: 0, - length: Some(3), - trim_in: 0, - trim_out: 2, - global_start: 0, - global_end: 2, - extend_first: 0, - extend_last: 0, - loop_clip: false, - reverse: false, - }; - assert_eq!(resolve_clip_path(&clip, 0), Some(f0)); - assert_eq!(resolve_clip_path(&clip, 1), None); - assert_eq!(resolve_clip_path(&clip, 2), Some(f2)); - - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn virtual_bytes_load_a_sequence_by_trailing_path() { - let png = |rgba: [u8; 4]| { - let mut out = std::io::Cursor::new(Vec::new()); - image::RgbaImage::from_pixel(2, 1, image::Rgba(rgba)) - .write_to(&mut out, image::ImageFormat::Png) - .unwrap(); - out.into_inner() - }; - MediaCache::insert_virtual_bytes("vf_proj\\vf_seq.0001.png", png([255, 0, 0, 255])); - MediaCache::insert_virtual_bytes("./vf_proj/vf_seq.0002.png", png([0, 255, 0, 255])); - let clip = ClipSpec { - filename: "/not/on/disk/vf_proj/vf_seq.0001.png".to_owned(), - alternate_filename: None, - start_frame: 1, - length: Some(2), - trim_in: 0, - trim_out: 1, - global_start: 0, - global_end: 1, - extend_first: 0, - extend_last: 0, - loop_clip: false, - reverse: false, - }; - let mut cache = MediaCache::new(64); - let (_, _, f0, from_disk) = cache.load_clip(&clip, 0, false, [None; 4]).unwrap(); - let (_, _, f1, _) = cache.load_clip(&clip, 1, false, [None; 4]).unwrap(); - assert!(from_disk); - assert_eq!((f0.size, &f0.rgba[..4]), ([2, 1], &[255, 0, 0, 255][..])); - assert_eq!(&f1.rgba[..4], &[0, 255, 0, 255]); - - MediaCache::insert_virtual_bytes("vf_proj/vf_seq.0002.png", png([0, 0, 255, 255])); - let (_, _, f1, _) = MediaCache::new(64).load_clip(&clip, 1, false, [None; 4]).unwrap(); - assert_eq!(&f1.rgba[..4], &[0, 0, 255, 255]); - assert!(path_exists(Path::new("elsewhere/vf_seq.0002.png"))); - assert!(!path_exists(Path::new("vf_proj/vf_seq.0003.png"))); - } - - fn file(path: &str, len: usize) -> VirtualFile { - VirtualFile { parts: path_parts(Path::new(path)), bytes: vec![0; len].into() } - } - - fn found<'a>(files: &'a [VirtualFile], path: &str) -> Option<&'a [String]> { - find_virtual(files, &path_parts(Path::new(path))).map(|f| f.parts.as_slice()) - } - - #[test] - fn virtual_paths_normalize_dots_and_separators() { - assert_eq!(path_parts(Path::new("/a/./b/../c\\d.png")), ["a", "c", "d.png"]); - assert_eq!(path_parts(Path::new("../../x.png")), ["x.png"]); - } - - #[test] - fn virtual_matching_prefers_exact_and_rejects_ambiguous_basenames() { - let files = [file("A/bg.png", 1), file("B/bg.png", 1), file("only.png", 1), file("Proj/Seq.exr", 1)]; - assert_eq!(found(&files, "/x/A/bg.png"), Some(&["A".to_owned(), "bg.png".to_owned()][..])); - assert_eq!(found(&files, "/x/../B/./bg.png").map(<[String]>::len), Some(2)); - assert_eq!(found(&files, "/C/bg.png"), None, "two files share the basename"); - assert_eq!(found(&files, "bg.png"), None); - assert!(found(&files, "/deep/elsewhere/only.png").is_some()); - assert!(found(&files, "/proj/seq.EXR").is_some(), "case-insensitive fallback"); - assert_eq!(found(&files, "/a/missing.png"), None); - } - - #[test] - fn virtual_files_stop_at_the_memory_cap() { - let mut files = Vec::new(); - let put = |files: &mut Vec, name: &str, len: usize| { - insert_capped(files, 10, path_parts(Path::new(name)), vec![0; len].into()) - }; - assert!(put(&mut files, "a", 6)); - assert!(!put(&mut files, "b", 5)); - assert!(put(&mut files, "b", 4)); - assert!(put(&mut files, "a", 6), "replacing a file frees its old bytes"); - assert!(!put(&mut files, "a", 7)); - assert_eq!(files.iter().map(|f| f.bytes.len()).sum::(), 10); - } - - #[test] - fn media_budget_scaling_matches_ram_tiers() { - const GIB: u64 = 1024 * 1024 * 1024; - assert_eq!(media_cache_budget_mb_for_total_bytes(8 * GIB), 512); - assert_eq!(media_cache_budget_mb_for_total_bytes(16 * GIB), 1024); - assert_eq!(media_cache_budget_mb_for_total_bytes(32 * GIB), 2048); - assert_eq!(media_cache_budget_mb_for_total_bytes(64 * GIB), 4096); - assert_eq!(media_cache_budget_mb_for_total_bytes(128 * GIB), 8192); - let default_cache = MediaCache::default(); - assert_eq!( - 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.shared.state.lock().unwrap().budget_bytes, - 32 * 1024 * 1024 - ); - } - - #[test] - fn parallel_post_multiply_matches_scalar_across_large_buffer() { - let len = 4 * 1024 * 1024 * 4 + 64; // > 4 MP threshold - let mut scalar = vec![0u8; len]; - for (i, px) in scalar.chunks_exact_mut(4).enumerate() { - px[0] = ((i * 7) % 256) as u8; - px[1] = ((i * 13) % 256) as u8; - px[2] = ((i * 29) % 256) as u8; - px[3] = (i % 256) as u8; - } - let mut parallel = scalar.clone(); - exr::apply_post_multiply_rgba8_parallel(&mut scalar, false); - exr::apply_post_multiply_rgba8_parallel(&mut parallel, true); - assert_eq!(scalar, parallel); - } - - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn preload_frame_loaders_and_prefetch_frames_populate_cache_in_parallel() { - let dir = std::env::temp_dir().join(format!("fission_preload_test_{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - - let p_bg = dir.join("bg.png"); - let p_fg0 = dir.join("fg_0000.png"); - let p_fg1 = dir.join("fg_0001.png"); - let p_fg2 = dir.join("fg_0002.png"); - let p_pruned = dir.join("pruned.png"); - image::RgbaImage::from_pixel(4, 4, image::Rgba([20, 40, 60, 255])).save(&p_bg).unwrap(); - image::RgbaImage::from_pixel(4, 4, image::Rgba([200, 100, 50, 128])).save(&p_fg0).unwrap(); - image::RgbaImage::from_pixel(4, 4, image::Rgba([0, 200, 50, 255])).save(&p_fg1).unwrap(); - image::RgbaImage::from_pixel(4, 4, image::Rgba([50, 0, 200, 255])).save(&p_fg2).unwrap(); - image::RgbaImage::from_pixel(4, 4, image::Rgba([9, 9, 9, 255])).save(&p_pruned).unwrap(); - - let esc = |p: &Path| p.to_string_lossy().replace('\\', "\\\\"); - let comp_src = format!( - r#"Composition {{ - CurrentTime = 0, - RenderRange = {{ 0, 2 }}, - GlobalRange = {{ 0, 2 }}, - Tools = ordered() {{ - BgLoader = Loader {{ - Clips = {{ - Clip {{ - ID = "Clip1", - Filename = "{}", - FormatID = "PNGFormat", - Length = 1, - GlobalStart = 0, - GlobalEnd = 2, - }}, - }}, - }}, - FgLoader = Loader {{ - Clips = {{ - Clip {{ - ID = "Clip1", - Filename = "{}", - FormatID = "PNGFormat", - StartFrame = 0, - Length = 3, - GlobalStart = 0, - GlobalEnd = 2, - }}, - }}, - Inputs = {{ - ["Clip1.PNGFormat.PostMultiply"] = Input {{ Value = 1, }}, - }}, - }}, - PrunedLoader = Loader {{ - Clips = {{ - Clip {{ - ID = "Clip1", - Filename = "{}", - FormatID = "PNGFormat", - Length = 1, - GlobalStart = 0, - GlobalEnd = 2, - }}, - }}, - }}, - PrunedMerge = Merge {{ - Inputs = {{ - Blend = Input {{ Value = 0, }}, - Background = Input {{ SourceOp = "BgLoader", Source = "Output", }}, - Foreground = Input {{ SourceOp = "PrunedLoader", Source = "Output", }}, - }}, - }}, - MainMerge = Merge {{ - Inputs = {{ - Background = Input {{ SourceOp = "PrunedMerge", Source = "Output", }}, - Foreground = Input {{ SourceOp = "FgLoader", Source = "Output", }}, - }}, - }}, - }}, -}}"#, - esc(&p_bg), - esc(&p_fg0), - esc(&p_pruned), - ); - let comp = Comp::from_fusion_str(&comp_src).expect("parse preload comp"); - let target = comp.find_node("MainMerge").expect("MainMerge"); - let expr = model::ExprEngine::new(); - let mut cache = MediaCache::new(64); - - cache.preload_frame_loaders(&comp, target, 0.0, &expr); - // BgLoader + FgLoader(f0) are cached; PrunedLoader is skipped because PrunedMerge Blend == 0. - assert_eq!(cache.entry_count(), 2); - - let bg_clip = comp.node(comp.find_node("BgLoader").unwrap()).clips[0].clone(); - let fg_clip = comp.node(comp.find_node("FgLoader").unwrap()).clips[0].clone(); - let (_, _, bg_img, bg_from_disk) = cache.load_clip(&bg_clip, 0, false, [None; 4]).unwrap(); - let (_, _, fg0_img, fg0_from_disk) = cache.load_clip(&fg_clip, 0, true, [None; 4]).unwrap(); - assert!(!bg_from_disk); - assert!(!fg0_from_disk); - assert_eq!(&bg_img.rgba[..4], &[20, 40, 60, 255]); - assert_eq!(&fg0_img.rgba[..4], &[100, 50, 25, 128]); - - // Prefetch frames 1 and 2 ahead of playback. - cache.prefetch_frames(&comp, target, &[1.0, 2.0], &expr); - assert_eq!(cache.entry_count(), 4); - let (_, _, fg1_img, fg1_from_disk) = cache.load_clip(&fg_clip, 1, true, [None; 4]).unwrap(); - let (_, _, fg2_img, fg2_from_disk) = cache.load_clip(&fg_clip, 2, true, [None; 4]).unwrap(); - assert!(!fg1_from_disk); - assert!(!fg2_from_disk); - assert_eq!(&fg1_img.rgba[..4], &[0, 200, 50, 255]); - assert_eq!(&fg2_img.rgba[..4], &[50, 0, 200, 255]); - - let _ = std::fs::remove_dir_all(&dir); - } - - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn preload_frame_loaders_decodes_multiple_videos_in_parallel() { - let dir = std::env::temp_dir().join(format!("fission_preload_vid_{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - - let mk_mp4 = |name: &str, color: &str| { - let p = dir.join(name); - let ok = Command::new("ffmpeg") - .args([ - "-y", - "-v", - "error", - "-f", - "lavfi", - "-i", - &format!("color=c={color}:size=32x32:rate=24:duration=0.2"), - "-c:v", - "libx264", - "-pix_fmt", - "yuv420p", - ]) - .arg(&p) - .status() - .is_ok_and(|s| s.success()); - (p, ok) - }; - let (v1, ok1) = mk_mp4("v1.mp4", "red"); - let (v2, ok2) = mk_mp4("v2.mp4", "blue"); - if !(ok1 && ok2) { - let _ = std::fs::remove_dir_all(&dir); - return; - } - - let esc = |p: &Path| p.to_string_lossy().replace('\\', "\\\\"); - let comp_src = format!( - r#"Composition {{ - CurrentTime = 0, - RenderRange = {{ 0, 3 }}, - GlobalRange = {{ 0, 3 }}, - Tools = ordered() {{ - V1 = Loader {{ - Clips = {{ - Clip {{ - ID = "Clip1", - Filename = "{}", - FormatID = "QuickTimeMovies", - Length = 4, - GlobalStart = 0, - GlobalEnd = 3, - }}, - }}, - }}, - V2 = Loader {{ - Clips = {{ - Clip {{ - ID = "Clip1", - Filename = "{}", - FormatID = "QuickTimeMovies", - Length = 4, - GlobalStart = 0, - GlobalEnd = 3, - }}, - }}, - }}, - M = Merge {{ - Inputs = {{ - Background = Input {{ SourceOp = "V1", Source = "Output", }}, - Foreground = Input {{ SourceOp = "V2", Source = "Output", }}, - }}, - }}, - }}, -}}"#, - esc(&v1), - esc(&v2), - ); - let comp = Comp::from_fusion_str(&comp_src).expect("parse video preload comp"); - let target = comp.find_node("M").expect("M"); - let expr = model::ExprEngine::new(); - let mut cache = MediaCache::new(64); - - cache.preload_frame_loaders(&comp, target, 0.0, &expr); - assert_eq!(cache.video_decoder_count(), 2); - assert_eq!(cache.entry_count(), 2); - - let c1 = comp.node(comp.find_node("V1").unwrap()).clips[0].clone(); - let c2 = comp.node(comp.find_node("V2").unwrap()).clips[0].clone(); - let (_, _, img1, disk1) = cache.load_clip(&c1, 0, false, [None; 4]).unwrap(); - let (_, _, img2, disk2) = cache.load_clip(&c2, 0, false, [None; 4]).unwrap(); - assert!(!disk1); - assert!(!disk2); - assert!(img1.rgba[0] > 200 && img1.rgba[2] < 40); - assert!(img2.rgba[2] > 200 && img2.rgba[0] < 40); - - cache.prefetch_frames(&comp, target, &[1.0, 2.0], &expr); - assert_eq!(cache.entry_count(), 6); - - 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); - } - - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn failed_opens_are_not_cached_and_evict_known_existing_paths() { - let dir = std::env::temp_dir().join(format!("fission_evict_test_{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - - let bad_vid = dir.join("corrupt.mp4"); - std::fs::write(&bad_vid, b"not a valid mp4").unwrap(); - let mut cache = MediaCache::new(64); - assert!(cache.shared.path_exists_cached(&bad_vid)); - assert!(cache.shared.get_or_open_video_decoder(&bad_vid).is_none()); - assert_eq!(cache.video_decoder_count(), 0); - assert!(!cache.shared.state.lock().unwrap().known_existing_paths.contains(&bad_vid)); - - let img_path = dir.join("gone.png"); - image::RgbaImage::from_pixel(2, 2, image::Rgba([10, 20, 30, 255])) - .save(&img_path) - .unwrap(); - assert!(cache.shared.path_exists_cached(&img_path)); - std::fs::remove_file(&img_path).unwrap(); - let clip = ClipSpec { - filename: img_path.to_string_lossy().into_owned(), - alternate_filename: None, - start_frame: 0, - length: Some(1), - trim_in: 0, - trim_out: 0, - global_start: 0, - global_end: 0, - extend_first: 0, - extend_last: 0, - loop_clip: false, - reverse: false, - }; - assert!(cache.load_clip(&clip, 0, false, [None; 4]).is_none()); - assert!(!cache.shared.path_exists_cached(&img_path)); - - let _ = std::fs::remove_dir_all(&dir); - } - - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn prefetch_queue_prunes_stale_and_avoids_hol_blocking() { - let dir = std::env::temp_dir().join(format!("fission_hol_prefetch_{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - - for i in 0..=10 { - let p = dir.join(format!("seq_{i:04}.png")); - image::RgbaImage::from_pixel(2, 2, image::Rgba([i as u8 * 20, 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, 10 }}, - GlobalRange = {{ 0, 10 }}, - Tools = ordered() {{ - LD = Loader {{ - Clips = {{ - Clip {{ - ID = "Clip1", - Filename = "{}", - FormatID = "PNGFormat", - StartFrame = 0, - Length = 11, - GlobalStart = 0, - GlobalEnd = 10, - }}, - }}, - }}, - }}, -}}"#, - esc(&p0) - ); - let comp = Comp::from_fusion_str(&comp_src).expect("parse hol 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(2); - // Enqueue far-future seq=10 first (outside lookahead=2), then seq=1 (within lookahead). - handle.enqueue_frame(&comp, target, 10, 10.0, &expr, false); - handle.enqueue_frame(&comp, target, 1, 1.0, &expr, false); - - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); - while cache.entry_count() < 1 && std::time::Instant::now() < deadline { - std::thread::sleep(std::time::Duration::from_millis(5)); - } - assert_eq!(cache.entry_count(), 1); - let (_, _, img1, from_disk1) = cache.load_clip(&clip, 1, false, [None; 4]).unwrap(); - assert!(!from_disk1, "seq=1 must not be head-of-line blocked by seq=10"); - assert_eq!(img1.rgba[0], 20); - - // Advancing current_seq past 10 prunes seq=10 cleanly. - handle.set_current_seq(11); - { - let q = handle.queue.state.lock().unwrap(); - assert!(q.raster.is_empty()); - assert!(q.queued_raster_keys.is_empty()); - } - handle.cancel(); - let _ = std::fs::remove_dir_all(&dir); - } - - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn prefetch_handle_scales_and_decodes_nine_videos_concurrently() { - let dir = std::env::temp_dir().join(format!("fission_9vid_prefetch_{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - - let v0 = dir.join("v0.mp4"); - let ok = Command::new("ffmpeg") - .args([ - "-y", - "-v", - "error", - "-f", - "lavfi", - "-i", - "color=c=green:size=16x16:rate=24:duration=0.15", - "-c:v", - "libx264", - "-pix_fmt", - "yuv420p", - ]) - .arg(&v0) - .status() - .is_ok_and(|s| s.success()); - if !ok { - let _ = std::fs::remove_dir_all(&dir); - return; - } - - let esc = |p: &Path| p.to_string_lossy().replace('\\', "\\\\"); - let mut tools = String::new(); - for i in 0..9 { - let vi = dir.join(format!("v{i}.mp4")); - if i > 0 { - std::fs::copy(&v0, &vi).unwrap(); - } - tools.push_str(&format!( - r#" V{i} = Loader {{ - Clips = {{ - Clip {{ - ID = "Clip1", - Filename = "{}", - FormatID = "QuickTimeMovies", - Length = 3, - GlobalStart = 0, - GlobalEnd = 2, - }}, - }}, - }}, -"#, - esc(&vi) - )); - } - let mut prev = "V0".to_owned(); - for i in 1..9 { - let mname = format!("M{i}"); - tools.push_str(&format!( - r#" {mname} = Merge {{ - Inputs = {{ - Background = Input {{ SourceOp = "{prev}", Source = "Output", }}, - Foreground = Input {{ SourceOp = "V{i}", Source = "Output", }}, - }}, - }}, -"# - )); - prev = mname; - } - let comp_src = format!( - "Composition {{\n CurrentTime = 0,\n RenderRange = {{ 0, 2 }},\n GlobalRange = {{ 0, 2 }},\n Tools = ordered() {{\n{tools} }},\n}}" - ); - let comp = Comp::from_fusion_str(&comp_src).expect("parse 9-video comp"); - let target = comp.find_node("M8").expect("M8"); - let expr = model::ExprEngine::new(); - let cache = MediaCache::new(64); - - let mut handle = cache.start_frame_prefetch(4); - let expected_workers = std::thread::available_parallelism() - .map(|n| n.get().clamp(2, 12)) - .unwrap_or(4); - assert_eq!(handle.workers.len(), expected_workers); - - handle.enqueue_frame(&comp, target, 0, 0.0, &expr, false); - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); - while cache.entry_count() < 9 && std::time::Instant::now() < deadline { - std::thread::sleep(std::time::Duration::from_millis(5)); - } - assert_eq!(cache.video_decoder_count(), 9); - assert_eq!(cache.entry_count(), 9); - handle.cancel(); - let _ = std::fs::remove_dir_all(&dir); - } - - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn warm_cache_over_75_percent_keeps_full_lookahead() { - let dir = std::env::temp_dir().join(format!("fission_warm_lookahead_{}", 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(512, 512, image::Rgba([i as u8 * 40, 20, 180, 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, 4 }}, - GlobalRange = {{ 0, 4 }}, - Tools = ordered() {{ - LD = Loader {{ - Clips = {{ - Clip {{ - ID = "Clip1", - Filename = "{}", - FormatID = "PNGFormat", - StartFrame = 0, - Length = 5, - GlobalStart = 0, - GlobalEnd = 4, - }}, - }}, - }}, - }}, -}}"#, - esc(&p0) - ); - let comp = Comp::from_fusion_str(&comp_src).expect("parse warm lookahead 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); - - // Warm the cache past 75% of its 64 MiB budget (13 x 4 MiB = 52 MiB = 81.25%). - let four_mb = Arc::new(vec![128u8; 1024 * 1024 * 4]); - { - let mut state = cache.shared.state.lock().unwrap(); - for i in 0..13 { - let key = ImageCacheKey { - path: dir.join(format!("warm_{i:04}.png")), - frame_idx: -1, - post_multiply: false, - exr_channels: [None, None, None, None], - }; - let img = DecodedImage { - size: [1024, 1024], - rgba: Arc::clone(&four_mb), - rgba_f16: None, - rgba_f32: None, - }; - cache.shared.insert_cached_locked(&mut state, key, img); - } - } - assert!( - cache.total_mb() > 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); - } - - #[test] - fn direct_png_decode_matches_image_crate_bit_for_bit_all_color_types() { - fn encode_png( - w: u32, - h: u32, - color: png::ColorType, - depth: png::BitDepth, - palette: Option<&[u8]>, - trns: Option<&[u8]>, - data: &[u8], - ) -> Vec { - let mut out = Vec::new(); - { - let mut enc = png::Encoder::new(&mut out, w, h); - enc.set_color(color); - enc.set_depth(depth); - if let Some(p) = palette { - enc.set_palette(p); - } - if let Some(t) = trns { - enc.set_trns(t); - } - let mut writer = enc.write_header().unwrap(); - writer.write_image_data(data).unwrap(); - } - out - } - - let (w, h) = (17u32, 11u32); - let n = (w * h) as usize; - let cases: Vec<(&str, Vec)> = vec![ - ( - "rgba8", - encode_png( - w, - h, - png::ColorType::Rgba, - png::BitDepth::Eight, - None, - None, - &(0..n * 4).map(|i| ((i * 37 + 13) % 256) as u8).collect::>(), - ), - ), - ( - "rgb8", - encode_png( - w, - h, - png::ColorType::Rgb, - png::BitDepth::Eight, - None, - None, - &(0..n * 3).map(|i| ((i * 53 + 7) % 256) as u8).collect::>(), - ), - ), - ( - "gray8", - encode_png( - w, - h, - png::ColorType::Grayscale, - png::BitDepth::Eight, - None, - None, - &(0..n).map(|i| ((i * 29 + 3) % 256) as u8).collect::>(), - ), - ), - ( - "gray_alpha8", - encode_png( - w, - h, - png::ColorType::GrayscaleAlpha, - png::BitDepth::Eight, - None, - None, - &(0..n * 2).map(|i| ((i * 41 + 19) % 256) as u8).collect::>(), - ), - ), - ( - "palette_trns", - encode_png( - w, - h, - png::ColorType::Indexed, - png::BitDepth::Eight, - Some(&[10, 20, 30, 200, 150, 50, 0, 255, 128, 255, 255, 255]), - Some(&[0, 128, 255]), - &(0..n).map(|i| (i % 4) as u8).collect::>(), - ), - ), - ( - "palette_opaque", - encode_png( - w, - h, - png::ColorType::Indexed, - png::BitDepth::Eight, - Some(&[10, 20, 30, 200, 150, 50, 0, 255, 128]), - None, - &(0..n).map(|i| (i % 3) as u8).collect::>(), - ), - ), - ( - "rgba16", - encode_png( - w, - h, - png::ColorType::Rgba, - png::BitDepth::Sixteen, - None, - None, - // Include boundary values like 0x01ff (511 -> rounds to 2, not 1). - &(0..n * 4) - .flat_map(|i| (((i * 1021 + 255) % 65536) as u16).to_be_bytes()) - .collect::>(), - ), - ), - ( - "rgb16", - encode_png( - w, - h, - png::ColorType::Rgb, - png::BitDepth::Sixteen, - None, - None, - &(0..n * 3) - .flat_map(|i| (((i * 997 + 511) % 65536) as u16).to_be_bytes()) - .collect::>(), - ), - ), - ( - "gray16", - encode_png( - w, - h, - png::ColorType::Grayscale, - png::BitDepth::Sixteen, - None, - None, - &(0..n) - .flat_map(|i| (((i * 773 + 128) % 65536) as u16).to_be_bytes()) - .collect::>(), - ), - ), - ( - "gray_alpha16", - encode_png( - w, - h, - png::ColorType::GrayscaleAlpha, - png::BitDepth::Sixteen, - None, - None, - &(0..n * 2) - .flat_map(|i| (((i * 613 + 384) % 65536) as u16).to_be_bytes()) - .collect::>(), - ), - ), - ]; - - for (label, bytes) in cases { - let dyn_img = image::load_from_memory(&bytes).expect("image crate decode"); - let expected_has_alpha = dyn_img.color().has_alpha(); - let expected_size = [dyn_img.width(), dyn_img.height()]; - let expected_rgba = dyn_img.into_rgba8().into_raw(); - - let (got_size, got_rgba, got_has_alpha) = match decode_png_bytes(&bytes) { - PngDecodeOutcome::Decoded(v) => v, - PngDecodeOutcome::Fallback | PngDecodeOutcome::Reject => { - panic!("direct decode failed for {label}") - } - }; - assert_eq!(got_size, expected_size, "size mismatch for {label}"); - assert_eq!(got_has_alpha, expected_has_alpha, "alpha flag mismatch for {label}"); - assert_eq!(got_rgba, expected_rgba, "pixel mismatch for {label}"); - } - } - - #[test] - fn reject_spoofed_oversized_png_ihdr_without_allocating() { - fn png_crc32(data: &[u8]) -> u32 { - let mut crc = 0xFFFF_FFFFu32; - for &b in data { - crc ^= b as u32; - for _ in 0..8 { - let mask = (crc & 1).wrapping_neg(); - crc = (crc >> 1) ^ (0xEDB8_8320 & mask); - } - } - !crc - } - - fn push_chunk(out: &mut Vec, chunk_type: &[u8; 4], payload: &[u8]) { - out.extend_from_slice(&(payload.len() as u32).to_be_bytes()); - let crc_start = out.len(); - out.extend_from_slice(chunk_type); - out.extend_from_slice(payload); - let crc = png_crc32(&out[crc_start..]); - out.extend_from_slice(&crc.to_be_bytes()); - } - - let mut crafted = vec![137, 80, 78, 71, 13, 10, 26, 10]; - let mut ihdr = [0u8; 13]; - ihdr[0..4].copy_from_slice(&16u32.to_be_bytes()); - ihdr[4..8].copy_from_slice(&1_000_000_000u32.to_be_bytes()); - ihdr[8] = 8; // bit depth - ihdr[9] = 6; // RGBA - push_chunk(&mut crafted, b"IHDR", &ihdr); - push_chunk(&mut crafted, b"IDAT", &[0x78, 0x9c, 0x03, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00]); - push_chunk(&mut crafted, b"IEND", &[]); - assert_eq!(crafted.len(), 67); - - assert!(matches!(decode_png_bytes(&crafted), PngDecodeOutcome::Reject)); - assert!(decode_raster_bytes(&crafted).is_none()); - } -} diff --git a/crates/engine/src/media/png.rs b/crates/engine/src/media/png.rs new file mode 100644 index 0000000000000000000000000000000000000000..b61109f7ae23de067013d00d1847c5957e9bbfaf --- /dev/null +++ b/crates/engine/src/media/png.rs @@ -0,0 +1,250 @@ +use ::png; +use super::*; + +#[inline(always)] +fn u16_be_to_u8_rounded(hi: u8, lo: u8) -> u8 { + ((u16::from_be_bytes([hi, lo]) as u32 + 128) / 257) as u8 +} + +const MAX_PNG_OUTPUT_BYTES: usize = 512 * 1024 * 1024; + +pub(super) enum PngDecodeOutcome { + Decoded(([u32; 2], Vec, bool)), + Fallback, + Reject, +} + +fn decode_png_rows( + reader: &mut png::Reader, + line_size: usize, + out_len: usize, + row_out_bytes: usize, + mut convert_row: F, +) -> Option> +where + F: FnMut(&[u8], &mut [u8]), +{ + let mut rgba = Vec::new(); + rgba.try_reserve_exact(out_len).ok()?; + rgba.resize(out_len, 0); + let mut row_buf = Vec::new(); + row_buf.try_reserve_exact(line_size).ok()?; + row_buf.resize(line_size, 0); + for dst_row in rgba.chunks_exact_mut(row_out_bytes) { + reader.read_row(&mut row_buf).ok()??; + convert_row(&row_buf, dst_row); + } + Some(rgba) +} + +/// Fast direct PNG decoder matching `image::load_from_memory().into_rgba8()` bit-for-bit. +/// Returns `Fallback` for non-PNG, interlaced, animated, ICC-tagged, or unusual formats so the +/// caller falls back cleanly to `image::load_from_memory`, and `Reject` for corrupt or +/// oversized PNGs so callers fail immediately without double-decoding or OOM. +pub(super) fn decode_png_bytes(bytes: &[u8]) -> PngDecodeOutcome { + const PNG_SIGNATURE: [u8; 8] = [137, 80, 78, 71, 13, 10, 26, 10]; + if !bytes.starts_with(&PNG_SIGNATURE) { + return PngDecodeOutcome::Fallback; + } + + let mut decoder = png::Decoder::new_with_limits( + std::io::Cursor::new(bytes), + png::Limits { + bytes: MAX_PNG_OUTPUT_BYTES, + }, + ); + decoder.set_ignore_text_chunk(true); + decoder.set_transformations(png::Transformations::EXPAND); + + let Ok(mut reader) = decoder.read_info() else { + return PngDecodeOutcome::Reject; + }; + let info = reader.info(); + let (w, h) = info.size(); + if w == 0 || h == 0 { + return PngDecodeOutcome::Reject; + } + + let Some(pixel_count) = (w as usize).checked_mul(h as usize) else { + return PngDecodeOutcome::Reject; + }; + let Some(out_len) = pixel_count.checked_mul(4) else { + return PngDecodeOutcome::Reject; + }; + if out_len > MAX_PNG_OUTPUT_BYTES { + return PngDecodeOutcome::Reject; + } + + if info.interlaced + || info.icc_profile.is_some() + || info.animation_control.is_some() + || info.frame_control.is_some() + { + return PngDecodeOutcome::Fallback; + } + + let (color_type, bit_depth) = reader.output_color_type(); + let Some(row_out_bytes) = (w as usize).checked_mul(4) else { + return PngDecodeOutcome::Reject; + }; + let Some(line_size) = reader.output_line_size(w) else { + return PngDecodeOutcome::Reject; + }; + + match (color_type, bit_depth) { + (png::ColorType::Rgba, png::BitDepth::Eight) => { + let mut rgba = Vec::new(); + if rgba.try_reserve_exact(out_len).is_err() { + return PngDecodeOutcome::Reject; + } + rgba.resize(out_len, 0); + if reader.next_frame(&mut rgba).is_err() { + return PngDecodeOutcome::Reject; + } + PngDecodeOutcome::Decoded(([w, h], rgba, true)) + } + (png::ColorType::Rgb, png::BitDepth::Eight) => { + let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| { + let (src_chunks, _) = src.as_chunks::<3>(); + let (dst_chunks, _) = dst.as_chunks_mut::<4>(); + for (&[r, g, b], dst_px) in src_chunks.iter().zip(dst_chunks) { + *dst_px = [r, g, b, 255]; + } + }) else { + return PngDecodeOutcome::Reject; + }; + PngDecodeOutcome::Decoded(([w, h], rgba, false)) + } + (png::ColorType::Grayscale, png::BitDepth::Eight) => { + let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| { + let (dst_chunks, _) = dst.as_chunks_mut::<4>(); + for (&g, dst_px) in src.iter().zip(dst_chunks) { + *dst_px = [g, g, g, 255]; + } + }) else { + return PngDecodeOutcome::Reject; + }; + PngDecodeOutcome::Decoded(([w, h], rgba, false)) + } + (png::ColorType::GrayscaleAlpha, png::BitDepth::Eight) => { + let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| { + let (src_chunks, _) = src.as_chunks::<2>(); + let (dst_chunks, _) = dst.as_chunks_mut::<4>(); + for (&[g, a], dst_px) in src_chunks.iter().zip(dst_chunks) { + *dst_px = [g, g, g, a]; + } + }) else { + return PngDecodeOutcome::Reject; + }; + PngDecodeOutcome::Decoded(([w, h], rgba, true)) + } + (png::ColorType::Rgba, png::BitDepth::Sixteen) => { + let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| { + let (src_chunks, _) = src.as_chunks::<8>(); + let (dst_chunks, _) = dst.as_chunks_mut::<4>(); + for (&s, dst_px) in src_chunks.iter().zip(dst_chunks) { + *dst_px = [ + u16_be_to_u8_rounded(s[0], s[1]), + u16_be_to_u8_rounded(s[2], s[3]), + u16_be_to_u8_rounded(s[4], s[5]), + u16_be_to_u8_rounded(s[6], s[7]), + ]; + } + }) else { + return PngDecodeOutcome::Reject; + }; + PngDecodeOutcome::Decoded(([w, h], rgba, true)) + } + (png::ColorType::Rgb, png::BitDepth::Sixteen) => { + let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| { + let (src_chunks, _) = src.as_chunks::<6>(); + let (dst_chunks, _) = dst.as_chunks_mut::<4>(); + for (&s, dst_px) in src_chunks.iter().zip(dst_chunks) { + *dst_px = [ + u16_be_to_u8_rounded(s[0], s[1]), + u16_be_to_u8_rounded(s[2], s[3]), + u16_be_to_u8_rounded(s[4], s[5]), + 255, + ]; + } + }) else { + return PngDecodeOutcome::Reject; + }; + PngDecodeOutcome::Decoded(([w, h], rgba, false)) + } + (png::ColorType::Grayscale, png::BitDepth::Sixteen) => { + let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| { + let (src_chunks, _) = src.as_chunks::<2>(); + let (dst_chunks, _) = dst.as_chunks_mut::<4>(); + for (&[hi, lo], dst_px) in src_chunks.iter().zip(dst_chunks) { + let g = u16_be_to_u8_rounded(hi, lo); + *dst_px = [g, g, g, 255]; + } + }) else { + return PngDecodeOutcome::Reject; + }; + PngDecodeOutcome::Decoded(([w, h], rgba, false)) + } + (png::ColorType::GrayscaleAlpha, png::BitDepth::Sixteen) => { + let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| { + let (src_chunks, _) = src.as_chunks::<4>(); + let (dst_chunks, _) = dst.as_chunks_mut::<4>(); + for (&s, dst_px) in src_chunks.iter().zip(dst_chunks) { + let g = u16_be_to_u8_rounded(s[0], s[1]); + *dst_px = [g, g, g, u16_be_to_u8_rounded(s[2], s[3])]; + } + }) else { + return PngDecodeOutcome::Reject; + }; + PngDecodeOutcome::Decoded(([w, h], rgba, true)) + } + _ => PngDecodeOutcome::Fallback, + } +} + +pub(super) fn decode_raster_bytes(bytes: &[u8]) -> Option<([u32; 2], Vec, bool)> { + match decode_png_bytes(bytes) { + PngDecodeOutcome::Decoded(decoded) => return Some(decoded), + PngDecodeOutcome::Reject => return None, + PngDecodeOutcome::Fallback => {} + } + let dyn_img = image::load_from_memory(bytes).ok()?; + let has_alpha = dyn_img.color().has_alpha(); + let size = [dyn_img.width(), dyn_img.height()]; + let raw = dyn_img.into_rgba8().into_raw(); + Some((size, raw, has_alpha)) +} + +fn open_raster_rgba(path: &Path) -> Option<([u32; 2], Vec, bool)> { + if let Some(bytes) = virtual_bytes(path) { + return decode_raster_bytes(&bytes); + } + // Read file contents in one contiguous pass to avoid tiny buffered syscalls over SMB/network shares. + match std::fs::read(path) { + Ok(bytes) => return decode_raster_bytes(&bytes), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return None, + Err(_) => {} + } + let dyn_img = image::open(path).ok()?; + let has_alpha = dyn_img.color().has_alpha(); + let size = [dyn_img.width(), dyn_img.height()]; + let raw = dyn_img.into_rgba8().into_raw(); + Some((size, raw, has_alpha)) +} + +pub(super) fn decode_raster_image( + path: &Path, + post_multiply: bool, + allow_parallel_premult: bool, +) -> Option { + let (size, mut raw, has_alpha) = open_raster_rgba(path)?; + if post_multiply && has_alpha { + apply_post_multiply_rgba8_parallel(&mut raw, allow_parallel_premult); + } + Some(DecodedImage { + size, + rgba: Arc::new(raw), + rgba_f16: None, + rgba_f32: None, + }) +} diff --git a/crates/engine/src/media/prefetch.rs b/crates/engine/src/media/prefetch.rs new file mode 100644 index 0000000000000000000000000000000000000000..078a6b56e0bed815822d445e0eb85c8ae899ec78 --- /dev/null +++ b/crates/engine/src/media/prefetch.rs @@ -0,0 +1,1309 @@ +use super::*; + +#[cfg(not(target_arch = "wasm32"))] +impl MediaState { + pub(super) 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; + } + + pub(super) 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; + } + } + + pub(super) 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 + } +} + +impl MediaShared { + pub(super) fn sync_lookahead_throttle(&self, state: &MediaState) -> bool { + #[cfg(not(target_arch = "wasm32"))] + { + 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; + 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"))] + pub(super) 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(); + } + } + } +} + +impl MediaCache { + /// Walks reachable `Loader` nodes upstream of `target` at `time` and decodes any missing + /// still/sequence/EXR frames into RAM in parallel when 2 or more distinct files are uncached. + pub fn preload_frame_loaders( + &mut self, + comp: &Comp, + target: NodeId, + time: f64, + expr: &model::ExprEngine, + ) { + self.preload_frame_loaders_with_proxy(comp, target, time, expr, false); + } + + /// Variant of [`Self::preload_frame_loaders`] honoring `use_proxy_clips`. + pub fn preload_frame_loaders_with_proxy( + &mut self, + comp: &Comp, + target: NodeId, + time: f64, + expr: &model::ExprEngine, + use_proxy_clips: bool, + ) { + #[cfg(target_arch = "wasm32")] + { + let _ = (comp, target, time, expr, use_proxy_clips); + } + #[cfg(not(target_arch = "wasm32"))] + { + 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() < 2 { + return; + } + self.decode_jobs_parallel(jobs); + } + } + + /// Pre-decodes reachable `Loader` files for upcoming `frames` in parallel into `MediaCache`. + pub fn prefetch_frames( + &mut self, + comp: &Comp, + target: NodeId, + frames: &[f64], + expr: &model::ExprEngine, + ) { + self.prefetch_frames_with_proxy(comp, target, frames, expr, false); + } + + /// Variant of [`Self::prefetch_frames`] honoring `use_proxy_clips`. + pub fn prefetch_frames_with_proxy( + &mut self, + comp: &Comp, + target: NodeId, + frames: &[f64], + expr: &model::ExprEngine, + use_proxy_clips: bool, + ) { + #[cfg(target_arch = "wasm32")] + { + let _ = (comp, target, frames, expr, use_proxy_clips); + } + #[cfg(not(target_arch = "wasm32"))] + { + if frames.is_empty() { + return; + } + let mut visited = HashSet::new(); + let mut jobs = MissingJobs::default(); + for &time in frames { + collect_missing_loader_jobs_shared( + &self.shared, + comp, + target, + time, + expr, + use_proxy_clips, + &mut visited, + &mut jobs, + ); + } + let total = jobs.total_units(); + if total == 0 { + return; + } + 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()); + self.shared.sync_lookahead_throttle(&state); + state.generation + }; + let mut guard = InFlightGuard { + shared: &self.shared, + 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, false); + return; + } + self.decode_jobs_parallel(jobs); + } + } + + /// 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)| VideoDecodeTask { path, requests }) + .collect(); + let video_count = video_tasks.len(); + let raster_jobs = jobs.raster; + let total_units = video_count + raster_jobs.len(); + if total_units == 0 { + return; + } + let workers = std::thread::available_parallelism() + .map(|n| n.get().clamp(2, 12)) + .unwrap_or(4) + .min(total_units); + + let next_idx = AtomicUsize::new(0); + let video_inputs: Vec>> = + video_tasks.drain(..).map(|t| Mutex::new(Some(t))).collect(); + + std::thread::scope(|scope| { + for _ in 0..workers { + scope.spawn(|| loop { + let idx = next_idx.fetch_add(1, Ordering::Relaxed); + if idx >= total_units { + break; + } + if idx < video_count { + let task = video_inputs[idx].lock().ok().and_then(|mut g| g.take()); + 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( + &req.clip, + req.frame_i, + info.nb_frames, + ); + if !seen_local.insert((frame_idx, req.post_multiply)) { + continue; + } + 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()); + self.shared.sync_lookahead_throttle(&state); + 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 decoded = DecodedImage { + size: [info.width, info.height], + rgba: Arc::new(raw), + rgba_f16: None, + rgba_f32: None, + }; + let unthrottled = if let Ok(mut state) = self.shared.state.lock() { + state.in_flight.remove(&key); + guard.key = None; + let unthrottled = if state.generation == cache_gen { + self.shared + .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(); + } + } + } + } + } + } else { + let r_idx = idx - video_count; + 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()); + self.shared.sync_lookahead_throttle(&state); + 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()), + }; + let decoded = decode_job(job, false); + finish_raster_job( + &self.shared, + job.cache_key.clone(), + cache_gen, + &mut guard, + decoded, + false, + ); + } + }); + } + }); + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn finish_raster_job( + shared: &MediaShared, + key: ImageCacheKey, + cache_gen: u64, + guard: &mut InFlightGuard<'_>, + decoded: Option, + is_speculative: bool, +) { + let unthrottled = if let Ok(mut state) = shared.state.lock() { + state.in_flight.remove(&key); + guard.key = None; + let unthrottled = if let Some(decoded) = decoded { + if state.generation == cache_gen { + state.record_existing_path(&key.path); + 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(); + } +} + +#[cfg(not(target_arch = "wasm32"))] +pub(super) struct PrefetchQueueState { + pub(super) raster: VecDeque<(usize, PreloadJob)>, + videos: HashMap>, + active_videos: HashSet, + pub(super) queued_raster_keys: HashSet, + current_seq: usize, + lookahead: usize, + cancelled: bool, +} + +#[cfg(not(target_arch = "wasm32"))] +impl PrefetchQueueState { + fn prune_stale(&mut self) { + let cur = self.current_seq; + if self.raster.iter().any(|&(seq, _)| seq < cur) { + let mut kept = VecDeque::with_capacity(self.raster.len()); + while let Some((seq, job)) = self.raster.pop_front() { + if seq >= cur { + kept.push_back((seq, job)); + } else { + self.queued_raster_keys.remove(&job.cache_key); + } + } + self.raster = kept; + } + self.videos.retain(|_, vq| { + vq.retain(|&(seq, _)| seq >= cur); + !vq.is_empty() + }); + } +} + +#[cfg(not(target_arch = "wasm32"))] +pub(super) struct PrefetchQueue { + pub(super) state: Mutex, + cv: Condvar, +} + +#[cfg(not(target_arch = "wasm32"))] +enum PrefetchWorkItem { + Raster(usize, usize, PreloadJob), + Video(usize, usize, PathBuf, VideoFrameRequest), +} + +/// 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, + pub(super) queue: Arc, + pub(super) 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(), + }); + shared.register_prefetch_queue(&queue); + let worker_count = std::thread::available_parallelism() + .map(|n| n.get().clamp(2, 12)) + .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, + } + } + + /// 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(); + self.queue.cv.notify_all(); + } + } + + /// Enqueues missing `Loader` decodes for `time` at sequence index `seq_idx`. + pub fn enqueue_frame( + &self, + comp: &Comp, + target: NodeId, + seq_idx: usize, + time: f64, + expr: &model::ExprEngine, + use_proxy_clips: bool, + ) { + 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; + } + if let Ok(mut q) = self.queue.state.lock() { + if q.cancelled || seq_idx < q.current_seq { + 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 { + if let Some((existing_seq, _)) = vq.iter_mut().find(|(_, existing)| { + existing.post_multiply == req.post_multiply + && match (existing.resolved_frame_idx, req.resolved_frame_idx) { + (Some(a), Some(b)) => a == b, + _ => { + existing.frame_i == req.frame_i + && existing.clip.global_start == req.clip.global_start + && existing.clip.trim_in == req.clip.trim_in + && existing.clip.trim_out == req.clip.trim_out + && existing.clip.reverse == req.clip.reverse + && existing.clip.loop_clip == req.clip.loop_clip + } + } + }) { + *existing_seq = (*existing_seq).min(seq_idx); + } else { + vq.push_back((seq_idx, req)); + } + } + } + self.queue.cv.notify_all(); + } + } + + /// 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(); + } + } + + 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 best_raster = q + .raster + .iter() + .enumerate() + .min_by_key(|&(_, (seq, _))| *seq) + .map(|(idx, (seq, _))| (idx, *seq)); + let mut best_video: Option<(&PathBuf, usize, usize)> = None; + for (path, vq) in &q.videos { + if q.active_videos.contains(path) { + continue; + } + if let Some((v_idx, &(seq, _))) = + vq.iter().enumerate().min_by_key(|&(_, (seq, _))| *seq) + { + if best_video.as_ref().is_none_or(|&(_, _, bseq)| seq < bseq) { + best_video = Some((path, v_idx, seq)); + } + } + } + + let chosen_seq = match (best_raster, &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) + && shared.lookahead_throttled.load(Ordering::Acquire) + { + q = match queue.cv.wait(q) { + Ok(g) => g, + Err(_) => return, + }; + 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((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(seq, cur_seq, path, req); + } + } + if let Some((r_idx, _)) = best_raster { + if let Some((seq, job)) = q.raster.remove(r_idx) { + q.queued_raster_keys.remove(&job.cache_key); + break PrefetchWorkItem::Raster(seq, cur_seq, job); + } + } + } + }; + + match item { + 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) + { + None + } else { + state.in_flight.insert(job.cache_key.clone()); + shared.sync_lookahead_throttle(&state); + Some(state.generation) + } + }); + let Some(cache_gen) = cache_gen_opt else { continue }; + let mut guard = InFlightGuard { + shared: &shared, + key: Some(job.cache_key.clone()), + }; + let decoded = decode_job(&job, false); + finish_raster_job( + &shared, + job.cache_key, + cache_gen, + &mut guard, + decoded, + item_seq > cur_seq, + ); + } + PrefetchWorkItem::Video(item_seq, cur_seq, 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()); + shared.sync_lookahead_throttle(&state); + 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, + }; + let unthrottled = if let Ok(mut state) = shared.state.lock() { + state.in_flight.remove(&key); + guard.key = None; + 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(); + } + } + } + } + } + } +} + +#[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, +) { + const MAX_PRELOAD_DEPTH: usize = 256; + if node_id.0 >= comp.nodes.len() || jobs.depth >= MAX_PRELOAD_DEPTH { + return; + } + let time_key = (if time == 0.0 { 0.0 } else { time }).to_bits() as i64; + if !visited.insert((node_id, time_key)) { + return; + } + jobs.depth += 1; + collect_missing_loader_jobs_inner( + shared, + comp, + node_id, + time, + expr, + use_proxy_clips, + visited, + jobs, + ); + jobs.depth -= 1; +} + +#[cfg(not(target_arch = "wasm32"))] +#[allow(clippy::too_many_arguments)] +fn collect_missing_loader_jobs_inner( + shared: &MediaShared, + comp: &Comp, + node_id: NodeId, + time: f64, + expr: &model::ExprEngine, + use_proxy_clips: bool, + visited: &mut HashSet<(NodeId, i64)>, + jobs: &mut MissingJobs, +) { + 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 { + 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; + } + 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) + } 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, + fg_id, + time, + expr, + use_proxy_clips, + visited, + jobs, + ); + } + } + 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 == "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 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.saturating_sub(effective_clip.extend_first.max(0)) + || (!effective_clip.loop_clip + && frame_i > effective_clip.global_end.saturating_add(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 mut resolved_frame_idx = effective_clip + .length + .map(|_| compute_video_frame_idx(&effective_clip, frame_i, 1)); + let need_decode = shared.state.lock().is_ok_and(|state| { + match state.video_decoders.get(base) { + Some(slot) => { + let idx = compute_video_frame_idx( + &effective_clip, + frame_i, + slot.info.nb_frames, + ); + resolved_frame_idx = Some(idx); + let cache_key = ImageCacheKey { + path: base.to_path_buf(), + frame_idx: idx, + post_multiply: post_mult, + exr_channels: [None, None, None, None], + }; + !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, + resolved_frame_idx, + }); + } + } + } 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) { + collect_missing_loader_jobs_shared( + shared, + 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); + } + } + } + } + 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, + ); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[derive(Default)] +struct MissingJobs { + raster: Vec, + seen_raster: HashSet, + videos: HashMap>, + depth: usize, +} + +#[cfg(not(target_arch = "wasm32"))] +impl MissingJobs { + fn total_units(&self) -> usize { + self.raster.len() + self.videos.len() + } +} + +#[cfg(not(target_arch = "wasm32"))] +struct VideoFrameRequest { + clip: ClipSpec, + frame_i: i64, + post_multiply: bool, + resolved_frame_idx: Option, +} + +#[cfg(not(target_arch = "wasm32"))] +struct VideoDecodeTask { + path: PathBuf, + requests: Vec, +} + +#[cfg(not(target_arch = "wasm32"))] +pub(super) struct PreloadJob { + cache_key: ImageCacheKey, + is_exr: bool, +} + +#[cfg(not(target_arch = "wasm32"))] +fn decode_job(job: &PreloadJob, allow_parallel: bool) -> Option { + if job.is_exr { + decode_exr_rgba( + &job.cache_key.path, + job.cache_key.exr_channels[0].as_deref(), + job.cache_key.exr_channels[1].as_deref(), + job.cache_key.exr_channels[2].as_deref(), + job.cache_key.exr_channels[3].as_deref(), + false, + allow_parallel, + ) + } else { + decode_raster_image( + &job.cache_key.path, + job.cache_key.post_multiply, + allow_parallel, + ) + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn resolve_effect_mask_id_for_node(comp: &Comp, node: &Node) -> Option { + if let Some(id) = node.connected_node("EffectMask").and_then(|s| comp.find_node(s)) { + return Some(id); + } + let has_explicit_mask_entry = |n: &Node| -> bool { + n.raw + .get_table("Inputs") + .and_then(|t| t.get("EffectMask")) + .is_some() + }; + if has_explicit_mask_entry(node) { + return None; + } + let mut visited = HashSet::new(); + visited.insert(node.id); + let mut cur = node; + for _ in 0..8 { + let master_name = cur.raw.get_str("SourceOp")?; + let mid = comp.find_node(master_name)?; + if !visited.insert(mid) { + break; + } + let master = comp.node(mid); + if let Some(mask_id) = master.connected_node("EffectMask").and_then(|s| comp.find_node(s)) { + return Some(mask_id); + } + if has_explicit_mask_entry(master) { + return None; + } + cur = master; + } + None +} diff --git a/crates/engine/src/media/tests.rs b/crates/engine/src/media/tests.rs new file mode 100644 index 0000000000000000000000000000000000000000..30ff9862dc8e375a60f7337c6adb896e37b0d77d --- /dev/null +++ b/crates/engine/src/media/tests.rs @@ -0,0 +1,1452 @@ +use ::png; +use super::*; +use std::time::Instant; + +#[test] +fn decoded_image_cache_separates_post_multiply() { + let dir = std::env::temp_dir().join("fission_media_post_multiply_key_test"); + std::fs::create_dir_all(&dir).unwrap(); + let png = dir.join("half.png"); + image::RgbaImage::from_pixel(2, 2, image::Rgba([200, 100, 50, 128])).save(&png).unwrap(); + let clip = ClipSpec { + filename: png.to_string_lossy().into_owned(), + alternate_filename: None, + start_frame: 0, + length: Some(1), + trim_in: 0, + trim_out: 0, + global_start: 0, + global_end: 0, + extend_first: 0, + extend_last: 0, + loop_clip: false, + reverse: false, + }; + let mut cache = MediaCache::new(64); + let mut first_px = |post_multiply| { + let (_, _, img, from_disk) = cache.load_clip(&clip, 0, post_multiply, [None; 4]).unwrap(); + (img.rgba[..4].to_vec(), from_disk) + }; + assert_eq!(first_px(false), (vec![200, 100, 50, 128], true)); + assert_eq!(first_px(true), (vec![100, 50, 25, 128], true)); + assert_eq!(first_px(false), (vec![200, 100, 50, 128], false)); + assert_eq!(first_px(true), (vec![100, 50, 25, 128], false)); + assert_eq!(cache.entry_count(), 2); + let _ = std::fs::remove_dir_all(&dir); +} + +fn mean_abs_error_rgb(a: &[u8], b: &[u8]) -> f64 { + assert_eq!(a.len(), b.len()); + let mut sum = 0u64; + let mut count = 0u64; + for (pa, pb) in a.chunks_exact(4).zip(b.chunks_exact(4)) { + sum += pa[0].abs_diff(pb[0]) as u64; + sum += pa[1].abs_diff(pb[1]) as u64; + sum += pa[2].abs_diff(pb[2]) as u64; + count += 3; + } + if count == 0 { + 0.0 + } else { + sum as f64 / count as f64 + } +} + +fn verify_clip_matches_ffmpeg(path: &Path) { + let mut dec = open_video_decoder(path).expect("open_video_decoder failed"); + let mut ff = FfmpegDecoder::open(path).expect("FfmpegDecoder::open failed"); + + #[cfg(target_os = "macos")] + assert_eq!( + dec.backend_name(), + "AVFoundation/VideoToolbox", + "expected AVFoundation backend for {}", + path.display() + ); + + let av_info = dec.info(); + let ff_info = ff.info(); + assert_eq!(av_info.width, ff_info.width, "width mismatch for {}", path.display()); + assert_eq!(av_info.height, ff_info.height, "height mismatch for {}", path.display()); + assert!( + (av_info.fps - ff_info.fps).abs() < 0.2, + "fps mismatch for {}: av={} ff={}", + path.display(), + av_info.fps, + ff_info.fps + ); + + let frames = [0_i64, 1, 2, 10, 0]; + let mut total_ms = 0.0; + for &f in &frames { + let t0 = Instant::now(); + let av_px = dec + .decode_frame(f) + .unwrap_or_else(|| panic!("av decode frame {f} failed for {}", path.display())); + let elapsed_ms = t0.elapsed().as_secs_f64() * 1000.0; + total_ms += elapsed_ms; + + let ff_px = ff + .decode_frame(f) + .unwrap_or_else(|| panic!("ffmpeg decode frame {f} failed for {}", path.display())); + let mae = mean_abs_error_rgb(&av_px, &ff_px); + eprintln!( + "[video-test] {} ({}x{} @{:.2}fps) frame {}: {:.2} ms, MAE vs ffmpeg = {:.2}", + path.file_name().and_then(|s| s.to_str()).unwrap_or("clip"), + av_info.width, + av_info.height, + av_info.fps, + f, + elapsed_ms, + mae + ); + // Allow small YUV->RGB matrix/rounding differences between VideoToolbox and swscale. + assert!( + mae < 12.0, + "high MAE ({mae:.2}) on {} frame {f} (possible orientation or PTS mismatch)", + path.display() + ); + } + eprintln!( + "[video-test] {} avg decode: {:.2} ms/frame", + path.file_name().and_then(|s| s.to_str()).unwrap_or("clip"), + total_ms / frames.len() as f64 + ); +} + +#[test] +fn test_video_decoder_real_mov_clips() { + let clips = [ + Path::new("/Volumes/Project/trees/EncodedMedia/A001_11071331_C002_4873-4988_d8716e17.mov"), + Path::new("/Volumes/Project/trees/EncodedMedia/IMG_1767_2395-2547_7efe6416.mov"), + ]; + for clip in clips { + if clip.exists() { + verify_clip_matches_ffmpeg(clip); + } + } +} + +#[test] +fn test_video_decoder_synthetic_mp4() { + let tmp = std::env::temp_dir().join("engine_test_synth_video.mp4"); + let status = Command::new("ffmpeg") + .args([ + "-y", + "-v", + "error", + "-f", + "lavfi", + "-i", + "testsrc2=size=320x180:rate=24:duration=1.0", + "-c:v", + "libx264", + "-pix_fmt", + "yuv420p", + ]) + .arg(&tmp) + .status(); + if let Ok(st) = status { + if st.success() { + verify_clip_matches_ffmpeg(&tmp); + let _ = std::fs::remove_file(&tmp); + } + } +} + +fn alpha_y_bounds(size: [u32; 2], origin: [i32; 2], rgba: &[u8]) -> (i32, i32) { + let [w, h] = size; + let mut min_y = i32::MAX; + let mut max_y = i32::MIN; + for y in 0..h as usize { + let row = y * w as usize * 4; + for x in 0..w as usize { + if rgba[row + x * 4 + 3] > 32 { + let cy = origin[1] + y as i32; + min_y = min_y.min(cy); + max_y = max_y.max(cy); + break; + } + } + } + (min_y, max_y) +} + +#[test] +fn test_text_plus_calibrated_metrics_and_anchoring() { + let base = |text: &str, v_tcb: f32, line_spacing: f32, dims: [u32; 2]| { + rasterize_text_plus( + dims, + &TextPlusParams { + text, + font_family: "Helvetica Neue", + font_style: "Regular", + size_norm: 0.08, + tracking: 1.0, + line_spacing, + center: [0.5, 0.5], + h_lcr: 0.0, + v_tcb, + fill_rgba: [1.0, 1.0, 1.0, 1.0], + write_on_start: 0.0, + write_on_end: 1.0, + shear_x: 0.0, + cls: &[], + outline_rgba: [0.0; 4], + outline_width_px: 0.0, + }, + 0, + ) + }; + + // 1. VerticalTopCenterBottom: -1 anchors top below cy=270, 0 centers around cy=270, + // +1 anchors bottom baseline at cy=270 (so glyphs sit above cy=270). + let (s_top, o_top, p_top) = base("HHHH", -1.0, 1.0, [960, 540]); + let (s_ctr, o_ctr, p_ctr) = base("HHHH", 0.0, 1.0, [960, 540]); + let (s_bot, o_bot, p_bot) = base("HHHH", 1.0, 1.0, [960, 540]); + let (top_y0, top_y1) = alpha_y_bounds(s_top, o_top, &p_top); + let (ctr_y0, ctr_y1) = alpha_y_bounds(s_ctr, o_ctr, &p_ctr); + let (bot_y0, bot_y1) = alpha_y_bounds(s_bot, o_bot, &p_bot); + assert!(top_y0 >= 268 && top_y1 > 300, "top-aligned should sit below cy=270: ({top_y0}, {top_y1})"); + assert!(ctr_y0 < 270 && ctr_y1 > 270, "center-aligned should straddle cy=270: ({ctr_y0}, {ctr_y1})"); + assert!(bot_y0 < 240 && bot_y1 <= 272, "bottom-aligned should sit above cy=270: ({bot_y0}, {bot_y1})"); + + // 2. LineSpacing=1.5 widens a 2-line block by 0.5 * (0.8 * 0.08 * 960 = 61.44px) = ~30.7px. + let (s_ls1, o_ls1, p_ls1) = base("HHHH\nHHHH", 0.0, 1.0, [960, 540]); + let (s_ls15, o_ls15, p_ls15) = base("HHHH\nHHHH", 0.0, 1.5, [960, 540]); + let (ls1_y0, ls1_y1) = alpha_y_bounds(s_ls1, o_ls1, &p_ls1); + let (ls15_y0, ls15_y1) = alpha_y_bounds(s_ls15, o_ls15, &p_ls15); + let span_diff = (ls15_y1 - ls15_y0) - (ls1_y1 - ls1_y0); + assert!( + (28..=34).contains(&span_diff), + "LineSpacing 1.5 vs 1.0 on 960x540 Size=0.08 should add ~31px span, got {span_diff}" + ); + + // 3. Size scales with canvas width W, independent of height H. + let (s_wide, o_wide, p_wide) = base("HHHH", 0.0, 1.0, [960, 540]); + let (s_tall, o_tall, p_tall) = base("HHHH", 0.0, 1.0, [540, 960]); + let (wy0, wy1) = alpha_y_bounds(s_wide, o_wide, &p_wide); + let (ty0, ty1) = alpha_y_bounds(s_tall, o_tall, &p_tall); + let wide_h = (wy1 - wy0) as f32; + let tall_h = (ty1 - ty0) as f32; + let ratio = wide_h / tall_h; + assert!( + (ratio - (960.0 / 540.0)).abs() < 0.15, + "glyph pixel height should scale with W (expected ~1.78, got {ratio:.2}: {wide_h}/{tall_h})" + ); +} + +#[test] +fn exr_channel_cache_isolation_and_non_beauty_guard() { + use ::exr::prelude::*; + let dir = std::env::temp_dir().join(format!("fission_exr_chan_test_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + + let multi_exr = dir.join("multi_aov.exr"); + let w = 4usize; + let h = 4usize; + let n = w * h; + let mut channels = SmallVec::<[AnyChannel; 4]>::new(); + for (name, val) in [ + ("ViewLayer.Combined.R", 0.9_f32), + ("ViewLayer.Combined.G", 0.2), + ("ViewLayer.Combined.B", 0.1), + ("ViewLayer.Combined.A", 1.0), + ("ViewLayer.Specular.R", 0.1), + ("ViewLayer.Specular.G", 0.8), + ("ViewLayer.Specular.B", 0.7), + ("ViewLayer.Specular.A", 1.0), + ("ViewLayer.CryptoObject00.R", 0.5), + ] { + channels.push(AnyChannel::new(name, FlatSamples::F32(vec![val; n]))); + } + Image::from_layer(Layer::new( + (w, h), + LayerAttributes::named("main"), + Encoding::FAST_LOSSLESS, + AnyChannels::sort(channels), + )) + .write() + .to_file(&multi_exr) + .expect("write multi-layer EXR"); + + let clip = ClipSpec { + filename: multi_exr.to_string_lossy().into_owned(), + alternate_filename: None, + start_frame: 0, + length: Some(1), + trim_in: 0, + trim_out: 0, + global_start: 0, + global_end: 0, + extend_first: 0, + extend_last: 0, + loop_clip: false, + reverse: false, + }; + let mut cache = MediaCache::new(64); + let (_, _, beauty, beauty_disk) = cache.load_clip(&clip, 0, false, [None; 4]).unwrap(); + assert!(beauty_disk); + let (_, _, spec, spec_disk) = cache + .load_clip( + &clip, + 0, + false, + [ + Some("Specular.R"), + Some("Specular.G"), + Some("Specular.B"), + Some("Specular.A"), + ], + ) + .unwrap(); + assert!(spec_disk); + assert_eq!(cache.entry_count(), 2); + + let b_px = beauty.rgba_f32.as_ref().unwrap(); + let s_px = spec.rgba_f32.as_ref().unwrap(); + assert!((b_px[0] - 0.9).abs() < 1e-4 && (b_px[1] - 0.2).abs() < 1e-4); + assert!((s_px[0] - 0.1).abs() < 1e-4 && (s_px[1] - 0.8).abs() < 1e-4); + + // Warm hits keep both AOVs isolated. + let (_, _, beauty_warm, beauty_disk2) = cache.load_clip(&clip, 0, false, [None; 4]).unwrap(); + assert!(!beauty_disk2); + assert!((beauty_warm.rgba_f32.as_ref().unwrap()[0] - 0.9).abs() < 1e-4); + + // EXR containing ONLY CryptoObject00.R (no bare R or Combined.R) must NOT match beauty fallback. + let crypto_only_exr = dir.join("crypto_only.exr"); + let mut crypto_channels = SmallVec::<[AnyChannel; 4]>::new(); + for (name, val) in [ + ("CryptoObject00.R", 0.42_f32), + ("CryptoObject00.G", 0.0), + ("CryptoObject00.B", 0.0), + ("CryptoObject00.A", 1.0), + ] { + crypto_channels.push(AnyChannel::new(name, FlatSamples::F32(vec![val; n]))); + } + Image::from_layer(Layer::new( + (w, h), + LayerAttributes::named("crypto"), + Encoding::FAST_LOSSLESS, + AnyChannels::sort(crypto_channels), + )) + .write() + .to_file(&crypto_only_exr) + .expect("write crypto-only EXR"); + + let crypto_clip = ClipSpec { + filename: crypto_only_exr.to_string_lossy().into_owned(), + ..clip + }; + assert!(cache.load_clip(&crypto_clip, 0, false, [None; 4]).is_none()); + let (_, _, explicit, _) = cache + .load_clip( + &crypto_clip, + 0, + false, + [ + Some("CryptoObject00.R"), + Some("CryptoObject00.G"), + Some("CryptoObject00.B"), + Some("CryptoObject00.A"), + ], + ) + .expect("explicit CryptoObject00 channel selection should succeed"); + assert!((explicit.rgba_f32.as_ref().unwrap()[0] - 0.42).abs() < 1e-4); + + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn video_decoder_clear_lru_cap_post_multiply_and_loop() { + let dir = std::env::temp_dir().join(format!("fission_media_video_lru_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + + let base_mp4 = dir.join("clip_00.mp4"); + let ok = Command::new("ffmpeg") + .args([ + "-y", + "-v", + "error", + "-f", + "lavfi", + "-i", + "color=c=red:size=32x32:rate=24:duration=0.25", + "-c:v", + "libx264", + "-pix_fmt", + "yuv420p", + ]) + .arg(&base_mp4) + .status() + .is_ok_and(|s| s.success()); + assert!(ok, "ffmpeg failed to create tiny mp4"); + + let mut cache = MediaCache::new(64); + for i in 0..15 { + let p = if i == 0 { + base_mp4.clone() + } else { + let dst = dir.join(format!("clip_{i:02}.mp4")); + std::fs::copy(&base_mp4, &dst).unwrap(); + dst + }; + let clip = ClipSpec { + filename: p.to_string_lossy().into_owned(), + alternate_filename: None, + start_frame: 0, + length: Some(6), + trim_in: 0, + trim_out: 5, + global_start: 10, + global_end: 15, + extend_first: 5, + extend_last: 0, + loop_clip: true, + reverse: false, + }; + // Frame 9 with global_start = 10, extend_first = 5 -> inside [5, 15]: ExtendFirst holds frame 0. + let (_, local_idx, _, _) = cache + .load_clip(&clip, 9, false, [None; 4]) + .expect("loop_clip inside ExtendFirst should resolve"); + assert_eq!(local_idx, 0); + // Looping clips ignore GlobalEnd + ExtendLast: frame 20 -> rel 10 -> 10 % 6 = 4. + let (_, local_idx, _, _) = cache + .load_clip(&clip, 20, false, [None; 4]) + .expect("loop_clip past GlobalEnd should keep looping"); + assert_eq!(local_idx, 4); + let once = ClipSpec { loop_clip: false, ..clip }; + assert!(cache.load_clip(&once, 20, false, [None; 4]).is_none()); + } + assert!( + cache.video_decoder_count() <= MAX_VIDEO_DECODERS, + "expected LRU cap <= {MAX_VIDEO_DECODERS}, got {}", + cache.video_decoder_count() + ); + assert_eq!(cache.video_decoder_count(), MAX_VIDEO_DECODERS); + + // Straight-alpha ProRes 4444 MOV test for post_multiply separation. + let alpha_png = dir.join("straight_half.png"); + image::RgbaImage::from_pixel(32, 32, image::Rgba([200, 100, 50, 128])) + .save(&alpha_png) + .unwrap(); + let alpha_mov = dir.join("straight_half.mov"); + let mov_ok = Command::new("ffmpeg") + .args([ + "-y", + "-v", + "error", + "-loop", + "1", + "-i", + ]) + .arg(&alpha_png) + .args([ + "-t", + "0.1", + "-r", + "24", + "-c:v", + "prores_ks", + "-profile:v", + "4", + "-pix_fmt", + "yuva444p10le", + ]) + .arg(&alpha_mov) + .status() + .is_ok_and(|s| s.success()); + if mov_ok { + let mov_clip = ClipSpec { + filename: alpha_mov.to_string_lossy().into_owned(), + alternate_filename: None, + start_frame: 0, + length: Some(2), + trim_in: 0, + trim_out: 1, + global_start: 0, + global_end: 1, + extend_first: 0, + extend_last: 0, + loop_clip: false, + reverse: false, + }; + let (_, _, raw_vid, _) = cache.load_clip(&mov_clip, 0, false, [None; 4]).unwrap(); + let (_, _, pm_vid, _) = cache.load_clip(&mov_clip, 0, true, [None; 4]).unwrap(); + assert!( + pm_vid.rgba[0] < raw_vid.rgba[0], + "post_multiply should darken straight-alpha RGB ({} vs {})", + pm_vid.rgba[0], + raw_vid.rgba[0] + ); + } + + cache.clear(); + assert_eq!(cache.entry_count(), 0); + assert_eq!(cache.video_decoder_count(), 0); + + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn resolve_clip_path_missing_mid_sequence_returns_none() { + let dir = std::env::temp_dir().join(format!("fission_seq_missing_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + + let f0 = dir.join("shot_0000.png"); + let f2 = dir.join("shot_0002.png"); + image::RgbaImage::from_pixel(2, 2, image::Rgba([255, 0, 0, 255])).save(&f0).unwrap(); + image::RgbaImage::from_pixel(2, 2, image::Rgba([0, 255, 0, 255])).save(&f2).unwrap(); + + let clip = ClipSpec { + filename: f0.to_string_lossy().into_owned(), + alternate_filename: None, + start_frame: 0, + length: Some(3), + trim_in: 0, + trim_out: 2, + global_start: 0, + global_end: 2, + extend_first: 0, + extend_last: 0, + loop_clip: false, + reverse: false, + }; + assert_eq!(resolve_clip_path(&clip, 0), Some(f0)); + assert_eq!(resolve_clip_path(&clip, 1), None); + assert_eq!(resolve_clip_path(&clip, 2), Some(f2)); + + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn virtual_bytes_load_a_sequence_by_trailing_path() { + let png = |rgba: [u8; 4]| { + let mut out = std::io::Cursor::new(Vec::new()); + image::RgbaImage::from_pixel(2, 1, image::Rgba(rgba)) + .write_to(&mut out, image::ImageFormat::Png) + .unwrap(); + out.into_inner() + }; + MediaCache::insert_virtual_bytes("vf_proj\\vf_seq.0001.png", png([255, 0, 0, 255])); + MediaCache::insert_virtual_bytes("./vf_proj/vf_seq.0002.png", png([0, 255, 0, 255])); + let clip = ClipSpec { + filename: "/not/on/disk/vf_proj/vf_seq.0001.png".to_owned(), + alternate_filename: None, + start_frame: 1, + length: Some(2), + trim_in: 0, + trim_out: 1, + global_start: 0, + global_end: 1, + extend_first: 0, + extend_last: 0, + loop_clip: false, + reverse: false, + }; + let mut cache = MediaCache::new(64); + let (_, _, f0, from_disk) = cache.load_clip(&clip, 0, false, [None; 4]).unwrap(); + let (_, _, f1, _) = cache.load_clip(&clip, 1, false, [None; 4]).unwrap(); + assert!(from_disk); + assert_eq!((f0.size, &f0.rgba[..4]), ([2, 1], &[255, 0, 0, 255][..])); + assert_eq!(&f1.rgba[..4], &[0, 255, 0, 255]); + + MediaCache::insert_virtual_bytes("vf_proj/vf_seq.0002.png", png([0, 0, 255, 255])); + let (_, _, f1, _) = MediaCache::new(64).load_clip(&clip, 1, false, [None; 4]).unwrap(); + assert_eq!(&f1.rgba[..4], &[0, 0, 255, 255]); + assert!(path_exists(Path::new("elsewhere/vf_seq.0002.png"))); + assert!(!path_exists(Path::new("vf_proj/vf_seq.0003.png"))); +} + +fn file(path: &str, len: usize) -> VirtualFile { + VirtualFile { parts: path_parts(Path::new(path)), bytes: vec![0; len].into() } +} + +fn found<'a>(files: &'a [VirtualFile], path: &str) -> Option<&'a [String]> { + find_virtual(files, &path_parts(Path::new(path))).map(|f| f.parts.as_slice()) +} + +#[test] +fn virtual_paths_normalize_dots_and_separators() { + assert_eq!(path_parts(Path::new("/a/./b/../c\\d.png")), ["a", "c", "d.png"]); + assert_eq!(path_parts(Path::new("../../x.png")), ["x.png"]); +} + +#[test] +fn virtual_matching_prefers_exact_and_rejects_ambiguous_basenames() { + let files = [file("A/bg.png", 1), file("B/bg.png", 1), file("only.png", 1), file("Proj/Seq.exr", 1)]; + assert_eq!(found(&files, "/x/A/bg.png"), Some(&["A".to_owned(), "bg.png".to_owned()][..])); + assert_eq!(found(&files, "/x/../B/./bg.png").map(<[String]>::len), Some(2)); + assert_eq!(found(&files, "/C/bg.png"), None, "two files share the basename"); + assert_eq!(found(&files, "bg.png"), None); + assert!(found(&files, "/deep/elsewhere/only.png").is_some()); + assert!(found(&files, "/proj/seq.EXR").is_some(), "case-insensitive fallback"); + assert_eq!(found(&files, "/a/missing.png"), None); +} + +#[test] +fn virtual_files_stop_at_the_memory_cap() { + let mut files = Vec::new(); + let put = |files: &mut Vec, name: &str, len: usize| { + insert_capped(files, 10, path_parts(Path::new(name)), vec![0; len].into()) + }; + assert!(put(&mut files, "a", 6)); + assert!(!put(&mut files, "b", 5)); + assert!(put(&mut files, "b", 4)); + assert!(put(&mut files, "a", 6), "replacing a file frees its old bytes"); + assert!(!put(&mut files, "a", 7)); + assert_eq!(files.iter().map(|f| f.bytes.len()).sum::(), 10); +} + +#[test] +fn media_budget_scaling_matches_ram_tiers() { + const GIB: u64 = 1024 * 1024 * 1024; + assert_eq!(media_cache_budget_mb_for_total_bytes(8 * GIB), 512); + assert_eq!(media_cache_budget_mb_for_total_bytes(16 * GIB), 1024); + assert_eq!(media_cache_budget_mb_for_total_bytes(32 * GIB), 2048); + assert_eq!(media_cache_budget_mb_for_total_bytes(64 * GIB), 4096); + assert_eq!(media_cache_budget_mb_for_total_bytes(128 * GIB), 8192); + let default_cache = MediaCache::default(); + assert_eq!( + 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.shared.state.lock().unwrap().budget_bytes, + 32 * 1024 * 1024 + ); +} + +#[test] +fn parallel_post_multiply_matches_scalar_across_large_buffer() { + let len = 4 * 1024 * 1024 * 4 + 64; // > 4 MP threshold + let mut scalar = vec![0u8; len]; + for (i, px) in scalar.chunks_exact_mut(4).enumerate() { + px[0] = ((i * 7) % 256) as u8; + px[1] = ((i * 13) % 256) as u8; + px[2] = ((i * 29) % 256) as u8; + px[3] = (i % 256) as u8; + } + let mut parallel = scalar.clone(); + exr::apply_post_multiply_rgba8_parallel(&mut scalar, false); + exr::apply_post_multiply_rgba8_parallel(&mut parallel, true); + assert_eq!(scalar, parallel); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn preload_frame_loaders_and_prefetch_frames_populate_cache_in_parallel() { + let dir = std::env::temp_dir().join(format!("fission_preload_test_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + + let p_bg = dir.join("bg.png"); + let p_fg0 = dir.join("fg_0000.png"); + let p_fg1 = dir.join("fg_0001.png"); + let p_fg2 = dir.join("fg_0002.png"); + let p_pruned = dir.join("pruned.png"); + image::RgbaImage::from_pixel(4, 4, image::Rgba([20, 40, 60, 255])).save(&p_bg).unwrap(); + image::RgbaImage::from_pixel(4, 4, image::Rgba([200, 100, 50, 128])).save(&p_fg0).unwrap(); + image::RgbaImage::from_pixel(4, 4, image::Rgba([0, 200, 50, 255])).save(&p_fg1).unwrap(); + image::RgbaImage::from_pixel(4, 4, image::Rgba([50, 0, 200, 255])).save(&p_fg2).unwrap(); + image::RgbaImage::from_pixel(4, 4, image::Rgba([9, 9, 9, 255])).save(&p_pruned).unwrap(); + + let esc = |p: &Path| p.to_string_lossy().replace('\\', "\\\\"); + let comp_src = format!( + r#"Composition {{ +CurrentTime = 0, +RenderRange = {{ 0, 2 }}, +GlobalRange = {{ 0, 2 }}, +Tools = ordered() {{ + BgLoader = Loader {{ + Clips = {{ + Clip {{ + ID = "Clip1", + Filename = "{}", + FormatID = "PNGFormat", + Length = 1, + GlobalStart = 0, + GlobalEnd = 2, + }}, + }}, + }}, + FgLoader = Loader {{ + Clips = {{ + Clip {{ + ID = "Clip1", + Filename = "{}", + FormatID = "PNGFormat", + StartFrame = 0, + Length = 3, + GlobalStart = 0, + GlobalEnd = 2, + }}, + }}, + Inputs = {{ + ["Clip1.PNGFormat.PostMultiply"] = Input {{ Value = 1, }}, + }}, + }}, + PrunedLoader = Loader {{ + Clips = {{ + Clip {{ + ID = "Clip1", + Filename = "{}", + FormatID = "PNGFormat", + Length = 1, + GlobalStart = 0, + GlobalEnd = 2, + }}, + }}, + }}, + PrunedMerge = Merge {{ + Inputs = {{ + Blend = Input {{ Value = 0, }}, + Background = Input {{ SourceOp = "BgLoader", Source = "Output", }}, + Foreground = Input {{ SourceOp = "PrunedLoader", Source = "Output", }}, + }}, + }}, + MainMerge = Merge {{ + Inputs = {{ + Background = Input {{ SourceOp = "PrunedMerge", Source = "Output", }}, + Foreground = Input {{ SourceOp = "FgLoader", Source = "Output", }}, + }}, + }}, +}}, +}}"#, + esc(&p_bg), + esc(&p_fg0), + esc(&p_pruned), + ); + let comp = Comp::from_fusion_str(&comp_src).expect("parse preload comp"); + let target = comp.find_node("MainMerge").expect("MainMerge"); + let expr = model::ExprEngine::new(); + let mut cache = MediaCache::new(64); + + cache.preload_frame_loaders(&comp, target, 0.0, &expr); + // BgLoader + FgLoader(f0) are cached; PrunedLoader is skipped because PrunedMerge Blend == 0. + assert_eq!(cache.entry_count(), 2); + + let bg_clip = comp.node(comp.find_node("BgLoader").unwrap()).clips[0].clone(); + let fg_clip = comp.node(comp.find_node("FgLoader").unwrap()).clips[0].clone(); + let (_, _, bg_img, bg_from_disk) = cache.load_clip(&bg_clip, 0, false, [None; 4]).unwrap(); + let (_, _, fg0_img, fg0_from_disk) = cache.load_clip(&fg_clip, 0, true, [None; 4]).unwrap(); + assert!(!bg_from_disk); + assert!(!fg0_from_disk); + assert_eq!(&bg_img.rgba[..4], &[20, 40, 60, 255]); + assert_eq!(&fg0_img.rgba[..4], &[100, 50, 25, 128]); + + // Prefetch frames 1 and 2 ahead of playback. + cache.prefetch_frames(&comp, target, &[1.0, 2.0], &expr); + assert_eq!(cache.entry_count(), 4); + let (_, _, fg1_img, fg1_from_disk) = cache.load_clip(&fg_clip, 1, true, [None; 4]).unwrap(); + let (_, _, fg2_img, fg2_from_disk) = cache.load_clip(&fg_clip, 2, true, [None; 4]).unwrap(); + assert!(!fg1_from_disk); + assert!(!fg2_from_disk); + assert_eq!(&fg1_img.rgba[..4], &[0, 200, 50, 255]); + assert_eq!(&fg2_img.rgba[..4], &[50, 0, 200, 255]); + + let _ = std::fs::remove_dir_all(&dir); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn preload_frame_loaders_decodes_multiple_videos_in_parallel() { + let dir = std::env::temp_dir().join(format!("fission_preload_vid_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + + let mk_mp4 = |name: &str, color: &str| { + let p = dir.join(name); + let ok = Command::new("ffmpeg") + .args([ + "-y", + "-v", + "error", + "-f", + "lavfi", + "-i", + &format!("color=c={color}:size=32x32:rate=24:duration=0.2"), + "-c:v", + "libx264", + "-pix_fmt", + "yuv420p", + ]) + .arg(&p) + .status() + .is_ok_and(|s| s.success()); + (p, ok) + }; + let (v1, ok1) = mk_mp4("v1.mp4", "red"); + let (v2, ok2) = mk_mp4("v2.mp4", "blue"); + if !(ok1 && ok2) { + let _ = std::fs::remove_dir_all(&dir); + return; + } + + let esc = |p: &Path| p.to_string_lossy().replace('\\', "\\\\"); + let comp_src = format!( + r#"Composition {{ +CurrentTime = 0, +RenderRange = {{ 0, 3 }}, +GlobalRange = {{ 0, 3 }}, +Tools = ordered() {{ + V1 = Loader {{ + Clips = {{ + Clip {{ + ID = "Clip1", + Filename = "{}", + FormatID = "QuickTimeMovies", + Length = 4, + GlobalStart = 0, + GlobalEnd = 3, + }}, + }}, + }}, + V2 = Loader {{ + Clips = {{ + Clip {{ + ID = "Clip1", + Filename = "{}", + FormatID = "QuickTimeMovies", + Length = 4, + GlobalStart = 0, + GlobalEnd = 3, + }}, + }}, + }}, + M = Merge {{ + Inputs = {{ + Background = Input {{ SourceOp = "V1", Source = "Output", }}, + Foreground = Input {{ SourceOp = "V2", Source = "Output", }}, + }}, + }}, +}}, +}}"#, + esc(&v1), + esc(&v2), + ); + let comp = Comp::from_fusion_str(&comp_src).expect("parse video preload comp"); + let target = comp.find_node("M").expect("M"); + let expr = model::ExprEngine::new(); + let mut cache = MediaCache::new(64); + + cache.preload_frame_loaders(&comp, target, 0.0, &expr); + assert_eq!(cache.video_decoder_count(), 2); + assert_eq!(cache.entry_count(), 2); + + let c1 = comp.node(comp.find_node("V1").unwrap()).clips[0].clone(); + let c2 = comp.node(comp.find_node("V2").unwrap()).clips[0].clone(); + let (_, _, img1, disk1) = cache.load_clip(&c1, 0, false, [None; 4]).unwrap(); + let (_, _, img2, disk2) = cache.load_clip(&c2, 0, false, [None; 4]).unwrap(); + assert!(!disk1); + assert!(!disk2); + assert!(img1.rgba[0] > 200 && img1.rgba[2] < 40); + assert!(img2.rgba[2] > 200 && img2.rgba[0] < 40); + + cache.prefetch_frames(&comp, target, &[1.0, 2.0], &expr); + assert_eq!(cache.entry_count(), 6); + + 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); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn failed_opens_are_not_cached_and_evict_known_existing_paths() { + let dir = std::env::temp_dir().join(format!("fission_evict_test_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + + let bad_vid = dir.join("corrupt.mp4"); + std::fs::write(&bad_vid, b"not a valid mp4").unwrap(); + let mut cache = MediaCache::new(64); + assert!(cache.shared.path_exists_cached(&bad_vid)); + assert!(cache.shared.get_or_open_video_decoder(&bad_vid).is_none()); + assert_eq!(cache.video_decoder_count(), 0); + assert!(!cache.shared.state.lock().unwrap().known_existing_paths.contains(&bad_vid)); + + let img_path = dir.join("gone.png"); + image::RgbaImage::from_pixel(2, 2, image::Rgba([10, 20, 30, 255])) + .save(&img_path) + .unwrap(); + assert!(cache.shared.path_exists_cached(&img_path)); + std::fs::remove_file(&img_path).unwrap(); + let clip = ClipSpec { + filename: img_path.to_string_lossy().into_owned(), + alternate_filename: None, + start_frame: 0, + length: Some(1), + trim_in: 0, + trim_out: 0, + global_start: 0, + global_end: 0, + extend_first: 0, + extend_last: 0, + loop_clip: false, + reverse: false, + }; + assert!(cache.load_clip(&clip, 0, false, [None; 4]).is_none()); + assert!(!cache.shared.path_exists_cached(&img_path)); + + let _ = std::fs::remove_dir_all(&dir); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn prefetch_queue_prunes_stale_and_avoids_hol_blocking() { + let dir = std::env::temp_dir().join(format!("fission_hol_prefetch_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + + for i in 0..=10 { + let p = dir.join(format!("seq_{i:04}.png")); + image::RgbaImage::from_pixel(2, 2, image::Rgba([i as u8 * 20, 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, 10 }}, +GlobalRange = {{ 0, 10 }}, +Tools = ordered() {{ + LD = Loader {{ + Clips = {{ + Clip {{ + ID = "Clip1", + Filename = "{}", + FormatID = "PNGFormat", + StartFrame = 0, + Length = 11, + GlobalStart = 0, + GlobalEnd = 10, + }}, + }}, + }}, +}}, +}}"#, + esc(&p0) + ); + let comp = Comp::from_fusion_str(&comp_src).expect("parse hol 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(2); + // Enqueue far-future seq=10 first (outside lookahead=2), then seq=1 (within lookahead). + handle.enqueue_frame(&comp, target, 10, 10.0, &expr, false); + handle.enqueue_frame(&comp, target, 1, 1.0, &expr, false); + + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + while cache.entry_count() < 1 && std::time::Instant::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert_eq!(cache.entry_count(), 1); + let (_, _, img1, from_disk1) = cache.load_clip(&clip, 1, false, [None; 4]).unwrap(); + assert!(!from_disk1, "seq=1 must not be head-of-line blocked by seq=10"); + assert_eq!(img1.rgba[0], 20); + + // Advancing current_seq past 10 prunes seq=10 cleanly. + handle.set_current_seq(11); + { + let q = handle.queue.state.lock().unwrap(); + assert!(q.raster.is_empty()); + assert!(q.queued_raster_keys.is_empty()); + } + handle.cancel(); + let _ = std::fs::remove_dir_all(&dir); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn prefetch_handle_scales_and_decodes_nine_videos_concurrently() { + let dir = std::env::temp_dir().join(format!("fission_9vid_prefetch_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + + let v0 = dir.join("v0.mp4"); + let ok = Command::new("ffmpeg") + .args([ + "-y", + "-v", + "error", + "-f", + "lavfi", + "-i", + "color=c=green:size=16x16:rate=24:duration=0.15", + "-c:v", + "libx264", + "-pix_fmt", + "yuv420p", + ]) + .arg(&v0) + .status() + .is_ok_and(|s| s.success()); + if !ok { + let _ = std::fs::remove_dir_all(&dir); + return; + } + + let esc = |p: &Path| p.to_string_lossy().replace('\\', "\\\\"); + let mut tools = String::new(); + for i in 0..9 { + let vi = dir.join(format!("v{i}.mp4")); + if i > 0 { + std::fs::copy(&v0, &vi).unwrap(); + } + tools.push_str(&format!( + r#" V{i} = Loader {{ + Clips = {{ + Clip {{ + ID = "Clip1", + Filename = "{}", + FormatID = "QuickTimeMovies", + Length = 3, + GlobalStart = 0, + GlobalEnd = 2, + }}, + }}, + }}, +"#, + esc(&vi) + )); + } + let mut prev = "V0".to_owned(); + for i in 1..9 { + let mname = format!("M{i}"); + tools.push_str(&format!( + r#" {mname} = Merge {{ + Inputs = {{ + Background = Input {{ SourceOp = "{prev}", Source = "Output", }}, + Foreground = Input {{ SourceOp = "V{i}", Source = "Output", }}, + }}, + }}, +"# + )); + prev = mname; + } + let comp_src = format!( + "Composition {{\n CurrentTime = 0,\n RenderRange = {{ 0, 2 }},\n GlobalRange = {{ 0, 2 }},\n Tools = ordered() {{\n{tools} }},\n}}" + ); + let comp = Comp::from_fusion_str(&comp_src).expect("parse 9-video comp"); + let target = comp.find_node("M8").expect("M8"); + let expr = model::ExprEngine::new(); + let cache = MediaCache::new(64); + + let mut handle = cache.start_frame_prefetch(4); + let expected_workers = std::thread::available_parallelism() + .map(|n| n.get().clamp(2, 12)) + .unwrap_or(4); + assert_eq!(handle.workers.len(), expected_workers); + + handle.enqueue_frame(&comp, target, 0, 0.0, &expr, false); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + while cache.entry_count() < 9 && std::time::Instant::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert_eq!(cache.video_decoder_count(), 9); + assert_eq!(cache.entry_count(), 9); + handle.cancel(); + let _ = std::fs::remove_dir_all(&dir); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn warm_cache_over_75_percent_keeps_full_lookahead() { + let dir = std::env::temp_dir().join(format!("fission_warm_lookahead_{}", 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(512, 512, image::Rgba([i as u8 * 40, 20, 180, 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, 4 }}, +GlobalRange = {{ 0, 4 }}, +Tools = ordered() {{ + LD = Loader {{ + Clips = {{ + Clip {{ + ID = "Clip1", + Filename = "{}", + FormatID = "PNGFormat", + StartFrame = 0, + Length = 5, + GlobalStart = 0, + GlobalEnd = 4, + }}, + }}, + }}, +}}, +}}"#, + esc(&p0) + ); + let comp = Comp::from_fusion_str(&comp_src).expect("parse warm lookahead 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); + + // Warm the cache past 75% of its 64 MiB budget (13 x 4 MiB = 52 MiB = 81.25%). + let four_mb = Arc::new(vec![128u8; 1024 * 1024 * 4]); + { + let mut state = cache.shared.state.lock().unwrap(); + for i in 0..13 { + let key = ImageCacheKey { + path: dir.join(format!("warm_{i:04}.png")), + frame_idx: -1, + post_multiply: false, + exr_channels: [None, None, None, None], + }; + let img = DecodedImage { + size: [1024, 1024], + rgba: Arc::clone(&four_mb), + rgba_f16: None, + rgba_f32: None, + }; + cache.shared.insert_cached_locked(&mut state, key, img); + } + } + assert!( + cache.total_mb() > 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); +} + +#[test] +fn direct_png_decode_matches_image_crate_bit_for_bit_all_color_types() { + fn encode_png( + w: u32, + h: u32, + color: png::ColorType, + depth: png::BitDepth, + palette: Option<&[u8]>, + trns: Option<&[u8]>, + data: &[u8], + ) -> Vec { + let mut out = Vec::new(); + { + let mut enc = png::Encoder::new(&mut out, w, h); + enc.set_color(color); + enc.set_depth(depth); + if let Some(p) = palette { + enc.set_palette(p); + } + if let Some(t) = trns { + enc.set_trns(t); + } + let mut writer = enc.write_header().unwrap(); + writer.write_image_data(data).unwrap(); + } + out + } + + let (w, h) = (17u32, 11u32); + let n = (w * h) as usize; + let cases: Vec<(&str, Vec)> = vec![ + ( + "rgba8", + encode_png( + w, + h, + png::ColorType::Rgba, + png::BitDepth::Eight, + None, + None, + &(0..n * 4).map(|i| ((i * 37 + 13) % 256) as u8).collect::>(), + ), + ), + ( + "rgb8", + encode_png( + w, + h, + png::ColorType::Rgb, + png::BitDepth::Eight, + None, + None, + &(0..n * 3).map(|i| ((i * 53 + 7) % 256) as u8).collect::>(), + ), + ), + ( + "gray8", + encode_png( + w, + h, + png::ColorType::Grayscale, + png::BitDepth::Eight, + None, + None, + &(0..n).map(|i| ((i * 29 + 3) % 256) as u8).collect::>(), + ), + ), + ( + "gray_alpha8", + encode_png( + w, + h, + png::ColorType::GrayscaleAlpha, + png::BitDepth::Eight, + None, + None, + &(0..n * 2).map(|i| ((i * 41 + 19) % 256) as u8).collect::>(), + ), + ), + ( + "palette_trns", + encode_png( + w, + h, + png::ColorType::Indexed, + png::BitDepth::Eight, + Some(&[10, 20, 30, 200, 150, 50, 0, 255, 128, 255, 255, 255]), + Some(&[0, 128, 255]), + &(0..n).map(|i| (i % 4) as u8).collect::>(), + ), + ), + ( + "palette_opaque", + encode_png( + w, + h, + png::ColorType::Indexed, + png::BitDepth::Eight, + Some(&[10, 20, 30, 200, 150, 50, 0, 255, 128]), + None, + &(0..n).map(|i| (i % 3) as u8).collect::>(), + ), + ), + ( + "rgba16", + encode_png( + w, + h, + png::ColorType::Rgba, + png::BitDepth::Sixteen, + None, + None, + // Include boundary values like 0x01ff (511 -> rounds to 2, not 1). + &(0..n * 4) + .flat_map(|i| (((i * 1021 + 255) % 65536) as u16).to_be_bytes()) + .collect::>(), + ), + ), + ( + "rgb16", + encode_png( + w, + h, + png::ColorType::Rgb, + png::BitDepth::Sixteen, + None, + None, + &(0..n * 3) + .flat_map(|i| (((i * 997 + 511) % 65536) as u16).to_be_bytes()) + .collect::>(), + ), + ), + ( + "gray16", + encode_png( + w, + h, + png::ColorType::Grayscale, + png::BitDepth::Sixteen, + None, + None, + &(0..n) + .flat_map(|i| (((i * 773 + 128) % 65536) as u16).to_be_bytes()) + .collect::>(), + ), + ), + ( + "gray_alpha16", + encode_png( + w, + h, + png::ColorType::GrayscaleAlpha, + png::BitDepth::Sixteen, + None, + None, + &(0..n * 2) + .flat_map(|i| (((i * 613 + 384) % 65536) as u16).to_be_bytes()) + .collect::>(), + ), + ), + ]; + + for (label, bytes) in cases { + let dyn_img = image::load_from_memory(&bytes).expect("image crate decode"); + let expected_has_alpha = dyn_img.color().has_alpha(); + let expected_size = [dyn_img.width(), dyn_img.height()]; + let expected_rgba = dyn_img.into_rgba8().into_raw(); + + let (got_size, got_rgba, got_has_alpha) = match decode_png_bytes(&bytes) { + PngDecodeOutcome::Decoded(v) => v, + PngDecodeOutcome::Fallback | PngDecodeOutcome::Reject => { + panic!("direct decode failed for {label}") + } + }; + assert_eq!(got_size, expected_size, "size mismatch for {label}"); + assert_eq!(got_has_alpha, expected_has_alpha, "alpha flag mismatch for {label}"); + assert_eq!(got_rgba, expected_rgba, "pixel mismatch for {label}"); + } +} + +#[test] +fn reject_spoofed_oversized_png_ihdr_without_allocating() { + fn png_crc32(data: &[u8]) -> u32 { + let mut crc = 0xFFFF_FFFFu32; + for &b in data { + crc ^= b as u32; + for _ in 0..8 { + let mask = (crc & 1).wrapping_neg(); + crc = (crc >> 1) ^ (0xEDB8_8320 & mask); + } + } + !crc + } + + fn push_chunk(out: &mut Vec, chunk_type: &[u8; 4], payload: &[u8]) { + out.extend_from_slice(&(payload.len() as u32).to_be_bytes()); + let crc_start = out.len(); + out.extend_from_slice(chunk_type); + out.extend_from_slice(payload); + let crc = png_crc32(&out[crc_start..]); + out.extend_from_slice(&crc.to_be_bytes()); + } + + let mut crafted = vec![137, 80, 78, 71, 13, 10, 26, 10]; + let mut ihdr = [0u8; 13]; + ihdr[0..4].copy_from_slice(&16u32.to_be_bytes()); + ihdr[4..8].copy_from_slice(&1_000_000_000u32.to_be_bytes()); + ihdr[8] = 8; // bit depth + ihdr[9] = 6; // RGBA + push_chunk(&mut crafted, b"IHDR", &ihdr); + push_chunk(&mut crafted, b"IDAT", &[0x78, 0x9c, 0x03, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00]); + push_chunk(&mut crafted, b"IEND", &[]); + assert_eq!(crafted.len(), 67); + + assert!(matches!(decode_png_bytes(&crafted), PngDecodeOutcome::Reject)); + assert!(decode_raster_bytes(&crafted).is_none()); +}