authoravatarclover caruso<git@paperclover.net>2026-12-01 18:57:10-08:00
committeravatarclover caruso<git@paperclover.net>2026-12-01 19:13:51-08:00
log4c8a96761128f8e16c9e38ea6f9d0a5f8f3b026c
tree7f2f0fe730f087002ae733c5edffacbe14e1a9a9
parent65e3eb9d114bdc05ad20b13c6c593763fe03ed0d
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

engine: harden eval, media, 3D, particle, audio, and export boundaries

Fix reproducible panics, stack overflows, integer overflows, runaway allocations, and wgpu validation errors cleanly at their architectural boundaries in crates/engine: - Guard DAG evaluation (eval_node) and media loader preloading against time-shifting cycles (MAX_EVAL_DEPTH / MAX_PRELOAD_DEPTH) and dangling NodeId indices. - Clamp PaintMask dimensions to max_texture_dimension_2d before CPU rasterization/upload (fixing Queue::write_texture overrun validation error) and bound Paint stamp_positions against non-finite/huge paths. - Reject non-finite TextPlus Size and use saturating bounds in text border/DoD calculations; reject non-finite/degenerate Camera3D clip and FOV values. - Fix Duplicate3D integer overflow, O(n) FirstCopy hang (exponentiation by squaring), and chained exponential mesh blowup (MAX_SCENE_MESHES). - Fix i64/i32 integer overflows in Particles, Filter noise seed, SetDomain DoD expansion, Loader frame ranges, GridWarp degenerate meshes, AudioTrack::waveform_peaks / sample_track_stereo, RamPrefetcher, and PNG/video export frame ranges. - Enforce pixel/byte caps with checked arithmetic and try_reserve_exact in EXR and Cryptomatte decoders to reject huge-header OOMs. - Add concise, fast (<1s) regression suite in crates/engine/tests/hardening_engine.rs.

18 files changed, 782 insertions(+), 118 deletions(-)

