1use ::png;
2use super::*;
3use std::time::Instant;
4
5#[test]
6fn decoded_image_cache_separates_post_multiply() {
7 let dir = std::env::temp_dir().join("fission_media_post_multiply_key_test");
8 std::fs::create_dir_all(&dir).unwrap();
9 let png = dir.join("half.png");
10 image::RgbaImage::from_pixel(2, 2, image::Rgba([200, 100, 50, 128])).save(&png).unwrap();
11 let clip = ClipSpec {
12 filename: png.to_string_lossy().into_owned(),
13 alternate_filename: None,
14 start_frame: 0,
15 length: Some(1),
16 trim_in: 0,
17 trim_out: 0,
18 global_start: 0,
19 global_end: 0,
20 extend_first: 0,
21 extend_last: 0,
22 loop_clip: false,
23 reverse: false,
24 };
25 let mut cache = MediaCache::new(64);
26 let mut first_px = |post_multiply| {
27 let (_, _, img, from_disk) = cache.load_clip(&clip, 0, post_multiply, [None; 4]).unwrap();
28 (img.rgba[..4].to_vec(), from_disk)
29 };
30 assert_eq!(first_px(false), (vec![200, 100, 50, 128], true));
31 assert_eq!(first_px(true), (vec![100, 50, 25, 128], true));
32 assert_eq!(first_px(false), (vec![200, 100, 50, 128], false));
33 assert_eq!(first_px(true), (vec![100, 50, 25, 128], false));
34 assert_eq!(cache.entry_count(), 2);
35 let _ = std::fs::remove_dir_all(&dir);
36}
37
38fn mean_abs_error_rgb(a: &[u8], b: &[u8]) -> f64 {
39 assert_eq!(a.len(), b.len());
40 let mut sum = 0u64;
41 let mut count = 0u64;
42 for (pa, pb) in a.chunks_exact(4).zip(b.chunks_exact(4)) {
43 sum += pa[0].abs_diff(pb[0]) as u64;
44 sum += pa[1].abs_diff(pb[1]) as u64;
45 sum += pa[2].abs_diff(pb[2]) as u64;
46 count += 3;
47 }
48 if count == 0 {
49 0.0
50 } else {
51 sum as f64 / count as f64
52 }
53}
54
55fn verify_clip_matches_ffmpeg(path: &Path) {
56 let mut dec = open_video_decoder(path).expect("open_video_decoder failed");
57 let mut ff = FfmpegDecoder::open(path).expect("FfmpegDecoder::open failed");
58
59 #[cfg(target_os = "macos")]
60 assert_eq!(
61 dec.backend_name(),
62 "AVFoundation/VideoToolbox",
63 "expected AVFoundation backend for {}",
64 path.display()
65 );
66
67 let av_info = dec.info();
68 let ff_info = ff.info();
69 assert_eq!(av_info.width, ff_info.width, "width mismatch for {}", path.display());
70 assert_eq!(av_info.height, ff_info.height, "height mismatch for {}", path.display());
71 assert!(
72 (av_info.fps - ff_info.fps).abs() < 0.2,
73 "fps mismatch for {}: av={} ff={}",
74 path.display(),
75 av_info.fps,
76 ff_info.fps
77 );
78
79 let frames = [0_i64, 1, 2, 10, 0];
80 let mut total_ms = 0.0;
81 for &f in &frames {
82 let t0 = Instant::now();
83 let av_px = dec
84 .decode_frame(f)
85 .unwrap_or_else(|| panic!("av decode frame {f} failed for {}", path.display()));
86 let elapsed_ms = t0.elapsed().as_secs_f64() * 1000.0;
87 total_ms += elapsed_ms;
88
89 let ff_px = ff
90 .decode_frame(f)
91 .unwrap_or_else(|| panic!("ffmpeg decode frame {f} failed for {}", path.display()));
92 let mae = mean_abs_error_rgb(&av_px, &ff_px);
93 eprintln!(
94 "[video-test] {} ({}x{} @{:.2}fps) frame {}: {:.2} ms, MAE vs ffmpeg = {:.2}",
95 path.file_name().and_then(|s| s.to_str()).unwrap_or("clip"),
96 av_info.width,
97 av_info.height,
98 av_info.fps,
99 f,
100 elapsed_ms,
101 mae
102 );
103 // Allow small YUV->RGB matrix/rounding differences between VideoToolbox and swscale.
104 assert!(
105 mae < 12.0,
106 "high MAE ({mae:.2}) on {} frame {f} (possible orientation or PTS mismatch)",
107 path.display()
108 );
109 }
110 eprintln!(
111 "[video-test] {} avg decode: {:.2} ms/frame",
112 path.file_name().and_then(|s| s.to_str()).unwrap_or("clip"),
113 total_ms / frames.len() as f64
114 );
115}
116
117#[test]
118fn test_video_decoder_real_mov_clips() {
119 let clips = [
120 Path::new("/Volumes/Project/trees/EncodedMedia/A001_11071331_C002_4873-4988_d8716e17.mov"),
121 Path::new("/Volumes/Project/trees/EncodedMedia/IMG_1767_2395-2547_7efe6416.mov"),
122 ];
123 for clip in clips {
124 if clip.exists() {
125 verify_clip_matches_ffmpeg(clip);
126 }
127 }
128}
129
130#[test]
131fn test_video_decoder_synthetic_mp4() {
132 let tmp = std::env::temp_dir().join("engine_test_synth_video.mp4");
133 let status = Command::new("ffmpeg")
134 .args([
135 "-y",
136 "-v",
137 "error",
138 "-f",
139 "lavfi",
140 "-i",
141 "testsrc2=size=320x180:rate=24:duration=1.0",
142 "-c:v",
143 "libx264",
144 "-pix_fmt",
145 "yuv420p",
146 ])
147 .arg(&tmp)
148 .status();
149 if let Ok(st) = status {
150 if st.success() {
151 verify_clip_matches_ffmpeg(&tmp);
152 let _ = std::fs::remove_file(&tmp);
153 }
154 }
155}
156
157fn alpha_y_bounds(size: [u32; 2], origin: [i32; 2], rgba: &[u8]) -> (i32, i32) {
158 let [w, h] = size;
159 let mut min_y = i32::MAX;
160 let mut max_y = i32::MIN;
161 for y in 0..h as usize {
162 let row = y * w as usize * 4;
163 for x in 0..w as usize {
164 if rgba[row + x * 4 + 3] > 32 {
165 let cy = origin[1] + y as i32;
166 min_y = min_y.min(cy);
167 max_y = max_y.max(cy);
168 break;
169 }
170 }
171 }
172 (min_y, max_y)
173}
174
175#[test]
176fn test_text_plus_calibrated_metrics_and_anchoring() {
177 let base = |text: &str, v_tcb: f32, line_spacing: f32, dims: [u32; 2]| {
178 rasterize_text_plus(
179 dims,
180 &TextPlusParams {
181 text,
182 font_family: "Helvetica Neue",
183 font_style: "Regular",
184 size_norm: 0.08,
185 tracking: 1.0,
186 line_spacing,
187 center: [0.5, 0.5],
188 h_lcr: 0.0,
189 v_tcb,
190 fill_rgba: [1.0, 1.0, 1.0, 1.0],
191 write_on_start: 0.0,
192 write_on_end: 1.0,
193 shear_x: 0.0,
194 cls: &[],
195 outline_rgba: [0.0; 4],
196 outline_width_px: 0.0,
197 },
198 0,
199 )
200 };
201
202 // 1. VerticalTopCenterBottom: -1 anchors top below cy=270, 0 centers around cy=270,
203 // +1 anchors bottom baseline at cy=270 (so glyphs sit above cy=270).
204 let (s_top, o_top, p_top) = base("HHHH", -1.0, 1.0, [960, 540]);
205 let (s_ctr, o_ctr, p_ctr) = base("HHHH", 0.0, 1.0, [960, 540]);
206 let (s_bot, o_bot, p_bot) = base("HHHH", 1.0, 1.0, [960, 540]);
207 let (top_y0, top_y1) = alpha_y_bounds(s_top, o_top, &p_top);
208 let (ctr_y0, ctr_y1) = alpha_y_bounds(s_ctr, o_ctr, &p_ctr);
209 let (bot_y0, bot_y1) = alpha_y_bounds(s_bot, o_bot, &p_bot);
210 assert!(top_y0 >= 268 && top_y1 > 300, "top-aligned should sit below cy=270: ({top_y0}, {top_y1})");
211 assert!(ctr_y0 < 270 && ctr_y1 > 270, "center-aligned should straddle cy=270: ({ctr_y0}, {ctr_y1})");
212 assert!(bot_y0 < 240 && bot_y1 <= 272, "bottom-aligned should sit above cy=270: ({bot_y0}, {bot_y1})");
213
214 // 2. LineSpacing=1.5 widens a 2-line block by 0.5 * (0.8 * 0.08 * 960 = 61.44px) = ~30.7px.
215 let (s_ls1, o_ls1, p_ls1) = base("HHHH\nHHHH", 0.0, 1.0, [960, 540]);
216 let (s_ls15, o_ls15, p_ls15) = base("HHHH\nHHHH", 0.0, 1.5, [960, 540]);
217 let (ls1_y0, ls1_y1) = alpha_y_bounds(s_ls1, o_ls1, &p_ls1);
218 let (ls15_y0, ls15_y1) = alpha_y_bounds(s_ls15, o_ls15, &p_ls15);
219 let span_diff = (ls15_y1 - ls15_y0) - (ls1_y1 - ls1_y0);
220 assert!(
221 (28..=34).contains(&span_diff),
222 "LineSpacing 1.5 vs 1.0 on 960x540 Size=0.08 should add ~31px span, got {span_diff}"
223 );
224
225 // 3. Size scales with canvas width W, independent of height H.
226 let (s_wide, o_wide, p_wide) = base("HHHH", 0.0, 1.0, [960, 540]);
227 let (s_tall, o_tall, p_tall) = base("HHHH", 0.0, 1.0, [540, 960]);
228 let (wy0, wy1) = alpha_y_bounds(s_wide, o_wide, &p_wide);
229 let (ty0, ty1) = alpha_y_bounds(s_tall, o_tall, &p_tall);
230 let wide_h = (wy1 - wy0) as f32;
231 let tall_h = (ty1 - ty0) as f32;
232 let ratio = wide_h / tall_h;
233 assert!(
234 (ratio - (960.0 / 540.0)).abs() < 0.15,
235 "glyph pixel height should scale with W (expected ~1.78, got {ratio:.2}: {wide_h}/{tall_h})"
236 );
237}
238
239#[test]
240fn exr_channel_cache_isolation_and_non_beauty_guard() {
241 use ::exr::prelude::*;
242 let dir = std::env::temp_dir().join(format!("fission_exr_chan_test_{}", std::process::id()));
243 let _ = std::fs::remove_dir_all(&dir);
244 std::fs::create_dir_all(&dir).unwrap();
245
246 let multi_exr = dir.join("multi_aov.exr");
247 let w = 4usize;
248 let h = 4usize;
249 let n = w * h;
250 let mut channels = SmallVec::<[AnyChannel<FlatSamples>; 4]>::new();
251 for (name, val) in [
252 ("ViewLayer.Combined.R", 0.9_f32),
253 ("ViewLayer.Combined.G", 0.2),
254 ("ViewLayer.Combined.B", 0.1),
255 ("ViewLayer.Combined.A", 1.0),
256 ("ViewLayer.Specular.R", 0.1),
257 ("ViewLayer.Specular.G", 0.8),
258 ("ViewLayer.Specular.B", 0.7),
259 ("ViewLayer.Specular.A", 1.0),
260 ("ViewLayer.CryptoObject00.R", 0.5),
261 ] {
262 channels.push(AnyChannel::new(name, FlatSamples::F32(vec![val; n])));
263 }
264 Image::from_layer(Layer::new(
265 (w, h),
266 LayerAttributes::named("main"),
267 Encoding::FAST_LOSSLESS,
268 AnyChannels::sort(channels),
269 ))
270 .write()
271 .to_file(&multi_exr)
272 .expect("write multi-layer EXR");
273
274 let clip = ClipSpec {
275 filename: multi_exr.to_string_lossy().into_owned(),
276 alternate_filename: None,
277 start_frame: 0,
278 length: Some(1),
279 trim_in: 0,
280 trim_out: 0,
281 global_start: 0,
282 global_end: 0,
283 extend_first: 0,
284 extend_last: 0,
285 loop_clip: false,
286 reverse: false,
287 };
288 let mut cache = MediaCache::new(64);
289 let (_, _, beauty, beauty_disk) = cache.load_clip(&clip, 0, false, [None; 4]).unwrap();
290 assert!(beauty_disk);
291 let (_, _, spec, spec_disk) = cache
292 .load_clip(
293 &clip,
294 0,
295 false,
296 [
297 Some("Specular.R"),
298 Some("Specular.G"),
299 Some("Specular.B"),
300 Some("Specular.A"),
301 ],
302 )
303 .unwrap();
304 assert!(spec_disk);
305 assert_eq!(cache.entry_count(), 2);
306
307 let b_px = beauty.rgba_f32.as_ref().unwrap();
308 let s_px = spec.rgba_f32.as_ref().unwrap();
309 assert!((b_px[0] - 0.9).abs() < 1e-4 && (b_px[1] - 0.2).abs() < 1e-4);
310 assert!((s_px[0] - 0.1).abs() < 1e-4 && (s_px[1] - 0.8).abs() < 1e-4);
311
312 // Warm hits keep both AOVs isolated.
313 let (_, _, beauty_warm, beauty_disk2) = cache.load_clip(&clip, 0, false, [None; 4]).unwrap();
314 assert!(!beauty_disk2);
315 assert!((beauty_warm.rgba_f32.as_ref().unwrap()[0] - 0.9).abs() < 1e-4);
316
317 // EXR containing ONLY CryptoObject00.R (no bare R or Combined.R) must NOT match beauty fallback.
318 let crypto_only_exr = dir.join("crypto_only.exr");
319 let mut crypto_channels = SmallVec::<[AnyChannel<FlatSamples>; 4]>::new();
320 for (name, val) in [
321 ("CryptoObject00.R", 0.42_f32),
322 ("CryptoObject00.G", 0.0),
323 ("CryptoObject00.B", 0.0),
324 ("CryptoObject00.A", 1.0),
325 ] {
326 crypto_channels.push(AnyChannel::new(name, FlatSamples::F32(vec![val; n])));
327 }
328 Image::from_layer(Layer::new(
329 (w, h),
330 LayerAttributes::named("crypto"),
331 Encoding::FAST_LOSSLESS,
332 AnyChannels::sort(crypto_channels),
333 ))
334 .write()
335 .to_file(&crypto_only_exr)
336 .expect("write crypto-only EXR");
337
338 let crypto_clip = ClipSpec {
339 filename: crypto_only_exr.to_string_lossy().into_owned(),
340 ..clip
341 };
342 assert!(cache.load_clip(&crypto_clip, 0, false, [None; 4]).is_none());
343 let (_, _, explicit, _) = cache
344 .load_clip(
345 &crypto_clip,
346 0,
347 false,
348 [
349 Some("CryptoObject00.R"),
350 Some("CryptoObject00.G"),
351 Some("CryptoObject00.B"),
352 Some("CryptoObject00.A"),
353 ],
354 )
355 .expect("explicit CryptoObject00 channel selection should succeed");
356 assert!((explicit.rgba_f32.as_ref().unwrap()[0] - 0.42).abs() < 1e-4);
357
358 let _ = std::fs::remove_dir_all(&dir);
359}
360
361#[test]
362fn video_decoder_clear_lru_cap_post_multiply_and_loop() {
363 let dir = std::env::temp_dir().join(format!("fission_media_video_lru_{}", std::process::id()));
364 let _ = std::fs::remove_dir_all(&dir);
365 std::fs::create_dir_all(&dir).unwrap();
366
367 let base_mp4 = dir.join("clip_00.mp4");
368 let ok = Command::new("ffmpeg")
369 .args([
370 "-y",
371 "-v",
372 "error",
373 "-f",
374 "lavfi",
375 "-i",
376 "color=c=red:size=32x32:rate=24:duration=0.25",
377 "-c:v",
378 "libx264",
379 "-pix_fmt",
380 "yuv420p",
381 ])
382 .arg(&base_mp4)
383 .status()
384 .is_ok_and(|s| s.success());
385 assert!(ok, "ffmpeg failed to create tiny mp4");
386
387 let mut cache = MediaCache::new(64);
388 for i in 0..15 {
389 let p = if i == 0 {
390 base_mp4.clone()
391 } else {
392 let dst = dir.join(format!("clip_{i:02}.mp4"));
393 std::fs::copy(&base_mp4, &dst).unwrap();
394 dst
395 };
396 let clip = ClipSpec {
397 filename: p.to_string_lossy().into_owned(),
398 alternate_filename: None,
399 start_frame: 0,
400 length: Some(6),
401 trim_in: 0,
402 trim_out: 5,
403 global_start: 10,
404 global_end: 15,
405 extend_first: 5,
406 extend_last: 0,
407 loop_clip: true,
408 reverse: false,
409 };
410 // Frame 9 with global_start = 10, extend_first = 5 -> inside [5, 15]: ExtendFirst holds frame 0.
411 let (_, local_idx, _, _) = cache
412 .load_clip(&clip, 9, false, [None; 4])
413 .expect("loop_clip inside ExtendFirst should resolve");
414 assert_eq!(local_idx, 0);
415 // Looping clips ignore GlobalEnd + ExtendLast: frame 20 -> rel 10 -> 10 % 6 = 4.
416 let (_, local_idx, _, _) = cache
417 .load_clip(&clip, 20, false, [None; 4])
418 .expect("loop_clip past GlobalEnd should keep looping");
419 assert_eq!(local_idx, 4);
420 let once = ClipSpec { loop_clip: false, ..clip };
421 assert!(cache.load_clip(&once, 20, false, [None; 4]).is_none());
422 }
423 assert!(
424 cache.video_decoder_count() <= MAX_VIDEO_DECODERS,
425 "expected LRU cap <= {MAX_VIDEO_DECODERS}, got {}",
426 cache.video_decoder_count()
427 );
428 assert_eq!(cache.video_decoder_count(), MAX_VIDEO_DECODERS);
429
430 // Straight-alpha ProRes 4444 MOV test for post_multiply separation.
431 let alpha_png = dir.join("straight_half.png");
432 image::RgbaImage::from_pixel(32, 32, image::Rgba([200, 100, 50, 128]))
433 .save(&alpha_png)
434 .unwrap();
435 let alpha_mov = dir.join("straight_half.mov");
436 let mov_ok = Command::new("ffmpeg")
437 .args([
438 "-y",
439 "-v",
440 "error",
441 "-loop",
442 "1",
443 "-i",
444 ])
445 .arg(&alpha_png)
446 .args([
447 "-t",
448 "0.1",
449 "-r",
450 "24",
451 "-c:v",
452 "prores_ks",
453 "-profile:v",
454 "4",
455 "-pix_fmt",
456 "yuva444p10le",
457 ])
458 .arg(&alpha_mov)
459 .status()
460 .is_ok_and(|s| s.success());
461 if mov_ok {
462 let mov_clip = ClipSpec {
463 filename: alpha_mov.to_string_lossy().into_owned(),
464 alternate_filename: None,
465 start_frame: 0,
466 length: Some(2),
467 trim_in: 0,
468 trim_out: 1,
469 global_start: 0,
470 global_end: 1,
471 extend_first: 0,
472 extend_last: 0,
473 loop_clip: false,
474 reverse: false,
475 };
476 let (_, _, raw_vid, _) = cache.load_clip(&mov_clip, 0, false, [None; 4]).unwrap();
477 let (_, _, pm_vid, _) = cache.load_clip(&mov_clip, 0, true, [None; 4]).unwrap();
478 assert!(
479 pm_vid.rgba[0] < raw_vid.rgba[0],
480 "post_multiply should darken straight-alpha RGB ({} vs {})",
481 pm_vid.rgba[0],
482 raw_vid.rgba[0]
483 );
484 }
485
486 cache.clear();
487 assert_eq!(cache.entry_count(), 0);
488 assert_eq!(cache.video_decoder_count(), 0);
489
490 let _ = std::fs::remove_dir_all(&dir);
491}
492
493#[test]
494fn resolve_clip_path_missing_mid_sequence_returns_none() {
495 let dir = std::env::temp_dir().join(format!("fission_seq_missing_{}", std::process::id()));
496 let _ = std::fs::remove_dir_all(&dir);
497 std::fs::create_dir_all(&dir).unwrap();
498
499 let f0 = dir.join("shot_0000.png");
500 let f2 = dir.join("shot_0002.png");
501 image::RgbaImage::from_pixel(2, 2, image::Rgba([255, 0, 0, 255])).save(&f0).unwrap();
502 image::RgbaImage::from_pixel(2, 2, image::Rgba([0, 255, 0, 255])).save(&f2).unwrap();
503
504 let clip = ClipSpec {
505 filename: f0.to_string_lossy().into_owned(),
506 alternate_filename: None,
507 start_frame: 0,
508 length: Some(3),
509 trim_in: 0,
510 trim_out: 2,
511 global_start: 0,
512 global_end: 2,
513 extend_first: 0,
514 extend_last: 0,
515 loop_clip: false,
516 reverse: false,
517 };
518 assert_eq!(resolve_clip_path(&clip, 0), Some(f0));
519 assert_eq!(resolve_clip_path(&clip, 1), None);
520 assert_eq!(resolve_clip_path(&clip, 2), Some(f2));
521
522 let _ = std::fs::remove_dir_all(&dir);
523}
524
525#[test]
526fn virtual_bytes_load_a_sequence_by_trailing_path() {
527 let png = |rgba: [u8; 4]| {
528 let mut out = std::io::Cursor::new(Vec::new());
529 image::RgbaImage::from_pixel(2, 1, image::Rgba(rgba))
530 .write_to(&mut out, image::ImageFormat::Png)
531 .unwrap();
532 out.into_inner()
533 };
534 MediaCache::insert_virtual_bytes("vf_proj\\vf_seq.0001.png", png([255, 0, 0, 255]));
535 MediaCache::insert_virtual_bytes("./vf_proj/vf_seq.0002.png", png([0, 255, 0, 255]));
536 let clip = ClipSpec {
537 filename: "/not/on/disk/vf_proj/vf_seq.0001.png".to_owned(),
538 alternate_filename: None,
539 start_frame: 1,
540 length: Some(2),
541 trim_in: 0,
542 trim_out: 1,
543 global_start: 0,
544 global_end: 1,
545 extend_first: 0,
546 extend_last: 0,
547 loop_clip: false,
548 reverse: false,
549 };
550 let mut cache = MediaCache::new(64);
551 let (_, _, f0, from_disk) = cache.load_clip(&clip, 0, false, [None; 4]).unwrap();
552 let (_, _, f1, _) = cache.load_clip(&clip, 1, false, [None; 4]).unwrap();
553 assert!(from_disk);
554 assert_eq!((f0.size, &f0.rgba[..4]), ([2, 1], &[255, 0, 0, 255][..]));
555 assert_eq!(&f1.rgba[..4], &[0, 255, 0, 255]);
556
557 MediaCache::insert_virtual_bytes("vf_proj/vf_seq.0002.png", png([0, 0, 255, 255]));
558 let (_, _, f1, _) = MediaCache::new(64).load_clip(&clip, 1, false, [None; 4]).unwrap();
559 assert_eq!(&f1.rgba[..4], &[0, 0, 255, 255]);
560 assert!(path_exists(Path::new("elsewhere/vf_seq.0002.png")));
561 assert!(!path_exists(Path::new("vf_proj/vf_seq.0003.png")));
562}
563
564fn file(path: &str, len: usize) -> VirtualFile {
565 VirtualFile { parts: path_parts(Path::new(path)), bytes: vec![0; len].into() }
566}
567
568fn found<'a>(files: &'a [VirtualFile], path: &str) -> Option<&'a [String]> {
569 find_virtual(files, &path_parts(Path::new(path))).map(|f| f.parts.as_slice())
570}
571
572#[test]
573fn virtual_paths_normalize_dots_and_separators() {
574 assert_eq!(path_parts(Path::new("/a/./b/../c\\d.png")), ["a", "c", "d.png"]);
575 assert_eq!(path_parts(Path::new("../../x.png")), ["x.png"]);
576}
577
578#[test]
579fn virtual_matching_prefers_exact_and_rejects_ambiguous_basenames() {
580 let files = [file("A/bg.png", 1), file("B/bg.png", 1), file("only.png", 1), file("Proj/Seq.exr", 1)];
581 assert_eq!(found(&files, "/x/A/bg.png"), Some(&["A".to_owned(), "bg.png".to_owned()][..]));
582 assert_eq!(found(&files, "/x/../B/./bg.png").map(<[String]>::len), Some(2));
583 assert_eq!(found(&files, "/C/bg.png"), None, "two files share the basename");
584 assert_eq!(found(&files, "bg.png"), None);
585 assert!(found(&files, "/deep/elsewhere/only.png").is_some());
586 assert!(found(&files, "/proj/seq.EXR").is_some(), "case-insensitive fallback");
587 assert_eq!(found(&files, "/a/missing.png"), None);
588}
589
590#[test]
591fn virtual_files_stop_at_the_memory_cap() {
592 let mut files = Vec::new();
593 let put = |files: &mut Vec<VirtualFile>, name: &str, len: usize| {
594 insert_capped(files, 10, path_parts(Path::new(name)), vec![0; len].into())
595 };
596 assert!(put(&mut files, "a", 6));
597 assert!(!put(&mut files, "b", 5));
598 assert!(put(&mut files, "b", 4));
599 assert!(put(&mut files, "a", 6), "replacing a file frees its old bytes");
600 assert!(!put(&mut files, "a", 7));
601 assert_eq!(files.iter().map(|f| f.bytes.len()).sum::<usize>(), 10);
602}
603
604#[test]
605fn media_budget_scaling_matches_ram_tiers() {
606 const GIB: u64 = 1024 * 1024 * 1024;
607 assert_eq!(media_cache_budget_mb_for_total_bytes(8 * GIB), 512);
608 assert_eq!(media_cache_budget_mb_for_total_bytes(16 * GIB), 1024);
609 assert_eq!(media_cache_budget_mb_for_total_bytes(32 * GIB), 2048);
610 assert_eq!(media_cache_budget_mb_for_total_bytes(64 * GIB), 4096);
611 assert_eq!(media_cache_budget_mb_for_total_bytes(128 * GIB), 8192);
612 let default_cache = MediaCache::default();
613 assert_eq!(
614 default_cache.shared.state.lock().unwrap().budget_bytes,
615 default_media_cache_budget_mb().saturating_mul(1024 * 1024)
616 );
617 let explicit = MediaCache::with_budget_mb(32);
618 assert_eq!(
619 explicit.shared.state.lock().unwrap().budget_bytes,
620 32 * 1024 * 1024
621 );
622}
623
624#[test]
625fn parallel_post_multiply_matches_scalar_across_large_buffer() {
626 let len = 4 * 1024 * 1024 * 4 + 64; // > 4 MP threshold
627 let mut scalar = vec![0u8; len];
628 for (i, px) in scalar.chunks_exact_mut(4).enumerate() {
629 px[0] = ((i * 7) % 256) as u8;
630 px[1] = ((i * 13) % 256) as u8;
631 px[2] = ((i * 29) % 256) as u8;
632 px[3] = (i % 256) as u8;
633 }
634 let mut parallel = scalar.clone();
635 exr::apply_post_multiply_rgba8_parallel(&mut scalar, false);
636 exr::apply_post_multiply_rgba8_parallel(&mut parallel, true);
637 assert_eq!(scalar, parallel);
638}
639
640#[cfg(not(target_arch = "wasm32"))]
641#[test]
642fn preload_frame_loaders_and_prefetch_frames_populate_cache_in_parallel() {
643 let dir = std::env::temp_dir().join(format!("fission_preload_test_{}", std::process::id()));
644 let _ = std::fs::remove_dir_all(&dir);
645 std::fs::create_dir_all(&dir).unwrap();
646
647 let p_bg = dir.join("bg.png");
648 let p_fg0 = dir.join("fg_0000.png");
649 let p_fg1 = dir.join("fg_0001.png");
650 let p_fg2 = dir.join("fg_0002.png");
651 let p_pruned = dir.join("pruned.png");
652 image::RgbaImage::from_pixel(4, 4, image::Rgba([20, 40, 60, 255])).save(&p_bg).unwrap();
653 image::RgbaImage::from_pixel(4, 4, image::Rgba([200, 100, 50, 128])).save(&p_fg0).unwrap();
654 image::RgbaImage::from_pixel(4, 4, image::Rgba([0, 200, 50, 255])).save(&p_fg1).unwrap();
655 image::RgbaImage::from_pixel(4, 4, image::Rgba([50, 0, 200, 255])).save(&p_fg2).unwrap();
656 image::RgbaImage::from_pixel(4, 4, image::Rgba([9, 9, 9, 255])).save(&p_pruned).unwrap();
657
658 let esc = |p: &Path| p.to_string_lossy().replace('\\', "\\\\");
659 let comp_src = format!(
660 r#"Composition {{
661CurrentTime = 0,
662RenderRange = {{ 0, 2 }},
663GlobalRange = {{ 0, 2 }},
664Tools = ordered() {{
665 BgLoader = Loader {{
666 Clips = {{
667 Clip {{
668 ID = "Clip1",
669 Filename = "{}",
670 FormatID = "PNGFormat",
671 Length = 1,
672 GlobalStart = 0,
673 GlobalEnd = 2,
674 }},
675 }},
676 }},
677 FgLoader = Loader {{
678 Clips = {{
679 Clip {{
680 ID = "Clip1",
681 Filename = "{}",
682 FormatID = "PNGFormat",
683 StartFrame = 0,
684 Length = 3,
685 GlobalStart = 0,
686 GlobalEnd = 2,
687 }},
688 }},
689 Inputs = {{
690 ["Clip1.PNGFormat.PostMultiply"] = Input {{ Value = 1, }},
691 }},
692 }},
693 PrunedLoader = Loader {{
694 Clips = {{
695 Clip {{
696 ID = "Clip1",
697 Filename = "{}",
698 FormatID = "PNGFormat",
699 Length = 1,
700 GlobalStart = 0,
701 GlobalEnd = 2,
702 }},
703 }},
704 }},
705 PrunedMerge = Merge {{
706 Inputs = {{
707 Blend = Input {{ Value = 0, }},
708 Background = Input {{ SourceOp = "BgLoader", Source = "Output", }},
709 Foreground = Input {{ SourceOp = "PrunedLoader", Source = "Output", }},
710 }},
711 }},
712 MainMerge = Merge {{
713 Inputs = {{
714 Background = Input {{ SourceOp = "PrunedMerge", Source = "Output", }},
715 Foreground = Input {{ SourceOp = "FgLoader", Source = "Output", }},
716 }},
717 }},
718}},
719}}"#,
720 esc(&p_bg),
721 esc(&p_fg0),
722 esc(&p_pruned),
723 );
724 let comp = Comp::from_fusion_str(&comp_src).expect("parse preload comp");
725 let target = comp.find_node("MainMerge").expect("MainMerge");
726 let expr = model::ExprEngine::new();
727 let mut cache = MediaCache::new(64);
728
729 cache.preload_frame_loaders(&comp, target, 0.0, &expr);
730 // BgLoader + FgLoader(f0) are cached; PrunedLoader is skipped because PrunedMerge Blend == 0.
731 assert_eq!(cache.entry_count(), 2);
732
733 let bg_clip = comp.node(comp.find_node("BgLoader").unwrap()).clips[0].clone();
734 let fg_clip = comp.node(comp.find_node("FgLoader").unwrap()).clips[0].clone();
735 let (_, _, bg_img, bg_from_disk) = cache.load_clip(&bg_clip, 0, false, [None; 4]).unwrap();
736 let (_, _, fg0_img, fg0_from_disk) = cache.load_clip(&fg_clip, 0, true, [None; 4]).unwrap();
737 assert!(!bg_from_disk);
738 assert!(!fg0_from_disk);
739 assert_eq!(&bg_img.rgba[..4], &[20, 40, 60, 255]);
740 assert_eq!(&fg0_img.rgba[..4], &[100, 50, 25, 128]);
741
742 // Prefetch frames 1 and 2 ahead of playback.
743 cache.prefetch_frames(&comp, target, &[1.0, 2.0], &expr);
744 assert_eq!(cache.entry_count(), 4);
745 let (_, _, fg1_img, fg1_from_disk) = cache.load_clip(&fg_clip, 1, true, [None; 4]).unwrap();
746 let (_, _, fg2_img, fg2_from_disk) = cache.load_clip(&fg_clip, 2, true, [None; 4]).unwrap();
747 assert!(!fg1_from_disk);
748 assert!(!fg2_from_disk);
749 assert_eq!(&fg1_img.rgba[..4], &[0, 200, 50, 255]);
750 assert_eq!(&fg2_img.rgba[..4], &[50, 0, 200, 255]);
751
752 let _ = std::fs::remove_dir_all(&dir);
753}
754
755#[cfg(not(target_arch = "wasm32"))]
756#[test]
757fn preload_frame_loaders_decodes_multiple_videos_in_parallel() {
758 let dir = std::env::temp_dir().join(format!("fission_preload_vid_{}", std::process::id()));
759 let _ = std::fs::remove_dir_all(&dir);
760 std::fs::create_dir_all(&dir).unwrap();
761
762 let mk_mp4 = |name: &str, color: &str| {
763 let p = dir.join(name);
764 let ok = Command::new("ffmpeg")
765 .args([
766 "-y",
767 "-v",
768 "error",
769 "-f",
770 "lavfi",
771 "-i",
772 &format!("color=c={color}:size=32x32:rate=24:duration=0.2"),
773 "-c:v",
774 "libx264",
775 "-pix_fmt",
776 "yuv420p",
777 ])
778 .arg(&p)
779 .status()
780 .is_ok_and(|s| s.success());
781 (p, ok)
782 };
783 let (v1, ok1) = mk_mp4("v1.mp4", "red");
784 let (v2, ok2) = mk_mp4("v2.mp4", "blue");
785 if !(ok1 && ok2) {
786 let _ = std::fs::remove_dir_all(&dir);
787 return;
788 }
789
790 let esc = |p: &Path| p.to_string_lossy().replace('\\', "\\\\");
791 let comp_src = format!(
792 r#"Composition {{
793CurrentTime = 0,
794RenderRange = {{ 0, 3 }},
795GlobalRange = {{ 0, 3 }},
796Tools = ordered() {{
797 V1 = Loader {{
798 Clips = {{
799 Clip {{
800 ID = "Clip1",
801 Filename = "{}",
802 FormatID = "QuickTimeMovies",
803 Length = 4,
804 GlobalStart = 0,
805 GlobalEnd = 3,
806 }},
807 }},
808 }},
809 V2 = Loader {{
810 Clips = {{
811 Clip {{
812 ID = "Clip1",
813 Filename = "{}",
814 FormatID = "QuickTimeMovies",
815 Length = 4,
816 GlobalStart = 0,
817 GlobalEnd = 3,
818 }},
819 }},
820 }},
821 M = Merge {{
822 Inputs = {{
823 Background = Input {{ SourceOp = "V1", Source = "Output", }},
824 Foreground = Input {{ SourceOp = "V2", Source = "Output", }},
825 }},
826 }},
827}},
828}}"#,
829 esc(&v1),
830 esc(&v2),
831 );
832 let comp = Comp::from_fusion_str(&comp_src).expect("parse video preload comp");
833 let target = comp.find_node("M").expect("M");
834 let expr = model::ExprEngine::new();
835 let mut cache = MediaCache::new(64);
836
837 cache.preload_frame_loaders(&comp, target, 0.0, &expr);
838 assert_eq!(cache.video_decoder_count(), 2);
839 assert_eq!(cache.entry_count(), 2);
840
841 let c1 = comp.node(comp.find_node("V1").unwrap()).clips[0].clone();
842 let c2 = comp.node(comp.find_node("V2").unwrap()).clips[0].clone();
843 let (_, _, img1, disk1) = cache.load_clip(&c1, 0, false, [None; 4]).unwrap();
844 let (_, _, img2, disk2) = cache.load_clip(&c2, 0, false, [None; 4]).unwrap();
845 assert!(!disk1);
846 assert!(!disk2);
847 assert!(img1.rgba[0] > 200 && img1.rgba[2] < 40);
848 assert!(img2.rgba[2] > 200 && img2.rgba[0] < 40);
849
850 cache.prefetch_frames(&comp, target, &[1.0, 2.0], &expr);
851 assert_eq!(cache.entry_count(), 6);
852
853 let _ = std::fs::remove_dir_all(&dir);
854}
855
856#[cfg(not(target_arch = "wasm32"))]
857#[test]
858fn background_frame_prefetch_populates_and_cancels_cleanly() {
859 let dir = std::env::temp_dir().join(format!("fission_bg_prefetch_{}", std::process::id()));
860 let _ = std::fs::remove_dir_all(&dir);
861 std::fs::create_dir_all(&dir).unwrap();
862
863 for i in 0..4 {
864 let p = dir.join(format!("seq_{i:04}.png"));
865 image::RgbaImage::from_pixel(4, 4, image::Rgba([i as u8 * 50, 10, 200, 255]))
866 .save(&p)
867 .unwrap();
868 }
869 let esc = |p: &Path| p.to_string_lossy().replace('\\', "\\\\");
870 let p0 = dir.join("seq_0000.png");
871 let comp_src = format!(
872 r#"Composition {{
873CurrentTime = 0,
874RenderRange = {{ 0, 3 }},
875GlobalRange = {{ 0, 3 }},
876Tools = ordered() {{
877 LD = Loader {{
878 Clips = {{
879 Clip {{
880 ID = "Clip1",
881 Filename = "{}",
882 FormatID = "PNGFormat",
883 StartFrame = 0,
884 Length = 4,
885 GlobalStart = 0,
886 GlobalEnd = 3,
887 }},
888 }},
889 }},
890}},
891}}"#,
892 esc(&p0)
893 );
894 let comp = Comp::from_fusion_str(&comp_src).expect("parse bg prefetch comp");
895 let target = comp.find_node("LD").unwrap();
896 let clip = comp.node(target).clips[0].clone();
897 let expr = model::ExprEngine::new();
898 let mut cache = MediaCache::new(64);
899
900 let mut handle = cache.start_frame_prefetch(4);
901 for f in 0..=3 {
902 handle.enqueue_frame(&comp, target, f, f as f64, &expr, false);
903 }
904 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
905 while cache.entry_count() < 4 && std::time::Instant::now() < deadline {
906 std::thread::sleep(std::time::Duration::from_millis(5));
907 }
908 assert_eq!(cache.entry_count(), 4);
909 for f in 0..=3 {
910 let (_, _, img, from_disk) = cache.load_clip(&clip, f, false, [None; 4]).unwrap();
911 assert!(!from_disk, "frame {f} should already be in MediaCache");
912 assert_eq!(img.rgba[0], (f as u8) * 50);
913 }
914 handle.cancel();
915 drop(handle);
916
917 let _ = std::fs::remove_dir_all(&dir);
918}
919
920#[cfg(not(target_arch = "wasm32"))]
921#[test]
922fn failed_opens_are_not_cached_and_evict_known_existing_paths() {
923 let dir = std::env::temp_dir().join(format!("fission_evict_test_{}", std::process::id()));
924 let _ = std::fs::remove_dir_all(&dir);
925 std::fs::create_dir_all(&dir).unwrap();
926
927 let bad_vid = dir.join("corrupt.mp4");
928 std::fs::write(&bad_vid, b"not a valid mp4").unwrap();
929 let mut cache = MediaCache::new(64);
930 assert!(cache.shared.path_exists_cached(&bad_vid));
931 assert!(cache.shared.get_or_open_video_decoder(&bad_vid).is_none());
932 assert_eq!(cache.video_decoder_count(), 0);
933 assert!(!cache.shared.state.lock().unwrap().known_existing_paths.contains(&bad_vid));
934
935 let img_path = dir.join("gone.png");
936 image::RgbaImage::from_pixel(2, 2, image::Rgba([10, 20, 30, 255]))
937 .save(&img_path)
938 .unwrap();
939 assert!(cache.shared.path_exists_cached(&img_path));
940 std::fs::remove_file(&img_path).unwrap();
941 let clip = ClipSpec {
942 filename: img_path.to_string_lossy().into_owned(),
943 alternate_filename: None,
944 start_frame: 0,
945 length: Some(1),
946 trim_in: 0,
947 trim_out: 0,
948 global_start: 0,
949 global_end: 0,
950 extend_first: 0,
951 extend_last: 0,
952 loop_clip: false,
953 reverse: false,
954 };
955 assert!(cache.load_clip(&clip, 0, false, [None; 4]).is_none());
956 assert!(!cache.shared.path_exists_cached(&img_path));
957
958 let _ = std::fs::remove_dir_all(&dir);
959}
960
961#[cfg(not(target_arch = "wasm32"))]
962#[test]
963fn prefetch_queue_prunes_stale_and_avoids_hol_blocking() {
964 let dir = std::env::temp_dir().join(format!("fission_hol_prefetch_{}", std::process::id()));
965 let _ = std::fs::remove_dir_all(&dir);
966 std::fs::create_dir_all(&dir).unwrap();
967
968 for i in 0..=10 {
969 let p = dir.join(format!("seq_{i:04}.png"));
970 image::RgbaImage::from_pixel(2, 2, image::Rgba([i as u8 * 20, 10, 200, 255]))
971 .save(&p)
972 .unwrap();
973 }
974 let esc = |p: &Path| p.to_string_lossy().replace('\\', "\\\\");
975 let p0 = dir.join("seq_0000.png");
976 let comp_src = format!(
977 r#"Composition {{
978CurrentTime = 0,
979RenderRange = {{ 0, 10 }},
980GlobalRange = {{ 0, 10 }},
981Tools = ordered() {{
982 LD = Loader {{
983 Clips = {{
984 Clip {{
985 ID = "Clip1",
986 Filename = "{}",
987 FormatID = "PNGFormat",
988 StartFrame = 0,
989 Length = 11,
990 GlobalStart = 0,
991 GlobalEnd = 10,
992 }},
993 }},
994 }},
995}},
996}}"#,
997 esc(&p0)
998 );
999 let comp = Comp::from_fusion_str(&comp_src).expect("parse hol prefetch comp");
1000 let target = comp.find_node("LD").unwrap();
1001 let clip = comp.node(target).clips[0].clone();
1002 let expr = model::ExprEngine::new();
1003 let mut cache = MediaCache::new(64);
1004
1005 let mut handle = cache.start_frame_prefetch(2);
1006 // Enqueue far-future seq=10 first (outside lookahead=2), then seq=1 (within lookahead).
1007 handle.enqueue_frame(&comp, target, 10, 10.0, &expr, false);
1008 handle.enqueue_frame(&comp, target, 1, 1.0, &expr, false);
1009
1010 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
1011 while cache.entry_count() < 1 && std::time::Instant::now() < deadline {
1012 std::thread::sleep(std::time::Duration::from_millis(5));
1013 }
1014 assert_eq!(cache.entry_count(), 1);
1015 let (_, _, img1, from_disk1) = cache.load_clip(&clip, 1, false, [None; 4]).unwrap();
1016 assert!(!from_disk1, "seq=1 must not be head-of-line blocked by seq=10");
1017 assert_eq!(img1.rgba[0], 20);
1018
1019 // Advancing current_seq past 10 prunes seq=10 cleanly.
1020 handle.set_current_seq(11);
1021 {
1022 let q = handle.queue.state.lock().unwrap();
1023 assert!(q.raster.is_empty());
1024 assert!(q.queued_raster_keys.is_empty());
1025 }
1026 handle.cancel();
1027 let _ = std::fs::remove_dir_all(&dir);
1028}
1029
1030#[cfg(not(target_arch = "wasm32"))]
1031#[test]
1032fn prefetch_handle_scales_and_decodes_nine_videos_concurrently() {
1033 let dir = std::env::temp_dir().join(format!("fission_9vid_prefetch_{}", std::process::id()));
1034 let _ = std::fs::remove_dir_all(&dir);
1035 std::fs::create_dir_all(&dir).unwrap();
1036
1037 let v0 = dir.join("v0.mp4");
1038 let ok = Command::new("ffmpeg")
1039 .args([
1040 "-y",
1041 "-v",
1042 "error",
1043 "-f",
1044 "lavfi",
1045 "-i",
1046 "color=c=green:size=16x16:rate=24:duration=0.15",
1047 "-c:v",
1048 "libx264",
1049 "-pix_fmt",
1050 "yuv420p",
1051 ])
1052 .arg(&v0)
1053 .status()
1054 .is_ok_and(|s| s.success());
1055 if !ok {
1056 let _ = std::fs::remove_dir_all(&dir);
1057 return;
1058 }
1059
1060 let esc = |p: &Path| p.to_string_lossy().replace('\\', "\\\\");
1061 let mut tools = String::new();
1062 for i in 0..9 {
1063 let vi = dir.join(format!("v{i}.mp4"));
1064 if i > 0 {
1065 std::fs::copy(&v0, &vi).unwrap();
1066 }
1067 tools.push_str(&format!(
1068 r#" V{i} = Loader {{
1069 Clips = {{
1070 Clip {{
1071 ID = "Clip1",
1072 Filename = "{}",
1073 FormatID = "QuickTimeMovies",
1074 Length = 3,
1075 GlobalStart = 0,
1076 GlobalEnd = 2,
1077 }},
1078 }},
1079 }},
1080"#,
1081 esc(&vi)
1082 ));
1083 }
1084 let mut prev = "V0".to_owned();
1085 for i in 1..9 {
1086 let mname = format!("M{i}");
1087 tools.push_str(&format!(
1088 r#" {mname} = Merge {{
1089 Inputs = {{
1090 Background = Input {{ SourceOp = "{prev}", Source = "Output", }},
1091 Foreground = Input {{ SourceOp = "V{i}", Source = "Output", }},
1092 }},
1093 }},
1094"#
1095 ));
1096 prev = mname;
1097 }
1098 let comp_src = format!(
1099 "Composition {{\n CurrentTime = 0,\n RenderRange = {{ 0, 2 }},\n GlobalRange = {{ 0, 2 }},\n Tools = ordered() {{\n{tools} }},\n}}"
1100 );
1101 let comp = Comp::from_fusion_str(&comp_src).expect("parse 9-video comp");
1102 let target = comp.find_node("M8").expect("M8");
1103 let expr = model::ExprEngine::new();
1104 let cache = MediaCache::new(64);
1105
1106 let mut handle = cache.start_frame_prefetch(4);
1107 let expected_workers = std::thread::available_parallelism()
1108 .map(|n| n.get().clamp(2, 12))
1109 .unwrap_or(4);
1110 assert_eq!(handle.workers.len(), expected_workers);
1111
1112 handle.enqueue_frame(&comp, target, 0, 0.0, &expr, false);
1113 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
1114 while cache.entry_count() < 9 && std::time::Instant::now() < deadline {
1115 std::thread::sleep(std::time::Duration::from_millis(5));
1116 }
1117 assert_eq!(cache.video_decoder_count(), 9);
1118 assert_eq!(cache.entry_count(), 9);
1119 handle.cancel();
1120 let _ = std::fs::remove_dir_all(&dir);
1121}
1122
1123#[cfg(not(target_arch = "wasm32"))]
1124#[test]
1125fn warm_cache_over_75_percent_keeps_full_lookahead() {
1126 let dir = std::env::temp_dir().join(format!("fission_warm_lookahead_{}", std::process::id()));
1127 let _ = std::fs::remove_dir_all(&dir);
1128 std::fs::create_dir_all(&dir).unwrap();
1129
1130 for i in 0..=4 {
1131 let p = dir.join(format!("seq_{i:04}.png"));
1132 image::RgbaImage::from_pixel(512, 512, image::Rgba([i as u8 * 40, 20, 180, 255]))
1133 .save(&p)
1134 .unwrap();
1135 }
1136 let esc = |p: &Path| p.to_string_lossy().replace('\\', "\\\\");
1137 let p0 = dir.join("seq_0000.png");
1138 let comp_src = format!(
1139 r#"Composition {{
1140CurrentTime = 0,
1141RenderRange = {{ 0, 4 }},
1142GlobalRange = {{ 0, 4 }},
1143Tools = ordered() {{
1144 LD = Loader {{
1145 Clips = {{
1146 Clip {{
1147 ID = "Clip1",
1148 Filename = "{}",
1149 FormatID = "PNGFormat",
1150 StartFrame = 0,
1151 Length = 5,
1152 GlobalStart = 0,
1153 GlobalEnd = 4,
1154 }},
1155 }},
1156 }},
1157}},
1158}}"#,
1159 esc(&p0)
1160 );
1161 let comp = Comp::from_fusion_str(&comp_src).expect("parse warm lookahead comp");
1162 let target = comp.find_node("LD").unwrap();
1163 let clip = comp.node(target).clips[0].clone();
1164 let expr = model::ExprEngine::new();
1165 let mut cache = MediaCache::new(64);
1166
1167 // Warm the cache past 75% of its 64 MiB budget (13 x 4 MiB = 52 MiB = 81.25%).
1168 let four_mb = Arc::new(vec![128u8; 1024 * 1024 * 4]);
1169 {
1170 let mut state = cache.shared.state.lock().unwrap();
1171 for i in 0..13 {
1172 let key = ImageCacheKey {
1173 path: dir.join(format!("warm_{i:04}.png")),
1174 frame_idx: -1,
1175 post_multiply: false,
1176 exr_channels: [None, None, None, None],
1177 };
1178 let img = DecodedImage {
1179 size: [1024, 1024],
1180 rgba: Arc::clone(&four_mb),
1181 rgba_f16: None,
1182 rgba_f32: None,
1183 z_f32: None,
1184 };
1185 cache.shared.insert_cached_locked(&mut state, key, img);
1186 }
1187 }
1188 assert!(
1189 cache.total_mb() > 48.0,
1190 "cache must be >75% of 64 MiB, got {:.2} MiB",
1191 cache.total_mb()
1192 );
1193
1194 let mut handle = cache.start_frame_prefetch(4);
1195 handle.set_current_seq(0);
1196 for seq in 1..=4 {
1197 handle.enqueue_frame(&comp, target, seq, seq as f64, &expr, false);
1198 }
1199
1200 // All 4 lookahead frames (through current_seq + 4) must be prefetched without collapsing
1201 // to current_seq + 1.
1202 let expected_keys: Vec<ImageCacheKey> = (1..=4)
1203 .map(|i| ImageCacheKey {
1204 path: dir.join(format!("seq_{i:04}.png")),
1205 frame_idx: -1,
1206 post_multiply: false,
1207 exr_channels: [None, None, None, None],
1208 })
1209 .collect();
1210 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
1211 loop {
1212 let all_cached = cache
1213 .shared
1214 .state
1215 .lock()
1216 .map(|s| expected_keys.iter().all(|k| s.images.contains_key(k)))
1217 .unwrap_or(false);
1218 if all_cached || std::time::Instant::now() >= deadline {
1219 break;
1220 }
1221 std::thread::sleep(std::time::Duration::from_millis(5));
1222 }
1223
1224 for i in 1..=4 {
1225 let (_, _, img, from_disk) = cache.load_clip(&clip, i, false, [None; 4]).unwrap();
1226 assert!(
1227 !from_disk,
1228 "frame {i} (current_seq + {i}) should have been prefetched while >75% warm"
1229 );
1230 assert_eq!(img.rgba[0], (i as u8) * 40);
1231 }
1232
1233 handle.cancel();
1234 let _ = std::fs::remove_dir_all(&dir);
1235}
1236
1237#[test]
1238fn direct_png_decode_matches_image_crate_bit_for_bit_all_color_types() {
1239 fn encode_png(
1240 w: u32,
1241 h: u32,
1242 color: png::ColorType,
1243 depth: png::BitDepth,
1244 palette: Option<&[u8]>,
1245 trns: Option<&[u8]>,
1246 data: &[u8],
1247 ) -> Vec<u8> {
1248 let mut out = Vec::new();
1249 {
1250 let mut enc = png::Encoder::new(&mut out, w, h);
1251 enc.set_color(color);
1252 enc.set_depth(depth);
1253 if let Some(p) = palette {
1254 enc.set_palette(p);
1255 }
1256 if let Some(t) = trns {
1257 enc.set_trns(t);
1258 }
1259 let mut writer = enc.write_header().unwrap();
1260 writer.write_image_data(data).unwrap();
1261 }
1262 out
1263 }
1264
1265 let (w, h) = (17u32, 11u32);
1266 let n = (w * h) as usize;
1267 let cases: Vec<(&str, Vec<u8>)> = vec![
1268 (
1269 "rgba8",
1270 encode_png(
1271 w,
1272 h,
1273 png::ColorType::Rgba,
1274 png::BitDepth::Eight,
1275 None,
1276 None,
1277 &(0..n * 4).map(|i| ((i * 37 + 13) % 256) as u8).collect::<Vec<_>>(),
1278 ),
1279 ),
1280 (
1281 "rgb8",
1282 encode_png(
1283 w,
1284 h,
1285 png::ColorType::Rgb,
1286 png::BitDepth::Eight,
1287 None,
1288 None,
1289 &(0..n * 3).map(|i| ((i * 53 + 7) % 256) as u8).collect::<Vec<_>>(),
1290 ),
1291 ),
1292 (
1293 "gray8",
1294 encode_png(
1295 w,
1296 h,
1297 png::ColorType::Grayscale,
1298 png::BitDepth::Eight,
1299 None,
1300 None,
1301 &(0..n).map(|i| ((i * 29 + 3) % 256) as u8).collect::<Vec<_>>(),
1302 ),
1303 ),
1304 (
1305 "gray_alpha8",
1306 encode_png(
1307 w,
1308 h,
1309 png::ColorType::GrayscaleAlpha,
1310 png::BitDepth::Eight,
1311 None,
1312 None,
1313 &(0..n * 2).map(|i| ((i * 41 + 19) % 256) as u8).collect::<Vec<_>>(),
1314 ),
1315 ),
1316 (
1317 "palette_trns",
1318 encode_png(
1319 w,
1320 h,
1321 png::ColorType::Indexed,
1322 png::BitDepth::Eight,
1323 Some(&[10, 20, 30, 200, 150, 50, 0, 255, 128, 255, 255, 255]),
1324 Some(&[0, 128, 255]),
1325 &(0..n).map(|i| (i % 4) as u8).collect::<Vec<_>>(),
1326 ),
1327 ),
1328 (
1329 "palette_opaque",
1330 encode_png(
1331 w,
1332 h,
1333 png::ColorType::Indexed,
1334 png::BitDepth::Eight,
1335 Some(&[10, 20, 30, 200, 150, 50, 0, 255, 128]),
1336 None,
1337 &(0..n).map(|i| (i % 3) as u8).collect::<Vec<_>>(),
1338 ),
1339 ),
1340 (
1341 "rgba16",
1342 encode_png(
1343 w,
1344 h,
1345 png::ColorType::Rgba,
1346 png::BitDepth::Sixteen,
1347 None,
1348 None,
1349 // Include boundary values like 0x01ff (511 -> rounds to 2, not 1).
1350 &(0..n * 4)
1351 .flat_map(|i| (((i * 1021 + 255) % 65536) as u16).to_be_bytes())
1352 .collect::<Vec<_>>(),
1353 ),
1354 ),
1355 (
1356 "rgb16",
1357 encode_png(
1358 w,
1359 h,
1360 png::ColorType::Rgb,
1361 png::BitDepth::Sixteen,
1362 None,
1363 None,
1364 &(0..n * 3)
1365 .flat_map(|i| (((i * 997 + 511) % 65536) as u16).to_be_bytes())
1366 .collect::<Vec<_>>(),
1367 ),
1368 ),
1369 (
1370 "gray16",
1371 encode_png(
1372 w,
1373 h,
1374 png::ColorType::Grayscale,
1375 png::BitDepth::Sixteen,
1376 None,
1377 None,
1378 &(0..n)
1379 .flat_map(|i| (((i * 773 + 128) % 65536) as u16).to_be_bytes())
1380 .collect::<Vec<_>>(),
1381 ),
1382 ),
1383 (
1384 "gray_alpha16",
1385 encode_png(
1386 w,
1387 h,
1388 png::ColorType::GrayscaleAlpha,
1389 png::BitDepth::Sixteen,
1390 None,
1391 None,
1392 &(0..n * 2)
1393 .flat_map(|i| (((i * 613 + 384) % 65536) as u16).to_be_bytes())
1394 .collect::<Vec<_>>(),
1395 ),
1396 ),
1397 ];
1398
1399 for (label, bytes) in cases {
1400 let dyn_img = image::load_from_memory(&bytes).expect("image crate decode");
1401 let expected_has_alpha = dyn_img.color().has_alpha();
1402 let expected_size = [dyn_img.width(), dyn_img.height()];
1403 let expected_rgba = dyn_img.into_rgba8().into_raw();
1404
1405 let (got_size, got_rgba, got_has_alpha) = match decode_png_bytes(&bytes) {
1406 PngDecodeOutcome::Decoded(v) => v,
1407 PngDecodeOutcome::Fallback | PngDecodeOutcome::Reject => {
1408 panic!("direct decode failed for {label}")
1409 }
1410 };
1411 assert_eq!(got_size, expected_size, "size mismatch for {label}");
1412 assert_eq!(got_has_alpha, expected_has_alpha, "alpha flag mismatch for {label}");
1413 assert_eq!(got_rgba, expected_rgba, "pixel mismatch for {label}");
1414 }
1415}
1416
1417#[test]
1418fn reject_spoofed_oversized_png_ihdr_without_allocating() {
1419 fn png_crc32(data: &[u8]) -> u32 {
1420 let mut crc = 0xFFFF_FFFFu32;
1421 for &b in data {
1422 crc ^= b as u32;
1423 for _ in 0..8 {
1424 let mask = (crc & 1).wrapping_neg();
1425 crc = (crc >> 1) ^ (0xEDB8_8320 & mask);
1426 }
1427 }
1428 !crc
1429 }
1430
1431 fn push_chunk(out: &mut Vec<u8>, chunk_type: &[u8; 4], payload: &[u8]) {
1432 out.extend_from_slice(&(payload.len() as u32).to_be_bytes());
1433 let crc_start = out.len();
1434 out.extend_from_slice(chunk_type);
1435 out.extend_from_slice(payload);
1436 let crc = png_crc32(&out[crc_start..]);
1437 out.extend_from_slice(&crc.to_be_bytes());
1438 }
1439
1440 let mut crafted = vec![137, 80, 78, 71, 13, 10, 26, 10];
1441 let mut ihdr = [0u8; 13];
1442 ihdr[0..4].copy_from_slice(&16u32.to_be_bytes());
1443 ihdr[4..8].copy_from_slice(&1_000_000_000u32.to_be_bytes());
1444 ihdr[8] = 8; // bit depth
1445 ihdr[9] = 6; // RGBA
1446 push_chunk(&mut crafted, b"IHDR", &ihdr);
1447 push_chunk(&mut crafted, b"IDAT", &[0x78, 0x9c, 0x03, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00]);
1448 push_chunk(&mut crafted, b"IEND", &[]);
1449 assert_eq!(crafted.len(), 67);
1450
1451 assert!(matches!(decode_png_bytes(&crafted), PngDecodeOutcome::Reject));
1452 assert!(decode_raster_bytes(&crafted).is_none());
1453}