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
IT WORKS
Louis Beaumont960e983cce0b
diff --git a/screenpipe-app-tauri/app/timeline/page.tsx b/screenpipe-app-tauri/app/timeline/page.tsxindex 41d990b12..69f5cded4 100644--- a/screenpipe-app-tauri/app/timeline/page.tsx+++ b/screenpipe-app-tauri/app/timeline/page.tsx@@ -31,14 +31,41 @@ export default function Timeline() {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);+ console.log("starting stream:", url);const eventSource = new EventSource(url);eventSourceRef.current = eventSource;+ eventSource.onmessage = (event) => {+ try {+ const frame = JSON.parse(event.data);+ if (frame === "keep-alive-text" || !frame.frame) return;++ setFrames((prev) => {+ // Deduplicate frames based on timestamp+ const exists = prev.some((f) => f.timestamp === frame.timestamp);+ if (exists) return prev;+ return [...prev, frame];+ });++ // Only set current frame and loading state if it's our first frame+ setCurrentFrame((prev) => prev || frame);+ setIsLoading(false);+ } catch (error) {+ console.error("failed to parse frame data:", error);+ }+ };+eventSource.onerror = (error) => {- console.error("EventSource error:", error);- setError("Connection lost. Retrying...");+ // Ignore end of stream errors (expected behavior)+ if (eventSource.readyState === EventSource.CLOSED) {+ console.log("stream ended (expected behavior)");+ setIsLoading(false);+ return;+ }++ console.error("eventsource error:", error);+ setError("connection lost. retrying...");eventSource.close();@@ -46,43 +73,23 @@ export default function Timeline() {retryTimeoutRef.current = setTimeout(() => {retryCount.current += 1;console.log(- `Retrying connection (${retryCount.current}/${maxRetries})...`+ `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."+ "failed to connect after multiple attempts. please refresh the page.");setIsLoading(false);}};eventSource.onopen = () => {- console.log("EventSource connection opened");+ 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(() => {@@ -116,15 +123,28 @@ export default function Timeline() {return (<div- className="fixed inset-0 flex flex-col bg-white text-white overflow-hidden"+ className="fixed inset-0 flex flex-col bg-black text-white overflow-hidden font-['Press_Start_2P'] relative"onWheel={handleScroll}style={{ height: "100vh" }}>+ {/* Scanline effect overlay */}+ <div+ className="fixed inset-0 pointer-events-none z-50"+ style={{+ background:+ "repeating-linear-gradient(0deg, rgba(0,0,0,0.1) 0px, rgba(0,0,0,0.1) 1px, transparent 1px, transparent 2px)",+ imageRendering: "pixelated",+ }}+ />+{/* 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 className="absolute inset-0 flex items-center justify-center">+ <div className="bg-black/90 p-5 border-4 border-[#333] shadow-2xl text-center">+ <p>loading frames...</p>+ <div className="animate-blink inline-block w-2 h-2 bg-white ml-1" />+ </div></div>)}{error && (@@ -135,53 +155,69 @@ export default function Timeline() {{currentFrame && (<imgsrc={`data:image/png;base64,${currentFrame.frame}`}- className="absolute inset-0 w-full h-full object-contain"+ className="absolute inset-0 w-4/5 h-auto max-h-[80vh] object-contain mx-auto mt-8 border-4 border-[#333] shadow-[0_0_16px_rgba(255,255,255,0.1)]"+ style={{ imageRendering: "pixelated" }}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>+ {/* Info text */}+ <div className="text-center text-[#888] text-xs tracking-wider my-5">+ {currentFrame && (<span>- {currentFrame?.app_name}{" "}- {currentFrame?.window_name ? `- ${currentFrame.window_name}` : ""}+ timestamp: {new Date(currentFrame.timestamp).toLocaleString()} |+ app: {currentFrame?.app_name || "n/a"} | window:{" "}+ {currentFrame?.window_name || "n/a"}</span>+ )}+ </div>++ {/* Timeline bar */}+ <div className="w-4/5 mx-auto mb-8 relative">+ <div+ className="h-[60px] bg-[#111] border-4 border-[#444] shadow-[0_0_16px_rgba(0,0,0,0.8),inset_0_0_8px_rgba(255,255,255,0.1)] cursor-crosshair relative"+ style={{ imageRendering: "pixelated" }}+ >+ {/* Grid lines */}+ <div+ className="absolute inset-0"+ style={{+ background:+ "linear-gradient(90deg, rgba(0,255,0,0.1) 1px, transparent 1px)",+ backgroundSize: "10% 100%",+ }}+ />++ {/* Current position indicator */}+ <div+ className="absolute top-0 h-full w-1 bg-[#0f0] shadow-[0_0_12px_#0f0] opacity-80"+ style={{+ left: `${(currentIndex / Math.max(frames.length - 1, 1)) * 100}%`,+ }}+ /></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>- ))}+ {/* Timeline timestamps */}+ <div className="relative mt-1 px-2 text-[10px] text-[#0f0] shadow-[0_0_8px_#0f0]">+ {frames.length > 0 &&+ Array(5)+ .fill(0)+ .map((_, i) => {+ const position = i / 4;+ const frameIndex = Math.floor(position * (frames.length - 1));+ return (+ <div+ key={i}+ className="absolute transform -translate-x-1/2"+ style={{ left: `${position * 100}%` }}+ >+ {new Date(+ frames[frameIndex]?.timestamp+ ).toLocaleTimeString()}+ </div>+ );+ })}</div></div></div>diff --git a/screenpipe-server/Cargo.toml b/screenpipe-server/Cargo.tomlindex 2027ae2c7..dabc217cc 100644--- a/screenpipe-server/Cargo.toml+++ b/screenpipe-server/Cargo.toml@@ -95,6 +95,7 @@ tempfile = "3.3.0"regex = "1.11.0"glob = "0.3.1"lazy_static = "1.4.0"+lru = "0.12.5"url = { version = "2.2.0", optional = true }diff --git a/screenpipe-server/examples/timeline_ui/index.html b/screenpipe-server/examples/timeline_ui/index.htmlindex c6d234f2c..8cc063485 100644--- a/screenpipe-server/examples/timeline_ui/index.html+++ b/screenpipe-server/examples/timeline_ui/index.html@@ -204,40 +204,37 @@<img id="frame" /><div id="info"></div><div id="error"></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();+ let frames = []; // Store all framesconst 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, message = '') {- isLoading = state;- loading.classList.toggle('active', state);- if (!state) {- progressBar.style.width = '0%';- progressText.textContent = '';- }- }+ function updateTimelineCursor() {+ const cursor = document.getElementById('cursor');+ const timeRange = endTime - startTime;+ const position = (currentTime - startTime) / timeRange;+ cursor.style.left = `${position * 100}%`;- function updateProgress(progress) {- progressBar.style.width = `${progress.percent}%`;- progressText.textContent = progress.message;+ // Update highlight position+ const highlight = document.querySelector('.timeline-highlight');+ highlight.style.left = `${position * 100}%`;}- function updateTimeline() {- const cursor = document.getElementById('cursor');- const position = ((currentTime - startTime) / (endTime - startTime)) * 100;- cursor.style.left = `${position}%`;+ function displayFrameAtTime(timestamp) {+ // Find the closest frame to the requested timestamp+ const frame = frames.reduce((prev, curr) => {+ return Math.abs(new Date(curr.timestamp) - timestamp) < Math.abs(new Date(prev.timestamp) - timestamp) ? curr : prev;+ });++ const frameElement = document.getElementById('frame');+ frameElement.style.display = 'block';+ frameElement.src = `data:image/jpeg;base64,${frame.frame.trim().replace(/\s/g, '')}`;++ document.getElementById('info').textContent =+ `timestamp: ${frame.timestamp} | app: ${frame.app_name || 'n/a'} | window: ${frame.window_name || 'n/a'}`;+ currentTime = new Date(frame.timestamp);+ updateTimelineCursor();}function connectToStream(startTime, endTime) {@@ -245,94 +242,34 @@window.eventSource.close();}- setLoading(true, 'connecting to stream...');-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');+ url.searchParams.append('start_time', `${startTime.toISOString().slice(0, -1)}Z`);+ url.searchParams.append('end_time', `${endTime.toISOString().slice(0, -1)}Z`);- console.log('connecting to:', url.toString());-- window.eventSource = new EventSource(url.toString(), {- withCredentials: false- });+ window.eventSource = new EventSource(url.toString());+window.eventSource.onopen = () => {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) => {- 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;- }+ const data = JSON.parse(event.data);+ console.log('frame event:', data.frame.length);++ if (data === 'keep-alive-text' || !data.frame) 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();+ frames.push(data);+ displayFrameAtTime(new Date(data.timestamp));} catch (e) {console.error('Failed to parse frame data:', e);- console.error('Raw event data:', event.data);}- });+ };window.eventSource.onerror = (error) => {- setLoading(false);- const errorDetails = {- type: error.type,- target: {- readyState: window.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)}`;+ console.log('stream ended or errored (expected behavior)');window.eventSource.close();};}@@ -357,46 +294,32 @@}}- // Initialize timeline interaction+ // Modified timeline interactionconst timeline = document.getElementById('timeline');timeline.addEventListener('click', (e) => {const rect = timeline.getBoundingClientRect();const position = (e.clientX - rect.left) / rect.width;const timeRange = endTime - startTime;currentTime = new Date(startTime.getTime() + (timeRange * position));-- // Recalculate window around new current time- const windowSize = 3 * 60 * 1000; // 3 minutes instead of 5- const newStartTime = new Date(currentTime.getTime() - (windowSize / 2));- const newEndTime = new Date(currentTime.getTime() + (windowSize / 2));-- connectToStream(newStartTime, newEndTime);- updateTimelineMarkers();+ displayFrameAtTime(currentTime);+ updateTimelineCursor();});- // Handle keyboard navigation+ // Modified keyboard navigationdocument.addEventListener('keydown', (e) => {const step = 1000; // 1 second stepif (e.key === 'ArrowLeft') {currentTime = new Date(currentTime.getTime() - step);- connectToStream(- new Date(currentTime.getTime() - 150000),- new Date(currentTime.getTime() + 150000)- );- updateTimelineMarkers();+ displayFrameAtTime(currentTime);} else if (e.key === 'ArrowRight') {currentTime = new Date(currentTime.getTime() + step);- connectToStream(- new Date(currentTime.getTime() - 150000),- new Date(currentTime.getTime() + 150000)- );- updateTimelineMarkers();+ displayFrameAtTime(currentTime);}});// Initial connectionconst endTime = new Date();- const startTime = new Date(endTime - 1000 * 60 * 3); // last 3 minutes instead of 5+ const startTime = new Date(endTime - 1000 * 60 * 3); // last 3 minutesconnectToStream(startTime, endTime);updateTimelineMarkers();</script>diff --git a/screenpipe-server/examples/timeline_ui_simple/index.html b/screenpipe-server/examples/timeline_ui_simple/index.htmlindex 14caba297..2b42c3356 100644--- a/screenpipe-server/examples/timeline_ui_simple/index.html+++ b/screenpipe-server/examples/timeline_ui_simple/index.html@@ -12,16 +12,33 @@}#controls {+ position: sticky;+ top: 0;+ background: #000;+ padding: 20px 0;margin-bottom: 20px;+ z-index: 100;}- #frame {- max-width: 100%;+ #frames {+ display: flex;+ flex-direction: column;+ gap: 20px;+ }++ .frame-container {+ display: flex;+ flex-direction: column;+ gap: 10px;+ padding: 10px;border: 1px solid #333;}- #status {- margin-top: 10px;+ .frame-container img {+ max-width: 100%;+ }++ .frame-timestamp {color: #666;}@@ -45,23 +62,55 @@<input type="datetime-local" id="endTime" step="1"><button onclick="startStream()">start stream</button><button onclick="stopStream()">stop</button>+ <button onclick="clearFrames()">clear</button></div>- <img id="frame" src="">- <div id="status"></div>+ <div id="frames"></div><script>let eventSource = null;- // Set default time range to last 5 minutesfunction setDefaultTimes() {const end = new Date();- const start = new Date(end - 5 * 60 * 1000); // 5 minutes ago+ const start = new Date(end - 5 * 60 * 1000);document.getElementById('startTime').value = start.toISOString().slice(0, -1);document.getElementById('endTime').value = end.toISOString().slice(0, -1);}+ function clearFrames() {+ document.getElementById('frames').innerHTML = '';+ }++ function appendFrame(frame, timestamp) {+ console.log('Frame data length:', frame.length);+ console.log('First 100 chars:', frame.substring(0, 100));++ const container = document.createElement('div');+ container.className = 'frame-container';++ const img = document.createElement('img');+ img.onerror = (e) => console.error('Failed to load image:', e);+ img.onload = () => console.log('Image loaded successfully');++ const cleanBase64 = frame.trim().replace(/\s/g, '');+ img.src = `data:image/jpeg;base64,${cleanBase64}`;++ img.style.display = 'block';+ img.style.minHeight = '100px';++ const ts = document.createElement('div');+ ts.className = 'frame-timestamp';+ ts.innerText = new Date(timestamp).toLocaleString();++ container.appendChild(img);+ container.appendChild(ts);++ const frames = document.getElementById('frames');+ frames.appendChild(container);+ frames.scrollTop = frames.scrollHeight;+ }+function startStream() {if (eventSource) {eventSource.close();@@ -71,23 +120,28 @@const endTime = document.getElementById('endTime').value;const url = `http://localhost:3030/stream/frames?start_time=${startTime}Z&end_time=${endTime}Z`;+ console.log('starting stream:', url);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.onmessage = (event) => {+ try {+ const data = JSON.parse(event.data);++ if (data === 'keep-alive-text') {+ return;+ }++ if (data.frame && data.timestamp) {+ console.log('appending frame from:', data.timestamp);+ appendFrame(data.frame, data.timestamp);+ }+ } catch (e) {+ console.error('Failed to parse frame data:', e);+ }+ };eventSource.onerror = (error) => {console.error('sse error:', error);- document.getElementById('status').innerText = 'error: connection lost';eventSource.close();};}@@ -96,11 +150,9 @@if (eventSource) {eventSource.close();eventSource = null;- document.getElementById('status').innerText = 'stopped';}}- // Initialize with default time rangesetDefaultTimes();</script></body>diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rsindex 8b019866b..d456eccf7 100644--- a/screenpipe-server/src/server.rs+++ b/screenpipe-server/src/server.rs@@ -12,9 +12,6 @@ use futures::{};use image::ImageFormat::{self};-use screenpipe_vision::monitor::list_monitors;-use screenpipe_vision::OcrEngine;-use crate::{db::TagContentType,pipe_manager::{PipeInfo, PipeManager},@@ -24,12 +21,15 @@ use crate::{ContentType, DatabaseManager, SearchResult,};use crate::{plugin::ApiPluginLayer, video_utils::extract_frame};+use base64::prelude::*;use chrono::{DateTime, Utc};use log::{debug, error, info};use screenpipe_audio::{default_input_device, default_output_device, list_audio_devices, AudioDevice, DeviceControl,DeviceType,};+use screenpipe_vision::monitor::list_monitors;+use screenpipe_vision::OcrEngine;use serde::{Deserialize, Serialize};use serde_json::{json, Value};use std::{@@ -753,8 +753,8 @@ impl Server {frame_cache: Arc::new(FrameCache::with_config(self.screenpipe_dir.clone().join("data"),+ None,FrameCacheConfig {- cache_dir: None,prefetch_size: chrono::Duration::seconds(60),cleanup_interval: chrono::Duration::minutes(360),fps: 1.0,@@ -1212,63 +1212,44 @@ async fn stream_frames_handler(State(state): State<Arc<AppState>>,) -> Sse<impl Stream<Item = Result<Event, Infallible>>> {info!(- "stream_frames_handler start_time={:?} end_time={:?}",+ "streaming frames from {} to {}",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+ // Spawn frame extraction tasktokio::spawn(async move {if let Err(e) = cache- .preload_frames_with_progress(- &request.start_time,- &request.end_time,- progress_tx,- frame_tx,- )+ .extract_frames_range(&request.start_time, &request.end_time, frame_tx).await{- error!("prefetch failed: {}", e);+ error!("frame extraction failed: {}", e);}});let stream = async_stream::stream! {- 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,- file_path: "".to_string(), // Could pass this through if needed- app_name: None,- window_name: None,- });-- if let Ok(json) = serde_json::to_string(&response) {- yield Ok(Event::default().event("frame").data(json));- }- }- else => break,+ while let Some((timestamp, frame_data)) = frame_rx.recv().await {+ let response = StreamFramesResponse {+ frame: BASE64_STANDARD.encode(&frame_data),+ timestamp,+ file_path: "".to_string(),+ app_name: None,+ window_name: None,+ };++ if let Ok(json) = serde_json::to_string(&response) {+ yield Ok(Event::default().data(json));}}};- Sse::new(stream)-}--// Add new response types-#[derive(Serialize)]-#[serde(tag = "type", content = "data")]-pub enum StreamResponse {- Progress(ProgressInfo),- Frame(StreamFramesResponse),+ Sse::new(stream).keep_alive(+ axum::response::sse::KeepAlive::new()+ .interval(Duration::from_secs(1))+ .text("keep-alive-text"),+ )}#[derive(Serialize)]diff --git a/screenpipe-server/src/video_cache.rs b/screenpipe-server/src/video_cache.rsindex 06796147f..7e889b14f 100644--- a/screenpipe-server/src/video_cache.rs+++ b/screenpipe-server/src/video_cache.rs@@ -7,24 +7,66 @@ 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 crate::server::ProgressInfo;use glob::glob;use screenpipe_core::find_ffmpeg_path;-use std::collections::{HashMap, HashSet};use std::time::SystemTime;use tokio::io::AsyncBufReadExt;use tokio::io::BufReader;-use tokio::process::ChildStdout;++// Add these new imports at the top+use lru::LruCache;+use std::num::NonZeroUsize;+use tokio::sync::oneshot;++// Add these new types after the existing imports+#[derive(Debug, Clone)]+struct CachedFrame {+ timestamp: DateTime<Utc>,+ data: Arc<Vec<u8>>,+ last_accessed: DateTime<Utc>,+}++enum CacheMsg {+ GetFrame(i64, oneshot::Sender<Option<CachedFrame>>), // timestamp as key+ InsertFrame(i64, CachedFrame),+ Clear,+}++struct FrameCacheManager {+ frames: LruCache<i64, CachedFrame>, // timestamp -> frame+}++impl FrameCacheManager {+ fn new(capacity: usize) -> Self {+ Self {+ frames: LruCache::new(NonZeroUsize::new(capacity).unwrap()),+ }+ }++ fn handle_message(&mut self, msg: CacheMsg) {+ match msg {+ CacheMsg::GetFrame(timestamp, resp) => {+ let value = self.frames.get(×tamp).cloned();+ let _ = resp.send(value);+ }+ CacheMsg::InsertFrame(timestamp, frame) => {+ self.frames.put(timestamp, frame);+ }+ CacheMsg::Clear => {+ self.frames.clear();+ }+ }+ }+}#[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 {@@ -33,7 +75,6 @@ impl Default for FrameCacheConfig {prefetch_size: Duration::minutes(5),cleanup_interval: Duration::minutes(5),fps: 1.0,- cache_dir: None,}}}@@ -42,16 +83,8 @@ impl Default for FrameCacheConfig {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,- validated_files: Arc<RwLock<HashSet<String>>>,-}--#[derive(Debug)]-enum CacheCommand {- Cleanup,- ScanForNewFrames,+ cache_manager_tx: Sender<CacheMsg>,}#[derive(Debug)]@@ -135,34 +168,40 @@ 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+ pub async fn new(screenpipe_dir: PathBuf, cache_dir: Option<PathBuf>) -> Result<Self> {+ Self::with_config(screenpipe_dir, cache_dir, FrameCacheConfig::default()).await}- pub async fn with_config(screenpipe_dir: PathBuf, config: FrameCacheConfig) -> Result<Self> {+ pub async fn with_config(+ screenpipe_dir: PathBuf,+ cache_dir_: Option<PathBuf>,+ config: FrameCacheConfig,+ ) -> Result<Self> {info!("initializing frame cache");- let cache_dir = match config.clone().cache_dir {+ let cache_dir = match 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);++ // Add chunk cache manager channel+ let (cache_manager_tx, mut cache_manager_rx) = channel::<CacheMsg>(100);++ // Spawn cache manager task+ tokio::spawn(async move {+ let mut manager = FrameCacheManager::new(1000); // Adjust capacity as needed+ while let Some(msg) = cache_manager_rx.recv().await {+ manager.handle_message(msg);+ }+ });let cache = Self {screenpipe_dir,cache_dir: cache_dir.clone(),- cache_tx,- last_accessed_range: Arc::new(RwLock::new(None)),config,- validated_files: Arc::new(RwLock::new(HashSet::new())),+ cache_manager_tx,};// Start background scanner task@@ -183,123 +222,60 @@ impl FrameCache {}});- // Clone the parts needed for the cleanup task- let cleanup_cache = cache.clone();-- // Modify existing cleanup task to also handle ScanForNewFrames- tokio::spawn(async move {- let mut interval =- tokio::time::interval(cleanup_cache.config.cleanup_interval.to_std().unwrap());- loop {- tokio::select! {- _ = interval.tick() => {- debug!("performing scheduled 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 => {- debug!("performing requested cleanup");- // if let Err(e) = Self::cleanup_old_frames(&cleanup_cache).await {- // error!("failed to cleanup frames: {}", e);- // }- }- CacheCommand::ScanForNewFrames => {- let now = Utc::now();- // should be a percentage of the prefetch size- let scan_start = now - Duration::minutes(- cleanup_cache.config.prefetch_size.num_minutes() / 10- );- if let Err(e) = cleanup_cache.preload_frames(&scan_start, &now).await {- error!("failed to scan for new frames: {}", e);- }- }- }- }- }- }- });-Ok(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);- }+ pub async fn get_frame(&self, target_time: DateTime<Utc>) -> Option<Vec<u8>> {+ let timestamp = target_time.timestamp();++ // Try cache first+ let (tx, rx) = oneshot::channel();+ if let Ok(()) = self+ .cache_manager_tx+ .send(CacheMsg::GetFrame(timestamp, tx))+ .await+ {+ if let Ok(Some(frame)) = rx.await {+ debug!("cache hit for frame at {}", target_time);+ return Some(frame.data.as_ref().clone());}}- Ok(())- }+ // Cache miss - extract from video+ debug!("cache miss for frame at {}", target_time);+ let prefetch_end = target_time + self.config.prefetch_size;- pub async fn get_frame(&self, target_time: DateTime<Utc>) -> Option<PathBuf> {- debug!("getting frame for time: {}", target_time);+ let (_, mut rx) = tokio::sync::mpsc::channel::<(DateTime<Utc>, Vec<u8>)>(100);- // First check cache- let frame_path = self- .cache_dir- .join(format!("frame_{}.jpg", target_time.timestamp()));+ // Spawn prefetch task+ let cache = self.clone();+ tokio::spawn(async move {+ if let Err(e) = cache.preload_frames(&target_time, &prefetch_end).await {+ debug!("failed to preload frames: {}", e);+ }+ });- if frame_path.exists() {- debug!("frame found in cache: {:?}", frame_path);- return Some(frame_path);- }+ // Wait for the specific frame we need+ while let Some((frame_time, frame_data)) = rx.recv().await {+ // Cache the frame+ let frame = CachedFrame {+ timestamp: frame_time,+ data: Arc::new(frame_data.clone()),+ last_accessed: Utc::now(),+ };++ let _ = self+ .cache_manager_tx+ .send(CacheMsg::InsertFrame(frame_time.timestamp(), frame))+ .await;- // If not in cache, trigger prefetch- let prefetch_end = target_time + self.config.prefetch_size;- debug!(- "frame not in cache, prefetching range {} to {}",- target_time, prefetch_end- );-- if let Err(e) = self.preload_frames(&target_time, &prefetch_end).await {- error!("prefetch failed: {}", e);- return None;+ // Return if this is the frame we wanted+ if (frame_time - target_time).num_milliseconds().abs() < 1000 {+ return Some(frame_data);+ }}- // After prefetch, check cache again- if frame_path.exists() {- debug!("frame found after prefetch: {:?}", frame_path);- Some(frame_path)- } else {- debug!("frame not found even after prefetch: {}", target_time);- None- }+ None}pub async fn extract_frames_batch(@@ -307,143 +283,103 @@ impl FrameCache {start_time: DateTime<Utc>,end_time: DateTime<Utc>,fps: f32,- frame_tx: tokio::sync::mpsc::Sender<(DateTime<Utc>, Vec<u8>)>,+ frame_tx: Sender<(DateTime<Utc>, Vec<u8>)>,) -> Result<()> {- let ffmpeg_path = find_ffmpeg_path().ok_or_else(|| anyhow::anyhow!("ffmpeg not found"))?;-- // 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 ffmpeg = find_ffmpeg_path().ok_or_else(|| anyhow::anyhow!("ffmpeg not found"))?;+ // Calculate duration in secondslet duration = (end_time - start_time).num_seconds();- debug!(- "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(&[- "-hwaccel",- "auto",- "-ss",- &seek_str,- "-i",- file_path,- "-t",- &duration.to_string(),- "-vf",- &format!("fps={}", fps),- "-f",- "image2pipe",- "-vcodec",- "mjpeg",- "-",- ])+ let mut cmd = Command::new(ffmpeg);+ cmd.args([+ "-i",+ file_path,+ "-ss",+ "0", // Start from beginning of file+ "-t",+ &duration.to_string(),+ "-vf",+ &format!("fps={}", fps),+ "-f",+ "image2pipe",+ "-vcodec",+ "mjpeg",+ "-",+ ]);++ let mut child = cmd.stdout(std::process::Stdio::piped())- .stderr(std::process::Stdio::piped());+ .stderr(std::process::Stdio::piped())+ .spawn()?;- let mut child = command.spawn()?;+ // Get stdout handlelet stdout = child.stdout.take()- .ok_or_else(|| anyhow::anyhow!("no stdout"))?;- let mut reader = BufReader::new(stdout);+ .ok_or_else(|| anyhow::anyhow!("failed to get stdout"))?;- // Spawn a task to handle stderr+ // Spawn task to read stderr and log itlet stderr = child.stderr.take()- .ok_or_else(|| anyhow::anyhow!("no stderr"))?;- let stderr_handle = tokio::spawn(async move {- 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();+ .ok_or_else(|| anyhow::anyhow!("failed to get stderr"))?;+ tokio::spawn(async move {+ let mut reader = BufReader::new(stderr).lines();+ while let Ok(Some(line)) = reader.next_line().await {+ debug!("ffmpeg: {}", line);}});- // Read JPEG frames from stdout+ // Process frames in chunks+ let mut reader = BufReader::new(stdout);+ let mut frame_count = 0;+ let mut frame_time = start_time;let frame_interval = Duration::milliseconds((1000.0 / fps) as i64);- let mut current_time = start_time;-- 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;++ loop {+ // Read JPEG header marker+ let mut buf = [0u8; 2];+ if reader.read_exact(&mut buf).await.is_err() {+ break;+ }+ if buf != [0xFF, 0xD8] {+ continue;+ }++ // Read until JPEG end marker+ let mut frame_data = vec![0xFF, 0xD8];+ let mut last_byte = 0;+ loop {+ match reader.read_u8().await {+ Ok(byte) => {+ frame_data.push(byte);+ if last_byte == 0xFF && byte == 0xD9 {+ break;+ }+ last_byte = byte;}- current_time = current_time + frame_interval;+ Err(_) => break,}- None => {- // End of stream+ }++ // Send frame if it's complete+ if frame_data.ends_with(&[0xFF, 0xD9]) {+ if let Err(e) = frame_tx.send((frame_time, frame_data)).await {+ println!("failed to send frame: {}", e);break;}+ frame_count += 1;+ frame_time = start_time + frame_interval * frame_count;}}- // Wait for stderr handler and child process to finish- stderr_handle.abort();- let _ = child.wait().await;-- 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);+ // Ensure child process is terminated+ let status = child.wait().await?;+ if !status.success() {+ return Err(anyhow::anyhow!("ffmpeg failed with status: {}", status));}- while marker != [0xFF, 0xD8] {- marker[0] = marker[1];- if reader.read_exact(&mut marker[1..]).await.is_err() {- return Ok(None);- }- }-- 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));- }- }+ Ok(())}async fn is_video_file_complete(&self, file_path: &str) -> bool {@@ -461,14 +397,6 @@ impl FrameCache {}}- // 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 => {@@ -492,10 +420,6 @@ 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) => {@@ -504,49 +428,45 @@ impl FrameCache {}}}+ pub async fn extract_frames_range(+ &self,+ start: &DateTime<Utc>,+ end: &DateTime<Utc>,+ frame_tx: tokio::sync::mpsc::Sender<(DateTime<Utc>, Vec<u8>)>,+ ) -> Result<()> {+ let chunks = self+ .find_video_chunks(&self.screenpipe_dir, *start, *end)+ .await?;++ for chunk in chunks {+ if !self.is_video_file_complete(&chunk.file_path).await {+ continue;+ }+ 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);+ }+ }++ Ok(())+ }async fn find_video_chunks(+ &self,data_dir: &PathBuf,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 firstlet 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();let paths: Vec<_> = glob(&pattern)?.filter_map(Result::ok).collect();@@ -572,6 +492,7 @@ impl FrameCache {"found usable chunk: {} ({} to {})",file_path, chunk_time, chunk_end);+chunks.push(VideoChunk {file_path,start_time: chunk_time,@@ -585,22 +506,6 @@ 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)}@@ -609,10 +514,11 @@ impl FrameCache {// Create channels for internal uselet (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 frames- let chunks = Self::find_video_chunks(&self.screenpipe_dir, *start, *end).await?;+ let chunks = self+ .find_video_chunks(&self.screenpipe_dir, *start, *end)+ .await?;debug!("found {} chunks to process", chunks.len());if chunks.is_empty() {@@ -642,21 +548,23 @@ impl FrameCache {// 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);- }+ self.insert_frame(timestamp, frame_data).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?;+ async fn insert_frame(&self, timestamp: DateTime<Utc>, frame_data: Vec<u8>) {+ let frame = CachedFrame {+ timestamp,+ data: Arc::new(frame_data),+ last_accessed: Utc::now(),+ };- Ok(())+ let _ = self+ .cache_manager_tx+ .send(CacheMsg::InsertFrame(timestamp.timestamp(), frame))+ .await;}pub async fn preload_frames_with_progress(@@ -668,7 +576,9 @@ impl FrameCache {) -> Result<()> {debug!("preloading frames from {} to {}", start, end);- let chunks = Self::find_video_chunks(&self.screenpipe_dir, *start, *end).await?;+ let chunks = self+ .find_video_chunks(&self.screenpipe_dir, *start, *end)+ .await?;let total_chunks = chunks.len();debug!("found {} chunks to process", total_chunks);diff --git a/screenpipe-server/tests/video_cache_test.rs b/screenpipe-server/tests/video_cache_test.rsindex e76454235..54d524442 100644--- a/screenpipe-server/tests/video_cache_test.rs+++ b/screenpipe-server/tests/video_cache_test.rs@@ -4,7 +4,7 @@ use dirs::home_dir;use std::time::SystemTime;use tempfile::TempDir;use tokio::fs;-use tracing::{debug, info};+use tracing::{debug, error, info};use screenpipe_server::video_cache::{FrameCache, FrameCacheConfig};@@ -26,11 +26,13 @@ async fn setup_test_env() -> Result<(FrameCache, TempDir)> {println!("using temp cache dir: {:?}", temp_dir.path());let config = FrameCacheConfig {- cache_dir: Some(temp_dir.path().to_path_buf()),+ prefetch_size: Duration::seconds(120),..FrameCacheConfig::default()};- let cache = FrameCache::with_config(screenpipe_dir, config).await?;+ let cache =+ FrameCache::with_config(screenpipe_dir, Some(temp_dir.path().to_path_buf()), config)+ .await?;Ok((cache, temp_dir))}@@ -39,19 +41,23 @@ async fn test_frame_retrieval() -> Result<()> {// Use custom config with shorter timeouts for testinglet temp_dir = TempDir::new()?;let config = FrameCacheConfig {- prefetch_size: Duration::seconds(300),+ prefetch_size: Duration::seconds(30),cleanup_interval: Duration::minutes(1),fps: 1.0,- cache_dir: Some(temp_dir.path().to_path_buf()),};let (frame_cache, _temp_dir) = setup_test_env().await?;- let cache = FrameCache::with_config(frame_cache.screenpipe_dir, config).await?;+ let cache = FrameCache::with_config(+ frame_cache.screenpipe_dir,+ Some(temp_dir.path().to_path_buf()),+ config,+ )+ .await?;let target_time = Utc::now() - Duration::seconds(300);// Now try to get the frame with timeoutlet frame = tokio::time::timeout(- std::time::Duration::from_secs(5),+ std::time::Duration::from_secs(60),cache.get_frame(target_time),).await@@ -88,11 +94,15 @@ async fn test_prefetch_mechanism() -> Result<()> {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, _temp_dir) = setup_test_env().await?;- let cache = FrameCache::with_config(frame_cache.screenpipe_dir, config).await?;+ let cache = FrameCache::with_config(+ frame_cache.screenpipe_dir,+ Some(temp_dir.path().to_path_buf()),+ config,+ )+ .await?;// Request frame from 1 hour ago to trigger prefetchlet target_time = Utc::now() - Duration::hours(1);@@ -115,19 +125,31 @@ async fn test_high_speed_streaming() -> Result<()> {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);- }+ // Add timeout for the entire test+ let result = tokio::time::timeout(std::time::Duration::from_secs(30), async {+ // Get frames with delay between requests+ 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 {+ debug!("retrieved {} frames", frames.len());+ }- if i % 10 == 0 {- info!("retrieved {} frames", frames.len());+ // Add small delay between requests+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;}- }+ Ok::<_, anyhow::Error>(frames.len())+ })+ .await??;++ debug!("total frames retrieved: {}", result);++ // Assert we got at least some frames+ assert!(result > 0, "Should retrieve at least one frame");- info!("total frames retrieved: {}", frames.len());Ok(())}@@ -196,3 +218,71 @@ async fn test_frame_extraction() -> Result<()> {Ok(())}++#[tokio::test]+async fn test_frame_jpeg_integrity() -> Result<()> {+ let (cache, _temp_dir) = setup_test_env().await?;++ // Get a frame from 5 minutes ago+ let target_time = Utc::now() - Duration::minutes(5);+ let frame = cache.get_frame(target_time).await;++ if let Some(frame_data) = frame {+ // Read the frame data from the file+ debug!(+ "checking frame at {}, size: {} bytes",+ target_time,+ frame_data.len()+ );++ // Check JPEG header (SOI marker)+ let has_jpeg_header = frame_data.starts_with(&[0xFF, 0xD8]);++ // Check JPEG footer (EOI marker)+ let has_jpeg_footer = frame_data.ends_with(&[0xFF, 0xD9]);++ // Basic size sanity check (typical JPEG frame should be between 10KB and 1MB)+ let has_valid_size = frame_data.len() > 10_000 && frame_data.len() < 1_000_000;++ if has_jpeg_header && has_jpeg_footer && has_valid_size {+ debug!("frame passed JPEG validation");+ } else {+ error!(+ "invalid JPEG frame: header={}, footer={}, size={}",+ has_jpeg_header,+ has_jpeg_footer,+ frame_data.len()+ );++ // Log first and last few bytes for debugging+ if frame_data.len() >= 4 {+ debug!(+ "first 4 bytes: {:02X} {:02X} {:02X} {:02X}",+ frame_data[0], frame_data[1], frame_data[2], frame_data[3]+ );+ }+ if frame_data.len() >= 4 {+ let len = frame_data.len();+ debug!(+ "last 4 bytes: {:02X} {:02X} {:02X} {:02X}",+ frame_data[len - 4],+ frame_data[len - 3],+ frame_data[len - 2],+ frame_data[len - 1]+ );+ }+ }++ // Assert frame validity+ assert!(has_jpeg_header, "Frame should have valid JPEG header");+ assert!(has_jpeg_footer, "Frame should have valid JPEG footer");+ assert!(+ has_valid_size,+ "Frame size should be within reasonable bounds"+ );+ } else {+ debug!("no frame found for timestamp {}", target_time);+ }++ Ok(())+}