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
rework into timeseries the video_cache
Louis Beaumont68a45a05f272
diff --git a/screenpipe-server/Cargo.toml b/screenpipe-server/Cargo.tomlindex 36e13120f..b49a8c0a1 100644--- a/screenpipe-server/Cargo.toml+++ b/screenpipe-server/Cargo.toml@@ -112,6 +112,12 @@ enigo = { version = "0.2.1", optional = true }# Scope guard for cancelation of streamsscopeguard = "1.2.0"+# Bincode for serializing hot cache+bincode = "1.3.3"++# SHA256 for hashing+sha2 = "0.10.6"+[dev-dependencies]tempfile = "3.3.0"diff --git a/screenpipe-server/src/db.rs b/screenpipe-server/src/db.rsindex 23a8e85d1..2412efdf6 100644--- a/screenpipe-server/src/db.rs+++ b/screenpipe-server/src/db.rs@@ -22,7 +22,9 @@ use std::fmt;use std::sync::Arc;use std::time::Duration;+use std::collections::BTreeMap;use tokio::time::{timeout, Duration as TokioDuration};+#[derive(Debug)]pub struct DatabaseError(String);@@ -1150,42 +1152,146 @@ impl DatabaseManager {))}- pub async fn get_frame_metadata(+ // ! TODO: atm not sure what will happen if we have multiple transcriptions, OCR, etc for same timestamp (multi monitor, multi audio device...)+ // ! just merging+ // ! the offset is not quite right but we try to index around frames which is the central human experience and most important sense+ // ! there should be a way to properly sync audio and video indexes+ pub async fn find_video_chunks(&self,- file_path: &str,- ) -> Result<Vec<(DateTime<Utc>, String, String, String, String)>, SqlxError> {- debug!("getting frame metadata for file: {}", file_path);- sqlx::query_as::<_, (DateTime<Utc>, String, String, String, String)>(- r#"+ start: DateTime<Utc>,+ end: DateTime<Utc>,+ ) -> Result<TimeSeriesChunk, SqlxError> {+ // First get all frames in time range with their OCR data+ let frames_query = r#"SELECT- frames.timestamp,- ocr_text.app_name,- ocr_text.window_name,- ocr_text.text as ocr_text,- audio_transcriptions.transcription- FROM video_chunks- JOIN frames ON frames.video_chunk_id = video_chunks.id- JOIN ocr_text ON frames.id = ocr_text.frame_id- LEFT JOIN audio_transcriptions ON frames.timestamp = audio_transcriptions.timestamp- WHERE video_chunks.file_path = ?1- ORDER BY frames.timestamp ASC- "#,- )- .bind(file_path)- .fetch_all(&self.pool)- .await- .map(|rows| {- rows.into_iter()- .map(- |(timestamp, app_name, window_name, ocr_text, transcription)| {- (timestamp, app_name, window_name, ocr_text, transcription)- },- )- .collect()+ f.timestamp,+ f.offset_index,+ ot.text,+ ot.app_name,+ ot.window_name,+ vc.device_name as screen_device,+ vc.file_path as video_path+ 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 >= ?1 AND f.timestamp <= ?2+ ORDER BY f.timestamp, f.offset_index+ "#;++ // Then get audio data that overlaps with these frames+ let audio_query = r#"+ SELECT+ at.timestamp,+ at.transcription,+ at.device as audio_device,+ at.is_input_device,+ ac.file_path as audio_path+ FROM audio_transcriptions at+ JOIN audio_chunks ac ON at.audio_chunk_id = ac.id+ WHERE at.timestamp >= ?1 AND at.timestamp <= ?2+ ORDER BY at.timestamp+ "#;++ // Execute both queries+ let (frame_rows, audio_rows) = tokio::try_join!(+ sqlx::query(frames_query)+ .bind(start)+ .bind(end)+ .fetch_all(&self.pool),+ sqlx::query(audio_query)+ .bind(start)+ .bind(end)+ .fetch_all(&self.pool)+ )?;++ // Process into structured data+ let mut frames_map: BTreeMap<(DateTime<Utc>, i64), FrameData> = BTreeMap::new();++ // Process frame/OCR data+ for row in frame_rows {+ let timestamp: DateTime<Utc> = row.get("timestamp");+ let offset_index: i64 = row.get("offset_index");+ let key = (timestamp, offset_index);++ let frame_data = frames_map.entry(key).or_insert_with(|| FrameData {+ timestamp,+ offset_index,+ ocr_entries: Vec::new(),+ audio_entries: Vec::new(),+ });++ if let Ok(text) = row.try_get::<String, _>("text") {+ frame_data.ocr_entries.push(OCREntry {+ text,+ app_name: row.get("app_name"),+ window_name: row.get("window_name"),+ device_name: row.get("screen_device"),+ video_file_path: row.get("video_path"),+ });+ }+ }++ // Process audio data+ for row in audio_rows {+ let timestamp: DateTime<Utc> = row.get("timestamp");++ // Find the closest frame+ if let Some((&key, _)) = frames_map.range(..(timestamp, i64::MAX)).next_back() {+ if let Some(frame_data) = frames_map.get_mut(&key) {+ frame_data.audio_entries.push(AudioEntry {+ transcription: row.get("transcription"),+ device_name: row.get("audio_device"),+ is_input: row.get("is_input_device"),+ audio_file_path: row.get("audio_path"),+ // duration_secs: row.get("duration_secs"),+ duration_secs: 0.0, // TODO+ });+ }+ }+ }++ Ok(TimeSeriesChunk {+ frames: frames_map.into_values().collect(),+ start_time: start,+ end_time: end,})}}+#[derive(Debug, Clone)]+pub struct FrameData {+ pub timestamp: DateTime<Utc>,+ pub offset_index: i64,+ pub ocr_entries: Vec<OCREntry>,+ pub audio_entries: Vec<AudioEntry>,+}++#[derive(Debug, Clone)]+pub struct OCREntry {+ pub text: String,+ pub app_name: String,+ pub window_name: String,+ pub device_name: String,+ pub video_file_path: String,+}++#[derive(Debug, Clone)]+pub struct AudioEntry {+ pub transcription: String,+ pub device_name: String,+ pub is_input: bool,+ pub audio_file_path: String,+ // Optional: duration of this transcription+ pub duration_secs: f64,+}++#[derive(Debug, Clone)]+pub struct TimeSeriesChunk {+ pub frames: Vec<FrameData>,+ pub start_time: DateTime<Utc>,+ pub end_time: DateTime<Utc>,+}+impl Clone for DatabaseManager {fn clone(&self) -> Self {DatabaseManager {diff --git a/screenpipe-server/src/lib.rs b/screenpipe-server/src/lib.rsindex 8520933b1..5ae82aa65 100644--- a/screenpipe-server/src/lib.rs+++ b/screenpipe-server/src/lib.rs@@ -2,7 +2,7 @@ mod auto_destruct;pub mod chunking;pub mod cli;pub mod core;-mod db;+pub mod db;pub mod filtering;pub mod highlight;mod pipe_manager;diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rsindex 480bafb17..430fcb509 100644--- a/screenpipe-server/src/server.rs+++ b/screenpipe-server/src/server.rs@@ -16,7 +16,7 @@ use crate::{db::TagContentType,pipe_manager::{PipeInfo, PipeManager},video::{finish_ffmpeg_process, start_ffmpeg_process, write_frame_to_ffmpeg, MAX_FPS},- video_cache::{FrameCache, FrameCacheConfig},+ video_cache::{FrameCache, TimeSeriesFrame},video_utils::{merge_videos, MergeVideosRequest, MergeVideosResponse},ContentType, DatabaseManager, SearchResult,};@@ -753,17 +753,9 @@ impl Server {audio_disabled: self.audio_disabled,frame_cache: if enable_frame_cache {Some(Arc::new(- FrameCache::with_config(- self.screenpipe_dir.clone().join("data"),- self.db.clone(),- FrameCacheConfig {- prefetch_size: chrono::Duration::seconds(60),- cleanup_interval: chrono::Duration::minutes(360),- fps: 1.0,- },- )- .await- .unwrap(),+ FrameCache::new(self.screenpipe_dir.clone().join("data"), self.db.clone())+ .await+ .unwrap(),))} else {None@@ -1179,15 +1171,74 @@ pub struct StreamFramesRequest {// order: Order,}-#[derive(Serialize)]-pub struct StreamFramesResponse {- timestamp: DateTime<Utc>,- frame: String,- file_path: String,- app_name: String,- window_name: String,- transcription: String,- ocr_text: String,+#[derive(Debug, Serialize)]+pub struct StreamTimeSeriesResponse {+ pub timestamp: DateTime<Utc>,+ pub devices: Vec<DeviceFrameResponse>,+}++#[derive(Debug, Serialize)]+pub struct DeviceFrameResponse {+ pub device_id: String,+ pub frame: String, // base64 encoded image+ pub metadata: DeviceMetadata,+ pub audio: Vec<AudioData>,+}++#[derive(Debug, Serialize)]+pub struct DeviceMetadata {+ pub file_path: String,+ pub app_name: String,+ pub window_name: String,+ pub ocr_text: String,+}++#[derive(Debug, Serialize)]+pub struct AudioData {+ pub device_name: String,+ pub is_input: bool,+ pub transcription: String,+ pub audio_file_path: String,+ pub duration_secs: f64,+ pub start_offset: f64, // offset from frame timestamp+}++impl From<TimeSeriesFrame> for StreamTimeSeriesResponse {+ fn from(frame: TimeSeriesFrame) -> Self {+ StreamTimeSeriesResponse {+ timestamp: frame.timestamp,+ devices: frame+ .frame_data+ .into_iter()+ .map(|device_frame| {+ DeviceFrameResponse {+ device_id: device_frame.device_id,+ frame: BASE64_STANDARD.encode(&device_frame.image_data),+ metadata: DeviceMetadata {+ file_path: device_frame.metadata.file_path,+ app_name: device_frame.metadata.app_name,+ window_name: device_frame.metadata.window_name,+ ocr_text: device_frame.metadata.ocr_text,+ },+ audio: device_frame+ .audio_entries+ .into_iter()+ .map(|audio| {+ AudioData {+ device_name: audio.device_name,+ is_input: audio.is_input,+ transcription: audio.transcription,+ audio_file_path: audio.audio_file_path,+ duration_secs: audio.duration_secs,+ start_offset: 0.0, // calculate based on audio timestamp vs frame timestamp+ }+ })+ .collect(),+ }+ })+ .collect(),+ }+ }}pub fn create_router() -> Router<Arc<AppState>> {@@ -1266,18 +1317,8 @@ async fn stream_frames_handler(let _ = tx.send(()); // Signal cancellation when stream is dropped});- while let Some(frame_info) = frame_rx.recv().await {- let response = StreamFramesResponse {- timestamp: frame_info.timestamp,- frame: BASE64_STANDARD.encode(&frame_info.data),- file_path: frame_info.metadata.file_path,- app_name: frame_info.metadata.app_name,- window_name: frame_info.metadata.window_name,- transcription: frame_info.metadata.transcription,- ocr_text: frame_info.metadata.ocr_text,- };-- if let Ok(json) = serde_json::to_string(&response) {+ while let Some(timeseries_frame) = frame_rx.recv().await {+ if let Ok(json) = serde_json::to_string(&StreamTimeSeriesResponse::from(timeseries_frame)) {yield Ok(Event::default().data(json));}}diff --git a/screenpipe-server/src/video_cache.rs b/screenpipe-server/src/video_cache.rsindex cebc68e41..078cc2048 100644--- a/screenpipe-server/src/video_cache.rs+++ b/screenpipe-server/src/video_cache.rs@@ -24,31 +24,54 @@ We should be able to allow users to:*/-use anyhow::Result;+use bincode;use chrono::{DateTime, Duration, Utc};-use std::collections::BTreeMap;-use std::num::NonZeroUsize;-use std::path::{Path, PathBuf};+use dirs::cache_dir;+use screenpipe_core::find_ffmpeg_path;+use serde::{Deserialize, Serialize};+use sha2::{Digest, Sha256};+use std::collections::{BTreeMap, HashMap};+use std::path::PathBuf;+use std::sync::atomic::AtomicBool;use std::sync::Arc;use std::time::SystemTime;-use tokio::io::{AsyncRead, AsyncReadExt};+use tokio::fs;+use tokio::io::AsyncBufReadExt;use tokio::process::Command;use tokio::sync::mpsc::{channel, Sender};use tokio::sync::RwLock;use tracing::{debug, error};-use glob::glob;-use lru::LruCache;-use screenpipe_core::find_ffmpeg_path;-use tokio::io::AsyncBufReadExt;-use tokio::io::BufReader;-+use crate::db::{FrameData, OCREntry};use crate::DatabaseManager;-type FrameChannel = Sender<(DateTime<Utc>, Vec<u8>, FrameMetadata)>;+type FrameChannel = Sender<TimeSeriesFrame>;++#[derive(Debug, Clone)]+pub struct TimeSeriesFrame {+ pub timestamp: DateTime<Utc>,+ pub frame_data: Vec<DeviceFrame>,+}#[derive(Debug, Clone)]+pub struct DeviceFrame {+ pub device_id: String,+ pub image_data: Vec<u8>,+ pub metadata: FrameMetadata,+ pub audio_entries: Vec<AudioEntry>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct AudioEntry {+ pub transcription: String,+ pub device_name: String,+ pub is_input: bool,+ pub audio_file_path: String,+ pub duration_secs: f64,+}++#[derive(Debug, Clone, Serialize, Deserialize)]pub struct FrameMetadata {pub file_path: String,pub app_name: String,@@ -57,558 +80,639 @@ pub struct FrameMetadata {pub ocr_text: String,}-#[derive(Debug, Clone)]-struct PreviewFrame {+pub struct FrameInfo {+ pub timestamp: DateTime<Utc>,+ pub data: Vec<u8>,+ pub metadata: FrameMetadata,+}++#[derive(Debug, Serialize, Deserialize)]+struct CachedFrame {+ #[serde(with = "chrono::serde::ts_microseconds")]timestamp: DateTime<Utc>,- data: Arc<Vec<u8>>,+ device_id: String,+ checksum: String,metadata: FrameMetadata,- is_preview: bool,+ frame_size: u64,+ compression: CompressionType,+ source_video: String,+ #[serde(with = "chrono::serde::ts_microseconds")]+ cached_at: DateTime<Utc>,+ audio_entries: Vec<AudioEntry>,+}++#[derive(Debug, Serialize, Deserialize)]+enum CompressionType {+ Jpeg { quality: u8 },}#[derive(Debug)]-struct VideoFile {+pub struct CacheEntry {+ frame: CachedFrame,path: PathBuf,- start_time: DateTime<Utc>,- end_time: DateTime<Utc>,- size: u64,- is_complete: bool,- metadata: BTreeMap<DateTime<Utc>, FrameMetadata>,+ last_accessed: SystemTime,}-struct VideoIndex {- files: BTreeMap<DateTime<Utc>, VideoFile>,- total_size: u64,+#[derive(Debug, Clone)]+struct CacheConfig {+ cache_dir: PathBuf,+ max_cache_size_gb: f64,+ frame_retention_days: u64,+ compression_quality: u8,}-impl VideoIndex {- fn new() -> Self {+impl Default for CacheConfig {+ fn default() -> Self {Self {- files: BTreeMap::new(),+ cache_dir: PathBuf::from("frame_cache"),+ max_cache_size_gb: 10.0,+ frame_retention_days: 7,+ compression_quality: 85,+ }+ }+}++pub struct FrameDiskCache {+ config: CacheConfig,+ entries: BTreeMap<(DateTime<Utc>, String), CacheEntry>,+ total_size: u64,+ index_path: PathBuf,+}++impl FrameDiskCache {+ async fn new(config: CacheConfig) -> Result<Self> {+ let cache_dir = &config.cache_dir;+ let index_path = cache_dir.join("cache_index.bin");++ // Ensure cache directory exists+ fs::create_dir_all(cache_dir).await?;++ // Initialize empty cache+ let mut cache = Self {+ config,+ entries: BTreeMap::new(),total_size: 0,+ index_path,+ };++ // Try to load existing index, but don't fail if it doesn't exist+ if cache.index_path.exists() {+ if let Err(e) = cache.load_index().await {+ debug!("could not load existing cache index: {}", e);+ // Clear any partial data+ cache.entries.clear();+ cache.total_size = 0;+ }+ } else {+ // Create empty index file+ cache.save_index().await?;}++ Ok(cache)}- fn find_files_in_range(&self, start: DateTime<Utc>, end: DateTime<Utc>) -> Vec<&VideoFile> {- self.files- .range(..=end)- .filter(|(_, file)| file.end_time >= start)- .map(|(_, file)| file)- .collect()+ async fn load_index(&mut self) -> Result<()> {+ match fs::read(&self.index_path).await {+ Ok(data) if !data.is_empty() => match bincode::deserialize::<Vec<CachedFrame>>(&data) {+ Ok(frames) => {+ for frame in frames {+ let path = self.get_frame_path(&frame.timestamp, &frame.device_id);+ if let Ok(metadata) = fs::metadata(&path).await {+ self.entries.insert(+ (frame.timestamp, frame.device_id.clone()),+ CacheEntry {+ frame,+ path,+ last_accessed: metadata.accessed()?,+ },+ );+ self.total_size += metadata.len();+ }+ }+ debug!("loaded {} cached frames", self.entries.len());+ }+ Err(e) => {+ error!("failed to deserialize cache index: {}", e);+ }+ },+ Ok(_) => {+ debug!("cache index is empty, starting fresh");+ }+ Err(e) => {+ error!("failed to read cache index: {}", e);+ }+ }+ Ok(())}- async fn refresh_index(&mut self, data_dir: &Path) -> Result<()> {- debug!("refreshing video index...");- let mut new_files = BTreeMap::new();- let mut total_size = 0;+ async fn save_index(&self) -> Result<()> {+ let frames: Vec<_> = self.entries.values().map(|entry| &entry.frame).collect();+ let temp_path = self.index_path.with_extension("tmp");- let pattern = data_dir.join("**/monitor_*.mp4");- for entry in glob(&pattern.to_string_lossy())?.filter_map(Result::ok) {- let metadata = tokio::fs::metadata(&entry).await?;- if metadata.len() == 0 {- continue;- }+ // Initialize with empty Vec if no frames+ let encoded = if frames.is_empty() {+ bincode::serialize(&Vec::<CachedFrame>::new())?+ } else {+ bincode::serialize(&frames)?+ };++ // Write to temporary file+ fs::write(&temp_path, encoded)+ .await+ .map_err(|e| anyhow::anyhow!("failed to write temp index: {}", e))?;++ // Atomically rename+ fs::rename(&temp_path, &self.index_path)+ .await+ .map_err(|e| anyhow::anyhow!("failed to rename temp index: {}", e))?;++ Ok(())+ }++ pub async fn store_frame(+ &mut self,+ cache_key: &str,+ frame_data: &[u8],+ device_data: OCREntry,+ audio_entries: &[AudioEntry],+ ) -> Result<()> {+ debug!("storing frame with cache key: {}", cache_key);+ let (timestamp_str, device_id) = cache_key+ .split_once("||")+ .ok_or_else(|| anyhow::anyhow!("invalid cache key format"))?;++ // Clean up the timestamp string+ let clean_timestamp = timestamp_str+ .trim_end_matches(" UTC")+ .replace(' ', "T")+ .trim()+ .to_string();++ let clean_timestamp = if !clean_timestamp.ends_with('Z') && !clean_timestamp.contains('+') {+ format!("{}Z", clean_timestamp)+ } else {+ clean_timestamp+ };++ let timestamp = DateTime::parse_from_rfc3339(&clean_timestamp).map_err(|e| {+ anyhow::anyhow!("failed to parse timestamp '{}': {}", clean_timestamp, e)+ })?;++ let frame_path = self.get_frame_path(×tamp.into(), device_id);- let is_complete = SystemTime::now()- .duration_since(metadata.modified()?)?- .as_secs()- >= 60;-- let start_time: DateTime<Utc> = metadata.created()?.into();- let end_time = start_time + Duration::minutes(2);-- new_files.insert(- start_time,- VideoFile {- path: entry,- start_time,- end_time,- size: metadata.len(),- is_complete,- metadata: BTreeMap::new(),- },- );-- total_size += metadata.len();+ // Ensure parent directory exists+ if let Some(parent) = frame_path.parent() {+ fs::create_dir_all(parent).await?;}- self.files = new_files;- self.total_size = total_size;+ // Calculate checksum+ let mut hasher = Sha256::new();+ hasher.update(frame_data);+ let checksum = format!("{:x}", hasher.finalize());++ // Create cached frame entry+ let cached_frame = CachedFrame {+ timestamp: timestamp.into(),+ device_id: device_id.to_string(),+ checksum,+ metadata: FrameMetadata {+ file_path: device_data.video_file_path.clone(),+ app_name: device_data.app_name,+ window_name: device_data.window_name,+ transcription: audio_entries+ .iter()+ .map(|a| a.transcription.clone())+ .collect::<Vec<_>>()+ .join(" "),+ ocr_text: device_data.text,+ },+ frame_size: frame_data.len() as u64,+ compression: CompressionType::Jpeg {+ quality: self.config.compression_quality,+ },+ source_video: device_data.video_file_path,+ cached_at: Utc::now(),+ audio_entries: audio_entries.to_vec(),+ };- debug!(- "index refreshed: {} files, {:.2}GB total",- self.files.len(),- self.total_size as f64 / 1024.0 / 1024.0 / 1024.0+ // Write frame data+ fs::write(&frame_path, frame_data)+ .await+ .map_err(|e| anyhow::anyhow!("failed to write frame data: {}", e))?;++ // Update in-memory entries+ self.entries.insert(+ (timestamp.into(), device_id.to_string()),+ CacheEntry {+ frame: cached_frame,+ path: frame_path,+ last_accessed: SystemTime::now(),+ },);++ self.total_size += frame_data.len() as u64;+ self.save_index().await?;+Ok(())}-}-#[derive(Clone)]-pub struct FrameCacheConfig {- pub prefetch_size: Duration,- pub cleanup_interval: Duration,- pub fps: f32,-}+ pub async fn get_frame_data(+ &self,+ cache_key: &str,+ ) -> Result<Option<(Vec<u8>, FrameMetadata, (DateTime<Utc>, String))>> {+ let (timestamp_str, device_id) = match cache_key.split_once("||") {+ Some(parts) => parts,+ None => return Ok(None),+ };-impl Default for FrameCacheConfig {- fn default() -> Self {- Self {- prefetch_size: Duration::minutes(5),- cleanup_interval: Duration::minutes(5),- fps: 1.0,+ let timestamp = match DateTime::parse_from_rfc3339(timestamp_str) {+ Ok(ts) => ts,+ Err(_) => return Ok(None),+ };++ let frame_path = self.get_frame_path(×tamp.into(), device_id);++ if !frame_path.exists() {+ return Ok(None);}- }-}-#[derive(Debug)]-struct VideoChunk {- file_path: String,- start_time: DateTime<Utc>,- end_time: DateTime<Utc>,- metadata: BTreeMap<DateTime<Utc>, FrameMetadata>,-}+ let frame_data = fs::read(&frame_path).await?;-#[derive(Debug, Clone)]-pub struct FrameInfo {- pub timestamp: DateTime<Utc>,- pub data: Vec<u8>,- pub metadata: FrameMetadata,+ // Find the entry in our in-memory cache+ if let Some(entry) = self.entries.get(&(timestamp.into(), device_id.to_string())) {+ let mut hasher = Sha256::new();+ hasher.update(&frame_data);+ let checksum = format!("{:x}", hasher.finalize());++ if checksum != entry.frame.checksum {+ debug!("checksum mismatch for frame at {}:{}", timestamp, device_id);+ return Ok(None);+ }++ Ok(Some((+ frame_data,+ entry.frame.metadata.clone(),+ (timestamp.into(), device_id.to_string()),+ )))+ } else {+ Ok(None)+ }+ }++ fn get_frame_path(&self, timestamp: &DateTime<Utc>, device_id: &str) -> PathBuf {+ self.config.cache_dir.join(format!(+ "{}_{}.cache",+ timestamp.timestamp_micros(),+ device_id.replace(['/', '\\', ':'], "_")+ ))+ }}#[derive(Clone)]pub struct FrameCache {pub screenpipe_dir: PathBuf,- config: FrameCacheConfig,- video_index: Arc<RwLock<VideoIndex>>,- recent_frames: Arc<RwLock<LruCache<i64, PreviewFrame>>>,- preview_frames: Arc<RwLock<LruCache<i64, PreviewFrame>>>,+ pub disk_cache: Arc<RwLock<FrameDiskCache>>,db: Arc<DatabaseManager>,}impl FrameCache {pub async fn new(screenpipe_dir: PathBuf, db: Arc<DatabaseManager>) -> Result<Self> {- Self::with_config(screenpipe_dir, db, FrameCacheConfig::default()).await- }+ let cache_config = CacheConfig {+ cache_dir: cache_dir().unwrap().join("screenpipe").join("frames"),+ ..Default::default()+ };- pub async fn with_config(- screenpipe_dir: PathBuf,- db: Arc<DatabaseManager>,- config: FrameCacheConfig,- ) -> Result<Self> {- debug!("initializing frame cache");-- let video_index = Arc::new(RwLock::new(VideoIndex::new()));- let recent_frames = Arc::new(RwLock::new(LruCache::new(NonZeroUsize::new(300).unwrap())));- let preview_frames = Arc::new(RwLock::new(LruCache::new(NonZeroUsize::new(720).unwrap())));-- // Initial index build- {- let mut index = video_index.write().await;- index.refresh_index(&screenpipe_dir).await?;- }+ fs::create_dir_all(&cache_config.cache_dir).await?;++ let disk_cache = Arc::new(RwLock::new(FrameDiskCache::new(cache_config).await?));let cache = Self {screenpipe_dir: screenpipe_dir.clone(),- config: config.clone(),- video_index: video_index.clone(),- recent_frames: recent_frames.clone(),- preview_frames: preview_frames.clone(),- db: db.clone(),+ disk_cache,+ db,};- let cache_clone = cache.clone();-- tokio::spawn(async move {- let mut interval = tokio::time::interval(tokio::time::Duration::from_secs(30));- loop {- interval.tick().await;-- // Refresh index- {- let mut index = cache_clone.video_index.write().await;- if let Err(e) = index.refresh_index(&screenpipe_dir).await {- error!("failed to refresh index: {}", e);- }- }-- let now = Utc::now();-- // Preload high-res recent frames (last 5 minutes)- let hi_res_start = now - Duration::minutes(5);- if let Err(e) = cache_clone.preload_frames(&hi_res_start, &now, false).await {- error!("failed to preload high-res frames: {}", e);- }-- // Preload low-res frames (last hour)- let low_res_start = now - Duration::minutes(60);- if let Err(e) = cache_clone.preload_frames(&low_res_start, &now, true).await {- error!("failed to preload low-res frames: {}", e);- }-- debug!("index refresh and frame preload complete");- }- });-Ok(cache)}async fn extract_frames_batch(&self,- file_path: &str,start_time: DateTime<Utc>,end_time: DateTime<Utc>,- fps: f32,frame_tx: FrameChannel,- is_preview: bool,) -> Result<()> {- let ffmpeg = find_ffmpeg_path().ok_or_else(|| anyhow::anyhow!("ffmpeg not found"))?;+ let mut extraction_queue = HashMap::new();- let scale_filter = if is_preview {- "scale=640:-1"- } else {- "scale=1280:-1"- };+ debug!(+ "extracting frames for time range: {} to {}",+ start_time, end_time+ );- let duration = (end_time - start_time).num_seconds();-- let mut cmd = Command::new(ffmpeg);- cmd.args([- "-i",- file_path,- "-ss",- "0",- "-t",- &duration.to_string(),- "-vf",- &format!("{},fps={}", scale_filter, fps),- "-f",- "image2pipe",- "-vcodec",- "mjpeg",- "-q:v",- if is_preview { "8" } else { "3" },- "-",- ]);-- let mut child = cmd- .stdout(std::process::Stdio::piped())- .stderr(std::process::Stdio::piped())- .spawn()?;-- // Set 30s timeout for frame extraction- let extraction_timeout = tokio::time::sleep(tokio::time::Duration::from_secs(30));- tokio::pin!(extraction_timeout);-- let stdout = child- .stdout- .take()- .ok_or_else(|| anyhow::anyhow!("failed to get stdout"))?;-- let stderr = child- .stderr- .take()- .ok_or_else(|| anyhow::anyhow!("failed to get stderr"))?;-- // Handle stderr in background- let stderr_handle = tokio::spawn(Self::log_ffmpeg_output(stderr));-- let mut reader = BufReader::new(stdout);- let frame_extraction = async {- let mut frame_count = 0;- let mut frame_time = start_time;- let frame_interval = Duration::milliseconds((1000.0 / fps) as i64);-- let metadata = self- .db- .get_frame_metadata(file_path)- .await- .unwrap_or_default();+ // First, get all the video chunks and organize by timestamp+ let chunks = self.db.find_video_chunks(start_time, end_time).await?;- debug!("found {} metadata entries in {}", metadata.len(), file_path);+ debug!("found {} chunks", chunks.frames.len());- let mut magic = [0u8; 2];- let mut error_count = 0;- const MAX_ERRORS: u32 = 3;+ let frame_times = chunks+ .frames+ .iter()+ .map(|c| c.timestamp)+ .collect::<Vec<_>>();- while reader.read_exact(&mut magic).await.is_ok() {- if magic != [0xFF, 0xD8] {- continue;- }+ debug!(+ "π― requested time range: {} to {} ({} frames)",+ start_time,+ end_time,+ frame_times.len()+ );- let mut frame_data = vec![0xFF, 0xD8];- let mut buf = [0u8; 1];- let mut last_byte = 0u8;-- while reader.read_exact(&mut buf).await.is_ok() {- frame_data.push(buf[0]);- if last_byte == 0xFF && buf[0] == 0xD9 {- let frame_metadata = FrameMetadata {- app_name: metadata- .get(frame_count)- .map_or("".to_string(), |(_, app, _, _, _)| app.clone()),- window_name: metadata- .get(frame_count)- .map_or("".to_string(), |(_, _, win, _, _)| win.clone()),- ocr_text: metadata- .get(frame_count)- .map_or("".to_string(), |(_, _, _, ocr, _)| ocr.clone()),- transcription: metadata- .get(frame_count)- .map_or("".to_string(), |(_, _, _, _, trans)| trans.clone()),- file_path: file_path.to_string(),- };-- if let Err(e) = frame_tx- .send((frame_time, frame_data, frame_metadata))- .await- {- error_count += 1;- error!("failed to send frame: {}", e);-- if error_count >= MAX_ERRORS {- debug!("channel appears closed, stopping extraction");- return Ok::<(), anyhow::Error>(());- }- }+ // Process each timestamp+ for chunk in &chunks.frames {+ let mut timeseries_frame = TimeSeriesFrame {+ timestamp: chunk.timestamp,+ frame_data: Vec::new(),+ };- frame_count += 1;- frame_time = start_time + frame_interval * (frame_count as i32);- break;- }- last_byte = buf[0];+ // Check cache first for each device - acquire lock only when needed+ for device_data in &chunk.ocr_entries {+ let cache_key = format!("{}:{}", chunk.timestamp, device_data.device_name);++ // Acquire read lock only for cache lookup+ if let Some((frame_data, metadata, _)) = self+ .disk_cache+ .read()+ .await+ .get_frame_data(&cache_key)+ .await?+ {+ timeseries_frame.frame_data.push(DeviceFrame {+ device_id: device_data.device_name.clone(),+ image_data: frame_data,+ metadata,+ audio_entries: chunk+ .audio_entries+ .iter()+ .map(|a| AudioEntry {+ transcription: a.transcription.clone(),+ device_name: a.device_name.clone(),+ is_input: a.is_input,+ audio_file_path: a.audio_file_path.clone(),+ duration_secs: a.duration_secs,+ })+ .collect(),+ });+ } else {+ // Cache miss - queue for extraction+ extraction_queue+ .entry(device_data.video_file_path.clone())+ .or_insert_with(Vec::new)+ .push((chunk.clone(), device_data.clone()));}}- Ok(())- };-- tokio::select! {- _ = &mut extraction_timeout => {- // Kill the ffmpeg process- if let Err(e) = child.kill().await {- error!("failed to kill ffmpeg process: {}", e);- }- stderr_handle.abort();- return Err(anyhow::anyhow!("frame extraction timed out"));- }- result = frame_extraction => {- stderr_handle.abort();- drop(result);+ // If we have any frames for this timestamp, send them+ if !timeseries_frame.frame_data.is_empty() {+ frame_tx.send(timeseries_frame).await?;}}- let status = child.wait().await?;- if !status.success() {- return Err(anyhow::anyhow!("ffmpeg failed with status: {}", status));- }+ // Process extraction queue+ let ffmpeg = find_ffmpeg_path().ok_or_else(|| anyhow::anyhow!("ffmpeg not found"))?;- Ok(())- }- async fn log_ffmpeg_output(stderr: impl AsyncRead + Unpin) -> Result<()> {- let mut lines = BufReader::new(stderr).lines();- while let Some(line) = lines.next_line().await? {- debug!("ffmpeg: {}", line);+ // Process each task+ for (file_path, tasks) in extraction_queue {+ extract_frame(+ ffmpeg.clone(),+ file_path,+ tasks,+ frame_tx.clone(),+ self.disk_cache.clone(),+ )+ .await?;}+ debug!("extraction queue completed");+Ok(())}- async fn is_video_file_complete(&self, file_path: &str) -> bool {- 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();- if age.as_secs() < 60 {- return false;- }- }- }+ pub async fn get_frames(+ &self,+ timestamp: DateTime<Utc>,+ duration_minutes: i64,+ frame_tx: Sender<TimeSeriesFrame>,+ _descending: bool,+ ) -> Result<()> {+ let start = timestamp - Duration::minutes(duration_minutes / 2);+ let end = timestamp + Duration::minutes(duration_minutes / 2);- let ffmpeg_path = match find_ffmpeg_path() {- Some(path) => path,- None => {- error!("failed to find ffmpeg path");- return false;+ let (extract_tx, mut extract_rx) = channel(100);+ let done = Arc::new(AtomicBool::new(false));+ let done_clone = done.clone();++ let cache_clone = self.clone();+ let mut extract_handle = tokio::spawn(async move {+ debug!("starting frame extraction");+ let result = cache_clone+ .extract_frames_batch(start, end, extract_tx.clone())+ .await;+ // Explicitly drop the sender after extraction is done to finish the channel+ drop(extract_tx);+ done_clone.store(true, std::sync::atomic::Ordering::Release);+ debug!("frame extraction completed");+ result+ });++ // Create a select future that completes when either:+ // 1. We receive a frame from extract_rx+ // 2. The extract_handle completes+ loop {+ if done.load(std::sync::atomic::Ordering::Acquire) {+ break;}- };- 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)- );+ tokio::select! {+ frame = extract_rx.recv() => {+ match frame {+ Some(timeseries_frame) => {+ debug!("sending frame at {} to client", timeseries_frame.timestamp);+ frame_tx.send(timeseries_frame).await?;+ }+ None => break, // Channel closed, extraction complete+ }+ }+ result = &mut extract_handle => {+ result??; // Propagate any errors+ break;}- is_complete- }- Err(e) => {- debug!("failed to check file {}: {}", file_path, e);- false}}- }- async fn find_video_chunks(- &self,- start: DateTime<Utc>,- end: DateTime<Utc>,- ) -> Result<Vec<VideoChunk>> {- debug!("finding video chunks from {} to {}", start, end);- let index = self.video_index.read().await;-- let chunks: Vec<VideoChunk> = index- .find_files_in_range(start, end)- .iter()- .filter(|file| file.is_complete)- .map(|file| VideoChunk {- file_path: file.path.to_string_lossy().to_string(),- start_time: file.start_time,- end_time: file.end_time,- metadata: file.metadata.clone(),- })- .collect();+ Ok(())+ }+}- debug!(- "found {} chunks between {} and {}",- chunks.len(),- start,- end- );+async fn extract_frame(+ ffmpeg: PathBuf,+ video_file_path: String,+ tasks: Vec<(FrameData, OCREntry)>,+ frame_tx: FrameChannel,+ disk_cache: Arc<RwLock<FrameDiskCache>>,+) -> Result<()> {+ if !is_video_file_complete(&ffmpeg, &video_file_path).await? {+ debug!("skipping incomplete video file: {}", video_file_path);+ return Ok(());+ }- Ok(chunks)+ // Extract ALL frames as separate JPEGs+ let temp_dir = tempfile::tempdir()?;+ let output_pattern = temp_dir.path().join("frame%d.jpg");++ let mut cmd = Command::new(&ffmpeg);+ cmd.args([+ "-i",+ &video_file_path,+ "-c:v",+ "mjpeg",+ "-q:v",+ "3",+ "-vsync",+ "0",+ output_pattern.to_str().unwrap(),+ ]);++ debug!("running ffmpeg command: {:?}", cmd);++ let output = cmd.output().await?;+ if !output.status.success() {+ error!("ffmpeg error: {}", String::from_utf8_lossy(&output.stderr));+ return Ok(());}- async fn preload_frames(- &self,- start: &DateTime<Utc>,- end: &DateTime<Utc>,- is_preview: bool,- ) -> Result<()> {- debug!("preloading frames from {} to {}", start, end);+ // Read all frames+ let mut entries = tokio::fs::read_dir(temp_dir.path()).await?;+ while let Some(entry) = entries.next_entry().await? {+ let frame_data = tokio::fs::read(entry.path()).await?;- let (frame_tx, mut frame_rx) = channel(100);+ debug!(+ "extracted frame of size {} bytes from {}",+ frame_data.len(),+ video_file_path+ );- let chunks = self.find_video_chunks(*start, *end).await?;- debug!("found {} chunks to process", chunks.len());+ // Group frames by timestamp+ let mut frames_by_timestamp: HashMap<DateTime<Utc>, Vec<DeviceFrame>> = HashMap::new();- if chunks.is_empty() {- debug!("no video chunks found for the requested time range");- return Ok(());- }+ // Process all tasks for this video file+ for (chunk, device_data) in &tasks {+ let cache_key = format!("{}||{}", chunk.timestamp, device_data.device_name);- for chunk in chunks {- debug!("processing chunk: {}", chunk.file_path);-- if let Err(e) = self- .extract_frames_batch(- &chunk.file_path,- chunk.start_time,- chunk.end_time,- self.config.fps,- frame_tx.clone(),- is_preview,- )- .await+ // Cache the frame{- error!("failed to extract frames from {}: {}", chunk.file_path, e);+ let mut cache = disk_cache.write().await;+ cache+ .store_frame(+ &cache_key,+ &frame_data,+ device_data.clone(),+ &chunk+ .audio_entries+ .iter()+ .map(|a| AudioEntry {+ transcription: a.transcription.clone(),+ device_name: a.device_name.clone(),+ is_input: a.is_input,+ audio_file_path: a.audio_file_path.clone(),+ duration_secs: a.duration_secs,+ })+ .collect::<Vec<_>>(),+ )+ .await?;+ drop(cache);}+ debug!("cached frame for {}", device_data.device_name);++ // Group frames by timestamp+ frames_by_timestamp+ .entry(chunk.timestamp)+ .or_default()+ .push(DeviceFrame {+ device_id: device_data.device_name.clone(),+ image_data: frame_data.clone(),+ metadata: FrameMetadata {+ file_path: device_data.video_file_path.clone(),+ app_name: device_data.app_name.clone(),+ window_name: device_data.window_name.clone(),+ transcription: chunk+ .audio_entries+ .iter()+ .map(|a| a.transcription.clone())+ .collect::<Vec<_>>()+ .join(" "),+ ocr_text: device_data.text.clone(),+ },+ audio_entries: chunk+ .audio_entries+ .iter()+ .map(|a| AudioEntry {+ transcription: a.transcription.clone(),+ device_name: a.device_name.clone(),+ is_input: a.is_input,+ audio_file_path: a.audio_file_path.clone(),+ duration_secs: a.duration_secs,+ })+ .collect(),+ });}- while let Some((timestamp, frame_data, metadata)) = frame_rx.recv().await {- let frame = PreviewFrame {- timestamp,- data: Arc::new(frame_data),- metadata,- is_preview: false,- };-- let cache = if is_preview {- &self.preview_frames- } else {- &self.recent_frames- };-- cache.write().await.put(timestamp.timestamp(), frame);- }-- Ok(())- }-- pub async fn get_frames(- &self,- timestamp: DateTime<Utc>,- duration_minutes: i64,- frame_tx: Sender<FrameInfo>,- descending: bool,- ) -> Result<()> {- let start = timestamp - Duration::minutes(duration_minutes / 2);- let end = timestamp + Duration::minutes(duration_minutes / 2);-- let (extract_tx, mut extract_rx) = channel(100);-- let cache_clone = self.clone();- let extract_handle = tokio::spawn(async move {- cache_clone- .extract_frames_range(&start, &end, extract_tx, descending)- .await- });-- while let Some((timestamp, data, metadata)) = extract_rx.recv().await {+ // Send all frames for each timestamp+ for (timestamp, device_frames) in frames_by_timestamp {frame_tx- .send(FrameInfo {+ .send(TimeSeriesFrame {timestamp,- data,- metadata,+ frame_data: device_frames,}).await?;}- extract_handle.await??;- Ok(())+ debug!("sent frames for entire video file {}", video_file_path);}- pub async fn extract_frames_range(- &self,- start: &DateTime<Utc>,- end: &DateTime<Utc>,- frame_tx: FrameChannel,- descending: bool,- ) -> Result<()> {- let mut chunks = self.find_video_chunks(*start, *end).await?;+ debug!("extraction completed");- if descending {- chunks.sort_by(|a, b| b.start_time.cmp(&a.start_time));- } else {- chunks.sort_by(|a, b| a.start_time.cmp(&b.start_time));- }+ Ok(())+}- for chunk in chunks {- if !self.is_video_file_complete(&chunk.file_path).await {- continue;+async fn is_video_file_complete(ffmpeg_path: &PathBuf, file_path: &str) -> Result<bool> {+ 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();+ if age.as_secs() < 60 {+ return Ok(false);}+ }+ }- if let Err(e) = self- .extract_frames_batch(- &chunk.file_path,- chunk.start_time,- chunk.end_time,- self.config.fps,- frame_tx.clone(),- false,- )- .await- {- error!("failed to extract frames from {}: {}", chunk.file_path, e);+ 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)+ );}+ Ok(is_complete)+ }+ Err(e) => {+ debug!("failed to check file {}: {}", file_path, e);+ Ok(false)}-- Ok(())}}diff --git a/screenpipe-server/tests/video_cache_test.rs b/screenpipe-server/tests/video_cache_test.rsindex 2f2f90b4e..54d599a84 100644--- a/screenpipe-server/tests/video_cache_test.rs+++ b/screenpipe-server/tests/video_cache_test.rs@@ -1,16 +1,13 @@use anyhow::Result;use chrono::{Duration, Utc};use dirs::home_dir;+use screenpipe_server::{db::OCREntry, video_cache::AudioEntry};use std::sync::Arc;-use tempfile::TempDir;use tracing::{debug, error};-use screenpipe_server::{- video_cache::{FrameCache, FrameCacheConfig},- DatabaseManager,-};+use screenpipe_server::{video_cache::FrameCache, DatabaseManager};-async fn setup_test_env() -> Result<(FrameCache, TempDir, Arc<DatabaseManager>)> {+async fn setup_test_env() -> Result<(FrameCache, Arc<DatabaseManager>)> {// enabled tracing loggingtracing_subscriber::fmt().with_max_level(tracing::Level::DEBUG)@@ -21,16 +18,8 @@ async fn setup_test_env() -> Result<(FrameCache, TempDir, Arc<DatabaseManager>)>.join(".screenpipe").join("data");- // Create temporary directory for cache- let temp_dir = TempDir::new()?;-debug!("using real screenpipe data dir: {:?}", screenpipe_dir);- debug!("using temp cache dir: {:?}", temp_dir.path());- let config = FrameCacheConfig {- prefetch_size: Duration::seconds(120),- ..FrameCacheConfig::default()- };let db = Arc::new(DatabaseManager::new(home_dir()@@ -44,53 +33,13 @@ async fn setup_test_env() -> Result<(FrameCache, TempDir, Arc<DatabaseManager>)>.unwrap(),);- let cache = FrameCache::with_config(screenpipe_dir, db.clone(), config).await?;- Ok((cache, temp_dir, db))-}--#[tokio::test]-async fn test_high_speed_streaming() -> Result<()> {- let (cache, _temp_dir, _db) = setup_test_env().await?;-- let start_time = Utc::now() - Duration::minutes(5);- let mut frames = Vec::new();-- let (tx, mut rx) = tokio::sync::mpsc::channel(100);-- // First, request the frames- cache.get_frames(start_time, 1, tx, true).await?;-- // Then use try_recv in a loop with timeout to collect frames- let timeout = tokio::time::sleep(std::time::Duration::from_secs(5));- tokio::pin!(timeout);-- loop {- tokio::select! {- frame = rx.recv() => {- match frame {- Some(frame) => {- debug!("got frame at: {}", frame.timestamp);- frames.push(frame);- },- None => break, // Channel closed- }- }- _ = &mut timeout => {- debug!("timeout reached after 5s");- break;- }- }- }-- debug!("total frames retrieved: {}", frames.len());- assert!(frames.len() > 0, "Should retrieve at least one frame");-- Ok(())+ let cache = FrameCache::new(screenpipe_dir, db.clone()).await?;+ Ok((cache, db))}#[tokio::test]async fn test_frame_jpeg_integrity() -> Result<()> {- let (cache, _temp_dir, _db) = setup_test_env().await?;+ let (cache, _db) = setup_test_env().await?;// Get a frame from 5 minutes agolet target_time = Utc::now() - Duration::minutes(5);@@ -107,17 +56,20 @@ async fn test_frame_jpeg_integrity() -> Result<()> {debug!("checking frame at {}, size: {} bytes",target_time,- frame_data.data.len()+ frame_data.frame_data[0].image_data.len());// Check JPEG header (SOI marker)- let has_jpeg_header = frame_data.data.starts_with(&[0xFF, 0xD8]);+ let has_jpeg_header = frame_data.frame_data[0]+ .image_data+ .starts_with(&[0xFF, 0xD8]);// Check JPEG footer (EOI marker)- let has_jpeg_footer = frame_data.data.ends_with(&[0xFF, 0xD9]);+ let has_jpeg_footer = frame_data.frame_data[0].image_data.ends_with(&[0xFF, 0xD9]);// Basic size sanity check (typical JPEG frame should be between 10KB and 1MB)- let has_valid_size = frame_data.data.len() > 10_000 && frame_data.data.len() < 1_000_000;+ let has_valid_size = frame_data.frame_data[0].image_data.len() > 10_000+ && frame_data.frame_data[0].image_data.len() < 1_000_000;if has_jpeg_header && has_jpeg_footer && has_valid_size {debug!("frame passed JPEG validation");@@ -126,24 +78,27 @@ async fn test_frame_jpeg_integrity() -> Result<()> {"invalid JPEG frame: header={}, footer={}, size={}",has_jpeg_header,has_jpeg_footer,- frame_data.data.len()+ frame_data.frame_data[0].image_data.len());// Log first and last few bytes for debugging- if frame_data.data.len() >= 4 {+ if frame_data.frame_data[0].image_data.len() >= 4 {debug!("first 4 bytes: {:02X} {:02X} {:02X} {:02X}",- frame_data.data[0], frame_data.data[1], frame_data.data[2], frame_data.data[3]+ frame_data.frame_data[0].image_data[0],+ frame_data.frame_data[0].image_data[1],+ frame_data.frame_data[0].image_data[2],+ frame_data.frame_data[0].image_data[3]);}- if frame_data.data.len() >= 4 {- let len = frame_data.data.len();+ if frame_data.frame_data[0].image_data.len() >= 4 {+ let len = frame_data.frame_data[0].image_data.len();debug!("last 4 bytes: {:02X} {:02X} {:02X} {:02X}",- frame_data.data[len - 4],- frame_data.data[len - 3],- frame_data.data[len - 2],- frame_data.data[len - 1]+ frame_data.frame_data[0].image_data[len - 4],+ frame_data.frame_data[0].image_data[len - 3],+ frame_data.frame_data[0].image_data[len - 2],+ frame_data.frame_data[0].image_data[len - 1]);}}@@ -204,7 +159,7 @@ async fn measure_frame_retrieval(#[tokio::test]async fn test_frame_retrieval_at_different_times() -> Result<()> {- let (cache, _temp_dir, _db) = setup_test_env().await?;+ let (cache, _db) = setup_test_env().await?;// Give some time for initial cache setup and potential recordingtokio::time::sleep(std::time::Duration::from_secs(2)).await;@@ -274,7 +229,7 @@ async fn test_frame_retrieval_at_different_times() -> Result<()> {#[tokio::test]async fn test_extended_time_range_retrieval() -> Result<()> {- let (cache, _temp_dir, _db) = setup_test_env().await?;+ let (cache, _db) = setup_test_env().await?;// Test retrieving frames over longer durationslet test_durations = vec![@@ -324,7 +279,7 @@ async fn test_extended_time_range_retrieval() -> Result<()> {#[tokio::test]async fn test_frame_metadata_integrity() -> Result<()> {- let (cache, _temp_dir, _db) = setup_test_env().await?;+ let (cache, _db) = setup_test_env().await?;// Get frames from last 5 minutes with a 1-minute duration windowlet target_time = Utc::now() - Duration::minutes(5);@@ -333,7 +288,6 @@ async fn test_frame_metadata_integrity() -> Result<()> {// Request frames with a 1-minute durationcache.get_frames(target_time, 2, tx, false).await?;- let mut found_metadata = false;let timeout = tokio::time::sleep(std::time::Duration::from_secs(50));tokio::pin!(timeout);@@ -346,20 +300,9 @@ async fn test_frame_metadata_integrity() -> Result<()> {match frame {Some(frame) => {println!("Frame at: {}", frame.timestamp);- println!("- App: {}", frame.metadata.app_name);- println!("- Window: {}", frame.metadata.window_name);- println!("- Transcription: {}", frame.metadata.transcription);- println!("- OCR: {}", frame.metadata.ocr_text);+ println!("- data: {:?}", frame.frame_data);println!("----------------------------");- // Check that at least one field has content- if !frame.metadata.app_name.is_empty()- || !frame.metadata.window_name.is_empty()- || !frame.metadata.transcription.is_empty()- || !frame.metadata.ocr_text.is_empty() {- found_metadata = true;- break;- }},None => {println!("No more frames");@@ -373,9 +316,273 @@ async fn test_frame_metadata_integrity() -> Result<()> {}}}- assert!(- found_metadata,- "should find at least one frame with non-empty metadata"- );+ Ok(())+}++#[tokio::test]+async fn test_basic_frame_retrieval() -> Result<()> {+ let (cache, _db) = setup_test_env().await?;++ // Get frames from last minute+ let target_time = Utc::now() - Duration::minutes(4);+ let (tx, mut rx) = tokio::sync::mpsc::channel(100);++ println!("\nbasic frame retrieval test:");+ println!("-------------------------");+ println!("target time: {}", target_time);++ // Request frames with a 2-minute window (1 min before and after target)+ cache.get_frames(target_time, 2, tx, true).await?;++ let mut frame_count = 0;+ let timeout = tokio::time::sleep(std::time::Duration::from_secs(60));+ tokio::pin!(timeout);++ loop {+ tokio::select! {+ frame = rx.recv() => {+ match frame {+ Some(f) => {+ println!("received frame at time: {}", f.timestamp);+ frame_count += 1;+ }+ None => break,+ }+ }+ _ = &mut timeout => {+ println!("timeout waiting for frames!");+ break;+ }+ }+ }++ println!("total frames retrieved: {}", frame_count);+ if frame_count == 0 {+ println!("warning: no frames found - checking time ranges:");+ }++ Ok(())+}++#[tokio::test]+async fn test_frame_storage() -> Result<()> {+ let (cache, _db) = setup_test_env().await?;++ // Create test frame data+ let test_timestamp = Utc::now();+ let test_device_id = "test_device";+ let cache_key = format!("{}||{}", test_timestamp.to_rfc3339(), test_device_id);++ // Create sample JPEG data (minimal valid JPEG)+ let frame_data = vec![+ 0xFF, 0xD8, // SOI marker+ 0xFF, 0xE0, 0x00, 0x10, // APP0 segment+ 0x4A, 0x46, 0x49, 0x46, // "JFIF"+ 0x00, 0x01, 0x01, 0x00, // version, units+ 0x00, 0x01, 0x00, 0x01, // density+ 0x00, 0x00, // thumbnail+ 0xFF, 0xD9, // EOI marker+ ];++ // Create test OCR entry+ let ocr_entry = OCREntry {+ device_name: test_device_id.to_string(),+ video_file_path: "test_video.mp4".to_string(),+ app_name: "test_app".to_string(),+ window_name: "test_window".to_string(),+ text: "test ocr text".to_string(),+ };++ // Create test audio entries+ let audio_entries = vec![AudioEntry {+ transcription: "test transcription".to_string(),+ device_name: test_device_id.to_string(),+ is_input: true,+ audio_file_path: "test_audio.wav".to_string(),+ duration_secs: 1.0,+ }];++ // Get write access to disk cache+ let mut disk_cache = cache.disk_cache.write().await;++ debug!("storing frame");+ // Store the frame+ disk_cache+ .store_frame(&cache_key, &frame_data, ocr_entry, &audio_entries)+ .await?;++ debug!("saved frame");++ // Drop write lock+ drop(disk_cache);++ // Get read access to verify storage+ let disk_cache = cache.disk_cache.read().await;++ // Verify frame was stored correctly+ if let Some((stored_data, metadata, (stored_timestamp, stored_device))) =+ disk_cache.get_frame_data(&cache_key).await?+ {+ // Verify frame data+ assert_eq!(stored_data, frame_data, "Frame data mismatch");++ // Verify metadata+ assert_eq!(metadata.app_name, "test_app", "App name mismatch");+ assert_eq!(metadata.window_name, "test_window", "Window name mismatch");+ assert_eq!(metadata.ocr_text, "test ocr text", "OCR text mismatch");++ // Verify timestamp and device+ assert_eq!(stored_timestamp, test_timestamp, "Timestamp mismatch");+ assert_eq!(stored_device, test_device_id, "Device ID mismatch");++ println!("β frame storage test passed:");+ println!("- stored {} bytes of frame data", stored_data.len());+ println!("- metadata verified");+ println!("- timestamp and device ID verified");+ } else {+ panic!("Failed to retrieve stored frame");+ }++ Ok(())+}++#[tokio::test]+async fn test_frame_storage_edge_cases() -> Result<()> {+ let (cache, _db) = setup_test_env().await?;++ // Test cases with potentially problematic timestamps and device IDs+ let test_cases = vec![+ // Regular case (control)+ (Utc::now(), "monitor_1", "normal case"),+ // Timestamp edge cases+ (Utc::now(), "monitor||1", "device id with pipes"),+ (Utc::now(), "monitor 1", "device id with spaces"),+ (Utc::now(), "monitor/1", "device id with slash"),+ (Utc::now(), "monitor\\1", "device id with backslash"),+ // Special characters+ (Utc::now(), "monitor#1", "device id with hash"),+ (Utc::now(), "monitor:1", "device id with colon"),+ (Utc::now(), "monitor?1", "device id with question mark"),+ ];++ // Sample frame data (minimal valid JPEG)+ let frame_data = vec![+ 0xFF, 0xD8, // SOI marker+ 0xFF, 0xE0, 0x00, 0x10, // APP0 segment+ 0x4A, 0x46, 0x49, 0x46, // "JFIF"+ 0x00, 0x01, 0x01, 0x00, // version, units+ 0x00, 0x01, 0x00, 0x01, // density+ 0x00, 0x00, // thumbnail+ 0xFF, 0xD9, // EOI marker+ ];++ println!("\nTesting frame storage edge cases:");+ println!("--------------------------------");++ for (timestamp, device_id, test_desc) in test_cases {+ println!("\nTesting: {}", test_desc);+ println!("Timestamp: {}", timestamp);+ println!("Device ID: {}", device_id);++ let cache_key = format!("{}||{}", timestamp.to_rfc3339(), device_id);+ println!("Cache key: {}", cache_key);++ // Create test OCR entry+ let ocr_entry = OCREntry {+ device_name: device_id.to_string(),+ video_file_path: "test_video.mp4".to_string(),+ app_name: "test_app".to_string(),+ window_name: "test_window".to_string(),+ text: "test ocr text".to_string(),+ };++ // Create test audio entries+ let audio_entries = vec![AudioEntry {+ transcription: "test transcription".to_string(),+ device_name: device_id.to_string(),+ is_input: true,+ audio_file_path: "test_audio.wav".to_string(),+ duration_secs: 1.0,+ }];++ // Get write access to disk cache+ let mut disk_cache = cache.disk_cache.write().await;++ // Try to store the frame and capture the result+ match disk_cache+ .store_frame(&cache_key, &frame_data, ocr_entry, &audio_entries)+ .await+ {+ Ok(_) => {+ println!("β Successfully stored frame");+ // Try retrieve only if storage succeeded+ match disk_cache.get_frame_data(&cache_key).await {+ Ok(Some(_)) => println!("β Successfully retrieved frame"),+ Ok(None) => println!("β Frame not found after storage"),+ Err(e) => println!("β Error retrieving frame: {}", e),+ }+ }+ Err(e) => println!("β Failed to store frame: {}", e),+ }+ }++ Ok(())+}++#[tokio::test]+async fn test_frame_storage_with_rfc3339_variations() -> Result<()> {+ let (cache, _db) = setup_test_env().await?;++ // Test cases with different RFC3339 timestamp formats+ let test_cases = vec![+ // Standard format+ "2024-11-03T01:05:11.690182Z",+ // With space instead of T+ "2024-11-03 01:05:11.690182Z",+ // Without microseconds+ "2024-11-03T01:05:11Z",+ // With offset+ "2024-11-03T01:05:11+00:00",+ ];++ let frame_data = vec![0xFF, 0xD8, 0xFF, 0xD9]; // Minimal JPEG+ let device_id = "monitor_1";++ println!("\nTesting RFC3339 timestamp variations:");+ println!("-----------------------------------");++ for timestamp_str in test_cases {+ println!("\nTesting timestamp: {}", timestamp_str);++ let cache_key = format!("{}||{}", timestamp_str, device_id);+ println!("Cache key: {}", cache_key);++ let ocr_entry = OCREntry {+ device_name: device_id.to_string(),+ video_file_path: "test_video.mp4".to_string(),+ app_name: "test_app".to_string(),+ window_name: "test_window".to_string(),+ text: "test ocr text".to_string(),+ };++ let audio_entries = vec![AudioEntry {+ transcription: "test transcription".to_string(),+ device_name: device_id.to_string(),+ is_input: true,+ audio_file_path: "test_audio.wav".to_string(),+ duration_secs: 1.0,+ }];++ let mut disk_cache = cache.disk_cache.write().await;++ match disk_cache+ .store_frame(&cache_key, &frame_data, ocr_entry, &audio_entries)+ .await+ {+ Ok(_) => println!("β Successfully stored frame"),+ Err(e) => println!("β Failed to store frame: {}", e),+ }+ }+Ok(())}