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

all

Louis Beaumont1e4d9351bca5
diff --git a/screenpipe-app-tauri/app/timeline/page.tsx b/screenpipe-app-tauri/app/timeline/page.tsx
new file mode 100644
index 000000000..1a1787089
--- /dev/null
+++ b/screenpipe-app-tauri/app/timeline/page.tsx
@@ -0,0 +1,189 @@
+"use client";
+import { useEffect, useState, useRef, WheelEvent } from "react";
+
+interface StreamFramesResponse {
+ frame: string;
+ timestamp: string;
+ file_path: string;
+ app_name?: string;
+ window_name?: string;
+}
+
+export default function Timeline() {
+ const [currentFrame, setCurrentFrame] = useState<StreamFramesResponse | null>(
+ null
+ );
+ const [frames, setFrames] = useState<StreamFramesResponse[]>([]);
+ const [currentIndex, setCurrentIndex] = useState(0);
+ const [isLoading, setIsLoading] = useState(true);
+ const [error, setError] = useState<string | null>(null);
+ const eventSourceRef = useRef<EventSource | null>(null);
+ const retryTimeoutRef = useRef<NodeJS.Timeout>();
+ const maxRetries = 3;
+ const retryCount = useRef(0);
+
+ const setupEventSource = () => {
+ if (eventSourceRef.current) {
+ eventSourceRef.current.close();
+ }
+
+ const endTime = new Date();
+ const startTime = new Date(endTime.getTime() - 30 * 60 * 1000);
+ const url = `http://localhost:3030/stream/frames?start_time=${startTime.toISOString()}&end_time=${endTime.toISOString()}&fps=3&reverse=true`;
+
+ console.log("Starting stream:", url);
+
+ const eventSource = new EventSource(url);
+ eventSourceRef.current = eventSource;
+
+ eventSource.onerror = (error) => {
+ console.error("EventSource error:", error);
+ setError("Connection lost. Retrying...");
+
+ eventSource.close();
+
+ if (retryCount.current < maxRetries) {
+ retryTimeoutRef.current = setTimeout(() => {
+ retryCount.current += 1;
+ console.log(
+ `Retrying connection (${retryCount.current}/${maxRetries})...`
+ );
+ setupEventSource();
+ }, 2000 * Math.pow(2, retryCount.current)); // Exponential backoff
+ } else {
+ setError(
+ "Failed to connect after multiple attempts. Please refresh the page."
+ );
+ setIsLoading(false);
+ }
+ };
+
+ eventSource.onopen = () => {
+ console.log("EventSource connection opened");
+ setError(null);
+ retryCount.current = 0;
+ setIsLoading(true);
+ };
+
+ eventSource.addEventListener("frame", (event) => {
+ try {
+ const frame = JSON.parse(event.data);
+ setFrames((prev) => {
+ // Deduplicate frames based on timestamp
+ const exists = prev.some((f) => f.timestamp === frame.timestamp);
+ if (exists) return prev;
+ return [...prev, frame];
+ });
+
+ if (!currentFrame) {
+ setCurrentFrame(frame);
+ setIsLoading(false);
+ }
+ } catch (error) {
+ console.error("Failed to parse frame data:", error);
+ }
+ });
+ };
+
+ useEffect(() => {
+ setupEventSource();
+
+ return () => {
+ if (eventSourceRef.current) {
+ eventSourceRef.current.close();
+ }
+ if (retryTimeoutRef.current) {
+ clearTimeout(retryTimeoutRef.current);
+ }
+ };
+ }, []);
+
+ const handleScroll = (e: WheelEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+
+ const delta = Math.sign(e.deltaY);
+ const newIndex = Math.min(
+ Math.max(0, currentIndex + delta),
+ frames.length - 1
+ );
+
+ if (newIndex !== currentIndex) {
+ setCurrentIndex(newIndex);
+ setCurrentFrame(frames[newIndex]);
+ }
+ };
+
+ return (
+ <div
+ className="fixed inset-0 flex flex-col bg-white text-white overflow-hidden"
+ onWheel={handleScroll}
+ style={{ height: "100vh" }}
+ >
+ {/* Frame viewer */}
+ <div className="flex-1 relative min-h-0">
+ {isLoading && (
+ <div className="absolute inset-0 flex items-center justify-center text-black">
+ <p>loading frames...</p>
+ </div>
+ )}
+ {error && (
+ <div className="absolute inset-0 flex items-center justify-center text-red-500">
+ <p>{error}</p>
+ </div>
+ )}
+ {currentFrame && (
+ <img
+ src={`data:image/png;base64,${currentFrame.frame}`}
+ className="absolute inset-0 w-full h-full object-contain"
+ alt="Current frame"
+ onError={(e) => console.error("Image load error:", e)}
+ />
+ )}
+ </div>
+
+ {/* Timeline bar */}
+ <div className="h-32 flex-none bg-white border-t border-black/10">
+ {/* Time and app info */}
+ <div className="h-8 px-4 flex items-center justify-between text-sm text-gray-400 border-b border-black/10">
+ <span>
+ {currentFrame?.timestamp
+ ? new Date(currentFrame.timestamp).toLocaleString()
+ : "Loading..."}
+ </span>
+ <span>
+ {currentFrame?.app_name}{" "}
+ {currentFrame?.window_name ? `- ${currentFrame.window_name}` : ""}
+ </span>
+ </div>
+
+ {/* Timeline thumbnails */}
+ <div className="flex overflow-x-auto h-24 gap-1 p-2 no-scrollbar">
+ {frames.map((frame, index) => (
+ <div
+ key={frame.timestamp}
+ className={`flex-none w-32 h-full relative cursor-pointer transition-all ${
+ index === currentIndex
+ ? "border-2 border-white"
+ : "border border-white/20"
+ }`}
+ onClick={() => {
+ setCurrentIndex(index);
+ setCurrentFrame(frame);
+ }}
+ >
+ <img
+ src={`data:image/png;base64,${frame.frame}`}
+ className="w-full h-full object-cover"
+ alt={`Frame ${index}`}
+ />
+ <div className="absolute bottom-0 left-0 right-0 bg-black/50 text-[8px] p-1 truncate">
+ {new Date(frame.timestamp).toLocaleTimeString()}
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/screenpipe-app-tauri/src-tauri/capabilities/main.json b/screenpipe-app-tauri/src-tauri/capabilities/main.json
index 20546c91a..958042a8c 100644
--- a/screenpipe-app-tauri/src-tauri/capabilities/main.json
+++ b/screenpipe-app-tauri/src-tauri/capabilities/main.json
@@ -2,7 +2,7 @@
"identifier": "migrated",
"description": "permissions that were migrated from v1",
"local": true,
- "windows": ["main"],
+ "windows": ["main", "timeline"],
"permissions": [
"core:event:allow-listen",
"core:event:default",
diff --git a/screenpipe-app-tauri/src-tauri/gen/schemas/capabilities.json b/screenpipe-app-tauri/src-tauri/gen/schemas/capabilities.json
index 4b017c79b..357d30ea9 100644
--- a/screenpipe-app-tauri/src-tauri/gen/schemas/capabilities.json
+++ b/screenpipe-app-tauri/src-tauri/gen/schemas/capabilities.json
@@ -1 +1 @@
-{"migrated":{"identifier":"migrated","description":"permissions that were migrated from v1","local":true,"windows":["main"],"permissions":["core:event:allow-listen","core:event:default","process:allow-restart","process:allow-exit","notification:default","core:resources:default","core:menu:default","core:tray:default","shell:default","store:default","store:allow-create-store","store:allow-get","store:allow-set","store:allow-save","store:allow-load","shell:allow-open","fs:allow-watch","fs:allow-open","fs:default","fs:allow-read-file","fs:allow-read-dir","fs:allow-read","fs:allow-write-file","fs:read-dirs","fs:allow-copy-file","fs:allow-exists","fs:allow-read-text-file","fs:allow-create","fs:allow-mkdir","global-shortcut:allow-is-registered","global-shortcut:allow-register","global-shortcut:allow-unregister","global-shortcut:allow-unregister-all","global-shortcut:default",{"identifier":"fs:scope","allow":[{"path":"$XDG_DATA_HOME","requireLiteralLeadingDot":false},{"path":"$XDG_DATA_HOME/**","requireLiteralLeadingDot":false},{"path":"$LOCALAPPDATA/*","requireLiteralLeadingDot":false},{"path":"$LOCALAPPDATA/**","requireLiteralLeadingDot":false},{"path":"$APPLOCALDATA/*","requireLiteralLeadingDot":false},{"path":"$APPLOCALDATA/**","requireLiteralLeadingDot":false},{"path":"$APPDATA/*","requireLiteralLeadingDot":false},{"path":"$APPDATA/**","requireLiteralLeadingDot":false},{"path":"$APPCONFIG/*","requireLiteralLeadingDot":false},{"path":"$RESOURCE/*","requireLiteralLeadingDot":false},{"path":"$RESOURCE/.screenpipe/*","requireLiteralLeadingDot":false},{"path":"$HOME/*","requireLiteralLeadingDot":false},{"path":"$HOME/.screenpipe/*","requireLiteralLeadingDot":false},{"path":"$APP/*","requireLiteralLeadingDot":false},{"path":"$HOME/.screenpipe/data/**","requireLiteralLeadingDot":false},{"path":"$HOME/.screenpipe/pipes/**","requireLiteralLeadingDot":false}]},{"identifier":"shell:allow-execute","allow":[{"args":["-c",{"validator":"\\S+"}],"cmd":"sh","name":"exec-sh","sidecar":false}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","purge","-y"],"cmd":"screenpipe","name":"screenpipe","sidecar":true}]},{"identifier":"shell:allow-spawn","allow":[{"args":["setup"],"cmd":"screenpipe","name":"screenpipe","sidecar":true}]},{"identifier":"shell:allow-spawn","allow":[{"args":["serve"],"cmd":"ollama","name":"ollama","sidecar":true}]},{"identifier":"shell:allow-spawn","allow":[{"args":["run",{"validator":"\\S*"}],"cmd":"ollama","name":"ollama-run","sidecar":true}]},"cli:default","shell:default","shell:allow-spawn","dialog:default","updater:default","os:default","os:allow-arch","os:allow-hostname","os:allow-os-type","core:path:default","process:default","store:default"]}}
\ No newline at end of file
+{"migrated":{"identifier":"migrated","description":"permissions that were migrated from v1","local":true,"windows":["main","timeline"],"permissions":["core:event:allow-listen","core:event:default","process:allow-restart","process:allow-exit","notification:default","core:resources:default","core:menu:default","core:tray:default","shell:default","store:default","store:allow-create-store","store:allow-get","store:allow-set","store:allow-save","store:allow-load","shell:allow-open","fs:allow-watch","fs:allow-open","fs:default","fs:allow-read-file","fs:allow-read-dir","fs:allow-read","fs:allow-write-file","fs:read-dirs","fs:allow-copy-file","fs:allow-exists","fs:allow-read-text-file","fs:allow-create","fs:allow-mkdir","global-shortcut:allow-is-registered","global-shortcut:allow-register","global-shortcut:allow-unregister","global-shortcut:allow-unregister-all","global-shortcut:default",{"identifier":"fs:scope","allow":[{"path":"$XDG_DATA_HOME","requireLiteralLeadingDot":false},{"path":"$XDG_DATA_HOME/**","requireLiteralLeadingDot":false},{"path":"$LOCALAPPDATA/*","requireLiteralLeadingDot":false},{"path":"$LOCALAPPDATA/**","requireLiteralLeadingDot":false},{"path":"$APPLOCALDATA/*","requireLiteralLeadingDot":false},{"path":"$APPLOCALDATA/**","requireLiteralLeadingDot":false},{"path":"$APPDATA/*","requireLiteralLeadingDot":false},{"path":"$APPDATA/**","requireLiteralLeadingDot":false},{"path":"$APPCONFIG/*","requireLiteralLeadingDot":false},{"path":"$RESOURCE/*","requireLiteralLeadingDot":false},{"path":"$RESOURCE/.screenpipe/*","requireLiteralLeadingDot":false},{"path":"$HOME/*","requireLiteralLeadingDot":false},{"path":"$HOME/.screenpipe/*","requireLiteralLeadingDot":false},{"path":"$APP/*","requireLiteralLeadingDot":false},{"path":"$HOME/.screenpipe/data/**","requireLiteralLeadingDot":false},{"path":"$HOME/.screenpipe/pipes/**","requireLiteralLeadingDot":false}]},{"identifier":"shell:allow-execute","allow":[{"args":["-c",{"validator":"\\S+"}],"cmd":"sh","name":"exec-sh","sidecar":false}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","purge","-y"],"cmd":"screenpipe","name":"screenpipe","sidecar":true}]},{"identifier":"shell:allow-spawn","allow":[{"args":["setup"],"cmd":"screenpipe","name":"screenpipe","sidecar":true}]},{"identifier":"shell:allow-spawn","allow":[{"args":["serve"],"cmd":"ollama","name":"ollama","sidecar":true}]},{"identifier":"shell:allow-spawn","allow":[{"args":["run",{"validator":"\\S*"}],"cmd":"ollama","name":"ollama-run","sidecar":true}]},"cli:default","shell:default","shell:allow-spawn","dialog:default","updater:default","os:default","os:allow-arch","os:allow-hostname","os:allow-os-type","core:path:default","process:default","store:default"]}}
\ No newline at end of file
diff --git a/screenpipe-app-tauri/src-tauri/src/commands.rs b/screenpipe-app-tauri/src-tauri/src/commands.rs
index 4ba753c18..cdf1646a0 100644
--- a/screenpipe-app-tauri/src-tauri/src/commands.rs
+++ b/screenpipe-app-tauri/src-tauri/src/commands.rs
@@ -126,6 +126,33 @@ pub fn show_main_window(app_handle: &tauri::AppHandle<tauri::Wry>, overlay: bool
}
}
+#[tauri::command]
+pub fn show_quick_capture(app_handle: &tauri::AppHandle<tauri::Wry>) {
+ if let Some(window) = app_handle.get_webview_window("timeline") {
+ #[cfg(target_os = "macos")]
+ let _ = app_handle.set_activation_policy(tauri::ActivationPolicy::Accessory);
+
+ let _ = window.set_visible_on_all_workspaces(true);
+ let _ = window.set_always_on_top(true);
+ let _ = window.show();
+ let _ = window.set_focus();
+ } else {
+ let _window = tauri::WebviewWindowBuilder::new(
+ app_handle,
+ "timeline",
+ tauri::WebviewUrl::App("timeline.html".into()),
+ )
+ .title("Timeline")
+ .decorations(false)
+ .transparent(true)
+ .always_on_top(true)
+ .visible_on_all_workspaces(true) // Added this
+ .center()
+ .build()
+ .unwrap();
+ }
+}
+
const DEFAULT_SHORTCUT: &str = "Super+Alt+S";
#[tauri::command(rename_all = "snake_case")]
@@ -143,7 +170,7 @@ pub fn update_show_screenpipe_shortcut(
// Try to parse the new shortcut, fall back to default if it fails
let shortcut_str = match new_shortcut.parse::<Shortcut>() {
- Ok(s) => new_shortcut,
+ Ok(_s) => new_shortcut,
Err(e) => {
info!(
"invalid shortcut '{}': {}, falling back to default",
@@ -183,5 +210,16 @@ pub fn update_show_screenpipe_shortcut(
return Err("failed to set shortcut, reverted to default".to_string());
}
+ // Register the new shortcut for quick capture window
+ let quick_capture_shortcut = "Super+Alt+Q".parse::<Shortcut>().unwrap();
+ if let Err(e) = app_handle.global_shortcut().on_shortcut(
+ quick_capture_shortcut,
+ move |app_handle, _event, _shortcut| {
+ show_quick_capture(app_handle);
+ },
+ ) {
+ info!("failed to register quick capture shortcut: {}", e);
+ }
+
Ok(())
}
diff --git a/screenpipe-app-tauri/src-tauri/tauri.conf.json b/screenpipe-app-tauri/src-tauri/tauri.conf.json
index e4d072f52..fe3f153fc 100644
--- a/screenpipe-app-tauri/src-tauri/tauri.conf.json
+++ b/screenpipe-app-tauri/src-tauri/tauri.conf.json
@@ -63,6 +63,19 @@
"minWidth": 1200,
"minHeight": 850,
"resizable": true
+ },
+ {
+ "title": "timeline",
+ "url": "/timeline",
+ "width": 1400,
+ "height": 600,
+ "minWidth": 1400,
+ "minHeight": 600,
+ "visible": true,
+ "decorations": true,
+ "transparent": true,
+ "alwaysOnTop": false,
+ "label": "timeline"
}
],
"security": {
diff --git a/screenpipe-server/Cargo.toml b/screenpipe-server/Cargo.toml
index 6f9d6e43d..2027ae2c7 100644
--- a/screenpipe-server/Cargo.toml
+++ b/screenpipe-server/Cargo.toml
@@ -44,6 +44,7 @@ rand = "0.8.5"
# Server
axum = "0.7.5"
+async-stream = "0.3"
tokio = { version = "1.15", features = ["full", "tracing"] }
tower-http = { version = "0.5.2", features = ["cors", "trace"] }
@@ -88,7 +89,13 @@ base64 = "0.22.1"
uuid = "1.5.0"
-tempfile = { version = "3.3.0", optional = true }
+tempfile = "3.3.0"
+
+# video cache
+regex = "1.11.0"
+glob = "0.3.1"
+lazy_static = "1.4.0"
+
url = { version = "2.2.0", optional = true }
@@ -116,7 +123,7 @@ default = []
metal = ["candle/metal", "candle-nn/metal", "candle-transformers/metal"]
cuda = ["candle/cuda", "candle-nn/cuda", "candle-transformers/cuda"]
mkl = ["candle/mkl", "candle-nn/mkl", "candle-transformers/mkl"]
-pipes = ["screenpipe-core/pipes", "tempfile", "url"]
+pipes = ["screenpipe-core/pipes", "url"]
llm = ["screenpipe-core/llm"]
beta = ["screenpipe-core/beta", "dep:screenpipe-actions"]
experimental = ["enigo"]
@@ -127,4 +134,4 @@ path = "src/bin/screenpipe-server.rs"
[package.metadata.cargo-machete]
-ignored = ["tempfile", "url"]
+ignored = ["url"]
diff --git a/screenpipe-server/examples/timeline_ui/index.html b/screenpipe-server/examples/timeline_ui/index.html
new file mode 100644
index 000000000..306949ace
--- /dev/null
+++ b/screenpipe-server/examples/timeline_ui/index.html
@@ -0,0 +1,79 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>screenpipe frame stream</title>
+ <style>
+ body {
+ background: #000;
+ color: #fff;
+ font-family: monospace;
+ margin: 0;
+ padding: 20px;
+ }
+ #frame {
+ max-width: 100%;
+ border: 1px solid #333;
+ }
+ #info {
+ margin-top: 10px;
+ font-size: 12px;
+ color: #666;
+ }
+ #error {
+ color: #ff4444;
+ margin-top: 10px;
+ white-space: pre-wrap;
+ font-family: monospace;
+ }
+ </style>
+</head>
+<body>
+ <img id="frame" />
+ <div id="info"></div>
+ <div id="error"></div>
+
+ <script>
+ const endTime = new Date();
+ const startTime = new Date(endTime - 1000 * 60 * 5); // last 5 minutes
+
+ // Properly encode the dates for the URL
+ const url = new URL('http://localhost:3030/stream/frames');
+ url.searchParams.append('start_time', startTime.toISOString());
+ url.searchParams.append('end_time', endTime.toISOString());
+ url.searchParams.append('fps', '1');
+
+ console.log('connecting to:', url.toString());
+
+ const eventSource = new EventSource(url.toString(), {
+ withCredentials: false
+ });
+
+ eventSource.onopen = () => {
+ console.log('connection opened');
+ document.getElementById('error').textContent = 'connected successfully';
+ };
+
+ eventSource.addEventListener('frame', (event) => {
+ const data = JSON.parse(event.data);
+ document.getElementById('frame').src = `data:image/jpeg;base64,${data.frame}`;
+ document.getElementById('info').textContent = `timestamp: ${data.timestamp} | app: ${data.app_name || 'n/a'} | window: ${data.window_name || 'n/a'}`;
+ });
+
+ eventSource.onerror = (error) => {
+ const errorDetails = {
+ type: error.type,
+ target: {
+ readyState: eventSource.readyState,
+ url: url.toString()
+ },
+ timestamp: new Date().toISOString()
+ };
+
+ console.error('sse error:', errorDetails);
+ document.getElementById('error').textContent =
+ `error connecting to stream:\n${JSON.stringify(errorDetails, null, 2)}`;
+ eventSource.close();
+ };
+ </script>
+</body>
+</html>
\ No newline at end of file
diff --git a/screenpipe-server/src/db.rs b/screenpipe-server/src/db.rs
index b8e28cfaf..fd6b6c9c2 100644
--- a/screenpipe-server/src/db.rs
+++ b/screenpipe-server/src/db.rs
@@ -158,7 +158,7 @@ impl DatabaseManager {
}
let pool = SqlitePoolOptions::new()
- .max_connections(10)
+ .max_connections(50)
.min_connections(3) // Minimum number of idle connections
.acquire_timeout(Duration::from_secs(10))
.connect(&connection_string)
@@ -261,7 +261,11 @@ impl DatabaseManager {
Ok(affected as i64)
}
- pub async fn insert_video_chunk(&self, file_path: &str, device_name: &str) -> Result<i64, sqlx::Error> {
+ pub async fn insert_video_chunk(
+ &self,
+ file_path: &str,
+ device_name: &str,
+ ) -> Result<i64, sqlx::Error> {
let mut tx = self.pool.begin().await?;
let id = sqlx::query("INSERT INTO video_chunks (file_path, device_name) VALUES (?1, ?2)")
.bind(file_path)
@@ -273,19 +277,21 @@ impl DatabaseManager {
Ok(id)
}
- pub async fn insert_frame(&self,
- device_name: &str,
+ pub async fn insert_frame(
+ &self,
+ device_name: &str,
timestamp: Option<DateTime<Utc>>,
) -> Result<i64, sqlx::Error> {
let mut tx = self.pool.begin().await?;
debug!("insert_frame Transaction started");
// Get the most recent video_chunk_id
- let video_chunk_id: Option<i64> =
- sqlx::query_scalar("SELECT id FROM video_chunks WHERE device_name = ?1 ORDER BY id DESC LIMIT 1")
- .bind(device_name)
- .fetch_optional(&mut *tx)
- .await?;
+ let video_chunk_id: Option<i64> = sqlx::query_scalar(
+ "SELECT id FROM video_chunks WHERE device_name = ?1 ORDER BY id DESC LIMIT 1",
+ )
+ .bind(device_name)
+ .fetch_optional(&mut *tx)
+ .await?;
debug!("Fetched most recent video_chunk_id: {:?}", video_chunk_id);
// If no video chunk is found, return 0
@@ -306,7 +312,7 @@ impl DatabaseManager {
.fetch_one(&mut *tx)
.await?;
debug!("insert_frame Calculated offset_index: {}", offset_index);
-
+
let timestamp = timestamp.unwrap_or_else(Utc::now);
// Insert the new frame
@@ -613,7 +619,7 @@ impl DatabaseManager {
AND (?5 IS NULL OR LENGTH(audio_transcriptions.transcription) <= ?5)
"#,
);
-
+
sql.push_str(
r#"
GROUP BY
@@ -626,7 +632,7 @@ impl DatabaseManager {
LIMIT ?6 OFFSET ?7
"#,
);
-
+
let query = sqlx::query_as::<_, AudioResultRaw>(&sql)
.bind(query)
.bind(start_time)
@@ -635,9 +641,9 @@ impl DatabaseManager {
.bind(max_length.map(|l| l as i64))
.bind(limit)
.bind(offset);
-
+
let audio_results_raw = query.fetch_all(&self.pool).await?;
-
+
// Parse the tags string into a Vec<String>
let audio_results = audio_results_raw
.into_iter()
@@ -660,7 +666,7 @@ impl DatabaseManager {
},
})
.collect();
-
+
Ok(audio_results)
}
@@ -1215,6 +1221,49 @@ impl DatabaseManager {
result.into_iter().map(serde_json::Value::Object).collect(),
))
}
+
+ pub async fn get_video_chunks_in_range(
+ &self,
+ start_time: DateTime<Utc>,
+ end_time: DateTime<Utc>,
+ ) -> Result<Vec<VideoChunk>, sqlx::Error> {
+ let rows = sqlx::query(
+ r#"
+ SELECT
+ vc.file_path,
+ f.timestamp as start_time,
+ COALESCE(
+ LEAD(f.timestamp) OVER (ORDER BY f.timestamp),
+ datetime('now')
+ ) as end_time,
+ ot.app_name,
+ ot.window_name
+ FROM frames f
+ JOIN video_chunks vc ON f.video_chunk_id = vc.id
+ LEFT JOIN ocr_text ot ON f.id = ot.frame_id
+ WHERE f.timestamp <= ? AND f.timestamp >= ?
+ GROUP BY f.id
+ ORDER BY f.timestamp ASC
+ "#,
+ )
+ .bind(end_time)
+ .bind(start_time)
+ .fetch_all(&self.pool)
+ .await?;
+
+ let chunks = rows
+ .iter()
+ .map(|row| VideoChunk {
+ file_path: row.get("file_path"),
+ start_time: row.get("start_time"),
+ end_time: row.get("end_time"),
+ app_name: row.get("app_name"),
+ window_name: row.get("window_name"),
+ })
+ .collect();
+
+ Ok(chunks)
+ }
}
impl Clone for DatabaseManager {
@@ -1310,3 +1359,18 @@ impl FriendWearableDatabase for DatabaseManager {
.map_err(|e| Box::new(e) as Box<dyn StdError + Send + Sync>)
}
}
+
+#[derive(Debug)]
+pub struct VideoChunk {
+ pub file_path: String,
+ pub start_time: DateTime<Utc>,
+ pub end_time: DateTime<Utc>,
+ pub app_name: Option<String>,
+ pub window_name: Option<String>,
+}
+
+impl VideoChunk {
+ pub fn contains_time(&self, time: DateTime<Utc>) -> bool {
+ time >= self.start_time && time <= self.end_time
+ }
+}
diff --git a/screenpipe-server/src/lib.rs b/screenpipe-server/src/lib.rs
index bedec86ed..2b11d0d60 100644
--- a/screenpipe-server/src/lib.rs
+++ b/screenpipe-server/src/lib.rs
@@ -9,16 +9,18 @@ mod plugin;
mod resource_monitor;
mod server;
mod video;
+pub mod video_cache;
mod video_db;
mod video_utils;
-pub use screenpipe_core::Language;
pub use auto_destruct::watch_pid;
pub use cli::Cli;
pub use core::start_continuous_recording;
pub use db::{ContentSource, ContentType, DatabaseManager, SearchResult};
+pub use pipe_manager::PipeControl;
pub use pipe_manager::PipeManager;
pub use resource_monitor::{ResourceMonitor, RestartSignal};
+pub use screenpipe_core::Language;
pub use server::create_router;
pub use server::health_check;
pub use server::AppState;
@@ -27,4 +29,3 @@ pub use server::HealthCheckResponse;
pub use server::PaginatedResponse;
pub use server::Server;
pub use video::VideoCapture;
-pub use pipe_manager::PipeControl;
diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rs
index c0ad936b3..644ff917a 100644
--- a/screenpipe-server/src/server.rs
+++ b/screenpipe-server/src/server.rs
@@ -1,26 +1,27 @@
use axum::{
- extract::{Path, Query, State, Json},
+ extract::{Json, Path, Query, State},
http::StatusCode,
- response::Json as JsonResponse,
+ response::{sse::Event, Json as JsonResponse, Sse},
routing::{get, post},
serve, Router,
};
use crossbeam::queue::SegQueue;
-use futures::future::{try_join, try_join_all};
-#[cfg(feature = "llm")]
-use screenpipe_core::LLM;
-#[cfg(feature = "llm")]
-use screenpipe_core::{ChatRequest, ChatResponse};
+use futures::{
+ future::{try_join, try_join_all},
+ Stream,
+};
+use image::ImageFormat::{self};
+
use screenpipe_vision::monitor::list_monitors;
use screenpipe_vision::OcrEngine;
-use image::ImageFormat::{self};
use crate::{
db::TagContentType,
pipe_manager::{PipeInfo, PipeManager},
+ video::{finish_ffmpeg_process, start_ffmpeg_process, write_frame_to_ffmpeg, MAX_FPS},
+ video_cache::FrameCache,
video_utils::{merge_videos, MergeVideosRequest, MergeVideosResponse},
ContentType, DatabaseManager, SearchResult,
- video::{start_ffmpeg_process, write_frame_to_ffmpeg, finish_ffmpeg_process, MAX_FPS}
};
use crate::{plugin::ApiPluginLayer, video_utils::extract_frame};
use chrono::{DateTime, Utc};
@@ -33,14 +34,15 @@ use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::{
collections::HashMap,
+ convert::Infallible,
net::SocketAddr,
path::PathBuf,
sync::{atomic::AtomicBool, Arc},
time::Duration,
};
-use tokio::net::TcpListener;
-use tower_http::trace::TraceLayer;
+use tokio::{fs, net::TcpListener};
+use tower_http::{cors::Any, trace::TraceLayer};
use tower_http::{cors::CorsLayer, trace::DefaultMakeSpan};
// At the top of the file, add:
@@ -57,10 +59,7 @@ pub struct AppState {
pub pipe_manager: Arc<PipeManager>,
pub vision_disabled: bool,
pub audio_disabled: bool,
- #[cfg(feature = "llm")]
- pub llm_enabled: bool,
- #[cfg(feature = "llm")]
- pub llm: Option<LLM>,
+ pub frame_cache: Arc<FrameCache>,
}
// Update the SearchQuery struct
@@ -487,8 +486,6 @@ pub async fn health_check(State(state): State<Arc<AppState>>) -> JsonResponse<He
(None, None)
}
};
- debug!("last frame timestamp: {:?}", last_frame);
- debug!("last audio timestamp: {:?}", last_audio);
let now = Utc::now();
let threshold = Duration::from_secs(60);
@@ -709,10 +706,6 @@ pub struct Server {
pipe_manager: Arc<PipeManager>,
vision_disabled: bool,
audio_disabled: bool,
- #[cfg(feature = "llm")]
- enable_llm: bool,
- #[cfg(feature = "llm")]
- llm: Option<LLM>,
}
impl Server {
@@ -726,8 +719,6 @@ impl Server {
pipe_manager: Arc<PipeManager>,
vision_disabled: bool,
audio_disabled: bool,
- #[cfg(feature = "llm")] enable_llm: bool,
- #[cfg(feature = "llm")] llm: Option<LLM>,
) -> Self {
Server {
db,
@@ -738,10 +729,6 @@ impl Server {
pipe_manager,
vision_disabled,
audio_disabled,
- #[cfg(feature = "llm")]
- enable_llm,
- #[cfg(feature = "llm")]
- llm,
}
}
@@ -754,7 +741,7 @@ impl Server {
F: Fn(&axum::http::Request<axum::body::Body>) + Clone + Send + Sync + 'static,
{
let app_state = Arc::new(AppState {
- db: self.db,
+ db: self.db.clone(),
vision_control: self.vision_control,
audio_devices_control: self.audio_devices_control,
devices_status: device_status,
@@ -763,15 +750,21 @@ impl Server {
pipe_manager: self.pipe_manager,
vision_disabled: self.vision_disabled,
audio_disabled: self.audio_disabled,
- #[cfg(feature = "llm")]
- llm_enabled: self.enable_llm,
- #[cfg(feature = "llm")]
- llm: self.llm,
+ frame_cache: Arc::new(FrameCache::new(self.screenpipe_dir.clone()).await.unwrap()),
});
let app = create_router()
.layer(ApiPluginLayer::new(api_plugin))
- .layer(CorsLayer::permissive())
+ .layer(
+ CorsLayer::new()
+ .allow_origin(Any)
+ .allow_methods(Any)
+ .allow_headers(Any)
+ .expose_headers([
+ axum::http::header::CONTENT_TYPE,
+ axum::http::header::CACHE_CONTROL,
+ ]), // Important for SSE
+ )
.layer(
TraceLayer::new_for_http()
.make_span_with(DefaultMakeSpan::new().include_headers(true)),
@@ -811,40 +804,6 @@ async fn merge_frames_handler(
}
}
-#[cfg(feature = "llm")]
-async fn llm_chat_handler(
- State(state): State<Arc<AppState>>,
- JsonResponse(payload): JsonResponse<ChatRequest>,
-) -> Result<JsonResponse<ChatResponse>, (StatusCode, JsonResponse<Value>)> {
- if payload.stream {
- return Err((
- StatusCode::BAD_REQUEST,
- JsonResponse(json!({"error": "Stream not supported"})),
- ));
- }
-
- let llm = match &state.llm {
- Some(llm) => llm,
- None => {
- return Err((
- StatusCode::BAD_REQUEST,
- JsonResponse(json!({"error": "LLM is not enabled"})),
- ))
- }
- };
-
- match llm.chat(payload) {
- Ok(res) => Ok(JsonResponse(res)),
- Err(e) => {
- error!("Failed to chat: {}", e);
- Err((
- StatusCode::INTERNAL_SERVER_ERROR,
- JsonResponse(json!({"error": e.to_string()})),
- ))
- }
- }
-}
-
#[derive(Deserialize)]
struct RawSqlQuery {
query: String,
@@ -868,7 +827,7 @@ async fn execute_raw_sql(
#[derive(Deserialize)]
pub struct AddContentRequest {
- pub device_name: String, // Moved device_name to the top level
+ pub device_name: String, // Moved device_name to the top level
pub content: AddContentData, // The actual content (either Frame or Transcription)
}
@@ -891,7 +850,7 @@ pub struct FrameContent {
pub timestamp: Option<DateTime<Utc>>,
pub app_name: Option<String>,
pub window_name: Option<String>,
- pub ocr_results: Option<Vec<OCRResult>>,
+ pub ocr_results: Option<Vec<OCRResult>>,
pub tags: Option<Vec<String>>,
}
@@ -922,10 +881,9 @@ async fn add_frame_to_db(
) -> Result<(), anyhow::Error> {
let db = &state.db;
- let frame_id = db.insert_frame(
- &device_name,
- Some(frame.timestamp.unwrap_or_else(Utc::now)),
- ).await?;
+ let frame_id = db
+ .insert_frame(&device_name, Some(frame.timestamp.unwrap_or_else(Utc::now)))
+ .await?;
if let Some(ocr_results) = &frame.ocr_results {
for ocr in ocr_results {
@@ -936,13 +894,15 @@ async fn add_frame_to_db(
&frame.app_name.as_deref().unwrap_or(""),
&frame.window_name.as_deref().unwrap_or(""),
Arc::new(OcrEngine::default()), // Ideally could pass any str as ocr_engine since can be run outside of screenpipe
- false
- ).await?;
+ false,
+ )
+ .await?;
}
}
if let Some(tags) = &frame.tags {
- db.add_tags(frame_id, TagContentType::Vision, tags.clone()).await?;
+ db.add_tags(frame_id, TagContentType::Vision, tags.clone())
+ .await?;
}
Ok(())
@@ -961,7 +921,10 @@ async fn write_frames_to_video(
fps: f64,
) -> Result<(), anyhow::Error> {
let mut ffmpeg_child = start_ffmpeg_process(video_file_path, fps).await?;
- let mut ffmpeg_stdin = ffmpeg_child.stdin.take().expect("Failed to open stdin for FFmpeg");
+ let mut ffmpeg_stdin = ffmpeg_child
+ .stdin
+ .take()
+ .expect("Failed to open stdin for FFmpeg");
for frame in frames {
let encoded_frame = encode_frame_from_file_path(&frame.file_path)?;
@@ -995,7 +958,8 @@ async fn add_transcription_to_db(
-1,
&transcription.transcription_engine,
&device,
- ).await?;
+ )
+ .await?;
Ok(())
}
@@ -1004,7 +968,6 @@ pub(crate) async fn add_to_database(
State(state): State<Arc<AppState>>,
Json(payload): Json<AddContentRequest>,
) -> Result<JsonResponse<AddContentResponse>, (StatusCode, JsonResponse<Value>)> {
-
let device_name = payload.device_name.clone();
let mut success_messages = Vec::new();
@@ -1021,25 +984,42 @@ pub(crate) async fn add_to_database(
.expect("Failed to create valid path")
.to_string();
- if let Err(e) = state.db.insert_video_chunk(&video_file_path, &device_name).await {
- error!("Failed to insert video chunk for device {}: {}", device_name, e);
+ if let Err(e) = state
+ .db
+ .insert_video_chunk(&video_file_path, &device_name)
+ .await
+ {
+ error!(
+ "Failed to insert video chunk for device {}: {}",
+ device_name, e
+ );
return Err((
StatusCode::INTERNAL_SERVER_ERROR,
- JsonResponse(json!({"error": format!("Failed to insert video chunk: {}", e)})),
+ JsonResponse(
+ json!({"error": format!("Failed to insert video chunk: {}", e)}),
+ ),
));
}
if let Err(e) = write_frames_to_video(frames, &video_file_path, MAX_FPS).await {
- error!("Failed to write frames to video file {}: {}", video_file_path, e);
+ error!(
+ "Failed to write frames to video file {}: {}",
+ video_file_path, e
+ );
return Err((
StatusCode::INTERNAL_SERVER_ERROR,
- JsonResponse(json!({"error": format!("Failed to write frames to video: {}", e)})),
+ JsonResponse(
+ json!({"error": format!("Failed to write frames to video: {}", e)}),
+ ),
));
}
for frame in frames {
if let Err(e) = add_frame_to_db(&state, frame, &device_name).await {
- error!("Failed to add frame content for device {}: {}", device_name, e);
+ error!(
+ "Failed to add frame content for device {}: {}",
+ device_name, e
+ );
}
}
@@ -1050,13 +1030,18 @@ pub(crate) async fn add_to_database(
"transcription" => {
if let ContentData::Transcription(transcription) = &payload.content.data {
if let Err(e) = add_transcription_to_db(&state, transcription, &device_name).await {
- error!("Failed to add transcription for device {}: {}", device_name, e);
+ error!(
+ "Failed to add transcription for device {}: {}",
+ device_name, e
+ );
return Err((
StatusCode::INTERNAL_SERVER_ERROR,
- JsonResponse(json!({"error": format!("Failed to add transcription: {}", e)})),
+ JsonResponse(
+ json!({"error": format!("Failed to add transcription: {}", e)}),
+ ),
));
}
-
+
success_messages.push("Transcription added successfully".to_string());
}
}
@@ -1161,8 +1146,34 @@ struct InputControlResponse {
success: bool,
}
+// Add this new struct
+#[derive(Deserialize)]
+pub struct StreamFramesRequest {
+ start_time: DateTime<Utc>,
+ end_time: DateTime<Utc>,
+ fps: Option<f64>,
+}
+
+#[derive(Serialize)]
+pub struct StreamFramesResponse {
+ frame: String, // base64 encoded frame
+ timestamp: DateTime<Utc>,
+ file_path: String,
+ app_name: Option<String>,
+ window_name: Option<String>,
+}
+
pub fn create_router() -> Router<Arc<AppState>> {
- let router = Router::new()
+ let cors = CorsLayer::new()
+ .allow_origin(Any)
+ .allow_methods(Any)
+ .allow_headers(Any)
+ .expose_headers([
+ axum::http::header::CONTENT_TYPE,
+ axum::http::header::CACHE_CONTROL,
+ ]); // Important for SSE
+
+ Router::new()
.route("/search", get(search))
.route("/audio/list", get(api_list_audio_devices))
.route("/vision/list", post(api_list_monitors))
@@ -1179,15 +1190,55 @@ pub fn create_router() -> Router<Arc<AppState>> {
.route("/experimental/frames/merge", post(merge_frames_handler))
.route("/health", get(health_check))
.route("/raw_sql", post(execute_raw_sql))
- .route("/add", post(add_to_database));
+ .route("/add", post(add_to_database))
+ .route("/stream/frames", get(stream_frames_handler))
+ .layer(cors)
+}
- #[cfg(feature = "llm")]
- let router = router.route("/llm/chat", post(llm_chat_handler));
+// Add the new handler
+async fn stream_frames_handler(
+ Query(request): Query<StreamFramesRequest>,
+ State(state): State<Arc<AppState>>,
+) -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
+ info!(
+ "stream_frames_handler start_time={:?} end_time={:?}",
+ request.start_time, request.end_time
+ );
+ let stream = async_stream::stream! {
+ let mut current_time = request.end_time;
+
+ while current_time >= request.start_time {
+ info!("checking frame at time: {}", current_time);
+ if let Some(frame_path) = state.frame_cache.get_frame(current_time).await {
+ info!("found frame at {}: {}", current_time, frame_path.to_string_lossy());
+ if let Ok(frame_data) = fs::read(&frame_path).await {
+ let response = StreamFramesResponse {
+ #[allow(deprecated)]
+ frame: base64::encode(&frame_data),
+ timestamp: current_time,
+ file_path: frame_path.to_string_lossy().to_string(),
+ app_name: None,
+ window_name: None,
+ };
+
+ if let Ok(json) = serde_json::to_string(&response) {
+ yield Ok(Event::default()
+ .event("frame")
+ .data(json));
+ }
+ } else {
+ error!("failed to read frame file: {}", frame_path.to_string_lossy());
+ }
+ } else {
+ info!("no frame found at time: {}", current_time);
+ }
- #[cfg(feature = "experimental")]
- let router = router.route("/experimental/input_control", post(input_control_handler));
+ current_time = current_time - chrono::Duration::milliseconds((1000.0 / request.fps.unwrap_or(10.0)) as i64);
+ tokio::time::sleep(Duration::from_millis(5)).await;
+ }
+ };
- router
+ Sse::new(stream)
}
/*
@@ -1399,4 +1450,3 @@ MERGED_VIDEO_PATH=$(echo "$MERGE_RESPONSE" | jq -r '.video_path')
echo "Merged Video Path: $MERGED_VIDEO_PATH"
*/
-
diff --git a/screenpipe-server/src/video.rs b/screenpipe-server/src/video.rs
index 6184bf981..f5ee0a513 100644
--- a/screenpipe-server/src/video.rs
+++ b/screenpipe-server/src/video.rs
@@ -5,6 +5,7 @@ use log::{debug, error};
use log::{info, warn};
use screenpipe_core::{find_ffmpeg_path, Language};
use screenpipe_vision::{continuous_capture, CaptureResult, OcrEngine};
+use std::env;
use std::path::PathBuf;
use std::process::Stdio;
use std::sync::Arc;
@@ -201,7 +202,10 @@ pub async fn start_ffmpeg_process(output_file: &str, fps: f64) -> Result<Child,
Ok(child)
}
-pub async fn write_frame_to_ffmpeg(stdin: &mut ChildStdin, buffer: &[u8]) -> Result<(), anyhow::Error> {
+pub async fn write_frame_to_ffmpeg(
+ stdin: &mut ChildStdin,
+ buffer: &[u8],
+) -> Result<(), anyhow::Error> {
stdin.write_all(buffer).await?;
Ok(())
}
@@ -395,5 +399,3 @@ pub async fn finish_ffmpeg_process(child: Child, stdin: Option<ChildStdin>) {
Err(e) => error!("Failed to wait for FFmpeg process: {}", e),
}
}
-
-use std::env;
diff --git a/screenpipe-server/src/video_cache.rs b/screenpipe-server/src/video_cache.rs
new file mode 100644
index 000000000..3f3cd64bd
--- /dev/null
+++ b/screenpipe-server/src/video_cache.rs
@@ -0,0 +1,585 @@
+use anyhow::Result;
+use chrono::{DateTime, Duration, Timelike, Utc};
+use dirs::cache_dir;
+use std::path::PathBuf;
+use std::sync::Arc;
+use tokio::fs;
+use tokio::io::AsyncReadExt;
+use tokio::process::Command;
+use tokio::sync::mpsc::{channel, Sender};
+use tokio::sync::RwLock;
+use tracing::{debug, error, info};
+
+use glob::glob;
+use lazy_static::lazy_static;
+use regex::Regex;
+use screenpipe_core::find_ffmpeg_path;
+use std::collections::HashMap;
+use std::time::SystemTime;
+
+#[derive(Clone)]
+pub struct FrameCacheConfig {
+ pub prefetch_size: Duration,
+ pub cleanup_interval: Duration,
+ pub fps: f32,
+}
+
+impl Default for FrameCacheConfig {
+ fn default() -> Self {
+ Self {
+ prefetch_size: Duration::minutes(30),
+ cleanup_interval: Duration::minutes(5),
+ fps: 10.0,
+ }
+ }
+}
+
+#[derive(Clone)]
+pub struct FrameCache {
+ pub screenpipe_dir: PathBuf,
+ cache_dir: PathBuf,
+ cache_tx: Sender<CacheCommand>,
+ last_accessed_range: Arc<RwLock<Option<(DateTime<Utc>, DateTime<Utc>)>>>,
+ config: FrameCacheConfig,
+}
+
+#[derive(Debug)]
+enum CacheCommand {
+ Cleanup,
+}
+
+#[derive(Debug)]
+struct VideoChunk {
+ file_path: String,
+ start_time: DateTime<Utc>,
+ end_time: DateTime<Utc>,
+}
+
+/*
+
+this file should properly:
+
+- maintain a cache of frames on cache dir with frequent cleanup if some timerange not accessed
+ - eg: if user starts viewing current time and scrolls up to 1h ago, keep cache from now to 1h30 ago
+ - cleanup frames outside this range to save disk space
+ - use filesystem timestamps to manage cache, no need for db
+ - add proper debug logging for cache operations
+ - ensure cache directory exists and is writable
+
+- handle video file access safely
+ - skip mp4 files that are less than 60 seconds old (likely being written)
+ - use filesystem metadata to check file age
+ - parse timestamps from filenames like "monitor_1_2024-10-30_22-02-42.mp4"
+ - validate video files using ffmpeg before processing
+ - add detailed logging for file validation steps
+ - handle file access errors gracefully
+
+- smart prefetching
+ - when user requests frames from a specific time, prefetch next N seconds
+ - use filesystem glob to find relevant mp4 files
+ - extract frames in batches for better performance
+ - maintain small time tolerance when matching frames (±1s)
+ - verify glob patterns are working correctly
+ - add debug logging for file discovery process
+ - handle timezone properly
+
+- efficient streaming
+ - stream frames to client at requested fps (default 10fps)
+ - client controls playback speed
+ - use SSE (Server-Sent Events) for streaming
+ - base64 encode frames for transport
+ - ensure frame extraction matches requested FPS
+ - handle frame extraction errors gracefully
+ - optimize memory usage during streaming
+
+- filesystem-first approach
+ - avoid database queries
+ - use file system for storage and lookups
+ - maintain in-memory index of available frames
+ - use channels for cleanup coordination
+ - verify directory paths are correct
+ - handle filesystem errors gracefully
+ - add metrics for cache performance
+
+- error handling
+ - log all errors with context
+ - provide meaningful error messages
+ - handle filesystem permission issues
+ - recover gracefully from corrupted files
+
+- performance considerations
+ - minimize disk I/O
+ - optimize frame extraction
+ - efficient memory usage
+ - proper cleanup of temporary files
+
+
+additional context:
+- files in the data dir looks like this:
+ - "/Users/louisbeaumont/.screenpipe/data/MacBook Pro Microphone (input)_2024-09-12_05-44-04.mp4"
+ - "/Users/louisbeaumont/.screenpipe/data/MacBook Pro Microphone (input)_2024-09-03_01-07-04.mp4"
+ - "/Users/louisbeaumont/.screenpipe/data/MacBook Pro Microphone (input)_2024-10-22_02-34-24.mp4"
+ - "/Users/louisbeaumont/.screenpipe/data/monitor_1_2024-10-20_21-27-02.mp4"
+ - "/Users/louisbeaumont/.screenpipe/data/monitor_1_2024-10-01_02-05-38.mp4"
+ - "/Users/louisbeaumont/.screenpipe/data/MacBook Pro Microphone (input)_2024-10-20_08-04-04.mp4"
+ - "/Users/louisbeaumont/.screenpipe/data/MacBook Pro Microphone (input)_2024-09-14_04-53-50.mp4"
+ - "/Users/louisbeaumont/.screenpipe/data/MacBook Pro Microphone (input)_2024-09-17_03-16-10.mp4"
+
+rules:
+- we should not use file name as to parse the date - too risky on cross-platform stuff
+
+*/
+
+impl FrameCache {
+ pub async fn new(screenpipe_dir: PathBuf) -> Result<Self> {
+ Self::with_config(screenpipe_dir, FrameCacheConfig::default()).await
+ }
+
+ pub async fn with_config(screenpipe_dir: PathBuf, config: FrameCacheConfig) -> Result<Self> {
+ info!("initializing frame cache");
+ let cache_dir = cache_dir().unwrap().join("screenpipe");
+ fs::create_dir_all(&cache_dir).await?;
+ let (cache_tx, mut cache_rx) = channel(100);
+
+ let cache = Self {
+ screenpipe_dir,
+ cache_dir: cache_dir.clone(),
+ cache_tx,
+ last_accessed_range: Arc::new(RwLock::new(None)),
+ config,
+ };
+
+ // Clone the parts needed for the cleanup task
+ let cleanup_cache = FrameCache {
+ screenpipe_dir: cache.screenpipe_dir.clone(),
+ cache_dir: cache.cache_dir.clone(),
+ cache_tx: cache.cache_tx.clone(),
+ last_accessed_range: cache.last_accessed_range.clone(),
+ config: cache.config,
+ };
+
+ // tokio::spawn(async move {
+ // let mut interval =
+ // tokio::time::interval(cleanup_cache.config.cleanup_interval.to_std().unwrap());
+ // loop {
+ // tokio::select! {
+ // _ = interval.tick() => {
+ // info!("performing cleanup");
+ // if let Err(e) = Self::cleanup_old_frames(&cleanup_cache).await {
+ // error!("failed to cleanup frames: {}", e);
+ // }
+ // }
+ // Some(cmd) = cache_rx.recv() => {
+ // match cmd {
+ // CacheCommand::Cleanup => {
+ // info!("performing cleanup");
+ // if let Err(e) = Self::cleanup_old_frames(&cleanup_cache).await {
+ // error!("failed to cleanup frames: {}", e);
+ // }
+ // }
+ // }
+ // }
+ // }
+ // }
+ // });
+
+ Ok(cleanup_cache)
+ }
+
+ async fn cleanup_old_frames(cache: &FrameCache) -> Result<()> {
+ debug!("cleaning up old frames");
+ // Don't lock for writing if we don't have a range yet
+ let last_range = cache.last_accessed_range.read().await;
+ if last_range.is_none() {
+ debug!("no last accessed range, skipping cleanup");
+ return Ok(());
+ }
+ drop(last_range);
+
+ // Now get write lock only if needed
+ let last_range = cache.last_accessed_range.write().await;
+ if let Some((start, _)) = last_range.as_ref() {
+ let cutoff = *start - Duration::hours(1);
+ let old_frames: Vec<_> = cache
+ .cache_dir
+ .read_dir()?
+ .filter_map(|e| e.ok())
+ .filter(|e| {
+ let name = e.file_name().to_string_lossy().to_string();
+ if name.starts_with("frame_") && name.ends_with(".jpg") {
+ if let Ok(ts) = name[6..name.len() - 4].parse::<i64>() {
+ if ts < cutoff.timestamp() {
+ return true;
+ }
+ }
+ }
+ false
+ })
+ .map(|e| e.path())
+ .collect();
+
+ for path in old_frames {
+ if let Err(e) = fs::remove_file(&path).await {
+ error!("failed to remove old frame {}: {}", path.display(), e);
+ }
+ }
+ }
+
+ Ok(())
+ }
+
+ pub async fn get_frame(&self, target_time: DateTime<Utc>) -> Option<PathBuf> {
+ debug!("getting frame for time: {}", target_time);
+
+ // First check cache
+ let frame_path = self
+ .cache_dir
+ .join(format!("frame_{}.jpg", target_time.timestamp()));
+ if frame_path.exists() {
+ return Some(frame_path);
+ }
+
+ // If not in cache, do the prefetch and WAIT for it
+ let prefetch_end = target_time + self.config.prefetch_size;
+ if let Err(e) = self.update_access_pattern(target_time, prefetch_end).await {
+ error!("prefetch failed: {}", e);
+ return None;
+ }
+
+ // After prefetch completes, check cache again
+ if frame_path.exists() {
+ Some(frame_path)
+ } else {
+ debug!("frame not found even after prefetch: {}", target_time);
+ None
+ }
+ }
+
+ async fn has_cached_range(&self, start: DateTime<Utc>, end: DateTime<Utc>) -> bool {
+ debug!("checking if range {} to {} is cached", start, end);
+ let last_range = self.last_accessed_range.read().await;
+ if let Some((cached_start, cached_end)) = last_range.as_ref() {
+ debug!("cached range is {} to {}", cached_start, cached_end);
+ start >= *cached_start && end <= *cached_end
+ } else {
+ false
+ }
+ }
+
+ pub async fn extract_frames_batch(
+ file_path: &str,
+ start_time: DateTime<Utc>,
+ end_time: DateTime<Utc>,
+ fps: f32,
+ ) -> Result<HashMap<DateTime<Utc>, Vec<u8>>> {
+ let ffmpeg_path = find_ffmpeg_path().ok_or_else(|| anyhow::anyhow!("ffmpeg not found"))?;
+ let mut frames = HashMap::new();
+
+ // Get file creation time to use as base for seeking
+ let metadata = tokio::fs::metadata(file_path).await?;
+ let file_start = DateTime::<Utc>::from(metadata.modified()?);
+
+ // Calculate seek offset from file start
+ let seek_offset = start_time.signed_duration_since(file_start);
+ if seek_offset.num_seconds() < 0 {
+ return Err(anyhow::anyhow!("start time is before file creation"));
+ }
+
+ let seek_str = format!(
+ "{}.{}",
+ seek_offset.num_seconds(),
+ seek_offset.num_milliseconds() % 1000
+ );
+
+ let duration = (end_time - start_time).num_seconds();
+
+ debug!(
+ "batch extracting frames from {} at offset {}s for {}s at {} fps",
+ file_path, seek_str, duration, fps
+ );
+
+ let mut command = Command::new(&ffmpeg_path);
+ command
+ .args(&[
+ "-loglevel",
+ "warning",
+ "-ss",
+ &seek_str,
+ "-i",
+ file_path,
+ "-t",
+ &duration.to_string(),
+ "-vf",
+ &format!(
+ "fps={},format=yuv420p,scale=iw:ih:force_original_aspect_ratio=decrease",
+ fps
+ ),
+ "-f",
+ "image2pipe",
+ "-vcodec",
+ "mjpeg",
+ "-q:v",
+ "2",
+ "-huffman",
+ "optimal",
+ "-strict",
+ "unofficial",
+ "-",
+ ])
+ .stdout(std::process::Stdio::piped())
+ .stderr(std::process::Stdio::piped());
+
+ debug!("executing ffmpeg command: {:?}", command);
+
+ let mut child = command.spawn()?;
+ let mut stdout = child
+ .stdout
+ .take()
+ .ok_or_else(|| anyhow::anyhow!("failed to get stdout"))?;
+ let mut stderr = child
+ .stderr
+ .take()
+ .ok_or_else(|| anyhow::anyhow!("failed to get stderr"))?;
+
+ // Read stderr in background to avoid blocking
+ let stderr_handle = tokio::spawn(async move {
+ let mut output = String::new();
+ stderr.read_to_string(&mut output).await?;
+ Ok::<String, std::io::Error>(output)
+ });
+
+ // Read JPEG magic bytes
+ let mut magic = [0u8; 2];
+ let mut current_time = start_time;
+
+ // Read frames until EOF
+ loop {
+ match stdout.read_exact(&mut magic).await {
+ Ok(_) if magic == [0xFF, 0xD8] => {
+ // Found JPEG start marker
+ let mut frame_data = vec![0xFF, 0xD8];
+ let mut buffer = [0u8; 4096];
+
+ // Read until JPEG end marker
+ loop {
+ match stdout.read(&mut buffer).await {
+ Ok(n) if n == 0 => break,
+ Ok(n) => {
+ frame_data.extend_from_slice(&buffer[..n]);
+ if buffer[..n].windows(2).any(|w| w == [0xFF, 0xD9]) {
+ break;
+ }
+ }
+ Err(e) => {
+ error!("error reading frame data: {}", e);
+ break;
+ }
+ }
+ }
+
+ frames.insert(current_time, frame_data);
+ current_time = current_time + Duration::milliseconds((1000.0 / fps) as i64);
+ }
+ Ok(_) => continue, // Not a JPEG frame, skip
+ Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => break,
+ Err(e) => {
+ error!("error reading frame: {}", e);
+ break;
+ }
+ }
+ }
+
+ let status = child.wait().await?;
+ let stderr_output = stderr_handle.await.unwrap_or_else(|e| {
+ error!("failed to read stderr: {}", e);
+ Ok(String::new())
+ })?;
+
+ if !status.success() {
+ error!(
+ "ffmpeg process failed with status {}, stderr: {}",
+ status, stderr_output
+ );
+ return Err(anyhow::anyhow!(
+ "ffmpeg process failed: status={}, stderr={}",
+ status,
+ stderr_output
+ ));
+ }
+
+ if frames.is_empty() {
+ error!(
+ "no frames extracted from {}, stderr: {}",
+ file_path, stderr_output
+ );
+ return Err(anyhow::anyhow!(
+ "no frames extracted from video file: {}",
+ stderr_output
+ ));
+ }
+
+ debug!("successfully extracted {} frames", frames.len());
+ Ok(frames)
+ }
+
+ async fn is_video_file_complete(file_path: &str) -> bool {
+ let ffmpeg_path = match find_ffmpeg_path() {
+ Some(path) => path,
+ None => {
+ error!("failed to find ffmpeg path");
+ return false;
+ }
+ };
+
+ // Just do a quick check if ffmpeg can read the file
+ match Command::new(&ffmpeg_path)
+ .args(&["-v", "error", "-i", file_path, "-f", "null", "-"])
+ .output()
+ .await
+ {
+ Ok(output) => {
+ let is_complete = output.status.success();
+ if !is_complete {
+ debug!(
+ "file {} is incomplete or corrupted: {:?}",
+ file_path,
+ String::from_utf8_lossy(&output.stderr)
+ );
+ }
+ is_complete
+ }
+ Err(e) => {
+ debug!("failed to check file {}: {}", file_path, e);
+ false
+ }
+ }
+ }
+
+ async fn find_video_chunks(
+ data_dir: &PathBuf,
+ start: DateTime<Utc>,
+ end: DateTime<Utc>,
+ ) -> Result<Vec<VideoChunk>> {
+ debug!("scanning dir for chunks: {:?}", data_dir);
+ let mut chunks = Vec::new();
+ let pattern = data_dir.join("monitor_*.mp4").to_string_lossy().to_string();
+
+ debug!("using glob pattern: {}", pattern);
+
+ let paths: Vec<_> = glob(&pattern)?.filter_map(Result::ok).collect();
+ debug!("found {} potential video files", paths.len());
+
+ for entry in paths {
+ let file_path = entry.to_string_lossy().to_string();
+ debug!("checking file: {}", file_path);
+
+ if let Ok(metadata) = entry.metadata() {
+ if let Ok(modified) = metadata.modified() {
+ let chunk_time = DateTime::<Utc>::from(modified);
+ let chunk_end = chunk_time + Duration::minutes(2);
+
+ let age = SystemTime::now()
+ .duration_since(modified)
+ .unwrap_or_default();
+
+ debug!("file age: {}s, chunk_time: {}", age.as_secs(), chunk_time);
+
+ if age.as_secs() < 60 {
+ debug!("skipping recent file: {}", file_path);
+ continue;
+ }
+
+ if chunk_time <= end && chunk_end >= start {
+ debug!(
+ "found usable chunk: {} ({} to {})",
+ file_path, chunk_time, chunk_end
+ );
+ chunks.push(VideoChunk {
+ file_path,
+ start_time: chunk_time,
+ end_time: chunk_end,
+ });
+ }
+ }
+ }
+ }
+
+ debug!("total usable chunks found: {}", chunks.len());
+ chunks.sort_by_key(|chunk| chunk.start_time);
+ Ok(chunks)
+ }
+
+ async fn preload_frames(&self, start: &DateTime<Utc>, end: &DateTime<Utc>) -> Result<()> {
+ debug!("preloading frames from {} to {}", start, end);
+
+ let chunks = Self::find_video_chunks(&self.screenpipe_dir, *start, *end).await?;
+ debug!("found {} chunks to process", chunks.len());
+
+ if chunks.is_empty() {
+ debug!("no video chunks found for the requested time range");
+ return Ok(());
+ }
+
+ for chunk in chunks {
+ debug!("processing chunk: {}", chunk.file_path);
+
+ // First verify the video file is complete and valid
+ if !Self::is_video_file_complete(&chunk.file_path).await {
+ debug!("skipping incomplete/corrupted file: {}", chunk.file_path);
+ continue;
+ }
+
+ match Self::extract_frames_batch(
+ &chunk.file_path,
+ chunk.start_time,
+ chunk.end_time,
+ self.config.fps,
+ )
+ .await
+ {
+ Ok(frames) => {
+ debug!("extracted {} frames from chunk", frames.len());
+ for (timestamp, frame_data) in frames {
+ if let Err(e) = self.insert_frame(timestamp, &frame_data).await {
+ error!("failed to cache frame at {}: {}", timestamp, e);
+ }
+ }
+ }
+ Err(e) => {
+ error!("failed to extract frames from {}: {}", chunk.file_path, e);
+ }
+ }
+ }
+
+ Ok(())
+ }
+
+ async fn update_access_pattern(&self, start: DateTime<Utc>, end: DateTime<Utc>) -> Result<()> {
+ // First check if we need to prefetch using read lock
+ let needs_prefetch = !self.has_cached_range(start, end).await;
+
+ // Update last accessed range
+ {
+ let mut last_range = self.last_accessed_range.write().await;
+ *last_range = Some((start, end));
+ debug!("updated last accessed range to {} to {}", start, end);
+ } // Release write lock immediately
+
+ // Trigger prefetch if needed
+ if needs_prefetch {
+ debug!("triggering prefetch for range {} to {}", start, end);
+ self.preload_frames(&start, &end).await?;
+ }
+
+ Ok(())
+ }
+
+ pub async fn insert_frame(&self, timestamp: DateTime<Utc>, frame_data: &[u8]) -> Result<()> {
+ let cache_path = self
+ .cache_dir
+ .join(format!("frame_{}.jpg", timestamp.timestamp()));
+ fs::write(&cache_path, frame_data).await?;
+
+ Ok(())
+ }
+}
diff --git a/screenpipe-server/tests/video_cache_test.rs b/screenpipe-server/tests/video_cache_test.rs
new file mode 100644
index 000000000..f5405fced
--- /dev/null
+++ b/screenpipe-server/tests/video_cache_test.rs
@@ -0,0 +1,183 @@
+use anyhow::Result;
+use chrono::{Duration, Utc};
+use dirs::home_dir;
+use std::{path::PathBuf, time::SystemTime};
+use tempfile::env::temp_dir;
+use tokio::{fs, process::Command};
+use tracing::debug;
+
+use screenpipe_server::video_cache::{FrameCache, FrameCacheConfig};
+
+async fn setup_test_env() -> Result<FrameCache> {
+ // enabled tracing logging
+ tracing_subscriber::fmt()
+ .with_max_level(tracing::Level::DEBUG)
+ .init();
+
+ let screenpipe_dir = home_dir()
+ .expect("couldn't find home dir")
+ .join(".screenpipe")
+ .join("data");
+
+ println!("using real screenpipe data dir: {:?}", screenpipe_dir);
+ let cache = FrameCache::new(screenpipe_dir).await?;
+ Ok(cache)
+}
+
+#[tokio::test]
+async fn test_frame_retrieval() -> Result<()> {
+ let cache = setup_test_env().await?;
+ let target_time = Utc::now() - Duration::minutes(30);
+
+ println!("triggering initial frame load for {}", target_time);
+
+ // First trigger the prefetch
+ cache.get_frame(target_time).await;
+
+ // Wait for prefetch to complete (30 seconds should be enough)
+ println!("waiting for prefetch to complete...");
+ tokio::time::sleep(std::time::Duration::from_secs(30)).await;
+
+ println!("attempting to retrieve frame for {}", target_time);
+
+ // Now try to get the frame with timeout
+ let frame = tokio::time::timeout(
+ std::time::Duration::from_secs(5),
+ cache.get_frame(target_time),
+ )
+ .await
+ .unwrap()
+ .unwrap();
+
+ println!(
+ "successfully retrieved frame for timestamp {}: {:?}",
+ target_time, frame
+ );
+ Ok(())
+}
+
+#[tokio::test]
+async fn test_skip_recent_videos() -> Result<()> {
+ let cache = setup_test_env().await?;
+
+ // Try to get frame from very recent recording
+ let target_time = Utc::now() - Duration::seconds(30);
+ let frame = cache.get_frame(target_time).await;
+
+ println!("attempted to get frame from recent video: {:?}", frame);
+ assert!(
+ frame.is_none(),
+ "should not get frames from very recent videos"
+ );
+ Ok(())
+}
+
+#[tokio::test]
+async fn test_prefetch_mechanism() -> Result<()> {
+ // Use custom config with smaller prefetch size for testing
+ let config = FrameCacheConfig {
+ prefetch_size: Duration::seconds(10), // Smaller window for testing
+ cleanup_interval: Duration::minutes(1),
+ fps: 1.0,
+ };
+
+ let frame_cache = setup_test_env().await?;
+ let cache = FrameCache::with_config(frame_cache.screenpipe_dir, config).await?;
+
+ // Request frame from 1 hour ago to trigger prefetch
+ let target_time = Utc::now() - Duration::hours(1);
+ let frame = cache.get_frame(target_time).await;
+
+ // Check if nearby frames were prefetched
+ let nearby_time = target_time + Duration::seconds(10);
+ let nearby_frame = cache.get_frame(nearby_time).await;
+
+ println!("prefetch test - initial frame: {:?}", frame);
+ println!("prefetch test - nearby frame: {:?}", nearby_frame);
+ assert!(nearby_frame.is_some(), "nearby frame should be prefetched");
+ Ok(())
+}
+
+#[tokio::test]
+async fn test_high_speed_streaming() -> Result<()> {
+ let cache = setup_test_env().await?;
+
+ let start_time = Utc::now() - Duration::minutes(5);
+ let mut frames = Vec::new();
+
+ // Try to get 30 frames (3 seconds at 10fps)
+ for i in 0..30 {
+ let target_time = start_time + Duration::milliseconds(i * 100);
+ if let Some(frame) = cache.get_frame(target_time).await {
+ frames.push(frame);
+ }
+
+ if i % 10 == 0 {
+ println!("retrieved {} frames", frames.len());
+ }
+ }
+
+ println!("total frames retrieved: {}", frames.len());
+ Ok(())
+}
+
+#[tokio::test]
+async fn test_frame_extraction() -> Result<()> {
+ // enabled tracing logging
+ tracing_subscriber::fmt()
+ .with_max_level(tracing::Level::DEBUG)
+ .init();
+
+ let screenpipe_dir = home_dir()
+ .expect("couldn't find home dir")
+ .join(".screenpipe")
+ .join("data");
+
+ // List available files and pick one that's not too recent
+ let mut entries = fs::read_dir(&screenpipe_dir).await?;
+ let mut test_file = None;
+
+ debug!("looking for suitable test video in {:?}", screenpipe_dir);
+
+ while let Some(entry) = entries.next_entry().await? {
+ let path = entry.path();
+ if let Some(ext) = path.extension() {
+ if ext == "mp4" {
+ let metadata = fs::metadata(&path).await?;
+ let age = SystemTime::now()
+ .duration_since(metadata.modified()?)?
+ .as_secs();
+
+ // Use a file that's between 5 minutes and 1 hour old
+ if age > 300 && age < 3600 {
+ test_file = Some(path.clone());
+ debug!("found suitable test file: {:?} (age: {}s)", path, age);
+ break;
+ }
+ }
+ }
+ }
+
+ let test_file = test_file.ok_or_else(|| anyhow::anyhow!("no suitable test file found"))?;
+
+ let metadata = fs::metadata(&test_file).await?;
+ let file_modified: std::time::SystemTime = metadata.modified()?.into();
+
+ // Set start time to 30 seconds after file creation
+ let start_time = chrono::DateTime::<Utc>::from(file_modified) + Duration::seconds(30);
+ let end_time = start_time + Duration::seconds(10); // shorter duration for testing
+
+ debug!(
+ "attempting to extract frames from {} to {}",
+ start_time, end_time
+ );
+
+ let frames =
+ FrameCache::extract_frames_batch(test_file.to_str().unwrap(), start_time, end_time, 10.0)
+ .await?;
+
+ debug!("extracted {} frames", frames.len());
+ assert!(!frames.is_empty(), "Should extract at least one frame");
+
+ Ok(())
+}