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
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
update
Louis Beaumont53d936ebe8a3
diff --git a/screenpipe-app-tauri/app/timeline/page.tsx b/screenpipe-app-tauri/app/timeline/page.tsxindex 1a1787089..41d990b12 100644--- a/screenpipe-app-tauri/app/timeline/page.tsx+++ b/screenpipe-app-tauri/app/timeline/page.tsx@@ -28,8 +28,8 @@ export default function Timeline() {}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`;+ const startTime = new Date(endTime.getTime() - 5 * 60 * 1000);+ const url = `http://localhost:3030/stream/frames?start_time=${startTime.toISOString()}&end_time=${endTime.toISOString()}&fps=1&reverse=true`;console.log("Starting stream:", url);diff --git a/screenpipe-core/Cargo.toml b/screenpipe-core/Cargo.tomlindex 65ada8cf7..a695c7528 100644--- a/screenpipe-core/Cargo.toml+++ b/screenpipe-core/Cargo.toml@@ -39,6 +39,8 @@ clap = { version = "4.5.20", features = ["derive"] }# randomrand = "0.8.5"+once_cell = "1.19.0"+[features]default = ["pipes", "security"]llm = ["candle", "candle-nn", "candle-transformers", "tokenizers", "hf-hub"]diff --git a/screenpipe-core/src/ffmpeg.rs b/screenpipe-core/src/ffmpeg.rsindex 882dc68e7..c4f63a32c 100644--- a/screenpipe-core/src/ffmpeg.rs+++ b/screenpipe-core/src/ffmpeg.rs@@ -1,6 +1,7 @@use log::{debug, error};use std::path::PathBuf;use which::which;+use once_cell::sync::Lazy;#[cfg(not(windows))]const EXECUTABLE_NAME: &str = "ffmpeg";@@ -8,7 +9,13 @@ const EXECUTABLE_NAME: &str = "ffmpeg";#[cfg(windows)]const EXECUTABLE_NAME: &str = "ffmpeg.exe";+static FFMPEG_PATH: Lazy<Option<PathBuf>> = Lazy::new(find_ffmpeg_path_internal);+pub fn find_ffmpeg_path() -> Option<PathBuf> {+ FFMPEG_PATH.as_ref().map(|p| p.clone())+}++fn find_ffmpeg_path_internal() -> Option<PathBuf> {debug!("Starting search for ffmpeg executable");// Check if `ffmpeg` is in the PATH environment variablediff --git a/screenpipe-server/examples/timeline_ui/index.html b/screenpipe-server/examples/timeline_ui/index.htmlindex f86eae691..c6d234f2c 100644--- a/screenpipe-server/examples/timeline_ui/index.html+++ b/screenpipe-server/examples/timeline_ui/index.html@@ -6,35 +6,51 @@body {background: #000;color: #fff;- font-family: monospace;+ font-family: 'Press Start 2P', monospace;margin: 0;padding: 20px;+ image-rendering: pixelated;+ max-width: 100vw;+ overflow-x: hidden;+ box-sizing: border-box;}#timeline {position: relative;- width: 100%;+ width: 80%;height: 60px;background: #111;- margin: 10px 0;- border: 1px solid #333;- cursor: pointer;+ border: 4px solid #444;+ image-rendering: pixelated;+ box-shadow: 0 0 16px rgba(0,0,0,0.8), inset 0 0 8px rgba(255,255,255,0.1);+ cursor: crosshair;+ margin: 0 auto 32px auto;+ max-width: calc(80vw - 48px);+ box-sizing: border-box;}#cursor {position: absolute;- width: 2px;+ width: 4px;height: 100%;- background: #fff;+ background: #0f0;+ box-shadow: 0 0 12px #0f0;top: 0;+ opacity: 0.8;}#frame {- max-width: 100%;- border: 1px solid #333;- min-height: 200px; /* prevent layout shift */+ display: none;+ margin: 32px auto;+ max-width: min(80%, calc(80vw - 48px));+ border: 4px solid #333;+ min-height: 200px;+ image-rendering: pixelated;+ box-shadow: 0 0 16px rgba(255,255,255,0.1);+ height: auto;}#info {margin-top: 10px;- font-size: 12px;- color: #666;+ font-size: 8px;+ color: #888;+ letter-spacing: 1px;}#error {color: #ff4444;@@ -47,22 +63,48 @@top: 50%;left: 50%;transform: translate(-50%, -50%);- background: rgba(0,0,0,0.8);+ background: rgba(0,0,0,0.9);padding: 20px;border-radius: 4px;- border: 1px solid #333;+ border: 4px solid #333;+ box-shadow: 0 0 32px rgba(0,0,0,0.8);+ image-rendering: pixelated;display: none;+ text-align: center;}.loading.active {display: block;}- /* retro loading animation */+ .progress-bar {+ width: 200px;+ height: 4px;+ background: #111;+ border: 2px solid #333;+ margin: 10px auto;+ position: relative;+ }+ .progress-bar-fill {+ position: absolute;+ left: 0;+ top: 0;+ height: 100%;+ background: #fff;+ transition: width 0.2s ease;+ box-shadow: 0 0 8px #fff;+ }+ .progress-text {+ font-size: 12px;+ color: #666;+ margin-top: 5px;+ }+ /* retro cursor animation */.loading::after {content: '';display: inline-block;width: 8px;height: 8px;background: #fff;+ margin-left: 5px;animation: blink 1s infinite;}@keyframes blink {@@ -70,24 +112,126 @@50% { opacity: 1; }100% { opacity: 0; }}+ /* New retro scanline effect */+ body::after {+ content: '';+ position: fixed;+ top: 0;+ left: 0;+ width: 100%;+ height: 100%;+ background: repeating-linear-gradient(+ 0deg,+ rgba(0,0,0,0.1) 0px,+ rgba(0,0,0,0.1) 1px,+ transparent 1px,+ transparent 2px+ );+ pointer-events: none;+ z-index: 999;+ }+ .timeline-timestamps {+ width: 80%;+ margin: 4px auto 0 auto;+ position: relative;+ font-size: 8px;+ color: #666;+ max-width: calc(80vw - 48px);+ box-sizing: border-box;+ padding: 0 8px;+ }+ .timestamp {+ position: absolute;+ transform: translateX(-50%);+ white-space: nowrap;+ left: 0;+ color: #0f0;+ text-shadow: 0 0 8px #0f0;+ font-size: 10px;+ bottom: -20px;+ }+ /* Add spacing between elements */+ #timeline {+ margin: 0 auto 32px auto; /* Increased bottom margin */+ }++ #frame {+ margin: 32px auto; /* Added vertical margin */+ }++ /* Center info and error text */+ #info, #error {+ text-align: center;+ margin: 20px auto;+ max-width: 80%;+ }++ /* Add colored background for current position */+ .timeline-highlight {+ position: absolute;+ height: 100%;+ width: 4px; /* Match cursor width instead of 20% */+ background: rgba(255, 255, 255, 0.1);+ top: 0;+ transform: translateX(-50%);+ pointer-events: none;+ transition: left 0.3s ease;+ box-shadow: 0 0 8px rgba(255, 255, 255, 0.1); /* Added subtle glow */+ }++ /* Add grid lines */+ #timeline::before {+ content: '';+ position: absolute;+ width: 100%;+ height: 100%;+ background:+ linear-gradient(90deg,+ rgba(0,255,0,0.1) 1px,+ transparent 1px+ );+ background-size: 10% 100%;+ }</style>+ <link href="https://fonts.googleapis.com/css2?family=Press+Start+2P&display=swap" rel="stylesheet"></head><body>- <div id="timeline"><div id="cursor"></div></div>+ <div id="timeline">+ <div class="timeline-highlight"></div>+ <div id="cursor"></div>+ </div>+ <div class="timeline-timestamps" id="timestamps"></div><img id="frame" /><div id="info"></div><div id="error"></div>- <div class="loading">loading frames...</div>+ <div class="loading">+ <div>preparing frames</div>+ <div class="progress-bar">+ <div class="progress-bar-fill" style="width: 0%"></div>+ </div>+ <div class="progress-text">initializing...</div>+ </div><script>let currentTime = new Date();const timelineWidth = document.getElementById('timeline').offsetWidth;const loading = document.querySelector('.loading');+ const progressBar = document.querySelector('.progress-bar-fill');+ const progressText = document.querySelector('.progress-text');let isLoading = false;- function setLoading(state) {+ function setLoading(state, message = '') {isLoading = state;loading.classList.toggle('active', state);+ if (!state) {+ progressBar.style.width = '0%';+ progressText.textContent = '';+ }+ }++ function updateProgress(progress) {+ progressBar.style.width = `${progress.percent}%`;+ progressText.textContent = progress.message;}function updateTimeline() {@@ -101,7 +245,7 @@window.eventSource.close();}- setLoading(true);+ setLoading(true, 'connecting to stream...');const url = new URL('http://localhost:3030/stream/frames');url.searchParams.append('start_time', startTime.toISOString());@@ -115,18 +259,64 @@});window.eventSource.onopen = () => {- console.log('connection opened');- document.getElementById('error').textContent = 'connected successfully';+ console.log('SSE connection opened');+ document.getElementById('error').textContent = '';};+ window.eventSource.addEventListener('progress', (event) => {+ console.log('raw progress event:', event);+ try {+ let progressData = JSON.parse(event.data);+ console.log('parsed progress:', progressData);++ // Extract progress data from the enum wrapper if needed+ if (progressData.type === 'Progress') {+ progressData = progressData.data;+ }++ updateProgress(progressData);++ // Add visual feedback even if percentage is 0+ if (progressData.percent === 0) {+ progressText.textContent = 'scanning files...';+ progressBar.style.width = '5%'; // Show some movement+ }+ } catch (e) {+ console.error('Failed to parse progress:', e);+ console.error('Raw data:', event.data);+ }+ });++ window.eventSource.onmessage = (event) => {+ console.log('generic message event:', event);+ };+window.eventSource.addEventListener('frame', (event) => {- setLoading(false);- 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'}`;- currentTime = new Date(data.timestamp);- updateTimeline();+ console.log('frame event received:', event.data);+ try {+ const parsed = JSON.parse(event.data);+ console.log('parsed frame data:', parsed);++ // Extract the actual frame data from the wrapper+ const data = parsed.type === 'Frame' ? parsed.data : parsed;++ if (!data.frame) {+ console.error('no frame data in response');+ return;+ }++ setLoading(false);+ const frameElement = document.getElementById('frame');+ frameElement.style.display = 'block';+ frameElement.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'}`;+ currentTime = new Date(data.timestamp);+ updateTimeline();+ } catch (e) {+ console.error('Failed to parse frame data:', e);+ console.error('Raw event data:', event.data);+ }});window.eventSource.onerror = (error) => {@@ -147,6 +337,26 @@};}+ function updateTimelineMarkers() {+ const timestampsContainer = document.getElementById('timestamps');+ timestampsContainer.innerHTML = '';++ // Create 5 evenly spaced timestamps+ const timeRange = endTime - startTime;+ const numMarkers = 5;++ for (let i = 0; i < numMarkers; i++) {+ // Adjust percentage to account for the actual timeline width+ const percent = (i / (numMarkers - 1)) * 100;+ const time = new Date(startTime.getTime() + (timeRange * (i / (numMarkers - 1))));+ const marker = document.createElement('div');+ marker.className = 'timestamp';+ marker.style.left = `${percent}%`;+ marker.textContent = time.toLocaleTimeString();+ timestampsContainer.appendChild(marker);+ }+ }+// Initialize timeline interactionconst timeline = document.getElementById('timeline');timeline.addEventListener('click', (e) => {@@ -156,11 +366,12 @@currentTime = new Date(startTime.getTime() + (timeRange * position));// Recalculate window around new current time- const windowSize = 5 * 60 * 1000; // 5 minutes+ const windowSize = 3 * 60 * 1000; // 3 minutes instead of 5const newStartTime = new Date(currentTime.getTime() - (windowSize / 2));const newEndTime = new Date(currentTime.getTime() + (windowSize / 2));connectToStream(newStartTime, newEndTime);+ updateTimelineMarkers();});// Handle keyboard navigation@@ -172,19 +383,22 @@new Date(currentTime.getTime() - 150000),new Date(currentTime.getTime() + 150000));+ updateTimelineMarkers();} else if (e.key === 'ArrowRight') {currentTime = new Date(currentTime.getTime() + step);connectToStream(new Date(currentTime.getTime() - 150000),new Date(currentTime.getTime() + 150000));+ updateTimelineMarkers();}});// Initial connectionconst endTime = new Date();- const startTime = new Date(endTime - 1000 * 60 * 5); // last 5 minutes+ const startTime = new Date(endTime - 1000 * 60 * 3); // last 3 minutes instead of 5connectToStream(startTime, endTime);+ updateTimelineMarkers();</script></body></html>\ No newline at end of filediff --git a/screenpipe-server/examples/timeline_ui_simple/index.html b/screenpipe-server/examples/timeline_ui_simple/index.htmlnew file mode 100644index 000000000..14caba297--- /dev/null+++ b/screenpipe-server/examples/timeline_ui_simple/index.html@@ -0,0 +1,107 @@+<!DOCTYPE html>+<html>+<head>+ <title>screenpipe frame stream</title>+ <style>+ body {+ background: #000;+ color: #fff;+ font-family: monospace;+ margin: 0;+ padding: 20px;+ }++ #controls {+ margin-bottom: 20px;+ }++ #frame {+ max-width: 100%;+ border: 1px solid #333;+ }++ #status {+ margin-top: 10px;+ color: #666;+ }++ input, button {+ background: #111;+ border: 1px solid #333;+ color: #fff;+ padding: 8px;+ font-family: monospace;+ }++ button:hover {+ background: #222;+ cursor: pointer;+ }+ </style>+</head>+<body>+ <div id="controls">+ <input type="datetime-local" id="startTime" step="1">+ <input type="datetime-local" id="endTime" step="1">+ <button onclick="startStream()">start stream</button>+ <button onclick="stopStream()">stop</button>+ </div>++ <img id="frame" src="">+ <div id="status"></div>++ <script>+ let eventSource = null;++ // Set default time range to last 5 minutes+ function setDefaultTimes() {+ const end = new Date();+ const start = new Date(end - 5 * 60 * 1000); // 5 minutes ago++ document.getElementById('startTime').value = start.toISOString().slice(0, -1);+ document.getElementById('endTime').value = end.toISOString().slice(0, -1);+ }++ function startStream() {+ if (eventSource) {+ eventSource.close();+ }++ const startTime = document.getElementById('startTime').value;+ const endTime = document.getElementById('endTime').value;++ const url = `http://localhost:3030/stream/frames?start_time=${startTime}Z&end_time=${endTime}Z`;+ eventSource = new EventSource(url);++ eventSource.addEventListener('frame', (event) => {+ const data = JSON.parse(event.data);+ document.getElementById('frame').src = `data:image/png;base64,${data.data.frame}`;+ document.getElementById('status').innerText = `timestamp: ${data.data.timestamp}`;+ });++ eventSource.addEventListener('progress', (event) => {+ const data = JSON.parse(event.data);+ document.getElementById('status').innerText =+ `${data.data.message} (${Math.round(data.data.percent)}%)`;+ });++ eventSource.onerror = (error) => {+ console.error('sse error:', error);+ document.getElementById('status').innerText = 'error: connection lost';+ eventSource.close();+ };+ }++ function stopStream() {+ if (eventSource) {+ eventSource.close();+ eventSource = null;+ document.getElementById('status').innerText = 'stopped';+ }+ }++ // Initialize with default time range+ setDefaultTimes();+ </script>+</body>+</html>diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rsindex ce7f8d864..8b019866b 100644--- a/screenpipe-server/src/server.rs+++ b/screenpipe-server/src/server.rs@@ -41,7 +41,7 @@ use std::{time::Duration,};-use tokio::{fs, net::TcpListener};+use tokio::net::TcpListener;use tower_http::{cors::Any, trace::TraceLayer};use tower_http::{cors::CorsLayer, trace::DefaultMakeSpan};@@ -754,6 +754,7 @@ impl Server {FrameCache::with_config(self.screenpipe_dir.clone().join("data"),FrameCacheConfig {+ cache_dir: None,prefetch_size: chrono::Duration::seconds(60),cleanup_interval: chrono::Duration::minutes(360),fps: 1.0,@@ -1162,7 +1163,6 @@ struct InputControlResponse {pub struct StreamFramesRequest {start_time: DateTime<Utc>,end_time: DateTime<Utc>,- fps: Option<f64>,}#[derive(Serialize)]@@ -1215,43 +1215,89 @@ async fn stream_frames_handler("stream_frames_handler start_time={:?} end_time={:?}",request.start_time, request.end_time);++ let (progress_tx, mut progress_rx) = tokio::sync::mpsc::channel(100);+ let (frame_tx, mut frame_rx) = tokio::sync::mpsc::channel(100);+ let cache = state.frame_cache.clone();++ // Spawn prefetch task+ tokio::spawn(async move {+ if let Err(e) = cache+ .preload_frames_with_progress(+ &request.start_time,+ &request.end_time,+ progress_tx,+ frame_tx,+ )+ .await+ {+ error!("prefetch failed: {}", e);+ }+ });+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)]+ loop {+ tokio::select! {+ Some(progress) = progress_rx.recv() => {+ let json = serde_json::to_string(&StreamResponse::Progress(progress)).unwrap();+ yield Ok(Event::default().event("progress").data(json));+ }+ Some((timestamp, frame_data)) = frame_rx.recv() => {+ let response = StreamResponse::Frame(StreamFramesResponse {frame: base64::encode(&frame_data),- timestamp: current_time,- file_path: frame_path.to_string_lossy().to_string(),+ timestamp,+ file_path: "".to_string(), // Could pass this through if neededapp_name: None,window_name: None,- };+ });if let Ok(json) = serde_json::to_string(&response) {- yield Ok(Event::default()- .event("frame")- .data(json));+ 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);+ else => break,}-- current_time = current_time - chrono::Duration::milliseconds((1000.0 / request.fps.unwrap_or(1.0)) as i64);- tokio::time::sleep(Duration::from_millis(5)).await;}};Sse::new(stream)}+// Add new response types+#[derive(Serialize)]+#[serde(tag = "type", content = "data")]+pub enum StreamResponse {+ Progress(ProgressInfo),+ Frame(StreamFramesResponse),+}++#[derive(Serialize)]+pub struct ProgressInfo {+ message: String,+ percent: f32,+ total_chunks: usize,+ processed_chunks: usize,+ current_timestamp: DateTime<Utc>,+}++impl ProgressInfo {+ pub fn new(+ message: String,+ percent: f32,+ total_chunks: usize,+ processed_chunks: usize,+ current_timestamp: DateTime<Utc>,+ ) -> Self {+ Self {+ message,+ percent,+ total_chunks,+ processed_chunks,+ current_timestamp,+ }+ }+}+/*Curl commands for reference:diff --git a/screenpipe-server/src/video_cache.rs b/screenpipe-server/src/video_cache.rsindex 24c43ee49..06796147f 100644--- a/screenpipe-server/src/video_cache.rs+++ b/screenpipe-server/src/video_cache.rs@@ -10,16 +10,21 @@ use tokio::sync::mpsc::{channel, Sender};use tokio::sync::RwLock;use tracing::{debug, error, info};+use crate::server::ProgressInfo;use glob::glob;use screenpipe_core::find_ffmpeg_path;-use std::collections::HashMap;+use std::collections::{HashMap, HashSet};use std::time::SystemTime;+use tokio::io::AsyncBufReadExt;+use tokio::io::BufReader;+use tokio::process::ChildStdout;#[derive(Clone)]pub struct FrameCacheConfig {pub prefetch_size: Duration,pub cleanup_interval: Duration,pub fps: f32,+ pub cache_dir: Option<PathBuf>,}impl Default for FrameCacheConfig {@@ -28,6 +33,7 @@ impl Default for FrameCacheConfig {prefetch_size: Duration::minutes(5),cleanup_interval: Duration::minutes(5),fps: 1.0,+ cache_dir: None,}}}@@ -39,6 +45,7 @@ pub struct FrameCache {cache_tx: Sender<CacheCommand>,last_accessed_range: Arc<RwLock<Option<(DateTime<Utc>, DateTime<Utc>)>>>,config: FrameCacheConfig,+ validated_files: Arc<RwLock<HashSet<String>>>,}#[derive(Debug)]@@ -128,7 +135,13 @@ rules:- we should not use file name as to parse the date - too risky on cross-platform stuff*/-+#[derive(Clone)]+struct CachedChunk {+ file_path: String,+ start_time: DateTime<Utc>,+ end_time: DateTime<Utc>,+ last_check: DateTime<Utc>,+}impl FrameCache {pub async fn new(screenpipe_dir: PathBuf) -> Result<Self> {Self::with_config(screenpipe_dir, FrameCacheConfig::default()).await@@ -136,7 +149,10 @@ impl FrameCache {pub async fn with_config(screenpipe_dir: PathBuf, config: FrameCacheConfig) -> Result<Self> {info!("initializing frame cache");- let cache_dir = cache_dir().unwrap().join("screenpipe");+ let cache_dir = match config.clone().cache_dir {+ Some(dir) => dir,+ None => cache_dir().unwrap().join("screenpipe"),+ };fs::create_dir_all(&cache_dir).await?;let (cache_tx, mut cache_rx) = channel(100);@@ -146,12 +162,15 @@ impl FrameCache {cache_tx,last_accessed_range: Arc::new(RwLock::new(None)),config,+ validated_files: Arc::new(RwLock::new(HashSet::new())),};// Start background scanner tasklet scanner_cache = cache.clone();tokio::spawn(async move {- let mut interval = tokio::time::interval(Duration::seconds(10).to_std().unwrap());+ // scan every prefetch_size / 3+ let mut interval =+ tokio::time::interval(scanner_cache.config.prefetch_size.to_std().unwrap());loop {interval.tick().await;let now = Utc::now();@@ -283,25 +302,14 @@ impl FrameCache {}}- 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>>> {+ frame_tx: tokio::sync::mpsc::Sender<(DateTime<Utc>, Vec<u8>)>,+ ) -> Result<()> {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 seekinglet metadata = tokio::fs::metadata(file_path).await?;@@ -322,15 +330,15 @@ impl FrameCache {let duration = (end_time - start_time).num_seconds();debug!(- "batch extracting frames from {} at offset {}s for {}s at {} fps",+ "streaming 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",+ "-hwaccel",+ "auto","-ss",&seek_str,"-i",@@ -338,119 +346,129 @@ impl FrameCache {"-t",&duration.to_string(),"-vf",- &format!(- "fps={},format=yuv420p,scale=iw:ih:force_original_aspect_ratio=decrease",- fps- ),+ &format!("fps={}", 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+ let stdout = child.stdout.take()- .ok_or_else(|| anyhow::anyhow!("failed to get stdout"))?;- let mut stderr = child+ .ok_or_else(|| anyhow::anyhow!("no stdout"))?;+ let mut reader = BufReader::new(stdout);++ // Spawn a task to handle stderr+ let stderr = child.stderr.take()- .ok_or_else(|| anyhow::anyhow!("failed to get stderr"))?;-- // Read stderr in background to avoid blocking+ .ok_or_else(|| anyhow::anyhow!("no stderr"))?;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)+ let mut stderr_reader = BufReader::new(stderr);+ let mut line = String::new();+ while let Ok(n) = stderr_reader.read_line(&mut line).await {+ if n == 0 {+ break;+ }+ // Only log as error if the line contains error-indicating terms+ if line.to_lowercase().contains("error") || line.to_lowercase().contains("fatal") {+ error!("ffmpeg error: {}", line.trim());+ } else {+ debug!("ffmpeg: {}", line.trim());+ }+ line.clear();+ }});- // Read JPEG magic bytes- let mut magic = [0u8; 2];+ // Read JPEG frames from stdout+ let frame_interval = Duration::milliseconds((1000.0 / fps) as i64);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;- }- }+ while let Ok(frame_read) = Self::read_jpeg_frame(&mut reader).await {+ match frame_read {+ Some(frame_data) => {+ // Successfully read a frame, send it through the channel+ if let Err(e) = frame_tx.send((current_time, frame_data)).await {+ error!("failed to send frame: {}", e);+ break;}-- frames.insert(current_time, frame_data);- current_time = current_time + Duration::milliseconds((1000.0 / fps) as i64);+ current_time = current_time + frame_interval;}- Ok(_) => continue, // Not a JPEG frame, skip- Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => break,- Err(e) => {- error!("error reading frame: {}", e);+ None => {+ // End of streambreak;}}}- let status = child.wait().await?;- let stderr_output = stderr_handle.await.unwrap_or_else(|e| {- error!("failed to read stderr: {}", e);- Ok(String::new())- })?;+ // Wait for stderr handler and child process to finish+ stderr_handle.abort();+ let _ = child.wait().await;- 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- ));+ Ok(())+ }++ // Helper function to read a JPEG frame from the stream+ async fn read_jpeg_frame(reader: &mut BufReader<ChildStdout>) -> Result<Option<Vec<u8>>> {+ let mut buffer = Vec::new();++ // Look for JPEG start marker+ let mut marker = [0u8; 2];+ if reader.read_exact(&mut marker).await.is_err() {+ return Ok(None);}- 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- ));+ while marker != [0xFF, 0xD8] {+ marker[0] = marker[1];+ if reader.read_exact(&mut marker[1..]).await.is_err() {+ return Ok(None);+ }}- debug!("successfully extracted {} frames", frames.len());- Ok(frames)+ buffer.extend_from_slice(&marker);++ // Read until JPEG end marker+ loop {+ if reader.read_exact(&mut marker).await.is_err() {+ return Ok(None);+ }+ buffer.extend_from_slice(&[marker[0]]);++ if marker == [0xFF, 0xD9] {+ buffer.extend_from_slice(&[marker[1]]);+ return Ok(Some(buffer));+ }+ }}- async fn is_video_file_complete(file_path: &str) -> bool {+ async fn is_video_file_complete(&self, file_path: &str) -> bool {+ // Add file age check first+ if let Ok(metadata) = tokio::fs::metadata(file_path).await {+ if let Ok(modified) = metadata.modified() {+ let age = SystemTime::now()+ .duration_since(modified)+ .unwrap_or_default();++ // Skip validation for files modified in last 60s+ if age.as_secs() < 60 {+ return false;+ }+ }+ }++ // Check validated cache first+ {+ let validated = self.validated_files.read().await;+ if validated.contains(file_path) {+ return true;+ }+ }+let ffmpeg_path = match find_ffmpeg_path() {Some(path) => path,None => {@@ -474,6 +492,10 @@ impl FrameCache {String::from_utf8_lossy(&output.stderr));}+ if is_complete {+ let mut validated = self.validated_files.write().await;+ validated.insert(file_path.to_string());+ }is_complete}Err(e) => {@@ -488,18 +510,49 @@ impl FrameCache {start: DateTime<Utc>,end: DateTime<Utc>,) -> Result<Vec<VideoChunk>> {+ // Add static chunk cache+ use lazy_static::lazy_static;+ use std::sync::Mutex;++ lazy_static! {+ static ref CHUNK_CACHE: Mutex<HashMap<String, CachedChunk>> =+ Mutex::new(HashMap::new());+ }++ let now = Utc::now();+ let cache_ttl = Duration::minutes(5);++ // Check cache first+ let mut chunks = Vec::new();+ {+ let cache = CHUNK_CACHE.lock().unwrap();+ for chunk in cache.values() {+ if (now - chunk.last_check) < cache_ttl+ && chunk.start_time <= end+ && chunk.end_time >= start+ {+ chunks.push(VideoChunk {+ file_path: chunk.file_path.clone(),+ start_time: chunk.start_time,+ end_time: chunk.end_time,+ });+ }+ }+ }++ if !chunks.is_empty() {+ debug!("using {} cached chunks", chunks.len());+ return Ok(chunks);+ }+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() {@@ -510,10 +563,7 @@ impl FrameCache {.duration_since(modified).unwrap_or_default();- debug!("file age: {}s, chunk_time: {}", age.as_secs(), chunk_time);-- if age.as_secs() < 10 {- debug!("skipping very recent file: {}", file_path);+ if age.as_secs() < 60 {continue;}@@ -534,12 +584,34 @@ impl FrameCache {debug!("total usable chunks found: {}", chunks.len());chunks.sort_by_key(|chunk| chunk.start_time);++ // Update cache+ {+ let mut cache = CHUNK_CACHE.lock().unwrap();+ for chunk in &chunks {+ cache.insert(+ chunk.file_path.clone(),+ CachedChunk {+ file_path: chunk.file_path.clone(),+ start_time: chunk.start_time,+ end_time: chunk.end_time,+ last_check: Utc::now(),+ },+ );+ }+ }+Ok(chunks)}async fn preload_frames(&self, start: &DateTime<Utc>, end: &DateTime<Utc>) -> Result<()> {debug!("preloading frames from {} to {}", start, end);+ // Create channels for internal use+ let (frame_tx, mut frame_rx) = tokio::sync::mpsc::channel::<(DateTime<Utc>, Vec<u8>)>(100);+ let (progress_tx, _progress_rx) = tokio::sync::mpsc::channel::<ProgressInfo>(100);++ // Process chunks and stream frameslet chunks = Self::find_video_chunks(&self.screenpipe_dir, *start, *end).await?;debug!("found {} chunks to process", chunks.len());@@ -551,52 +623,28 @@ impl FrameCache {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);+ if !self.is_video_file_complete(&chunk.file_path).await {continue;}- match Self::extract_frames_batch(+ if let Err(e) = Self::extract_frames_batch(&chunk.file_path,chunk.start_time,chunk.end_time,self.config.fps,+ frame_tx.clone(),).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);- }+ 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?;+ // Handle received frames if needed (e.g., caching)+ while let Some((timestamp, frame_data)) = frame_rx.recv().await {+ if let Err(e) = self.insert_frame(timestamp, &frame_data).await {+ error!("failed to cache frame at {}: {}", timestamp, e);+ }}Ok(())@@ -610,4 +658,82 @@ impl FrameCache {Ok(())}++ pub async fn preload_frames_with_progress(+ &self,+ start: &DateTime<Utc>,+ end: &DateTime<Utc>,+ progress_tx: tokio::sync::mpsc::Sender<ProgressInfo>,+ frame_tx: tokio::sync::mpsc::Sender<(DateTime<Utc>, Vec<u8>)>,+ ) -> Result<()> {+ debug!("preloading frames from {} to {}", start, end);++ let chunks = Self::find_video_chunks(&self.screenpipe_dir, *start, *end).await?;+ let total_chunks = chunks.len();++ debug!("found {} chunks to process", total_chunks);++ if chunks.is_empty() {+ let _ = progress_tx+ .send(ProgressInfo::new(+ "no video chunks found".to_string(),+ 100.0,+ 0,+ 0,+ *start,+ ))+ .await;+ return Ok(());+ }++ for (i, chunk) in chunks.into_iter().enumerate() {+ debug!(+ "processing chunk {}/{}: {}",+ i + 1,+ total_chunks,+ chunk.file_path+ );++ // Send progress update+ let _ = progress_tx+ .send(ProgressInfo::new(+ format!("processing chunk {}/{}", i + 1, total_chunks),+ (i as f32 / total_chunks as f32) * 100.0,+ total_chunks,+ i,+ chunk.start_time,+ ))+ .await;++ if !self.is_video_file_complete(&chunk.file_path).await {+ continue;+ }++ // Pass the frame_tx channel to extract_frames_batch+ if let Err(e) = Self::extract_frames_batch(+ &chunk.file_path,+ chunk.start_time,+ chunk.end_time,+ self.config.fps,+ frame_tx.clone(),+ )+ .await+ {+ error!("failed to extract frames from {}: {}", chunk.file_path, e);+ }+ }++ // Send completion progress+ let _ = progress_tx+ .send(ProgressInfo::new(+ "completed frame extraction".to_string(),+ 100.0,+ total_chunks,+ total_chunks,+ *end,+ ))+ .await;++ Ok(())+ }}diff --git a/screenpipe-server/tests/video_cache_test.rs b/screenpipe-server/tests/video_cache_test.rsindex 06f0bf69e..e76454235 100644--- a/screenpipe-server/tests/video_cache_test.rs+++ b/screenpipe-server/tests/video_cache_test.rs@@ -1,14 +1,14 @@use anyhow::Result;-use chrono::{Duration, Utc};+use chrono::{DateTime, 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 std::time::SystemTime;+use tempfile::TempDir;+use tokio::fs;+use tracing::{debug, info};use screenpipe_server::video_cache::{FrameCache, FrameCacheConfig};-async fn setup_test_env() -> Result<FrameCache> {+async fn setup_test_env() -> Result<(FrameCache, TempDir)> {// enabled tracing loggingtracing_subscriber::fmt().with_max_level(tracing::Level::DEBUG)@@ -19,34 +19,35 @@ async fn setup_test_env() -> Result<FrameCache> {.join(".screenpipe").join("data");+ // Create temporary directory for cache+ let temp_dir = TempDir::new()?;+println!("using real screenpipe data dir: {:?}", screenpipe_dir);- let cache = FrameCache::new(screenpipe_dir).await?;- Ok(cache)+ println!("using temp cache dir: {:?}", temp_dir.path());++ let config = FrameCacheConfig {+ cache_dir: Some(temp_dir.path().to_path_buf()),+ ..FrameCacheConfig::default()+ };++ let cache = FrameCache::with_config(screenpipe_dir, config).await?;+ Ok((cache, temp_dir))}#[tokio::test]async fn test_frame_retrieval() -> Result<()> {// Use custom config with shorter timeouts for testing+ let temp_dir = TempDir::new()?;let config = FrameCacheConfig {- prefetch_size: Duration::seconds(10),+ prefetch_size: Duration::seconds(300),cleanup_interval: Duration::minutes(1),fps: 1.0,+ cache_dir: Some(temp_dir.path().to_path_buf()),};-- let frame_cache = setup_test_env().await?;- let cache = FrameCache::with_config(frame_cache.screenpipe_dir, config).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);+ let (frame_cache, _temp_dir) = setup_test_env().await?;+ let cache = FrameCache::with_config(frame_cache.screenpipe_dir, config).await?;+ let target_time = Utc::now() - Duration::seconds(300);// Now try to get the frame with timeoutlet frame = tokio::time::timeout(@@ -57,7 +58,7 @@ async fn test_frame_retrieval() -> Result<()> {.unwrap().unwrap();- println!(+ info!("successfully retrieved frame for timestamp {}: {:?}",target_time, frame);@@ -66,13 +67,13 @@ async fn test_frame_retrieval() -> Result<()> {#[tokio::test]async fn test_skip_recent_videos() -> Result<()> {- let cache = setup_test_env().await?;+ let (cache, _temp_dir) = setup_test_env().await?;// Try to get frame from very recent recordinglet target_time = Utc::now() - Duration::seconds(30);let frame = cache.get_frame(target_time).await;- println!("attempted to get frame from recent video: {:?}", frame);+ info!("attempted to get frame from recent video: {:?}", frame);assert!(frame.is_none(),"should not get frames from very recent videos"@@ -82,14 +83,15 @@ async fn test_skip_recent_videos() -> Result<()> {#[tokio::test]async fn test_prefetch_mechanism() -> Result<()> {- // Use custom config with smaller prefetch size for testing+ let temp_dir = TempDir::new()?;let config = FrameCacheConfig {- prefetch_size: Duration::seconds(10), // Smaller window for testing+ prefetch_size: Duration::seconds(10),cleanup_interval: Duration::minutes(1),fps: 1.0,+ cache_dir: Some(temp_dir.path().to_path_buf()),};- let frame_cache = setup_test_env().await?;+ let (frame_cache, _temp_dir) = setup_test_env().await?;let cache = FrameCache::with_config(frame_cache.screenpipe_dir, config).await?;// Request frame from 1 hour ago to trigger prefetch@@ -100,15 +102,15 @@ async fn test_prefetch_mechanism() -> Result<()> {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);+ info!("prefetch test - initial frame: {:?}", frame);+ info!("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 (cache, _temp_dir) = setup_test_env().await?;let start_time = Utc::now() - Duration::minutes(5);let mut frames = Vec::new();@@ -121,11 +123,11 @@ async fn test_high_speed_streaming() -> Result<()> {}if i % 10 == 0 {- println!("retrieved {} frames", frames.len());+ info!("retrieved {} frames", frames.len());}}- println!("total frames retrieved: {}", frames.len());+ info!("total frames retrieved: {}", frames.len());Ok(())}@@ -180,9 +182,14 @@ async fn test_frame_extraction() -> Result<()> {start_time, end_time);- let frames =- FrameCache::extract_frames_batch(test_file.to_str().unwrap(), start_time, end_time, 10.0)- .await?;+ let (tx, mut rx) = tokio::sync::mpsc::channel::<(DateTime<Utc>, Vec<u8>)>(100);+ FrameCache::extract_frames_batch(test_file.to_str().unwrap(), start_time, end_time, 10.0, tx)+ .await?;++ let mut frames = Vec::new();+ while let Some((timestamp, frame)) = rx.recv().await {+ frames.push((timestamp, frame));+ }debug!("extracted {} frames", frames.len());assert!(!frames.is_empty(), "Should extract at least one frame");