1//! Boundary-hardening regression tests for `crates/engine`.
2//!
3//! Each test covers a real crash, stack overflow, integer overflow, runaway allocation,
4//! or `wgpu` validation error fixed at its architectural boundary.
5
6use engine::audio::AudioTrack;
7use engine::cryptomatte::extract_cryptomatte;
8use engine::export::{
9 ExportControl, ExportOptions, VideoCodec, VideoExportOptions, export_node_video_ffmpeg_with_progress,
10 export_saver_png_sequence_with_progress,
11};
12use engine::media::{MediaCache, rasterize_polyline_mask};
13use engine::ram_cache::{PrefetchJob, RamFrame, RamFrameCache, RamFrameKey, RamPrefetcher};
14use engine::Engine;
15use model::{ClipSpec, Comp, NodeId, PolyPoint};
16use std::path::PathBuf;
17use std::sync::Arc;
18use std::time::{Duration, Instant};
19
20fn eval_checked(eng: &mut Engine, comp: &Comp, target: NodeId, time: f64) -> [u32; 2] {
21 let scope = eng.device().push_error_scope(wgpu::ErrorFilter::Validation);
22 let (tex, _) = eng.evaluate(comp, target, time);
23 if let Some(err) = pollster::block_on(scope.pop()) {
24 panic!("wgpu validation error evaluating {target:?} @ {time}: {err}");
25 }
26 assert!(tex.size[0] >= 1 && tex.size[1] >= 1);
27 tex.size
28}
29
30fn make_clip(filename: String) -> ClipSpec {
31 ClipSpec {
32 filename,
33 alternate_filename: None,
34 start_frame: 0,
35 length: Some(1),
36 trim_in: 0,
37 trim_out: 0,
38 global_start: 0,
39 global_end: 0,
40 extend_first: 0,
41 extend_last: 0,
42 loop_clip: false,
43 reverse: false,
44 }
45}
46
47#[test]
48fn eval_entry_time_shifting_cycles_dangling_id_zero_dims_and_non_finite_time() {
49 let Ok(mut eng) = Engine::new_headless() else { return };
50
51 // Time-shifting self-cycles in TimeSpeed (Delay = 1) and TimeStretcher (SourceTime = time + 1)
52 // must hit MAX_EVAL_DEPTH / MAX_PRELOAD_DEPTH cleanly instead of blowing the Rust stack.
53 let cycle_comp = Comp::from_fusion_str(
54 r#"Composition {
55 CurrentTime = 0,
56 RenderRange = { 0, 10 },
57 GlobalRange = { 0, 10 },
58 Tools = ordered() {
59 TS = TimeSpeed {
60 Inputs = {
61 Input = Input { SourceOp = "TS", Source = "Output", },
62 Delay = Input { Value = 1, },
63 Speed = Input { Value = 0.5, },
64 },
65 },
66 TSt = TimeStretcher {
67 Inputs = {
68 Input = Input { SourceOp = "TSt", Source = "Output", },
69 SourceTime = Input { Expression = "time + 1", },
70 },
71 },
72 BG = Background { },
73 },
74 }"#,
75 )
76 .unwrap();
77
78 for name in ["TS", "TSt"] {
79 let id = cycle_comp.find_node(name).unwrap();
80 eval_checked(&mut eng, &cycle_comp, id, 0.0);
81 }
82
83 // Dangling NodeId must return cleanly without panicking on comp.node(id).
84 eval_checked(&mut eng, &cycle_comp, NodeId(9999), 0.0);
85
86 // proxy_scale == 0 and 0x0 comp dimensions with a node inheriting comp dimensions.
87 let mut zero_comp = cycle_comp.clone();
88 zero_comp.width = 0;
89 zero_comp.height = 0;
90 eng.proxy_scale = 0;
91 let bg = zero_comp.find_node("BG").unwrap();
92 eval_checked(&mut eng, &zero_comp, bg, 0.0);
93 eng.proxy_scale = 1;
94
95 // Non-finite and extreme frames.
96 for t in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 1e20, -1e20] {
97 eval_checked(&mut eng, &cycle_comp, bg, t);
98 }
99}
100
101#[test]
102fn text_paint_and_mask_boundaries_have_no_panics_ooms_or_validation_errors() {
103 let Ok(mut eng) = Engine::new_headless() else { return };
104 let max_dim = eng.device().limits().max_texture_dimension_2d.max(1);
105 let over_dim = max_dim.saturating_add(4096);
106
107 let src = format!(
108 r#"Composition {{ Tools = ordered() {{
109 BG = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, }}, }},
110 T_Empty = TextPlus {{ Inputs = {{ StyledText = Input {{ Value = "", }}, Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, }}, }},
111 T_Zero = TextPlus {{ Inputs = {{ StyledText = Input {{ Value = "Hi", }}, Size = Input {{ Value = 0, }}, Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, }}, }},
112 T_Neg = TextPlus {{ Inputs = {{ StyledText = Input {{ Value = "Hi", }}, Size = Input {{ Value = -1, }}, Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, }}, }},
113 T_NaN = TextPlus {{ Inputs = {{ StyledText = Input {{ Value = "Hi", }}, Size = Input {{ Expression = "0/0", }}, Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, }}, }},
114 T_NoFont = TextPlus {{ Inputs = {{ StyledText = Input {{ Value = "Hi", }}, Font = Input {{ Value = "NoSuchFontXYZ_9999", }}, Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, }}, }},
115 T_BorderInf = TextPlus {{ Inputs = {{ StyledText = Input {{ Value = "A", }}, Size = Input {{ Expression = "1/0", }}, Enabled2 = Input {{ Value = 1, }}, ElementShape2 = Input {{ Value = 2, }}, Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, }}, }},
116 T3D_Empty = Text3D {{ Inputs = {{ StyledText = Input {{ Value = "", }}, }}, }},
117 T3D_NaN = Text3D {{ Inputs = {{ StyledText = Input {{ Value = "Hi", }}, Size = Input {{ Expression = "0/0", }}, }}, }},
118 Cam = Camera3D {{ Inputs = {{ ["Transform3DOp.Translate.Z"] = Input {{ Value = 5, }}, }}, }},
119 M3D = Merge3D {{ Inputs = {{
120 SceneInput1 = Input {{ SourceOp = "T3D_Empty", Source = "Output", }},
121 SceneInput2 = Input {{ SourceOp = "T3D_NaN", Source = "Output", }},
122 SceneInput3 = Input {{ SourceOp = "Cam", Source = "Output", }},
123 }}, }},
124 R3D = Renderer3D {{ Inputs = {{ SceneInput = Input {{ SourceOp = "M3D", Source = "Output", }}, Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, }}, }},
125
126 S0 = PolylineStroke {{ Inputs = {{ ["CircleBrush.Size"] = Input {{ Value = 0.1, }}, Polyline = Input {{ Value = Polyline {{ Points = {{ }}, }}, }}, }}, }},
127 S1 = PolylineStroke {{ Inputs = {{ ["CircleBrush.Size"] = Input {{ Value = 0.1, }}, Polyline = Input {{ Value = Polyline {{ Points = {{ {{ X = 0.0, Y = 0.0, Linear = true }}, }}, }}, }}, }}, }},
128 SHuge = PolylineStroke {{ Inputs = {{ ["CircleBrush.Size"] = Input {{ Value = 0.001, }}, Spacing = Input {{ Value = 0.001, }}, Polyline = Input {{ Value = Polyline {{ Points = {{ {{ X = 0.0, Y = 0.0, Linear = true }}, {{ X = 1e12, Y = 0.0, Linear = true }}, }}, }}, }}, }}, }},
129 P0 = Paint {{ Inputs = {{ Input = Input {{ SourceOp = "BG", Source = "Output", }}, Paint = Input {{ SourceOp = "S0", Source = "Out", }}, }}, }},
130 P1 = Paint {{ Inputs = {{ Input = Input {{ SourceOp = "BG", Source = "Output", }}, Paint = Input {{ SourceOp = "S1", Source = "Out", }}, }}, }},
131 PHuge = Paint {{ Inputs = {{ Input = Input {{ SourceOp = "BG", Source = "Output", }}, Paint = Input {{ SourceOp = "SHuge", Source = "Out", }}, }}, }},
132 PMBig = PaintMask {{ Inputs = {{ MaskWidth = Input {{ Value = {over_dim}, }}, MaskHeight = Input {{ Value = 64, }}, Paint = Input {{ SourceOp = "S1", Source = "Out", }}, }}, }},
133 Poly0 = PolylineMask {{ Inputs = {{ MaskWidth = Input {{ Value = 64, }}, MaskHeight = Input {{ Value = 64, }}, }}, }},
134 BS0 = BSplineMask {{ Inputs = {{ MaskWidth = Input {{ Value = 64, }}, MaskHeight = Input {{ Value = 64, }}, }}, }},
135 }}, }}"#
136 );
137 let comp = Comp::from_fusion_str(&src).unwrap();
138 for name in [
139 "T_Empty", "T_Zero", "T_Neg", "T_NaN", "T_NoFont", "T_BorderInf", "R3D",
140 "P0", "P1", "PHuge", "PMBig", "Poly0", "BS0",
141 ] {
142 let id = comp.find_node(name).unwrap();
143 let sz = eval_checked(&mut eng, &comp, id, 0.0);
144 if name == "PMBig" {
145 assert!(sz[0] <= max_dim && sz[1] <= max_dim);
146 }
147 }
148
149 // Direct polyline mask rasterizer with NaN/Inf coords and angle.
150 let pts = [
151 PolyPoint { x: f64::NAN, y: 0.0, lx: 0.0, ly: 0.0, rx: 0.0, ry: 0.0, linear: true },
152 PolyPoint { x: f64::INFINITY, y: 0.5, lx: 0.0, ly: 0.0, rx: 0.0, ry: 0.0, linear: true },
153 PolyPoint { x: 0.2, y: 0.2, lx: 0.0, ly: 0.0, rx: 0.0, ry: 0.0, linear: true },
154 ];
155 let buf = rasterize_polyline_mask([32, 32], &pts, [0.5, 0.5], f32::NAN, false, 1.0);
156 assert_eq!(buf.len(), 32 * 32 * 4);
157}
158
159#[test]
160fn scene3d_duplicate_overflow_and_chained_blowup_and_particles_extreme_frames() {
161 let Ok(mut eng) = Engine::new_headless() else { return };
162
163 let dir = std::env::temp_dir().join(format!("fission-hardening-fbx-{}", std::process::id()));
164 let _ = std::fs::create_dir_all(&dir);
165 let bad_fbx = dir.join("corrupt.fbx");
166 let mut fbx = b"Kaydara FBX Binary \0\x1a\x00".to_vec();
167 fbx.extend_from_slice(&7500u32.to_le_bytes());
168 fbx.extend_from_slice(&[0xFF; 64]);
169 std::fs::write(&bad_fbx, &fbx).unwrap();
170 let fbx_esc = bad_fbx.to_string_lossy().replace('\\', "\\\\");
171
172 let src = format!(
173 r#"Composition {{
174 CurrentTime = 0,
175 RenderRange = {{ 0, 10 }},
176 GlobalRange = {{ 0, 10 }},
177 Tools = ordered() {{
178 Empty3D = Merge3D {{ }},
179 REmpty = Renderer3D {{ Inputs = {{ SceneInput = Input {{ SourceOp = "Empty3D", Source = "Output", }}, Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, }}, }},
180
181 Cube = Cube3D {{ Inputs = {{ ["SurfaceCubeInputs.Width"] = Input {{ Value = 0, }}, }}, }},
182 DupOverflow = Duplicate3D {{ Inputs = {{ SceneInput = Input {{ SourceOp = "Cube", Source = "Output", }}, FirstCopy = Input {{ Value = -2147483648, }}, LastCopy = Input {{ Value = 1, }}, }}, }},
183 DupHugeFirst = Duplicate3D {{ Inputs = {{ SceneInput = Input {{ SourceOp = "Cube", Source = "Output", }}, FirstCopy = Input {{ Value = 1000000000, }}, LastCopy = Input {{ Value = 1000000002, }}, }}, }},
184 DupA = Duplicate3D {{ Inputs = {{ SceneInput = Input {{ SourceOp = "Cube", Source = "Output", }}, FirstCopy = Input {{ Value = 0, }}, LastCopy = Input {{ Value = 128, }}, }}, }},
185 DupB = Duplicate3D {{ Inputs = {{ SceneInput = Input {{ SourceOp = "DupA", Source = "Output", }}, FirstCopy = Input {{ Value = 0, }}, LastCopy = Input {{ Value = 128, }}, }}, }},
186 DupC = Duplicate3D {{ Inputs = {{ SceneInput = Input {{ SourceOp = "DupB", Source = "Output", }}, FirstCopy = Input {{ Value = 0, }}, LastCopy = Input {{ Value = 128, }}, }}, }},
187 BadFbx = SurfaceFBXMesh {{ Inputs = {{ ImportFile = Input {{ Value = "{fbx_esc}", }}, }}, }},
188 CamBad = Camera3D {{ Inputs = {{ FLength = Input {{ Expression = "0/0", }}, NearClip = Input {{ Expression = "0/0", }}, FarClip = Input {{ Value = 1, }}, }}, }},
189 CamGood = Camera3D {{ Inputs = {{ ["Transform3DOp.Translate.Z"] = Input {{ Value = 5, }}, }}, }},
190 M3BadCam = Merge3D {{ Inputs = {{ SceneInput1 = Input {{ SourceOp = "CamBad", Source = "Output", }}, SceneInput2 = Input {{ SourceOp = "DupOverflow", Source = "Output", }}, }}, }},
191 RBadCam = Renderer3D {{ Inputs = {{ SceneInput = Input {{ SourceOp = "M3BadCam", Source = "Output", }}, Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, }}, }},
192 M3Stress = Merge3D {{ Inputs = {{
193 SceneInput1 = Input {{ SourceOp = "CamGood", Source = "Output", }},
194 SceneInput2 = Input {{ SourceOp = "DupOverflow", Source = "Output", }},
195 SceneInput3 = Input {{ SourceOp = "DupHugeFirst", Source = "Output", }},
196 SceneInput4 = Input {{ SourceOp = "DupC", Source = "Output", }},
197 SceneInput5 = Input {{ SourceOp = "BadFbx", Source = "Output", }},
198 }}, }},
199 RStress = Renderer3D {{ Inputs = {{ SceneInput = Input {{ SourceOp = "M3Stress", Source = "Output", }}, Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, }}, }},
200
201 PE_Many = pEmitter {{ Inputs = {{ Number = Input {{ Value = 1000000, }}, Lifespan = Input {{ Value = 0, }}, ["StyleParticle.Size"] = Input {{ Expression = "0/0", }}, }}, }},
202 PR_Many = pRender {{ Inputs = {{ Input = Input {{ SourceOp = "PE_Many", Source = "Output", }}, Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, }}, }},
203
204 PE_Pre = pEmitter {{ Inputs = {{ Number = Input {{ Value = 5, }}, Lifespan = Input {{ Value = 10, }}, }}, }},
205 PTurb = pTurbulence {{ Inputs = {{ Input = Input {{ SourceOp = "PE_Pre", Source = "Output", }}, XStrength = Input {{ Value = 1e18, }}, }}, }},
206 PR_Pre = pRender {{ Inputs = {{ Input = Input {{ SourceOp = "PTurb", Source = "Output", }}, PreGenerateFrames = Input {{ Value = 100000, }}, Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, }}, }},
207 }},
208 }}"#
209 );
210 let comp = Comp::from_fusion_str(&src).unwrap();
211
212 let t0 = Instant::now();
213 for (name, t) in [
214 ("REmpty", 0.0),
215 ("RBadCam", 0.0),
216 ("RStress", 0.0),
217 ("PR_Many", 0.0),
218 ("PR_Pre", 0.0),
219 ("PR_Pre", 1e9),
220 ("PR_Pre", 1e20),
221 ("PR_Pre", f64::NAN),
222 ("PR_Pre", f64::INFINITY),
223 ("PR_Pre", f64::NEG_INFINITY),
224 ] {
225 let id = comp.find_node(name).unwrap();
226 eval_checked(&mut eng, &comp, id, t);
227 }
228 assert!(
229 t0.elapsed() < Duration::from_secs(5),
230 "3D/Particles stress should stay bounded, took {:?}",
231 t0.elapsed()
232 );
233
234 let _ = std::fs::remove_dir_all(&dir);
235}
236
237#[test]
238fn optflow_custom_and_2d_tool_overflow_and_nan_boundaries() {
239 let Ok(mut eng) = Engine::new_headless() else { return };
240
241 let deep_parens = format!("{}1{}", "(".repeat(200), ")".repeat(200));
242 let deep_unary = format!("{}1", "-".repeat(200));
243 let src = format!(
244 r#"Composition {{
245 CurrentTime = 0,
246 RenderRange = {{ 0, 10 }},
247 GlobalRange = {{ 0, 10 }},
248 Tools = ordered() {{
249 BG1x1 = Background {{ Inputs = {{ Width = Input {{ Value = 1, }}, Height = Input {{ Value = 1, }}, }}, }},
250 OF1 = OpticalFlow {{ Inputs = {{ Input = Input {{ SourceOp = "BG1x1", Source = "Output", }}, }}, }},
251 VMB1 = VectorMotionBlur {{ Inputs = {{ Input = Input {{ SourceOp = "OF1", Source = "Output", }}, }}, }},
252 NaNImg = Custom {{ Inputs = {{
253 Image1 = Input {{ SourceOp = "BG1x1", Source = "Output", }},
254 Depth = Input {{ Value = 4, }},
255 RedExpression = Input {{ Value = "0/0", }},
256 GreenExpression = Input {{ Value = "1/0", }},
257 BlueExpression = Input {{ Value = "-1/0", }},
258 AlphaExpression = Input {{ Value = "0/0", }},
259 }}, }},
260 OFNaN = OpticalFlow {{ Inputs = {{ Input = Input {{ SourceOp = "NaNImg", Source = "Output", }}, }}, }},
261 VMBNaN = VectorMotionBlur {{ Inputs = {{ Input = Input {{ SourceOp = "OFNaN", Source = "Output", }}, }}, }},
262 CustBad = Custom {{ Inputs = {{ Image1 = Input {{ SourceOp = "BG1x1", Source = "Output", }}, RedExpression = Input {{ Value = "1 + * ) ( @@@", }}, }}, }},
263 CustDeep1 = Custom {{ Inputs = {{ Image1 = Input {{ SourceOp = "BG1x1", Source = "Output", }}, RedExpression = Input {{ Value = "{deep_parens}", }}, }}, }},
264 CustDeep2 = Custom {{ Inputs = {{ Image1 = Input {{ SourceOp = "BG1x1", Source = "Output", }}, RedExpression = Input {{ Value = "{deep_unary}", }}, }}, }},
265
266 BG64 = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, }}, }},
267 DB = DirectionalBlur {{ Inputs = {{ Input = Input {{ SourceOp = "BG64", Source = "Output", }}, Length = Input {{ Value = 0.2, }}, ClippingMode = Input {{ Value = FuID {{ "None" }}, }}, }}, }},
268 SetDom = SetDomain {{ Inputs = {{ Input = Input {{ SourceOp = "DB", Source = "Output", }}, Mode = Input {{ Value = FuID {{ "Set" }}, }}, Left = Input {{ Value = -1e12, }}, Right = Input {{ Value = 1e12, }}, }}, }},
269 FilterNoise = Filter {{ Inputs = {{ Input = Input {{ SourceOp = "BG64", Source = "Output", }}, FilterType = Input {{ Value = 5, }}, Animated = Input {{ Value = 1, }}, }}, }},
270 LoaderExtreme = Loader {{
271 Clips = {{ Clip {{ Filename = "/nonexistent/x.png", ExtendFirst = 10, ExtendLast = 10, }}, }},
272 Inputs = {{ GlobalIn = Input {{ Value = -1e20, }}, GlobalOut = Input {{ Value = 1e20, }}, }},
273 }},
274 CropZero = Crop {{ Inputs = {{ Input = Input {{ SourceOp = "BG64", Source = "Output", }}, XSize = Input {{ Value = 0, }}, YSize = Input {{ Value = 0, }}, }}, }},
275 CropHuge = Crop {{ Inputs = {{ Input = Input {{ SourceOp = "BG64", Source = "Output", }}, XSize = Input {{ Value = 100000, }}, YSize = Input {{ Value = 100000, }}, }}, }},
276 ScaleBad = Scale {{ Inputs = {{ Input = Input {{ SourceOp = "BG64", Source = "Output", }}, XSize = Input {{ Value = 0, }}, YSize = Input {{ Value = 100000, }}, }}, }},
277 ResizeBad = BetterResize {{ Inputs = {{ Input = Input {{ SourceOp = "BG64", Source = "Output", }}, Width = Input {{ Value = 0, }}, Height = Input {{ Value = 100000, }}, }}, }},
278 BlurBad = Blur {{ Inputs = {{ Input = Input {{ SourceOp = "BG64", Source = "Output", }}, XBlurSize = Input {{ Value = 100000, }}, YBlurSize = Input {{ Expression = "0/0", }}, }}, }},
279 XfBad = Transform {{ Inputs = {{ Input = Input {{ SourceOp = "BG64", Source = "Output", }}, Size = Input {{ Value = 0, }}, Angle = Input {{ Expression = "0/0", }}, }}, }},
280 MergeBad = Merge {{ Inputs = {{ Background = Input {{ SourceOp = "BG64", Source = "Output", }}, Foreground = Input {{ SourceOp = "BG64", Source = "Output", }}, Size = Input {{ Value = 0, }}, Blend = Input {{ Expression = "0/0", }}, }}, }},
281 GridBad = GridWarp {{ Inputs = {{
282 Input = Input {{ SourceOp = "BG64", Source = "Output", }},
283 SrcGridChange = Input {{ Value = Mesh {{ Columns = 3, Rows = 3, DeltaC = 1, DeltaR = 1, Center = {{ 0, 0 }}, Corners = {{ -0.5, -0.5, 0.5, 0.5 }}, Points = {{ {{ X = 0, Y = 0 }}, }}, }}, }},
284 DstGridChange = Input {{ Value = Mesh {{ Columns = 3, Rows = 3, DeltaC = 1, DeltaR = 1, Center = {{ 0, 0 }}, Corners = {{ -0.5, -0.5, 0.5, 0.5 }}, Points = {{ {{ X = 0, Y = 0 }}, }}, }}, }},
285 }}, }},
286 }},
287 }}"#
288 );
289 let comp = Comp::from_fusion_str(&src).unwrap();
290 for (name, t) in [
291 ("VMB1", 0.0),
292 ("VMBNaN", 0.0),
293 ("CustBad", 0.0),
294 ("CustDeep1", 0.0),
295 ("CustDeep2", 0.0),
296 ("SetDom", 0.0),
297 ("FilterNoise", 1e15),
298 ("LoaderExtreme", 0.0),
299 ("CropZero", 0.0),
300 ("CropHuge", 0.0),
301 ("ScaleBad", 0.0),
302 ("ResizeBad", 0.0),
303 ("BlurBad", 0.0),
304 ("XfBad", 0.0),
305 ("MergeBad", 0.0),
306 ("GridBad", 0.0),
307 ] {
308 let id = comp.find_node(name).unwrap();
309 eval_checked(&mut eng, &comp, id, t);
310 }
311}
312
313#[test]
314fn external_media_exr_huge_header_and_audio_boundaries() {
315 // 1. Audio waveform_peaks: invalid fps/offset, NaN samples, i64::MAX frame, i64 span overflow.
316 let nan_track = AudioTrack {
317 path: PathBuf::from("nan.wav"),
318 sample_rate: 48000,
319 channels: 2,
320 samples: Arc::new(vec![f32::NAN, f32::INFINITY, f32::NEG_INFINITY, 0.5]),
321 duration_secs: 2.0 / 48000.0,
322 };
323 assert!(nan_track.waveform_peaks(0.0, 0.0, 0, 10).is_empty());
324 assert!(nan_track.waveform_peaks(-24.0, 0.0, 0, 10).is_empty());
325 assert!(nan_track.waveform_peaks(f64::NAN, 0.0, 0, 10).is_empty());
326 assert!(nan_track.waveform_peaks(f64::INFINITY, 0.0, 0, 10).is_empty());
327 assert!(nan_track.waveform_peaks(24.0, f64::NAN, 0, 10).is_empty());
328 assert!(nan_track.waveform_peaks(24.0, 0.0, i64::MIN, i64::MAX).is_empty());
329 let max_frame_peaks = nan_track.waveform_peaks(24.0, 0.0, i64::MAX, i64::MAX);
330 assert_eq!(max_frame_peaks, vec![0.0]);
331 let peaks = nan_track.waveform_peaks(24.0, 0.0, 0, 2);
332 assert_eq!(peaks.len(), 3);
333 assert!(peaks.iter().all(|p| p.is_finite() && (0.0..=1.0).contains(p)));
334
335 // 2. Malformed WAV/MP3 + malformed PNG/JPG/TIFF/BMP/TGA/EXR + huge-header EXR (OOM guard).
336 let dir = std::env::temp_dir().join(format!("fission-hardening-media-{}", std::process::id()));
337 let _ = std::fs::remove_dir_all(&dir);
338 std::fs::create_dir_all(&dir).unwrap();
339
340 let bad_audio: [(&str, Vec<u8>); 4] = [
341 ("empty.wav", vec![]),
342 ("trunc.wav", b"RIFF\x24\x00\x00\x00WAVEfmt ".to_vec()),
343 ("zero_fields.wav", {
344 let mut v = b"RIFF\x24\x00\x00\x00WAVEfmt \x10\x00\x00\x00".to_vec();
345 v.extend_from_slice(&[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0]);
346 v.extend_from_slice(b"data\x04\x00\x00\x00\x00\x00\x00\x00");
347 v
348 }),
349 ("garbage.mp3", vec![0xFF, 0xFB, 0x90, 0x00, 0xDE, 0xAD, 0xBE, 0xEF]),
350 ];
351 for (name, bytes) in &bad_audio {
352 let p = dir.join(name);
353 std::fs::write(&p, bytes).unwrap();
354 assert!(AudioTrack::load(&p).is_err(), "{name} should fail cleanly");
355 }
356
357 // Build a valid tiny 2x2 EXR via `image`, then patch its `dataWindow` box to 100_000 x 100_000
358 // to prove `decode_exr_rgba` and `extract_cryptomatte` reject huge-header EXRs without OOM.
359 let mut exr_bytes = Vec::new();
360 let img = image::Rgba32FImage::from_pixel(2, 2, image::Rgba([1.0, 0.5, 0.25, 1.0]));
361 image::DynamicImage::ImageRgba32F(img)
362 .write_to(&mut std::io::Cursor::new(&mut exr_bytes), image::ImageFormat::OpenExr)
363 .unwrap();
364 let dw_needle = b"dataWindow\0box2i\0\x10\x00\x00\x00";
365 if let Some(pos) = exr_bytes.windows(dw_needle.len()).position(|w| w == dw_needle) {
366 let box_off = pos + dw_needle.len();
367 // box2i = [xMin: i32, yMin: i32, xMax: i32, yMax: i32] -> 100_000 x 100_000 (160 GB if uncapped!)
368 exr_bytes[box_off..box_off + 16].copy_from_slice(
369 &[0i32, 0i32, 99_999i32, 99_999i32]
370 .into_iter()
371 .flat_map(i32::to_le_bytes)
372 .collect::<Vec<_>>(),
373 );
374 }
375
376 let mut mc = MediaCache::new(64);
377 let bad_imgs: [(&str, Vec<u8>); 8] = [
378 ("trunc.png", vec![137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, b'I', b'H', b'D', b'R']),
379 ("huge.png", {
380 let mut v = vec![137, 80, 78, 71, 13, 10, 26, 10];
381 v.extend_from_slice(&13u32.to_be_bytes());
382 v.extend_from_slice(b"IHDR");
383 v.extend_from_slice(&100_000u32.to_be_bytes());
384 v.extend_from_slice(&100_000u32.to_be_bytes());
385 v.extend_from_slice(&[8, 6, 0, 0, 0, 0, 0, 0, 0]);
386 v
387 }),
388 ("trunc.jpg", vec![0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10]),
389 ("trunc.tiff", b"II*\x00\x08\x00\x00\x00".to_vec()),
390 ("trunc.bmp", b"BM\x36\x00\x00\x00\x00\x00\x00\x00\x36\x00\x00\x00".to_vec()),
391 ("trunc.tga", vec![0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, 0xFF, 0xFF, 32, 0]),
392 ("trunc.exr", vec![0x76, 0x2F, 0x31, 0x01, 2, 0, 0, 0]),
393 ("huge_header.exr", exr_bytes),
394 ];
395 for (name, bytes) in &bad_imgs {
396 let p = dir.join(name);
397 std::fs::write(&p, bytes).unwrap();
398 let clip = make_clip(p.to_string_lossy().into_owned());
399 assert!(mc.load_clip(&clip, 0, false, [None; 4]).is_none(), "{name} must return None");
400 if name.ends_with(".exr") {
401 assert!(extract_cryptomatte(&p, None, "Hero").is_none());
402 }
403 }
404
405 let _ = std::fs::remove_dir_all(&dir);
406}
407
408#[test]
409fn cache_prefetcher_and_export_concurrency_and_range_boundaries() {
410 let comp = Comp::from_fusion_str(
411 r#"Composition {
412 CurrentTime = 0,
413 RenderRange = { 0, 4 },
414 GlobalRange = { 0, 4 },
415 Tools = ordered() {
416 BG = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, TopLeftRed = Input { Value = 0.5, }, TopLeftAlpha = Input { Value = 1.0, }, }, },
417 Saver1 = Saver { Inputs = { Input = Input { SourceOp = "BG", Source = "Output", }, }, },
418 },
419 }"#,
420 )
421 .unwrap();
422 let bg = comp.find_node("BG").unwrap();
423 let Ok(mut eng) = Engine::new_headless() else { return };
424
425 // 1. Tight VRAM budgets (0 MB and 1 MB).
426 for mb in [0u64, 1] {
427 eng.set_vram_budget_mb(mb);
428 eval_checked(&mut eng, &comp, bg, 0.0);
429 }
430 eng.set_vram_budget_mb(128);
431
432 // 2. RamFrameCache 0 MB and 1 MB budgets.
433 let rc0 = RamFrameCache::new(0);
434 let key0 = RamFrameKey { target: bg, revision: 1, frame: 0, proxy_scale: 1, hiq: true, use_proxy_clips: false };
435 let frame = RamFrame { size: [64, 64], rgba: Arc::new(vec![0u8; 64 * 64 * 4]), eval_ms: 1.0 };
436 rc0.insert(key0, frame.clone());
437 assert_eq!(rc0.entry_count(), 0);
438 let rc1 = RamFrameCache::new(1);
439 rc1.insert(key0, frame);
440 assert_eq!(rc1.entry_count(), 1);
441
442 // 3. RamPrefetcher rapid request_lookahead + cancel + extreme range + dangling target + Drop.
443 {
444 let rc = RamFrameCache::new(16);
445 let mut pf = RamPrefetcher::new(rc, 128);
446 pf.request_lookahead(PrefetchJob {
447 comp: comp.clone(),
448 target: NodeId(9999),
449 center_frame: 0,
450 range: [i64::MIN, i64::MAX],
451 lookahead: 4,
452 proxy_scale: 0,
453 hiq: true,
454 use_proxy_clips: false,
455 });
456 for i in 0..8 {
457 pf.request_lookahead(PrefetchJob {
458 comp: comp.clone(),
459 target: bg,
460 center_frame: i,
461 range: [i64::MIN, i64::MAX],
462 lookahead: 3,
463 proxy_scale: 0,
464 hiq: true,
465 use_proxy_clips: false,
466 });
467 if i % 2 == 0 {
468 pf.cancel();
469 }
470 }
471 }
472
473 // 4. PNG & Video export range/path errors + cancellation at frame 0, 1, last with zero leaked temp files.
474 let dir = std::env::temp_dir().join(format!("fission-hardening-export-{}", std::process::id()));
475 let _ = std::fs::remove_dir_all(&dir);
476 std::fs::create_dir_all(&dir).unwrap();
477
478 for bad_range in [[10, 5], [i64::MIN, i64::MAX]] {
479 let opts = ExportOptions {
480 out_dir_override: Some(dir.clone()),
481 range_override: Some(bad_range),
482 ..ExportOptions::default()
483 };
484 assert!(export_saver_png_sequence_with_progress(&mut eng, &comp, &opts, None, |_| {}).is_err());
485 }
486
487 // Single-frame PNG export at i64::MAX must not overflow prefetch arithmetic.
488 let max_opts = ExportOptions {
489 out_dir_override: Some(dir.clone()),
490 range_override: Some([i64::MAX, i64::MAX]),
491 ..ExportOptions::default()
492 };
493 let summary = export_saver_png_sequence_with_progress(&mut eng, &comp, &max_opts, None, |_| {}).unwrap();
494 assert_eq!(summary.frames_written, 1);
495
496 // Invalid output path (parent is a regular file).
497 let blocking_file = dir.join("not_a_dir");
498 std::fs::write(&blocking_file, b"x").unwrap();
499 let bad_path_opts = ExportOptions {
500 out_dir_override: Some(blocking_file.join("child")),
501 range_override: Some([0, 0]),
502 ..ExportOptions::default()
503 };
504 assert!(export_saver_png_sequence_with_progress(&mut eng, &comp, &bad_path_opts, None, |_| {}).is_err());
505
506 // Video export cancellation at frame 0, 1, and last frame (4): zero deadlocks, zero leaked `.fission_tmp_*`.
507 for cancel_at in [0usize, 1, 4] {
508 let out_mp4 = dir.join(format!("cancel_{cancel_at}.mp4"));
509 let ctrl = ExportControl::new();
510 let ctrl_c = ctrl.clone();
511 if cancel_at == 0 {
512 ctrl.cancel();
513 }
514 let vopts = VideoExportOptions {
515 target: bg,
516 out_path: out_mp4,
517 range: [0, 4],
518 codec: VideoCodec::H264Share,
519 include_audio: false,
520 ..VideoExportOptions::default()
521 };
522 let res = export_node_video_ffmpeg_with_progress(&mut eng, &comp, &vopts, Some(&ctrl), move |p| {
523 if p.index >= cancel_at {
524 ctrl_c.cancel();
525 }
526 });
527 assert!(res.is_err(), "cancel@{cancel_at} should return Err");
528 let leaked = std::fs::read_dir(&dir)
529 .unwrap()
530 .filter_map(|e| e.ok())
531 .filter(|e| e.file_name().to_string_lossy().contains(".fission_tmp_"))
532 .count();
533 assert_eq!(leaked, 0, "leaked temp export file on cancel@{cancel_at}");
534 }
535
536 let _ = std::fs::remove_dir_all(&dir);
537}