authoravatarclover caruso<git@paperclover.net>2026-12-01 18:56:54-08:00
committeravatarclover caruso<git@paperclover.net>2026-12-01 19:13:51-08:00
log65e3eb9d114bdc05ad20b13c6c593763fe03ed0d
treea305e7277acee57c7f06fd02edfa652004568fcc
parenta2ed1ffbd69daa39be5cd41986d4dff547094b8f
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

fix(model): harden parser recursion, non-finite boundaries, and serializer parity


9 files changed, 637 insertions(+), 106 deletions(-)

crates/model/src/comp.rs+3-6
...@@ -232,7 +232,7 @@ impl SaverSpec {...@@ -232,7 +232,7 @@ impl SaverSpec {
232 /// - `render.png` -> `render{frame:04}.png` (4-digit default when no trailing digits exist)232 /// - `render.png` -> `render{frame:04}.png` (4-digit default when no trailing digits exist)
233 pub fn frame_path(&self, frame: i64) -> PathBuf {233 pub fn frame_path(&self, frame: i64) -> PathBuf {
234 let effective_frame = if let Some(start) = self.sequence_start {234 let effective_frame = if let Some(start) = self.sequence_start {
235 start + (frame - self.range[0])235 start.saturating_add(frame.saturating_sub(self.range[0]))
236 } else {236 } else {
237 frame237 frame
238 };238 };
...@@ -246,11 +246,8 @@ impl SaverSpec {...@@ -246,11 +246,8 @@ impl SaverSpec {
246 None => (fname, ""),246 None => (fname, ""),
247 };247 };
248248
249 let digit_start = stem249 let prefix = stem.trim_end_matches(|c: char| c.is_ascii_digit());
250 .rfind(|c: char| !c.is_ascii_digit())250 let digits = &stem[prefix.len()..];
251 .map_or(0, |idx| idx + 1);
252 let prefix = &stem[..digit_start];
253 let digits = &stem[digit_start..];
254 let width = if digits.is_empty() { 4 } else { digits.len() };251 let width = if digits.is_empty() { 4 } else { digits.len() };
255252
256 let formatted_num = if effective_frame < 0 {253 let formatted_num = if effective_frame < 0 {
crates/model/src/comp/eval.rs+17-7
...@@ -88,7 +88,7 @@ impl Comp {...@@ -88,7 +88,7 @@ impl Comp {
88 if kfs.is_empty() {88 if kfs.is_empty() {
89 return None;89 return None;
90 }90 }
91 if kfs.len() == 1 || time <= kfs[0].0 {91 if kfs.len() == 1 || time.is_nan() || time <= kfs[0].0 {
92 return Some(kfs[0].1.clone());92 return Some(kfs[0].1.clone());
93 }93 }
94 if time >= kfs[kfs.len() - 1].0 {94 if time >= kfs[kfs.len() - 1].0 {
...@@ -261,7 +261,9 @@ impl Comp {...@@ -261,7 +261,9 @@ impl Comp {
261 }261 }
262 if let Some(expr) = &binding.expression {262 if let Some(expr) = &binding.expression {
263 if let Some(p) = self.eval_expr_point(node, expr, time, expr_engine) {263 if let Some(p) = self.eval_expr_point(node, expr, time, expr_engine) {
264 return p;264 if p[0].is_finite() && p[1].is_finite() {
265 return p;
266 }
265 }267 }
266 }268 }
267 if let Some(src) = &binding.source_op {269 if let Some(src) = &binding.source_op {
...@@ -329,7 +331,12 @@ impl Comp {...@@ -329,7 +331,12 @@ impl Comp {
329 }331 }
330332
331 fn eval_shake_axis(&self, sh: &ShakeModifier, axis: u32, time: f64, expr_engine: &ExprEngine) -> f64 {333 fn eval_shake_axis(&self, sh: &ShakeModifier, axis: u32, time: f64, expr_engine: &ExprEngine) -> f64 {
332 let smoothness = self.eval_shake_input(sh, "Smoothness", time, 1.0, expr_engine).max(0.01);334 let smoothness_raw = self.eval_shake_input(sh, "Smoothness", time, 1.0, expr_engine);
335 let smoothness = if smoothness_raw.is_finite() {
336 smoothness_raw.max(0.01)
337 } else {
338 1.0
339 };
333 let seed = self.eval_shake_input(sh, "RandomSeed", time, 0.0, expr_engine).round() as i64;340 let seed = self.eval_shake_input(sh, "RandomSeed", time, 0.0, expr_engine).round() as i64;
334 let lock_xy = self.eval_shake_input(sh, "LockXY", time, 1.0, expr_engine) > 0.5;341 let lock_xy = self.eval_shake_input(sh, "LockXY", time, 1.0, expr_engine) > 0.5;
335 let (min_v, max_v) = if axis == 0 || lock_xy {342 let (min_v, max_v) = if axis == 0 || lock_xy {
...@@ -345,6 +352,9 @@ impl Comp {...@@ -345,6 +352,9 @@ impl Comp {
345 };352 };
346 // Smooth Catmull-Rom interpolation over seeded lattice points spaced by `smoothness` frames353 // Smooth Catmull-Rom interpolation over seeded lattice points spaced by `smoothness` frames
347 let u = time / smoothness;354 let u = time / smoothness;
355 if !u.is_finite() || u.abs() >= 4.5e15 {
356 return min_v;
357 }
348 let k = u.floor() as i64;358 let k = u.floor() as i64;
349 let f = u - k as f64;359 let f = u - k as f64;
350 let hash01 = |i: i64| -> f64 {360 let hash01 = |i: i64| -> f64 {
...@@ -356,10 +366,10 @@ impl Comp {...@@ -356,10 +366,10 @@ impl Comp {
356 x ^= x >> 31;366 x ^= x >> 31;
357 (x >> 11) as f64 / (1u64 << 53) as f64367 (x >> 11) as f64 / (1u64 << 53) as f64
358 };368 };
359 let p0 = hash01(k - 1);369 let p0 = hash01(k.wrapping_sub(1));
360 let p1 = hash01(k);370 let p1 = hash01(k);
361 let p2 = hash01(k + 1);371 let p2 = hash01(k.wrapping_add(1));
362 let p3 = hash01(k + 2);372 let p3 = hash01(k.wrapping_add(2));
363 let f2 = f * f;373 let f2 = f * f;
364 let f3 = f2 * f;374 let f3 = f2 * f;
365 let cr = 0.5 * ((2.0 * p1)375 let cr = 0.5 * ((2.0 * p1)
...@@ -788,7 +798,7 @@ impl Comp {...@@ -788,7 +798,7 @@ impl Comp {
788 if kfs.is_empty() {798 if kfs.is_empty() {
789 return None;799 return None;
790 }800 }
791 if kfs.len() == 1 || time <= kfs[0].0 {801 if kfs.len() == 1 || time.is_nan() || time <= kfs[0].0 {
792 return Some(kfs[0].1.clone());802 return Some(kfs[0].1.clone());
793 }803 }
794 let last = &kfs[kfs.len() - 1];804 let last = &kfs[kfs.len() - 1];
crates/model/src/comp/load.rs+31-16
...@@ -30,19 +30,19 @@ impl Comp {...@@ -30,19 +30,19 @@ impl Comp {
30 });30 });
31 };31 };
3232
33 let current_time = root.get_f64("CurrentTime").unwrap_or(0.0);33 let current_time = root.get_f64("CurrentTime").filter(|t| t.is_finite()).unwrap_or(0.0);
34 let global_range = root34 let global_range = root
35 .get_table("GlobalRange")35 .get_table("GlobalRange")
36 .and_then(read_vec2)36 .and_then(read_vec2)
37 .map(|[a, b]| [a as i64, b as i64])37 .and_then(normalize_frame_range)
38 .unwrap_or([0, 1000]);38 .unwrap_or([0, 1000]);
39 let render_range = root39 let render_range = root
40 .get_table("RenderRange")40 .get_table("RenderRange")
41 .and_then(read_vec2)41 .and_then(read_vec2)
42 .map(|[a, b]| [a as i64, b as i64])42 .and_then(normalize_frame_range)
43 .unwrap_or(global_range);43 .unwrap_or(global_range);
44 let audio_filename = root.get_str("AudioFilename").map(str::to_owned);44 let audio_filename = root.get_str("AudioFilename").map(str::to_owned);
45 let audio_offset = root.get_f64("AudioOffset").unwrap_or(0.0);45 let audio_offset = root.get_f64("AudioOffset").filter(|t| t.is_finite()).unwrap_or(0.0);
4646
47 // Extract FrameFormat from Prefs.Comp.FrameFormat (default 1920x1080 @ 30fps, Int8)47 // Extract FrameFormat from Prefs.Comp.FrameFormat (default 1920x1080 @ 30fps, Int8)
48 let mut width = 1920u32;48 let mut width = 1920u32;
...@@ -55,20 +55,22 @@ impl Comp {...@@ -55,20 +55,22 @@ impl Comp {
55 .and_then(|p| p.get_table("Comp"))55 .and_then(|p| p.get_table("Comp"))
56 .and_then(|c| c.get_table("FrameFormat"))56 .and_then(|c| c.get_table("FrameFormat"))
57 {57 {
58 if let Some(w) = ff.get_f64("Width") {58 if let Some(w) = ff.get_f64("Width").and_then(normalize_frame_dim) {
59 width = w.round().max(1.0) as u32;59 width = w;
60 explicit_size = true;60 explicit_size = true;
61 }61 }
62 if let Some(h) = ff.get_f64("Height") {62 if let Some(h) = ff.get_f64("Height").and_then(normalize_frame_dim) {
63 height = h.round().max(1.0) as u32;63 height = h;
64 explicit_size = true;64 explicit_size = true;
65 }65 }
66 if let Some(r) = ff.get_f64("Rate") {66 if let Some(r) = ff.get_f64("Rate").filter(|r| r.is_finite() && *r > 0.0) {
67 if r > 0.0 {67 fps = r;
68 fps = r;
69 }
70 }68 }
71 if let Some(d) = ff.get_f64("DepthFull").and_then(|v| BitDepth::from_fusion_depth(v.round() as i32)) {69 if let Some(d) = ff
70 .get_f64("DepthFull")
71 .filter(|v| v.is_finite())
72 .and_then(|v| BitDepth::from_fusion_depth(v.round() as i32))
73 {
72 depth_full = d;74 depth_full = d;
73 }75 }
74 }76 }
...@@ -263,9 +265,9 @@ impl Comp {...@@ -263,9 +265,9 @@ impl Comp {
263 for n in &nodes {265 for n in &nodes {
264 if matches!(n.kind.as_str(), "Background" | "TextPlus" | "FastNoise") {266 if matches!(n.kind.as_str(), "Background" | "TextPlus" | "FastNoise") {
265 if let (Some(w), Some(h)) = (n.static_number("Width"), n.static_number("Height")) {267 if let (Some(w), Some(h)) = (n.static_number("Width"), n.static_number("Height")) {
266 if w >= 64.0 && h >= 64.0 {268 if w.is_finite() && h.is_finite() && w >= 64.0 && h >= 64.0 {
267 width = w as u32;269 width = normalize_frame_dim(w).unwrap_or(width);
268 height = h as u32;270 height = normalize_frame_dim(h).unwrap_or(height);
269 break;271 break;
270 }272 }
271 }273 }
...@@ -304,6 +306,19 @@ impl Comp {...@@ -304,6 +306,19 @@ impl Comp {
304306
305}307}
306308
309pub(super) fn normalize_frame_dim(v: f64) -> Option<u32> {
310 v.is_finite()
311 .then(|| v.round().clamp(1.0, 65536.0) as u32)
312}
313
314fn normalize_frame_range([a, b]: [f64; 2]) -> Option<[i64; 2]> {
315 (a.is_finite() && b.is_finite()).then(|| {
316 let lo = i32::MIN as f64;
317 let hi = i32::MAX as f64;
318 [a.round().clamp(lo, hi) as i64, b.round().clamp(lo, hi) as i64]
319 })
320}
321
307/// Fusion resolves a macro-internal `SourceOp` only within the macro's own scope (itself, its322/// Fusion resolves a macro-internal `SourceOp` only within the macro's own scope (itself, its
308/// enclosing macros, its nested macros) or at top level; a name that only exists inside an323/// enclosing macros, its nested macros) or at top level; a name that only exists inside an
309/// unrelated macro stays unconnected. Returns the `(node, port)` wires whose `source_op` was324/// unrelated macro stays unconnected. Returns the `(node, port)` wires whose `source_op` was
crates/model/src/comp/math.rs+36-17
...@@ -30,7 +30,11 @@ impl GridMesh {...@@ -30,7 +30,11 @@ impl GridMesh {
30 if tbl.tag.as_deref() != Some("Mesh") {30 if tbl.tag.as_deref() != Some("Mesh") {
31 return None;31 return None;
32 }32 }
33 let cols = tbl.get_f64("Col")?.round().max(2.0) as usize;33 let cols_f = tbl.get_f64("Col")?;
34 if !cols_f.is_finite() {
35 return None;
36 }
37 let cols = cols_f.round().clamp(2.0, 65536.0) as usize;
34 let pts_tbl = tbl.get_table("Points")?;38 let pts_tbl = tbl.get_table("Points")?;
35 let mut points = Vec::new();39 let mut points = Vec::new();
36 for pval in pts_tbl.positional_values() {40 for pval in pts_tbl.positional_values() {
...@@ -48,7 +52,7 @@ impl GridMesh {...@@ -48,7 +52,7 @@ impl GridMesh {
48 b_cy: pt.get_f64("B_CY"),52 b_cy: pt.get_f64("B_CY"),
49 });53 });
50 }54 }
51 if points.len() < cols * 2 {55 if points.len() < cols.checked_mul(2)? {
52 return None;56 return None;
53 }57 }
54 let rows = points.len() / cols;58 let rows = points.len() / cols;
...@@ -148,7 +152,7 @@ impl Comp {...@@ -148,7 +152,7 @@ impl Comp {
148 }152 }
149 if !kfs.is_empty() {153 if !kfs.is_empty() {
150 kfs.sort_by(|a, b| a.0.total_cmp(&b.0));154 kfs.sort_by(|a, b| a.0.total_cmp(&b.0));
151 if kfs.len() == 1 || time <= kfs[0].0 {155 if kfs.len() == 1 || time.is_nan() || time <= kfs[0].0 {
152 return Some(kfs[0].1.clone());156 return Some(kfs[0].1.clone());
153 }157 }
154 if time >= kfs[kfs.len() - 1].0 {158 if time >= kfs[kfs.len() - 1].0 {
...@@ -182,13 +186,25 @@ impl Comp {...@@ -182,13 +186,25 @@ impl Comp {
182/// Evaluates a Fusion `Expression` modifier math formula (C-like Fusion math DSL) to an `f64`.186/// Evaluates a Fusion `Expression` modifier math formula (C-like Fusion math DSL) to an `f64`.
183/// Returns `None` if syntax is not recognized so callers can fall back to Lua `ExprEngine`.187/// Returns `None` if syntax is not recognized so callers can fall back to Lua `ExprEngine`.
184pub(super) fn eval_fusion_math_expr(src: &str, vars: &HashMap<String, f64>) -> Option<f64> {188pub(super) fn eval_fusion_math_expr(src: &str, vars: &HashMap<String, f64>) -> Option<f64> {
189 const MAX_EXPR_DEPTH: usize = 64;
190
185 struct Parser<'a> {191 struct Parser<'a> {
186 bytes: &'a [u8],192 bytes: &'a [u8],
187 pos: usize,193 pos: usize,
188 vars: &'a HashMap<String, f64>,194 vars: &'a HashMap<String, f64>,
195 depth: usize,
189 }196 }
190197
191 impl<'a> Parser<'a> {198 impl<'a> Parser<'a> {
199 fn with_depth(&mut self, f: impl FnOnce(&mut Self) -> Option<f64>) -> Option<f64> {
200 if self.depth >= MAX_EXPR_DEPTH {
201 return None;
202 }
203 self.depth += 1;
204 let res = f(self);
205 self.depth -= 1;
206 res
207 }
192 fn skip_ws(&mut self) {208 fn skip_ws(&mut self) {
193 while self.pos < self.bytes.len() {209 while self.pos < self.bytes.len() {
194 let b = self.bytes[self.pos];210 let b = self.bytes[self.pos];
...@@ -220,17 +236,19 @@ pub(super) fn eval_fusion_math_expr(src: &str, vars: &HashMap<String, f64>) -> O...@@ -220,17 +236,19 @@ pub(super) fn eval_fusion_math_expr(src: &str, vars: &HashMap<String, f64>) -> O
220 }236 }
221237
222 fn parse_or(&mut self) -> Option<f64> {238 fn parse_or(&mut self) -> Option<f64> {
223 let mut v = self.parse_and()?;239 self.with_depth(|p| {
224 loop {240 let mut v = p.parse_and()?;
225 self.skip_ws();241 loop {
226 if self.eat_str("||") || self.eat_str("|") {242 p.skip_ws();
227 let r = self.parse_and()?;243 if p.eat_str("||") || p.eat_str("|") {
228 v = if v != 0.0 || r != 0.0 { 1.0 } else { 0.0 };244 let r = p.parse_and()?;
229 } else {245 v = if v != 0.0 || r != 0.0 { 1.0 } else { 0.0 };
230 break;246 } else {
247 break;
248 }
231 }249 }
232 }250 Some(v)
233 Some(v)251 })
234 }252 }
235253
236 fn parse_and(&mut self) -> Option<f64> {254 fn parse_and(&mut self) -> Option<f64> {
...@@ -322,7 +340,7 @@ pub(super) fn eval_fusion_math_expr(src: &str, vars: &HashMap<String, f64>) -> O...@@ -322,7 +340,7 @@ pub(super) fn eval_fusion_math_expr(src: &str, vars: &HashMap<String, f64>) -> O
322 let base = self.parse_unary()?;340 let base = self.parse_unary()?;
323 if self.peek() == Some(b'^') {341 if self.peek() == Some(b'^') {
324 self.pos += 1;342 self.pos += 1;
325 let exp = self.parse_pow()?;343 let exp = self.with_depth(Self::parse_pow)?;
326 Some(if base > 0.0 {344 Some(if base > 0.0 {
327 base.powf(exp)345 base.powf(exp)
328 } else if base == 0.0 {346 } else if base == 0.0 {
...@@ -342,15 +360,15 @@ pub(super) fn eval_fusion_math_expr(src: &str, vars: &HashMap<String, f64>) -> O...@@ -342,15 +360,15 @@ pub(super) fn eval_fusion_math_expr(src: &str, vars: &HashMap<String, f64>) -> O
342 match self.peek() {360 match self.peek() {
343 Some(b'-') => {361 Some(b'-') => {
344 self.pos += 1;362 self.pos += 1;
345 Some(-self.parse_unary()?)363 Some(-self.with_depth(Self::parse_unary)?)
346 }364 }
347 Some(b'+') => {365 Some(b'+') => {
348 self.pos += 1;366 self.pos += 1;
349 self.parse_unary()367 self.with_depth(Self::parse_unary)
350 }368 }
351 Some(b'!') => {369 Some(b'!') => {
352 self.pos += 1;370 self.pos += 1;
353 let v = self.parse_unary()?;371 let v = self.with_depth(Self::parse_unary)?;
354 Some(if v == 0.0 { 1.0 } else { 0.0 })372 Some(if v == 0.0 { 1.0 } else { 0.0 })
355 }373 }
356 _ => self.parse_primary(),374 _ => self.parse_primary(),
...@@ -509,6 +527,7 @@ pub(super) fn eval_fusion_math_expr(src: &str, vars: &HashMap<String, f64>) -> O...@@ -509,6 +527,7 @@ pub(super) fn eval_fusion_math_expr(src: &str, vars: &HashMap<String, f64>) -> O
509 bytes: src.as_bytes(),527 bytes: src.as_bytes(),
510 pos: 0,528 pos: 0,
511 vars,529 vars,
530 depth: 0,
512 };531 };
513 let val = p.parse_or()?;532 let val = p.parse_or()?;
514 p.skip_ws();533 p.skip_ws();
crates/model/src/comp/save.rs+35-34
...@@ -1,4 +1,4 @@...@@ -1,4 +1,4 @@
1use super::load::{parse_input_binding, parse_param_value};1use super::load::{normalize_frame_dim, parse_input_binding, parse_param_value};
2use super::math::find_raw_tool_mut;2use super::math::find_raw_tool_mut;
3use super::{BitDepth, Comp, InputBinding, Node, ParamValue, is_modifier_type};3use super::{BitDepth, Comp, InputBinding, Node, ParamValue, is_modifier_type};
4use crate::lua_value::{4use crate::lua_value::{
...@@ -92,30 +92,8 @@ impl Comp {...@@ -92,30 +92,8 @@ impl Comp {
92 }92 }
9393
94 // Update Prefs.Comp.FrameFormat (Width, Height, Rate, DepthFull)94 // Update Prefs.Comp.FrameFormat (Width, Height, Rate, DepthFull)
95 {95 let prefs = ensure_table_mut(&mut root, "Prefs", None);
96 let prefs = ensure_table_mut(&mut root, "Prefs", None);96 self.patch_prefs_table(prefs);
97 let comp_prefs = ensure_table_mut(prefs, "Comp", None);
98 let ff = ensure_table_mut(comp_prefs, "FrameFormat", None);
99 if ff.get_f64("Width").map(|w| w.round().max(1.0) as u32) != Some(self.width) {
100 ff.set(LuaKey::Str("Width".to_owned()), LuaValue::Number(self.width as f64));
101 }
102 if ff.get_f64("Height").map(|h| h.round().max(1.0) as u32) != Some(self.height) {
103 ff.set(LuaKey::Str("Height".to_owned()), LuaValue::Number(self.height as f64));
104 }
105 if ff.get_f64("Rate").is_none_or(|r| (r - self.fps).abs() > 1e-9) {
106 ff.set(LuaKey::Str("Rate".to_owned()), LuaValue::Number(self.fps));
107 }
108 let existing_depth = ff
109 .get_f64("DepthFull")
110 .and_then(|v| BitDepth::from_fusion_depth(v.round() as i32))
111 .unwrap_or(BitDepth::Int8);
112 if existing_depth != self.depth_full {
113 ff.set(
114 LuaKey::Str("DepthFull".to_owned()),
115 LuaValue::Number((self.depth_full as i32) as f64),
116 );
117 }
118 }
11997
120 // Sync Tools98 // Sync Tools
121 let tools = ensure_table_mut(&mut root, "Tools", Some("ordered"));99 let tools = ensure_table_mut(&mut root, "Tools", Some("ordered"));
...@@ -533,17 +511,21 @@ impl Comp {...@@ -533,17 +511,21 @@ impl Comp {
533 else {511 else {
534 return true;512 return true;
535 };513 };
536 if ff.get_f64("Width").map(|w| w.round().max(1.0) as u32) != Some(self.width) {514 if ff.get_f64("Width").and_then(normalize_frame_dim) != Some(self.width) {
537 return true;515 return true;
538 }516 }
539 if ff.get_f64("Height").map(|h| h.round().max(1.0) as u32) != Some(self.height) {517 if ff.get_f64("Height").and_then(normalize_frame_dim) != Some(self.height) {
540 return true;518 return true;
541 }519 }
542 if ff.get_f64("Rate").is_none_or(|r| (r - self.fps).abs() > 1e-9) {520 if ff
521 .get_f64("Rate")
522 .is_none_or(|r| !r.is_finite() || (r - self.fps).abs() > 1e-9)
523 {
543 return true;524 return true;
544 }525 }
545 let existing_depth = ff526 let existing_depth = ff
546 .get_f64("DepthFull")527 .get_f64("DepthFull")
528 .filter(|v| v.is_finite())
547 .and_then(|v| BitDepth::from_fusion_depth(v.round() as i32))529 .and_then(|v| BitDepth::from_fusion_depth(v.round() as i32))
548 .unwrap_or(BitDepth::Int8);530 .unwrap_or(BitDepth::Int8);
549 existing_depth != self.depth_full531 existing_depth != self.depth_full
...@@ -552,17 +534,21 @@ impl Comp {...@@ -552,17 +534,21 @@ impl Comp {
552 fn patch_prefs_table(&self, prefs: &mut LuaTable) {534 fn patch_prefs_table(&self, prefs: &mut LuaTable) {
553 let comp_prefs = ensure_table_mut(prefs, "Comp", None);535 let comp_prefs = ensure_table_mut(prefs, "Comp", None);
554 let ff = ensure_table_mut(comp_prefs, "FrameFormat", None);536 let ff = ensure_table_mut(comp_prefs, "FrameFormat", None);
555 if ff.get_f64("Width").map(|w| w.round().max(1.0) as u32) != Some(self.width) {537 if ff.get_f64("Width").and_then(normalize_frame_dim) != Some(self.width) {
556 ff.set(LuaKey::Str("Width".to_owned()), LuaValue::Number(self.width as f64));538 ff.set(LuaKey::Str("Width".to_owned()), LuaValue::Number(self.width as f64));
557 }539 }
558 if ff.get_f64("Height").map(|h| h.round().max(1.0) as u32) != Some(self.height) {540 if ff.get_f64("Height").and_then(normalize_frame_dim) != Some(self.height) {
559 ff.set(LuaKey::Str("Height".to_owned()), LuaValue::Number(self.height as f64));541 ff.set(LuaKey::Str("Height".to_owned()), LuaValue::Number(self.height as f64));
560 }542 }
561 if ff.get_f64("Rate").is_none_or(|r| (r - self.fps).abs() > 1e-9) {543 if ff
544 .get_f64("Rate")
545 .is_none_or(|r| !r.is_finite() || (r - self.fps).abs() > 1e-9)
546 {
562 ff.set(LuaKey::Str("Rate".to_owned()), LuaValue::Number(self.fps));547 ff.set(LuaKey::Str("Rate".to_owned()), LuaValue::Number(self.fps));
563 }548 }
564 let existing_depth = ff549 let existing_depth = ff
565 .get_f64("DepthFull")550 .get_f64("DepthFull")
551 .filter(|v| v.is_finite())
566 .and_then(|v| BitDepth::from_fusion_depth(v.round() as i32))552 .and_then(|v| BitDepth::from_fusion_depth(v.round() as i32))
567 .unwrap_or(BitDepth::Int8);553 .unwrap_or(BitDepth::Int8);
568 if existing_depth != self.depth_full {554 if existing_depth != self.depth_full {
...@@ -933,6 +919,9 @@ impl Comp {...@@ -933,6 +919,9 @@ impl Comp {
933 if !remaining_splines.is_empty() {919 if !remaining_splines.is_empty() {
934 for (k, v) in &inner_tools.entries {920 for (k, v) in &inner_tools.entries {
935 let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { continue };921 let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { continue };
922 if !is_modifier_type(tbl.tag.as_deref().unwrap_or("Unknown")) {
923 continue;
924 }
936 if !top_level_spline_names.contains(name.as_str())925 if !top_level_spline_names.contains(name.as_str())
937 && !claimed_splines.contains(name.as_str())926 && !claimed_splines.contains(name.as_str())
938 {927 {
...@@ -1116,7 +1105,10 @@ fn commit_inner_tools_verbatim<'a>(...@@ -1116,7 +1105,10 @@ fn commit_inner_tools_verbatim<'a>(
1116 // (matching `sync_existing_splines_in_tools` top-down order).1105 // (matching `sync_existing_splines_in_tools` top-down order).
1117 if !remaining_splines.is_empty() {1106 if !remaining_splines.is_empty() {
1118 for (k, v) in &inner_tools.entries {1107 for (k, v) in &inner_tools.entries {
1119 let (LuaKey::Str(name), Some(_)) = (k, v.as_table()) else { continue };1108 let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { continue };
1109 if !is_modifier_type(tbl.tag.as_deref().unwrap_or("Unknown")) {
1110 continue;
1111 }
1120 if !top_level_spline_names.contains(name.as_str()) {1112 if !top_level_spline_names.contains(name.as_str()) {
1121 remaining_splines.remove(name.as_str());1113 remaining_splines.remove(name.as_str());
1122 if remaining_splines.is_empty() {1114 if remaining_splines.is_empty() {
...@@ -1157,6 +1149,9 @@ fn nested_splines_verbatim<'a, 'b>(...@@ -1157,6 +1149,9 @@ fn nested_splines_verbatim<'a, 'b>(
1157 }1149 }
1158 for (k, v) in &tools.entries {1150 for (k, v) in &tools.entries {
1159 let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { continue };1151 let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { continue };
1152 if !is_modifier_type(tbl.tag.as_deref().unwrap_or("Unknown")) {
1153 continue;
1154 }
1160 if !top_level_spline_names.contains(name.as_str())1155 if !top_level_spline_names.contains(name.as_str())
1161 && !claimed_splines.contains(name.as_str())1156 && !claimed_splines.contains(name.as_str())
1162 {1157 {
...@@ -1192,7 +1187,10 @@ fn consume_nested_splines(...@@ -1192,7 +1187,10 @@ fn consume_nested_splines(
1192 return;1187 return;
1193 }1188 }
1194 for (k, v) in &tools.entries {1189 for (k, v) in &tools.entries {
1195 let (LuaKey::Str(name), Some(_)) = (k, v.as_table()) else { continue };1190 let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { continue };
1191 if !is_modifier_type(tbl.tag.as_deref().unwrap_or("Unknown")) {
1192 continue;
1193 }
1196 if !top_level_spline_names.contains(name.as_str()) {1194 if !top_level_spline_names.contains(name.as_str()) {
1197 remaining_splines.remove(name.as_str());1195 remaining_splines.remove(name.as_str());
1198 if remaining_splines.is_empty() {1196 if remaining_splines.is_empty() {
...@@ -1220,7 +1218,7 @@ fn sync_existing_splines_in_tools_excluding(...@@ -1220,7 +1218,7 @@ fn sync_existing_splines_in_tools_excluding(
1220 }1218 }
1221 for (k, v) in &mut tools.entries {1219 for (k, v) in &mut tools.entries {
1222 let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table_mut()) else { continue };1220 let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table_mut()) else { continue };
1223 if excluded.contains(name.as_str()) {1221 if !is_modifier_type(tbl.tag.as_deref().unwrap_or("Unknown")) || excluded.contains(name.as_str()) {
1224 continue;1222 continue;
1225 }1223 }
1226 if let Some(spline) = remaining.remove(name.as_str()) {1224 if let Some(spline) = remaining.remove(name.as_str()) {
...@@ -1799,6 +1797,9 @@ fn sync_existing_splines_in_tools(tools: &mut LuaTable, remaining: &mut HashMap<...@@ -1799,6 +1797,9 @@ fn sync_existing_splines_in_tools(tools: &mut LuaTable, remaining: &mut HashMap<
1799 }1797 }
1800 for (k, v) in &mut tools.entries {1798 for (k, v) in &mut tools.entries {
1801 let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table_mut()) else { continue };1799 let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table_mut()) else { continue };
1800 if !is_modifier_type(tbl.tag.as_deref().unwrap_or("Unknown")) {
1801 continue;
1802 }
1802 if let Some(spline) = remaining.remove(name.as_str()) {1803 if let Some(spline) = remaining.remove(name.as_str()) {
1803 sync_spline_table(name, spline, tbl);1804 sync_spline_table(name, spline, tbl);
1804 if remaining.is_empty() {1805 if remaining.is_empty() {
crates/model/src/expr.rs+3
...@@ -715,6 +715,9 @@ mod pure {...@@ -715,6 +715,9 @@ mod pure {
715 let mut toks = Vec::new();715 let mut toks = Vec::new();
716 let mut i = 0;716 let mut i = 0;
717 while i < chars.len() {717 while i < chars.len() {
718 if toks.len() >= MAX_TOKENS {
719 return None;
720 }
718 let c = chars[i];721 let c = chars[i];
719 if c.is_whitespace() {722 if c.is_whitespace() {
720 i += 1;723 i += 1;
crates/model/src/lua_value.rs+35-15
...@@ -182,9 +182,12 @@ pub fn parse_lua(input: &str) -> Result<LuaValue, ParseError> {...@@ -182,9 +182,12 @@ pub fn parse_lua(input: &str) -> Result<LuaValue, ParseError> {
182 Ok(val)182 Ok(val)
183}183}
184184
185const MAX_PARSE_DEPTH: usize = 128;
186
185struct Parser<'a> {187struct Parser<'a> {
186 src: &'a [u8],188 src: &'a [u8],
187 pos: usize,189 pos: usize,
190 depth: usize,
188}191}
189192
190impl<'a> Parser<'a> {193impl<'a> Parser<'a> {
...@@ -194,7 +197,17 @@ impl<'a> Parser<'a> {...@@ -194,7 +197,17 @@ impl<'a> Parser<'a> {
194 if input.as_bytes().starts_with(&[0xEF, 0xBB, 0xBF]) {197 if input.as_bytes().starts_with(&[0xEF, 0xBB, 0xBF]) {
195 pos = 3;198 pos = 3;
196 }199 }
197 Self { src: input.as_bytes(), pos }200 Self { src: input.as_bytes(), pos, depth: 0 }
201 }
202
203 fn with_depth<T>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, ParseError>) -> Result<T, ParseError> {
204 if self.depth >= MAX_PARSE_DEPTH {
205 return Err(self.err(format!("maximum nesting depth ({MAX_PARSE_DEPTH}) exceeded")));
206 }
207 self.depth += 1;
208 let res = f(self);
209 self.depth -= 1;
210 res
198 }211 }
199212
200 fn err(&self, msg: impl Into<String>) -> ParseError {213 fn err(&self, msg: impl Into<String>) -> ParseError {
...@@ -387,22 +400,25 @@ impl<'a> Parser<'a> {...@@ -387,22 +400,25 @@ impl<'a> Parser<'a> {
387 // Handle calls like `ordered() { ... }` or `FuID("...")` or `Clip(...)`400 // Handle calls like `ordered() { ... }` or `FuID("...")` or `Clip(...)`
388 if self.peek() == Some(b'(') {401 if self.peek() == Some(b'(') {
389 self.pos += 1;402 self.pos += 1;
390 let mut args = Vec::new();403 let args = self.with_depth(|p| {
391 self.skip_ws_and_comments()?;404 let mut args = Vec::new();
392 if self.peek() != Some(b')') {405 p.skip_ws_and_comments()?;
393 loop {406 if p.peek() != Some(b')') {
394 args.push(self.parse_value()?);407 loop {
395 self.skip_ws_and_comments()?;408 args.push(p.parse_value()?);
396 if self.peek() == Some(b',') {409 p.skip_ws_and_comments()?;
397 self.pos += 1;410 if p.peek() == Some(b',') {
398 } else {411 p.pos += 1;
399 break;412 } else {
413 break;
414 }
400 }415 }
401 }416 }
402 }417 if p.bump() != Some(b')') {
403 if self.bump() != Some(b')') {418 return Err(p.err(format!("expected ')' after {ident}(...")));
404 return Err(self.err(format!("expected ')' after {ident}(...")));419 }
405 }420 Ok(args)
421 })?;
406 self.skip_ws_and_comments()?;422 self.skip_ws_and_comments()?;
407 if self.peek() == Some(b'{') {423 if self.peek() == Some(b'{') {
408 let mut table = self.parse_table(Some(ident))?;424 let mut table = self.parse_table(Some(ident))?;
...@@ -438,6 +454,10 @@ impl<'a> Parser<'a> {...@@ -438,6 +454,10 @@ impl<'a> Parser<'a> {
438 }454 }
439455
440 fn parse_table(&mut self, tag: Option<String>) -> Result<LuaTable, ParseError> {456 fn parse_table(&mut self, tag: Option<String>) -> Result<LuaTable, ParseError> {
457 self.with_depth(|p| p.parse_table_inner(tag))
458 }
459
460 fn parse_table_inner(&mut self, tag: Option<String>) -> Result<LuaTable, ParseError> {
441 if self.bump() != Some(b'{') {461 if self.bump() != Some(b'{') {
442 return Err(self.err("expected '{'"));462 return Err(self.err("expected '{'"));
443 }463 }
crates/model/src/spline.rs+30-11
...@@ -83,10 +83,19 @@ impl BezierSpline {...@@ -83,10 +83,19 @@ impl BezierSpline {
83 LuaKey::Number(n) => *n,83 LuaKey::Number(n) => *n,
84 _ => continue,84 _ => continue,
85 };85 };
86 if !time.is_finite() {
87 continue;
88 }
86 let Some(kt) = v.as_table() else { continue };89 let Some(kt) = v.as_table() else { continue };
87 let value = kt.get_index(1).and_then(LuaValue::as_f64).unwrap_or(0.0);90 let value = kt.get_index(1).and_then(LuaValue::as_f64).unwrap_or(0.0);
88 let lh = kt.get_table("LH").and_then(read_vec2);91 if !value.is_finite() {
89 let rh = kt.get_table("RH").and_then(read_vec2);92 continue;
93 }
94 let finite_vec2 = |t: &LuaTable| {
95 read_vec2(t).filter(|[x, y]| x.is_finite() && y.is_finite())
96 };
97 let lh = kt.get_table("LH").and_then(finite_vec2);
98 let rh = kt.get_table("RH").and_then(finite_vec2);
90 let mut flags = KeyFlags::default();99 let mut flags = KeyFlags::default();
91 if let Some(ft) = kt.get_table("Flags") {100 if let Some(ft) = kt.get_table("Flags") {
92 flags.linear = ft.get_bool("Linear").unwrap_or(false);101 flags.linear = ft.get_bool("Linear").unwrap_or(false);
...@@ -133,17 +142,19 @@ impl BezierSpline {...@@ -133,17 +142,19 @@ impl BezierSpline {
133 let last = &kfs[kfs.len() - 1];142 let last = &kfs[kfs.len() - 1];
134143
135 // Fusion never loops backwards before the first keyframe (`Loop` / `LoopRel` / `PingPong` all clamp).144 // Fusion never loops backwards before the first keyframe (`Loop` / `LoopRel` / `PingPong` all clamp).
136 if t <= first.time {145 if t.is_nan() || t <= first.time {
137 return first.value;146 return first.value;
138 }147 }
139148
140 // In Fusion, `Loop` / `LoopRel` requires at least two loop-flagged keyframes (`loop_start < loop_end`).149 // In Fusion, `Loop` / `LoopRel` requires at least two loop-flagged keyframes (`loop_start < loop_end`).
141 // The loop repeats `[loop_start, loop_end]` for `t >= loop_end.time` up to the next keyframe (if any).150 // The loop repeats `[loop_start, loop_end]` for `t >= loop_end.time` up to the next keyframe (if any).
142 let is_loop_key = |k: &Keyframe| k.flags.loop_after || k.flags.loop_rel;151 let is_loop_key = |k: &Keyframe| k.flags.loop_after || k.flags.loop_rel;
143 let loop_pair = kfs.iter().position(is_loop_key).and_then(|s| {152 let loop_pair = t.is_finite().then(|| {
144 let e = kfs.iter().rposition(is_loop_key)?;153 kfs.iter().position(is_loop_key).and_then(|s| {
145 (s < e).then_some((s, e))154 let e = kfs.iter().rposition(is_loop_key)?;
146 });155 (s < e).then_some((s, e))
156 })
157 }).flatten();
147158
148 let mut t = t;159 let mut t = t;
149 let mut value_offset = 0.0_f64;160 let mut value_offset = 0.0_f64;
...@@ -230,13 +241,14 @@ pub fn segment_control_points(k0: &Keyframe, k1: &Keyframe) -> [[f64; 2]; 4] {...@@ -230,13 +241,14 @@ pub fn segment_control_points(k0: &Keyframe, k1: &Keyframe) -> [[f64; 2]; 4] {
230 let p3 = [k1.time, k1.value];241 let p3 = [k1.time, k1.value];
231 let dt = k1.time - k0.time;242 let dt = k1.time - k0.time;
232 let dv = k1.value - k0.value;243 let dv = k1.value - k0.value;
233 // Keys can be transiently unsorted mid-drag; `f64::clamp` would panic on `lo > hi`.244 // Keys can be transiently unsorted mid-drag; `f64::clamp` would panic on `lo > hi` or `NaN`.
234 let (t_lo, t_hi) = (k0.time.min(k1.time), k0.time.max(k1.time));245 let (t_lo, t_hi) = (k0.time.min(k1.time), k0.time.max(k1.time));
246 let clamp_t = |x: f64| if t_lo <= t_hi { x.clamp(t_lo, t_hi) } else { x };
235247
236 let p1 = if k1.flags.linear && k0.rh.is_none() {248 let p1 = if k1.flags.linear && k0.rh.is_none() {
237 [k0.time + dt / 3.0, k0.value + dv / 3.0]249 [k0.time + dt / 3.0, k0.value + dv / 3.0]
238 } else if let Some(rh) = k0.rh {250 } else if let Some(rh) = k0.rh {
239 [rh[0].clamp(t_lo, t_hi), rh[1]]251 [clamp_t(rh[0]), rh[1]]
240 } else {252 } else {
241 [k0.time + dt / 3.0, k0.value + dv / 3.0]253 [k0.time + dt / 3.0, k0.value + dv / 3.0]
242 };254 };
...@@ -244,7 +256,7 @@ pub fn segment_control_points(k0: &Keyframe, k1: &Keyframe) -> [[f64; 2]; 4] {...@@ -244,7 +256,7 @@ pub fn segment_control_points(k0: &Keyframe, k1: &Keyframe) -> [[f64; 2]; 4] {
244 let p2 = if k1.flags.linear && k1.lh.is_none() {256 let p2 = if k1.flags.linear && k1.lh.is_none() {
245 [k1.time - dt / 3.0, k1.value - dv / 3.0]257 [k1.time - dt / 3.0, k1.value - dv / 3.0]
246 } else if let Some(lh) = k1.lh {258 } else if let Some(lh) = k1.lh {
247 [lh[0].clamp(t_lo, t_hi), lh[1]]259 [clamp_t(lh[0]), lh[1]]
248 } else {260 } else {
249 [k1.time - dt / 3.0, k1.value - dv / 3.0]261 [k1.time - dt / 3.0, k1.value - dv / 3.0]
250 };262 };
...@@ -428,9 +440,16 @@ impl PolyPath {...@@ -428,9 +440,16 @@ impl PolyPath {
428 }440 }
429 }441 }
430442
431 if cum_len <= 1e-12 {443 if cum_len <= 1e-12 || displacement.is_nan() {
432 return samples[0].1;444 return samples[0].1;
433 }445 }
446 if !displacement.is_finite() {
447 return if displacement.is_sign_positive() {
448 samples[samples.len() - 1].1
449 } else {
450 samples[0].1
451 };
452 }
434 // Extrapolate smoothly along end/start tangent when displacement is outside [0, 1]453 // Extrapolate smoothly along end/start tangent when displacement is outside [0, 1]
435 if displacement > 1.0 && samples.len() >= 2 {454 if displacement > 1.0 && samples.len() >= 2 {
436 let (l0, v0) = samples[samples.len() - 2];455 let (l0, v0) = samples[samples.len() - 2];
crates/model/tests/hardening_model.rs created+447
...@@ -0,0 +1,447 @@
1use model::comp::{BitDepth, Comp, NodeId, ParamValue, SaverSpec};
2use model::edit::CompHistory;
3use model::expr::ExprEngine;
4use model::lua_value::{LuaTable, parse_lua};
5use model::spline::{BezierSpline, HandleMode, KeyFlags, Keyframe, PolyPath, PolyPoint, segment_control_points};
6use std::collections::HashMap;
7
8fn ast_fusion_string(comp: &Comp) -> String {
9 let mut s = comp.sync_to_raw_ast().to_fusion_string();
10 if !s.ends_with('\n') {
11 s.push('\n');
12 }
13 s
14}
15
16fn assert_save_equivalence_and_reparse(comp: &Comp) {
17 let streamed = comp.to_fusion_string();
18 let ast = ast_fusion_string(comp);
19 assert_eq!(streamed, ast, "streaming vs AST save divergence");
20 Comp::from_fusion_str(&streamed).expect("saved comp must re-parse cleanly");
21}
22
23#[test]
24fn lua_parser_bounds_deep_nesting_without_stack_overflow() {
25 for depth in [200, 500, 5000] {
26 let open_tables = "{".repeat(depth);
27 assert!(parse_lua(&open_tables).is_err(), "unclosed tables depth {depth}");
28
29 let closed_tables = format!("{}1{}", "{".repeat(depth), "}".repeat(depth));
30 assert!(parse_lua(&closed_tables).is_err(), "closed tables depth {depth}");
31
32 let nested_calls = format!("{}1{}", "Foo(".repeat(depth), ")".repeat(depth));
33 assert!(parse_lua(&nested_calls).is_err(), "nested calls depth {depth}");
34
35 let nested_keys = format!("{}1{}", "{[".repeat(depth), "]=1}".repeat(depth));
36 assert!(parse_lua(&nested_keys).is_err(), "nested keys depth {depth}");
37
38 let nested_groups = format!(
39 "Composition {{ Tools = ordered() {{ {} }} }}",
40 "G = GroupOperator { Tools = ordered() { ".repeat(depth / 2)
41 + &"} } ".repeat(depth / 2)
42 );
43 assert!(Comp::from_fusion_str(&nested_groups).is_err(), "nested groups depth {depth}");
44 }
45
46 // Legitimate Fusion-like nesting well under the cap still parses cleanly.
47 let ok = format!("{}42{}", "{".repeat(32), "}".repeat(32));
48 assert!(parse_lua(&ok).is_ok());
49}
50
51#[test]
52fn malformed_comp_prefixes_escapes_nul_brackets_and_huge_numbers_never_panic() {
53 let sample = r#"Composition {
54 CurrentTime = 10,
55 GlobalRange = { 0, 100 },
56 RenderRange = { 0, 100 },
57 Prefs = { Comp = { FrameFormat = { Width = 1920, Height = 1080, Rate = 24 } } },
58 Tools = ordered() {
59 BG1 = Background { Inputs = { Width = Input { Value = 1920 } } },
60 Blur1 = Blur { Inputs = { Input = Input { SourceOp = "BG1", Source = "Output" } } },
61 },
62 }"#;
63
64 // Every UTF-8 prefix truncation must return Ok or Err without panicking or hanging.
65 for (idx, _) in sample.char_indices() {
66 let _ = Comp::from_fusion_str(&sample[..idx]);
67 }
68
69 // Deterministic byte/char mutations over a representative comp never panic or hang.
70 let mut seed = 0x9E37_79B9_7F4A_7C15u64;
71 let mut next_u32 = || -> u32 {
72 seed ^= seed << 13;
73 seed ^= seed >> 7;
74 seed ^= seed << 17;
75 (seed >> 16) as u32
76 };
77 let sample_bytes = sample.as_bytes();
78 for _ in 0..256 {
79 let mut buf = sample_bytes.to_vec();
80 let edits = 1 + (next_u32() as usize % 6);
81 for _ in 0..edits {
82 let pos = next_u32() as usize % buf.len();
83 match next_u32() % 3 {
84 0 => buf[pos] = next_u32() as u8,
85 1 if buf.len() > 1 => {
86 buf.remove(pos);
87 }
88 _ => buf.insert(pos, next_u32() as u8),
89 }
90 }
91 let mutated = String::from_utf8_lossy(&buf);
92 if let Ok(comp) = Comp::from_fusion_str(&mutated) {
93 let _ = comp.to_fusion_string();
94 }
95 }
96
97 // Bad escapes, unterminated strings/long brackets/comments, bare NUL bytes.
98 for bad in [
99 "",
100 " -- just a comment",
101 "\0",
102 "Composition { \0 }",
103 r#"Composition { Name = "unterminated"#,
104 r#"Composition { Name = "bad\x" }"#,
105 r#"Composition { Name = "bad\xZZ" }"#,
106 r#"Composition { Name = [===[unterminated ]==] }"#,
107 r#"--[===[unterminated comment ]==] Composition {}"#,
108 "12345",
109 "nil",
110 "\"not a table\"",
111 ] {
112 assert!(Comp::from_fusion_str(bad).is_err(), "expected Err for {bad:?}");
113 }
114
115 // NUL inside quoted strings/long brackets/comments and huge numbers survive roundtrip.
116 let weird = concat!(
117 "-- comment with \0 nul\n",
118 "Composition {\n",
119 "\tTools = ordered() {\n",
120 "\t\tN1 = Note { Inputs = { Comments = Input { Value = \"a\0b\\255\" } } },\n",
121 "\t\tN2 = Note { Inputs = { Comments = Input { Value = [=[x\0y]=] } } },\n",
122 "\t\tB1 = Blur { Inputs = { XBlurSize = Input { Value = 1e9999 } } },\n",
123 "\t\tB2 = Blur { Inputs = { XBlurSize = Input { Value = -1e9999 } } },\n",
124 "\t\tB3 = Blur {},\n",
125 "\t},\n",
126 "}\n"
127 );
128 let comp = Comp::from_fusion_str(weird).expect("weird valid comp parses");
129 assert_save_equivalence_and_reparse(&comp);
130}
131
132#[test]
133fn non_finite_and_degenerate_metadata_normalizes_and_saves_equivalently() {
134 let weird_meta = r#"Composition {
135 CurrentTime = nan,
136 AudioOffset = 1e9999,
137 GlobalRange = { nan, 1e9999 },
138 RenderRange = { -1e9999, nan },
139 Prefs = { Comp = { FrameFormat = { Width = 1e9999, Height = nan, Rate = 1e9999, DepthFull = nan } } },
140 Tools = ordered() {
141 A = Blur {},
142 B = Blur {},
143 C = Blur {},
144 D = Blur {},
145 E = Blur {},
146 },
147 }"#;
148 let comp = Comp::from_fusion_str(weird_meta).expect("parses comp with non-finite metadata");
149 assert_eq!(comp.width, 1920);
150 assert_eq!(comp.height, 1080);
151 assert_eq!(comp.fps, 30.0);
152 assert_eq!(comp.depth_full, BitDepth::Int8);
153 assert_eq!(comp.current_time, 0.0);
154 assert_eq!(comp.audio_offset, 0.0);
155 assert_eq!(comp.global_range, [0, 1000]);
156 assert_eq!(comp.render_range, [0, 1000]);
157 assert_save_equivalence_and_reparse(&comp);
158
159 // Non-table Prefs / Tools, empty Tools, and inferred huge Background sizes.
160 for src in [
161 "Composition { Prefs = 123, Tools = 123 }",
162 "Composition { Prefs = { Comp = 123 }, Tools = {} }",
163 "Composition { Tools = ordered() {} }",
164 "Composition { Prefs = { Comp = { FrameFormat = { Width = 1e20, Height = 1e20, Rate = nan } } }, Tools = ordered() { A = Blur {}, B = Blur {}, C = Blur {}, D = Blur {}, E = Blur {} } }",
165 "Composition { Tools = ordered() { BG = Background { Inputs = { Width = Input { Value = 1e9999 }, Height = Input { Value = 1e9999 } } } } }",
166 ] {
167 let c = Comp::from_fusion_str(src).expect(src);
168 assert!(c.width <= 65536 && c.height <= 65536);
169 assert!(c.fps.is_finite() && c.fps > 0.0);
170 assert_save_equivalence_and_reparse(&c);
171 }
172
173 // Duplicate flow + modifier name in Tools must not diverge between streaming and AST save.
174 let dup_name = r#"Composition {
175 Tools = ordered() {
176 Foo = Blur {},
177 Foo = BezierSpline { KeyFrames = { [0] = { 1, Flags = { Linear = true } } } },
178 B = Blur {},
179 C = Blur {},
180 D = Blur {},
181 },
182 }"#;
183 let mut comp = Comp::from_fusion_str(dup_name).expect("dup name parses");
184 comp.splines.get_mut("Foo").unwrap().keyframes[0].value = 2.5;
185 assert_save_equivalence_and_reparse(&comp);
186}
187
188#[test]
189fn cyclic_source_op_and_grid_mesh_overflow_and_utf8_saver_path_do_not_panic() {
190 let cyclic = r#"Composition {
191 Tools = ordered() {
192 A = ColorCorrector { SourceOp = "B", Inputs = { MasterRGBGain = Input { Value = 2 } } },
193 B = ColorCorrector { SourceOp = "A" },
194 SelfInst = ColorCorrector { SourceOp = "SelfInst" },
195 GW = GridWarp {
196 Inputs = {
197 SrcMesh = Input {
198 Value = Mesh {
199 Col = 1e9999,
200 Points = {
201 { X = 0, Y = 0 }, { X = 1, Y = 0 },
202 { X = 0, Y = 1 }, { X = 1, Y = 1 },
203 },
204 },
205 },
206 },
207 },
208 },
209 }"#;
210 let comp = Comp::from_fusion_str(cyclic).expect("cyclic SourceOp parses");
211 let gw = comp.node(comp.find_node("GW").unwrap());
212 assert!(comp.eval_grid_mesh(gw, "SrcMesh", 0.0).is_none());
213 assert!(comp.eval_grid_mesh(gw, "SrcMesh", f64::NAN).is_none());
214
215 // Multi-byte UTF-8 Saver stem + extreme range must never slice mid-char or overflow i64.
216 for filename in ["render_é.png", "出力.exr", "frame_é001.exr", "plain.png"] {
217 let spec = SaverSpec {
218 node_id: NodeId(0),
219 name: "S".to_owned(),
220 upstream: None,
221 filename: filename.to_owned(),
222 range: [i64::MIN, i64::MAX],
223 sequence_start: Some(10),
224 };
225 let p = spec.frame_path(100);
226 assert!(!p.as_os_str().is_empty());
227 }
228}
229
230#[test]
231fn expression_engine_math_dsl_and_shake_handle_cycles_depth_and_non_finite_time() {
232 let expr = ExprEngine::new();
233
234 // Non-finite times & expressions never panic in Lua or format_number.
235 let empty_nums = HashMap::new();
236 let empty_pts = HashMap::new();
237 let empty_nodes = HashMap::new();
238 for t in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 0.0] {
239 let _ = expr.eval_number("time + 1", t, &empty_nums, &empty_pts, &empty_nodes);
240 let _ = expr.eval_string("tostring(time)", t, &empty_nums, &empty_pts, &empty_nodes);
241 let _ = expr.eval_point("Point(time, 0/0)", t, &empty_nums, &empty_pts, &empty_nodes);
242 }
243 assert_eq!(
244 expr.eval_string("0/0", 0.0, &empty_nums, &empty_pts, &empty_nodes).as_deref(),
245 Some("nan")
246 );
247 assert_eq!(
248 expr.eval_string("1/0", 0.0, &empty_nums, &empty_pts, &empty_nodes).as_deref(),
249 Some("inf")
250 );
251 assert_eq!(
252 expr.eval_string("-1/0", 0.0, &empty_nums, &empty_pts, &empty_nodes).as_deref(),
253 Some("-inf")
254 );
255
256 // Deeply nested expressions in ExpressionModifier math DSL & Lua must not overflow stack.
257 let deep_parens = format!("{}1{}", "(".repeat(4000), ")".repeat(4000));
258 let deep_unary = format!("{}1", "-".repeat(4000));
259 let deep_pow = format!("{}2", "2^".repeat(4000));
260 let src = format!(
261 r#"Composition {{
262 Tools = ordered() {{
263 A = Transform {{
264 Inputs = {{
265 Size = Input {{ Expression = "B.Size", }},
266 Angle = Input {{ SourceOp = "Shk", Source = "X", }},
267 Width = Input {{ SourceOp = "EM1", Source = "NumberResult", }},
268 Height = Input {{ SourceOp = "EM2", Source = "NumberResult", }},
269 Edges = Input {{ SourceOp = "EM3", Source = "NumberResult", }},
270 }},
271 }},
272 B = Transform {{
273 Inputs = {{
274 Size = Input {{ Expression = "A.Size", }},
275 }},
276 }},
277 Shk = Shake {{
278 Inputs = {{
279 Smoothness = Input {{ Value = 0.01 }},
280 XMinimum = Input {{ Value = 0 }},
281 XMaximum = Input {{ Value = 10 }},
282 }},
283 }},
284 EM1 = Expression {{ Inputs = {{ NumberExpression = Input {{ Value = "{deep_parens}" }} }} }},
285 EM2 = Expression {{ Inputs = {{ NumberExpression = Input {{ Value = "{deep_unary}" }} }} }},
286 EM3 = Expression {{ Inputs = {{ NumberExpression = Input {{ Value = "{deep_pow}" }} }} }},
287 }},
288 }}"#
289 );
290 let comp = Comp::from_fusion_str(&src).expect("comp parses");
291 let a = comp.node(comp.find_node("A").unwrap());
292
293 for t in [0.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 1e20, -1e20] {
294 // Cyclic NodeA.P <-> NodeB.P terminates cleanly.
295 assert_eq!(comp.eval_number(a, "Size", t, 42.0, &expr), 42.0);
296 // Shake at huge / non-finite times never panics with i64 overflow.
297 let shk = comp.eval_number(a, "Angle", t, -1.0, &expr);
298 assert!(shk.is_finite());
299 // Deep ExpressionModifier formulas don't overflow stack.
300 assert_eq!(comp.eval_number(a, "Width", t, 7.0, &expr), 7.0);
301 assert_eq!(comp.eval_number(a, "Height", t, 7.0, &expr), 7.0);
302 assert_eq!(comp.eval_number(a, "Edges", t, 7.0, &expr), 7.0);
303 }
304}
305
306#[test]
307fn splines_and_polypaths_survive_degenerate_keys_nan_and_inf() {
308 // Empty & 1-key splines
309 let empty_sp = BezierSpline {
310 name: "e".to_owned(),
311 color: [0, 0, 0],
312 keyframes: vec![],
313 };
314 assert_eq!(empty_sp.eval(f64::NAN), 0.0);
315 assert_eq!(empty_sp.eval(f64::INFINITY), 0.0);
316
317 // Manually constructed NaN-timed keyframes with handles must not panic in segment_control_points.
318 let mut k0 = Keyframe::new(f64::NAN, 1.0);
319 k0.rh = Some([1.0, 2.0]);
320 let mut k1 = Keyframe::new(f64::NAN, 3.0);
321 k1.lh = Some([2.0, 4.0]);
322 let _ = segment_control_points(&k0, &k1);
323
324 // Loop spline evaluated at NaN / Inf / -Inf must stay finite (no inf - inf = NaN).
325 let lp = KeyFlags {
326 linear: true,
327 loop_after: true,
328 ..Default::default()
329 };
330 let mut sp = BezierSpline {
331 name: "loop".to_owned(),
332 color: [255, 255, 255],
333 keyframes: vec![
334 Keyframe { time: 20.0, value: 2.0, lh: None, rh: None, flags: lp, handle_mode: HandleMode::Vector },
335 Keyframe { time: 10.0, value: 1.0, lh: None, rh: None, flags: lp, handle_mode: HandleMode::Vector },
336 Keyframe { time: 10.0, value: 1.5, lh: None, rh: None, flags: lp, handle_mode: HandleMode::Vector },
337 ],
338 };
339 sp.sort();
340 for t in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 10.0, 15.0, 25.0] {
341 assert!(sp.eval(t).is_finite(), "non-finite eval at t={t}");
342 }
343
344 // Malformed KeyFrames table with nan/inf keys & handles filters non-finite entries cleanly.
345 let sp_tbl = parse_lua(
346 r#"BezierSpline {
347 KeyFrames = {
348 [nan] = { 1, LH = { nan, 0 }, RH = { inf, 0 } },
349 [inf] = { 2 },
350 [0] = { nan },
351 [5] = { 0.5, LH = { nan, 1 } },
352 [10] = { 1.5 },
353 },
354 }"#,
355 )
356 .unwrap();
357 let parsed_sp = BezierSpline::from_lua("s".to_owned(), sp_tbl.as_table().unwrap());
358 assert_eq!(parsed_sp.keyframes.len(), 2);
359 assert!(parsed_sp.keyframes[0].lh.is_none());
360 assert!(parsed_sp.eval(f64::NAN).is_finite());
361
362 // PolyPath at NaN / Inf / -Inf stays finite.
363 let pp = PolyPath {
364 name: "p".to_owned(),
365 displacement_op: None,
366 displacement_value: 0.0,
367 closed: false,
368 points: vec![
369 PolyPoint { x: 0.0, y: 0.0, lx: 0.0, ly: 0.0, rx: 0.0, ry: 0.0, linear: true },
370 PolyPoint { x: 0.5, y: 0.0, lx: 0.0, ly: 0.0, rx: 0.0, ry: 0.0, linear: true },
371 ],
372 };
373 for d in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
374 let p = pp.eval_center(d);
375 assert!(p[0].is_finite() && p[1].is_finite(), "non-finite PolyPath at d={d}");
376 }
377}
378
379#[test]
380fn comp_history_and_edits_handle_stale_ids_and_rapid_roundtrips() {
381 let mut comp = Comp::from_fusion_str("Composition { Tools = ordered() {} }").unwrap();
382 let mut history = CompHistory::with_max_depth(8);
383 history.mark_saved(&comp);
384
385 let stale = NodeId(999);
386 assert!(comp.set_keyframe(stale, "Gain", 0.0, 1.0).is_err());
387 assert!(!comp.delete_keyframe("MissingSpline", 0.0));
388 assert!(comp.rename_node(stale, "ValidName").is_err());
389 assert!(comp.connect_output(stale, "Output", stale, "Input").is_err());
390 assert!(!comp.disconnect(stale, "Input"));
391 assert!(comp.splice_node_into_pipe(stale, stale, stale, "Input").is_err());
392 assert!(!comp.set_input_value(stale, "Gain", ParamValue::Number(1.0)));
393 assert!(!comp.set_input_expression(stale, "Gain", Some("1".to_owned())));
394 assert!(!comp.toggle_passthrough(stale));
395 comp.set_node_pos(stale, [1.0, 2.0]);
396 assert!(comp.delete_nodes(&[stale]).is_empty());
397 assert!(comp.node_splines(stale).is_empty());
398 assert!(history.paste_fusion_clipboard(&mut comp, "{{{{{", (0.0, 0.0)).is_err());
399 assert!(!history.undo(&mut comp));
400 assert!(!history.redo(&mut comp));
401
402 // Rapid add -> wire -> keyframe -> rename -> splice -> delete -> undo -> redo sequence.
403 history.push_snapshot(&comp, "Add BG");
404 let bg = comp.add_node("Background", None, [0.0, 0.0]);
405 assert!(comp.rename_node(bg, "123bad").is_err());
406 assert!(comp.rename_node(bg, "end").is_err());
407 assert!(comp.rename_node(bg, "").is_err());
408
409 history.push_snapshot(&comp, "Add Merge");
410 let merge = comp.add_node("Merge", None, [200.0, 0.0]);
411 comp.connect_output(bg, "Output", merge, "Background").unwrap();
412
413 history.push_snapshot(&comp, "Keyframe & Splice");
414 let sp = comp.set_keyframe(merge, "Blend", 10.0, 0.5).unwrap();
415 assert!(comp.set_keyframe(merge, "Blend", f64::NAN, 1.0).is_err());
416 let blur = comp.add_node("Blur", None, [100.0, 0.0]);
417 comp.splice_node_into_pipe(blur, bg, merge, "Background").unwrap();
418 assert_save_equivalence_and_reparse(&comp);
419
420 history.push_snapshot(&comp, "Rename & Delete key");
421 comp.rename_node(blur, "SoftBlur").unwrap();
422 assert!(comp.delete_keyframe(&sp, 10.0));
423 assert!(!comp.delete_keyframe(&sp, f64::NAN));
424 assert_save_equivalence_and_reparse(&comp);
425
426 history.push_snapshot(&comp, "Delete Blur");
427 comp.delete_nodes(&[blur]);
428 assert_save_equivalence_and_reparse(&comp);
429
430 // Undo everything back to empty and redo everything forward.
431 while history.undo(&mut comp) {
432 assert_save_equivalence_and_reparse(&comp);
433 }
434 assert!(comp.nodes.is_empty());
435 while history.redo(&mut comp) {
436 assert_save_equivalence_and_reparse(&comp);
437 }
438
439 // Cancel and commit group edge cases.
440 assert!(!history.commit_group(&comp));
441 assert!(!history.cancel_group(&mut comp));
442 history.begin_group(&comp, "Canceled");
443 let _tmp = comp.add_node("Note", None, [0.0, 0.0]);
444 assert!(history.cancel_group(&mut comp));
445 assert_save_equivalence_and_reparse(&comp);
446 let _ = LuaTable::default();
447}