From b72d3326c594153d96b2fa4add70819663b71002 Mon Sep 17 00:00:00 2001 From: clover caruso Date: Tue, 1 Dec 2026 13:12:27 -0800 Subject: [PATCH] perf(engine): parallel loader pre-decode, pipelined export, and RAM-scaled caches --- crates/engine/src/bin/render_check.rs | 171 +++- crates/engine/src/export.rs | 293 +++++-- crates/engine/src/media.rs | 1141 +++++++++++++++++++++++-- crates/engine/src/media/exr.rs | 54 +- crates/engine/src/ram_cache.rs | 105 ++- 5 files changed, 1621 insertions(+), 143 deletions(-) diff --git a/crates/engine/src/bin/render_check.rs b/crates/engine/src/bin/render_check.rs index b49f041c3907e338e9309a64b6cef86fa1b1bf2d..6574ed3bc9adc6813daa86865a5b284880be7db5 100644 --- a/crates/engine/src/bin/render_check.rs +++ b/crates/engine/src/bin/render_check.rs @@ -1,11 +1,15 @@ //! Headless verification, parity+perf suite runner, and batch PNG sequence renderer for `engine`. use engine::export::{VideoCodec, VideoExportOptions, export_node_video_ffmpeg}; +use engine::media::default_media_cache_budget_mb; use engine::{CacheMode, Engine, ExportOptions, export_saver_png_sequence}; use model::Comp; use std::collections::HashMap; use std::fs::File; +use std::io::BufWriter; use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, mpsc}; use std::time::Instant; fn compute_diff(pixels: &[u8], tex_size: [u32; 2], ref_path: &Path) -> Result<(f64, f64, f64), Box> { @@ -36,20 +40,34 @@ fn compute_diff(pixels: &[u8], tex_size: [u32; 2], ref_path: &Path) -> Result<(f Ok((mae, rmse, alpha_abs as f64 / px as f64)) } -fn write_png(path: &Path, size: [u32; 2], pixels: &[u8]) -> Result<(), Box> { - if let Some(parent) = path.parent() { - std::fs::create_dir_all(parent)?; - } - let mut enc = png::Encoder::new(File::create(path)?, size[0], size[1]); +fn write_png_raw(path: &Path, size: [u32; 2], pixels: &[u8]) -> Result<(), String> { + let file = File::create(path).map_err(|e| format!("failed to create '{}': {e}", path.display()))?; + let writer = BufWriter::with_capacity(256 * 1024, file); + let mut enc = png::Encoder::new(writer, size[0], size[1]); enc.set_color(png::ColorType::Rgba); enc.set_depth(png::BitDepth::Eight); - enc.write_header()?.write_image_data(pixels)?; + enc.set_compression(png::Compression::Fast); + enc.set_filter(png::Filter::Sub); + enc.write_header() + .map_err(|e| format!("failed to write PNG header '{}': {e}", path.display()))? + .write_image_data(pixels) + .map_err(|e| format!("failed to write PNG data '{}': {e}", path.display()))?; Ok(()) } +fn write_png(path: &Path, size: [u32; 2], pixels: &[u8]) -> Result<(), Box> { + if let Some(parent) = path.parent() { + if !parent.as_os_str().is_empty() { + std::fs::create_dir_all(parent)?; + } + } + write_png_raw(path, size, pixels).map_err(|e| e.into()) +} + fn run_suite(manifest_path: &Path, hiq: bool) -> Result<(), Box> { let text = std::fs::read_to_string(manifest_path)?; let mut engine = Engine::new_headless()?; + engine.set_media_budget_mb(default_media_cache_budget_mb()); engine.hiq = hiq; let mut comps: HashMap = HashMap::new(); let mut passed = 0usize; @@ -93,6 +111,13 @@ fn run_suite(manifest_path: &Path, hiq: bool) -> Result<(), Box4}/{total}] f{f:04} | eval={:.1}ms | avg={fps:.1} fps | vram={:.0}MB | unsupported={:?}", - idx + 1, - stats.eval_ms, - stats.cached_vram_mb, - stats.unsupported_nodes, - ); + + if total > 0 { + struct RenderEncodeJob { + path: PathBuf, + size: [u32; 2], + pixels: Vec, } + let workers = std::thread::available_parallelism() + .map(|n| n.get().clamp(2, 8)) + .unwrap_or(4); + let queue_cap = (workers * 2).clamp(16, 32); + let first_err: Arc>> = Arc::new(Mutex::new(None)); + let failed = Arc::new(AtomicBool::new(false)); + + std::thread::scope(|scope| -> Result<(), Box> { + let (tx, rx) = mpsc::sync_channel::(queue_cap); + let shared_rx = Arc::new(Mutex::new(rx)); + let mut handles = Vec::with_capacity(workers); + for _ in 0..workers { + let rx_c = Arc::clone(&shared_rx); + let err_c = Arc::clone(&first_err); + let fail_c = Arc::clone(&failed); + handles.push(scope.spawn(move || { + loop { + let job = { + let Ok(guard) = rx_c.lock() else { break }; + guard.recv() + }; + let Ok(job) = job else { break }; + if fail_c.load(Ordering::Acquire) { + continue; + } + if let Err(e) = write_png_raw(&job.path, job.size, &job.pixels) { + if let Ok(mut g) = err_c.lock() { + if g.is_none() { + *g = Some(e); + } + } + fail_c.store(true, Ordering::Release); + } + } + })); + } + + let mut loop_err: Option = None; + const PREFETCH_WINDOW: usize = 8; + for (idx, f) in (start..=end).enumerate() { + if failed.load(Ordering::Acquire) { + break; + } + if idx % PREFETCH_WINDOW == 0 { + let win_end = (idx + PREFETCH_WINDOW).min(total); + let window: Vec = + (idx..win_end).map(|k| (start + k as i64) as f64).collect(); + engine.media.prefetch_frames_with_proxy( + &comp, + target, + &window, + &engine.expr, + engine.use_proxy_clips, + ); + } + let (tex, stats) = engine.evaluate(&comp, target, f as f64); + let pixels = match engine.readback_rgba(&tex) { + Ok(px) => px, + Err(e) => { + loop_err = Some(format!("GPU readback failed at frame {f}: {e}")); + break; + } + }; + let out_file = out_dir.join(format!("{f:04}.png")); + if tx + .send(RenderEncodeJob { + path: out_file, + size: tex.size, + pixels, + }) + .is_err() + { + break; + } + if idx == 0 || (idx + 1) % 10 == 0 || idx + 1 == total { + let elapsed = t_all.elapsed().as_secs_f64().max(1e-6); + let fps = (idx + 1) as f64 / elapsed; + eprintln!( + " [{:>4}/{total}] f{f:04} | eval={:.1}ms | avg={fps:.1} fps | vram={:.0}MB | unsupported={:?}", + idx + 1, + stats.eval_ms, + stats.cached_vram_mb, + stats.unsupported_nodes, + ); + } + } + + drop(tx); + for h in handles { + let _ = h.join(); + } + + if let Some(e) = loop_err { + return Err(e.into()); + } + if let Ok(mut g) = first_err.lock() { + if let Some(e) = g.take() { + return Err(e.into()); + } + } + Ok(()) + })?; } eprintln!( "Finished {total} frames in {:.2}s ({:.1} fps)", @@ -218,6 +337,7 @@ fn run_saver_export( _ => None, }; let mut engine = Engine::new_headless()?; + engine.set_media_budget_mb(default_media_cache_budget_mb()); let opts = ExportOptions { saver_name: saver_name.map(str::to_owned), out_dir_override, @@ -287,6 +407,7 @@ fn run_video_export( _ => comp.render_range, }; let mut engine = Engine::new_headless()?; + engine.set_media_budget_mb(default_media_cache_budget_mb()); let opts = VideoExportOptions { target, out_path: out_path.clone(), @@ -589,6 +710,7 @@ fn main() -> Result<(), Box> { ); let mut engine = Engine::new_headless()?; + engine.set_media_budget_mb(default_media_cache_budget_mb()); engine.proxy_scale = proxy_scale; engine.use_proxy_clips = use_proxy_clips; if let Some(mb) = vram_budget_mb { @@ -599,6 +721,13 @@ fn main() -> Result<(), Box> { if profile { engine.cache.begin_frame_profile_with_comp(&comp); } + engine.media.preload_frame_loaders_with_proxy( + &comp, + target, + frame, + &engine.expr, + engine.use_proxy_clips, + ); let (tex, cold) = engine.evaluate(&comp, target, frame); let cold_profile = if profile { engine.cache.take_frame_profile().map(|mut fp| { diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 674e5856d22ad3192b435598c19af049ddf831d9..bad4f528f89556079a50898e5dd001b228c03fd9 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -196,11 +196,12 @@ fn write_png_fast(path: &Path, size: [u32; 2], pixels: &[u8]) -> Result<(), Stri } let file = File::create(path) .map_err(|e| format!("failed to create '{}': {e}", path.display()))?; - let writer = BufWriter::new(file); + let writer = BufWriter::with_capacity(256 * 1024, file); let mut enc = png::Encoder::new(writer, size[0], size[1]); enc.set_color(png::ColorType::Rgba); enc.set_depth(png::BitDepth::Eight); enc.set_compression(png::Compression::Fast); + enc.set_filter(png::Filter::Sub); let mut png_w = enc .write_header() .map_err(|e| format!("failed to write PNG header '{}': {e}", path.display()))?; @@ -272,7 +273,8 @@ pub fn export_saver_png_sequence_with_progress( let cancelled = Arc::new(AtomicBool::new(false)); let eval_result: Result<(), String> = std::thread::scope(|scope| { - let (tx, rx) = mpsc::sync_channel::(workers * 2); + let queue_cap = (workers * 2).clamp(16, 32); + let (tx, rx) = mpsc::sync_channel::(queue_cap); let shared_rx = Arc::new(Mutex::new(rx)); let mut handles = Vec::with_capacity(workers); @@ -304,6 +306,7 @@ pub fn export_saver_png_sequence_with_progress( } let mut loop_err: Option = None; + const PREFETCH_WINDOW: usize = 8; for (idx, frame) in (start..=end).enumerate() { if failed.load(Ordering::Acquire) { break; @@ -312,6 +315,17 @@ pub fn export_saver_png_sequence_with_progress( cancelled.store(true, Ordering::Release); break; } + if idx % PREFETCH_WINDOW == 0 { + let win_end = (idx + PREFETCH_WINDOW).min(total); + let window: Vec = (idx..win_end).map(|k| (start + k as i64) as f64).collect(); + engine.media.prefetch_frames_with_proxy( + comp, + target, + &window, + &engine.expr, + engine.use_proxy_clips, + ); + } let out_path = match resolve_output_path(&saver, frame, opts.out_dir_override.as_deref()) { Ok(p) => p, Err(e) => { @@ -639,6 +653,13 @@ pub fn export_node_video_ffmpeg_with_progress( let node_name = comp.node(opts.target).name.clone(); // Evaluate the first frame before spawning ffmpeg so dimensions match actual GPU output. + engine.media.preload_frame_loaders_with_proxy( + comp, + opts.target, + start as f64, + &engine.expr, + engine.use_proxy_clips, + ); let (first_tex, first_stats) = engine.evaluate(comp, opts.target, start as f64); if first_tex.size[0] == 0 || first_tex.size[1] == 0 { return Err(format!( @@ -815,77 +836,135 @@ pub fn export_node_video_ffmpeg_with_progress( let mut pipe_err: Option = None; let mut cancelled = false; - { - let mut stdin = child - .stdin - .take() - .ok_or_else(|| "failed to open ffmpeg stdin".to_owned())?; + let writer_err: Arc>> = Arc::new(Mutex::new(None)); + let writer_failed = Arc::new(AtomicBool::new(false)); + let stdin = child + .stdin + .take() + .ok_or_else(|| "failed to open ffmpeg stdin".to_owned())?; - if let Err(e) = stdin.write_all(&first_pixels) { - pipe_err = Some(format!("failed writing frame {start} to ffmpeg: {e}")); - } else { - let first_prog = make_progress( - start, - 0, + let frame_bytes_len = (width as usize) + .saturating_mul(height as usize) + .saturating_mul(4) + .max(1); + let queue_cap = (128 * 1024 * 1024 / frame_bytes_len).clamp(4, 16); + let (tx, rx) = mpsc::sync_channel::<(i64, [u32; 2], Vec)>(queue_cap); + let writer_err_c = Arc::clone(&writer_err); + let writer_failed_c = Arc::clone(&writer_failed); + let dst_size = [width, height]; + let writer_thread = std::thread::spawn(move || { + let mut stdin = BufWriter::with_capacity(4 * 1024 * 1024, stdin); + while let Ok((frame, src_size, pixels)) = rx.recv() { + let frame_bytes = match fit_frame_rgba(pixels, src_size, dst_size, frame) { + Ok(bytes) => bytes, + Err(e) => { + if let Ok(mut g) = writer_err_c.lock() { + if g.is_none() { + *g = Some(e); + } + } + writer_failed_c.store(true, Ordering::Release); + break; + } + }; + if let Err(e) = stdin.write_all(&frame_bytes) { + if let Ok(mut g) = writer_err_c.lock() { + if g.is_none() { + *g = Some(format!("failed writing frame {frame} to ffmpeg: {e}")); + } + } + writer_failed_c.store(true, Ordering::Release); + break; + } + } + let _ = stdin.flush(); + }); + + if tx.send((start, [width, height], first_pixels)).is_err() { + pipe_err = writer_err + .lock() + .ok() + .and_then(|mut g| g.take()) + .or_else(|| Some(format!("failed writing frame {start} to ffmpeg"))); + } else { + let first_prog = make_progress( + start, + 0, + total, + first_stats.eval_ms, + opts.out_path.clone(), + node_name.clone(), + t0, + ); + if let Some(ctrl) = control { + ctrl.update_progress(&first_prog); + } + on_progress(first_prog); + + const PREFETCH_WINDOW: usize = 8; + let remaining = total.saturating_sub(1); + for (idx, frame) in ((start + 1)..=end).enumerate() { + if writer_failed.load(Ordering::Acquire) { + break; + } + if control.is_some_and(ExportControl::is_cancelled) { + cancelled = true; + break; + } + if idx % PREFETCH_WINDOW == 0 { + let win_end = (idx + PREFETCH_WINDOW).min(remaining); + let window: Vec = (idx..win_end).map(|k| (start + 1 + k as i64) as f64).collect(); + engine.media.prefetch_frames_with_proxy( + comp, + opts.target, + &window, + &engine.expr, + engine.use_proxy_clips, + ); + } + let (tex, stats) = engine.evaluate(comp, opts.target, frame as f64); + let pixels = match engine.readback_rgba(&tex) { + Ok(px) => px, + Err(e) => { + pipe_err = Some(format!("GPU readback failed at frame {frame}: {e}")); + break; + } + }; + if control.is_some_and(ExportControl::is_cancelled) { + cancelled = true; + break; + } + if tx.send((frame, tex.size, pixels)).is_err() { + break; + } + let prog = make_progress( + frame, + idx + 1, total, - first_stats.eval_ms, + stats.eval_ms, opts.out_path.clone(), node_name.clone(), t0, ); if let Some(ctrl) = control { - ctrl.update_progress(&first_prog); - } - on_progress(first_prog); - - for (idx, frame) in ((start + 1)..=end).enumerate() { - if control.is_some_and(ExportControl::is_cancelled) { - cancelled = true; - break; - } - let (tex, stats) = engine.evaluate(comp, opts.target, frame as f64); - let pixels = match engine.readback_rgba(&tex) { - Ok(px) => px, - Err(e) => { - pipe_err = Some(format!("GPU readback failed at frame {frame}: {e}")); - break; - } - }; - if control.is_some_and(ExportControl::is_cancelled) { - cancelled = true; - break; - } - let frame_bytes = match fit_frame_rgba(pixels, tex.size, [width, height], frame) { - Ok(bytes) => bytes, - Err(e) => { - pipe_err = Some(e); - break; - } - }; - - if let Err(e) = stdin.write_all(&frame_bytes) { - pipe_err = Some(format!("failed writing frame {frame} to ffmpeg: {e}")); - break; - } - let prog = make_progress( - frame, - idx + 1, - total, - stats.eval_ms, - opts.out_path.clone(), - node_name.clone(), - t0, - ); - if let Some(ctrl) = control { - ctrl.update_progress(&prog); - } - on_progress(prog); + ctrl.update_progress(&prog); } + on_progress(prog); } - let _ = stdin.flush(); } + drop(tx); - if cancelled || pipe_err.is_some() { + if cancelled || pipe_err.is_some() || writer_failed.load(Ordering::Acquire) { + // Kill ffmpeg before joining writer_thread so a blocked pipe write unblocks immediately. + let _ = child.kill(); + } + let _ = writer_thread.join(); + if pipe_err.is_none() && !cancelled { + if let Ok(mut g) = writer_err.lock() { + pipe_err = g.take(); + } + } + if pipe_err.is_some() && !cancelled { let _ = child.kill(); } let status = child @@ -1598,4 +1677,94 @@ mod tests { let _ = std::fs::remove_dir_all(&tmp_dir); } + + #[test] + fn pipelined_png_export_is_pixel_exact_and_propagates_write_errors() { + let tmp_dir = std::env::temp_dir().join(format!( + "fission-png-pipeline-exact-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&tmp_dir); + std::fs::create_dir_all(&tmp_dir).expect("create temp dir"); + + let saver_path = tmp_dir.join("out").join("frame_0000.png"); + let saver_path_escaped = saver_path.to_string_lossy().replace('\\', "\\\\"); + let comp_src = format!( + r#"Composition {{ + CurrentTime = 0, + RenderRange = {{ 0, 5 }}, + GlobalRange = {{ 0, 5 }}, + Tools = ordered() {{ + BG = Background {{ + Inputs = {{ + Width = Input {{ Value = 96, }}, + Height = Input {{ Value = 48, }}, + TopLeftRed = Input {{ SourceOp = "BGRed", Source = "Value", }}, + TopLeftGreen = Input {{ Value = 0.5, }}, + TopLeftBlue = Input {{ Value = 0.25, }}, + TopLeftAlpha = Input {{ Value = 1.0, }}, + }}, + }}, + BGRed = BezierSpline {{ + KeyFrames = {{ + [0] = {{ 0.1, Flags = {{ Linear = true }} }}, + [5] = {{ 0.9, Flags = {{ Linear = true }} }}, + }}, + }}, + Saver1 = Saver {{ + Inputs = {{ + Clip = Input {{ + Value = Clip {{ + Filename = "{saver_path_escaped}", + FormatID = "PNGFormat", + Saving = true, + }}, + }}, + Input = Input {{ SourceOp = "BG", Source = "Output", }}, + }}, + }}, + }}, + Prefs = {{ Comp = {{ FrameFormat = {{ Width = 96, Height = 48, Rate = 24, DepthFull = 1 }} }} }}, +}}"# + ); + + let comp = Comp::from_fusion_str(&comp_src).expect("parse comp"); + let target = comp.find_node("BG").unwrap(); + let mut engine = Engine::new_headless().expect("headless wgpu engine"); + + let summary = export_saver_png_sequence(&mut engine, &comp, &ExportOptions::default(), |_| {}) + .expect("export png sequence"); + assert_eq!(summary.frames_written, 6); + + // Verify fast-compressed PNGs decode byte-identically to direct GPU readback. + for f in 0..=5 { + let (tex, _) = engine.evaluate(&comp, target, f as f64); + let expected = engine.readback_rgba(&tex).expect("readback"); + let png_path = tmp_dir.join("out").join(format!("frame_{f:04}.png")); + let decoded = image::open(&png_path).expect("decode png").to_rgba8(); + assert_eq!(decoded.dimensions(), (tex.size[0], tex.size[1])); + assert_eq!( + decoded.into_raw(), + expected, + "fast PNG encode must be 100% lossless at frame {f}" + ); + } + + // Verify worker write error propagates cleanly: point out_dir_override inside a regular file. + let blocking_file = tmp_dir.join("not_a_dir"); + std::fs::write(&blocking_file, b"file").expect("write blocking file"); + let err = export_saver_png_sequence( + &mut engine, + &comp, + &ExportOptions { + out_dir_override: Some(blocking_file), + ..ExportOptions::default() + }, + |_| {}, + ) + .expect_err("writing into a regular file path must return Err"); + assert!(!err.is_empty()); + + let _ = std::fs::remove_dir_all(&tmp_dir); + } } diff --git a/crates/engine/src/media.rs b/crates/engine/src/media.rs index 4fd76e90ac8e50c0d43258d0da8d16b27ef72ba9..6484b73f776cc58fceac2b601b862404cb5aefd1 100644 --- a/crates/engine/src/media.rs +++ b/crates/engine/src/media.rs @@ -10,15 +10,26 @@ pub use raster::{TextPlusParams, rasterize_polyline_mask, rasterize_text_plus}; #[cfg(target_os = "macos")] pub use video::AvFoundationDecoder; pub use video::{FfmpegDecoder, VideoDecoder, VideoInfo, open_video_decoder}; -use exr::{apply_post_multiply_rgba8, decode_exr_rgba, is_exr_path, normalize_channel_opt}; +use exr::{ + apply_post_multiply_rgba8, apply_post_multiply_rgba8_parallel, decode_exr_rgba, is_exr_path, + normalize_channel_opt, +}; use video::is_video_path; use crate::text_engine; -use model::{ClipSpec, ClsEntry, PolyPoint}; +#[cfg(not(target_arch = "wasm32"))] +use model::{Node, default_main_input_port}; +use model::{ClipSpec, ClsEntry, Comp, NodeId, PolyPoint}; +#[cfg(not(target_arch = "wasm32"))] +use std::collections::HashSet; use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::process::Command; +#[cfg(not(target_arch = "wasm32"))] +use std::sync::Mutex; use std::sync::{Arc, RwLock}; +#[cfg(not(target_arch = "wasm32"))] +use std::sync::atomic::{AtomicUsize, Ordering}; #[derive(Clone)] pub struct DecodedImage { @@ -119,10 +130,56 @@ fn path_exists(path: &Path) -> bool { } fn open_image(path: &Path) -> Option { - match virtual_bytes(path) { - Some(bytes) => image::load_from_memory(&bytes).ok(), - None => image::open(path).ok(), + if let Some(bytes) = virtual_bytes(path) { + return image::load_from_memory(&bytes).ok(); } + // Read file contents in one contiguous pass to avoid tiny buffered syscalls over SMB/network shares. + if let Ok(bytes) = std::fs::read(path) { + if let Ok(img) = image::load_from_memory(&bytes) { + return Some(img); + } + } + image::open(path).ok() +} + +fn decode_raster_image( + path: &Path, + post_multiply: bool, + allow_parallel_premult: bool, +) -> Option { + let dyn_img = open_image(path)?; + let has_alpha = dyn_img.color().has_alpha(); + let size = [dyn_img.width(), dyn_img.height()]; + let mut raw = dyn_img.into_rgba8().into_raw(); + 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 { + 8 * 1024 + } else if gib >= 64 { + 4 * 1024 + } else if gib >= 32 { + 2 * 1024 + } else if gib >= 16 { + 1024 + } else { + 512 + } +} + +/// Returns the default `MediaCache` budget in MiB scaled to host physical RAM. +pub fn default_media_cache_budget_mb() -> u64 { + media_cache_budget_mb_for_total_bytes(crate::ram_cache::system_memory_bytes()) } #[derive(Clone, Debug, PartialEq, Eq, Hash)] @@ -147,18 +204,28 @@ pub struct MediaCache { tick: u64, } +impl Default for MediaCache { + fn default() -> Self { + Self::new(default_media_cache_budget_mb()) + } +} + impl MediaCache { pub fn new(budget_mb: u64) -> Self { Self { images: HashMap::new(), video_decoders: HashMap::new(), total_bytes: 0, - budget_bytes: budget_mb * 1024 * 1024, + budget_bytes: budget_mb.saturating_mul(1024 * 1024), lru: HashMap::new(), tick: 0, } } + pub fn with_budget_mb(budget_mb: u64) -> Self { + Self::new(budget_mb) + } + /// Registers `bytes` as the file at `path` for every `MediaCache` in the process. `false` /// when the files held would pass [`MAX_VIRTUAL_BYTES`], leaving the registry unchanged. pub fn insert_virtual_bytes(path: impl AsRef, bytes: impl Into>) -> bool { @@ -224,12 +291,13 @@ impl MediaCache { } } - fn get_or_open_video_decoder(&mut self, path: &Path) -> Option { + fn put_video_decoder(&mut self, path: PathBuf, decoder: Option>) { self.tick += 1; let now_tick = self.tick; - if let Some(entry) = self.video_decoders.get_mut(path) { + if let Some(entry) = self.video_decoders.get_mut(&path) { + entry.decoder = decoder; entry.last_used = now_tick; - return entry.decoder.as_ref().map(|d| d.info()); + return; } while self.video_decoders.len() >= MAX_VIDEO_DECODERS { let Some(oldest_path) = self @@ -242,15 +310,25 @@ impl MediaCache { }; self.video_decoders.remove(&oldest_path); } - let decoder = open_video_decoder(path); - let info = decoder.as_ref().map(|d| d.info()); self.video_decoders.insert( - path.to_path_buf(), + path, VideoDecoderEntry { decoder, last_used: now_tick, }, ); + } + + fn get_or_open_video_decoder(&mut self, path: &Path) -> Option { + self.tick += 1; + let now_tick = self.tick; + if let Some(entry) = self.video_decoders.get_mut(path) { + entry.last_used = now_tick; + return entry.decoder.as_ref().map(|d| d.info()); + } + let decoder = open_video_decoder(path); + let info = decoder.as_ref().map(|d| d.info()); + self.put_video_decoder(path.to_path_buf(), decoder); info } @@ -265,36 +343,12 @@ impl MediaCache { ) -> Option<(PathBuf, i64, DecodedImage, bool)> { let base = Path::new(&clip.filename); if is_video_path(base) { - if !base.exists() { + if !base.exists() || !video_frame_in_range(clip, frame) { return None; } - // Enforce active timeline range [GlobalStart - ExtendFirst, GlobalEnd + ExtendLast]. - if clip.global_end >= clip.global_start - && (clip.length.unwrap_or(0) > 1 || clip.global_end > clip.global_start) - { - let min_f = clip.global_start - clip.extend_first.max(0); - let max_f = clip.global_end + clip.extend_last.max(0); - if frame < min_f || (!clip.loop_clip && frame > max_f) { - return None; - } - } let base_buf = base.to_path_buf(); let info = self.get_or_open_video_decoder(base)?; - - let len = clip.length.unwrap_or(info.nb_frames.max(1)).max(1); - let trim_in = clip.trim_in.clamp(0, len - 1); - let trim_out = if clip.trim_out > 0 { - clip.trim_out.clamp(trim_in, len - 1) - } else { - len - 1 - }; - let span = (trim_out - trim_in + 1).max(1); - let rel = if clip.loop_clip { - (frame - clip.global_start).max(0).rem_euclid(span) - } else { - (frame - clip.global_start).clamp(0, span - 1) - }; - let idx = if clip.reverse { trim_out - rel } else { trim_in + rel }; + let idx = compute_video_frame_idx(clip, frame, info.nb_frames); let cache_key = ImageCacheKey { path: base_buf.clone(), frame_idx: idx, @@ -359,23 +413,759 @@ impl MediaCache { false, )? } else { - let dyn_img = open_image(&resolved)?; - let rgba_img = dyn_img.to_rgba8(); - let size = [rgba_img.width(), rgba_img.height()]; - let mut raw = rgba_img.into_raw(); - if post_multiply { - apply_post_multiply_rgba8(&mut raw); - } - DecodedImage { - size, - rgba: Arc::new(raw), - rgba_f16: None, - rgba_f32: None, - } + decode_raster_image(&resolved, post_multiply, true)? }; self.insert_cached(cache_key, decoded.clone()); 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(); + self.collect_missing_loader_jobs( + 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 { + self.collect_missing_loader_jobs( + 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"); + if let Some(decoded) = decode_job(&job, true) { + self.insert_cached(job.cache_key, decoded); + } + return; + } + self.decode_jobs_parallel(jobs); + } + } + + #[cfg(not(target_arch = "wasm32"))] + fn decode_jobs_parallel(&mut self, mut jobs: MissingJobs) { + let mut video_tasks: Vec = jobs + .videos + .drain() + .map(|(path, requests)| { + let decoder = self + .video_decoders + .get_mut(&path) + .and_then(|entry| entry.decoder.take()); + VideoDecodeTask { + path, + decoder, + requests, + } + }) + .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(1, 8)) + .unwrap_or(4) + .min(total_units); + + let next_idx = AtomicUsize::new(0); + let video_slots: Vec< + Mutex>, Vec<(ImageCacheKey, DecodedImage)>)>>, + > = (0..video_count).map(|_| Mutex::new(None)).collect(); + let raster_slots: Vec>> = + (0..raster_jobs.len()).map(|_| Mutex::new(None)).collect(); + + let video_inputs: Vec>> = + video_tasks.drain(..).map(|t| Mutex::new(Some(t))).collect(); + + 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(mut task) = task { + let mut dec_opt = + task.decoder.take().or_else(|| open_video_decoder(&task.path)); + let mut decoded_frames = Vec::new(); + if let Some(ref mut dec) = dec_opt { + let info = dec.info(); + 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; + } + if let Some(mut raw) = dec.decode_frame(frame_idx) { + if req.post_multiply { + apply_post_multiply_rgba8_parallel(&mut raw, false); + } + let key = ImageCacheKey { + path: task.path.clone(), + frame_idx, + post_multiply: req.post_multiply, + exr_channels: [None, None, None, None], + }; + decoded_frames.push(( + key, + DecodedImage { + size: [info.width, info.height], + rgba: Arc::new(raw), + rgba_f16: None, + rgba_f32: None, + }, + )); + } + } + } + if let Ok(mut slot) = video_slots[idx].lock() { + *slot = Some((task.path, dec_opt, decoded_frames)); + } + } + } else { + let r_idx = idx - video_count; + let decoded = decode_job(&raster_jobs[r_idx], false); + if let Ok(mut slot) = raster_slots[r_idx].lock() { + *slot = decoded; + } + } + }); + } + }); + + for slot in video_slots { + if let Ok(mut guard) = slot.into_inner() { + if let Some((path, dec_opt, frames)) = guard.take() { + self.put_video_decoder(path, dec_opt); + for (key, img) in frames { + self.insert_cached(key, img); + } + } + } + } + for (job, slot) in raster_jobs.into_iter().zip(raster_slots) { + if let Ok(mut guard) = slot.into_inner() { + if let Some(decoded) = guard.take() { + self.insert_cached(job.cache_key, decoded); + } + } + } + } + + #[cfg(not(target_arch = "wasm32"))] + #[allow(clippy::too_many_arguments)] + fn collect_missing_loader_jobs( + &self, + comp: &Comp, + node_id: NodeId, + time: f64, + expr: &model::ExprEngine, + use_proxy_clips: bool, + visited: &mut HashSet<(NodeId, i64)>, + jobs: &mut MissingJobs, + ) { + if node_id.0 >= comp.nodes.len() { + return; + } + let time_key = (if time == 0.0 { 0.0 } else { time }).to_bits() as i64; + if !visited.insert((node_id, time_key)) { + return; + } + let node = comp.node(node_id); + + if node.bypassed + || matches!( + node.kind.as_str(), + "Saver" + | "PipeRouter" + | "Fuse.Wireless" + | "Tracker" + | "Dimension.OpticalFlow" + | "OpticalFlow" + | "Dimension.CopyAux" + ) + { + let port = default_main_input_port(&node.kind); + if let Some(src_id) = node.connected_node(port).and_then(|s| comp.find_node(s)) { + self.collect_missing_loader_jobs( + 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 { + self.collect_missing_loader_jobs( + 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(); + self.collect_missing_loader_jobs( + 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 + }; + self.collect_missing_loader_jobs( + comp, + eval_src_id, + f0, + expr, + use_proxy_clips, + visited, + jobs, + ); + self.collect_missing_loader_jobs( + comp, + eval_src_id, + f0 + 1.0, + expr, + use_proxy_clips, + visited, + jobs, + ); + } else { + self.collect_missing_loader_jobs( + comp, + src_id, + remapped, + expr, + use_proxy_clips, + visited, + jobs, + ); + } + return; + } + + if node.kind == "Switch" || node.kind == "Fuse.Switch" { + let is_native_zero_indexed = node.kind == "Switch" + && (node.inputs.contains_key("Source") + || node.inputs.contains_key("Input0") + || !node.inputs.contains_key("Which")); + let src_name = if is_native_zero_indexed { + let source = comp + .eval_number(node, "Source", time, 0.0, expr) + .round() + .max(0.0) as usize; + let port = format!("Input{source}"); + node.connected_node(&port) + .or_else(|| node.connected_node("Input0")) + } else { + let which = comp + .eval_number(node, "Which", time, 1.0, expr) + .round() + .max(1.0) as usize; + let port = format!("Input{which}"); + node.connected_node(&port) + .or_else(|| node.connected_node("Input1")) + }; + if let Some(src_id) = src_name.and_then(|s| comp.find_node(s)) { + self.collect_missing_loader_jobs( + comp, + src_id, + time, + expr, + use_proxy_clips, + visited, + jobs, + ); + } + return; + } + + if node.kind == "Fuse.SwitchElse" { + let index = |name: &str, default: f64| { + comp.eval_number(node, name, time, default, expr) + .round() + .max(1.0) as usize + }; + let picked = [index("Switch", 1.0), index("Else", 2.0)].into_iter().find_map(|i| { + node.connected_node(&format!("Input{i}")) + .and_then(|s| comp.find_node(s)) + }); + if let Some(src_id) = picked { + self.collect_missing_loader_jobs( + 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)) { + self.collect_missing_loader_jobs( + 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)) { + self.collect_missing_loader_jobs( + comp, + fg_id, + time, + expr, + use_proxy_clips, + visited, + jobs, + ); + } + } + if let Some(mid) = mask_id { + self.collect_missing_loader_jobs( + comp, + mid, + 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 resolve_clip_path(&proxy_clip, frame_i).is_some_and(|p| path_exists(&p)) { + effective_clip = proxy_clip; + } + } + } + let out_of_range = effective_clip.global_end >= effective_clip.global_start + && (frame_i < effective_clip.global_start - effective_clip.extend_first.max(0) + || (!effective_clip.loop_clip + && frame_i > effective_clip.global_end + effective_clip.extend_last.max(0))); + if !out_of_range { + let base = Path::new(&effective_clip.filename); + if is_video_path(base) { + if base.exists() && video_frame_in_range(&effective_clip, frame_i) { + let need_decode = match self.video_decoders.get(base) { + Some(entry) => entry.decoder.as_ref().is_some_and(|dec| { + let idx = compute_video_frame_idx( + &effective_clip, + frame_i, + dec.info().nb_frames, + ); + let cache_key = ImageCacheKey { + path: base.to_path_buf(), + frame_idx: idx, + post_multiply: post_mult, + exr_channels: [None, None, None, None], + }; + !self.images.contains_key(&cache_key) + }), + None => true, + }; + if need_decode { + jobs.videos + .entry(base.to_path_buf()) + .or_default() + .push(VideoFrameRequest { + clip: effective_clip, + frame_i, + post_multiply: post_mult, + }); + } + } + } else if let Some(resolved) = resolve_clip_path(&effective_clip, frame_i) { + let is_exr = is_exr_path(&resolved); + let key_channels = if is_exr { + [ + normalize_channel_opt(exr_channels[0]), + normalize_channel_opt(exr_channels[1]), + normalize_channel_opt(exr_channels[2]), + normalize_channel_opt(exr_channels[3]), + ] + } else { + [None, None, None, None] + }; + let cache_key = ImageCacheKey { + path: resolved, + frame_idx: -1, + post_multiply: post_mult && !is_exr, + exr_channels: key_channels, + }; + if !self.images.contains_key(&cache_key) + && jobs.seen_raster.insert(cache_key.clone()) + { + jobs.raster.push(PreloadJob { cache_key, is_exr }); + } + } + } + } + if let Some(mid) = resolve_effect_mask_id_for_node(comp, node) { + self.collect_missing_loader_jobs( + comp, + mid, + time, + expr, + use_proxy_clips, + visited, + jobs, + ); + } + return; + } + + // General node: traverse all wired upstream node inputs and inherited EffectMask. + let mut child_ids = Vec::new(); + for binding in node.inputs.values() { + if let Some(src) = binding.source_op.as_deref() { + if let Some(cid) = comp.find_node(src) { + if !child_ids.contains(&cid) { + child_ids.push(cid); + } + } + } + } + if let Some(mid) = resolve_effect_mask_id_for_node(comp, node) { + if !child_ids.contains(&mid) { + child_ids.push(mid); + } + } + for cid in child_ids { + self.collect_missing_loader_jobs( + comp, + cid, + time, + expr, + use_proxy_clips, + visited, + jobs, + ); + } + } +} + +fn video_frame_in_range(clip: &ClipSpec, frame: i64) -> bool { + if clip.global_end >= clip.global_start + && (clip.length.unwrap_or(0) > 1 || clip.global_end > clip.global_start) + { + let min_f = clip.global_start - clip.extend_first.max(0); + let max_f = clip.global_end + clip.extend_last.max(0); + if frame < min_f || (!clip.loop_clip && frame > max_f) { + return false; + } + } + true +} + +fn compute_video_frame_idx(clip: &ClipSpec, frame: i64, nb_frames: i64) -> i64 { + let len = clip.length.unwrap_or(nb_frames.max(1)).max(1); + let trim_in = clip.trim_in.clamp(0, len - 1); + let trim_out = if clip.trim_out > 0 { + clip.trim_out.clamp(trim_in, len - 1) + } else { + len - 1 + }; + let span = (trim_out - trim_in + 1).max(1); + let rel = if clip.loop_clip { + (frame - clip.global_start).max(0).rem_euclid(span) + } else { + (frame - clip.global_start).clamp(0, span - 1) + }; + if clip.reverse { trim_out - rel } else { trim_in + rel } +} + +#[cfg(not(target_arch = "wasm32"))] +#[derive(Default)] +struct MissingJobs { + raster: Vec, + seen_raster: HashSet, + videos: HashMap>, +} + +#[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, +} + +#[cfg(not(target_arch = "wasm32"))] +struct VideoDecodeTask { + path: PathBuf, + decoder: Option>, + 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_premult: 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, + ) + } else { + decode_raster_image( + &job.cache_key.path, + job.cache_key.post_multiply, + allow_parallel_premult, + ) + } +} + +#[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 } /// Resolves a Fusion `ClipSpec` (still image or numbered image sequence) at `frame`. @@ -1022,4 +1812,253 @@ mod tests { 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.budget_bytes, + default_media_cache_budget_mb().saturating_mul(1024 * 1024) + ); + let explicit = MediaCache::with_budget_mb(32); + assert_eq!(explicit.budget_bytes, 32 * 1024 * 1024); + } + + #[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); + } } diff --git a/crates/engine/src/media/exr.rs b/crates/engine/src/media/exr.rs index 705d14a50f704526ffed56259ec10c9f9bb9d9f6..a828b0470a3cdf24b8aa21949ebe12356b024a2f 100644 --- a/crates/engine/src/media/exr.rs +++ b/crates/engine/src/media/exr.rs @@ -51,15 +51,51 @@ pub(super) fn normalize_channel_opt(opt: Option<&str>) -> Option { .map(str::to_owned) } -pub(super) fn apply_post_multiply_rgba8(raw: &mut [u8]) { +fn apply_post_multiply_rgba8_slice(raw: &mut [u8]) { for px in raw.chunks_exact_mut(4) { - let a = u16::from(px[3]); - if a < 255 { - px[0] = ((u16::from(px[0]) * a + 127) / 255) as u8; - px[1] = ((u16::from(px[1]) * a + 127) / 255) as u8; - px[2] = ((u16::from(px[2]) * a + 127) / 255) as u8; + let a = px[3]; + if a == 255 { + continue; + } + if a == 0 { + px[0] = 0; + px[1] = 0; + px[2] = 0; + continue; + } + let a16 = u16::from(a); + px[0] = ((u16::from(px[0]) * a16 + 127) / 255) as u8; + px[1] = ((u16::from(px[1]) * a16 + 127) / 255) as u8; + px[2] = ((u16::from(px[2]) * a16 + 127) / 255) as u8; + } +} + +pub(super) fn apply_post_multiply_rgba8(raw: &mut [u8]) { + apply_post_multiply_rgba8_parallel(raw, true); +} + +pub(super) fn apply_post_multiply_rgba8_parallel(raw: &mut [u8], allow_parallel: bool) { + #[cfg(not(target_arch = "wasm32"))] + { + // Parallelize across worker slices for > 4 MP images (e.g. 15 MP plates) when not + // already running inside a multi-image worker pool. + const PARALLEL_THRESHOLD_BYTES: usize = 4 * 1024 * 1024 * 4; + if allow_parallel && raw.len() >= PARALLEL_THRESHOLD_BYTES { + let workers = std::thread::available_parallelism() + .map(|n| n.get().clamp(2, 8)) + .unwrap_or(4); + let total_px = raw.len() / 4; + let chunk_bytes = total_px.div_ceil(workers).max(1) * 4; + std::thread::scope(|scope| { + for chunk in raw.chunks_mut(chunk_bytes) { + scope.spawn(move || apply_post_multiply_rgba8_slice(chunk)); + } + }); + return; } } + let _ = allow_parallel; + apply_post_multiply_rgba8_slice(raw); } pub(super) fn find_exr_channel_loc( @@ -154,7 +190,11 @@ pub(super) fn decode_exr_rgba( let names = [red_name, green_name, blue_name, alpha_name]; match super::virtual_bytes(path) { Some(bytes) => decode_exr_from(std::io::Cursor::new(bytes), names, post_multiply), - None => decode_exr_from(std::io::BufReader::new(std::fs::File::open(path).ok()?), names, post_multiply), + None => decode_exr_from( + std::io::BufReader::with_capacity(256 * 1024, std::fs::File::open(path).ok()?), + names, + post_multiply, + ), } } diff --git a/crates/engine/src/ram_cache.rs b/crates/engine/src/ram_cache.rs index 1c570b3983c862dce733318f00ff810a8b9545a3..0db72c84505a297054cb2f2b57ed539617d4f1d4 100644 --- a/crates/engine/src/ram_cache.rs +++ b/crates/engine/src/ram_cache.rs @@ -22,13 +22,90 @@ use std::sync::Condvar; #[cfg(not(target_arch = "wasm32"))] use std::thread::{self, JoinHandle}; -/// Default RAM frame cache ceiling (1 GiB ≈ 130 full-res 1080p frames or ~520 half-res frames). +/// Fallback RAM frame cache ceiling (1 GiB ≈ 130 full-res 1080p frames or ~520 half-res frames). pub const DEFAULT_RAM_CACHE_MB: u64 = 1024; /// Modest VRAM budget for the shared-device background prefetcher `Engine`. pub const DEFAULT_PREFETCH_VRAM_MB: u64 = 256; /// Modest media decode cache budget for the shared-device background prefetcher `Engine`. pub const DEFAULT_PREFETCH_MEDIA_MB: u64 = 128; +/// Returns total physical system memory in bytes, or a conservative 2 GiB default on `wasm32`. +pub fn system_memory_bytes() -> u64 { + #[cfg(target_arch = "wasm32")] + { + 2 * 1024 * 1024 * 1024 + } + #[cfg(target_os = "macos")] + { + unsafe extern "C" { + fn sysctlbyname( + name: *const std::ffi::c_char, + oldp: *mut std::ffi::c_void, + oldlenp: *mut usize, + newp: *const std::ffi::c_void, + newlen: usize, + ) -> std::ffi::c_int; + } + let mut memsize: u64 = 0; + let mut size = std::mem::size_of::(); + // SAFETY: `memsize` is a stack u64 and `size` matches its exact byte size. + let rc = unsafe { + sysctlbyname( + c"hw.memsize".as_ptr(), + (&raw mut memsize).cast::(), + &raw mut size, + std::ptr::null(), + 0, + ) + }; + if rc == 0 && size == std::mem::size_of::() && memsize > 0 { + return memsize; + } + 8 * 1024 * 1024 * 1024 + } + #[cfg(target_os = "linux")] + { + if let Ok(meminfo) = std::fs::read_to_string("/proc/meminfo") { + for line in meminfo.lines() { + if let Some(rest) = line.strip_prefix("MemTotal:") { + if let Some(kb) = rest.split_whitespace().next().and_then(|s| s.parse::().ok()) { + if kb > 0 { + return kb.saturating_mul(1024); + } + } + } + } + } + 8 * 1024 * 1024 * 1024 + } + #[cfg(all(not(target_arch = "wasm32"), not(target_os = "macos"), not(target_os = "linux")))] + { + 8 * 1024 * 1024 * 1024 + } +} + +pub(crate) fn ram_cache_budget_mb_for_total_bytes(total_bytes: u64) -> u64 { + let gib = total_bytes / (1024 * 1024 * 1024); + if gib >= 256 { + 32 * 1024 + } else if gib >= 128 { + 16 * 1024 + } else if gib >= 64 { + 8 * 1024 + } else if gib >= 32 { + 4 * 1024 + } else if gib >= 16 { + 2 * 1024 + } else { + DEFAULT_RAM_CACHE_MB + } +} + +/// Returns the default `RamFrameCache` budget in MiB scaled to host physical RAM. +pub fn default_ram_cache_budget_mb() -> u64 { + ram_cache_budget_mb_for_total_bytes(system_memory_bytes()) +} + #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct RamFrameKey { pub target: NodeId, @@ -89,7 +166,7 @@ pub struct RamFrameCache { impl Default for RamFrameCache { fn default() -> Self { - Self::new(DEFAULT_RAM_CACHE_MB) + Self::new(default_ram_cache_budget_mb()) } } @@ -113,6 +190,10 @@ impl RamFrameCache { } } + pub fn with_budget_mb(budget_mb: u64) -> Self { + Self::new(budget_mb) + } + pub fn epoch(&self) -> u64 { self.cache_epoch.load(Ordering::Acquire) } @@ -859,4 +940,24 @@ Composition { ); prefetcher.cancel(); } + + #[test] + fn system_memory_and_ram_budget_scaling() { + const GIB: u64 = 1024 * 1024 * 1024; + assert!(system_memory_bytes() >= GIB); + assert_eq!(ram_cache_budget_mb_for_total_bytes(8 * GIB), DEFAULT_RAM_CACHE_MB); + assert_eq!(ram_cache_budget_mb_for_total_bytes(16 * GIB), 2048); + assert_eq!(ram_cache_budget_mb_for_total_bytes(32 * GIB), 4096); + assert_eq!(ram_cache_budget_mb_for_total_bytes(64 * GIB), 8192); + assert_eq!(ram_cache_budget_mb_for_total_bytes(128 * GIB), 16384); + assert_eq!(ram_cache_budget_mb_for_total_bytes(256 * GIB), 32768); + + let default_cache = RamFrameCache::default(); + assert_eq!(default_cache.budget_mb(), default_ram_cache_budget_mb()); + + let explicit = RamFrameCache::with_budget_mb(32); + assert_eq!(explicit.budget_mb(), 32); + explicit.set_budget_mb(16); + assert_eq!(explicit.budget_mb(), 16); + } } -- 2.54.1