Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
improve: index cursor data and prepare export zoom incrementally
Richie McIlroy38f3e55481cd
diff --git a/crates/project/src/cursor.rs b/crates/project/src/cursor.rsindex a5a4e542b..8dad727e5 100644--- a/crates/project/src/cursor.rs+++ b/crates/project/src/cursor.rs@@ -5,6 +5,7 @@ use std::ops::Range;pub const SHORT_CURSOR_SHAPE_DEBOUNCE_MS: f64 = 1000.0;use std::fs::File;+use std::io::BufReader;use std::path::{Path, PathBuf};use crate::XY;@@ -59,7 +60,8 @@ pub struct CursorData {impl CursorData {pub fn load_from_file(path: &Path) -> Result<Self, String> {let file = File::open(path).map_err(|e| format!("Failed to open cursor file: {e}"))?;- serde_json::from_reader(file).map_err(|e| format!("Failed to parse cursor data: {e}"))+ serde_json::from_reader(BufReader::new(file))+ .map_err(|e| format!("Failed to parse cursor data: {e}"))}}@@ -72,7 +74,8 @@ pub struct CursorEvents {impl CursorEvents {pub fn load_from_file(path: &Path) -> Result<Self, String> {let file = File::open(path).map_err(|e| format!("Failed to open cursor file: {e}"))?;- serde_json::from_reader(file).map_err(|e| format!("Failed to parse cursor data: {e}"))+ serde_json::from_reader(BufReader::new(file))+ .map_err(|e| format!("Failed to parse cursor data: {e}"))}pub fn stabilize_short_lived_cursor_shapes(@@ -279,6 +282,85 @@ struct CursorSegment {mod tests {use super::*;+ #[test]+ fn buffered_load_preserves_events_and_legacy_images_across_read_boundaries() {+ let data = CursorData {+ clicks: vec![click_event(0.0, "pointer"), click_event(9876.5, "文字🖱")],+ moves: (0..2000)+ .map(|index| move_event(f64::from(index) * 16.67, "文字🖱"))+ .collect(),+ cursor_images: CursorImages(HashMap::from([(+ "文字🖱".to_string(),+ CursorImage {+ path: "cursors/文字.png".into(),+ hotspot: XY::new(0.125, 0.75),+ },+ )])),+ };+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("cursor.json");+ let json = serde_json::to_vec(&data).unwrap();+ std::fs::write(&path, &json).unwrap();++ let expected: CursorData = serde_json::from_reader(File::open(&path).unwrap()).unwrap();+ let events = CursorEvents::load_from_file(&path).unwrap();+ assert_eq!(events.moves, expected.moves);+ assert_eq!(events.clicks, expected.clicks);+ let legacy = CursorData::load_from_file(&path).unwrap();+ assert_eq!(+ serde_json::to_value(legacy).unwrap(),+ serde_json::to_value(expected).unwrap()+ );++ let events_json = serde_json::to_vec(&events).unwrap();+ std::fs::write(&path, events_json).unwrap();+ let expected: CursorEvents = serde_json::from_reader(File::open(&path).unwrap()).unwrap();+ let loaded_events = CursorEvents::load_from_file(&path).unwrap();+ assert_eq!(loaded_events.moves, expected.moves);+ assert_eq!(loaded_events.clicks, expected.clicks);+ }++ #[test]+ fn buffered_load_preserves_parse_and_open_errors() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("cursor.json");+ for json in [+ "",+ "{",+ r#"{"moves":[],"clicks":[]} trailing"#,+ r#"{"moves":[{"time_ms":1e999}],"clicks":[]}"#,+ r#"{"moves":[],"clicks":[],"cursor_images":null}"#,+ ] {+ for padding in [0, 8191, 8192] {+ std::fs::write(&path, format!("{}{json}", " ".repeat(padding))).unwrap();+ let expected_events =+ serde_json::from_reader::<_, CursorEvents>(File::open(&path).unwrap())+ .map_err(|error| format!("Failed to parse cursor data: {error}"));+ assert_eq!(+ CursorEvents::load_from_file(&path).err(),+ expected_events.err()+ );+ let expected_legacy =+ serde_json::from_reader::<_, CursorData>(File::open(&path).unwrap())+ .map_err(|error| format!("Failed to parse cursor data: {error}"));+ assert_eq!(+ CursorData::load_from_file(&path).err(),+ expected_legacy.err()+ );+ }+ }+ let missing = dir.path().join("missing.json");+ let expected = format!(+ "Failed to open cursor file: {}",+ File::open(&missing).unwrap_err()+ );+ assert_eq!(+ CursorEvents::load_from_file(&missing).unwrap_err(),+ expected+ );+ assert_eq!(CursorData::load_from_file(&missing).unwrap_err(), expected);+ }+fn move_event(time_ms: f64, cursor_id: &str) -> CursorMoveEvent {CursorMoveEvent {active_modifiers: vec![],diff --git a/crates/rendering/src/cursor_interpolation.rs b/crates/rendering/src/cursor_interpolation.rsindex 281bace64..2c4f3fc0c 100644--- a/crates/rendering/src/cursor_interpolation.rs+++ b/crates/rendering/src/cursor_interpolation.rs@@ -142,7 +142,11 @@ fn next_click_within(clicks.get(idx).filter(|c| c.time_ms - time_ms <= window_ms)}-fn position_at_time(moves: &[CursorMoveEvent], time_ms: f64) -> (f64, f64) {+fn position_at_time(+ moves: &[CursorMoveEvent],+ time_ms: f64,+ moves_are_ordered: bool,+) -> (f64, f64) {if moves.is_empty() {return (0.0, 0.0);}@@ -154,9 +158,16 @@ fn position_at_time(moves: &[CursorMoveEvent], time_ms: f64) -> (f64, f64) {{return (last.x, last.y);}- moves- .windows(2)- .find_map(|w| {+ let window = if moves_are_ordered && !time_ms.is_nan() {+ let end = moves.partition_point(|event| event.time_ms <= time_ms);+ end.checked_sub(1).and_then(|start| moves.get(start..=end))+ } else {+ moves+ .windows(2)+ .find(|w| time_ms >= w[0].time_ms && time_ms < w[1].time_ms)+ };+ window+ .and_then(|w| {if time_ms >= w[0].time_ms && time_ms < w[1].time_ms {let dt = w[1].time_ms - w[0].time_ms;if dt > IDLE_GAP_THRESHOLD_MS {@@ -345,7 +356,7 @@ impl PrecomputedCursorTimeline {Self {timeline,- raw_cursor: cursor.clone(),+ raw_cursor: CursorEvents::default(),has_smoothing: true,}}@@ -370,6 +381,8 @@ fn build_smoothed_timeline(return vec![];}+ let moves_are_ordered =+ !cursor.clicks.is_empty() && moves.is_sorted_by(|a, b| a.time_ms <= b.time_ms);let presets = CursorSpringPresets::new(smoothing_config, click_spring);let mut context = CursorSpringContext::new(&cursor.clicks);let mut sim = SpringMassDamperSimulation::new(smoothing_config);@@ -416,7 +429,8 @@ fn build_smoothed_timeline(let target = if let Some(click) =next_click_within(&cursor.clicks, t_ms, CLICK_LOOKAHEAD_TARGET_MS){- let (tx, ty) = position_at_time(moves, click.time_ms.min(end_time_ms));+ let (tx, ty) =+ position_at_time(moves, click.time_ms.min(end_time_ms), moves_are_ordered);XY::new(tx as f32, ty as f32)} else {XY::new(cx as f32, cy as f32)@@ -481,9 +495,11 @@ fn interpolate_timeline(if events[idx].time <= query && idx + 1 < events.len() && query < events[idx + 1].time {(&events[idx], &events[idx + 1])} else {- match events- .windows(2)- .find(|w| w[0].time <= query && query < w[1].time)+ let end = events.partition_point(|event| event.time <= query);+ match end+ .checked_sub(1)+ .and_then(|start| events.get(start..=end))+ .filter(|w| w[0].time <= query && query < w[1].time){Some(w) => (&w[0], &w[1]),None => {@@ -830,4 +846,562 @@ mod tests {prev = pos;}}+ fn linear_position_at_time(moves: &[CursorMoveEvent], time_ms: f64) -> (f64, f64) {+ if moves.is_empty() {+ return (0.0, 0.0);+ }+ if time_ms <= moves[0].time_ms {+ return (moves[0].x, moves[0].y);+ }+ if let Some(last) = moves.last()+ && time_ms >= last.time_ms+ {+ return (last.x, last.y);+ }+ moves+ .windows(2)+ .find_map(|w| {+ if time_ms >= w[0].time_ms && time_ms < w[1].time_ms {+ let dt = w[1].time_ms - w[0].time_ms;+ if dt > IDLE_GAP_THRESHOLD_MS {+ return Some((w[0].x, w[0].y));+ }+ let u = if dt.abs() < 1e-9 {+ 0.0+ } else {+ (time_ms - w[0].time_ms) / dt+ };+ Some((+ w[0].x + (w[1].x - w[0].x) * u,+ w[0].y + (w[1].y - w[0].y) * u,+ ))+ } else {+ None+ }+ })+ .unwrap_or_else(|| {+ let l = moves.last().unwrap();+ (l.x, l.y)+ })+ }++ fn linear_build_smoothed_timeline(+ cursor: &CursorEvents,+ moves: &[CursorMoveEvent],+ smoothing_config: SpringMassDamperSimulationConfig,+ click_spring: Option<ClickSpringConfig>,+ ) -> Vec<SmoothedCursorEvent> {+ if moves.is_empty() {+ return vec![];+ }++ let presets = CursorSpringPresets::new(smoothing_config, click_spring);+ let mut context = CursorSpringContext::new(&cursor.clicks);+ let mut sim = SpringMassDamperSimulation::new(smoothing_config);++ let start_pos = XY::new(moves[0].x as f32, moves[0].y as f32);+ sim.set_position(start_pos);+ sim.set_velocity(XY::new(0.0, 0.0));+ sim.set_target_position(start_pos);++ let end_time_ms = moves.last().unwrap().time_ms;+ let settle_end = end_time_ms + SPRING_SETTLE_EXTRA_MS;++ let capacity = ((settle_end / SIMULATION_STEP_MS).ceil() as usize) + 2;+ let mut events = Vec::with_capacity(capacity);+ let mut target_hint: usize = 0;+ let mut cid_hint: usize = 0;++ events.push(SmoothedCursorEvent {+ time: 0.0,+ position: start_pos,+ velocity: XY::new(0.0, 0.0),+ cursor_id: moves[0].cursor_id.clone(),+ });++ let mut t_ms = SIMULATION_STEP_MS;+ let mut lead_ms = spring_lag_ms(&smoothing_config);++ while t_ms <= settle_end {+ let clamped_t = t_ms.min(end_time_ms);++ context.advance_to(t_ms);+ let config = presets.config(context.profile(t_ms));+ sim.set_config(config);+ lead_ms += (spring_lag_ms(&config) - lead_ms) * LEAD_SMOOTHING;++ let lead_t = (clamped_t + lead_ms).min(end_time_ms);+ let (cx, cy) = position_at_time_hinted(moves, lead_t, &mut target_hint);+ let _ = position_at_time_hinted(moves, clamped_t, &mut cid_hint);+ let cid = cursor_id_at_time(moves, clamped_t, cid_hint).to_string();++ let target = if let Some(click) =+ next_click_within(&cursor.clicks, t_ms, CLICK_LOOKAHEAD_TARGET_MS)+ {+ let (tx, ty) = linear_position_at_time(moves, click.time_ms.min(end_time_ms));+ XY::new(tx as f32, ty as f32)+ } else {+ XY::new(cx as f32, cy as f32)+ };++ sim.set_target_position(target);++ sim.run(SIMULATION_STEP_MS as f32);++ events.push(SmoothedCursorEvent {+ time: t_ms as f32,+ position: sim.position,+ velocity: sim.velocity,+ cursor_id: cid,+ });++ t_ms += SIMULATION_STEP_MS;+ }++ events+ }++ fn linear_interpolate_timeline(+ events: &[SmoothedCursorEvent],+ query_ms: f64,+ ) -> Option<InterpolatedCursorPosition> {+ if events.is_empty() {+ return None;+ }++ let query = query_ms as f32;++ if query <= events[0].time {+ let e = &events[0];+ return Some(InterpolatedCursorPosition {+ position: Coord::new(XY::new(e.position.x as f64, e.position.y as f64)),+ velocity: e.velocity,+ cursor_id: e.cursor_id.clone(),+ });+ }++ if query >= events.last().unwrap().time {+ let e = events.last().unwrap();+ return Some(InterpolatedCursorPosition {+ position: Coord::new(XY::new(e.position.x as f64, e.position.y as f64)),+ velocity: e.velocity,+ cursor_id: e.cursor_id.clone(),+ });+ }++ let first_time = events[0].time;+ let step = if events.len() > 1 {+ events[1].time - events[0].time+ } else {+ SIMULATION_STEP_MS as f32+ };++ let raw_idx = ((query - first_time) / step) as usize;+ let idx = raw_idx.min(events.len().saturating_sub(2));++ let (a, b) = if events[idx].time <= query+ && idx + 1 < events.len()+ && query < events[idx + 1].time+ {+ (&events[idx], &events[idx + 1])+ } else {+ match events+ .windows(2)+ .find(|w| w[0].time <= query && query < w[1].time)+ {+ Some(w) => (&w[0], &w[1]),+ None => {+ let e = events.last().unwrap();+ return Some(InterpolatedCursorPosition {+ position: Coord::new(XY::new(e.position.x as f64, e.position.y as f64)),+ velocity: e.velocity,+ cursor_id: e.cursor_id.clone(),+ });+ }+ }+ };++ let dt = b.time - a.time;+ let t = if dt.abs() < 1e-6 {+ 0.0+ } else {+ ((query - a.time) / dt).clamp(0.0, 1.0)+ };+ let inv = 1.0 - t;++ Some(InterpolatedCursorPosition {+ position: Coord::new(XY::new(+ (a.position.x * inv + b.position.x * t) as f64,+ (a.position.y * inv + b.position.y * t) as f64,+ )),+ velocity: XY::new(+ a.velocity.x * inv + b.velocity.x * t,+ a.velocity.y * inv + b.velocity.y * t,+ ),+ cursor_id: a.cursor_id.clone(),+ })+ }++ fn assert_position_bits(+ expected: Option<InterpolatedCursorPosition>,+ actual: Option<InterpolatedCursorPosition>,+ ) {+ match (expected, actual) {+ (None, None) => {}+ (Some(expected), Some(actual)) => {+ assert_eq!(+ expected.position.coord.x.to_bits(),+ actual.position.coord.x.to_bits()+ );+ assert_eq!(+ expected.position.coord.y.to_bits(),+ actual.position.coord.y.to_bits()+ );+ assert_eq!(expected.velocity.x.to_bits(), actual.velocity.x.to_bits());+ assert_eq!(expected.velocity.y.to_bits(), actual.velocity.y.to_bits());+ assert_eq!(expected.cursor_id, actual.cursor_id);+ }+ (expected, actual) => panic!("cursor position mismatch: {expected:?} != {actual:?}"),+ }+ }++ fn assert_timeline_bits(expected: &[SmoothedCursorEvent], actual: &[SmoothedCursorEvent]) {+ assert_eq!(expected.len(), actual.len());+ for (index, (expected, actual)) in expected.iter().zip(actual).enumerate() {+ assert_eq!(+ expected.time.to_bits(),+ actual.time.to_bits(),+ "time at {index}"+ );+ assert_eq!(+ expected.position.x.to_bits(),+ actual.position.x.to_bits(),+ "position.x at {index}"+ );+ assert_eq!(+ expected.position.y.to_bits(),+ actual.position.y.to_bits(),+ "position.y at {index}"+ );+ assert_eq!(+ expected.velocity.x.to_bits(),+ actual.velocity.x.to_bits(),+ "velocity.x at {index}"+ );+ assert_eq!(+ expected.velocity.y.to_bits(),+ actual.velocity.y.to_bits(),+ "velocity.y at {index}"+ );+ assert_eq!(expected.cursor_id, actual.cursor_id, "cursor_id at {index}");+ }+ }++ fn sampled_event(time: f32, index: usize) -> SmoothedCursorEvent {+ SmoothedCursorEvent {+ time,+ position: XY::new(index as f32 * 0.013, index as f32 * -0.007),+ velocity: XY::new(index as f32 * -0.002, index as f32 * 0.003),+ cursor_id: (index % 3).to_string(),+ }+ }++ fn dense_cursor(duration_secs: usize) -> CursorEvents {+ CursorEvents {+ moves: (0..=duration_secs * 120)+ .map(|index| {+ let mut event = cursor_move(+ index as f64 * 1000.0 / 120.0,+ (index % 479) as f64 / 479.0,+ (index % 283) as f64 / 283.0,+ );+ event.cursor_id = (index / 31 % 3).to_string();+ event+ })+ .collect(),+ clicks: (1..duration_secs * 2)+ .map(|index| click_event(index as f64 * 500.0, index % 2 != 0))+ .collect(),+ }+ }++ #[test]+ fn smoothed_timeline_releases_unused_raw_events_without_changing_output() {+ let cursor = dense_cursor(8);+ let filtered = filter_cursor_shake(&cursor.moves);+ let moves = decimate_cursor_moves(filtered.as_ref());+ let expected = linear_build_smoothed_timeline(+ &cursor,+ &moves,+ DEFAULT_CLICK_SPRING,+ Some(ClickSpringConfig::default()),+ );+ let timeline = PrecomputedCursorTimeline::new(+ &cursor,+ Some(DEFAULT_CLICK_SPRING),+ Some(ClickSpringConfig::default()),+ );++ assert!(timeline.has_smoothing);+ assert!(timeline.raw_cursor.moves.is_empty());+ assert!(timeline.raw_cursor.clicks.is_empty());+ assert_timeline_bits(&expected, &timeline.timeline);+ drop(moves);+ drop(filtered);+ drop(cursor);++ for index in 0..=500 {+ let time_secs = index as f32 * 0.017_137;+ assert_position_bits(+ linear_interpolate_timeline(&expected, (time_secs * 1000.0) as f64),+ timeline.interpolate(time_secs),+ );+ }+ }++ #[test]+ fn raw_and_empty_timelines_preserve_source_events() {+ let cursor = dense_cursor(2);+ let timeline = PrecomputedCursorTimeline::new(&cursor, None, None);+ assert!(!timeline.has_smoothing);+ assert_eq!(timeline.raw_cursor.moves.len(), cursor.moves.len());+ assert_eq!(timeline.raw_cursor.clicks.len(), cursor.clicks.len());+ for time_secs in [-1.0, 0.0, 0.017, 0.5, 1.0, 2.0, 3.0] {+ assert_position_bits(+ interpolate_cursor(&cursor, time_secs, None),+ timeline.interpolate(time_secs),+ );+ }++ let empty = CursorEvents {+ moves: Vec::new(),+ clicks: vec![click_event(100.0, true)],+ };+ let timeline = PrecomputedCursorTimeline::new(&empty, Some(DEFAULT_CLICK_SPRING), None);+ assert!(!timeline.has_smoothing);+ assert!(timeline.raw_cursor.moves.is_empty());+ assert_eq!(timeline.raw_cursor.clicks.len(), 1);+ assert!(timeline.interpolate(0.1).is_none());+ }++ #[test]+ fn cursor_position_lookup_matches_linear_reference() {+ let cases = [+ vec![],+ vec![0.0],+ vec![f64::NAN],+ vec![0.0, 0.0, 10.0, 10.0, 20.0, 100.0, 100.0],+ vec![-0.0, 0.0, 0.0, 10.0, 100.0],+ vec![0.0, 20.0, 10.0, 50.0, 100.0],+ vec![0.0, 10.0, f64::NAN, 30.0, 100.0],+ vec![f64::NAN, 10.0, 30.0, 100.0],+ vec![0.0, 10.0, 30.0, f64::NAN],+ vec![f64::NEG_INFINITY, 0.0, 10.0, f64::INFINITY],+ vec![0.0, 0.000_000_000_1, 20.0, 100.0],+ ];+ let queries = [+ f64::NEG_INFINITY,+ -1.0,+ -0.0,+ 0.0,+ 0.000_000_000_05,+ 5.0,+ 10.0,+ 19.999,+ 20.0,+ 21.0,+ 30.0,+ 49.0,+ 50.0,+ 99.0,+ 100.0,+ 101.0,+ f64::INFINITY,+ f64::NAN,+ ];+ for times in cases {+ let moves: Vec<_> = times+ .iter()+ .enumerate()+ .map(|(index, &time)| cursor_move(time, index as f64 * 0.17, index as f64 * -0.11))+ .collect();+ let ordered = moves.is_sorted_by(|a, b| a.time_ms <= b.time_ms);+ for query in queries {+ let expected = linear_position_at_time(&moves, query);+ let actual = position_at_time(&moves, query, ordered);+ assert_eq!(+ expected.0.to_bits(),+ actual.0.to_bits(),+ "x for {times:?} at {query}"+ );+ assert_eq!(+ expected.1.to_bits(),+ actual.1.to_bits(),+ "y for {times:?} at {query}"+ );+ }+ }+ }++ #[test]+ fn complete_smoothed_timeline_matches_linear_reference() {+ for variant in 0..7 {+ let mut cursor = dense_cursor(8);+ match variant {+ 1 => cursor.moves[50].time_ms = cursor.moves[49].time_ms,+ 2 => cursor.moves.swap(50, 100),+ 3 => cursor.moves[100].time_ms = f64::NAN,+ 4 => cursor.clicks.reverse(),+ 5 => cursor.clicks.clear(),+ 6 => cursor.moves[100].time_ms = f64::NEG_INFINITY,+ _ => {}+ }+ let filtered = filter_cursor_shake(&cursor.moves);+ let moves = decimate_cursor_moves(filtered.as_ref());+ for config in [+ DEFAULT_CLICK_SPRING,+ DRAG_SPRING,+ SpringMassDamperSimulationConfig {+ tension: 470.0,+ mass: 3.0,+ friction: 70.0,+ },+ ] {+ for click_spring in [None, Some(ClickSpringConfig::default())] {+ let expected =+ linear_build_smoothed_timeline(&cursor, &moves, config, click_spring);+ let actual = build_smoothed_timeline(&cursor, &moves, config, click_spring);+ assert_timeline_bits(&expected, &actual);+ for index in 0..=500 {+ let query = index as f64 * 17.137;+ assert_position_bits(+ linear_interpolate_timeline(&expected, query),+ interpolate_timeline(&actual, query),+ );+ }+ }+ }+ }+ }++ #[test]+ fn timeline_lookup_matches_linear_reference_at_long_times_and_duplicate_timestamps() {+ assert_position_bits(+ linear_interpolate_timeline(&[], 0.0),+ interpolate_timeline(&[], 0.0),+ );+ for duration_hours in [0.0, 1.0, 20.0] {+ for interval_ms in [1.0, SIMULATION_STEP_MS] {+ let origin_ms = duration_hours * 3_600_000.0;+ let events: Vec<_> = [0.0, SIMULATION_STEP_MS as f32]+ .into_iter()+ .chain(+ (0..512)+ .map(|index| (origin_ms + 100.0 + index as f64 * interval_ms) as f32),+ )+ .enumerate()+ .map(|(index, time)| sampled_event(time, index))+ .collect();+ for query in [+ f64::NAN,+ f64::NEG_INFINITY,+ f64::INFINITY,+ -1.0,+ 0.0,+ origin_ms,+ origin_ms + 10_000.0,+ ] {+ assert_position_bits(+ linear_interpolate_timeline(&events, query),+ interpolate_timeline(&events, query),+ );+ }+ for event in &events {+ for query in [+ event.time as f64 - 0.001,+ event.time as f64,+ event.time as f64 + 0.001,+ event.time as f64 + interval_ms * 0.5,+ ] {+ assert_position_bits(+ linear_interpolate_timeline(&events, query),+ interpolate_timeline(&events, query),+ );+ }+ }+ }+ }+ let duplicate_origin: Vec<_> = [0.0, 0.0, 0.0, 16.0, 16.0, 32.0]+ .into_iter()+ .enumerate()+ .map(|(index, time)| sampled_event(time, index))+ .collect();+ for query in [-0.0, 0.0, 0.01, 8.0, 16.0, 16.01, 24.0, 32.0] {+ assert_position_bits(+ linear_interpolate_timeline(&duplicate_origin, query),+ interpolate_timeline(&duplicate_origin, query),+ );+ }+ }++ #[test]+ #[ignore]+ fn benchmark_dense_cursor_lookup_against_linear_reference() {+ use std::{hint::black_box, time::Instant};++ for duration_secs in [60, 600] {+ let cursor = dense_cursor(duration_secs);+ let filtered = filter_cursor_shake(&cursor.moves);+ let moves = decimate_cursor_moves(filtered.as_ref());+ let started = Instant::now();+ let expected =+ linear_build_smoothed_timeline(&cursor, &moves, DEFAULT_CLICK_SPRING, None);+ let baseline_time = started.elapsed();+ let started = Instant::now();+ let actual = build_smoothed_timeline(&cursor, &moves, DEFAULT_CLICK_SPRING, None);+ let optimized_time = started.elapsed();+ assert_timeline_bits(black_box(&expected), black_box(&actual));+ println!(+ "cursor_precompute duration_secs={duration_secs} moves={} clicks={} samples={} baseline_ms={:.3} optimized_ms={:.3}",+ moves.len(),+ cursor.clicks.len(),+ actual.len(),+ baseline_time.as_secs_f64() * 1000.0,+ optimized_time.as_secs_f64() * 1000.0+ );+ }++ let events: Vec<_> = (0..=20 * 60 * 60 * 60)+ .map(|index| {+ let mut event = sampled_event((index as f64 * SIMULATION_STEP_MS) as f32, index);+ event.cursor_id = String::new();+ event+ })+ .collect();+ let queries: Vec<_> = (0..128)+ .map(|index| 72_000_000.0 - index as f64 * 171.13 - 1.0)+ .collect();+ let started = Instant::now();+ let expected: Vec<_> = queries+ .iter()+ .map(|&query| linear_interpolate_timeline(black_box(&events), black_box(query)))+ .collect();+ let baseline_time = started.elapsed();+ let started = Instant::now();+ let actual: Vec<_> = queries+ .iter()+ .map(|&query| interpolate_timeline(black_box(&events), black_box(query)))+ .collect();+ let optimized_time = started.elapsed();+ for (expected, actual) in expected.into_iter().zip(actual) {+ assert_position_bits(expected, actual);+ }+ println!(+ "cursor_seek duration_hours=20 samples={} queries={} baseline_ms={:.3} optimized_ms={:.3}",+ events.len(),+ queries.len(),+ baseline_time.as_secs_f64() * 1000.0,+ optimized_time.as_secs_f64() * 1000.0+ );+ }}diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rsindex da28e5b9b..c9ced9ac9 100644--- a/crates/rendering/src/lib.rs+++ b/crates/rendering/src/lib.rs@@ -1147,14 +1147,6 @@ pub async fn render_video_to_channel_nv12(}).collect::<Vec<_>>()});- for timeline in &mut zoom_timelines {- timeline.precompute();- }- if let Some(timelines) = &mut outgoing_zoom_timelines {- for timeline in timelines {- timeline.precompute();- }- }let zoom_focus_interpolators_construct_ms = zoom_build_start.elapsed().as_millis() as u64;let mut frame_number = 0;diff --git a/crates/rendering/tests/export_zoom_equivalence.rs b/crates/rendering/tests/export_zoom_equivalence.rsnew file mode 100644index 000000000..f282303d7--- /dev/null+++ b/crates/rendering/tests/export_zoom_equivalence.rs@@ -0,0 +1,153 @@+use cap_project::{CursorClickEvent, CursorEvents, CursorMoveEvent, ProjectConfiguration, XY};+use cap_rendering::ZoomTransformTimeline;++fn project() -> ProjectConfiguration {+ ProjectConfiguration {+ timeline: Some(+ serde_json::from_value(serde_json::json!({+ "segments": [+ {"recordingClip": 0, "start": 2.0, "end": 14.0, "timescale": 1.5},+ {"recordingClip": 1, "start": 1.0, "end": 10.0, "timescale": 0.5},+ {"recordingClip": 0, "start": 0.0, "end": 4.0, "timescale": 1.0}+ ],+ "transitions": [+ {"segmentIndex": 0, "type": "cross-fade", "duration": 0.6},+ {"segmentIndex": 1, "type": "fade-through-black", "duration": 0.4}+ ],+ "zoomSegments": [+ {"start": 0.0, "end": 6.0, "amount": 2.0, "mode": "auto"},+ {"start": 6.0, "end": 9.0, "amount": 3.0, "mode": {"manual": {"x": 0.2, "y": 0.8}}},+ {"start": 11.0, "end": 14.0, "amount": 1.6, "mode": "auto", "instantAnimation": true},+ {"start": 18.0, "end": 25.0, "amount": 2.2, "mode": {"manual": {"x": 0.9, "y": 0.1}}}+ ]+ }))+ .unwrap(),+ ),+ ..ProjectConfiguration::default()+ }+}++fn cursor(clip: u32) -> CursorEvents {+ CursorEvents {+ moves: (0..250)+ .map(|i| CursorMoveEvent {+ time_ms: f64::from(i) * 60.0,+ x: f64::from((i * 7 + clip * 17) % 100) / 100.0,+ y: f64::from((i * 3 + clip * 23) % 100) / 100.0,+ cursor_id: "default".into(),+ active_modifiers: Vec::new(),+ })+ .collect(),+ clicks: (0..20)+ .map(|i| CursorClickEvent {+ time_ms: f64::from(i) * 630.0,+ cursor_num: 0,+ cursor_id: "default".into(),+ down: true,+ active_modifiers: Vec::new(),+ })+ .collect(),+ }+}++#[test]+fn incremental_export_zoom_matches_eager_across_clips_transitions_and_seeks() {+ let project = project();+ for clip in 0..2 {+ let cursor = cursor(clip);+ for outgoing in [false, true] {+ let make = || {+ if outgoing {+ ZoomTransformTimeline::from_project_for_outgoing_clip(+ &project,+ &cursor,+ 30.0,+ XY::new(1920, 1080),+ clip,+ )+ } else {+ ZoomTransformTimeline::from_project_for_clip(+ &project,+ &cursor,+ 30.0,+ XY::new(1920, 1080),+ clip,+ )+ }+ };+ let mut eager = make();+ eager.precompute();+ for fps in [24, 30, 60] {+ let mut incremental = make();+ for frame in 0..30 * fps {+ let time = frame as f32 / fps as f32;+ incremental.ensure_precomputed_until((frame + 1) as f32 / fps as f32);+ let previous = (time - 1.0 / fps as f32).max(0.0);+ assert_eq!(+ eager.snapped_within(previous, time),+ incremental.snapped_within(previous, time),+ );+ for query in [time, previous] {+ let before = eager.sample(query);+ let after = incremental.sample(query);+ assert_eq!(before.t.to_bits(), after.t.to_bits());+ for (a, b) in [+ (before.bounds.top_left.x, after.bounds.top_left.x),+ (before.bounds.top_left.y, after.bounds.top_left.y),+ (before.bounds.bottom_right.x, after.bounds.bottom_right.x),+ (before.bounds.bottom_right.y, after.bounds.bottom_right.y),+ ] {+ assert_eq!(+ a.to_bits(),+ b.to_bits(),+ "clip={clip} outgoing={outgoing} fps={fps} frame={frame}"+ );+ }+ }+ }+ for time in [0.0, 24.5, 6.0, 11.01, 0.0, 29.9] {+ let mut seeked = make();+ seeked.ensure_precomputed_until(time + 1.0 / fps as f32);+ assert_eq!(eager.sample(time).bounds, seeked.sample(time).bounds);+ assert_eq!(eager.sample(time).bounds, incremental.sample(time).bounds);+ }+ }+ }+ }+}++#[test]+#[ignore]+fn benchmark_long_recording_zoom_startup() {+ use std::{hint::black_box, time::Instant};+ let project = project();+ let cursor = cursor(0);+ for duration in [60.0, 8640.0, 72000.0] {+ let start = Instant::now();+ let mut eager = ZoomTransformTimeline::from_project_for_clip(+ &project,+ &cursor,+ duration,+ XY::new(1920, 1080),+ 0,+ );+ eager.precompute();+ let eager_ms = start.elapsed().as_secs_f64() * 1000.0;+ let start = Instant::now();+ let mut incremental = ZoomTransformTimeline::from_project_for_clip(+ &project,+ &cursor,+ duration,+ XY::new(1920, 1080),+ 0,+ );+ incremental.ensure_precomputed_until(1.0 / 60.0);+ let incremental_ms = start.elapsed().as_secs_f64() * 1000.0;+ assert_eq!(eager.sample(0.0).bounds, incremental.sample(0.0).bounds);+ black_box((eager, incremental));+ println!(+ "{}",+ serde_json::json!({"duration_seconds":duration,"eager_ms":eager_ms,"incremental_ms":incremental_ms,"scope":"zoom construction and first-frame simulation"})+ );+ }+}