Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

perf: dramatically improve timeline frame loading performance (#2163)

Louis Beaumonta261c939dd0c
diff --git a/screenpipe-app-tauri/components/rewind/current-frame-timeline.tsx b/screenpipe-app-tauri/components/rewind/current-frame-timeline.tsx
index af291d259..d0ee77ade 100644
--- a/screenpipe-app-tauri/components/rewind/current-frame-timeline.tsx
+++ b/screenpipe-app-tauri/components/rewind/current-frame-timeline.tsx
@@ -1,5 +1,5 @@
import { StreamTimeSeriesResponse } from "@/components/rewind/timeline";
-import React, { FC, useState, useRef } from "react";
+import React, { FC, useState, useRef, useEffect, useCallback } from "react";
import { useFrameOcrData } from "@/lib/hooks/use-frame-ocr-data";
import { TextOverlay } from "@/components/text-overlay";
import { ImageOff, ChevronLeft, ChevronRight, Loader2 } from "lucide-react";
@@ -26,6 +26,10 @@ export const SkeletonLoader: FC = () => {
);
};
+// Debounce delay for frame loading (ms)
+// When scrolling fast, only load the frame after user "settles" for this duration
+const FRAME_LOAD_DEBOUNCE_MS = 150;
+
export const CurrentFrameTimeline: FC<CurrentFrameTimelineProps> = ({
currentFrame,
onNavigate,
@@ -47,30 +51,120 @@ export const CurrentFrameTimeline: FC<CurrentFrameTimelineProps> = ({
offsetX: number;
offsetY: number;
} | null>(null);
+
+ // Debounced frame ID - only updates after scroll settles
+ const [debouncedFrameId, setDebouncedFrameId] = useState<string | null>(null);
+
const imageRef = useRef<HTMLImageElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
+
+ // Abort controller for canceling pending image loads
+ const abortControllerRef = useRef<AbortController | null>(null);
+
+ // Debounce timer ref
+ const debounceTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const frameId = currentFrame?.devices?.[0]?.frame_id;
- const imageUrl = `http://localhost:3030/frames/${frameId}`;
+
+ // Debounce frame ID changes to avoid loading frames during fast scrolling
+ // This is critical for performance - without debouncing, every scroll step
+ // triggers a new HTTP request that won't be used
+ useEffect(() => {
+ // Clear any pending debounce
+ if (debounceTimerRef.current) {
+ clearTimeout(debounceTimerRef.current);
+ }
+
+ // If no frame, clear immediately
+ if (!frameId) {
+ setDebouncedFrameId(null);
+ return;
+ }
+
+ // Show loading state immediately for responsive feel
+ setIsLoading(true);
+
+ // Debounce the actual frame ID update
+ debounceTimerRef.current = setTimeout(() => {
+ setDebouncedFrameId(frameId);
+ }, FRAME_LOAD_DEBOUNCE_MS);
+
+ return () => {
+ if (debounceTimerRef.current) {
+ clearTimeout(debounceTimerRef.current);
+ }
+ };
+ }, [frameId]);
+
+ // Construct image URL only for debounced frame ID
+ const imageUrl = debouncedFrameId ? `http://localhost:3030/frames/${debouncedFrameId}` : null;
// Fetch OCR text positions for text selection overlay
+ // Use debounced frame ID to avoid unnecessary fetches
const { textPositions } = useFrameOcrData(
- frameId ? parseInt(frameId, 10) : null
+ debouncedFrameId ? parseInt(debouncedFrameId, 10) : null
);
- // Reset loading state when frame changes, but be smarter about it
- React.useEffect(() => {
- if (frameId && !imageRef.current?.complete) {
- setIsLoading(true);
- setHasError(false);
- setRetryCount(0);
- setNaturalDimensions(null);
+ // Abort previous image load and start new one when debounced frame changes
+ useEffect(() => {
+ // Abort any pending request when frame changes
+ if (abortControllerRef.current) {
+ abortControllerRef.current.abort();
}
- }, [frameId]);
+
+ if (!debouncedFrameId || !imageUrl) {
+ return;
+ }
+
+ // Create new abort controller for this request
+ abortControllerRef.current = new AbortController();
+
+ // Reset state for new frame
+ setHasError(false);
+ setRetryCount(0);
+ setNaturalDimensions(null);
+
+ // Preload the image using fetch with abort signal
+ // This allows us to cancel the request if user scrolls away
+ const controller = abortControllerRef.current;
+
+ fetch(imageUrl, { signal: controller.signal })
+ .then(response => {
+ if (!response.ok) {
+ throw new Error(`HTTP ${response.status}`);
+ }
+ return response.blob();
+ })
+ .then(blob => {
+ // Request completed successfully - image will be in browser cache
+ // The <img> tag will load it instantly from cache
+ if (!controller.signal.aborted) {
+ // Image is now cached, the img onLoad will handle the rest
+ }
+ })
+ .catch(err => {
+ if (err.name === 'AbortError') {
+ // Request was aborted (user scrolled away) - this is expected
+ console.log('Frame request aborted (user scrolled):', debouncedFrameId);
+ } else {
+ // Actual error
+ console.error('Frame fetch error:', err);
+ if (!controller.signal.aborted) {
+ setIsLoading(false);
+ setHasError(true);
+ }
+ }
+ });
+
+ return () => {
+ // Cleanup: abort if component unmounts or frame changes
+ controller.abort();
+ };
+ }, [debouncedFrameId, imageUrl]);
// Update rendered image info on resize
// For object-cover: image fills container, may be cropped, centered
- React.useEffect(() => {
+ useEffect(() => {
const updateDimensions = () => {
if (containerRef.current && naturalDimensions) {
const containerRect = containerRef.current.getBoundingClientRect();
@@ -117,7 +211,7 @@ export const CurrentFrameTimeline: FC<CurrentFrameTimelineProps> = ({
};
// Auto-skip to next frame when error occurs - instant, no delay
- React.useEffect(() => {
+ useEffect(() => {
if (hasError && !isLoading && onFrameUnavailable) {
// Minimal delay just to batch multiple errors
const timer = setTimeout(() => {
@@ -178,34 +272,36 @@ export const CurrentFrameTimeline: FC<CurrentFrameTimelineProps> = ({
return (
<div ref={containerRef} className="absolute inset-0 w-full h-full">
{isLoading && <SkeletonLoader />}
- <img
- src={imageUrl}
- ref={imageRef}
- className="absolute inset-0 w-full h-full object-cover"
- style={{
- zIndex: 1,
- display: hasError ? 'none' : 'block',
- opacity: isLoading ? 0 : 1,
- transition: 'opacity 0.2s ease-in-out',
- }}
- alt="Current frame"
- draggable={false}
- onLoad={(e) => {
- const img = e.target as HTMLImageElement;
- console.log('Image loaded successfully for frame:', frameId);
- setIsLoading(false);
- setHasError(false);
- setNaturalDimensions({
- width: img.naturalWidth,
- height: img.naturalHeight,
- });
- }}
- onError={() => {
- console.log('Image failed to load for frame:', frameId);
- setIsLoading(false);
- setHasError(true);
- }}
- />
+ {imageUrl && (
+ <img
+ src={imageUrl}
+ ref={imageRef}
+ className="absolute inset-0 w-full h-full object-cover"
+ style={{
+ zIndex: 1,
+ display: hasError ? 'none' : 'block',
+ opacity: isLoading ? 0 : 1,
+ transition: 'opacity 0.15s ease-in-out',
+ }}
+ alt="Current frame"
+ draggable={false}
+ onLoad={(e) => {
+ const img = e.target as HTMLImageElement;
+ console.log('Image loaded successfully for frame:', debouncedFrameId);
+ setIsLoading(false);
+ setHasError(false);
+ setNaturalDimensions({
+ width: img.naturalWidth,
+ height: img.naturalHeight,
+ });
+ }}
+ onError={() => {
+ console.log('Image failed to load for frame:', debouncedFrameId);
+ setIsLoading(false);
+ setHasError(true);
+ }}
+ />
+ )}
{/* Text selection overlay for timeline view */}
{/* Position overlay to match the actual rendered image (accounting for object-cover cropping) */}
{!isLoading && !hasError && naturalDimensions && renderedImageInfo && textPositions.length > 0 && (
diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rs
index 0dbc6c5aa..c1f7da5c8 100644
--- a/screenpipe-server/src/server.rs
+++ b/screenpipe-server/src/server.rs
@@ -1356,9 +1356,12 @@ impl SCServer {
} else {
None
},
+ // Frame image cache: increased from 100 to 1000 for better timeline scrolling performance.
+ // Each entry is just a file path (~100 bytes) + Instant, so 1000 entries ≈ 100KB.
+ // This dramatically reduces FFmpeg extraction calls when scrolling through timeline.
frame_image_cache: if enable_frame_cache {
Some(Arc::new(Mutex::new(LruCache::new(
- NonZeroUsize::new(100).unwrap(),
+ NonZeroUsize::new(1000).unwrap(),
))))
} else {
None
@@ -3139,7 +3142,10 @@ pub async fn get_frame_data(
match cache_result {
Ok(mut cache) => {
if let Some((file_path, timestamp)) = cache.get(&frame_id) {
- if timestamp.elapsed() < Duration::from_secs(300) {
+ // Increased TTL from 5 minutes to 30 minutes.
+ // Frames are immutable once captured, so longer caching is safe
+ // and significantly improves timeline scrolling performance.
+ if timestamp.elapsed() < Duration::from_secs(1800) {
debug!(
"Cache hit for frame_id: {}. Retrieved in {:?}",
frame_id,
diff --git a/screenpipe-server/src/video_utils.rs b/screenpipe-server/src/video_utils.rs
index 9fffe2384..d34651b0f 100644
--- a/screenpipe-server/src/video_utils.rs
+++ b/screenpipe-server/src/video_utils.rs
@@ -10,14 +10,24 @@ use screenpipe_core::find_ffmpeg_path;
use screenpipe_core::pii_removal::PiiRegion;
use screenpipe_db::VideoMetadata as DBVideoMetadata;
use serde::{Deserialize, Serialize};
+use std::collections::HashMap;
use std::io::Cursor;
use std::path::Path;
use std::path::PathBuf;
+use std::sync::LazyLock;
use tokio::io::AsyncReadExt;
use tokio::process::Command;
+use tokio::sync::RwLock;
use tracing::{debug, error, info};
use uuid::Uuid;
+/// Global cache for video metadata (FPS, duration) to avoid repeated ffprobe calls.
+/// Key: canonical file path, Value: (fps, duration_seconds)
+/// This dramatically improves frame extraction performance by eliminating
+/// redundant ffprobe process spawns (~200-500ms saved per frame request).
+static VIDEO_METADATA_CACHE: LazyLock<RwLock<HashMap<String, (f64, f64)>>> =
+ LazyLock::new(|| RwLock::new(HashMap::with_capacity(100)));
+
/// Get ffprobe path from ffmpeg path, handling Windows .exe extension
/// Tries with .exe first on Windows, falls back to without
fn get_ffprobe_path(ffmpeg_path: &Path) -> PathBuf {
@@ -368,7 +378,46 @@ async fn get_video_fps(ffmpeg_path: &PathBuf, video_path: &str) -> Result<f64> {
Ok(fps)
}
+/// Get video FPS and duration with caching.
+/// Uses a global cache to avoid repeated ffprobe calls for the same video file.
+/// This is critical for timeline performance - without caching, every frame
+/// request spawns a new ffprobe process (~200-500ms overhead).
async fn get_video_fps_and_duration(ffmpeg_path: &PathBuf, video_path: &str) -> Result<(f64, f64)> {
+ // Check cache first (fast path)
+ {
+ let cache = VIDEO_METADATA_CACHE.read().await;
+ if let Some(&(fps, duration)) = cache.get(video_path) {
+ debug!("Video metadata cache HIT for {}: fps={}, duration={}", video_path, fps, duration);
+ return Ok((fps, duration));
+ }
+ }
+
+ debug!("Video metadata cache MISS for {}, calling ffprobe", video_path);
+
+ // Cache miss - call ffprobe
+ let (fps, duration) = get_video_fps_and_duration_uncached(ffmpeg_path, video_path).await?;
+
+ // Store in cache
+ {
+ let mut cache = VIDEO_METADATA_CACHE.write().await;
+ // Limit cache size to prevent unbounded memory growth
+ if cache.len() >= 1000 {
+ // Simple eviction: clear half the cache when full
+ // In production, consider LRU eviction
+ let keys_to_remove: Vec<_> = cache.keys().take(500).cloned().collect();
+ for key in keys_to_remove {
+ cache.remove(&key);
+ }
+ debug!("Video metadata cache pruned to {} entries", cache.len());
+ }
+ cache.insert(video_path.to_string(), (fps, duration));
+ }
+
+ Ok((fps, duration))
+}
+
+/// Internal function that actually calls ffprobe - used by the cached wrapper.
+async fn get_video_fps_and_duration_uncached(ffmpeg_path: &PathBuf, video_path: &str) -> Result<(f64, f64)> {
let ffprobe_path = get_ffprobe_path(ffmpeg_path);
let mut cmd = Command::new(&ffprobe_path);