Skip to content

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

feat: apps and windows

Louis Beaumontde18beca7d17
diff --git a/screenpipe-app-tauri/components/recording-settings.tsx b/screenpipe-app-tauri/components/recording-settings.tsx
index 3eca31315..165fd03f3 100644
--- a/screenpipe-app-tauri/components/recording-settings.tsx
+++ b/screenpipe-app-tauri/components/recording-settings.tsx
@@ -227,6 +227,7 @@ export function RecordingSettings({
useChineseMirror: localSettings.useChineseMirror,
languages: localSettings.languages,
enableBeta: localSettings.enableBeta,
+ enableFrameCache: localSettings.enableFrameCache,
};
console.log("Settings to update:", settingsToUpdate);
await updateSettings(settingsToUpdate);
diff --git a/screenpipe-server/examples/timeline_ui/index.html b/screenpipe-server/examples/timeline_ui/index.html
index 8cc063485..501086f77 100644
--- a/screenpipe-server/examples/timeline_ui/index.html
+++ b/screenpipe-server/examples/timeline_ui/index.html
@@ -192,6 +192,42 @@
);
background-size: 10% 100%;
}
+
+ /* Add new styles for app and window info */
+ .metadata {
+ font-family: 'Press Start 2P', monospace;
+ font-size: 8px;
+ color: #0f0;
+ text-shadow: 0 0 8px rgba(0,255,0,0.3);
+ margin: 8px 0;
+ }
+ .metadata span {
+ margin: 0 8px;
+ }
+
+ #timeline::after {
+ content: '← scroll to navigate →';
+ position: absolute;
+ bottom: -24px;
+ left: 50%;
+ transform: translateX(-50%);
+ font-size: 8px;
+ color: #666;
+ white-space: nowrap;
+ }
+
+ /* Add hover effect to indicate scrollable */
+ #timeline:hover {
+ border-color: #0f0;
+ box-shadow: 0 0 16px rgba(0,255,0,0.2), inset 0 0 8px rgba(0,255,0,0.1);
+ }
+
+ /* Add these styles */
+ html, body {
+ overscroll-behavior: none; /* Disable the bounce/rubber-band effect */
+ height: 100%;
+ overflow: hidden; /* Prevent default scrolling */
+ }
</style>
<link href="https://fonts.googleapis.com/css2?family=Press+Start+2P&display=swap" rel="stylesheet">
</head>
@@ -202,39 +238,78 @@
</div>
<div class="timeline-timestamps" id="timestamps"></div>
<img id="frame" />
+ <div class="metadata">
+ <span id="timestamp-display"></span>
+ <span id="app-name-display"></span>
+ <span id="window-name-display"></span>
+ </div>
<div id="info"></div>
<div id="error"></div>
<script>
let currentTime = new Date();
+ let endTime = new Date();
+ let startTime = new Date(endTime - 1000 * 60 * 15); // last 15 minutes
let frames = []; // Store all frames
const timelineWidth = document.getElementById('timeline').offsetWidth;
+ // Add debounce utility
+ let scrollTimeout = null;
+
function updateTimelineCursor() {
const cursor = document.getElementById('cursor');
const timeRange = endTime - startTime;
const position = (currentTime - startTime) / timeRange;
- cursor.style.left = `${position * 100}%`;
+
+ const boundedPosition = Math.max(0, Math.min(1, position));
+ cursor.style.left = `${boundedPosition * 100}%`;
// Update highlight position
const highlight = document.querySelector('.timeline-highlight');
- highlight.style.left = `${position * 100}%`;
+ highlight.style.left = `${boundedPosition * 100}%`;
+
+ console.log('cursor position:', boundedPosition); // Debug log
}
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;
- });
+ if (!frames.length) {
+ console.log('No frames available yet');
+ return;
+ }
- 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();
+ try {
+ // Find the closest frame
+ const frame = frames.reduce((prev, curr) => {
+ const prevDiff = Math.abs(new Date(prev.timestamp) - timestamp);
+ const currDiff = Math.abs(new Date(curr.timestamp) - timestamp);
+ return currDiff < prevDiff ? curr : prev;
+ });
+
+ console.log('Displaying frame:', {
+ timestamp: frame.timestamp,
+ app_name: frame.app_name,
+ window_name: frame.window_name
+ });
+
+ if (!frame.frame) {
+ throw new Error('Frame data is missing');
+ }
+
+ const frameElement = document.getElementById('frame');
+ frameElement.style.display = 'block';
+ frameElement.src = `data:image/jpeg;base64,${frame.frame}`;
+
+ // Updated IDs to match the HTML
+ document.getElementById('timestamp-display').textContent = `time: ${new Date(frame.timestamp).toLocaleTimeString()}`;
+ document.getElementById('app-name-display').textContent = `app: ${frame.app_name || 'n/a'}`;
+ document.getElementById('window-name-display').textContent = `window: ${frame.window_name || 'n/a'}`;
+
+ currentTime = new Date(frame.timestamp);
+ updateTimelineCursor();
+ } catch (e) {
+ console.error('Error displaying frame:', e);
+ document.getElementById('error').textContent = `Error displaying frame: ${e.message}`;
+ }
}
function connectToStream(startTime, endTime) {
@@ -248,7 +323,6 @@
window.eventSource = new EventSource(url.toString());
-
window.eventSource.onopen = () => {
console.log('SSE connection opened');
document.getElementById('error').textContent = '';
@@ -257,14 +331,39 @@
window.eventSource.onmessage = (event) => {
try {
const data = JSON.parse(event.data);
- console.log('frame event:', data.frame.length);
-
- if (data === 'keep-alive-text' || !data.frame) return;
+
+ // Skip keep-alive messages
+ if (data === 'keep-alive-text') return;
+
+ // Add debug logging
+ console.log('Received frame data:', {
+ timestamp: data.timestamp,
+ app_name: data.app_name,
+ window_name: data.window_name,
+ hasFrame: !!data.frame
+ });
+
+ // Validate frame data
+ if (!data || !data.frame || !data.timestamp) {
+ console.warn('Invalid frame data received:', data);
+ return;
+ }
+ // Clean the frame data before storing
+ data.frame = data.frame.trim();
+
+ console.log('Received frame for timestamp:', data.timestamp);
frames.push(data);
- displayFrameAtTime(new Date(data.timestamp));
+
+ if (window.pendingTimestamp) {
+ displayFrameAtTime(window.pendingTimestamp);
+ window.pendingTimestamp = null;
+ } else if (frames.length === 1) { // If this is our first frame
+ displayFrameAtTime(currentTime);
+ }
} catch (e) {
- console.error('Failed to parse frame data:', e);
+ console.error('Failed to parse frame data:', e, '\nRaw data:', event.data);
+ document.getElementById('error').textContent = `Error parsing frame: ${e.message}`;
}
};
@@ -294,6 +393,22 @@
}
}
+ function navigateTimeRange(direction) {
+ const timeWindow = endTime - startTime;
+
+ if (direction === 'past') {
+ endTime = new Date(startTime);
+ startTime = new Date(startTime - timeWindow);
+ } else if (direction === 'future') {
+ startTime = new Date(endTime);
+ endTime = new Date(endTime + timeWindow);
+ }
+
+ frames = []; // Clear existing frames
+ connectToStream(startTime, endTime);
+ updateTimelineMarkers();
+ }
+
// Modified timeline interaction
const timeline = document.getElementById('timeline');
timeline.addEventListener('click', (e) => {
@@ -314,12 +429,64 @@
} else if (e.key === 'ArrowRight') {
currentTime = new Date(currentTime.getTime() + step);
displayFrameAtTime(currentTime);
+ } else if (e.key === 'PageUp') {
+ navigateTimeRange('past');
+ } else if (e.key === 'PageDown') {
+ navigateTimeRange('future');
}
});
+ // Replace the wheel event listener with this improved version:
+ document.addEventListener('wheel', (e) => {
+ e.preventDefault(); // Prevent default scroll
+
+ // Clear any pending scroll timeout
+ if (scrollTimeout) {
+ clearTimeout(scrollTimeout);
+ }
+
+ // Calculate time step (make it smaller for finer control)
+ const timeStep = 1000; // 1 second per scroll tick
+
+ // Update current time based on scroll direction
+ if (e.deltaY > 0) {
+ currentTime = new Date(currentTime.getTime() + timeStep);
+ } else {
+ currentTime = new Date(currentTime.getTime() - timeStep);
+ }
+
+ // Keep currentTime within bounds
+ currentTime = new Date(Math.max(
+ startTime.getTime(),
+ Math.min(endTime.getTime(), currentTime.getTime())
+ ));
+
+ // Add debug logging
+ console.log('scroll: updating time to:', currentTime.toISOString());
+
+ // Debounce the frame display update
+ scrollTimeout = setTimeout(() => {
+ displayFrameAtTime(currentTime);
+ updateTimelineCursor(); // Make sure cursor updates even if frame isn't ready
+ }, 16); // ~60fps throttle
+
+ // Update cursor position immediately for smooth visual feedback
+ updateTimelineCursor();
+ }, { passive: false });
+
+ // Optional: Add touch support for mobile
+ document.addEventListener('touchmove', (e) => {
+ e.preventDefault();
+
+ const touch = e.touches[0];
+ if (touch.clientY > e.target.clientY) {
+ navigateTimeRange('future');
+ } else {
+ navigateTimeRange('past');
+ }
+ }, { passive: false });
+
// Initial connection
- const endTime = new Date();
- const startTime = new Date(endTime - 1000 * 60 * 3); // last 3 minutes
connectToStream(startTime, endTime);
updateTimelineMarkers();
</script>
diff --git a/screenpipe-server/src/db.rs b/screenpipe-server/src/db.rs
index fd6b6c9c2..1e3115e41 100644
--- a/screenpipe-server/src/db.rs
+++ b/screenpipe-server/src/db.rs
@@ -822,78 +822,6 @@ impl DatabaseManager {
Ok((latest_frame.map(|f| f.0), latest_audio.map(|a| a.0)))
}
- // Modify the insert_chunked_text method to handle both OCR and audio transcriptions
- pub async fn insert_chunked_text(
- &self,
- id: i64,
- text: &str,
- timestamp: DateTime<Utc>,
- engine: &str,
- chunking_engine: &str,
- source: ContentSource,
- ) -> Result<(), sqlx::Error> {
- let mut tx = self.pool.begin().await?;
-
- // Insert or get the text_id
- let text_id: i64 = sqlx::query_scalar(
- "INSERT INTO chunked_text_index (text) VALUES (?1) ON CONFLICT(text) DO UPDATE SET text=text RETURNING text_id",
- )
- .bind(text)
- .fetch_one(&mut *tx)
- .await?;
-
- // Insert the entry into chunked_text_entries
- let query = match source {
- ContentSource::Audio => "INSERT INTO chunked_text_entries (text_id, audio_chunk_id, timestamp, engine, chunking_engine, source) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
- ContentSource::Screen => "INSERT INTO chunked_text_entries (text_id, frame_id, timestamp, engine, chunking_engine, source) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
- };
-
- sqlx::query(query)
- .bind(text_id)
- .bind(id)
- .bind(timestamp)
- .bind(engine)
- .bind(chunking_engine)
- .bind(source.to_string())
- .execute(&mut *tx)
- .await?;
-
- tx.commit().await?;
- Ok(())
- }
-
- pub async fn search_chunked_text(
- &self,
- query: &str,
- start_time: Option<DateTime<Utc>>,
- end_time: Option<DateTime<Utc>>,
- ) -> Result<Vec<(i64, DateTime<Utc>)>, sqlx::Error> {
- let sql = r#"
- SELECT
- chunked_text_entries.frame_id,
- chunked_text_entries.timestamp
- FROM
- chunked_text_index
- JOIN
- chunked_text_entries ON chunked_text_index.text_id = chunked_text_entries.text_id
- WHERE
- chunked_text_index.text LIKE '%' || ?1 || '%' COLLATE NOCASE
- AND (?2 IS NULL OR chunked_text_entries.timestamp >= ?2)
- AND (?3 IS NULL OR chunked_text_entries.timestamp <= ?3)
- ORDER BY
- chunked_text_entries.timestamp DESC
- "#;
-
- let results = sqlx::query_as::<_, (i64, DateTime<Utc>)>(sql)
- .bind(query)
- .bind(start_time)
- .bind(end_time)
- .fetch_all(&self.pool)
- .await?;
-
- Ok(results)
- }
-
pub async fn get_chunked_data_since_last_request(
&self,
memory_source: &str,
@@ -1222,47 +1150,24 @@ impl DatabaseManager {
))
}
- pub async fn get_video_chunks_in_range(
+ pub async fn get_frame_metadata(
&self,
- start_time: DateTime<Utc>,
- end_time: DateTime<Utc>,
- ) -> Result<Vec<VideoChunk>, sqlx::Error> {
- let rows = sqlx::query(
+ file_path: &str,
+ ) -> Result<Vec<(String, String)>, SqlxError> {
+ debug!("getting frame metadata for file: {}", file_path);
+ sqlx::query_as::<_, (String, String)>(
r#"
- SELECT
- vc.file_path,
- f.timestamp as start_time,
- COALESCE(
- LEAD(f.timestamp) OVER (ORDER BY f.timestamp),
- datetime('now')
- ) as end_time,
- ot.app_name,
- ot.window_name
- FROM frames f
- JOIN video_chunks vc ON f.video_chunk_id = vc.id
- LEFT JOIN ocr_text ot ON f.id = ot.frame_id
- WHERE f.timestamp <= ? AND f.timestamp >= ?
- GROUP BY f.id
- ORDER BY f.timestamp ASC
+ SELECT ocr_text.app_name, ocr_text.window_name
+ FROM video_chunks
+ JOIN frames ON frames.video_chunk_id = video_chunks.id
+ JOIN ocr_text ON frames.id = ocr_text.frame_id
+ WHERE video_chunks.file_path = ?1
+ ORDER BY frames.offset_index ASC
"#,
)
- .bind(end_time)
- .bind(start_time)
+ .bind(file_path)
.fetch_all(&self.pool)
- .await?;
-
- let chunks = rows
- .iter()
- .map(|row| VideoChunk {
- file_path: row.get("file_path"),
- start_time: row.get("start_time"),
- end_time: row.get("end_time"),
- app_name: row.get("app_name"),
- window_name: row.get("window_name"),
- })
- .collect();
-
- Ok(chunks)
+ .await
}
}
@@ -1359,18 +1264,3 @@ impl FriendWearableDatabase for DatabaseManager {
.map_err(|e| Box::new(e) as Box<dyn StdError + Send + Sync>)
}
}
-
-#[derive(Debug)]
-pub struct VideoChunk {
- pub file_path: String,
- pub start_time: DateTime<Utc>,
- pub end_time: DateTime<Utc>,
- pub app_name: Option<String>,
- pub window_name: Option<String>,
-}
-
-impl VideoChunk {
- pub fn contains_time(&self, time: DateTime<Utc>) -> bool {
- time >= self.start_time && time <= self.end_time
- }
-}
diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rs
index 355d96fb6..b03607cd6 100644
--- a/screenpipe-server/src/server.rs
+++ b/screenpipe-server/src/server.rs
@@ -755,7 +755,7 @@ impl Server {
Some(Arc::new(
FrameCache::with_config(
self.screenpipe_dir.clone().join("data"),
- None,
+ self.db.clone(),
FrameCacheConfig {
prefetch_size: chrono::Duration::seconds(60),
cleanup_interval: chrono::Duration::minutes(360),
@@ -1237,13 +1237,13 @@ async fn stream_frames_handler(
});
let stream = async_stream::stream! {
- while let Some((timestamp, frame_data)) = frame_rx.recv().await {
+ while let Some((timestamp, frame_data, file_path, app_name, window_name)) = frame_rx.recv().await {
let response = StreamFramesResponse {
frame: BASE64_STANDARD.encode(&frame_data),
timestamp,
- file_path: "".to_string(),
- app_name: None,
- window_name: None,
+ file_path,
+ app_name: Some(app_name),
+ window_name: Some(window_name),
};
if let Ok(json) = serde_json::to_string(&response) {
@@ -1259,33 +1259,6 @@ async fn stream_frames_handler(
)
}
-#[derive(Serialize)]
-pub struct ProgressInfo {
- message: String,
- percent: f32,
- total_chunks: usize,
- processed_chunks: usize,
- current_timestamp: DateTime<Utc>,
-}
-
-impl ProgressInfo {
- pub fn new(
- message: String,
- percent: f32,
- total_chunks: usize,
- processed_chunks: usize,
- current_timestamp: DateTime<Utc>,
- ) -> Self {
- Self {
- message,
- percent,
- total_chunks,
- processed_chunks,
- current_timestamp,
- }
- }
-}
-
/*
Curl commands for reference:
diff --git a/screenpipe-server/src/video_cache.rs b/screenpipe-server/src/video_cache.rs
index 7e889b14f..2a3f0f9b3 100644
--- a/screenpipe-server/src/video_cache.rs
+++ b/screenpipe-server/src/video_cache.rs
@@ -1,15 +1,11 @@
use anyhow::Result;
use chrono::{DateTime, Duration, Utc};
-use dirs::cache_dir;
use std::path::PathBuf;
use std::sync::Arc;
-use tokio::fs;
-use tokio::io::AsyncReadExt;
use tokio::process::Command;
use tokio::sync::mpsc::{channel, Sender};
use tracing::{debug, error, info};
-use crate::server::ProgressInfo;
use glob::glob;
use screenpipe_core::find_ffmpeg_path;
use std::time::SystemTime;
@@ -17,22 +13,26 @@ use tokio::io::AsyncBufReadExt;
use tokio::io::BufReader;
// Add these new imports at the top
+use crate::DatabaseManager;
use lru::LruCache;
use std::num::NonZeroUsize;
+use tokio::io::AsyncReadExt;
use tokio::sync::oneshot;
+type FrameChannel = Sender<(DateTime<Utc>, Vec<u8>, String, String, String)>;
// Add these new types after the existing imports
#[derive(Debug, Clone)]
struct CachedFrame {
timestamp: DateTime<Utc>,
data: Arc<Vec<u8>>,
- last_accessed: DateTime<Utc>,
+ file_path: String,
+ app_name: String,
+ window_name: String,
}
enum CacheMsg {
GetFrame(i64, oneshot::Sender<Option<CachedFrame>>), // timestamp as key
InsertFrame(i64, CachedFrame),
- Clear,
}
struct FrameCacheManager {
@@ -55,9 +55,6 @@ impl FrameCacheManager {
CacheMsg::InsertFrame(timestamp, frame) => {
self.frames.put(timestamp, frame);
}
- CacheMsg::Clear => {
- self.frames.clear();
- }
}
}
}
@@ -82,9 +79,9 @@ impl Default for FrameCacheConfig {
#[derive(Clone)]
pub struct FrameCache {
pub screenpipe_dir: PathBuf,
- cache_dir: PathBuf,
config: FrameCacheConfig,
cache_manager_tx: Sender<CacheMsg>,
+ db: Arc<DatabaseManager>,
}
#[derive(Debug)]
@@ -94,6 +91,15 @@ struct VideoChunk {
end_time: DateTime<Utc>,
}
+// Add a new struct for frame metadata
+#[derive(Debug, Clone)]
+pub struct FrameInfo {
+ pub timestamp: DateTime<Utc>,
+ pub data: Vec<u8>,
+ pub app_name: String,
+ pub window_name: String,
+}
+
/*
this file should properly:
@@ -170,22 +176,16 @@ rules:
*/
impl FrameCache {
- 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 new(screenpipe_dir: PathBuf, db: Arc<DatabaseManager>) -> Result<Self> {
+ Self::with_config(screenpipe_dir, db, FrameCacheConfig::default()).await
}
pub async fn with_config(
screenpipe_dir: PathBuf,
- cache_dir_: Option<PathBuf>,
+ db: Arc<DatabaseManager>,
config: FrameCacheConfig,
) -> Result<Self> {
info!("initializing frame cache");
- let cache_dir = match cache_dir_ {
- Some(dir) => dir,
- None => cache_dir().unwrap().join("screenpipe"),
- };
- fs::create_dir_all(&cache_dir).await?;
-
// Add chunk cache manager channel
let (cache_manager_tx, mut cache_manager_rx) = channel::<CacheMsg>(100);
@@ -199,9 +199,9 @@ impl FrameCache {
let cache = Self {
screenpipe_dir,
- cache_dir: cache_dir.clone(),
config,
cache_manager_tx,
+ db: db.clone(),
};
// Start background scanner task
@@ -225,7 +225,7 @@ impl FrameCache {
Ok(cache)
}
- pub async fn get_frame(&self, target_time: DateTime<Utc>) -> Option<Vec<u8>> {
+ pub async fn get_frame(&self, target_time: DateTime<Utc>) -> Option<FrameInfo> {
let timestamp = target_time.timestamp();
// Try cache first
@@ -237,7 +237,12 @@ impl FrameCache {
{
if let Ok(Some(frame)) = rx.await {
debug!("cache hit for frame at {}", target_time);
- return Some(frame.data.as_ref().clone());
+ return Some(FrameInfo {
+ timestamp: frame.timestamp,
+ data: frame.data.as_ref().clone(),
+ app_name: frame.app_name,
+ window_name: frame.window_name,
+ });
}
}
@@ -245,7 +250,7 @@ impl FrameCache {
debug!("cache miss for frame at {}", target_time);
let prefetch_end = target_time + self.config.prefetch_size;
- let (_, mut rx) = tokio::sync::mpsc::channel::<(DateTime<Utc>, Vec<u8>)>(100);
+ let (_, mut rx): (FrameChannel, _) = tokio::sync::mpsc::channel(100);
// Spawn prefetch task
let cache = self.clone();
@@ -256,12 +261,15 @@ impl FrameCache {
});
// Wait for the specific frame we need
- while let Some((frame_time, frame_data)) = rx.recv().await {
+ while let Some((frame_time, frame_data, file_path, app_name, window_name)) = rx.recv().await
+ {
// Cache the frame
let frame = CachedFrame {
timestamp: frame_time,
data: Arc::new(frame_data.clone()),
- last_accessed: Utc::now(),
+ file_path: file_path.clone(),
+ app_name: app_name.clone(),
+ window_name: window_name.clone(),
};
let _ = self
@@ -271,7 +279,12 @@ impl FrameCache {
// Return if this is the frame we wanted
if (frame_time - target_time).num_milliseconds().abs() < 1000 {
- return Some(frame_data);
+ return Some(FrameInfo {
+ timestamp: frame_time,
+ data: frame_data,
+ app_name,
+ window_name,
+ });
}
}
@@ -279,11 +292,12 @@ impl FrameCache {
}
pub async fn extract_frames_batch(
+ &self,
file_path: &str,
start_time: DateTime<Utc>,
end_time: DateTime<Utc>,
fps: f32,
- frame_tx: Sender<(DateTime<Utc>, Vec<u8>)>,
+ frame_tx: FrameChannel,
) -> Result<()> {
let ffmpeg = find_ffmpeg_path().ok_or_else(|| anyhow::anyhow!("ffmpeg not found"))?;
@@ -336,40 +350,52 @@ impl FrameCache {
let mut frame_time = start_time;
let frame_interval = Duration::milliseconds((1000.0 / fps) as i64);
- 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;
+ // Get metadata from database for the file chunk
+ let metadata = self
+ .db
+ .get_frame_metadata(&file_path)
+ .await
+ .unwrap_or_default();
+
+ info!("found {} metadata entries in {}", metadata.len(), file_path);
+ // Read JPEG magic bytes
+ let mut magic = [0u8; 2];
+ while reader.read_exact(&mut magic).await.is_ok() {
+ if magic != [0xFF, 0xD8] {
+ continue; // Not a JPEG start marker, keep searching
}
- // Read until JPEG end marker
+ // Read until we find 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;
+ 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 {
+ if let Err(e) = frame_tx
+ .send((
+ frame_time,
+ frame_data,
+ file_path.to_string(),
+ metadata
+ .get(frame_count)
+ .map_or("".to_string(), |(app, _)| app.clone()),
+ metadata
+ .get(frame_count)
+ .map_or("".to_string(), |(_, win)| win.clone()),
+ ))
+ .await
+ {
+ error!("failed to send frame: {}", e);
+ break;
}
- Err(_) => break,
- }
- }
- // 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);
+ frame_count += 1;
+ frame_time = start_time + frame_interval * (frame_count as i32);
break;
}
- frame_count += 1;
- frame_time = start_time + frame_interval * frame_count;
+ last_byte = buf[0];
}
}
@@ -432,7 +458,7 @@ impl FrameCache {
&self,
start: &DateTime<Utc>,
end: &DateTime<Utc>,
- frame_tx: tokio::sync::mpsc::Sender<(DateTime<Utc>, Vec<u8>)>,
+ frame_tx: FrameChannel,
) -> Result<()> {
let chunks = self
.find_video_chunks(&self.screenpipe_dir, *start, *end)
@@ -443,14 +469,15 @@ impl FrameCache {
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
+ 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);
}
@@ -513,7 +540,7 @@ impl FrameCache {
debug!("preloading frames from {} to {}", start, end);
// Create channels for internal use
- let (frame_tx, mut frame_rx) = tokio::sync::mpsc::channel::<(DateTime<Utc>, Vec<u8>)>(100);
+ let (frame_tx, mut frame_rx) = tokio::sync::mpsc::channel(100);
// Process chunks and stream frames
let chunks = self
@@ -533,32 +560,45 @@ impl FrameCache {
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
+ 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);
}
}
// Handle received frames if needed (e.g., caching)
- while let Some((timestamp, frame_data)) = frame_rx.recv().await {
- self.insert_frame(timestamp, frame_data).await;
+ while let Some((timestamp, frame_data, file_path, app_name, window_name)) =
+ frame_rx.recv().await
+ {
+ self.insert_frame(timestamp, frame_data, file_path, app_name, window_name)
+ .await;
}
Ok(())
}
- async fn insert_frame(&self, timestamp: DateTime<Utc>, frame_data: Vec<u8>) {
+ async fn insert_frame(
+ &self,
+ timestamp: DateTime<Utc>,
+ frame_data: Vec<u8>,
+ file_path: String,
+ app_name: String,
+ window_name: String,
+ ) {
let frame = CachedFrame {
timestamp,
data: Arc::new(frame_data),
- last_accessed: Utc::now(),
+ file_path,
+ app_name,
+ window_name,
};
let _ = self
@@ -566,84 +606,4 @@ impl FrameCache {
.send(CacheMsg::InsertFrame(timestamp.timestamp(), frame))
.await;
}
-
- pub async fn preload_frames_with_progress(
- &self,
- start: &DateTime<Utc>,
- end: &DateTime<Utc>,
- progress_tx: tokio::sync::mpsc::Sender<ProgressInfo>,
- frame_tx: tokio::sync::mpsc::Sender<(DateTime<Utc>, Vec<u8>)>,
- ) -> Result<()> {
- debug!("preloading frames from {} to {}", start, end);
-
- let chunks = self
- .find_video_chunks(&self.screenpipe_dir, *start, *end)
- .await?;
- let total_chunks = chunks.len();
-
- debug!("found {} chunks to process", total_chunks);
-
- if chunks.is_empty() {
- let _ = progress_tx
- .send(ProgressInfo::new(
- "no video chunks found".to_string(),
- 100.0,
- 0,
- 0,
- *start,
- ))
- .await;
- return Ok(());
- }
-
- for (i, chunk) in chunks.into_iter().enumerate() {
- debug!(
- "processing chunk {}/{}: {}",
- i + 1,
- total_chunks,
- chunk.file_path
- );
-
- // Send progress update
- let _ = progress_tx
- .send(ProgressInfo::new(
- format!("processing chunk {}/{}", i + 1, total_chunks),
- (i as f32 / total_chunks as f32) * 100.0,
- total_chunks,
- i,
- chunk.start_time,
- ))
- .await;
-
- if !self.is_video_file_complete(&chunk.file_path).await {
- continue;
- }
-
- // Pass the frame_tx channel to extract_frames_batch
- if let Err(e) = Self::extract_frames_batch(
- &chunk.file_path,
- chunk.start_time,
- chunk.end_time,
- self.config.fps,
- frame_tx.clone(),
- )
- .await
- {
- error!("failed to extract frames from {}: {}", chunk.file_path, e);
- }
- }
-
- // Send completion progress
- let _ = progress_tx
- .send(ProgressInfo::new(
- "completed frame extraction".to_string(),
- 100.0,
- total_chunks,
- total_chunks,
- *end,
- ))
- .await;
-
- Ok(())
- }
}
diff --git a/screenpipe-server/tests/tags_test.rs b/screenpipe-server/tests/tags_test.rs
index d829efcf0..632f000c1 100644
--- a/screenpipe-server/tests/tags_test.rs
+++ b/screenpipe-server/tests/tags_test.rs
@@ -357,7 +357,10 @@ async fn test_search_by_multiple_tags() {
async fn insert_test_data(db: &Arc<DatabaseManager>) {
// Insert test video chunk
- let _video_chunk_id = db.insert_video_chunk("test_video_file.mp4", "test_device").await.unwrap();
+ let _video_chunk_id = db
+ .insert_video_chunk("test_video_file.mp4", "test_device")
+ .await
+ .unwrap();
// Insert test frame
let frame_id = db.insert_frame("test_device", None).await.unwrap();
@@ -388,16 +391,4 @@ async fn insert_test_data(db: &Arc<DatabaseManager>) {
)
.await
.unwrap();
-
- // Insert test FTS data
- db.insert_chunked_text(
- frame_id,
- "Test FTS text",
- Utc::now(),
- "tesseract",
- "local_simple",
- ContentSource::Screen,
- )
- .await
- .unwrap();
-}
\ No newline at end of file
+}