PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Timeline: out-of-range duration and fps are rejected; stepping never panics (#1009) (#1023)
yange1a874d9e937
diff --git a/crates/doc/src/video.rs b/crates/doc/src/video.rsindex 50b0d9f58..4ed25b11a 100644--- a/crates/doc/src/video.rs+++ b/crates/doc/src/video.rs@@ -68,24 +68,37 @@ pub struct Timeline {impl Timeline {pub fn new(duration: usize, fps: f32) -> Self {let d = duration.max(1);- Timeline { fps: if fps > 0.0 { fps } else { 30.0 }, duration: d, current: 0, work_start: 0, work_end: d }+ Timeline { fps: valid_fps(fps), duration: d, current: 0, work_start: 0, work_end: d }}/// Keep every index inside `0..duration` and the work area non-empty.pub fn clamp(&mut self) {self.duration = self.duration.max(1);- self.fps = if self.fps > 0.0 { self.fps } else { 30.0 };+ self.fps = valid_fps(self.fps);self.current = self.current.min(self.duration - 1);self.work_start = self.work_start.min(self.duration - 1);self.work_end = self.work_end.clamp(self.work_start + 1, self.duration);}+ /// Move the playhead `delta` frames, stopping at the first and last frame. Saturating, so it's+ /// safe on any stored timeline, even one loaded with `duration` 0 or `usize::MAX` (#1009).+ pub fn step(&mut self, delta: i64) {+ let n = usize::try_from(delta.unsigned_abs()).unwrap_or(usize::MAX);+ let moved = if delta < 0 { self.current.saturating_sub(n) } else { self.current.saturating_add(n) };+ self.current = moved.min(self.duration.saturating_sub(1));+ }+/// Playhead time in seconds.pub fn time(&self) -> f32 {self.current as f32 / self.fps.max(1e-3)}}+/// A usable frame rate: positive and finite, else the 30 fps default.+fn valid_fps(fps: f32) -> f32 {+ if fps.is_finite() && fps > 0.0 { fps } else { 30.0 }+}+#[cfg(test)]mod tests {use super::*;@@ -104,6 +117,27 @@ mod tests {assert!((t.time() - 23.0 / 24.0).abs() < 1e-6);}+ /// #1009: stepping never panics or leaves the timeline, whatever was stored.+ #[test]+ fn step_saturates_at_both_ends() {+ let mut t = Timeline::new(3, 24.0);+ t.step(-1);+ assert_eq!(t.current, 0);+ t.step(1);+ t.step(i64::MAX);+ assert_eq!(t.current, 2);+ t.step(i64::MIN);+ assert_eq!(t.current, 0);+ for duration in [0, usize::MAX] {+ let mut t = Timeline { fps: f32::INFINITY, duration, current: usize::MAX, work_start: 0, work_end: 0 };+ t.step(1);+ assert_eq!(t.current, duration.saturating_sub(1));+ t.clamp();+ assert_eq!(t.fps, 30.0);+ assert!(t.current < t.duration);+ }+ }+#[test]fn round_trips() {let t = Timeline::new(48, 25.0);diff --git a/crates/engine/src/timeline_cmds.rs b/crates/engine/src/timeline_cmds.rsindex 9f8f5a99e..6e1aadeda 100644--- a/crates/engine/src/timeline_cmds.rs+++ b/crates/engine/src/timeline_cmds.rs@@ -10,6 +10,12 @@ use serde_json::{Value, json};use crate::commands::CommandSpec;use crate::{EngineError, Result, Session};+/// Longest timeline, in frames: every frame becomes a surface in a new video layer and a file in+/// Render Video, so `duration` is capped well before it can exhaust memory or overflow (#1009).+const MAX_DURATION: usize = 1_000_000;+/// Highest frame rate; larger values only come from mistakes and become `inf` as `f32` (#1009).+const MAX_FPS: f32 = 1000.0;+fn has_doc(s: &Session) -> std::result::Result<(), String> {s.active().map(|_| ()).ok_or_else(|| "no document".into())}@@ -36,9 +42,33 @@ fn with_timeline(s: &mut Session, f: impl FnOnce(&mut Option<Timeline>)) -> Resuinfo(s)}+fn bad(cmd: &str, msg: String) -> EngineError {+ EngineError::BadParams { cmd: cmd.into(), msg }+}++/// The optional `duration` param, rejected unless it's a whole number in `1..=MAX_DURATION`.+/// Before #1009 any `u64` was kept and stepping panicked on it.+fn duration_param(cmd: &str, p: &Value) -> Result<Option<usize>> {+ let Some(v) = p.get("duration").filter(|v| !v.is_null()) else { return Ok(None) };+ v.as_u64()+ .and_then(|d| usize::try_from(d).ok())+ .filter(|d| (1..=MAX_DURATION).contains(d))+ .map(Some)+ .ok_or_else(|| bad(cmd, format!("`duration` must be a whole number of frames from 1 to {MAX_DURATION}, got {v}")))+}++/// The optional `fps` param, rejected unless it's a finite number in `(0, MAX_FPS]` (#1009).+fn fps_param(cmd: &str, p: &Value) -> Result<Option<f32>> {+ let Some(v) = p.get("fps").filter(|v| !v.is_null()) else { return Ok(None) };+ v.as_f64()+ .filter(|f| f.is_finite() && *f > 0.0 && *f <= f64::from(MAX_FPS))+ .map(|f| Some(f as f32))+ .ok_or_else(|| bad(cmd, format!("`fps` must be a number above 0 and at most {MAX_FPS}, got {v}")))+}+fn create(s: &mut Session, p: &Value) -> Result<Value> {- let duration = p.get("duration").and_then(Value::as_u64).unwrap_or(30) as usize;- let fps = p.get("fps").and_then(Value::as_f64).unwrap_or(30.0) as f32;+ let duration = duration_param("timeline.create", p)?.unwrap_or(30);+ let fps = fps_param("timeline.create", p)?.unwrap_or(30.0);with_timeline(s, |t| *t = Some(Timeline::new(duration, fps)))}@@ -59,19 +89,21 @@ fn set_frame(s: &mut Session, p: &Value) -> Result<Value> {fn step(s: &mut Session, delta: i64) -> Result<Value> {with_timeline(s, |t| {if let Some(t) = t {- t.current = (t.current as i64 + delta).clamp(0, t.duration as i64 - 1) as usize;+ t.step(delta);}})}fn set_props(s: &mut Session, p: &Value) -> Result<Value> {+ let fps = fps_param("timeline.setProps", p)?;+ let duration = duration_param("timeline.setProps", p)?;with_timeline(s, |t| {if let Some(t) = t {- if let Some(fps) = p.get("fps").and_then(Value::as_f64) {- t.fps = fps as f32;+ if let Some(fps) = fps {+ t.fps = fps;}- if let Some(d) = p.get("duration").and_then(Value::as_u64) {- t.duration = d as usize;+ if let Some(d) = duration {+ t.duration = d;}if let Some(ws) = p.get("workStart").and_then(Value::as_u64) {t.work_start = ws as usize;@@ -127,6 +159,8 @@ mod tests {s.execute("timeline.setFrame", json!({"frame": 10})).unwrap();s.execute("timeline.nextFrame", json!({})).unwrap();assert_eq!(s.execute("timeline.info", json!({})).unwrap()["timeline"]["current"], 11);+ s.execute("timeline.previousFrame", json!({})).unwrap();+ assert_eq!(s.execute("timeline.info", json!({})).unwrap()["timeline"]["current"], 10);// Clamp beyond the end.let r = s.execute("timeline.setFrame", json!({"frame": 999})).unwrap();assert_eq!(r["timeline"]["current"], 23);@@ -138,6 +172,104 @@ mod tests {assert_eq!(s.execute("timeline.info", json!({})).unwrap()["timeline"], Value::Null);}+ /// The document's timeline, revision and history depth, to show a rejected command changed nothing.+ fn snapshot(s: &Session) -> (Option<Timeline>, u64, usize) {+ let st = s.active().unwrap();+ (st.doc.timeline.clone(), st.revision, st.history.past_len())+ }++ fn current(s: &mut Session) -> Value {+ s.execute("timeline.info", json!({})).unwrap()["timeline"]["current"].clone()+ }++ /// #1009: `timeline.create` kept any `duration` (even `u64::MAX`) and `fps`, and stepping then+ /// panicked in `i64::clamp`. Bad values are now rejected before anything changes.+ #[test]+ fn create_rejects_out_of_range_params() {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();+ s.execute("timeline.create", json!({"duration": 24, "fps": 24.0})).unwrap();+ s.execute("timeline.setFrame", json!({"frame": 5})).unwrap();+ let before = snapshot(&s);+ let too_long = MAX_DURATION as u64 + 1;+ for p in [+ json!({"duration": 0}),+ json!({"duration": u64::MAX}),+ json!({"duration": i64::MAX as u64 + 1}),+ json!({"duration": too_long}),+ json!({"duration": -1}),+ json!({"duration": 2.5}),+ json!({"duration": "24"}),+ json!({"fps": 0.0}),+ json!({"fps": -24.0}),+ json!({"fps": MAX_FPS as f64 + 1.0}),+ json!({"fps": 1e300}),+ json!({"fps": "fast"}),+ ] {+ let e = s.execute("timeline.create", p.clone()).expect_err(&format!("{p} must be rejected"));+ assert!(matches!(e, EngineError::BadParams { .. }), "{p}: {e}");+ assert_eq!(snapshot(&s), before, "{p}: nothing changes");+ }+ // The issue's repro: stepping still works on the surviving timeline.+ s.execute("timeline.nextFrame", json!({})).unwrap();+ assert_eq!(current(&mut s), 6);+ s.execute("timeline.previousFrame", json!({})).unwrap();+ assert_eq!(current(&mut s), 5);+ // Control: the largest accepted values still create a timeline that steps at both ends.+ let r = s.execute("timeline.create", json!({"duration": MAX_DURATION, "fps": MAX_FPS as f64})).unwrap();+ assert_eq!(r["timeline"]["duration"], MAX_DURATION);+ s.execute("timeline.previousFrame", json!({})).unwrap();+ assert_eq!(current(&mut s), 0);+ s.execute("timeline.setFrame", json!({"frame": MAX_DURATION})).unwrap();+ s.execute("timeline.nextFrame", json!({})).unwrap();+ assert_eq!(current(&mut s), MAX_DURATION - 1);+ // Control: `null` means "use the default", as before.+ let r = s.execute("timeline.create", json!({"duration": null, "fps": null})).unwrap();+ assert_eq!((r["timeline"]["duration"].as_u64(), r["timeline"]["fps"].as_f64()), (Some(30), Some(30.0)));+ }++ /// #1009: `timeline.setProps` could store the same out-of-range `duration` and `fps`.+ #[test]+ fn set_props_rejects_out_of_range_params() {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();+ s.execute("timeline.create", json!({"duration": 24, "fps": 24.0})).unwrap();+ let before = snapshot(&s);+ for p in [json!({"duration": 0}), json!({"duration": u64::MAX}), json!({"fps": 0.0}), json!({"fps": -1.0}), json!({"fps": 30.0, "duration": 0})] {+ let e = s.execute("timeline.setProps", p.clone()).expect_err(&format!("{p} must be rejected"));+ assert!(matches!(e, EngineError::BadParams { .. }), "{p}: {e}");+ assert_eq!(snapshot(&s), before, "{p}: nothing changes");+ }+ s.execute("timeline.nextFrame", json!({})).unwrap();+ assert_eq!(current(&mut s), 1);+ }++ /// #1009: a timeline stored with `duration` 0 or `u64::MAX` (an old or hand-edited file) steps+ /// without panicking and lands on a valid frame.+ #[test]+ fn step_is_safe_on_any_stored_timeline() {+ for duration in [0, 1, usize::MAX] {+ for current in [0, usize::MAX] {+ for (cmd, delta) in [("timeline.nextFrame", 1i64), ("timeline.previousFrame", -1)] {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();+ let st = s.active_mut().unwrap();+ let mut doc = (*st.doc).clone();+ doc.timeline = Some(Timeline { fps: f32::NAN, duration, current, work_start: usize::MAX, work_end: 0 });+ st.doc = Arc::new(doc);+ let r = s.execute(cmd, json!({})).unwrap_or_else(|e| panic!("{cmd} d={duration} c={current}: {e}"));+ let t = &r["timeline"];+ let d = t["duration"].as_u64().unwrap();+ let c = t["current"].as_u64().unwrap();+ assert!(d >= 1 && c < d, "{cmd} d={duration} c={current}: {t}");+ if duration == usize::MAX && current == 0 {+ assert_eq!(c, if delta > 0 { 1 } else { 0 });+ }+ }+ }+ }+ }+#[test]fn navigation_without_timeline_errors() {let mut s = Session::new();