crates/engine/src/audio.rs+31-10
...@@ -471,11 +471,25 @@ impl AudioTrack {...@@ -471,11 +471,25 @@ impl AudioTrack {
471 start_frame: i64,471 start_frame: i64,
472 end_frame: i64,472 end_frame: i64,
473 ) -> Vec<f32> {473 ) -> Vec<f32> {
474 if end_frame < start_frame || fps <= 0.0 || self.sample_rate == 0 {474 const MAX_WAVEFORM_PEAKS: usize = 10_000_000;
475 if end_frame < start_frame
476 || !fps.is_finite()
477 || fps <= 0.0
478 || !offset_frames.is_finite()
479 || self.sample_rate == 0
480 {
481 return Vec::new();
482 }
483 let span = i128::from(end_frame) - i128::from(start_frame) + 1;
484 if span <= 0 || span > MAX_WAVEFORM_PEAKS as i128 {
485 return Vec::new();
486 }
487 let count = span as usize;
488 let mut peaks = Vec::new();
489 if peaks.try_reserve_exact(count).is_err() {
475 return Vec::new();490 return Vec::new();
476 }491 }
477 let count = (end_frame - start_frame + 1) as usize;492 peaks.resize(count, 0.0_f32);
478 let mut peaks = vec![0.0_f32; count];
479 let total_frames = self.samples.len() / 2;493 let total_frames = self.samples.len() / 2;
480 if total_frames == 0 {494 if total_frames == 0 {
481 return peaks;495 return peaks;
...@@ -483,10 +497,10 @@ impl AudioTrack {...@@ -483,10 +497,10 @@ impl AudioTrack {
483 let sr = self.sample_rate as f64;497 let sr = self.sample_rate as f64;
484498
485 for (i, peak_out) in peaks.iter_mut().enumerate() {499 for (i, peak_out) in peaks.iter_mut().enumerate() {
486 let f = start_frame + i as i64;500 let f = start_frame as f64 + i as f64;
487 let t0 = (f as f64 - offset_frames) / fps;501 let t0 = (f - offset_frames) / fps;
488 let t1 = ((f + 1) as f64 - offset_frames) / fps;502 let t1 = ((f + 1.0) - offset_frames) / fps;
489 if t1 <= 0.0 {503 if !t0.is_finite() || !t1.is_finite() || t1 <= 0.0 {
490 continue;504 continue;
491 }505 }
492 let s0 = (t0.max(0.0) * sr).floor() as usize;506 let s0 = (t0.max(0.0) * sr).floor() as usize;
...@@ -715,7 +729,7 @@ impl AudioPlayer {...@@ -715,7 +729,7 @@ impl AudioPlayer {
715 }729 }
716730
717 pub fn set_volume(&mut self, vol: f32) {731 pub fn set_volume(&mut self, vol: f32) {
718 let clamped = vol.clamp(0.0, 2.0);732 let clamped = if vol.is_finite() { vol.clamp(0.0, 2.0) } else { 0.0 };
719 self.state733 self.state
720 .volume_bits734 .volume_bits
721 .store(clamped.to_bits(), Ordering::Relaxed);735 .store(clamped.to_bits(), Ordering::Relaxed);
...@@ -766,11 +780,18 @@ fn sample_track_stereo(...@@ -766,11 +780,18 @@ fn sample_track_stereo(
766 t_sec: f64,780 t_sec: f64,
767 gain: f32,781 gain: f32,
768) -> (f32, f32) {782) -> (f32, f32) {
769 if total_frames == 0 || t_sec < 0.0 || gain <= 0.0 {783 if total_frames == 0
784 || !t_sec.is_finite()
785 || t_sec < 0.0
786 || !gain.is_finite()
787 || gain <= 0.0
788 || !track_sr.is_finite()
789 || track_sr <= 0.0
790 {
770 return (0.0, 0.0);791 return (0.0, 0.0);
771 }792 }
772 let src_pos = t_sec * track_sr;793 let src_pos = t_sec * track_sr;
773 if src_pos >= total_frames as f64 {794 if !src_pos.is_finite() || src_pos < 0.0 || src_pos >= total_frames as f64 {
774 return (0.0, 0.0);795 return (0.0, 0.0);
775 }796 }
776 let idx0 = src_pos.floor() as usize;797 let idx0 = src_pos.floor() as usize;
crates/engine/src/cryptomatte.rs+21-4
...@@ -678,11 +678,25 @@ pub fn extract_cryptomatte(...@@ -678,11 +678,25 @@ pub fn extract_cryptomatte(
678 }678 }
679679
680 let (w, h) = dims?;680 let (w, h) = dims?;
681 let pixel_count = w * h;681 const MAX_CRYPTO_PIXELS: usize = 64 * 1024 * 1024;
682 const MAX_CRYPTO_BYTES: usize = 512 * 1024 * 1024;
683 let pixel_count = w.checked_mul(h)?;
684 if w > u32::MAX as usize || h > u32::MAX as usize || pixel_count > MAX_CRYPTO_PIXELS {
685 return None;
686 }
687 let total_slot_bytes = pixel_count
688 .checked_mul(matched_channels.len().max(1))?
689 .checked_mul(std::mem::size_of::<f32>())?;
690 if total_slot_bytes > MAX_CRYPTO_BYTES {
691 return None;
692 }
682 if target_ids.is_empty() {693 if target_ids.is_empty() {
694 let mut matte = Vec::new();
695 matte.try_reserve_exact(pixel_count).ok()?;
696 matte.resize(pixel_count, 0.0_f32);
683 return Some(CryptomatteResult {697 return Some(CryptomatteResult {
684 size: [w as u32, h as u32],698 size: [w as u32, h as u32],
685 matte: vec![0.0_f32; pixel_count],699 matte,
686 });700 });
687 }701 }
688702
...@@ -691,7 +705,10 @@ pub fn extract_cryptomatte(...@@ -691,7 +705,10 @@ pub fn extract_cryptomatte(
691 HashMap::with_capacity(matched_channels.len());705 HashMap::with_capacity(matched_channels.len());
692 for (loc, rank, comp_idx) in matched_channels {706 for (loc, rank, comp_idx) in matched_channels {
693 let idx = slot_buffers.len();707 let idx = slot_buffers.len();
694 slot_buffers.push((rank, comp_idx, vec![0.0_f32; pixel_count]));708 let mut buf = Vec::new();
709 buf.try_reserve_exact(pixel_count).ok()?;
710 buf.resize(pixel_count, 0.0_f32);
711 slot_buffers.push((rank, comp_idx, buf));
695 loc_to_slot.insert(loc, idx);712 loc_to_slot.insert(loc, idx);
696 }713 }
697714
...@@ -713,7 +730,7 @@ pub fn extract_cryptomatte(...@@ -713,7 +730,7 @@ pub fn extract_cryptomatte(
713 let y = line.location.position.y();730 let y = line.location.position.y();
714 let x0 = line.location.position.x();731 let x0 = line.location.position.x();
715 let len = line.location.sample_count;732 let len = line.location.sample_count;
716 if y >= h || x0 + len > w {733 if y >= h || x0.saturating_add(len) > w {
717 continue;734 continue;
718 }735 }
719 let row_base = y * w + x0;736 let row_base = y * w + x0;
crates/engine/src/eval/blur_glow.rs+1-1
...@@ -1228,7 +1228,7 @@ impl Engine {...@@ -1228,7 +1228,7 @@ impl Engine {
1228 let animated = comp.eval_number(node, "Animated", time, 1.0, &self.expr) > 0.5;1228 let animated = comp.eval_number(node, "Animated", time, 1.0, &self.expr) > 0.5;
1229 // Only Noise and Grain read the seed; zeroing it elsewhere lets static filters hit the cache.1229 // Only Noise and Grain read the seed; zeroing it elsewhere lets static filters hit the cache.
1230 let seed = match ftype {1230 let seed = match ftype {
1231 5 | 6 if animated => seed_base.wrapping_add(frame_i as i32 * 101),1231 5 | 6 if animated => seed_base.wrapping_add((frame_i as i32).wrapping_mul(101)),
1232 5 | 6 => seed_base,1232 5 | 6 => seed_base,
1233 _ => 0,1233 _ => 0,
1234 };1234 };
crates/engine/src/eval/io.rs+4-4
...@@ -243,9 +243,9 @@ impl Engine {...@@ -243,9 +243,9 @@ impl Engine {
243 // playback past `GlobalEnd`), Fusion outputs no image regardless of `MissingFrames` or243 // playback past `GlobalEnd`), Fusion outputs no image regardless of `MissingFrames` or
244 // whether `Length == 1` (even single-frame stills return empty outside their active range).244 // whether `Length == 1` (even single-frame stills return empty outside their active range).
245 let out_of_range = effective_clip.global_end >= effective_clip.global_start245 let out_of_range = effective_clip.global_end >= effective_clip.global_start
246 && (frame_i < effective_clip.global_start - effective_clip.extend_first.max(0)246 && (frame_i < effective_clip.global_start.saturating_sub(effective_clip.extend_first.max(0))
247 || (!effective_clip.loop_clip247 || (!effective_clip.loop_clip
248 && frame_i > effective_clip.global_end + effective_clip.extend_last.max(0)));248 && frame_i > effective_clip.global_end.saturating_add(effective_clip.extend_last.max(0))));
249 let loaded = if out_of_range {249 let loaded = if out_of_range {
250 None250 None
251 } else {251 } else {
...@@ -1026,8 +1026,8 @@ impl Engine {...@@ -1026,8 +1026,8 @@ impl Engine {
1026 let x1 = (dr.max(1.0) * cw).ceil() as i32;1026 let x1 = (dr.max(1.0) * cw).ceil() as i32;
1027 let y0 = ((1.0 - dt.max(1.0)) * ch).floor() as i32;1027 let y0 = ((1.0 - dt.max(1.0)) * ch).floor() as i32;
1028 let y1 = ((1.0 - db.min(0.0)) * ch).ceil() as i32;1028 let y1 = ((1.0 - db.min(0.0)) * ch).ceil() as i32;
1029 let w = (x1 - x0).clamp(1, 8192) as u32;1029 let w = x1.saturating_sub(x0).clamp(1, 8192) as u32;
1030 let h = (y1 - y0).clamp(1, 8192) as u32;1030 let h = y1.saturating_sub(y0).clamp(1, 8192) as u32;
1031 ([x0, y0], [w, h])1031 ([x0, y0], [w, h])
1032 } else {1032 } else {
1033 ([0, 0], src.canvas_size)1033 ([0, 0], src.canvas_size)
crates/engine/src/eval/mod.rs+4
...@@ -551,6 +551,10 @@ impl Engine {...@@ -551,6 +551,10 @@ impl Engine {
551 visiting: &mut HashSet<(NodeId, i64)>,551 visiting: &mut HashSet<(NodeId, i64)>,
552 stats: &mut EvalStats,552 stats: &mut EvalStats,
553 ) -> CachedTexture {553 ) -> CachedTexture {
554 const MAX_EVAL_DEPTH: usize = 256;
555 if id.0 >= comp.nodes.len() || visiting.len() >= MAX_EVAL_DEPTH {
556 return self.dummy.clone();
557 }
554 let frame_i = time.round() as i64;558 let frame_i = time.round() as i64;
555 let time_key = (if time == 0.0 { 0.0 } else { time }).to_bits() as i64;559 let time_key = (if time == 0.0 { 0.0 } else { time }).to_bits() as i64;
556 let memo_sz = self.mask_target_size;560 let memo_sz = self.mask_target_size;
crates/engine/src/eval/paint.rs+13-6
...@@ -176,9 +176,10 @@ fn stroke_style(...@@ -176,9 +176,10 @@ fn stroke_style(
176176
177/// Brush stamp positions along `path` (pixels) between the `write_on` fractions of its arclength.177/// Brush stamp positions along `path` (pixels) between the `write_on` fractions of its arclength.
178fn stamp_positions(path: &[[f32; 2]], write_on: [f32; 2], spacing: f32) -> Vec<[f32; 2]> {178fn stamp_positions(path: &[[f32; 2]], write_on: [f32; 2], spacing: f32) -> Vec<[f32; 2]> {
179 const MAX_STAMPS_PER_STROKE: usize = 65_536;
179 let Some(&first) = path.first() else { return Vec::new() };180 let Some(&first) = path.first() else { return Vec::new() };
180 let [start, end] = write_on.map(|v| v.clamp(0.0, 1.0));181 let [start, end] = write_on.map(|v| v.clamp(0.0, 1.0));
181 if end <= start {182 if !start.is_finite() || !end.is_finite() || end <= start {
182 return Vec::new();183 return Vec::new();
183 }184 }
184 let mut cum = vec![0.0f32];185 let mut cum = vec![0.0f32];
...@@ -186,15 +187,18 @@ fn stamp_positions(path: &[[f32; 2]], write_on: [f32; 2], spacing: f32) -> Vec<[...@@ -186,15 +187,18 @@ fn stamp_positions(path: &[[f32; 2]], write_on: [f32; 2], spacing: f32) -> Vec<[
186 cum.push(cum.last().unwrap() + (w[1][0] - w[0][0]).hypot(w[1][1] - w[0][1]));187 cum.push(cum.last().unwrap() + (w[1][0] - w[0][0]).hypot(w[1][1] - w[0][1]));
187 }188 }
188 let total = *cum.last().unwrap();189 let total = *cum.last().unwrap();
190 if !total.is_finite() {
191 return Vec::new();
192 }
189 if total < 1e-4 {193 if total < 1e-4 {
190 return vec![first];194 return if first[0].is_finite() && first[1].is_finite() { vec![first] } else { Vec::new() };
191 }195 }
192 let (d0, d1) = (start * total, end * total);196 let (d0, d1) = (start * total, end * total);
193 let span = d1 - d0;197 let span = d1 - d0;
194 if span <= 1e-4 {198 if !span.is_finite() || span <= 1e-4 {
195 return Vec::new();199 return Vec::new();
196 }200 }
197 let n = (span / spacing).round().max(1.0) as usize;201 let n = ((span / spacing.max(1e-4)).round().max(1.0) as usize).min(MAX_STAMPS_PER_STROKE);
198 let step = span / n as f32;202 let step = span / n as f32;
199 (0..=n)203 (0..=n)
200 .map(|k| {204 .map(|k| {
...@@ -349,7 +353,9 @@ impl Engine {...@@ -349,7 +353,9 @@ impl Engine {
349 visiting: &mut HashSet<(NodeId, i64)>,353 visiting: &mut HashSet<(NodeId, i64)>,
350 stats: &mut EvalStats,354 stats: &mut EvalStats,
351 ) -> CachedTexture {355 ) -> CachedTexture {
352 let size = self.explicit_mask_size(comp, node, time, comp_dims);356 let raw_size = self.explicit_mask_size(comp, node, time, comp_dims);
357 let max_dim = self.device.limits().max_texture_dimension_2d.max(1);
358 let (size, tex_scale) = crate::cache::clamp_dims_to_limit(raw_size[0], raw_size[1], max_dim);
353 let soft = comp.eval_number(node, "SoftEdge", time, 0.0, &self.expr).max(0.0) as f32;359 let soft = comp.eval_number(node, "SoftEdge", time, 0.0, &self.expr).max(0.0) as f32;
354 let invert = comp.eval_number(node, "Invert", time, 0.0, &self.expr) > 0.5;360 let invert = comp.eval_number(node, "Invert", time, 0.0, &self.expr) > 0.5;
355 let level = comp.eval_number(node, "Level", time, 1.0, &self.expr) as f32;361 let level = comp.eval_number(node, "Level", time, 1.0, &self.expr) as f32;
...@@ -380,7 +386,8 @@ impl Engine {...@@ -380,7 +386,8 @@ impl Engine {
380 level,386 level,
381 prev: prev_mask.as_ref(),387 prev: prev_mask.as_ref(),
382 };388 };
383 let tex = self.upload_cpu_mask(enc, size, key, &pixels, Some(post));389 let mut tex = self.upload_cpu_mask(enc, size, key, &pixels, Some(post));
390 tex.tex_scale = tex_scale;
384 self.cache.insert(key, tex.clone(), node.id, frame_i);391 self.cache.insert(key, tex.clone(), node.id, frame_i);
385 tex392 tex
386 }393 }
crates/engine/src/eval/text_3d.rs+9-6
...@@ -593,7 +593,8 @@ impl Engine {...@@ -593,7 +593,8 @@ impl Engine {
593 let ext_max = ti.border_ext_h.abs().max(ti.border_ext_v.abs()) * size_px;593 let ext_max = ti.border_ext_h.abs().max(ti.border_ext_v.abs()) * size_px;
594 let off_max = (ti.border_offset[0].abs() * size[0] as f32)594 let off_max = (ti.border_offset[0].abs() * size[0] as f32)
595 .max(ti.border_offset[1].abs() * size[1] as f32);595 .max(ti.border_offset[1].abs() * size[1] as f32);
596 (0.45 * size_px + ext_max + off_max).ceil() as i32 + 4596 let pad = 0.45 * size_px + ext_max + off_max;
597 if pad.is_finite() { (pad.ceil() as i32).saturating_add(4) } else { 0 }
597 } else {598 } else {
598 0599 0
599 };600 };
...@@ -769,10 +770,10 @@ impl Engine {...@@ -769,10 +770,10 @@ impl Engine {
769 let hw = (0.5 * (b[2] - b[0])).max(0.5);770 let hw = (0.5 * (b[2] - b[0])).max(0.5);
770 let hh = (0.5 * (b[3] - b[1])).max(0.5);771 let hh = (0.5 * (b[3] - b[1])).max(0.5);
771 let rad = (border_round * hh).min(hw.min(hh));772 let rad = (border_round * hh).min(hw.min(hh));
772 let ix0 = (b[0].floor() as i32 - 1).clamp(0, tw as i32 - 1) as usize;773 let ix0 = (b[0].floor() as i32).saturating_sub(1).clamp(0, tw as i32 - 1) as usize;
773 let ix1 = (b[2].ceil() as i32 + 1).clamp(0, tw as i32 - 1) as usize;774 let ix1 = (b[2].ceil() as i32).saturating_add(1).clamp(0, tw as i32 - 1) as usize;
774 let iy0 = (b[1].floor() as i32 - 1).clamp(0, th as i32 - 1) as usize;775 let iy0 = (b[1].floor() as i32).saturating_sub(1).clamp(0, th as i32 - 1) as usize;
775 let iy1 = (b[3].ceil() as i32 + 1).clamp(0, th as i32 - 1) as usize;776 let iy1 = (b[3].ceil() as i32).saturating_add(1).clamp(0, th as i32 - 1) as usize;
776 for yy in iy0..=iy1 {777 for yy in iy0..=iy1 {
777 let py = yy as f32 + 0.5 - cy;778 let py = yy as f32 + 0.5 - cy;
778 let qy = py.abs() - (hh - rad);779 let qy = py.abs() - (hh - rad);
...@@ -915,7 +916,9 @@ impl Engine {...@@ -915,7 +916,9 @@ impl Engine {
915 let selected_camera = cameras.iter().find(|c| c.name == selector).or(cameras.first());916 let selected_camera = cameras.iter().find(|c| c.name == selector).or(cameras.first());
916917
917 let (view, mut proj, cam_pos, cam_far) = if let Some(cam) = selected_camera {918 let (view, mut proj, cam_pos, cam_far) = if let Some(cam) = selected_camera {
918 if cam.near >= cam.far || (!cam.orthographic && cam.near <= 0.0) {919 let bad_clip = !(cam.near.is_finite() && cam.far.is_finite() && cam.near < cam.far)
920 || (!cam.orthographic && (cam.near <= 0.0 || !cam.vfov_rad.is_finite() || cam.vfov_rad <= 0.0 || cam.vfov_rad >= std::f32::consts::PI));
921 if bad_clip {
919 let mut empty = create_texture(&self.device, size, 0);922 let mut empty = create_texture(&self.device, size, 0);
920 empty.tex_scale = tex_scale;923 empty.tex_scale = tex_scale;
921 return empty;924 return empty;
crates/engine/src/eval/warps.rs+3
...@@ -806,6 +806,9 @@ struct CoonsPt {...@@ -806,6 +806,9 @@ struct CoonsPt {
806fn mesh_coons_cells(mesh: &model::comp::GridMesh) -> Vec<[CoonsPt; 4]> {806fn mesh_coons_cells(mesh: &model::comp::GridMesh) -> Vec<[CoonsPt; 4]> {
807 let cols = mesh.cols;807 let cols = mesh.cols;
808 let rows = mesh.rows;808 let rows = mesh.rows;
809 if cols < 2 || rows < 2 || mesh.points.len() < cols.saturating_mul(rows) {
810 return Vec::new();
811 }
809 let dc = (mesh.delta_c as f32) / 3.0;812 let dc = (mesh.delta_c as f32) / 3.0;
810 let dr = (mesh.delta_r as f32) / 3.0;813 let dr = (mesh.delta_r as f32) / 3.0;
811 let pts: Vec<CoonsPt> = mesh814 let pts: Vec<CoonsPt> = mesh
crates/engine/src/export.rs+44-36
...@@ -271,7 +271,8 @@ pub fn export_saver_png_sequence_with_progress(...@@ -271,7 +271,8 @@ pub fn export_saver_png_sequence_with_progress(
271 let saver = select_saver(comp, opts.saver_name.as_deref())?;271 let saver = select_saver(comp, opts.saver_name.as_deref())?;
272 let target: NodeId = saver.upstream.unwrap_or(saver.node_id);272 let target: NodeId = saver.upstream.unwrap_or(saver.node_id);
273 let [start, end] = opts.range_override.unwrap_or(saver.range);273 let [start, end] = opts.range_override.unwrap_or(saver.range);
274 if end < start {274 let total_i128 = i128::from(end) - i128::from(start) + 1;
275 if end < start || total_i128 <= 0 || total_i128 > i128::from(u32::MAX) {
275 return Err(format!("invalid export frame range {start}..={end}"));276 return Err(format!("invalid export frame range {start}..={end}"));
276 }277 }
277278
...@@ -280,7 +281,7 @@ pub fn export_saver_png_sequence_with_progress(...@@ -280,7 +281,7 @@ pub fn export_saver_png_sequence_with_progress(
280 engine.hiq = opts.hiq;281 engine.hiq = opts.hiq;
281 engine.proxy_scale = opts.proxy_scale.max(1);282 engine.proxy_scale = opts.proxy_scale.max(1);
282283
283 let total = (end - start + 1) as usize;284 let total = total_i128 as usize;
284 let workers = if opts.png_workers > 0 {285 let workers = if opts.png_workers > 0 {
285 opts.png_workers.clamp(1, 24)286 opts.png_workers.clamp(1, 24)
286 } else {287 } else {
...@@ -348,16 +349,19 @@ pub fn export_saver_png_sequence_with_progress(...@@ -348,16 +349,19 @@ pub fn export_saver_png_sequence_with_progress(
348 const PREFETCH_LOOKAHEAD: usize = 12;349 const PREFETCH_LOOKAHEAD: usize = 12;
349 engine.prewarm_for_depth(comp.depth_full);350 engine.prewarm_for_depth(comp.depth_full);
350 let prefetch = engine.media.start_frame_prefetch(PREFETCH_LOOKAHEAD);351 let prefetch = engine.media.start_frame_prefetch(PREFETCH_LOOKAHEAD);
351 let seed_end = (start + PREFETCH_LOOKAHEAD as i64 - 1).min(end);352 if start < end {
352 for (k, f) in ((start + 1)..=seed_end).enumerate() {353 let seed_start = start.saturating_add(1);
353 prefetch.enqueue_frame(354 let seed_end = start.saturating_add(PREFETCH_LOOKAHEAD as i64 - 1).min(end);
354 comp,355 for (k, f) in (seed_start..=seed_end).enumerate() {
355 target,356 prefetch.enqueue_frame(
356 k + 1,357 comp,
357 f as f64,358 target,
358 &engine.expr,359 k + 1,
359 engine.use_proxy_clips,360 f as f64,
360 );361 &engine.expr,
362 engine.use_proxy_clips,
363 );
364 }
361 }365 }
362 // Double-buffered async GPU readback: frame N+1 evaluates/submits on GPU while366 // Double-buffered async GPU readback: frame N+1 evaluates/submits on GPU while
363 // frame N finishes its copy/map and hands off to the background PNG writer pool.367 // frame N finishes its copy/map and hands off to the background PNG writer pool.
...@@ -371,16 +375,17 @@ pub fn export_saver_png_sequence_with_progress(...@@ -371,16 +375,17 @@ pub fn export_saver_png_sequence_with_progress(
371 break;375 break;
372 }376 }
373 prefetch.set_current_seq(idx);377 prefetch.set_current_seq(idx);
374 let ahead_frame = frame + PREFETCH_LOOKAHEAD as i64;378 if let Some(ahead_frame) = frame.checked_add(PREFETCH_LOOKAHEAD as i64) {
375 if ahead_frame <= end {379 if ahead_frame <= end {
376 prefetch.enqueue_frame(380 prefetch.enqueue_frame(
377 comp,381 comp,
378 target,382 target,
379 idx + PREFETCH_LOOKAHEAD,383 idx + PREFETCH_LOOKAHEAD,
380 ahead_frame as f64,384 ahead_frame as f64,
381 &engine.expr,385 &engine.expr,
382 engine.use_proxy_clips,386 engine.use_proxy_clips,
383 );387 );
388 }
384 }389 }
385 let out_path = match resolve_output_path(&saver, frame, opts.out_dir_override.as_deref()) {390 let out_path = match resolve_output_path(&saver, frame, opts.out_dir_override.as_deref()) {
386 Ok(p) => p,391 Ok(p) => p,
...@@ -954,7 +959,8 @@ pub fn export_node_video_ffmpeg_with_progress(...@@ -954,7 +959,8 @@ pub fn export_node_video_ffmpeg_with_progress(
954 return Err("Cancelled".to_owned());959 return Err("Cancelled".to_owned());
955 }960 }
956 let [start, end] = opts.range;961 let [start, end] = opts.range;
957 if end < start {962 let total_i128 = i128::from(end) - i128::from(start) + 1;
963 if end < start || total_i128 <= 0 || total_i128 > i128::from(u32::MAX) {
958 return Err(format!("invalid export frame range {start}..={end}"));964 return Err(format!("invalid export frame range {start}..={end}"));
959 }965 }
960 if opts.target.0 >= comp.nodes.len() {966 if opts.target.0 >= comp.nodes.len() {
...@@ -1248,8 +1254,9 @@ fn export_node_video_ffmpeg_with_encoder(...@@ -1248,8 +1254,9 @@ fn export_node_video_ffmpeg_with_encoder(
1248 } else if start < end {1254 } else if start < end {
1249 const PREFETCH_LOOKAHEAD: usize = 12;1255 const PREFETCH_LOOKAHEAD: usize = 12;
1250 let prefetch = engine.media.start_frame_prefetch(PREFETCH_LOOKAHEAD);1256 let prefetch = engine.media.start_frame_prefetch(PREFETCH_LOOKAHEAD);
1251 let seed_end = (start + PREFETCH_LOOKAHEAD as i64).min(end);1257 let seed_start = start.saturating_add(1);
1252 for (k, f) in ((start + 1)..=seed_end).enumerate() {1258 let seed_end = start.saturating_add(PREFETCH_LOOKAHEAD as i64).min(end);
1259 for (k, f) in (seed_start..=seed_end).enumerate() {
1253 prefetch.enqueue_frame(1260 prefetch.enqueue_frame(
1254 comp,1261 comp,
1255 opts.target,1262 opts.target,
...@@ -1260,7 +1267,7 @@ fn export_node_video_ffmpeg_with_encoder(...@@ -1260,7 +1267,7 @@ fn export_node_video_ffmpeg_with_encoder(
1260 );1267 );
1261 }1268 }
1262 let mut pending: Option<(crate::eval::PendingReadback, i64, usize, [u32; 2], f64)> = None;1269 let mut pending: Option<(crate::eval::PendingReadback, i64, usize, [u32; 2], f64)> = None;
1263 for (idx, frame) in ((start + 1)..=end).enumerate() {1270 for (idx, frame) in (seed_start..=end).enumerate() {
1264 if control.is_some_and(ExportControl::is_cancelled) {1271 if control.is_some_and(ExportControl::is_cancelled) {
1265 cancelled = true;1272 cancelled = true;
1266 break;1273 break;
...@@ -1269,16 +1276,17 @@ fn export_node_video_ffmpeg_with_encoder(...@@ -1269,16 +1276,17 @@ fn export_node_video_ffmpeg_with_encoder(
1269 break;1276 break;
1270 }1277 }
1271 prefetch.set_current_seq(idx);1278 prefetch.set_current_seq(idx);
1272 let ahead_frame = frame + PREFETCH_LOOKAHEAD as i64;1279 if let Some(ahead_frame) = frame.checked_add(PREFETCH_LOOKAHEAD as i64) {
1273 if ahead_frame <= end {1280 if ahead_frame <= end {
1274 prefetch.enqueue_frame(1281 prefetch.enqueue_frame(
1275 comp,1282 comp,
1276 opts.target,1283 opts.target,
1277 idx + PREFETCH_LOOKAHEAD,1284 idx + PREFETCH_LOOKAHEAD,
1278 ahead_frame as f64,1285 ahead_frame as f64,
1279 &engine.expr,1286 &engine.expr,
1280 engine.use_proxy_clips,1287 engine.use_proxy_clips,
1281 );1288 );
1289 }
1282 }1290 }
1283 let (tex, stats) = engine.evaluate(comp, opts.target, frame as f64);1291 let (tex, stats) = engine.evaluate(comp, opts.target, frame as f64);
1284 let next_rb = match engine.begin_readback_rgba(&tex) {1292 let next_rb = match engine.begin_readback_rgba(&tex) {
crates/engine/src/media.rs+38-9
...@@ -1950,13 +1950,40 @@ fn collect_missing_loader_jobs_shared(...@@ -1950,13 +1950,40 @@ fn collect_missing_loader_jobs_shared(
1950 visited: &mut HashSet<(NodeId, i64)>,1950 visited: &mut HashSet<(NodeId, i64)>,
1951 jobs: &mut MissingJobs,1951 jobs: &mut MissingJobs,
1952) {1952) {
1953 if node_id.0 >= comp.nodes.len() {1953 const MAX_PRELOAD_DEPTH: usize = 256;
1954 if node_id.0 >= comp.nodes.len() || jobs.depth >= MAX_PRELOAD_DEPTH {
1954 return;1955 return;
1955 }1956 }
1956 let time_key = (if time == 0.0 { 0.0 } else { time }).to_bits() as i64;1957 let time_key = (if time == 0.0 { 0.0 } else { time }).to_bits() as i64;
1957 if !visited.insert((node_id, time_key)) {1958 if !visited.insert((node_id, time_key)) {
1958 return;1959 return;
1959 }1960 }
1961 jobs.depth += 1;
1962 collect_missing_loader_jobs_inner(
1963 shared,
1964 comp,
1965 node_id,
1966 time,
1967 expr,
1968 use_proxy_clips,
1969 visited,
1970 jobs,
1971 );
1972 jobs.depth -= 1;
1973}
1974
1975#[cfg(not(target_arch = "wasm32"))]
1976#[allow(clippy::too_many_arguments)]
1977fn collect_missing_loader_jobs_inner(
1978 shared: &MediaShared,
1979 comp: &Comp,
1980 node_id: NodeId,
1981 time: f64,
1982 expr: &model::ExprEngine,
1983 use_proxy_clips: bool,
1984 visited: &mut HashSet<(NodeId, i64)>,
1985 jobs: &mut MissingJobs,
1986) {
1960 let node = comp.node(node_id);1987 let node = comp.node(node_id);
19611988
1962 if node.bypassed1989 if node.bypassed
...@@ -2252,9 +2279,9 @@ fn collect_missing_loader_jobs_shared(...@@ -2252,9 +2279,9 @@ fn collect_missing_loader_jobs_shared(
2252 }2279 }
2253 }2280 }
2254 let out_of_range = effective_clip.global_end >= effective_clip.global_start2281 let out_of_range = effective_clip.global_end >= effective_clip.global_start
2255 && (frame_i < effective_clip.global_start - effective_clip.extend_first.max(0)2282 && (frame_i < effective_clip.global_start.saturating_sub(effective_clip.extend_first.max(0))
2256 || (!effective_clip.loop_clip2283 || (!effective_clip.loop_clip
2257 && frame_i > effective_clip.global_end + effective_clip.extend_last.max(0)));2284 && frame_i > effective_clip.global_end.saturating_add(effective_clip.extend_last.max(0))));
2258 if !out_of_range {2285 if !out_of_range {
2259 let base = Path::new(&effective_clip.filename);2286 let base = Path::new(&effective_clip.filename);
2260 if is_video_path(base) {2287 if is_video_path(base) {
...@@ -2378,8 +2405,8 @@ fn video_frame_in_range(clip: &ClipSpec, frame: i64) -> bool {...@@ -2378,8 +2405,8 @@ fn video_frame_in_range(clip: &ClipSpec, frame: i64) -> bool {
2378 if clip.global_end >= clip.global_start2405 if clip.global_end >= clip.global_start
2379 && (clip.length.unwrap_or(0) > 1 || clip.global_end > clip.global_start)2406 && (clip.length.unwrap_or(0) > 1 || clip.global_end > clip.global_start)
2380 {2407 {
2381 let min_f = clip.global_start - clip.extend_first.max(0);2408 let min_f = clip.global_start.saturating_sub(clip.extend_first.max(0));
2382 let max_f = clip.global_end + clip.extend_last.max(0);2409 let max_f = clip.global_end.saturating_add(clip.extend_last.max(0));
2383 if frame < min_f || (!clip.loop_clip && frame > max_f) {2410 if frame < min_f || (!clip.loop_clip && frame > max_f) {
2384 return false;2411 return false;
2385 }2412 }
...@@ -2395,13 +2422,14 @@ fn compute_video_frame_idx(clip: &ClipSpec, frame: i64, nb_frames: i64) -> i64 {...@@ -2395,13 +2422,14 @@ fn compute_video_frame_idx(clip: &ClipSpec, frame: i64, nb_frames: i64) -> i64 {
2395 } else {2422 } else {
2396 len - 12423 len - 1
2397 };2424 };
2398 let span = (trim_out - trim_in + 1).max(1);2425 let span = trim_out.saturating_sub(trim_in).saturating_add(1).max(1);
2426 let delta = frame.saturating_sub(clip.global_start);
2399 let rel = if clip.loop_clip {2427 let rel = if clip.loop_clip {
2400 (frame - clip.global_start).max(0).rem_euclid(span)2428 delta.max(0).rem_euclid(span)
2401 } else {2429 } else {
2402 (frame - clip.global_start).clamp(0, span - 1)2430 delta.clamp(0, span - 1)
2403 };2431 };
2404 if clip.reverse { trim_out - rel } else { trim_in + rel }2432 if clip.reverse { trim_out.saturating_sub(rel) } else { trim_in.saturating_add(rel) }
2405}2433}
24062434
2407#[cfg(not(target_arch = "wasm32"))]2435#[cfg(not(target_arch = "wasm32"))]
...@@ -2410,6 +2438,7 @@ struct MissingJobs {...@@ -2410,6 +2438,7 @@ struct MissingJobs {
2410 raster: Vec<PreloadJob>,2438 raster: Vec<PreloadJob>,
2411 seen_raster: HashSet<ImageCacheKey>,2439 seen_raster: HashSet<ImageCacheKey>,
2412 videos: HashMap<PathBuf, Vec<VideoFrameRequest>>,2440 videos: HashMap<PathBuf, Vec<VideoFrameRequest>>,
2441 depth: usize,
2413}2442}
24142443
2415#[cfg(not(target_arch = "wasm32"))]2444#[cfg(not(target_arch = "wasm32"))]
crates/engine/src/media/exr.rs+14-5
...@@ -321,9 +321,12 @@ fn decode_exr_from<R: std::io::Read + std::io::Seek + Send>(...@@ -321,9 +321,12 @@ fn decode_exr_from<R: std::io::Read + std::io::Seek + Send>(
321 let first_header = chunks_reader.headers().first()?;321 let first_header = chunks_reader.headers().first()?;
322 let w = first_header.layer_size.width();322 let w = first_header.layer_size.width();
323 let h = first_header.layer_size.height();323 let h = first_header.layer_size.height();
324 if w == 0 || h == 0 {324 const MAX_EXR_PIXELS: usize = 64 * 1024 * 1024;
325 let pixel_count = w.checked_mul(h)?;
326 if w == 0 || h == 0 || w > u32::MAX as usize || h > u32::MAX as usize || pixel_count > MAX_EXR_PIXELS {
325 return None;327 return None;
326 }328 }
329 let elem_count = pixel_count.checked_mul(4)?;
327330
328 let r_loc = find_exr_channel_loc(chunks_reader.headers(), w, h, red_name, "R", "r")?;331 let r_loc = find_exr_channel_loc(chunks_reader.headers(), w, h, red_name, "R", "r")?;
329 let g_loc = find_exr_channel_loc(chunks_reader.headers(), w, h, green_name, "G", "g");332 let g_loc = find_exr_channel_loc(chunks_reader.headers(), w, h, green_name, "G", "g");
...@@ -335,7 +338,9 @@ fn decode_exr_from<R: std::io::Read + std::io::Seek + Send>(...@@ -335,7 +338,9 @@ fn decode_exr_from<R: std::io::Read + std::io::Seek + Send>(
335 needed_layers.sort_unstable();338 needed_layers.sort_unstable();
336 needed_layers.dedup();339 needed_layers.dedup();
337340
338 let mut raw_f32 = vec![0.0_f32; w * h * 4];341 let mut raw_f32 = Vec::new();
342 raw_f32.try_reserve_exact(elem_count).ok()?;
343 raw_f32.resize(elem_count, 0.0_f32);
339 let mut line_f32 = Vec::<f32>::new();344 let mut line_f32 = Vec::<f32>::new();
340 let mut line_f16 = Vec::<f16>::new();345 let mut line_f16 = Vec::<f16>::new();
341 let mut line_u32 = Vec::<u32>::new();346 let mut line_u32 = Vec::<u32>::new();
...@@ -361,7 +366,7 @@ fn decode_exr_from<R: std::io::Read + std::io::Seek + Send>(...@@ -361,7 +366,7 @@ fn decode_exr_from<R: std::io::Read + std::io::Seek + Send>(
361 let y = line.location.position.y();366 let y = line.location.position.y();
362 let x0 = line.location.position.x();367 let x0 = line.location.position.x();
363 let len = line.location.sample_count;368 let len = line.location.sample_count;
364 if y >= h || x0 + len > w {369 if y >= h || x0.saturating_add(len) > w {
365 continue;370 continue;
366 }371 }
367372
...@@ -402,8 +407,12 @@ fn decode_exr_from<R: std::io::Read + std::io::Seek + Send>(...@@ -402,8 +407,12 @@ fn decode_exr_from<R: std::io::Read + std::io::Seek + Send>(
402 filtered.decompress_sequential(false, insert_block).ok()?;407 filtered.decompress_sequential(false, insert_block).ok()?;
403 }408 }
404409
405 let mut raw = vec![0u8; w * h * 4];410 let mut raw = Vec::new();
406 let mut raw_f16 = vec![0u16; w * h * 4];411 raw.try_reserve_exact(elem_count).ok()?;
412 raw.resize(elem_count, 0u8);
413 let mut raw_f16 = Vec::new();
414 raw_f16.try_reserve_exact(elem_count).ok()?;
415 raw_f16.resize(elem_count, 0u16);
407 convert_exr_rgba_buffers(416 convert_exr_rgba_buffers(
408 &mut raw_f32,417 &mut raw_f32,
409 &mut raw_f16,418 &mut raw_f16,
crates/engine/src/media/raster.rs+6-6
...@@ -27,7 +27,7 @@ pub struct TextPlusParams<'a> {...@@ -27,7 +27,7 @@ pub struct TextPlusParams<'a> {
27pub fn rasterize_text_plus(dims: [u32; 2], params: &TextPlusParams<'_>, dod_pad: i32) -> ([u32; 2], [i32; 2], Vec<u8>) {27pub fn rasterize_text_plus(dims: [u32; 2], params: &TextPlusParams<'_>, dod_pad: i32) -> ([u32; 2], [i32; 2], Vec<u8>) {
28 let [w, h] = dims;28 let [w, h] = dims;
29 let empty = || (dims, [0, 0], vec![0u8; (w as usize) * (h as usize) * 4]);29 let empty = || (dims, [0, 0], vec![0u8; (w as usize) * (h as usize) * 4]);
30 if params.text.is_empty() || params.size_norm <= 1e-4 {30 if params.text.is_empty() || !params.size_norm.is_finite() || params.size_norm <= 1e-4 {
31 return empty();31 return empty();
32 }32 }
3333
...@@ -48,7 +48,7 @@ pub fn rasterize_text_plus(dims: [u32; 2], params: &TextPlusParams<'_>, dod_pad:...@@ -48,7 +48,7 @@ pub fn rasterize_text_plus(dims: [u32; 2], params: &TextPlusParams<'_>, dod_pad:
48 let mut cls_dy = vec![0.0_f32; total_chars];48 let mut cls_dy = vec![0.0_f32; total_chars];
49 for e in params.cls {49 for e in params.cls {
50 let s = e.start.min(total_chars);50 let s = e.start.min(total_chars);
51 let end = (e.end + 1).min(total_chars);51 let end = e.end.saturating_add(1).min(total_chars);
52 for i in s..end {52 for i in s..end {
53 if e.prop_id == 1350 {53 if e.prop_id == 1350 {
54 cls_dx[i] = e.value;54 cls_dx[i] = e.value;
...@@ -90,10 +90,10 @@ pub fn rasterize_text_plus(dims: [u32; 2], params: &TextPlusParams<'_>, dod_pad:...@@ -90,10 +90,10 @@ pub fn rasterize_text_plus(dims: [u32; 2], params: &TextPlusParams<'_>, dod_pad:
90 let mut placed = Vec::new();90 let mut placed = Vec::new();
91 let (mut min_x, mut min_y, mut max_x, mut max_y) = (0i32, 0i32, w as i32, h as i32);91 let (mut min_x, mut min_y, mut max_x, mut max_y) = (0i32, 0i32, w as i32, h as i32);
92 let mut grow = |c: &text_engine::Coverage, pad: i32| {92 let mut grow = |c: &text_engine::Coverage, pad: i32| {
93 min_x = min_x.min(c.left - pad);93 min_x = min_x.min(c.left.saturating_sub(pad));
94 min_y = min_y.min(c.top - pad);94 min_y = min_y.min(c.top.saturating_sub(pad));
95 max_x = max_x.max(c.left + c.width as i32 + pad);95 max_x = max_x.max(c.left.saturating_add(c.width as i32).saturating_add(pad));
96 max_y = max_y.max(c.top + c.height as i32 + pad);96 max_y = max_y.max(c.top.saturating_add(c.height as i32).saturating_add(pad));
97 };97 };
9898
99 let mut char_cursor = 0usize;99 let mut char_cursor = 0usize;
crates/engine/src/particles.rs+20-13
...@@ -170,7 +170,8 @@ impl SplitMix64 {...@@ -170,7 +170,8 @@ impl SplitMix64 {
170}170}
171171
172fn maybe_record_snapshot(cached: &mut CachedSim, frame: i64) {172fn maybe_record_snapshot(cached: &mut CachedSim, frame: i64) {
173 if (frame - cached.base_start).rem_euclid(SNAPSHOT_INTERVAL) == 0 {173 let delta = i128::from(frame) - i128::from(cached.base_start);
174 if delta.rem_euclid(i128::from(SNAPSHOT_INTERVAL)) == 0 {
174 cached.snapshots.insert(frame, cached.state.clone());175 cached.snapshots.insert(frame, cached.state.clone());
175 while cached.snapshots.len() > MAX_SNAPSHOTS {176 while cached.snapshots.len() > MAX_SNAPSHOTS {
176 if let Some(&oldest) = cached.snapshots.keys().next() {177 if let Some(&oldest) = cached.snapshots.keys().next() {
...@@ -196,7 +197,7 @@ pub fn render_particles_2d(...@@ -196,7 +197,7 @@ pub fn render_particles_2d(
196) -> Vec<u8> {197) -> Vec<u8> {
197 let pixel_count = (dims[0] as usize).saturating_mul(dims[1] as usize);198 let pixel_count = (dims[0] as usize).saturating_mul(dims[1] as usize);
198 let mut out = vec![0u8; pixel_count.saturating_mul(4)];199 let mut out = vec![0u8; pixel_count.saturating_mul(4)];
199 if pixel_count == 0 {200 if pixel_count == 0 || !time.is_finite() {
200 return out;201 return out;
201 }202 }
202203
...@@ -226,7 +227,7 @@ pub fn render_particles_2d(...@@ -226,7 +227,7 @@ pub fn render_particles_2d(
226 .eval_number(rnode, "PreGenerateFrames", time, 0.0, expr)227 .eval_number(rnode, "PreGenerateFrames", time, 0.0, expr)
227 .round()228 .round()
228 .clamp(0.0, MAX_SIM_WINDOW as f64) as i64;229 .clamp(0.0, MAX_SIM_WINDOW as f64) as i64;
229 let sim_origin = base_start - pre_gen;230 let sim_origin = base_start.saturating_sub(pre_gen);
230231
231 let subgraph_hash = particle_subgraph_hash(comp, render_node, base_start);232 let subgraph_hash = particle_subgraph_hash(comp, render_node, base_start);
232 let key = (rnode.name.clone(), subgraph_hash);233 let key = (rnode.name.clone(), subgraph_hash);
...@@ -235,15 +236,15 @@ pub fn render_particles_2d(...@@ -235,15 +236,15 @@ pub fn render_particles_2d(
235 .entries236 .entries
236 .retain(|(name, h), _| name != &key.0 || *h == subgraph_hash);237 .retain(|(name, h), _| name != &key.0 || *h == subgraph_hash);
237238
238 let cold_sim_start = |target: i64| sim_origin.max(target - MAX_SIM_WINDOW);239 let cold_sim_start = |target: i64| sim_origin.max(target.saturating_sub(MAX_SIM_WINDOW));
239240
240 let need_cold_init = match cache.entries.get_mut(&key) {241 let need_cold_init = match cache.entries.get_mut(&key) {
241 Some(cached) if cached.base_start == sim_origin => {242 Some(cached) if cached.base_start == sim_origin => {
242 if target_frame == cached.current_frame {243 if target_frame == cached.current_frame {
243 false244 false
244 } else if target_frame > cached.current_frame {245 } else if target_frame > cached.current_frame {
245 if target_frame - cached.current_frame <= MAX_SIM_WINDOW {246 if i128::from(target_frame) - i128::from(cached.current_frame) <= i128::from(MAX_SIM_WINDOW) {
246 for f in (cached.current_frame + 1)..=target_frame {247 for f in cached.current_frame.saturating_add(1)..=target_frame {
247 step_simulation(&mut cached.state, comp, &plan, f, expr);248 step_simulation(&mut cached.state, comp, &plan, f, expr);
248 maybe_record_snapshot(cached, f);249 maybe_record_snapshot(cached, f);
249 }250 }
...@@ -253,14 +254,20 @@ pub fn render_particles_2d(...@@ -253,14 +254,20 @@ pub fn render_particles_2d(
253 true254 true
254 }255 }
255 } else if let Some((&snap_f, snap_state)) = cached.snapshots.range(..=target_frame).next_back() {256 } else if let Some((&snap_f, snap_state)) = cached.snapshots.range(..=target_frame).next_back() {
256 cached.state = snap_state.clone();257 if i128::from(target_frame) - i128::from(snap_f) <= i128::from(MAX_SIM_WINDOW) {
257 cached.current_frame = snap_f;258 cached.state = snap_state.clone();
258 for f in (snap_f + 1)..=target_frame {259 cached.current_frame = snap_f;
259 step_simulation(&mut cached.state, comp, &plan, f, expr);260 if snap_f < target_frame {
260 maybe_record_snapshot(cached, f);261 for f in snap_f.saturating_add(1)..=target_frame {
262 step_simulation(&mut cached.state, comp, &plan, f, expr);
263 maybe_record_snapshot(cached, f);
264 }
265 }
266 cached.current_frame = target_frame;
267 false
268 } else {
269 true
261 }270 }
262 cached.current_frame = target_frame;
263 false
264 } else {271 } else {
265 true272 true
266 }273 }
crates/engine/src/particles/sim.rs+10-7
...@@ -894,14 +894,17 @@ fn value_noise_3d(x: f64, y: f64, z: f64, seed: u64) -> f64 {...@@ -894,14 +894,17 @@ fn value_noise_3d(x: f64, y: f64, z: f64, seed: u64) -> f64 {
894 let v = yf * yf * (3.0 - 2.0 * yf);894 let v = yf * yf * (3.0 - 2.0 * yf);
895 let w = zf * zf * (3.0 - 2.0 * zf);895 let w = zf * zf * (3.0 - 2.0 * zf);
896896
897 let xi1 = xi.wrapping_add(1);
898 let yi1 = yi.wrapping_add(1);
899 let zi1 = zi.wrapping_add(1);
897 let n000 = lattice_hash(xi, yi, zi, seed);900 let n000 = lattice_hash(xi, yi, zi, seed);
898 let n100 = lattice_hash(xi + 1, yi, zi, seed);901 let n100 = lattice_hash(xi1, yi, zi, seed);
899 let n010 = lattice_hash(xi, yi + 1, zi, seed);902 let n010 = lattice_hash(xi, yi1, zi, seed);
900 let n110 = lattice_hash(xi + 1, yi + 1, zi, seed);903 let n110 = lattice_hash(xi1, yi1, zi, seed);
901 let n001 = lattice_hash(xi, yi, zi + 1, seed);904 let n001 = lattice_hash(xi, yi, zi1, seed);
902 let n101 = lattice_hash(xi + 1, yi, zi + 1, seed);905 let n101 = lattice_hash(xi1, yi, zi1, seed);
903 let n011 = lattice_hash(xi, yi + 1, zi + 1, seed);906 let n011 = lattice_hash(xi, yi1, zi1, seed);
904 let n111 = lattice_hash(xi + 1, yi + 1, zi + 1, seed);907 let n111 = lattice_hash(xi1, yi1, zi1, seed);
905908
906 let nx00 = n000 + (n100 - n000) * u;909 let nx00 = n000 + (n100 - n000) * u;
907 let nx10 = n010 + (n110 - n010) * u;910 let nx10 = n010 + (n110 - n010) * u;
crates/engine/src/ram_cache.rs+9-3
...@@ -681,11 +681,14 @@ impl RamPrefetcher {...@@ -681,11 +681,14 @@ impl RamPrefetcher {
681 engine.hiq = job.hiq;681 engine.hiq = job.hiq;
682 engine.use_proxy_clips = job.use_proxy_clips;682 engine.use_proxy_clips = job.use_proxy_clips;
683683
684 if job.target.0 >= job.comp.nodes.len() {
685 continue;
686 }
684 busy.store(true, Ordering::Release);687 busy.store(true, Ordering::Release);
685 let start = job.range[0].min(job.range[1]);688 let start = job.range[0].min(job.range[1]);
686 let end = job.range[0].max(job.range[1]);689 let end = job.range[0].max(job.range[1]);
687 let span = (end - start + 1).max(1);690 let span = (i128::from(end) - i128::from(start) + 1).max(1);
688 let count = job.lookahead.max(0).min(span);691 let count = i128::from(job.lookahead.max(0)).min(span).min(i128::from(i64::MAX)) as i64;
689692
690 let is_cancelled = || {693 let is_cancelled = || {
691 shutdown.load(Ordering::Acquire)694 shutdown.load(Ordering::Acquire)
...@@ -708,7 +711,10 @@ impl RamPrefetcher {...@@ -708,7 +711,10 @@ impl RamPrefetcher {
708 let mut chunk_items = Vec::with_capacity((chunk_end - chunk_start + 1) as usize);711 let mut chunk_items = Vec::with_capacity((chunk_end - chunk_start + 1) as usize);
709 let mut batch_frames = Vec::with_capacity((chunk_end - chunk_start + 1) as usize);712 let mut batch_frames = Vec::with_capacity((chunk_end - chunk_start + 1) as usize);
710 for offset in chunk_start..=chunk_end {713 for offset in chunk_start..=chunk_end {
711 let f = start + (job.center_frame - start + offset).rem_euclid(span);714 let f_i128 = i128::from(start)
715 + (i128::from(job.center_frame) - i128::from(start) + i128::from(offset))
716 .rem_euclid(span);
717 let f = f_i128 as i64;
712 let key = RamFrameKey {718 let key = RamFrameKey {
713 target: job.target,719 target: job.target,
714 revision: job.comp.revision,720 revision: job.comp.revision,
crates/engine/src/scene3d/collect.rs+17-7
...@@ -117,7 +117,8 @@ fn collect_scene_inner(...@@ -117,7 +117,8 @@ fn collect_scene_inner(
117 visited: &mut Vec<NodeId>,117 visited: &mut Vec<NodeId>,
118 depth: usize,118 depth: usize,
119) {119) {
120 if depth > 32 {120 const MAX_SCENE_MESHES: usize = 16_384;
121 if depth > 32 || node_id.0 >= comp.nodes.len() || meshes.len() >= MAX_SCENE_MESHES {
121 return;122 return;
122 }123 }
123 visited.push(node_id);124 visited.push(node_id);
...@@ -230,7 +231,7 @@ fn collect_scene_inner(...@@ -230,7 +231,7 @@ fn collect_scene_inner(
230 }231 }
231 let first = comp.eval_number(node, "FirstCopy", time, 0.0, expr).round() as i32;232 let first = comp.eval_number(node, "FirstCopy", time, 0.0, expr).round() as i32;
232 let last = comp.eval_number(node, "LastCopy", time, 2.0, expr).round() as i32;233 let last = comp.eval_number(node, "LastCopy", time, 2.0, expr).round() as i32;
233 let count = (last - first).clamp(0, 256);234 let count = (i64::from(last) - i64::from(first)).clamp(0, 256) as i32;
234 if count == 0 {235 if count == 0 {
235 return;236 return;
236 }237 }
...@@ -261,13 +262,22 @@ fn collect_scene_inner(...@@ -261,13 +262,22 @@ fn collect_scene_inner(
261 + jsx.abs() + jsy.abs() + jsz.abs()) > 1e-5;262 + jsx.abs() + jsy.abs() + jsz.abs()) > 1e-5;
262263
263 let mut acc = mat4_identity();264 let mut acc = mat4_identity();
264 if !is_linear {265 if !is_linear && first > 0 {
265 for _ in 0..first.max(0) {266 let mut exp = first as u32;
266 acc = mat4_mul(acc, step);267 let mut base = step;
268 while exp > 0 {
269 if (exp & 1) != 0 {
270 acc = mat4_mul(acc, base);
271 }
272 exp >>= 1;
273 if exp > 0 {
274 base = mat4_mul(base, base);
275 }
267 }276 }
268 }277 }
269 for i in 0..count {278 for i in 0..count {
270 let copy_idx = (first + i) as u64;279 let copy_i64 = i64::from(first) + i64::from(i);
280 let copy_idx = copy_i64 as u64;
271 let s = seed.wrapping_mul(6364136223846793005).wrapping_add(copy_idx.wrapping_mul(1442695040888963407));281 let s = seed.wrapping_mul(6364136223846793005).wrapping_add(copy_idx.wrapping_mul(1442695040888963407));
272 if copy_prob < 0.9999 && (splitmix64(s ^ 13) + 0.5) > copy_prob {282 if copy_prob < 0.9999 && (splitmix64(s ^ 13) + 0.5) > copy_prob {
273 if !is_linear {283 if !is_linear {
...@@ -276,7 +286,7 @@ fn collect_scene_inner(...@@ -276,7 +286,7 @@ fn collect_scene_inner(
276 continue;286 continue;
277 }287 }
278 let base_m = if is_linear {288 let base_m = if is_linear {
279 dup_params.matrix_for_step((first + i) as f32, true)289 dup_params.matrix_for_step(copy_i64 as f32, true)
280 } else {290 } else {
281 acc291 acc
282 };292 };
crates/engine/src/text_engine.rs+1-1
...@@ -785,7 +785,7 @@ fn size_metrics(face: &Face<'_>, size_norm: f32, canvas_w: f32) -> (f32, f32, f3...@@ -785,7 +785,7 @@ fn size_metrics(face: &Face<'_>, size_norm: f32, canvas_w: f32) -> (f32, f32, f3
785fn layout_glyph_specs(dims: [u32; 2], params: &RichTextPlusParams<'_>) -> Option<(Vec<GlyphSpec>, usize)> {785fn layout_glyph_specs(dims: [u32; 2], params: &RichTextPlusParams<'_>) -> Option<(Vec<GlyphSpec>, usize)> {
786 let [w, h] = dims;786 let [w, h] = dims;
787 let total_chars = params.text.chars().count();787 let total_chars = params.text.chars().count();
788 if total_chars == 0 || params.size_norm <= 1e-4 {788 if total_chars == 0 || !params.size_norm.is_finite() || params.size_norm <= 1e-4 {
789 return None;789 return None;
790 }790 }
791 let c_start = (params.write_on_start.clamp(0.0, 1.0) * total_chars as f32).floor() as usize;791 let c_start = (params.write_on_start.clamp(0.0, 1.0) * total_chars as f32).floor() as usize;
crates/engine/tests/hardening_engine.rs created+537
...@@ -0,0 +1,537 @@
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}