authoravatarclover caruso<git@paperclover.net>2026-12-01 13:12:27-08:00
committeravatarclover caruso<git@paperclover.net>2026-12-01 13:31:51-08:00
logb72d3326c594153d96b2fa4add70819663b71002
tree154756acf2ed2e3fb8ba93f9755ea5e7fb557f23
parentada4f74499c41f1f97bb372ec21043f2e260071d
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

perf(engine): parallel loader pre-decode, pipelined export, and RAM-scaled caches


5 files changed, 1621 insertions(+), 143 deletions(-)

crates/engine/src/bin/render_check.rs+150-21
......@@ -1,11 +1,15 @@
11//! Headless verification, parity+perf suite runner, and batch PNG sequence renderer for `engine`.
22
33use engine::export::{VideoCodec, VideoExportOptions, export_node_video_ffmpeg};
4use engine::media::default_media_cache_budget_mb;
45use engine::{CacheMode, Engine, ExportOptions, export_saver_png_sequence};
56use model::Comp;
67use std::collections::HashMap;
78use std::fs::File;
9use std::io::BufWriter;
810use std::path::{Path, PathBuf};
11use std::sync::atomic::{AtomicBool, Ordering};
12use std::sync::{Arc, Mutex, mpsc};
913use std::time::Instant;
1014
1115fn compute_diff(pixels: &[u8], tex_size: [u32; 2], ref_path: &Path) -> Result<(f64, f64, f64), Box<dyn std::error::Error>> {
......@@ -36,20 +40,34 @@ fn compute_diff(pixels: &[u8], tex_size: [u32; 2], ref_path: &Path) -> Result<(f
3640 Ok((mae, rmse, alpha_abs as f64 / px as f64))
3741}
3842
39fn write_png(path: &Path, size: [u32; 2], pixels: &[u8]) -> Result<(), Box<dyn std::error::Error>> {
40 if let Some(parent) = path.parent() {
41 std::fs::create_dir_all(parent)?;
42 }
43 let mut enc = png::Encoder::new(File::create(path)?, size[0], size[1]);
43fn write_png_raw(path: &Path, size: [u32; 2], pixels: &[u8]) -> Result<(), String> {
44 let file = File::create(path).map_err(|e| format!("failed to create '{}': {e}", path.display()))?;
45 let writer = BufWriter::with_capacity(256 * 1024, file);
46 let mut enc = png::Encoder::new(writer, size[0], size[1]);
4447 enc.set_color(png::ColorType::Rgba);
4548 enc.set_depth(png::BitDepth::Eight);
46 enc.write_header()?.write_image_data(pixels)?;
49 enc.set_compression(png::Compression::Fast);
50 enc.set_filter(png::Filter::Sub);
51 enc.write_header()
52 .map_err(|e| format!("failed to write PNG header '{}': {e}", path.display()))?
53 .write_image_data(pixels)
54 .map_err(|e| format!("failed to write PNG data '{}': {e}", path.display()))?;
4755 Ok(())
4856}
4957
58fn write_png(path: &Path, size: [u32; 2], pixels: &[u8]) -> Result<(), Box<dyn std::error::Error>> {
59 if let Some(parent) = path.parent() {
60 if !parent.as_os_str().is_empty() {
61 std::fs::create_dir_all(parent)?;
62 }
63 }
64 write_png_raw(path, size, pixels).map_err(|e| e.into())
65}
66
5067fn run_suite(manifest_path: &Path, hiq: bool) -> Result<(), Box<dyn std::error::Error>> {
5168 let text = std::fs::read_to_string(manifest_path)?;
5269 let mut engine = Engine::new_headless()?;
70 engine.set_media_budget_mb(default_media_cache_budget_mb());
5371 engine.hiq = hiq;
5472 let mut comps: HashMap<PathBuf, Comp> = HashMap::new();
5573 let mut passed = 0usize;
......@@ -93,6 +111,13 @@ fn run_suite(manifest_path: &Path, hiq: bool) -> Result<(), Box<dyn std::error::
93111 };
94112
95113 engine.set_cache_mode(CacheMode::Enabled);
114 engine.media.preload_frame_loaders_with_proxy(
115 comp,
116 target,
117 frame,
118 &engine.expr,
119 engine.use_proxy_clips,
120 );
96121 let (tex, cold) = engine.evaluate(comp, target, frame);
97122 let (_, warm) = engine.evaluate(comp, target, frame);
98123 engine.bust_gpu_cache();
......@@ -157,6 +182,7 @@ fn run_batch_render(
157182 };
158183 std::fs::create_dir_all(out_dir)?;
159184 let mut engine = Engine::new_headless()?;
185 engine.set_media_budget_mb(default_media_cache_budget_mb());
160186 engine.proxy_scale = proxy_scale;
161187
162188 let total = (end - start + 1).max(0) as usize;
......@@ -172,22 +198,115 @@ fn run_batch_render(
172198 end,
173199 out_dir.display()
174200 );
175 for (idx, f) in (start..=end).enumerate() {
176 let (tex, stats) = engine.evaluate(&comp, target, f as f64);
177 let pixels = engine.readback_rgba(&tex)?;
178 let out_file = out_dir.join(format!("{f:04}.png"));
179 write_png(&out_file, tex.size, &pixels)?;
180 if idx == 0 || (idx + 1) % 10 == 0 || idx + 1 == total {
181 let elapsed = t_all.elapsed().as_secs_f64().max(1e-6);
182 let fps = (idx + 1) as f64 / elapsed;
183 eprintln!(
184 " [{:>4}/{total}] f{f:04} | eval={:.1}ms | avg={fps:.1} fps | vram={:.0}MB | unsupported={:?}",
185 idx + 1,
186 stats.eval_ms,
187 stats.cached_vram_mb,
188 stats.unsupported_nodes,
189 );
201
202 if total > 0 {
203 struct RenderEncodeJob {
204 path: PathBuf,
205 size: [u32; 2],
206 pixels: Vec<u8>,
190207 }
208 let workers = std::thread::available_parallelism()
209 .map(|n| n.get().clamp(2, 8))
210 .unwrap_or(4);
211 let queue_cap = (workers * 2).clamp(16, 32);
212 let first_err: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));
213 let failed = Arc::new(AtomicBool::new(false));
214
215 std::thread::scope(|scope| -> Result<(), Box<dyn std::error::Error>> {
216 let (tx, rx) = mpsc::sync_channel::<RenderEncodeJob>(queue_cap);
217 let shared_rx = Arc::new(Mutex::new(rx));
218 let mut handles = Vec::with_capacity(workers);
219 for _ in 0..workers {
220 let rx_c = Arc::clone(&shared_rx);
221 let err_c = Arc::clone(&first_err);
222 let fail_c = Arc::clone(&failed);
223 handles.push(scope.spawn(move || {
224 loop {
225 let job = {
226 let Ok(guard) = rx_c.lock() else { break };
227 guard.recv()
228 };
229 let Ok(job) = job else { break };
230 if fail_c.load(Ordering::Acquire) {
231 continue;
232 }
233 if let Err(e) = write_png_raw(&job.path, job.size, &job.pixels) {
234 if let Ok(mut g) = err_c.lock() {
235 if g.is_none() {
236 *g = Some(e);
237 }
238 }
239 fail_c.store(true, Ordering::Release);
240 }
241 }
242 }));
243 }
244
245 let mut loop_err: Option<String> = None;
246 const PREFETCH_WINDOW: usize = 8;
247 for (idx, f) in (start..=end).enumerate() {
248 if failed.load(Ordering::Acquire) {
249 break;
250 }
251 if idx % PREFETCH_WINDOW == 0 {
252 let win_end = (idx + PREFETCH_WINDOW).min(total);
253 let window: Vec<f64> =
254 (idx..win_end).map(|k| (start + k as i64) as f64).collect();
255 engine.media.prefetch_frames_with_proxy(
256 &comp,
257 target,
258 &window,
259 &engine.expr,
260 engine.use_proxy_clips,
261 );
262 }
263 let (tex, stats) = engine.evaluate(&comp, target, f as f64);
264 let pixels = match engine.readback_rgba(&tex) {
265 Ok(px) => px,
266 Err(e) => {
267 loop_err = Some(format!("GPU readback failed at frame {f}: {e}"));
268 break;
269 }
270 };
271 let out_file = out_dir.join(format!("{f:04}.png"));
272 if tx
273 .send(RenderEncodeJob {
274 path: out_file,
275 size: tex.size,
276 pixels,
277 })
278 .is_err()
279 {
280 break;
281 }
282 if idx == 0 || (idx + 1) % 10 == 0 || idx + 1 == total {
283 let elapsed = t_all.elapsed().as_secs_f64().max(1e-6);
284 let fps = (idx + 1) as f64 / elapsed;
285 eprintln!(
286 " [{:>4}/{total}] f{f:04} | eval={:.1}ms | avg={fps:.1} fps | vram={:.0}MB | unsupported={:?}",
287 idx + 1,
288 stats.eval_ms,
289 stats.cached_vram_mb,
290 stats.unsupported_nodes,
291 );
292 }
293 }
294
295 drop(tx);
296 for h in handles {
297 let _ = h.join();
298 }
299
300 if let Some(e) = loop_err {
301 return Err(e.into());
302 }
303 if let Ok(mut g) = first_err.lock() {
304 if let Some(e) = g.take() {
305 return Err(e.into());
306 }
307 }
308 Ok(())
309 })?;
191310 }
192311 eprintln!(
193312 "Finished {total} frames in {:.2}s ({:.1} fps)",
......@@ -218,6 +337,7 @@ fn run_saver_export(
218337 _ => None,
219338 };
220339 let mut engine = Engine::new_headless()?;
340 engine.set_media_budget_mb(default_media_cache_budget_mb());
221341 let opts = ExportOptions {
222342 saver_name: saver_name.map(str::to_owned),
223343 out_dir_override,
......@@ -287,6 +407,7 @@ fn run_video_export(
287407 _ => comp.render_range,
288408 };
289409 let mut engine = Engine::new_headless()?;
410 engine.set_media_budget_mb(default_media_cache_budget_mb());
290411 let opts = VideoExportOptions {
291412 target,
292413 out_path: out_path.clone(),
......@@ -589,6 +710,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
589710 );
590711
591712 let mut engine = Engine::new_headless()?;
713 engine.set_media_budget_mb(default_media_cache_budget_mb());
592714 engine.proxy_scale = proxy_scale;
593715 engine.use_proxy_clips = use_proxy_clips;
594716 if let Some(mb) = vram_budget_mb {
......@@ -599,6 +721,13 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
599721 if profile {
600722 engine.cache.begin_frame_profile_with_comp(&comp);
601723 }
724 engine.media.preload_frame_loaders_with_proxy(
725 &comp,
726 target,
727 frame,
728 &engine.expr,
729 engine.use_proxy_clips,
730 );
602731 let (tex, cold) = engine.evaluate(&comp, target, frame);
603732 let cold_profile = if profile {
604733 engine.cache.take_frame_profile().map(|mut fp| {
crates/engine/src/export.rs+231-62
......@@ -196,11 +196,12 @@ fn write_png_fast(path: &Path, size: [u32; 2], pixels: &[u8]) -> Result<(), Stri
196196 }
197197 let file = File::create(path)
198198 .map_err(|e| format!("failed to create '{}': {e}", path.display()))?;
199 let writer = BufWriter::new(file);
199 let writer = BufWriter::with_capacity(256 * 1024, file);
200200 let mut enc = png::Encoder::new(writer, size[0], size[1]);
201201 enc.set_color(png::ColorType::Rgba);
202202 enc.set_depth(png::BitDepth::Eight);
203203 enc.set_compression(png::Compression::Fast);
204 enc.set_filter(png::Filter::Sub);
204205 let mut png_w = enc
205206 .write_header()
206207 .map_err(|e| format!("failed to write PNG header '{}': {e}", path.display()))?;
......@@ -272,7 +273,8 @@ pub fn export_saver_png_sequence_with_progress(
272273 let cancelled = Arc::new(AtomicBool::new(false));
273274
274275 let eval_result: Result<(), String> = std::thread::scope(|scope| {
275 let (tx, rx) = mpsc::sync_channel::<EncodeJob>(workers * 2);
276 let queue_cap = (workers * 2).clamp(16, 32);
277 let (tx, rx) = mpsc::sync_channel::<EncodeJob>(queue_cap);
276278 let shared_rx = Arc::new(Mutex::new(rx));
277279
278280 let mut handles = Vec::with_capacity(workers);
......@@ -304,6 +306,7 @@ pub fn export_saver_png_sequence_with_progress(
304306 }
305307
306308 let mut loop_err: Option<String> = None;
309 const PREFETCH_WINDOW: usize = 8;
307310 for (idx, frame) in (start..=end).enumerate() {
308311 if failed.load(Ordering::Acquire) {
309312 break;
......@@ -312,6 +315,17 @@ pub fn export_saver_png_sequence_with_progress(
312315 cancelled.store(true, Ordering::Release);
313316 break;
314317 }
318 if idx % PREFETCH_WINDOW == 0 {
319 let win_end = (idx + PREFETCH_WINDOW).min(total);
320 let window: Vec<f64> = (idx..win_end).map(|k| (start + k as i64) as f64).collect();
321 engine.media.prefetch_frames_with_proxy(
322 comp,
323 target,
324 &window,
325 &engine.expr,
326 engine.use_proxy_clips,
327 );
328 }
315329 let out_path = match resolve_output_path(&saver, frame, opts.out_dir_override.as_deref()) {
316330 Ok(p) => p,
317331 Err(e) => {
......@@ -639,6 +653,13 @@ pub fn export_node_video_ffmpeg_with_progress(
639653 let node_name = comp.node(opts.target).name.clone();
640654
641655 // Evaluate the first frame before spawning ffmpeg so dimensions match actual GPU output.
656 engine.media.preload_frame_loaders_with_proxy(
657 comp,
658 opts.target,
659 start as f64,
660 &engine.expr,
661 engine.use_proxy_clips,
662 );
642663 let (first_tex, first_stats) = engine.evaluate(comp, opts.target, start as f64);
643664 if first_tex.size[0] == 0 || first_tex.size[1] == 0 {
644665 return Err(format!(
......@@ -815,77 +836,135 @@ pub fn export_node_video_ffmpeg_with_progress(
815836
816837 let mut pipe_err: Option<String> = None;
817838 let mut cancelled = false;
818 {
819 let mut stdin = child
820 .stdin
821 .take()
822 .ok_or_else(|| "failed to open ffmpeg stdin".to_owned())?;
823
824 if let Err(e) = stdin.write_all(&first_pixels) {
825 pipe_err = Some(format!("failed writing frame {start} to ffmpeg: {e}"));
826 } else {
827 let first_prog = make_progress(
828 start,
829 0,
830 total,
831 first_stats.eval_ms,
832 opts.out_path.clone(),
833 node_name.clone(),
834 t0,
835 );
836 if let Some(ctrl) = control {
837 ctrl.update_progress(&first_prog);
838 }
839 on_progress(first_prog);
840
841 for (idx, frame) in ((start + 1)..=end).enumerate() {
842 if control.is_some_and(ExportControl::is_cancelled) {
843 cancelled = true;
844 break;
845 }
846 let (tex, stats) = engine.evaluate(comp, opts.target, frame as f64);
847 let pixels = match engine.readback_rgba(&tex) {
848 Ok(px) => px,
849 Err(e) => {
850 pipe_err = Some(format!("GPU readback failed at frame {frame}: {e}"));
851 break;
839 let writer_err: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));
840 let writer_failed = Arc::new(AtomicBool::new(false));
841 let stdin = child
842 .stdin
843 .take()
844 .ok_or_else(|| "failed to open ffmpeg stdin".to_owned())?;
845
846 let frame_bytes_len = (width as usize)
847 .saturating_mul(height as usize)
848 .saturating_mul(4)
849 .max(1);
850 let queue_cap = (128 * 1024 * 1024 / frame_bytes_len).clamp(4, 16);
851 let (tx, rx) = mpsc::sync_channel::<(i64, [u32; 2], Vec<u8>)>(queue_cap);
852 let writer_err_c = Arc::clone(&writer_err);
853 let writer_failed_c = Arc::clone(&writer_failed);
854 let dst_size = [width, height];
855 let writer_thread = std::thread::spawn(move || {
856 let mut stdin = BufWriter::with_capacity(4 * 1024 * 1024, stdin);
857 while let Ok((frame, src_size, pixels)) = rx.recv() {
858 let frame_bytes = match fit_frame_rgba(pixels, src_size, dst_size, frame) {
859 Ok(bytes) => bytes,
860 Err(e) => {
861 if let Ok(mut g) = writer_err_c.lock() {
862 if g.is_none() {
863 *g = Some(e);
864 }
852865 }
853 };
854 if control.is_some_and(ExportControl::is_cancelled) {
855 cancelled = true;
866 writer_failed_c.store(true, Ordering::Release);
856867 break;
857868 }
858 let frame_bytes = match fit_frame_rgba(pixels, tex.size, [width, height], frame) {
859 Ok(bytes) => bytes,
860 Err(e) => {
861 pipe_err = Some(e);
862 break;
869 };
870 if let Err(e) = stdin.write_all(&frame_bytes) {
871 if let Ok(mut g) = writer_err_c.lock() {
872 if g.is_none() {
873 *g = Some(format!("failed writing frame {frame} to ffmpeg: {e}"));
863874 }
864 };
865
866 if let Err(e) = stdin.write_all(&frame_bytes) {
867 pipe_err = Some(format!("failed writing frame {frame} to ffmpeg: {e}"));
868 break;
869875 }
870 let prog = make_progress(
871 frame,
872 idx + 1,
873 total,
874 stats.eval_ms,
875 opts.out_path.clone(),
876 node_name.clone(),
877 t0,
876 writer_failed_c.store(true, Ordering::Release);
877 break;
878 }
879 }
880 let _ = stdin.flush();
881 });
882
883 if tx.send((start, [width, height], first_pixels)).is_err() {
884 pipe_err = writer_err
885 .lock()
886 .ok()
887 .and_then(|mut g| g.take())
888 .or_else(|| Some(format!("failed writing frame {start} to ffmpeg")));
889 } else {
890 let first_prog = make_progress(
891 start,
892 0,
893 total,
894 first_stats.eval_ms,
895 opts.out_path.clone(),
896 node_name.clone(),
897 t0,
898 );
899 if let Some(ctrl) = control {
900 ctrl.update_progress(&first_prog);
901 }
902 on_progress(first_prog);
903
904 const PREFETCH_WINDOW: usize = 8;
905 let remaining = total.saturating_sub(1);
906 for (idx, frame) in ((start + 1)..=end).enumerate() {
907 if writer_failed.load(Ordering::Acquire) {
908 break;
909 }
910 if control.is_some_and(ExportControl::is_cancelled) {
911 cancelled = true;
912 break;
913 }
914 if idx % PREFETCH_WINDOW == 0 {
915 let win_end = (idx + PREFETCH_WINDOW).min(remaining);
916 let window: Vec<f64> = (idx..win_end).map(|k| (start + 1 + k as i64) as f64).collect();
917 engine.media.prefetch_frames_with_proxy(
918 comp,
919 opts.target,
920 &window,
921 &engine.expr,
922 engine.use_proxy_clips,
878923 );
879 if let Some(ctrl) = control {
880 ctrl.update_progress(&prog);
924 }
925 let (tex, stats) = engine.evaluate(comp, opts.target, frame as f64);
926 let pixels = match engine.readback_rgba(&tex) {
927 Ok(px) => px,
928 Err(e) => {
929 pipe_err = Some(format!("GPU readback failed at frame {frame}: {e}"));
930 break;
881931 }
882 on_progress(prog);
932 };
933 if control.is_some_and(ExportControl::is_cancelled) {
934 cancelled = true;
935 break;
936 }
937 if tx.send((frame, tex.size, pixels)).is_err() {
938 break;
883939 }
940 let prog = make_progress(
941 frame,
942 idx + 1,
943 total,
944 stats.eval_ms,
945 opts.out_path.clone(),
946 node_name.clone(),
947 t0,
948 );
949 if let Some(ctrl) = control {
950 ctrl.update_progress(&prog);
951 }
952 on_progress(prog);
884953 }
885 let _ = stdin.flush();
886954 }
955 drop(tx);
887956
888 if cancelled || pipe_err.is_some() {
957 if cancelled || pipe_err.is_some() || writer_failed.load(Ordering::Acquire) {
958 // Kill ffmpeg before joining writer_thread so a blocked pipe write unblocks immediately.
959 let _ = child.kill();
960 }
961 let _ = writer_thread.join();
962 if pipe_err.is_none() && !cancelled {
963 if let Ok(mut g) = writer_err.lock() {
964 pipe_err = g.take();
965 }
966 }
967 if pipe_err.is_some() && !cancelled {
889968 let _ = child.kill();
890969 }
891970 let status = child
......@@ -1598,4 +1677,94 @@ mod tests {
15981677
15991678 let _ = std::fs::remove_dir_all(&tmp_dir);
16001679 }
1680
1681 #[test]
1682 fn pipelined_png_export_is_pixel_exact_and_propagates_write_errors() {
1683 let tmp_dir = std::env::temp_dir().join(format!(
1684 "fission-png-pipeline-exact-{}",
1685 std::process::id()
1686 ));
1687 let _ = std::fs::remove_dir_all(&tmp_dir);
1688 std::fs::create_dir_all(&tmp_dir).expect("create temp dir");
1689
1690 let saver_path = tmp_dir.join("out").join("frame_0000.png");
1691 let saver_path_escaped = saver_path.to_string_lossy().replace('\\', "\\\\");
1692 let comp_src = format!(
1693 r#"Composition {{
1694 CurrentTime = 0,
1695 RenderRange = {{ 0, 5 }},
1696 GlobalRange = {{ 0, 5 }},
1697 Tools = ordered() {{
1698 BG = Background {{
1699 Inputs = {{
1700 Width = Input {{ Value = 96, }},
1701 Height = Input {{ Value = 48, }},
1702 TopLeftRed = Input {{ SourceOp = "BGRed", Source = "Value", }},
1703 TopLeftGreen = Input {{ Value = 0.5, }},
1704 TopLeftBlue = Input {{ Value = 0.25, }},
1705 TopLeftAlpha = Input {{ Value = 1.0, }},
1706 }},
1707 }},
1708 BGRed = BezierSpline {{
1709 KeyFrames = {{
1710 [0] = {{ 0.1, Flags = {{ Linear = true }} }},
1711 [5] = {{ 0.9, Flags = {{ Linear = true }} }},
1712 }},
1713 }},
1714 Saver1 = Saver {{
1715 Inputs = {{
1716 Clip = Input {{
1717 Value = Clip {{
1718 Filename = "{saver_path_escaped}",
1719 FormatID = "PNGFormat",
1720 Saving = true,
1721 }},
1722 }},
1723 Input = Input {{ SourceOp = "BG", Source = "Output", }},
1724 }},
1725 }},
1726 }},
1727 Prefs = {{ Comp = {{ FrameFormat = {{ Width = 96, Height = 48, Rate = 24, DepthFull = 1 }} }} }},
1728}}"#
1729 );
1730
1731 let comp = Comp::from_fusion_str(&comp_src).expect("parse comp");
1732 let target = comp.find_node("BG").unwrap();
1733 let mut engine = Engine::new_headless().expect("headless wgpu engine");
1734
1735 let summary = export_saver_png_sequence(&mut engine, &comp, &ExportOptions::default(), |_| {})
1736 .expect("export png sequence");
1737 assert_eq!(summary.frames_written, 6);
1738
1739 // Verify fast-compressed PNGs decode byte-identically to direct GPU readback.
1740 for f in 0..=5 {
1741 let (tex, _) = engine.evaluate(&comp, target, f as f64);
1742 let expected = engine.readback_rgba(&tex).expect("readback");
1743 let png_path = tmp_dir.join("out").join(format!("frame_{f:04}.png"));
1744 let decoded = image::open(&png_path).expect("decode png").to_rgba8();
1745 assert_eq!(decoded.dimensions(), (tex.size[0], tex.size[1]));
1746 assert_eq!(
1747 decoded.into_raw(),
1748 expected,
1749 "fast PNG encode must be 100% lossless at frame {f}"
1750 );
1751 }
1752
1753 // Verify worker write error propagates cleanly: point out_dir_override inside a regular file.
1754 let blocking_file = tmp_dir.join("not_a_dir");
1755 std::fs::write(&blocking_file, b"file").expect("write blocking file");
1756 let err = export_saver_png_sequence(
1757 &mut engine,
1758 &comp,
1759 &ExportOptions {
1760 out_dir_override: Some(blocking_file),
1761 ..ExportOptions::default()
1762 },
1763 |_| {},
1764 )
1765 .expect_err("writing into a regular file path must return Err");
1766 assert!(!err.is_empty());
1767
1768 let _ = std::fs::remove_dir_all(&tmp_dir);
1769 }
16011770}
crates/engine/src/media.rs+1090-51
......@@ -10,15 +10,26 @@ pub use raster::{TextPlusParams, rasterize_polyline_mask, rasterize_text_plus};
1010#[cfg(target_os = "macos")]
1111pub use video::AvFoundationDecoder;
1212pub use video::{FfmpegDecoder, VideoDecoder, VideoInfo, open_video_decoder};
13use exr::{apply_post_multiply_rgba8, decode_exr_rgba, is_exr_path, normalize_channel_opt};
13use exr::{
14 apply_post_multiply_rgba8, apply_post_multiply_rgba8_parallel, decode_exr_rgba, is_exr_path,
15 normalize_channel_opt,
16};
1417use video::is_video_path;
1518
1619use crate::text_engine;
17use model::{ClipSpec, ClsEntry, PolyPoint};
20#[cfg(not(target_arch = "wasm32"))]
21use model::{Node, default_main_input_port};
22use model::{ClipSpec, ClsEntry, Comp, NodeId, PolyPoint};
23#[cfg(not(target_arch = "wasm32"))]
24use std::collections::HashSet;
1825use std::collections::HashMap;
1926use std::path::{Path, PathBuf};
2027use std::process::Command;
28#[cfg(not(target_arch = "wasm32"))]
29use std::sync::Mutex;
2130use std::sync::{Arc, RwLock};
31#[cfg(not(target_arch = "wasm32"))]
32use std::sync::atomic::{AtomicUsize, Ordering};
2233
2334#[derive(Clone)]
2435pub struct DecodedImage {
......@@ -119,12 +130,58 @@ fn path_exists(path: &Path) -> bool {
119130}
120131
121132fn open_image(path: &Path) -> Option<image::DynamicImage> {
122 match virtual_bytes(path) {
123 Some(bytes) => image::load_from_memory(&bytes).ok(),
124 None => image::open(path).ok(),
133 if let Some(bytes) = virtual_bytes(path) {
134 return image::load_from_memory(&bytes).ok();
135 }
136 // Read file contents in one contiguous pass to avoid tiny buffered syscalls over SMB/network shares.
137 if let Ok(bytes) = std::fs::read(path) {
138 if let Ok(img) = image::load_from_memory(&bytes) {
139 return Some(img);
140 }
141 }
142 image::open(path).ok()
143}
144
145fn decode_raster_image(
146 path: &Path,
147 post_multiply: bool,
148 allow_parallel_premult: bool,
149) -> Option<DecodedImage> {
150 let dyn_img = open_image(path)?;
151 let has_alpha = dyn_img.color().has_alpha();
152 let size = [dyn_img.width(), dyn_img.height()];
153 let mut raw = dyn_img.into_rgba8().into_raw();
154 if post_multiply && has_alpha {
155 apply_post_multiply_rgba8_parallel(&mut raw, allow_parallel_premult);
156 }
157 Some(DecodedImage {
158 size,
159 rgba: Arc::new(raw),
160 rgba_f16: None,
161 rgba_f32: None,
162 })
163}
164
165pub(crate) fn media_cache_budget_mb_for_total_bytes(total_bytes: u64) -> u64 {
166 let gib = total_bytes / (1024 * 1024 * 1024);
167 if gib >= 128 {
168 8 * 1024
169 } else if gib >= 64 {
170 4 * 1024
171 } else if gib >= 32 {
172 2 * 1024
173 } else if gib >= 16 {
174 1024
175 } else {
176 512
125177 }
126178}
127179
180/// Returns the default `MediaCache` budget in MiB scaled to host physical RAM.
181pub fn default_media_cache_budget_mb() -> u64 {
182 media_cache_budget_mb_for_total_bytes(crate::ram_cache::system_memory_bytes())
183}
184
128185#[derive(Clone, Debug, PartialEq, Eq, Hash)]
129186struct ImageCacheKey {
130187 path: PathBuf,
......@@ -147,18 +204,28 @@ pub struct MediaCache {
147204 tick: u64,
148205}
149206
207impl Default for MediaCache {
208 fn default() -> Self {
209 Self::new(default_media_cache_budget_mb())
210 }
211}
212
150213impl MediaCache {
151214 pub fn new(budget_mb: u64) -> Self {
152215 Self {
153216 images: HashMap::new(),
154217 video_decoders: HashMap::new(),
155218 total_bytes: 0,
156 budget_bytes: budget_mb * 1024 * 1024,
219 budget_bytes: budget_mb.saturating_mul(1024 * 1024),
157220 lru: HashMap::new(),
158221 tick: 0,
159222 }
160223 }
161224
225 pub fn with_budget_mb(budget_mb: u64) -> Self {
226 Self::new(budget_mb)
227 }
228
162229 /// Registers `bytes` as the file at `path` for every `MediaCache` in the process. `false`
163230 /// when the files held would pass [`MAX_VIRTUAL_BYTES`], leaving the registry unchanged.
164231 pub fn insert_virtual_bytes(path: impl AsRef<Path>, bytes: impl Into<Arc<[u8]>>) -> bool {
......@@ -224,12 +291,13 @@ impl MediaCache {
224291 }
225292 }
226293
227 fn get_or_open_video_decoder(&mut self, path: &Path) -> Option<VideoInfo> {
294 fn put_video_decoder(&mut self, path: PathBuf, decoder: Option<Box<dyn VideoDecoder>>) {
228295 self.tick += 1;
229296 let now_tick = self.tick;
230 if let Some(entry) = self.video_decoders.get_mut(path) {
297 if let Some(entry) = self.video_decoders.get_mut(&path) {
298 entry.decoder = decoder;
231299 entry.last_used = now_tick;
232 return entry.decoder.as_ref().map(|d| d.info());
300 return;
233301 }
234302 while self.video_decoders.len() >= MAX_VIDEO_DECODERS {
235303 let Some(oldest_path) = self
......@@ -242,15 +310,25 @@ impl MediaCache {
242310 };
243311 self.video_decoders.remove(&oldest_path);
244312 }
245 let decoder = open_video_decoder(path);
246 let info = decoder.as_ref().map(|d| d.info());
247313 self.video_decoders.insert(
248 path.to_path_buf(),
314 path,
249315 VideoDecoderEntry {
250316 decoder,
251317 last_used: now_tick,
252318 },
253319 );
320 }
321
322 fn get_or_open_video_decoder(&mut self, path: &Path) -> Option<VideoInfo> {
323 self.tick += 1;
324 let now_tick = self.tick;
325 if let Some(entry) = self.video_decoders.get_mut(path) {
326 entry.last_used = now_tick;
327 return entry.decoder.as_ref().map(|d| d.info());
328 }
329 let decoder = open_video_decoder(path);
330 let info = decoder.as_ref().map(|d| d.info());
331 self.put_video_decoder(path.to_path_buf(), decoder);
254332 info
255333 }
256334
......@@ -265,36 +343,12 @@ impl MediaCache {
265343 ) -> Option<(PathBuf, i64, DecodedImage, bool)> {
266344 let base = Path::new(&clip.filename);
267345 if is_video_path(base) {
268 if !base.exists() {
346 if !base.exists() || !video_frame_in_range(clip, frame) {
269347 return None;
270348 }
271 // Enforce active timeline range [GlobalStart - ExtendFirst, GlobalEnd + ExtendLast].
272 if clip.global_end >= clip.global_start
273 && (clip.length.unwrap_or(0) > 1 || clip.global_end > clip.global_start)
274 {
275 let min_f = clip.global_start - clip.extend_first.max(0);
276 let max_f = clip.global_end + clip.extend_last.max(0);
277 if frame < min_f || (!clip.loop_clip && frame > max_f) {
278 return None;
279 }
280 }
281349 let base_buf = base.to_path_buf();
282350 let info = self.get_or_open_video_decoder(base)?;
283
284 let len = clip.length.unwrap_or(info.nb_frames.max(1)).max(1);
285 let trim_in = clip.trim_in.clamp(0, len - 1);
286 let trim_out = if clip.trim_out > 0 {
287 clip.trim_out.clamp(trim_in, len - 1)
288 } else {
289 len - 1
290 };
291 let span = (trim_out - trim_in + 1).max(1);
292 let rel = if clip.loop_clip {
293 (frame - clip.global_start).max(0).rem_euclid(span)
294 } else {
295 (frame - clip.global_start).clamp(0, span - 1)
296 };
297 let idx = if clip.reverse { trim_out - rel } else { trim_in + rel };
351 let idx = compute_video_frame_idx(clip, frame, info.nb_frames);
298352 let cache_key = ImageCacheKey {
299353 path: base_buf.clone(),
300354 frame_idx: idx,
......@@ -359,23 +413,759 @@ impl MediaCache {
359413 false,
360414 )?
361415 } else {
362 let dyn_img = open_image(&resolved)?;
363 let rgba_img = dyn_img.to_rgba8();
364 let size = [rgba_img.width(), rgba_img.height()];
365 let mut raw = rgba_img.into_raw();
366 if post_multiply {
367 apply_post_multiply_rgba8(&mut raw);
368 }
369 DecodedImage {
370 size,
371 rgba: Arc::new(raw),
372 rgba_f16: None,
373 rgba_f32: None,
374 }
416 decode_raster_image(&resolved, post_multiply, true)?
375417 };
376418 self.insert_cached(cache_key, decoded.clone());
377419 Some((resolved, -1, decoded, true))
378420 }
421
422 /// Walks reachable `Loader` nodes upstream of `target` at `time` and decodes any missing
423 /// still/sequence/EXR frames into RAM in parallel when 2 or more distinct files are uncached.
424 pub fn preload_frame_loaders(
425 &mut self,
426 comp: &Comp,
427 target: NodeId,
428 time: f64,
429 expr: &model::ExprEngine,
430 ) {
431 self.preload_frame_loaders_with_proxy(comp, target, time, expr, false);
432 }
433
434 /// Variant of [`Self::preload_frame_loaders`] honoring `use_proxy_clips`.
435 pub fn preload_frame_loaders_with_proxy(
436 &mut self,
437 comp: &Comp,
438 target: NodeId,
439 time: f64,
440 expr: &model::ExprEngine,
441 use_proxy_clips: bool,
442 ) {
443 #[cfg(target_arch = "wasm32")]
444 {
445 let _ = (comp, target, time, expr, use_proxy_clips);
446 }
447 #[cfg(not(target_arch = "wasm32"))]
448 {
449 let mut visited = HashSet::new();
450 let mut jobs = MissingJobs::default();
451 self.collect_missing_loader_jobs(
452 comp,
453 target,
454 time,
455 expr,
456 use_proxy_clips,
457 &mut visited,
458 &mut jobs,
459 );
460 if jobs.total_units() < 2 {
461 return;
462 }
463 self.decode_jobs_parallel(jobs);
464 }
465 }
466
467 /// Pre-decodes reachable `Loader` files for upcoming `frames` in parallel into `MediaCache`.
468 pub fn prefetch_frames(
469 &mut self,
470 comp: &Comp,
471 target: NodeId,
472 frames: &[f64],
473 expr: &model::ExprEngine,
474 ) {
475 self.prefetch_frames_with_proxy(comp, target, frames, expr, false);
476 }
477
478 /// Variant of [`Self::prefetch_frames`] honoring `use_proxy_clips`.
479 pub fn prefetch_frames_with_proxy(
480 &mut self,
481 comp: &Comp,
482 target: NodeId,
483 frames: &[f64],
484 expr: &model::ExprEngine,
485 use_proxy_clips: bool,
486 ) {
487 #[cfg(target_arch = "wasm32")]
488 {
489 let _ = (comp, target, frames, expr, use_proxy_clips);
490 }
491 #[cfg(not(target_arch = "wasm32"))]
492 {
493 if frames.is_empty() {
494 return;
495 }
496 let mut visited = HashSet::new();
497 let mut jobs = MissingJobs::default();
498 for &time in frames {
499 self.collect_missing_loader_jobs(
500 comp,
501 target,
502 time,
503 expr,
504 use_proxy_clips,
505 &mut visited,
506 &mut jobs,
507 );
508 }
509 let total = jobs.total_units();
510 if total == 0 {
511 return;
512 }
513 if total == 1 && jobs.raster.len() == 1 {
514 let job = jobs.raster.pop().expect("len == 1");
515 if let Some(decoded) = decode_job(&job, true) {
516 self.insert_cached(job.cache_key, decoded);
517 }
518 return;
519 }
520 self.decode_jobs_parallel(jobs);
521 }
522 }
523
524 #[cfg(not(target_arch = "wasm32"))]
525 fn decode_jobs_parallel(&mut self, mut jobs: MissingJobs) {
526 let mut video_tasks: Vec<VideoDecodeTask> = jobs
527 .videos
528 .drain()
529 .map(|(path, requests)| {
530 let decoder = self
531 .video_decoders
532 .get_mut(&path)
533 .and_then(|entry| entry.decoder.take());
534 VideoDecodeTask {
535 path,
536 decoder,
537 requests,
538 }
539 })
540 .collect();
541 let video_count = video_tasks.len();
542 let raster_jobs = jobs.raster;
543 let total_units = video_count + raster_jobs.len();
544 if total_units == 0 {
545 return;
546 }
547 let workers = std::thread::available_parallelism()
548 .map(|n| n.get().clamp(1, 8))
549 .unwrap_or(4)
550 .min(total_units);
551
552 let next_idx = AtomicUsize::new(0);
553 let video_slots: Vec<
554 Mutex<Option<(PathBuf, Option<Box<dyn VideoDecoder>>, Vec<(ImageCacheKey, DecodedImage)>)>>,
555 > = (0..video_count).map(|_| Mutex::new(None)).collect();
556 let raster_slots: Vec<Mutex<Option<DecodedImage>>> =
557 (0..raster_jobs.len()).map(|_| Mutex::new(None)).collect();
558
559 let video_inputs: Vec<Mutex<Option<VideoDecodeTask>>> =
560 video_tasks.drain(..).map(|t| Mutex::new(Some(t))).collect();
561
562 std::thread::scope(|scope| {
563 for _ in 0..workers {
564 scope.spawn(|| loop {
565 let idx = next_idx.fetch_add(1, Ordering::Relaxed);
566 if idx >= total_units {
567 break;
568 }
569 if idx < video_count {
570 let task = video_inputs[idx].lock().ok().and_then(|mut g| g.take());
571 if let Some(mut task) = task {
572 let mut dec_opt =
573 task.decoder.take().or_else(|| open_video_decoder(&task.path));
574 let mut decoded_frames = Vec::new();
575 if let Some(ref mut dec) = dec_opt {
576 let info = dec.info();
577 let mut seen_local = HashSet::new();
578 for req in &task.requests {
579 let frame_idx = compute_video_frame_idx(
580 &req.clip,
581 req.frame_i,
582 info.nb_frames,
583 );
584 if !seen_local.insert((frame_idx, req.post_multiply)) {
585 continue;
586 }
587 if let Some(mut raw) = dec.decode_frame(frame_idx) {
588 if req.post_multiply {
589 apply_post_multiply_rgba8_parallel(&mut raw, false);
590 }
591 let key = ImageCacheKey {
592 path: task.path.clone(),
593 frame_idx,
594 post_multiply: req.post_multiply,
595 exr_channels: [None, None, None, None],
596 };
597 decoded_frames.push((
598 key,
599 DecodedImage {
600 size: [info.width, info.height],
601 rgba: Arc::new(raw),
602 rgba_f16: None,
603 rgba_f32: None,
604 },
605 ));
606 }
607 }
608 }
609 if let Ok(mut slot) = video_slots[idx].lock() {
610 *slot = Some((task.path, dec_opt, decoded_frames));
611 }
612 }
613 } else {
614 let r_idx = idx - video_count;
615 let decoded = decode_job(&raster_jobs[r_idx], false);
616 if let Ok(mut slot) = raster_slots[r_idx].lock() {
617 *slot = decoded;
618 }
619 }
620 });
621 }
622 });
623
624 for slot in video_slots {
625 if let Ok(mut guard) = slot.into_inner() {
626 if let Some((path, dec_opt, frames)) = guard.take() {
627 self.put_video_decoder(path, dec_opt);
628 for (key, img) in frames {
629 self.insert_cached(key, img);
630 }
631 }
632 }
633 }
634 for (job, slot) in raster_jobs.into_iter().zip(raster_slots) {
635 if let Ok(mut guard) = slot.into_inner() {
636 if let Some(decoded) = guard.take() {
637 self.insert_cached(job.cache_key, decoded);
638 }
639 }
640 }
641 }
642
643 #[cfg(not(target_arch = "wasm32"))]
644 #[allow(clippy::too_many_arguments)]
645 fn collect_missing_loader_jobs(
646 &self,
647 comp: &Comp,
648 node_id: NodeId,
649 time: f64,
650 expr: &model::ExprEngine,
651 use_proxy_clips: bool,
652 visited: &mut HashSet<(NodeId, i64)>,
653 jobs: &mut MissingJobs,
654 ) {
655 if node_id.0 >= comp.nodes.len() {
656 return;
657 }
658 let time_key = (if time == 0.0 { 0.0 } else { time }).to_bits() as i64;
659 if !visited.insert((node_id, time_key)) {
660 return;
661 }
662 let node = comp.node(node_id);
663
664 if node.bypassed
665 || matches!(
666 node.kind.as_str(),
667 "Saver"
668 | "PipeRouter"
669 | "Fuse.Wireless"
670 | "Tracker"
671 | "Dimension.OpticalFlow"
672 | "OpticalFlow"
673 | "Dimension.CopyAux"
674 )
675 {
676 let port = default_main_input_port(&node.kind);
677 if let Some(src_id) = node.connected_node(port).and_then(|s| comp.find_node(s)) {
678 self.collect_missing_loader_jobs(
679 comp,
680 src_id,
681 time,
682 expr,
683 use_proxy_clips,
684 visited,
685 jobs,
686 );
687 }
688 return;
689 }
690
691 if matches!(node.kind.as_str(), "MacroOperator" | "GroupOperator") {
692 let next_id = node.macro_output.or_else(|| {
693 node.connected_node("Input")
694 .or_else(|| node.connected_node("MainInput1"))
695 .and_then(|s| comp.find_node(s))
696 });
697 if let Some(src_id) = next_id {
698 self.collect_missing_loader_jobs(
699 comp,
700 src_id,
701 time,
702 expr,
703 use_proxy_clips,
704 visited,
705 jobs,
706 );
707 }
708 return;
709 }
710
711 if matches!(node.kind.as_str(), "TimeStretcher" | "TimeSpeed") {
712 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
713 return;
714 };
715 let remapped = match node.kind.as_str() {
716 "TimeStretcher" => comp.eval_number(node, "SourceTime", time, 0.0, expr),
717 "TimeSpeed" => {
718 let speed = comp.eval_number(node, "Speed", time, 1.0, expr);
719 let delay = comp.eval_number(node, "Delay", time, 0.0, expr);
720 let g_start = comp.global_range[0] as f64;
721 let g_end = comp.global_range[1] as f64;
722 if speed < 0.0 {
723 ((g_end + 1.0) + (time - delay - g_start) * speed).min(g_end)
724 } else {
725 g_start + (time - delay - g_start) * speed
726 }
727 }
728 _ => time,
729 };
730 let interp = comp
731 .eval_number(node, "InterpolateBetweenFrames", time, 1.0, expr)
732 .round() as i32;
733 if interp <= 0 {
734 let snapped = (remapped + 0.5).floor();
735 self.collect_missing_loader_jobs(
736 comp,
737 src_id,
738 snapped,
739 expr,
740 use_proxy_clips,
741 visited,
742 jobs,
743 );
744 return;
745 }
746 let f0 = remapped.floor();
747 let frac = (remapped - f0) as f32;
748 if frac > 1e-3 && frac < 1.0 - 1e-3 {
749 let src_node = comp.node(src_id);
750 let has_optflow = matches!(src_node.kind.as_str(), "Dimension.OpticalFlow" | "OpticalFlow");
751 let eval_src_id = if has_optflow {
752 src_node
753 .connected_node("Input")
754 .and_then(|s| comp.find_node(s))
755 .unwrap_or(src_id)
756 } else {
757 src_id
758 };
759 self.collect_missing_loader_jobs(
760 comp,
761 eval_src_id,
762 f0,
763 expr,
764 use_proxy_clips,
765 visited,
766 jobs,
767 );
768 self.collect_missing_loader_jobs(
769 comp,
770 eval_src_id,
771 f0 + 1.0,
772 expr,
773 use_proxy_clips,
774 visited,
775 jobs,
776 );
777 } else {
778 self.collect_missing_loader_jobs(
779 comp,
780 src_id,
781 remapped,
782 expr,
783 use_proxy_clips,
784 visited,
785 jobs,
786 );
787 }
788 return;
789 }
790
791 if node.kind == "Switch" || node.kind == "Fuse.Switch" {
792 let is_native_zero_indexed = node.kind == "Switch"
793 && (node.inputs.contains_key("Source")
794 || node.inputs.contains_key("Input0")
795 || !node.inputs.contains_key("Which"));
796 let src_name = if is_native_zero_indexed {
797 let source = comp
798 .eval_number(node, "Source", time, 0.0, expr)
799 .round()
800 .max(0.0) as usize;
801 let port = format!("Input{source}");
802 node.connected_node(&port)
803 .or_else(|| node.connected_node("Input0"))
804 } else {
805 let which = comp
806 .eval_number(node, "Which", time, 1.0, expr)
807 .round()
808 .max(1.0) as usize;
809 let port = format!("Input{which}");
810 node.connected_node(&port)
811 .or_else(|| node.connected_node("Input1"))
812 };
813 if let Some(src_id) = src_name.and_then(|s| comp.find_node(s)) {
814 self.collect_missing_loader_jobs(
815 comp,
816 src_id,
817 time,
818 expr,
819 use_proxy_clips,
820 visited,
821 jobs,
822 );
823 }
824 return;
825 }
826
827 if node.kind == "Fuse.SwitchElse" {
828 let index = |name: &str, default: f64| {
829 comp.eval_number(node, name, time, default, expr)
830 .round()
831 .max(1.0) as usize
832 };
833 let picked = [index("Switch", 1.0), index("Else", 2.0)].into_iter().find_map(|i| {
834 node.connected_node(&format!("Input{i}"))
835 .and_then(|s| comp.find_node(s))
836 });
837 if let Some(src_id) = picked {
838 self.collect_missing_loader_jobs(
839 comp,
840 src_id,
841 time,
842 expr,
843 use_proxy_clips,
844 visited,
845 jobs,
846 );
847 }
848 return;
849 }
850
851 if node.kind == "Merge" {
852 if let Some(bg_id) = node.connected_node("Background").and_then(|s| comp.find_node(s)) {
853 self.collect_missing_loader_jobs(
854 comp,
855 bg_id,
856 time,
857 expr,
858 use_proxy_clips,
859 visited,
860 jobs,
861 );
862 }
863 let blend = comp.eval_number(node, "Blend", time, 1.0, expr) as f32;
864 let mbm = comp.eval_number(node, "MultiplyByMask", time, 0.0, expr) > 0.5;
865 let mask_id = resolve_effect_mask_id_for_node(comp, node);
866 if !(blend <= 1e-6 && !(mbm && node.connected_node("EffectMask").is_some())) {
867 if let Some(fg_id) = node.connected_node("Foreground").and_then(|s| comp.find_node(s)) {
868 self.collect_missing_loader_jobs(
869 comp,
870 fg_id,
871 time,
872 expr,
873 use_proxy_clips,
874 visited,
875 jobs,
876 );
877 }
878 }
879 if let Some(mid) = mask_id {
880 self.collect_missing_loader_jobs(
881 comp,
882 mid,
883 time,
884 expr,
885 use_proxy_clips,
886 visited,
887 jobs,
888 );
889 }
890 return;
891 }
892
893 if node.kind == "Loader" {
894 if let Some(clip) = node.clips.first() {
895 let frame_i = time.round() as i64;
896 let post_mult = node.static_number("Clip1.PNGFormat.PostMultiply").unwrap_or(0.0) > 0.5;
897 let exr_channels = [
898 node.static_str("Clip1.OpenEXRFormat.RedName"),
899 node.static_str("Clip1.OpenEXRFormat.GreenName"),
900 node.static_str("Clip1.OpenEXRFormat.BlueName"),
901 node.static_str("Clip1.OpenEXRFormat.AlphaName"),
902 ];
903 let mut effective_clip = clip.clone();
904 if node.inputs.contains_key("GlobalIn") {
905 effective_clip.global_start = comp
906 .eval_number(node, "GlobalIn", time, effective_clip.global_start as f64, expr)
907 .round() as i64;
908 }
909 if node.inputs.contains_key("GlobalOut") {
910 effective_clip.global_end = comp
911 .eval_number(node, "GlobalOut", time, effective_clip.global_end as f64, expr)
912 .round() as i64;
913 }
914 if node.inputs.contains_key("Loop") {
915 effective_clip.loop_clip = comp.eval_number(
916 node,
917 "Loop",
918 time,
919 if effective_clip.loop_clip { 1.0 } else { 0.0 },
920 expr,
921 ) > 0.5;
922 }
923 if node.inputs.contains_key("Reverse") {
924 effective_clip.reverse = comp.eval_number(
925 node,
926 "Reverse",
927 time,
928 if effective_clip.reverse { 1.0 } else { 0.0 },
929 expr,
930 ) > 0.5;
931 }
932 if use_proxy_clips {
933 let proxy_candidate = node
934 .static_str("ProxyFilename")
935 .filter(|s| !s.trim().is_empty())
936 .or_else(|| clip.alternate_filename.as_deref().filter(|s| !s.trim().is_empty()));
937 if let Some(proxy_name) = proxy_candidate {
938 let mut proxy_clip = effective_clip.clone();
939 proxy_clip.filename = proxy_name.to_owned();
940 if resolve_clip_path(&proxy_clip, frame_i).is_some_and(|p| path_exists(&p)) {
941 effective_clip = proxy_clip;
942 }
943 }
944 }
945 let out_of_range = effective_clip.global_end >= effective_clip.global_start
946 && (frame_i < effective_clip.global_start - effective_clip.extend_first.max(0)
947 || (!effective_clip.loop_clip
948 && frame_i > effective_clip.global_end + effective_clip.extend_last.max(0)));
949 if !out_of_range {
950 let base = Path::new(&effective_clip.filename);
951 if is_video_path(base) {
952 if base.exists() && video_frame_in_range(&effective_clip, frame_i) {
953 let need_decode = match self.video_decoders.get(base) {
954 Some(entry) => entry.decoder.as_ref().is_some_and(|dec| {
955 let idx = compute_video_frame_idx(
956 &effective_clip,
957 frame_i,
958 dec.info().nb_frames,
959 );
960 let cache_key = ImageCacheKey {
961 path: base.to_path_buf(),
962 frame_idx: idx,
963 post_multiply: post_mult,
964 exr_channels: [None, None, None, None],
965 };
966 !self.images.contains_key(&cache_key)
967 }),
968 None => true,
969 };
970 if need_decode {
971 jobs.videos
972 .entry(base.to_path_buf())
973 .or_default()
974 .push(VideoFrameRequest {
975 clip: effective_clip,
976 frame_i,
977 post_multiply: post_mult,
978 });
979 }
980 }
981 } else if let Some(resolved) = resolve_clip_path(&effective_clip, frame_i) {
982 let is_exr = is_exr_path(&resolved);
983 let key_channels = if is_exr {
984 [
985 normalize_channel_opt(exr_channels[0]),
986 normalize_channel_opt(exr_channels[1]),
987 normalize_channel_opt(exr_channels[2]),
988 normalize_channel_opt(exr_channels[3]),
989 ]
990 } else {
991 [None, None, None, None]
992 };
993 let cache_key = ImageCacheKey {
994 path: resolved,
995 frame_idx: -1,
996 post_multiply: post_mult && !is_exr,
997 exr_channels: key_channels,
998 };
999 if !self.images.contains_key(&cache_key)
1000 && jobs.seen_raster.insert(cache_key.clone())
1001 {
1002 jobs.raster.push(PreloadJob { cache_key, is_exr });
1003 }
1004 }
1005 }
1006 }
1007 if let Some(mid) = resolve_effect_mask_id_for_node(comp, node) {
1008 self.collect_missing_loader_jobs(
1009 comp,
1010 mid,
1011 time,
1012 expr,
1013 use_proxy_clips,
1014 visited,
1015 jobs,
1016 );
1017 }
1018 return;
1019 }
1020
1021 // General node: traverse all wired upstream node inputs and inherited EffectMask.
1022 let mut child_ids = Vec::new();
1023 for binding in node.inputs.values() {
1024 if let Some(src) = binding.source_op.as_deref() {
1025 if let Some(cid) = comp.find_node(src) {
1026 if !child_ids.contains(&cid) {
1027 child_ids.push(cid);
1028 }
1029 }
1030 }
1031 }
1032 if let Some(mid) = resolve_effect_mask_id_for_node(comp, node) {
1033 if !child_ids.contains(&mid) {
1034 child_ids.push(mid);
1035 }
1036 }
1037 for cid in child_ids {
1038 self.collect_missing_loader_jobs(
1039 comp,
1040 cid,
1041 time,
1042 expr,
1043 use_proxy_clips,
1044 visited,
1045 jobs,
1046 );
1047 }
1048 }
1049}
1050
1051fn video_frame_in_range(clip: &ClipSpec, frame: i64) -> bool {
1052 if clip.global_end >= clip.global_start
1053 && (clip.length.unwrap_or(0) > 1 || clip.global_end > clip.global_start)
1054 {
1055 let min_f = clip.global_start - clip.extend_first.max(0);
1056 let max_f = clip.global_end + clip.extend_last.max(0);
1057 if frame < min_f || (!clip.loop_clip && frame > max_f) {
1058 return false;
1059 }
1060 }
1061 true
1062}
1063
1064fn compute_video_frame_idx(clip: &ClipSpec, frame: i64, nb_frames: i64) -> i64 {
1065 let len = clip.length.unwrap_or(nb_frames.max(1)).max(1);
1066 let trim_in = clip.trim_in.clamp(0, len - 1);
1067 let trim_out = if clip.trim_out > 0 {
1068 clip.trim_out.clamp(trim_in, len - 1)
1069 } else {
1070 len - 1
1071 };
1072 let span = (trim_out - trim_in + 1).max(1);
1073 let rel = if clip.loop_clip {
1074 (frame - clip.global_start).max(0).rem_euclid(span)
1075 } else {
1076 (frame - clip.global_start).clamp(0, span - 1)
1077 };
1078 if clip.reverse { trim_out - rel } else { trim_in + rel }
1079}
1080
1081#[cfg(not(target_arch = "wasm32"))]
1082#[derive(Default)]
1083struct MissingJobs {
1084 raster: Vec<PreloadJob>,
1085 seen_raster: HashSet<ImageCacheKey>,
1086 videos: HashMap<PathBuf, Vec<VideoFrameRequest>>,
1087}
1088
1089#[cfg(not(target_arch = "wasm32"))]
1090impl MissingJobs {
1091 fn total_units(&self) -> usize {
1092 self.raster.len() + self.videos.len()
1093 }
1094}
1095
1096#[cfg(not(target_arch = "wasm32"))]
1097struct VideoFrameRequest {
1098 clip: ClipSpec,
1099 frame_i: i64,
1100 post_multiply: bool,
1101}
1102
1103#[cfg(not(target_arch = "wasm32"))]
1104struct VideoDecodeTask {
1105 path: PathBuf,
1106 decoder: Option<Box<dyn VideoDecoder>>,
1107 requests: Vec<VideoFrameRequest>,
1108}
1109
1110#[cfg(not(target_arch = "wasm32"))]
1111struct PreloadJob {
1112 cache_key: ImageCacheKey,
1113 is_exr: bool,
1114}
1115
1116#[cfg(not(target_arch = "wasm32"))]
1117fn decode_job(job: &PreloadJob, allow_parallel_premult: bool) -> Option<DecodedImage> {
1118 if job.is_exr {
1119 decode_exr_rgba(
1120 &job.cache_key.path,
1121 job.cache_key.exr_channels[0].as_deref(),
1122 job.cache_key.exr_channels[1].as_deref(),
1123 job.cache_key.exr_channels[2].as_deref(),
1124 job.cache_key.exr_channels[3].as_deref(),
1125 false,
1126 )
1127 } else {
1128 decode_raster_image(
1129 &job.cache_key.path,
1130 job.cache_key.post_multiply,
1131 allow_parallel_premult,
1132 )
1133 }
1134}
1135
1136#[cfg(not(target_arch = "wasm32"))]
1137fn resolve_effect_mask_id_for_node(comp: &Comp, node: &Node) -> Option<NodeId> {
1138 if let Some(id) = node.connected_node("EffectMask").and_then(|s| comp.find_node(s)) {
1139 return Some(id);
1140 }
1141 let has_explicit_mask_entry = |n: &Node| -> bool {
1142 n.raw
1143 .get_table("Inputs")
1144 .and_then(|t| t.get("EffectMask"))
1145 .is_some()
1146 };
1147 if has_explicit_mask_entry(node) {
1148 return None;
1149 }
1150 let mut visited = HashSet::new();
1151 visited.insert(node.id);
1152 let mut cur = node;
1153 for _ in 0..8 {
1154 let master_name = cur.raw.get_str("SourceOp")?;
1155 let mid = comp.find_node(master_name)?;
1156 if !visited.insert(mid) {
1157 break;
1158 }
1159 let master = comp.node(mid);
1160 if let Some(mask_id) = master.connected_node("EffectMask").and_then(|s| comp.find_node(s)) {
1161 return Some(mask_id);
1162 }
1163 if has_explicit_mask_entry(master) {
1164 return None;
1165 }
1166 cur = master;
1167 }
1168 None
3791169}
3801170
3811171/// Resolves a Fusion `ClipSpec` (still image or numbered image sequence) at `frame`.
......@@ -1022,4 +1812,253 @@ mod tests {
10221812 assert!(!put(&mut files, "a", 7));
10231813 assert_eq!(files.iter().map(|f| f.bytes.len()).sum::<usize>(), 10);
10241814 }
1815
1816 #[test]
1817 fn media_budget_scaling_matches_ram_tiers() {
1818 const GIB: u64 = 1024 * 1024 * 1024;
1819 assert_eq!(media_cache_budget_mb_for_total_bytes(8 * GIB), 512);
1820 assert_eq!(media_cache_budget_mb_for_total_bytes(16 * GIB), 1024);
1821 assert_eq!(media_cache_budget_mb_for_total_bytes(32 * GIB), 2048);
1822 assert_eq!(media_cache_budget_mb_for_total_bytes(64 * GIB), 4096);
1823 assert_eq!(media_cache_budget_mb_for_total_bytes(128 * GIB), 8192);
1824 let default_cache = MediaCache::default();
1825 assert_eq!(
1826 default_cache.budget_bytes,
1827 default_media_cache_budget_mb().saturating_mul(1024 * 1024)
1828 );
1829 let explicit = MediaCache::with_budget_mb(32);
1830 assert_eq!(explicit.budget_bytes, 32 * 1024 * 1024);
1831 }
1832
1833 #[test]
1834 fn parallel_post_multiply_matches_scalar_across_large_buffer() {
1835 let len = 4 * 1024 * 1024 * 4 + 64; // > 4 MP threshold
1836 let mut scalar = vec![0u8; len];
1837 for (i, px) in scalar.chunks_exact_mut(4).enumerate() {
1838 px[0] = ((i * 7) % 256) as u8;
1839 px[1] = ((i * 13) % 256) as u8;
1840 px[2] = ((i * 29) % 256) as u8;
1841 px[3] = (i % 256) as u8;
1842 }
1843 let mut parallel = scalar.clone();
1844 exr::apply_post_multiply_rgba8_parallel(&mut scalar, false);
1845 exr::apply_post_multiply_rgba8_parallel(&mut parallel, true);
1846 assert_eq!(scalar, parallel);
1847 }
1848
1849 #[cfg(not(target_arch = "wasm32"))]
1850 #[test]
1851 fn preload_frame_loaders_and_prefetch_frames_populate_cache_in_parallel() {
1852 let dir = std::env::temp_dir().join(format!("fission_preload_test_{}", std::process::id()));
1853 let _ = std::fs::remove_dir_all(&dir);
1854 std::fs::create_dir_all(&dir).unwrap();
1855
1856 let p_bg = dir.join("bg.png");
1857 let p_fg0 = dir.join("fg_0000.png");
1858 let p_fg1 = dir.join("fg_0001.png");
1859 let p_fg2 = dir.join("fg_0002.png");
1860 let p_pruned = dir.join("pruned.png");
1861 image::RgbaImage::from_pixel(4, 4, image::Rgba([20, 40, 60, 255])).save(&p_bg).unwrap();
1862 image::RgbaImage::from_pixel(4, 4, image::Rgba([200, 100, 50, 128])).save(&p_fg0).unwrap();
1863 image::RgbaImage::from_pixel(4, 4, image::Rgba([0, 200, 50, 255])).save(&p_fg1).unwrap();
1864 image::RgbaImage::from_pixel(4, 4, image::Rgba([50, 0, 200, 255])).save(&p_fg2).unwrap();
1865 image::RgbaImage::from_pixel(4, 4, image::Rgba([9, 9, 9, 255])).save(&p_pruned).unwrap();
1866
1867 let esc = |p: &Path| p.to_string_lossy().replace('\\', "\\\\");
1868 let comp_src = format!(
1869 r#"Composition {{
1870 CurrentTime = 0,
1871 RenderRange = {{ 0, 2 }},
1872 GlobalRange = {{ 0, 2 }},
1873 Tools = ordered() {{
1874 BgLoader = Loader {{
1875 Clips = {{
1876 Clip {{
1877 ID = "Clip1",
1878 Filename = "{}",
1879 FormatID = "PNGFormat",
1880 Length = 1,
1881 GlobalStart = 0,
1882 GlobalEnd = 2,
1883 }},
1884 }},
1885 }},
1886 FgLoader = Loader {{
1887 Clips = {{
1888 Clip {{
1889 ID = "Clip1",
1890 Filename = "{}",
1891 FormatID = "PNGFormat",
1892 StartFrame = 0,
1893 Length = 3,
1894 GlobalStart = 0,
1895 GlobalEnd = 2,
1896 }},
1897 }},
1898 Inputs = {{
1899 ["Clip1.PNGFormat.PostMultiply"] = Input {{ Value = 1, }},
1900 }},
1901 }},
1902 PrunedLoader = Loader {{
1903 Clips = {{
1904 Clip {{
1905 ID = "Clip1",
1906 Filename = "{}",
1907 FormatID = "PNGFormat",
1908 Length = 1,
1909 GlobalStart = 0,
1910 GlobalEnd = 2,
1911 }},
1912 }},
1913 }},
1914 PrunedMerge = Merge {{
1915 Inputs = {{
1916 Blend = Input {{ Value = 0, }},
1917 Background = Input {{ SourceOp = "BgLoader", Source = "Output", }},
1918 Foreground = Input {{ SourceOp = "PrunedLoader", Source = "Output", }},
1919 }},
1920 }},
1921 MainMerge = Merge {{
1922 Inputs = {{
1923 Background = Input {{ SourceOp = "PrunedMerge", Source = "Output", }},
1924 Foreground = Input {{ SourceOp = "FgLoader", Source = "Output", }},
1925 }},
1926 }},
1927 }},
1928}}"#,
1929 esc(&p_bg),
1930 esc(&p_fg0),
1931 esc(&p_pruned),
1932 );
1933 let comp = Comp::from_fusion_str(&comp_src).expect("parse preload comp");
1934 let target = comp.find_node("MainMerge").expect("MainMerge");
1935 let expr = model::ExprEngine::new();
1936 let mut cache = MediaCache::new(64);
1937
1938 cache.preload_frame_loaders(&comp, target, 0.0, &expr);
1939 // BgLoader + FgLoader(f0) are cached; PrunedLoader is skipped because PrunedMerge Blend == 0.
1940 assert_eq!(cache.entry_count(), 2);
1941
1942 let bg_clip = comp.node(comp.find_node("BgLoader").unwrap()).clips[0].clone();
1943 let fg_clip = comp.node(comp.find_node("FgLoader").unwrap()).clips[0].clone();
1944 let (_, _, bg_img, bg_from_disk) = cache.load_clip(&bg_clip, 0, false, [None; 4]).unwrap();
1945 let (_, _, fg0_img, fg0_from_disk) = cache.load_clip(&fg_clip, 0, true, [None; 4]).unwrap();
1946 assert!(!bg_from_disk);
1947 assert!(!fg0_from_disk);
1948 assert_eq!(&bg_img.rgba[..4], &[20, 40, 60, 255]);
1949 assert_eq!(&fg0_img.rgba[..4], &[100, 50, 25, 128]);
1950
1951 // Prefetch frames 1 and 2 ahead of playback.
1952 cache.prefetch_frames(&comp, target, &[1.0, 2.0], &expr);
1953 assert_eq!(cache.entry_count(), 4);
1954 let (_, _, fg1_img, fg1_from_disk) = cache.load_clip(&fg_clip, 1, true, [None; 4]).unwrap();
1955 let (_, _, fg2_img, fg2_from_disk) = cache.load_clip(&fg_clip, 2, true, [None; 4]).unwrap();
1956 assert!(!fg1_from_disk);
1957 assert!(!fg2_from_disk);
1958 assert_eq!(&fg1_img.rgba[..4], &[0, 200, 50, 255]);
1959 assert_eq!(&fg2_img.rgba[..4], &[50, 0, 200, 255]);
1960
1961 let _ = std::fs::remove_dir_all(&dir);
1962 }
1963
1964 #[cfg(not(target_arch = "wasm32"))]
1965 #[test]
1966 fn preload_frame_loaders_decodes_multiple_videos_in_parallel() {
1967 let dir = std::env::temp_dir().join(format!("fission_preload_vid_{}", std::process::id()));
1968 let _ = std::fs::remove_dir_all(&dir);
1969 std::fs::create_dir_all(&dir).unwrap();
1970
1971 let mk_mp4 = |name: &str, color: &str| {
1972 let p = dir.join(name);
1973 let ok = Command::new("ffmpeg")
1974 .args([
1975 "-y",
1976 "-v",
1977 "error",
1978 "-f",
1979 "lavfi",
1980 "-i",
1981 &format!("color=c={color}:size=32x32:rate=24:duration=0.2"),
1982 "-c:v",
1983 "libx264",
1984 "-pix_fmt",
1985 "yuv420p",
1986 ])
1987 .arg(&p)
1988 .status()
1989 .is_ok_and(|s| s.success());
1990 (p, ok)
1991 };
1992 let (v1, ok1) = mk_mp4("v1.mp4", "red");
1993 let (v2, ok2) = mk_mp4("v2.mp4", "blue");
1994 if !(ok1 && ok2) {
1995 let _ = std::fs::remove_dir_all(&dir);
1996 return;
1997 }
1998
1999 let esc = |p: &Path| p.to_string_lossy().replace('\\', "\\\\");
2000 let comp_src = format!(
2001 r#"Composition {{
2002 CurrentTime = 0,
2003 RenderRange = {{ 0, 3 }},
2004 GlobalRange = {{ 0, 3 }},
2005 Tools = ordered() {{
2006 V1 = Loader {{
2007 Clips = {{
2008 Clip {{
2009 ID = "Clip1",
2010 Filename = "{}",
2011 FormatID = "QuickTimeMovies",
2012 Length = 4,
2013 GlobalStart = 0,
2014 GlobalEnd = 3,
2015 }},
2016 }},
2017 }},
2018 V2 = Loader {{
2019 Clips = {{
2020 Clip {{
2021 ID = "Clip1",
2022 Filename = "{}",
2023 FormatID = "QuickTimeMovies",
2024 Length = 4,
2025 GlobalStart = 0,
2026 GlobalEnd = 3,
2027 }},
2028 }},
2029 }},
2030 M = Merge {{
2031 Inputs = {{
2032 Background = Input {{ SourceOp = "V1", Source = "Output", }},
2033 Foreground = Input {{ SourceOp = "V2", Source = "Output", }},
2034 }},
2035 }},
2036 }},
2037}}"#,
2038 esc(&v1),
2039 esc(&v2),
2040 );
2041 let comp = Comp::from_fusion_str(&comp_src).expect("parse video preload comp");
2042 let target = comp.find_node("M").expect("M");
2043 let expr = model::ExprEngine::new();
2044 let mut cache = MediaCache::new(64);
2045
2046 cache.preload_frame_loaders(&comp, target, 0.0, &expr);
2047 assert_eq!(cache.video_decoder_count(), 2);
2048 assert_eq!(cache.entry_count(), 2);
2049
2050 let c1 = comp.node(comp.find_node("V1").unwrap()).clips[0].clone();
2051 let c2 = comp.node(comp.find_node("V2").unwrap()).clips[0].clone();
2052 let (_, _, img1, disk1) = cache.load_clip(&c1, 0, false, [None; 4]).unwrap();
2053 let (_, _, img2, disk2) = cache.load_clip(&c2, 0, false, [None; 4]).unwrap();
2054 assert!(!disk1);
2055 assert!(!disk2);
2056 assert!(img1.rgba[0] > 200 && img1.rgba[2] < 40);
2057 assert!(img2.rgba[2] > 200 && img2.rgba[0] < 40);
2058
2059 cache.prefetch_frames(&comp, target, &[1.0, 2.0], &expr);
2060 assert_eq!(cache.entry_count(), 6);
2061
2062 let _ = std::fs::remove_dir_all(&dir);
2063 }
10252064}
crates/engine/src/media/exr.rs+47-7
......@@ -51,15 +51,51 @@ pub(super) fn normalize_channel_opt(opt: Option<&str>) -> Option<String> {
5151 .map(str::to_owned)
5252}
5353
54pub(super) fn apply_post_multiply_rgba8(raw: &mut [u8]) {
54fn apply_post_multiply_rgba8_slice(raw: &mut [u8]) {
5555 for px in raw.chunks_exact_mut(4) {
56 let a = u16::from(px[3]);
57 if a < 255 {
58 px[0] = ((u16::from(px[0]) * a + 127) / 255) as u8;
59 px[1] = ((u16::from(px[1]) * a + 127) / 255) as u8;
60 px[2] = ((u16::from(px[2]) * a + 127) / 255) as u8;
56 let a = px[3];
57 if a == 255 {
58 continue;
59 }
60 if a == 0 {
61 px[0] = 0;
62 px[1] = 0;
63 px[2] = 0;
64 continue;
65 }
66 let a16 = u16::from(a);
67 px[0] = ((u16::from(px[0]) * a16 + 127) / 255) as u8;
68 px[1] = ((u16::from(px[1]) * a16 + 127) / 255) as u8;
69 px[2] = ((u16::from(px[2]) * a16 + 127) / 255) as u8;
70 }
71}
72
73pub(super) fn apply_post_multiply_rgba8(raw: &mut [u8]) {
74 apply_post_multiply_rgba8_parallel(raw, true);
75}
76
77pub(super) fn apply_post_multiply_rgba8_parallel(raw: &mut [u8], allow_parallel: bool) {
78 #[cfg(not(target_arch = "wasm32"))]
79 {
80 // Parallelize across worker slices for > 4 MP images (e.g. 15 MP plates) when not
81 // already running inside a multi-image worker pool.
82 const PARALLEL_THRESHOLD_BYTES: usize = 4 * 1024 * 1024 * 4;
83 if allow_parallel && raw.len() >= PARALLEL_THRESHOLD_BYTES {
84 let workers = std::thread::available_parallelism()
85 .map(|n| n.get().clamp(2, 8))
86 .unwrap_or(4);
87 let total_px = raw.len() / 4;
88 let chunk_bytes = total_px.div_ceil(workers).max(1) * 4;
89 std::thread::scope(|scope| {
90 for chunk in raw.chunks_mut(chunk_bytes) {
91 scope.spawn(move || apply_post_multiply_rgba8_slice(chunk));
92 }
93 });
94 return;
6195 }
6296 }
97 let _ = allow_parallel;
98 apply_post_multiply_rgba8_slice(raw);
6399}
64100
65101pub(super) fn find_exr_channel_loc(
......@@ -154,7 +190,11 @@ pub(super) fn decode_exr_rgba(
154190 let names = [red_name, green_name, blue_name, alpha_name];
155191 match super::virtual_bytes(path) {
156192 Some(bytes) => decode_exr_from(std::io::Cursor::new(bytes), names, post_multiply),
157 None => decode_exr_from(std::io::BufReader::new(std::fs::File::open(path).ok()?), names, post_multiply),
193 None => decode_exr_from(
194 std::io::BufReader::with_capacity(256 * 1024, std::fs::File::open(path).ok()?),
195 names,
196 post_multiply,
197 ),
158198 }
159199}
160200
crates/engine/src/ram_cache.rs+103-2
......@@ -22,13 +22,90 @@ use std::sync::Condvar;
2222#[cfg(not(target_arch = "wasm32"))]
2323use std::thread::{self, JoinHandle};
2424
25/// Default RAM frame cache ceiling (1 GiB ≈ 130 full-res 1080p frames or ~520 half-res frames).
25/// Fallback RAM frame cache ceiling (1 GiB ≈ 130 full-res 1080p frames or ~520 half-res frames).
2626pub const DEFAULT_RAM_CACHE_MB: u64 = 1024;
2727/// Modest VRAM budget for the shared-device background prefetcher `Engine`.
2828pub const DEFAULT_PREFETCH_VRAM_MB: u64 = 256;
2929/// Modest media decode cache budget for the shared-device background prefetcher `Engine`.
3030pub const DEFAULT_PREFETCH_MEDIA_MB: u64 = 128;
3131
32/// Returns total physical system memory in bytes, or a conservative 2 GiB default on `wasm32`.
33pub fn system_memory_bytes() -> u64 {
34 #[cfg(target_arch = "wasm32")]
35 {
36 2 * 1024 * 1024 * 1024
37 }
38 #[cfg(target_os = "macos")]
39 {
40 unsafe extern "C" {
41 fn sysctlbyname(
42 name: *const std::ffi::c_char,
43 oldp: *mut std::ffi::c_void,
44 oldlenp: *mut usize,
45 newp: *const std::ffi::c_void,
46 newlen: usize,
47 ) -> std::ffi::c_int;
48 }
49 let mut memsize: u64 = 0;
50 let mut size = std::mem::size_of::<u64>();
51 // SAFETY: `memsize` is a stack u64 and `size` matches its exact byte size.
52 let rc = unsafe {
53 sysctlbyname(
54 c"hw.memsize".as_ptr(),
55 (&raw mut memsize).cast::<std::ffi::c_void>(),
56 &raw mut size,
57 std::ptr::null(),
58 0,
59 )
60 };
61 if rc == 0 && size == std::mem::size_of::<u64>() && memsize > 0 {
62 return memsize;
63 }
64 8 * 1024 * 1024 * 1024
65 }
66 #[cfg(target_os = "linux")]
67 {
68 if let Ok(meminfo) = std::fs::read_to_string("/proc/meminfo") {
69 for line in meminfo.lines() {
70 if let Some(rest) = line.strip_prefix("MemTotal:") {
71 if let Some(kb) = rest.split_whitespace().next().and_then(|s| s.parse::<u64>().ok()) {
72 if kb > 0 {
73 return kb.saturating_mul(1024);
74 }
75 }
76 }
77 }
78 }
79 8 * 1024 * 1024 * 1024
80 }
81 #[cfg(all(not(target_arch = "wasm32"), not(target_os = "macos"), not(target_os = "linux")))]
82 {
83 8 * 1024 * 1024 * 1024
84 }
85}
86
87pub(crate) fn ram_cache_budget_mb_for_total_bytes(total_bytes: u64) -> u64 {
88 let gib = total_bytes / (1024 * 1024 * 1024);
89 if gib >= 256 {
90 32 * 1024
91 } else if gib >= 128 {
92 16 * 1024
93 } else if gib >= 64 {
94 8 * 1024
95 } else if gib >= 32 {
96 4 * 1024
97 } else if gib >= 16 {
98 2 * 1024
99 } else {
100 DEFAULT_RAM_CACHE_MB
101 }
102}
103
104/// Returns the default `RamFrameCache` budget in MiB scaled to host physical RAM.
105pub fn default_ram_cache_budget_mb() -> u64 {
106 ram_cache_budget_mb_for_total_bytes(system_memory_bytes())
107}
108
32109#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
33110pub struct RamFrameKey {
34111 pub target: NodeId,
......@@ -89,7 +166,7 @@ pub struct RamFrameCache {
89166
90167impl Default for RamFrameCache {
91168 fn default() -> Self {
92 Self::new(DEFAULT_RAM_CACHE_MB)
169 Self::new(default_ram_cache_budget_mb())
93170 }
94171}
95172
......@@ -113,6 +190,10 @@ impl RamFrameCache {
113190 }
114191 }
115192
193 pub fn with_budget_mb(budget_mb: u64) -> Self {
194 Self::new(budget_mb)
195 }
196
116197 pub fn epoch(&self) -> u64 {
117198 self.cache_epoch.load(Ordering::Acquire)
118199 }
......@@ -859,4 +940,24 @@ Composition {
859940 );
860941 prefetcher.cancel();
861942 }
943
944 #[test]
945 fn system_memory_and_ram_budget_scaling() {
946 const GIB: u64 = 1024 * 1024 * 1024;
947 assert!(system_memory_bytes() >= GIB);
948 assert_eq!(ram_cache_budget_mb_for_total_bytes(8 * GIB), DEFAULT_RAM_CACHE_MB);
949 assert_eq!(ram_cache_budget_mb_for_total_bytes(16 * GIB), 2048);
950 assert_eq!(ram_cache_budget_mb_for_total_bytes(32 * GIB), 4096);
951 assert_eq!(ram_cache_budget_mb_for_total_bytes(64 * GIB), 8192);
952 assert_eq!(ram_cache_budget_mb_for_total_bytes(128 * GIB), 16384);
953 assert_eq!(ram_cache_budget_mb_for_total_bytes(256 * GIB), 32768);
954
955 let default_cache = RamFrameCache::default();
956 assert_eq!(default_cache.budget_mb(), default_ram_cache_budget_mb());
957
958 let explicit = RamFrameCache::with_budget_mb(32);
959 assert_eq!(explicit.budget_mb(), 32);
960 explicit.set_budget_mb(16);
961 assert_eq!(explicit.budget_mb(), 16);
962 }
862963}