diff --git a/crates/engine/src/audio.rs b/crates/engine/src/audio.rs index 2d160542eb03f36c851688aeb78ead5c31cc7678..38ba84550bbdf3c9cba428cda21448a1a52d8abc 100644 --- a/crates/engine/src/audio.rs +++ b/crates/engine/src/audio.rs @@ -471,11 +471,25 @@ impl AudioTrack { start_frame: i64, end_frame: i64, ) -> Vec { - if end_frame < start_frame || fps <= 0.0 || self.sample_rate == 0 { + const MAX_WAVEFORM_PEAKS: usize = 10_000_000; + if end_frame < start_frame + || !fps.is_finite() + || fps <= 0.0 + || !offset_frames.is_finite() + || self.sample_rate == 0 + { return Vec::new(); } - let count = (end_frame - start_frame + 1) as usize; - let mut peaks = vec![0.0_f32; count]; + let span = i128::from(end_frame) - i128::from(start_frame) + 1; + if span <= 0 || span > MAX_WAVEFORM_PEAKS as i128 { + return Vec::new(); + } + let count = span as usize; + let mut peaks = Vec::new(); + if peaks.try_reserve_exact(count).is_err() { + return Vec::new(); + } + peaks.resize(count, 0.0_f32); let total_frames = self.samples.len() / 2; if total_frames == 0 { return peaks; @@ -483,10 +497,10 @@ impl AudioTrack { let sr = self.sample_rate as f64; for (i, peak_out) in peaks.iter_mut().enumerate() { - let f = start_frame + i as i64; - let t0 = (f as f64 - offset_frames) / fps; - let t1 = ((f + 1) as f64 - offset_frames) / fps; - if t1 <= 0.0 { + let f = start_frame as f64 + i as f64; + let t0 = (f - offset_frames) / fps; + let t1 = ((f + 1.0) - offset_frames) / fps; + if !t0.is_finite() || !t1.is_finite() || t1 <= 0.0 { continue; } let s0 = (t0.max(0.0) * sr).floor() as usize; @@ -715,7 +729,7 @@ impl AudioPlayer { } pub fn set_volume(&mut self, vol: f32) { - let clamped = vol.clamp(0.0, 2.0); + let clamped = if vol.is_finite() { vol.clamp(0.0, 2.0) } else { 0.0 }; self.state .volume_bits .store(clamped.to_bits(), Ordering::Relaxed); @@ -766,11 +780,18 @@ fn sample_track_stereo( t_sec: f64, gain: f32, ) -> (f32, f32) { - if total_frames == 0 || t_sec < 0.0 || gain <= 0.0 { + if total_frames == 0 + || !t_sec.is_finite() + || t_sec < 0.0 + || !gain.is_finite() + || gain <= 0.0 + || !track_sr.is_finite() + || track_sr <= 0.0 + { return (0.0, 0.0); } let src_pos = t_sec * track_sr; - if src_pos >= total_frames as f64 { + if !src_pos.is_finite() || src_pos < 0.0 || src_pos >= total_frames as f64 { return (0.0, 0.0); } let idx0 = src_pos.floor() as usize; diff --git a/crates/engine/src/cryptomatte.rs b/crates/engine/src/cryptomatte.rs index 15463625d6fd55eedaa53163db86c2aab9413ef6..7d1e00cb2205b30ef6ea5dae80a3070bcebe61ce 100644 --- a/crates/engine/src/cryptomatte.rs +++ b/crates/engine/src/cryptomatte.rs @@ -678,11 +678,25 @@ pub fn extract_cryptomatte( } let (w, h) = dims?; - let pixel_count = w * h; + const MAX_CRYPTO_PIXELS: usize = 64 * 1024 * 1024; + const MAX_CRYPTO_BYTES: usize = 512 * 1024 * 1024; + let pixel_count = w.checked_mul(h)?; + if w > u32::MAX as usize || h > u32::MAX as usize || pixel_count > MAX_CRYPTO_PIXELS { + return None; + } + let total_slot_bytes = pixel_count + .checked_mul(matched_channels.len().max(1))? + .checked_mul(std::mem::size_of::())?; + if total_slot_bytes > MAX_CRYPTO_BYTES { + return None; + } if target_ids.is_empty() { + let mut matte = Vec::new(); + matte.try_reserve_exact(pixel_count).ok()?; + matte.resize(pixel_count, 0.0_f32); return Some(CryptomatteResult { size: [w as u32, h as u32], - matte: vec![0.0_f32; pixel_count], + matte, }); } @@ -691,7 +705,10 @@ pub fn extract_cryptomatte( HashMap::with_capacity(matched_channels.len()); for (loc, rank, comp_idx) in matched_channels { let idx = slot_buffers.len(); - slot_buffers.push((rank, comp_idx, vec![0.0_f32; pixel_count])); + let mut buf = Vec::new(); + buf.try_reserve_exact(pixel_count).ok()?; + buf.resize(pixel_count, 0.0_f32); + slot_buffers.push((rank, comp_idx, buf)); loc_to_slot.insert(loc, idx); } @@ -713,7 +730,7 @@ pub fn extract_cryptomatte( let y = line.location.position.y(); let x0 = line.location.position.x(); let len = line.location.sample_count; - if y >= h || x0 + len > w { + if y >= h || x0.saturating_add(len) > w { continue; } let row_base = y * w + x0; diff --git a/crates/engine/src/eval/blur_glow.rs b/crates/engine/src/eval/blur_glow.rs index ad50c82abb3c0162cc49913e21fe8d984d2702c6..0ac4ec04aea642d33457fe29924f071f8166caa2 100644 --- a/crates/engine/src/eval/blur_glow.rs +++ b/crates/engine/src/eval/blur_glow.rs @@ -1228,7 +1228,7 @@ impl Engine { let animated = comp.eval_number(node, "Animated", time, 1.0, &self.expr) > 0.5; // Only Noise and Grain read the seed; zeroing it elsewhere lets static filters hit the cache. let seed = match ftype { - 5 | 6 if animated => seed_base.wrapping_add(frame_i as i32 * 101), + 5 | 6 if animated => seed_base.wrapping_add((frame_i as i32).wrapping_mul(101)), 5 | 6 => seed_base, _ => 0, }; diff --git a/crates/engine/src/eval/io.rs b/crates/engine/src/eval/io.rs index d9db7618930f4313b66f0a3da0ca2f0e0ba33567..214f092829163258862d831dee1ff90e11f28345 100644 --- a/crates/engine/src/eval/io.rs +++ b/crates/engine/src/eval/io.rs @@ -243,9 +243,9 @@ impl Engine { // playback past `GlobalEnd`), Fusion outputs no image regardless of `MissingFrames` or // whether `Length == 1` (even single-frame stills return empty outside their active range). let out_of_range = effective_clip.global_end >= effective_clip.global_start - && (frame_i < effective_clip.global_start - effective_clip.extend_first.max(0) + && (frame_i < effective_clip.global_start.saturating_sub(effective_clip.extend_first.max(0)) || (!effective_clip.loop_clip - && frame_i > effective_clip.global_end + effective_clip.extend_last.max(0))); + && frame_i > effective_clip.global_end.saturating_add(effective_clip.extend_last.max(0)))); let loaded = if out_of_range { None } else { @@ -1026,8 +1026,8 @@ impl Engine { let x1 = (dr.max(1.0) * cw).ceil() as i32; let y0 = ((1.0 - dt.max(1.0)) * ch).floor() as i32; let y1 = ((1.0 - db.min(0.0)) * ch).ceil() as i32; - let w = (x1 - x0).clamp(1, 8192) as u32; - let h = (y1 - y0).clamp(1, 8192) as u32; + let w = x1.saturating_sub(x0).clamp(1, 8192) as u32; + let h = y1.saturating_sub(y0).clamp(1, 8192) as u32; ([x0, y0], [w, h]) } else { ([0, 0], src.canvas_size) diff --git a/crates/engine/src/eval/mod.rs b/crates/engine/src/eval/mod.rs index 604c626ce8ae8efea47728747597c6dc53295f9c..e9ee157f33cc2da61fdaea8206d641d49462bc70 100644 --- a/crates/engine/src/eval/mod.rs +++ b/crates/engine/src/eval/mod.rs @@ -551,6 +551,10 @@ impl Engine { visiting: &mut HashSet<(NodeId, i64)>, stats: &mut EvalStats, ) -> CachedTexture { + const MAX_EVAL_DEPTH: usize = 256; + if id.0 >= comp.nodes.len() || visiting.len() >= MAX_EVAL_DEPTH { + return self.dummy.clone(); + } let frame_i = time.round() as i64; let time_key = (if time == 0.0 { 0.0 } else { time }).to_bits() as i64; let memo_sz = self.mask_target_size; diff --git a/crates/engine/src/eval/paint.rs b/crates/engine/src/eval/paint.rs index 754cd5795aca2198d26df6b24695e8a9ba9a4d5c..3ee60470c8d09df3f5de91b3c3eaa9e571f4af03 100644 --- a/crates/engine/src/eval/paint.rs +++ b/crates/engine/src/eval/paint.rs @@ -176,9 +176,10 @@ fn stroke_style( /// Brush stamp positions along `path` (pixels) between the `write_on` fractions of its arclength. fn stamp_positions(path: &[[f32; 2]], write_on: [f32; 2], spacing: f32) -> Vec<[f32; 2]> { + const MAX_STAMPS_PER_STROKE: usize = 65_536; let Some(&first) = path.first() else { return Vec::new() }; let [start, end] = write_on.map(|v| v.clamp(0.0, 1.0)); - if end <= start { + if !start.is_finite() || !end.is_finite() || end <= start { return Vec::new(); } let mut cum = vec![0.0f32]; @@ -186,15 +187,18 @@ fn stamp_positions(path: &[[f32; 2]], write_on: [f32; 2], spacing: f32) -> Vec<[ cum.push(cum.last().unwrap() + (w[1][0] - w[0][0]).hypot(w[1][1] - w[0][1])); } let total = *cum.last().unwrap(); + if !total.is_finite() { + return Vec::new(); + } if total < 1e-4 { - return vec![first]; + return if first[0].is_finite() && first[1].is_finite() { vec![first] } else { Vec::new() }; } let (d0, d1) = (start * total, end * total); let span = d1 - d0; - if span <= 1e-4 { + if !span.is_finite() || span <= 1e-4 { return Vec::new(); } - let n = (span / spacing).round().max(1.0) as usize; + let n = ((span / spacing.max(1e-4)).round().max(1.0) as usize).min(MAX_STAMPS_PER_STROKE); let step = span / n as f32; (0..=n) .map(|k| { @@ -349,7 +353,9 @@ impl Engine { visiting: &mut HashSet<(NodeId, i64)>, stats: &mut EvalStats, ) -> CachedTexture { - let size = self.explicit_mask_size(comp, node, time, comp_dims); + let raw_size = self.explicit_mask_size(comp, node, time, comp_dims); + let max_dim = self.device.limits().max_texture_dimension_2d.max(1); + let (size, tex_scale) = crate::cache::clamp_dims_to_limit(raw_size[0], raw_size[1], max_dim); let soft = comp.eval_number(node, "SoftEdge", time, 0.0, &self.expr).max(0.0) as f32; let invert = comp.eval_number(node, "Invert", time, 0.0, &self.expr) > 0.5; let level = comp.eval_number(node, "Level", time, 1.0, &self.expr) as f32; @@ -380,7 +386,8 @@ impl Engine { level, prev: prev_mask.as_ref(), }; - let tex = self.upload_cpu_mask(enc, size, key, &pixels, Some(post)); + let mut tex = self.upload_cpu_mask(enc, size, key, &pixels, Some(post)); + tex.tex_scale = tex_scale; self.cache.insert(key, tex.clone(), node.id, frame_i); tex } diff --git a/crates/engine/src/eval/text_3d.rs b/crates/engine/src/eval/text_3d.rs index 1abbc08927913975a93a313328b78695f564a131..150fc8b03cabfb181fe1960643df7d0697b02b44 100644 --- a/crates/engine/src/eval/text_3d.rs +++ b/crates/engine/src/eval/text_3d.rs @@ -593,7 +593,8 @@ impl Engine { let ext_max = ti.border_ext_h.abs().max(ti.border_ext_v.abs()) * size_px; let off_max = (ti.border_offset[0].abs() * size[0] as f32) .max(ti.border_offset[1].abs() * size[1] as f32); - (0.45 * size_px + ext_max + off_max).ceil() as i32 + 4 + let pad = 0.45 * size_px + ext_max + off_max; + if pad.is_finite() { (pad.ceil() as i32).saturating_add(4) } else { 0 } } else { 0 }; @@ -769,10 +770,10 @@ impl Engine { let hw = (0.5 * (b[2] - b[0])).max(0.5); let hh = (0.5 * (b[3] - b[1])).max(0.5); let rad = (border_round * hh).min(hw.min(hh)); - let ix0 = (b[0].floor() as i32 - 1).clamp(0, tw as i32 - 1) as usize; - let ix1 = (b[2].ceil() as i32 + 1).clamp(0, tw as i32 - 1) as usize; - let iy0 = (b[1].floor() as i32 - 1).clamp(0, th as i32 - 1) as usize; - let iy1 = (b[3].ceil() as i32 + 1).clamp(0, th as i32 - 1) as usize; + let ix0 = (b[0].floor() as i32).saturating_sub(1).clamp(0, tw as i32 - 1) as usize; + let ix1 = (b[2].ceil() as i32).saturating_add(1).clamp(0, tw as i32 - 1) as usize; + let iy0 = (b[1].floor() as i32).saturating_sub(1).clamp(0, th as i32 - 1) as usize; + let iy1 = (b[3].ceil() as i32).saturating_add(1).clamp(0, th as i32 - 1) as usize; for yy in iy0..=iy1 { let py = yy as f32 + 0.5 - cy; let qy = py.abs() - (hh - rad); @@ -915,7 +916,9 @@ impl Engine { let selected_camera = cameras.iter().find(|c| c.name == selector).or(cameras.first()); let (view, mut proj, cam_pos, cam_far) = if let Some(cam) = selected_camera { - if cam.near >= cam.far || (!cam.orthographic && cam.near <= 0.0) { + let bad_clip = !(cam.near.is_finite() && cam.far.is_finite() && cam.near < cam.far) + || (!cam.orthographic && (cam.near <= 0.0 || !cam.vfov_rad.is_finite() || cam.vfov_rad <= 0.0 || cam.vfov_rad >= std::f32::consts::PI)); + if bad_clip { let mut empty = create_texture(&self.device, size, 0); empty.tex_scale = tex_scale; return empty; diff --git a/crates/engine/src/eval/warps.rs b/crates/engine/src/eval/warps.rs index e0cfc711523fa482249a522091495255ffbae0ba..2334269d8d660231d56787d264b491e60e95c65e 100644 --- a/crates/engine/src/eval/warps.rs +++ b/crates/engine/src/eval/warps.rs @@ -806,6 +806,9 @@ struct CoonsPt { fn mesh_coons_cells(mesh: &model::comp::GridMesh) -> Vec<[CoonsPt; 4]> { let cols = mesh.cols; let rows = mesh.rows; + if cols < 2 || rows < 2 || mesh.points.len() < cols.saturating_mul(rows) { + return Vec::new(); + } let dc = (mesh.delta_c as f32) / 3.0; let dr = (mesh.delta_r as f32) / 3.0; let pts: Vec = mesh diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 357ded683f6ed4504b0310afbdcaf0a2aa71ac73..17515a0c55e42ee89a4b50c400b0c8750548d7bd 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -271,7 +271,8 @@ pub fn export_saver_png_sequence_with_progress( let saver = select_saver(comp, opts.saver_name.as_deref())?; let target: NodeId = saver.upstream.unwrap_or(saver.node_id); let [start, end] = opts.range_override.unwrap_or(saver.range); - if end < start { + let total_i128 = i128::from(end) - i128::from(start) + 1; + if end < start || total_i128 <= 0 || total_i128 > i128::from(u32::MAX) { return Err(format!("invalid export frame range {start}..={end}")); } @@ -280,7 +281,7 @@ pub fn export_saver_png_sequence_with_progress( engine.hiq = opts.hiq; engine.proxy_scale = opts.proxy_scale.max(1); - let total = (end - start + 1) as usize; + let total = total_i128 as usize; let workers = if opts.png_workers > 0 { opts.png_workers.clamp(1, 24) } else { @@ -348,16 +349,19 @@ pub fn export_saver_png_sequence_with_progress( const PREFETCH_LOOKAHEAD: usize = 12; engine.prewarm_for_depth(comp.depth_full); let prefetch = engine.media.start_frame_prefetch(PREFETCH_LOOKAHEAD); - let seed_end = (start + PREFETCH_LOOKAHEAD as i64 - 1).min(end); - for (k, f) in ((start + 1)..=seed_end).enumerate() { - prefetch.enqueue_frame( - comp, - target, - k + 1, - f as f64, - &engine.expr, - engine.use_proxy_clips, - ); + if start < end { + let seed_start = start.saturating_add(1); + let seed_end = start.saturating_add(PREFETCH_LOOKAHEAD as i64 - 1).min(end); + for (k, f) in (seed_start..=seed_end).enumerate() { + prefetch.enqueue_frame( + comp, + target, + k + 1, + f as f64, + &engine.expr, + engine.use_proxy_clips, + ); + } } // Double-buffered async GPU readback: frame N+1 evaluates/submits on GPU while // 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( break; } prefetch.set_current_seq(idx); - let ahead_frame = frame + PREFETCH_LOOKAHEAD as i64; - if ahead_frame <= end { - prefetch.enqueue_frame( - comp, - target, - idx + PREFETCH_LOOKAHEAD, - ahead_frame as f64, - &engine.expr, - engine.use_proxy_clips, - ); + if let Some(ahead_frame) = frame.checked_add(PREFETCH_LOOKAHEAD as i64) { + if ahead_frame <= end { + prefetch.enqueue_frame( + comp, + target, + idx + PREFETCH_LOOKAHEAD, + ahead_frame as f64, + &engine.expr, + engine.use_proxy_clips, + ); + } } let out_path = match resolve_output_path(&saver, frame, opts.out_dir_override.as_deref()) { Ok(p) => p, @@ -954,7 +959,8 @@ pub fn export_node_video_ffmpeg_with_progress( return Err("Cancelled".to_owned()); } let [start, end] = opts.range; - if end < start { + let total_i128 = i128::from(end) - i128::from(start) + 1; + if end < start || total_i128 <= 0 || total_i128 > i128::from(u32::MAX) { return Err(format!("invalid export frame range {start}..={end}")); } if opts.target.0 >= comp.nodes.len() { @@ -1248,8 +1254,9 @@ fn export_node_video_ffmpeg_with_encoder( } else if start < end { const PREFETCH_LOOKAHEAD: usize = 12; let prefetch = engine.media.start_frame_prefetch(PREFETCH_LOOKAHEAD); - let seed_end = (start + PREFETCH_LOOKAHEAD as i64).min(end); - for (k, f) in ((start + 1)..=seed_end).enumerate() { + let seed_start = start.saturating_add(1); + let seed_end = start.saturating_add(PREFETCH_LOOKAHEAD as i64).min(end); + for (k, f) in (seed_start..=seed_end).enumerate() { prefetch.enqueue_frame( comp, opts.target, @@ -1260,7 +1267,7 @@ fn export_node_video_ffmpeg_with_encoder( ); } let mut pending: Option<(crate::eval::PendingReadback, i64, usize, [u32; 2], f64)> = None; - for (idx, frame) in ((start + 1)..=end).enumerate() { + for (idx, frame) in (seed_start..=end).enumerate() { if control.is_some_and(ExportControl::is_cancelled) { cancelled = true; break; @@ -1269,16 +1276,17 @@ fn export_node_video_ffmpeg_with_encoder( break; } prefetch.set_current_seq(idx); - let ahead_frame = frame + PREFETCH_LOOKAHEAD as i64; - if ahead_frame <= end { - prefetch.enqueue_frame( - comp, - opts.target, - idx + PREFETCH_LOOKAHEAD, - ahead_frame as f64, - &engine.expr, - engine.use_proxy_clips, - ); + if let Some(ahead_frame) = frame.checked_add(PREFETCH_LOOKAHEAD as i64) { + if ahead_frame <= end { + prefetch.enqueue_frame( + comp, + opts.target, + idx + PREFETCH_LOOKAHEAD, + ahead_frame as f64, + &engine.expr, + engine.use_proxy_clips, + ); + } } let (tex, stats) = engine.evaluate(comp, opts.target, frame as f64); let next_rb = match engine.begin_readback_rgba(&tex) { diff --git a/crates/engine/src/media.rs b/crates/engine/src/media.rs index b05a6ac7753697536969cb7e4edc619a0165fc00..834ad35ba3e2d72c732aa8f209afa8e203be4165 100644 --- a/crates/engine/src/media.rs +++ b/crates/engine/src/media.rs @@ -1950,13 +1950,40 @@ fn collect_missing_loader_jobs_shared( visited: &mut HashSet<(NodeId, i64)>, jobs: &mut MissingJobs, ) { - if node_id.0 >= comp.nodes.len() { + const MAX_PRELOAD_DEPTH: usize = 256; + if node_id.0 >= comp.nodes.len() || jobs.depth >= MAX_PRELOAD_DEPTH { return; } let time_key = (if time == 0.0 { 0.0 } else { time }).to_bits() as i64; if !visited.insert((node_id, time_key)) { return; } + jobs.depth += 1; + collect_missing_loader_jobs_inner( + shared, + comp, + node_id, + time, + expr, + use_proxy_clips, + visited, + jobs, + ); + jobs.depth -= 1; +} + +#[cfg(not(target_arch = "wasm32"))] +#[allow(clippy::too_many_arguments)] +fn collect_missing_loader_jobs_inner( + shared: &MediaShared, + comp: &Comp, + node_id: NodeId, + time: f64, + expr: &model::ExprEngine, + use_proxy_clips: bool, + visited: &mut HashSet<(NodeId, i64)>, + jobs: &mut MissingJobs, +) { let node = comp.node(node_id); if node.bypassed @@ -2252,9 +2279,9 @@ fn collect_missing_loader_jobs_shared( } } let out_of_range = effective_clip.global_end >= effective_clip.global_start - && (frame_i < effective_clip.global_start - effective_clip.extend_first.max(0) + && (frame_i < effective_clip.global_start.saturating_sub(effective_clip.extend_first.max(0)) || (!effective_clip.loop_clip - && frame_i > effective_clip.global_end + effective_clip.extend_last.max(0))); + && frame_i > effective_clip.global_end.saturating_add(effective_clip.extend_last.max(0)))); if !out_of_range { let base = Path::new(&effective_clip.filename); if is_video_path(base) { @@ -2378,8 +2405,8 @@ fn video_frame_in_range(clip: &ClipSpec, frame: i64) -> bool { if clip.global_end >= clip.global_start && (clip.length.unwrap_or(0) > 1 || clip.global_end > clip.global_start) { - let min_f = clip.global_start - clip.extend_first.max(0); - let max_f = clip.global_end + clip.extend_last.max(0); + let min_f = clip.global_start.saturating_sub(clip.extend_first.max(0)); + let max_f = clip.global_end.saturating_add(clip.extend_last.max(0)); if frame < min_f || (!clip.loop_clip && frame > max_f) { return false; } @@ -2395,13 +2422,14 @@ fn compute_video_frame_idx(clip: &ClipSpec, frame: i64, nb_frames: i64) -> i64 { } else { len - 1 }; - let span = (trim_out - trim_in + 1).max(1); + let span = trim_out.saturating_sub(trim_in).saturating_add(1).max(1); + let delta = frame.saturating_sub(clip.global_start); let rel = if clip.loop_clip { - (frame - clip.global_start).max(0).rem_euclid(span) + delta.max(0).rem_euclid(span) } else { - (frame - clip.global_start).clamp(0, span - 1) + delta.clamp(0, span - 1) }; - if clip.reverse { trim_out - rel } else { trim_in + rel } + if clip.reverse { trim_out.saturating_sub(rel) } else { trim_in.saturating_add(rel) } } #[cfg(not(target_arch = "wasm32"))] @@ -2410,6 +2438,7 @@ struct MissingJobs { raster: Vec, seen_raster: HashSet, videos: HashMap>, + depth: usize, } #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/engine/src/media/exr.rs b/crates/engine/src/media/exr.rs index 40840d072e927826d139f4cac84079e46cb498fb..2ceb7f0e259bb7dd7c5461d57bae55da424d6d84 100644 --- a/crates/engine/src/media/exr.rs +++ b/crates/engine/src/media/exr.rs @@ -321,9 +321,12 @@ fn decode_exr_from( let first_header = chunks_reader.headers().first()?; let w = first_header.layer_size.width(); let h = first_header.layer_size.height(); - if w == 0 || h == 0 { + const MAX_EXR_PIXELS: usize = 64 * 1024 * 1024; + let pixel_count = w.checked_mul(h)?; + if w == 0 || h == 0 || w > u32::MAX as usize || h > u32::MAX as usize || pixel_count > MAX_EXR_PIXELS { return None; } + let elem_count = pixel_count.checked_mul(4)?; let r_loc = find_exr_channel_loc(chunks_reader.headers(), w, h, red_name, "R", "r")?; let g_loc = find_exr_channel_loc(chunks_reader.headers(), w, h, green_name, "G", "g"); @@ -335,7 +338,9 @@ fn decode_exr_from( needed_layers.sort_unstable(); needed_layers.dedup(); - let mut raw_f32 = vec![0.0_f32; w * h * 4]; + let mut raw_f32 = Vec::new(); + raw_f32.try_reserve_exact(elem_count).ok()?; + raw_f32.resize(elem_count, 0.0_f32); let mut line_f32 = Vec::::new(); let mut line_f16 = Vec::::new(); let mut line_u32 = Vec::::new(); @@ -361,7 +366,7 @@ fn decode_exr_from( let y = line.location.position.y(); let x0 = line.location.position.x(); let len = line.location.sample_count; - if y >= h || x0 + len > w { + if y >= h || x0.saturating_add(len) > w { continue; } @@ -402,8 +407,12 @@ fn decode_exr_from( filtered.decompress_sequential(false, insert_block).ok()?; } - let mut raw = vec![0u8; w * h * 4]; - let mut raw_f16 = vec![0u16; w * h * 4]; + let mut raw = Vec::new(); + raw.try_reserve_exact(elem_count).ok()?; + raw.resize(elem_count, 0u8); + let mut raw_f16 = Vec::new(); + raw_f16.try_reserve_exact(elem_count).ok()?; + raw_f16.resize(elem_count, 0u16); convert_exr_rgba_buffers( &mut raw_f32, &mut raw_f16, diff --git a/crates/engine/src/media/raster.rs b/crates/engine/src/media/raster.rs index 46f6125aefd5bc406d9b54794e3b914c3dba6282..d3d3e08746c3f39064de86439b2b664d318f60ca 100644 --- a/crates/engine/src/media/raster.rs +++ b/crates/engine/src/media/raster.rs @@ -27,7 +27,7 @@ pub struct TextPlusParams<'a> { pub fn rasterize_text_plus(dims: [u32; 2], params: &TextPlusParams<'_>, dod_pad: i32) -> ([u32; 2], [i32; 2], Vec) { let [w, h] = dims; let empty = || (dims, [0, 0], vec![0u8; (w as usize) * (h as usize) * 4]); - if params.text.is_empty() || params.size_norm <= 1e-4 { + if params.text.is_empty() || !params.size_norm.is_finite() || params.size_norm <= 1e-4 { return empty(); } @@ -48,7 +48,7 @@ pub fn rasterize_text_plus(dims: [u32; 2], params: &TextPlusParams<'_>, dod_pad: let mut cls_dy = vec![0.0_f32; total_chars]; for e in params.cls { let s = e.start.min(total_chars); - let end = (e.end + 1).min(total_chars); + let end = e.end.saturating_add(1).min(total_chars); for i in s..end { if e.prop_id == 1350 { cls_dx[i] = e.value; @@ -90,10 +90,10 @@ pub fn rasterize_text_plus(dims: [u32; 2], params: &TextPlusParams<'_>, dod_pad: let mut placed = Vec::new(); let (mut min_x, mut min_y, mut max_x, mut max_y) = (0i32, 0i32, w as i32, h as i32); let mut grow = |c: &text_engine::Coverage, pad: i32| { - min_x = min_x.min(c.left - pad); - min_y = min_y.min(c.top - pad); - max_x = max_x.max(c.left + c.width as i32 + pad); - max_y = max_y.max(c.top + c.height as i32 + pad); + min_x = min_x.min(c.left.saturating_sub(pad)); + min_y = min_y.min(c.top.saturating_sub(pad)); + max_x = max_x.max(c.left.saturating_add(c.width as i32).saturating_add(pad)); + max_y = max_y.max(c.top.saturating_add(c.height as i32).saturating_add(pad)); }; let mut char_cursor = 0usize; diff --git a/crates/engine/src/particles.rs b/crates/engine/src/particles.rs index b7b0bc9f378810073ceea970660c1c510ef699df..78309e13ca226305d3c61ff24dcc2a38c19a5109 100644 --- a/crates/engine/src/particles.rs +++ b/crates/engine/src/particles.rs @@ -170,7 +170,8 @@ impl SplitMix64 { } fn maybe_record_snapshot(cached: &mut CachedSim, frame: i64) { - if (frame - cached.base_start).rem_euclid(SNAPSHOT_INTERVAL) == 0 { + let delta = i128::from(frame) - i128::from(cached.base_start); + if delta.rem_euclid(i128::from(SNAPSHOT_INTERVAL)) == 0 { cached.snapshots.insert(frame, cached.state.clone()); while cached.snapshots.len() > MAX_SNAPSHOTS { if let Some(&oldest) = cached.snapshots.keys().next() { @@ -196,7 +197,7 @@ pub fn render_particles_2d( ) -> Vec { let pixel_count = (dims[0] as usize).saturating_mul(dims[1] as usize); let mut out = vec![0u8; pixel_count.saturating_mul(4)]; - if pixel_count == 0 { + if pixel_count == 0 || !time.is_finite() { return out; } @@ -226,7 +227,7 @@ pub fn render_particles_2d( .eval_number(rnode, "PreGenerateFrames", time, 0.0, expr) .round() .clamp(0.0, MAX_SIM_WINDOW as f64) as i64; - let sim_origin = base_start - pre_gen; + let sim_origin = base_start.saturating_sub(pre_gen); let subgraph_hash = particle_subgraph_hash(comp, render_node, base_start); let key = (rnode.name.clone(), subgraph_hash); @@ -235,15 +236,15 @@ pub fn render_particles_2d( .entries .retain(|(name, h), _| name != &key.0 || *h == subgraph_hash); - let cold_sim_start = |target: i64| sim_origin.max(target - MAX_SIM_WINDOW); + let cold_sim_start = |target: i64| sim_origin.max(target.saturating_sub(MAX_SIM_WINDOW)); let need_cold_init = match cache.entries.get_mut(&key) { Some(cached) if cached.base_start == sim_origin => { if target_frame == cached.current_frame { false } else if target_frame > cached.current_frame { - if target_frame - cached.current_frame <= MAX_SIM_WINDOW { - for f in (cached.current_frame + 1)..=target_frame { + if i128::from(target_frame) - i128::from(cached.current_frame) <= i128::from(MAX_SIM_WINDOW) { + for f in cached.current_frame.saturating_add(1)..=target_frame { step_simulation(&mut cached.state, comp, &plan, f, expr); maybe_record_snapshot(cached, f); } @@ -253,14 +254,20 @@ pub fn render_particles_2d( true } } else if let Some((&snap_f, snap_state)) = cached.snapshots.range(..=target_frame).next_back() { - cached.state = snap_state.clone(); - cached.current_frame = snap_f; - for f in (snap_f + 1)..=target_frame { - step_simulation(&mut cached.state, comp, &plan, f, expr); - maybe_record_snapshot(cached, f); + if i128::from(target_frame) - i128::from(snap_f) <= i128::from(MAX_SIM_WINDOW) { + cached.state = snap_state.clone(); + cached.current_frame = snap_f; + if snap_f < target_frame { + for f in snap_f.saturating_add(1)..=target_frame { + step_simulation(&mut cached.state, comp, &plan, f, expr); + maybe_record_snapshot(cached, f); + } + } + cached.current_frame = target_frame; + false + } else { + true } - cached.current_frame = target_frame; - false } else { true } diff --git a/crates/engine/src/particles/sim.rs b/crates/engine/src/particles/sim.rs index 815d5af3048ae74f9fbc8680293f9376fa8aa587..121ba32d085a1a793e5c91ecfd3634bc3ae830f9 100644 --- a/crates/engine/src/particles/sim.rs +++ b/crates/engine/src/particles/sim.rs @@ -894,14 +894,17 @@ fn value_noise_3d(x: f64, y: f64, z: f64, seed: u64) -> f64 { let v = yf * yf * (3.0 - 2.0 * yf); let w = zf * zf * (3.0 - 2.0 * zf); + let xi1 = xi.wrapping_add(1); + let yi1 = yi.wrapping_add(1); + let zi1 = zi.wrapping_add(1); let n000 = lattice_hash(xi, yi, zi, seed); - let n100 = lattice_hash(xi + 1, yi, zi, seed); - let n010 = lattice_hash(xi, yi + 1, zi, seed); - let n110 = lattice_hash(xi + 1, yi + 1, zi, seed); - let n001 = lattice_hash(xi, yi, zi + 1, seed); - let n101 = lattice_hash(xi + 1, yi, zi + 1, seed); - let n011 = lattice_hash(xi, yi + 1, zi + 1, seed); - let n111 = lattice_hash(xi + 1, yi + 1, zi + 1, seed); + let n100 = lattice_hash(xi1, yi, zi, seed); + let n010 = lattice_hash(xi, yi1, zi, seed); + let n110 = lattice_hash(xi1, yi1, zi, seed); + let n001 = lattice_hash(xi, yi, zi1, seed); + let n101 = lattice_hash(xi1, yi, zi1, seed); + let n011 = lattice_hash(xi, yi1, zi1, seed); + let n111 = lattice_hash(xi1, yi1, zi1, seed); let nx00 = n000 + (n100 - n000) * u; let nx10 = n010 + (n110 - n010) * u; diff --git a/crates/engine/src/ram_cache.rs b/crates/engine/src/ram_cache.rs index 42edaab41cbdefc943aa6398e435f0d9012f6ddb..da9c9893636aeef6cfb7d0685bd3e2f32c71a78e 100644 --- a/crates/engine/src/ram_cache.rs +++ b/crates/engine/src/ram_cache.rs @@ -681,11 +681,14 @@ impl RamPrefetcher { engine.hiq = job.hiq; engine.use_proxy_clips = job.use_proxy_clips; + if job.target.0 >= job.comp.nodes.len() { + continue; + } busy.store(true, Ordering::Release); let start = job.range[0].min(job.range[1]); let end = job.range[0].max(job.range[1]); - let span = (end - start + 1).max(1); - let count = job.lookahead.max(0).min(span); + let span = (i128::from(end) - i128::from(start) + 1).max(1); + let count = i128::from(job.lookahead.max(0)).min(span).min(i128::from(i64::MAX)) as i64; let is_cancelled = || { shutdown.load(Ordering::Acquire) @@ -708,7 +711,10 @@ impl RamPrefetcher { let mut chunk_items = Vec::with_capacity((chunk_end - chunk_start + 1) as usize); let mut batch_frames = Vec::with_capacity((chunk_end - chunk_start + 1) as usize); for offset in chunk_start..=chunk_end { - let f = start + (job.center_frame - start + offset).rem_euclid(span); + let f_i128 = i128::from(start) + + (i128::from(job.center_frame) - i128::from(start) + i128::from(offset)) + .rem_euclid(span); + let f = f_i128 as i64; let key = RamFrameKey { target: job.target, revision: job.comp.revision, diff --git a/crates/engine/src/scene3d/collect.rs b/crates/engine/src/scene3d/collect.rs index a5c737cef244411e90e341928d8b931e5129dabd..49b6d98114bcba6abefbeda894b721b4f82758da 100644 --- a/crates/engine/src/scene3d/collect.rs +++ b/crates/engine/src/scene3d/collect.rs @@ -117,7 +117,8 @@ fn collect_scene_inner( visited: &mut Vec, depth: usize, ) { - if depth > 32 { + const MAX_SCENE_MESHES: usize = 16_384; + if depth > 32 || node_id.0 >= comp.nodes.len() || meshes.len() >= MAX_SCENE_MESHES { return; } visited.push(node_id); @@ -230,7 +231,7 @@ fn collect_scene_inner( } let first = comp.eval_number(node, "FirstCopy", time, 0.0, expr).round() as i32; let last = comp.eval_number(node, "LastCopy", time, 2.0, expr).round() as i32; - let count = (last - first).clamp(0, 256); + let count = (i64::from(last) - i64::from(first)).clamp(0, 256) as i32; if count == 0 { return; } @@ -261,13 +262,22 @@ fn collect_scene_inner( + jsx.abs() + jsy.abs() + jsz.abs()) > 1e-5; let mut acc = mat4_identity(); - if !is_linear { - for _ in 0..first.max(0) { - acc = mat4_mul(acc, step); + if !is_linear && first > 0 { + let mut exp = first as u32; + let mut base = step; + while exp > 0 { + if (exp & 1) != 0 { + acc = mat4_mul(acc, base); + } + exp >>= 1; + if exp > 0 { + base = mat4_mul(base, base); + } } } for i in 0..count { - let copy_idx = (first + i) as u64; + let copy_i64 = i64::from(first) + i64::from(i); + let copy_idx = copy_i64 as u64; let s = seed.wrapping_mul(6364136223846793005).wrapping_add(copy_idx.wrapping_mul(1442695040888963407)); if copy_prob < 0.9999 && (splitmix64(s ^ 13) + 0.5) > copy_prob { if !is_linear { @@ -276,7 +286,7 @@ fn collect_scene_inner( continue; } let base_m = if is_linear { - dup_params.matrix_for_step((first + i) as f32, true) + dup_params.matrix_for_step(copy_i64 as f32, true) } else { acc }; diff --git a/crates/engine/src/text_engine.rs b/crates/engine/src/text_engine.rs index ac306bce05964793b91f4ad34873261ef508bf97..be43559a667df78b58deae7d6daca9e53cf3bc7a 100644 --- a/crates/engine/src/text_engine.rs +++ b/crates/engine/src/text_engine.rs @@ -785,7 +785,7 @@ fn size_metrics(face: &Face<'_>, size_norm: f32, canvas_w: f32) -> (f32, f32, f3 fn layout_glyph_specs(dims: [u32; 2], params: &RichTextPlusParams<'_>) -> Option<(Vec, usize)> { let [w, h] = dims; let total_chars = params.text.chars().count(); - if total_chars == 0 || params.size_norm <= 1e-4 { + if total_chars == 0 || !params.size_norm.is_finite() || params.size_norm <= 1e-4 { return None; } let c_start = (params.write_on_start.clamp(0.0, 1.0) * total_chars as f32).floor() as usize; diff --git a/crates/engine/tests/hardening_engine.rs b/crates/engine/tests/hardening_engine.rs new file mode 100644 index 0000000000000000000000000000000000000000..087f850f733b18806ea0259c5476d7bcb576cae4 --- /dev/null +++ b/crates/engine/tests/hardening_engine.rs @@ -0,0 +1,537 @@ +//! Boundary-hardening regression tests for `crates/engine`. +//! +//! Each test covers a real crash, stack overflow, integer overflow, runaway allocation, +//! or `wgpu` validation error fixed at its architectural boundary. + +use engine::audio::AudioTrack; +use engine::cryptomatte::extract_cryptomatte; +use engine::export::{ + ExportControl, ExportOptions, VideoCodec, VideoExportOptions, export_node_video_ffmpeg_with_progress, + export_saver_png_sequence_with_progress, +}; +use engine::media::{MediaCache, rasterize_polyline_mask}; +use engine::ram_cache::{PrefetchJob, RamFrame, RamFrameCache, RamFrameKey, RamPrefetcher}; +use engine::Engine; +use model::{ClipSpec, Comp, NodeId, PolyPoint}; +use std::path::PathBuf; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +fn eval_checked(eng: &mut Engine, comp: &Comp, target: NodeId, time: f64) -> [u32; 2] { + let scope = eng.device().push_error_scope(wgpu::ErrorFilter::Validation); + let (tex, _) = eng.evaluate(comp, target, time); + if let Some(err) = pollster::block_on(scope.pop()) { + panic!("wgpu validation error evaluating {target:?} @ {time}: {err}"); + } + assert!(tex.size[0] >= 1 && tex.size[1] >= 1); + tex.size +} + +fn make_clip(filename: String) -> ClipSpec { + ClipSpec { + filename, + alternate_filename: None, + start_frame: 0, + length: Some(1), + trim_in: 0, + trim_out: 0, + global_start: 0, + global_end: 0, + extend_first: 0, + extend_last: 0, + loop_clip: false, + reverse: false, + } +} + +#[test] +fn eval_entry_time_shifting_cycles_dangling_id_zero_dims_and_non_finite_time() { + let Ok(mut eng) = Engine::new_headless() else { return }; + + // Time-shifting self-cycles in TimeSpeed (Delay = 1) and TimeStretcher (SourceTime = time + 1) + // must hit MAX_EVAL_DEPTH / MAX_PRELOAD_DEPTH cleanly instead of blowing the Rust stack. + let cycle_comp = Comp::from_fusion_str( + r#"Composition { + CurrentTime = 0, + RenderRange = { 0, 10 }, + GlobalRange = { 0, 10 }, + Tools = ordered() { + TS = TimeSpeed { + Inputs = { + Input = Input { SourceOp = "TS", Source = "Output", }, + Delay = Input { Value = 1, }, + Speed = Input { Value = 0.5, }, + }, + }, + TSt = TimeStretcher { + Inputs = { + Input = Input { SourceOp = "TSt", Source = "Output", }, + SourceTime = Input { Expression = "time + 1", }, + }, + }, + BG = Background { }, + }, + }"#, + ) + .unwrap(); + + for name in ["TS", "TSt"] { + let id = cycle_comp.find_node(name).unwrap(); + eval_checked(&mut eng, &cycle_comp, id, 0.0); + } + + // Dangling NodeId must return cleanly without panicking on comp.node(id). + eval_checked(&mut eng, &cycle_comp, NodeId(9999), 0.0); + + // proxy_scale == 0 and 0x0 comp dimensions with a node inheriting comp dimensions. + let mut zero_comp = cycle_comp.clone(); + zero_comp.width = 0; + zero_comp.height = 0; + eng.proxy_scale = 0; + let bg = zero_comp.find_node("BG").unwrap(); + eval_checked(&mut eng, &zero_comp, bg, 0.0); + eng.proxy_scale = 1; + + // Non-finite and extreme frames. + for t in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 1e20, -1e20] { + eval_checked(&mut eng, &cycle_comp, bg, t); + } +} + +#[test] +fn text_paint_and_mask_boundaries_have_no_panics_ooms_or_validation_errors() { + let Ok(mut eng) = Engine::new_headless() else { return }; + let max_dim = eng.device().limits().max_texture_dimension_2d.max(1); + let over_dim = max_dim.saturating_add(4096); + + let src = format!( + r#"Composition {{ Tools = ordered() {{ + BG = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, }}, }}, + T_Empty = TextPlus {{ Inputs = {{ StyledText = Input {{ Value = "", }}, Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, }}, }}, + T_Zero = TextPlus {{ Inputs = {{ StyledText = Input {{ Value = "Hi", }}, Size = Input {{ Value = 0, }}, Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, }}, }}, + T_Neg = TextPlus {{ Inputs = {{ StyledText = Input {{ Value = "Hi", }}, Size = Input {{ Value = -1, }}, Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, }}, }}, + T_NaN = TextPlus {{ Inputs = {{ StyledText = Input {{ Value = "Hi", }}, Size = Input {{ Expression = "0/0", }}, Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, }}, }}, + T_NoFont = TextPlus {{ Inputs = {{ StyledText = Input {{ Value = "Hi", }}, Font = Input {{ Value = "NoSuchFontXYZ_9999", }}, Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, }}, }}, + 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, }}, }}, }}, + T3D_Empty = Text3D {{ Inputs = {{ StyledText = Input {{ Value = "", }}, }}, }}, + T3D_NaN = Text3D {{ Inputs = {{ StyledText = Input {{ Value = "Hi", }}, Size = Input {{ Expression = "0/0", }}, }}, }}, + Cam = Camera3D {{ Inputs = {{ ["Transform3DOp.Translate.Z"] = Input {{ Value = 5, }}, }}, }}, + M3D = Merge3D {{ Inputs = {{ + SceneInput1 = Input {{ SourceOp = "T3D_Empty", Source = "Output", }}, + SceneInput2 = Input {{ SourceOp = "T3D_NaN", Source = "Output", }}, + SceneInput3 = Input {{ SourceOp = "Cam", Source = "Output", }}, + }}, }}, + R3D = Renderer3D {{ Inputs = {{ SceneInput = Input {{ SourceOp = "M3D", Source = "Output", }}, Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, }}, }}, + + S0 = PolylineStroke {{ Inputs = {{ ["CircleBrush.Size"] = Input {{ Value = 0.1, }}, Polyline = Input {{ Value = Polyline {{ Points = {{ }}, }}, }}, }}, }}, + S1 = PolylineStroke {{ Inputs = {{ ["CircleBrush.Size"] = Input {{ Value = 0.1, }}, Polyline = Input {{ Value = Polyline {{ Points = {{ {{ X = 0.0, Y = 0.0, Linear = true }}, }}, }}, }}, }}, }}, + 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 }}, }}, }}, }}, }}, }}, + P0 = Paint {{ Inputs = {{ Input = Input {{ SourceOp = "BG", Source = "Output", }}, Paint = Input {{ SourceOp = "S0", Source = "Out", }}, }}, }}, + P1 = Paint {{ Inputs = {{ Input = Input {{ SourceOp = "BG", Source = "Output", }}, Paint = Input {{ SourceOp = "S1", Source = "Out", }}, }}, }}, + PHuge = Paint {{ Inputs = {{ Input = Input {{ SourceOp = "BG", Source = "Output", }}, Paint = Input {{ SourceOp = "SHuge", Source = "Out", }}, }}, }}, + PMBig = PaintMask {{ Inputs = {{ MaskWidth = Input {{ Value = {over_dim}, }}, MaskHeight = Input {{ Value = 64, }}, Paint = Input {{ SourceOp = "S1", Source = "Out", }}, }}, }}, + Poly0 = PolylineMask {{ Inputs = {{ MaskWidth = Input {{ Value = 64, }}, MaskHeight = Input {{ Value = 64, }}, }}, }}, + BS0 = BSplineMask {{ Inputs = {{ MaskWidth = Input {{ Value = 64, }}, MaskHeight = Input {{ Value = 64, }}, }}, }}, + }}, }}"# + ); + let comp = Comp::from_fusion_str(&src).unwrap(); + for name in [ + "T_Empty", "T_Zero", "T_Neg", "T_NaN", "T_NoFont", "T_BorderInf", "R3D", + "P0", "P1", "PHuge", "PMBig", "Poly0", "BS0", + ] { + let id = comp.find_node(name).unwrap(); + let sz = eval_checked(&mut eng, &comp, id, 0.0); + if name == "PMBig" { + assert!(sz[0] <= max_dim && sz[1] <= max_dim); + } + } + + // Direct polyline mask rasterizer with NaN/Inf coords and angle. + let pts = [ + PolyPoint { x: f64::NAN, y: 0.0, lx: 0.0, ly: 0.0, rx: 0.0, ry: 0.0, linear: true }, + PolyPoint { x: f64::INFINITY, y: 0.5, lx: 0.0, ly: 0.0, rx: 0.0, ry: 0.0, linear: true }, + PolyPoint { x: 0.2, y: 0.2, lx: 0.0, ly: 0.0, rx: 0.0, ry: 0.0, linear: true }, + ]; + let buf = rasterize_polyline_mask([32, 32], &pts, [0.5, 0.5], f32::NAN, false, 1.0); + assert_eq!(buf.len(), 32 * 32 * 4); +} + +#[test] +fn scene3d_duplicate_overflow_and_chained_blowup_and_particles_extreme_frames() { + let Ok(mut eng) = Engine::new_headless() else { return }; + + let dir = std::env::temp_dir().join(format!("fission-hardening-fbx-{}", std::process::id())); + let _ = std::fs::create_dir_all(&dir); + let bad_fbx = dir.join("corrupt.fbx"); + let mut fbx = b"Kaydara FBX Binary \0\x1a\x00".to_vec(); + fbx.extend_from_slice(&7500u32.to_le_bytes()); + fbx.extend_from_slice(&[0xFF; 64]); + std::fs::write(&bad_fbx, &fbx).unwrap(); + let fbx_esc = bad_fbx.to_string_lossy().replace('\\', "\\\\"); + + let src = format!( + r#"Composition {{ + CurrentTime = 0, + RenderRange = {{ 0, 10 }}, + GlobalRange = {{ 0, 10 }}, + Tools = ordered() {{ + Empty3D = Merge3D {{ }}, + REmpty = Renderer3D {{ Inputs = {{ SceneInput = Input {{ SourceOp = "Empty3D", Source = "Output", }}, Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, }}, }}, + + Cube = Cube3D {{ Inputs = {{ ["SurfaceCubeInputs.Width"] = Input {{ Value = 0, }}, }}, }}, + DupOverflow = Duplicate3D {{ Inputs = {{ SceneInput = Input {{ SourceOp = "Cube", Source = "Output", }}, FirstCopy = Input {{ Value = -2147483648, }}, LastCopy = Input {{ Value = 1, }}, }}, }}, + DupHugeFirst = Duplicate3D {{ Inputs = {{ SceneInput = Input {{ SourceOp = "Cube", Source = "Output", }}, FirstCopy = Input {{ Value = 1000000000, }}, LastCopy = Input {{ Value = 1000000002, }}, }}, }}, + DupA = Duplicate3D {{ Inputs = {{ SceneInput = Input {{ SourceOp = "Cube", Source = "Output", }}, FirstCopy = Input {{ Value = 0, }}, LastCopy = Input {{ Value = 128, }}, }}, }}, + DupB = Duplicate3D {{ Inputs = {{ SceneInput = Input {{ SourceOp = "DupA", Source = "Output", }}, FirstCopy = Input {{ Value = 0, }}, LastCopy = Input {{ Value = 128, }}, }}, }}, + DupC = Duplicate3D {{ Inputs = {{ SceneInput = Input {{ SourceOp = "DupB", Source = "Output", }}, FirstCopy = Input {{ Value = 0, }}, LastCopy = Input {{ Value = 128, }}, }}, }}, + BadFbx = SurfaceFBXMesh {{ Inputs = {{ ImportFile = Input {{ Value = "{fbx_esc}", }}, }}, }}, + CamBad = Camera3D {{ Inputs = {{ FLength = Input {{ Expression = "0/0", }}, NearClip = Input {{ Expression = "0/0", }}, FarClip = Input {{ Value = 1, }}, }}, }}, + CamGood = Camera3D {{ Inputs = {{ ["Transform3DOp.Translate.Z"] = Input {{ Value = 5, }}, }}, }}, + M3BadCam = Merge3D {{ Inputs = {{ SceneInput1 = Input {{ SourceOp = "CamBad", Source = "Output", }}, SceneInput2 = Input {{ SourceOp = "DupOverflow", Source = "Output", }}, }}, }}, + RBadCam = Renderer3D {{ Inputs = {{ SceneInput = Input {{ SourceOp = "M3BadCam", Source = "Output", }}, Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, }}, }}, + M3Stress = Merge3D {{ Inputs = {{ + SceneInput1 = Input {{ SourceOp = "CamGood", Source = "Output", }}, + SceneInput2 = Input {{ SourceOp = "DupOverflow", Source = "Output", }}, + SceneInput3 = Input {{ SourceOp = "DupHugeFirst", Source = "Output", }}, + SceneInput4 = Input {{ SourceOp = "DupC", Source = "Output", }}, + SceneInput5 = Input {{ SourceOp = "BadFbx", Source = "Output", }}, + }}, }}, + RStress = Renderer3D {{ Inputs = {{ SceneInput = Input {{ SourceOp = "M3Stress", Source = "Output", }}, Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, }}, }}, + + PE_Many = pEmitter {{ Inputs = {{ Number = Input {{ Value = 1000000, }}, Lifespan = Input {{ Value = 0, }}, ["StyleParticle.Size"] = Input {{ Expression = "0/0", }}, }}, }}, + PR_Many = pRender {{ Inputs = {{ Input = Input {{ SourceOp = "PE_Many", Source = "Output", }}, Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, }}, }}, + + PE_Pre = pEmitter {{ Inputs = {{ Number = Input {{ Value = 5, }}, Lifespan = Input {{ Value = 10, }}, }}, }}, + PTurb = pTurbulence {{ Inputs = {{ Input = Input {{ SourceOp = "PE_Pre", Source = "Output", }}, XStrength = Input {{ Value = 1e18, }}, }}, }}, + PR_Pre = pRender {{ Inputs = {{ Input = Input {{ SourceOp = "PTurb", Source = "Output", }}, PreGenerateFrames = Input {{ Value = 100000, }}, Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, }}, }}, + }}, + }}"# + ); + let comp = Comp::from_fusion_str(&src).unwrap(); + + let t0 = Instant::now(); + for (name, t) in [ + ("REmpty", 0.0), + ("RBadCam", 0.0), + ("RStress", 0.0), + ("PR_Many", 0.0), + ("PR_Pre", 0.0), + ("PR_Pre", 1e9), + ("PR_Pre", 1e20), + ("PR_Pre", f64::NAN), + ("PR_Pre", f64::INFINITY), + ("PR_Pre", f64::NEG_INFINITY), + ] { + let id = comp.find_node(name).unwrap(); + eval_checked(&mut eng, &comp, id, t); + } + assert!( + t0.elapsed() < Duration::from_secs(5), + "3D/Particles stress should stay bounded, took {:?}", + t0.elapsed() + ); + + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn optflow_custom_and_2d_tool_overflow_and_nan_boundaries() { + let Ok(mut eng) = Engine::new_headless() else { return }; + + let deep_parens = format!("{}1{}", "(".repeat(200), ")".repeat(200)); + let deep_unary = format!("{}1", "-".repeat(200)); + let src = format!( + r#"Composition {{ + CurrentTime = 0, + RenderRange = {{ 0, 10 }}, + GlobalRange = {{ 0, 10 }}, + Tools = ordered() {{ + BG1x1 = Background {{ Inputs = {{ Width = Input {{ Value = 1, }}, Height = Input {{ Value = 1, }}, }}, }}, + OF1 = OpticalFlow {{ Inputs = {{ Input = Input {{ SourceOp = "BG1x1", Source = "Output", }}, }}, }}, + VMB1 = VectorMotionBlur {{ Inputs = {{ Input = Input {{ SourceOp = "OF1", Source = "Output", }}, }}, }}, + NaNImg = Custom {{ Inputs = {{ + Image1 = Input {{ SourceOp = "BG1x1", Source = "Output", }}, + Depth = Input {{ Value = 4, }}, + RedExpression = Input {{ Value = "0/0", }}, + GreenExpression = Input {{ Value = "1/0", }}, + BlueExpression = Input {{ Value = "-1/0", }}, + AlphaExpression = Input {{ Value = "0/0", }}, + }}, }}, + OFNaN = OpticalFlow {{ Inputs = {{ Input = Input {{ SourceOp = "NaNImg", Source = "Output", }}, }}, }}, + VMBNaN = VectorMotionBlur {{ Inputs = {{ Input = Input {{ SourceOp = "OFNaN", Source = "Output", }}, }}, }}, + CustBad = Custom {{ Inputs = {{ Image1 = Input {{ SourceOp = "BG1x1", Source = "Output", }}, RedExpression = Input {{ Value = "1 + * ) ( @@@", }}, }}, }}, + CustDeep1 = Custom {{ Inputs = {{ Image1 = Input {{ SourceOp = "BG1x1", Source = "Output", }}, RedExpression = Input {{ Value = "{deep_parens}", }}, }}, }}, + CustDeep2 = Custom {{ Inputs = {{ Image1 = Input {{ SourceOp = "BG1x1", Source = "Output", }}, RedExpression = Input {{ Value = "{deep_unary}", }}, }}, }}, + + BG64 = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, }}, }}, + DB = DirectionalBlur {{ Inputs = {{ Input = Input {{ SourceOp = "BG64", Source = "Output", }}, Length = Input {{ Value = 0.2, }}, ClippingMode = Input {{ Value = FuID {{ "None" }}, }}, }}, }}, + SetDom = SetDomain {{ Inputs = {{ Input = Input {{ SourceOp = "DB", Source = "Output", }}, Mode = Input {{ Value = FuID {{ "Set" }}, }}, Left = Input {{ Value = -1e12, }}, Right = Input {{ Value = 1e12, }}, }}, }}, + FilterNoise = Filter {{ Inputs = {{ Input = Input {{ SourceOp = "BG64", Source = "Output", }}, FilterType = Input {{ Value = 5, }}, Animated = Input {{ Value = 1, }}, }}, }}, + LoaderExtreme = Loader {{ + Clips = {{ Clip {{ Filename = "/nonexistent/x.png", ExtendFirst = 10, ExtendLast = 10, }}, }}, + Inputs = {{ GlobalIn = Input {{ Value = -1e20, }}, GlobalOut = Input {{ Value = 1e20, }}, }}, + }}, + CropZero = Crop {{ Inputs = {{ Input = Input {{ SourceOp = "BG64", Source = "Output", }}, XSize = Input {{ Value = 0, }}, YSize = Input {{ Value = 0, }}, }}, }}, + CropHuge = Crop {{ Inputs = {{ Input = Input {{ SourceOp = "BG64", Source = "Output", }}, XSize = Input {{ Value = 100000, }}, YSize = Input {{ Value = 100000, }}, }}, }}, + ScaleBad = Scale {{ Inputs = {{ Input = Input {{ SourceOp = "BG64", Source = "Output", }}, XSize = Input {{ Value = 0, }}, YSize = Input {{ Value = 100000, }}, }}, }}, + ResizeBad = BetterResize {{ Inputs = {{ Input = Input {{ SourceOp = "BG64", Source = "Output", }}, Width = Input {{ Value = 0, }}, Height = Input {{ Value = 100000, }}, }}, }}, + BlurBad = Blur {{ Inputs = {{ Input = Input {{ SourceOp = "BG64", Source = "Output", }}, XBlurSize = Input {{ Value = 100000, }}, YBlurSize = Input {{ Expression = "0/0", }}, }}, }}, + XfBad = Transform {{ Inputs = {{ Input = Input {{ SourceOp = "BG64", Source = "Output", }}, Size = Input {{ Value = 0, }}, Angle = Input {{ Expression = "0/0", }}, }}, }}, + MergeBad = Merge {{ Inputs = {{ Background = Input {{ SourceOp = "BG64", Source = "Output", }}, Foreground = Input {{ SourceOp = "BG64", Source = "Output", }}, Size = Input {{ Value = 0, }}, Blend = Input {{ Expression = "0/0", }}, }}, }}, + GridBad = GridWarp {{ Inputs = {{ + Input = Input {{ SourceOp = "BG64", Source = "Output", }}, + 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 }}, }}, }}, }}, + 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 }}, }}, }}, }}, + }}, }}, + }}, + }}"# + ); + let comp = Comp::from_fusion_str(&src).unwrap(); + for (name, t) in [ + ("VMB1", 0.0), + ("VMBNaN", 0.0), + ("CustBad", 0.0), + ("CustDeep1", 0.0), + ("CustDeep2", 0.0), + ("SetDom", 0.0), + ("FilterNoise", 1e15), + ("LoaderExtreme", 0.0), + ("CropZero", 0.0), + ("CropHuge", 0.0), + ("ScaleBad", 0.0), + ("ResizeBad", 0.0), + ("BlurBad", 0.0), + ("XfBad", 0.0), + ("MergeBad", 0.0), + ("GridBad", 0.0), + ] { + let id = comp.find_node(name).unwrap(); + eval_checked(&mut eng, &comp, id, t); + } +} + +#[test] +fn external_media_exr_huge_header_and_audio_boundaries() { + // 1. Audio waveform_peaks: invalid fps/offset, NaN samples, i64::MAX frame, i64 span overflow. + let nan_track = AudioTrack { + path: PathBuf::from("nan.wav"), + sample_rate: 48000, + channels: 2, + samples: Arc::new(vec![f32::NAN, f32::INFINITY, f32::NEG_INFINITY, 0.5]), + duration_secs: 2.0 / 48000.0, + }; + assert!(nan_track.waveform_peaks(0.0, 0.0, 0, 10).is_empty()); + assert!(nan_track.waveform_peaks(-24.0, 0.0, 0, 10).is_empty()); + assert!(nan_track.waveform_peaks(f64::NAN, 0.0, 0, 10).is_empty()); + assert!(nan_track.waveform_peaks(f64::INFINITY, 0.0, 0, 10).is_empty()); + assert!(nan_track.waveform_peaks(24.0, f64::NAN, 0, 10).is_empty()); + assert!(nan_track.waveform_peaks(24.0, 0.0, i64::MIN, i64::MAX).is_empty()); + let max_frame_peaks = nan_track.waveform_peaks(24.0, 0.0, i64::MAX, i64::MAX); + assert_eq!(max_frame_peaks, vec![0.0]); + let peaks = nan_track.waveform_peaks(24.0, 0.0, 0, 2); + assert_eq!(peaks.len(), 3); + assert!(peaks.iter().all(|p| p.is_finite() && (0.0..=1.0).contains(p))); + + // 2. Malformed WAV/MP3 + malformed PNG/JPG/TIFF/BMP/TGA/EXR + huge-header EXR (OOM guard). + let dir = std::env::temp_dir().join(format!("fission-hardening-media-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + + let bad_audio: [(&str, Vec); 4] = [ + ("empty.wav", vec![]), + ("trunc.wav", b"RIFF\x24\x00\x00\x00WAVEfmt ".to_vec()), + ("zero_fields.wav", { + let mut v = b"RIFF\x24\x00\x00\x00WAVEfmt \x10\x00\x00\x00".to_vec(); + v.extend_from_slice(&[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0]); + v.extend_from_slice(b"data\x04\x00\x00\x00\x00\x00\x00\x00"); + v + }), + ("garbage.mp3", vec![0xFF, 0xFB, 0x90, 0x00, 0xDE, 0xAD, 0xBE, 0xEF]), + ]; + for (name, bytes) in &bad_audio { + let p = dir.join(name); + std::fs::write(&p, bytes).unwrap(); + assert!(AudioTrack::load(&p).is_err(), "{name} should fail cleanly"); + } + + // Build a valid tiny 2x2 EXR via `image`, then patch its `dataWindow` box to 100_000 x 100_000 + // to prove `decode_exr_rgba` and `extract_cryptomatte` reject huge-header EXRs without OOM. + let mut exr_bytes = Vec::new(); + let img = image::Rgba32FImage::from_pixel(2, 2, image::Rgba([1.0, 0.5, 0.25, 1.0])); + image::DynamicImage::ImageRgba32F(img) + .write_to(&mut std::io::Cursor::new(&mut exr_bytes), image::ImageFormat::OpenExr) + .unwrap(); + let dw_needle = b"dataWindow\0box2i\0\x10\x00\x00\x00"; + if let Some(pos) = exr_bytes.windows(dw_needle.len()).position(|w| w == dw_needle) { + let box_off = pos + dw_needle.len(); + // box2i = [xMin: i32, yMin: i32, xMax: i32, yMax: i32] -> 100_000 x 100_000 (160 GB if uncapped!) + exr_bytes[box_off..box_off + 16].copy_from_slice( + &[0i32, 0i32, 99_999i32, 99_999i32] + .into_iter() + .flat_map(i32::to_le_bytes) + .collect::>(), + ); + } + + let mut mc = MediaCache::new(64); + let bad_imgs: [(&str, Vec); 8] = [ + ("trunc.png", vec![137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, b'I', b'H', b'D', b'R']), + ("huge.png", { + let mut v = vec![137, 80, 78, 71, 13, 10, 26, 10]; + v.extend_from_slice(&13u32.to_be_bytes()); + v.extend_from_slice(b"IHDR"); + v.extend_from_slice(&100_000u32.to_be_bytes()); + v.extend_from_slice(&100_000u32.to_be_bytes()); + v.extend_from_slice(&[8, 6, 0, 0, 0, 0, 0, 0, 0]); + v + }), + ("trunc.jpg", vec![0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10]), + ("trunc.tiff", b"II*\x00\x08\x00\x00\x00".to_vec()), + ("trunc.bmp", b"BM\x36\x00\x00\x00\x00\x00\x00\x00\x36\x00\x00\x00".to_vec()), + ("trunc.tga", vec![0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, 0xFF, 0xFF, 32, 0]), + ("trunc.exr", vec![0x76, 0x2F, 0x31, 0x01, 2, 0, 0, 0]), + ("huge_header.exr", exr_bytes), + ]; + for (name, bytes) in &bad_imgs { + let p = dir.join(name); + std::fs::write(&p, bytes).unwrap(); + let clip = make_clip(p.to_string_lossy().into_owned()); + assert!(mc.load_clip(&clip, 0, false, [None; 4]).is_none(), "{name} must return None"); + if name.ends_with(".exr") { + assert!(extract_cryptomatte(&p, None, "Hero").is_none()); + } + } + + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn cache_prefetcher_and_export_concurrency_and_range_boundaries() { + let comp = Comp::from_fusion_str( + r#"Composition { + CurrentTime = 0, + RenderRange = { 0, 4 }, + GlobalRange = { 0, 4 }, + Tools = ordered() { + BG = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, TopLeftRed = Input { Value = 0.5, }, TopLeftAlpha = Input { Value = 1.0, }, }, }, + Saver1 = Saver { Inputs = { Input = Input { SourceOp = "BG", Source = "Output", }, }, }, + }, + }"#, + ) + .unwrap(); + let bg = comp.find_node("BG").unwrap(); + let Ok(mut eng) = Engine::new_headless() else { return }; + + // 1. Tight VRAM budgets (0 MB and 1 MB). + for mb in [0u64, 1] { + eng.set_vram_budget_mb(mb); + eval_checked(&mut eng, &comp, bg, 0.0); + } + eng.set_vram_budget_mb(128); + + // 2. RamFrameCache 0 MB and 1 MB budgets. + let rc0 = RamFrameCache::new(0); + let key0 = RamFrameKey { target: bg, revision: 1, frame: 0, proxy_scale: 1, hiq: true, use_proxy_clips: false }; + let frame = RamFrame { size: [64, 64], rgba: Arc::new(vec![0u8; 64 * 64 * 4]), eval_ms: 1.0 }; + rc0.insert(key0, frame.clone()); + assert_eq!(rc0.entry_count(), 0); + let rc1 = RamFrameCache::new(1); + rc1.insert(key0, frame); + assert_eq!(rc1.entry_count(), 1); + + // 3. RamPrefetcher rapid request_lookahead + cancel + extreme range + dangling target + Drop. + { + let rc = RamFrameCache::new(16); + let mut pf = RamPrefetcher::new(rc, 128); + pf.request_lookahead(PrefetchJob { + comp: comp.clone(), + target: NodeId(9999), + center_frame: 0, + range: [i64::MIN, i64::MAX], + lookahead: 4, + proxy_scale: 0, + hiq: true, + use_proxy_clips: false, + }); + for i in 0..8 { + pf.request_lookahead(PrefetchJob { + comp: comp.clone(), + target: bg, + center_frame: i, + range: [i64::MIN, i64::MAX], + lookahead: 3, + proxy_scale: 0, + hiq: true, + use_proxy_clips: false, + }); + if i % 2 == 0 { + pf.cancel(); + } + } + } + + // 4. PNG & Video export range/path errors + cancellation at frame 0, 1, last with zero leaked temp files. + let dir = std::env::temp_dir().join(format!("fission-hardening-export-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + + for bad_range in [[10, 5], [i64::MIN, i64::MAX]] { + let opts = ExportOptions { + out_dir_override: Some(dir.clone()), + range_override: Some(bad_range), + ..ExportOptions::default() + }; + assert!(export_saver_png_sequence_with_progress(&mut eng, &comp, &opts, None, |_| {}).is_err()); + } + + // Single-frame PNG export at i64::MAX must not overflow prefetch arithmetic. + let max_opts = ExportOptions { + out_dir_override: Some(dir.clone()), + range_override: Some([i64::MAX, i64::MAX]), + ..ExportOptions::default() + }; + let summary = export_saver_png_sequence_with_progress(&mut eng, &comp, &max_opts, None, |_| {}).unwrap(); + assert_eq!(summary.frames_written, 1); + + // Invalid output path (parent is a regular file). + let blocking_file = dir.join("not_a_dir"); + std::fs::write(&blocking_file, b"x").unwrap(); + let bad_path_opts = ExportOptions { + out_dir_override: Some(blocking_file.join("child")), + range_override: Some([0, 0]), + ..ExportOptions::default() + }; + assert!(export_saver_png_sequence_with_progress(&mut eng, &comp, &bad_path_opts, None, |_| {}).is_err()); + + // Video export cancellation at frame 0, 1, and last frame (4): zero deadlocks, zero leaked `.fission_tmp_*`. + for cancel_at in [0usize, 1, 4] { + let out_mp4 = dir.join(format!("cancel_{cancel_at}.mp4")); + let ctrl = ExportControl::new(); + let ctrl_c = ctrl.clone(); + if cancel_at == 0 { + ctrl.cancel(); + } + let vopts = VideoExportOptions { + target: bg, + out_path: out_mp4, + range: [0, 4], + codec: VideoCodec::H264Share, + include_audio: false, + ..VideoExportOptions::default() + }; + let res = export_node_video_ffmpeg_with_progress(&mut eng, &comp, &vopts, Some(&ctrl), move |p| { + if p.index >= cancel_at { + ctrl_c.cancel(); + } + }); + assert!(res.is_err(), "cancel@{cancel_at} should return Err"); + let leaked = std::fs::read_dir(&dir) + .unwrap() + .filter_map(|e| e.ok()) + .filter(|e| e.file_name().to_string_lossy().contains(".fission_tmp_")) + .count(); + assert_eq!(leaked, 0, "leaked temp export file on cancel@{cancel_at}"); + } + + let _ = std::fs::remove_dir_all(&dir); +}