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

fix: frame offset desync and audio duplication bugs

Louis Beaumontdf1ff5890d1c
diff --git a/Cargo.toml b/Cargo.toml
index 13d095b84..0cdd115b7 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -12,7 +12,7 @@ exclude = ["screenpipe-app-tauri/src-tauri"]
resolver = "2"
[workspace.package]
-version = "0.3.4"
+version = "0.3.5"
authors = ["louis030195 <[email protected]>"]
description = ""
repository = "https://github.com/mediar-ai/screenpipe"
diff --git a/content/changelogs/v2.0.130.md b/content/changelogs/v2.0.130.md
new file mode 100644
index 000000000..66d5f851f
--- /dev/null
+++ b/content/changelogs/v2.0.130.md
@@ -0,0 +1,9 @@
+## Bug Fixes
+- Fixed search results showing wrong images: OCR text now correctly matches video frames even under heavy load
+- Fixed timeline audio duplication: audio entries no longer repeat for each text region on screen
+
+## Improvements
+- FrameWriteTracker: New architecture ensures video frame offsets stay synchronized with database entries
+- Better frame dropping behavior: frames dropped from video queue are now properly skipped in database
+
+#### **Full Changelog:** [7060274d..HEAD](https://github.com/mediar-ai/screenpipe/compare/7060274d..HEAD)
diff --git a/screenpipe-app-tauri/public/CHANGELOG.md b/screenpipe-app-tauri/public/CHANGELOG.md
index d22fba687..66d5f851f 100644
--- a/screenpipe-app-tauri/public/CHANGELOG.md
+++ b/screenpipe-app-tauri/public/CHANGELOG.md
@@ -1,11 +1,9 @@
-## New Features
-- Added `--use-all-monitors` flag for dynamic monitor detection: automatically records all connected monitors and detects when monitors are connected/disconnected in real-time
+## Bug Fixes
+- Fixed search results showing wrong images: OCR text now correctly matches video frames even under heavy load
+- Fixed timeline audio duplication: audio entries no longer repeat for each text region on screen
## Improvements
-- VisionManager: New architecture for per-monitor recording with automatic monitor lifecycle management
-- MonitorWatcher: Polls for monitor changes every 2 seconds for seamless multi-monitor support
-
-## Bug Fixes
-- Fixed timeline z-index for audio transcript panel
+- FrameWriteTracker: New architecture ensures video frame offsets stay synchronized with database entries
+- Better frame dropping behavior: frames dropped from video queue are now properly skipped in database
-#### **Full Changelog:** [a5b8dacf..HEAD](https://github.com/mediar-ai/screenpipe/compare/a5b8dacf..HEAD)
+#### **Full Changelog:** [7060274d..HEAD](https://github.com/mediar-ai/screenpipe/compare/7060274d..HEAD)
diff --git a/screenpipe-app-tauri/src-tauri/Cargo.toml b/screenpipe-app-tauri/src-tauri/Cargo.toml
index 4842936b4..b4cfda028 100644
--- a/screenpipe-app-tauri/src-tauri/Cargo.toml
+++ b/screenpipe-app-tauri/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "screenpipe-app"
-version = "2.0.129"
+version = "2.0.130"
description = "24/7 memory for your desktop. 100% local."
authors = ["you"]
license = ""
diff --git a/screenpipe-server/src/core.rs b/screenpipe-server/src/core.rs
index ff6367423..82f453d7e 100644
--- a/screenpipe-server/src/core.rs
+++ b/screenpipe-server/src/core.rs
@@ -229,15 +229,34 @@ pub async fn record_video(
frames_processed += 1;
debug!(
- "record_video: Processing frame {} with {} window results ({}ms since last frame)",
+ "record_video: Processing frame {} (frame_number={}) with {} window results ({}ms since last frame)",
frames_processed,
+ frame.frame_number,
frame.window_ocr_results.len(),
time_since_last_frame.as_millis()
);
- // Get the current video frame offset for this capture cycle
- // All window results from this capture share the same video frame
- let video_frame_offset = db.get_next_frame_offset(&device_name).await.unwrap_or(0);
+ // Check if this frame was actually written to video
+ // If not, skip DB insertion to prevent offset mismatch
+ let frame_write_info = video_capture.frame_write_tracker.get_offset(frame.frame_number);
+ let video_frame_offset = match frame_write_info {
+ Some(info) => info.offset as i64,
+ None => {
+ // Frame wasn't written to video (likely dropped from video queue)
+ // Wait a bit and retry - the video encoder might not have processed it yet
+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;
+ match video_capture.frame_write_tracker.get_offset(frame.frame_number) {
+ Some(info) => info.offset as i64,
+ None => {
+ debug!(
+ "Skipping frame {} - not found in video write tracker (was dropped)",
+ frame.frame_number
+ );
+ continue;
+ }
+ }
+ }
+ };
for window_result in &frame.window_ocr_results {
let insert_frame_start = std::time::Instant::now();
diff --git a/screenpipe-server/src/lib.rs b/screenpipe-server/src/lib.rs
index 26246ab49..9d5eb8c0f 100644
--- a/screenpipe-server/src/lib.rs
+++ b/screenpipe-server/src/lib.rs
@@ -28,5 +28,5 @@ pub use server::HealthCheckResponse;
pub use server::PaginatedResponse;
pub use server::SCServer;
pub use server::{api_list_monitors, MonitorInfo};
-pub use video::VideoCapture;
+pub use video::{FrameWriteInfo, FrameWriteTracker, VideoCapture};
pub mod embedding;
diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rs
index de3012c7a..cdb34e8dd 100644
--- a/screenpipe-server/src/server.rs
+++ b/screenpipe-server/src/server.rs
@@ -3244,46 +3244,63 @@ async fn serve_file(path: &str) -> Result<Response, (StatusCode, JsonResponse<Va
}
fn create_time_series_frame(chunk: FrameData) -> TimeSeriesFrame {
+ // Pre-compute audio entries once (avoid duplicating for each OCR entry)
+ let audio_entries: Vec<AudioEntry> = 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,
+ audio_chunk_id: a.audio_chunk_id,
+ speaker_id: a.speaker_id,
+ speaker_name: a.speaker_name.clone(),
+ })
+ .collect();
+
+ // Pre-compute transcription text once
+ let transcription_text: String = chunk
+ .audio_entries
+ .iter()
+ .map(|a| a.transcription.clone())
+ .collect::<Vec<_>>()
+ .join(" ");
+
+ // Create DeviceFrames from OCR entries
+ let mut device_frames: Vec<DeviceFrame> = chunk
+ .ocr_entries
+ .into_iter()
+ // Filter out screenpipe frames at display time
+ .filter(|device_data| !device_data.app_name.to_lowercase().contains("screenpipe"))
+ .map(|device_data| DeviceFrame {
+ device_id: device_data.device_name,
+ frame_id: chunk.frame_id,
+ image_data: vec![], // Empty since we don't need image data
+ metadata: FrameMetadata {
+ file_path: device_data.video_file_path,
+ app_name: device_data.app_name,
+ window_name: device_data.window_name,
+ transcription: transcription_text.clone(),
+ ocr_text: device_data.text,
+ browser_url: device_data.browser_url,
+ },
+ // FIX: Don't duplicate audio entries for each OCR entry
+ // Audio will be added only to the first DeviceFrame
+ audio_entries: vec![],
+ })
+ .collect();
+
+ // Only put audio entries in the first DeviceFrame to avoid duplication
+ // This ensures audio is displayed once per frame, not once per OCR text region
+ if let Some(first_frame) = device_frames.first_mut() {
+ first_frame.audio_entries = audio_entries;
+ }
+
TimeSeriesFrame {
timestamp: chunk.timestamp,
- frame_data: chunk
- .ocr_entries
- .into_iter()
- // Filter out screenpipe frames at display time
- .filter(|device_data| !device_data.app_name.to_lowercase().contains("screenpipe"))
- .map(|device_data| DeviceFrame {
- device_id: device_data.device_name,
- frame_id: chunk.frame_id,
- image_data: vec![], // Empty since we don't need image data
- metadata: FrameMetadata {
- file_path: device_data.video_file_path,
- app_name: device_data.app_name,
- window_name: device_data.window_name,
- transcription: chunk
- .audio_entries
- .iter()
- .map(|a| a.transcription.clone())
- .collect::<Vec<_>>()
- .join(" "),
- ocr_text: device_data.text,
- browser_url: device_data.browser_url,
- },
- 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,
- audio_chunk_id: a.audio_chunk_id,
- speaker_id: a.speaker_id,
- speaker_name: a.speaker_name.clone(),
- })
- .collect(),
- })
- .collect(),
+ frame_data: device_frames,
error: None,
}
}
@@ -3851,4 +3868,116 @@ mod tests {
"Different queries should produce different cache keys"
);
}
+
+ // ===========================================================================
+ // AUDIO DUPLICATION TESTS
+ // ===========================================================================
+
+ fn create_test_frame_data(num_ocr_entries: usize, num_audio_entries: usize) -> FrameData {
+ use screenpipe_db::{AudioEntry as DbAudioEntry, OCREntry};
+
+ let ocr_entries: Vec<OCREntry> = (0..num_ocr_entries)
+ .map(|i| OCREntry {
+ device_name: format!("monitor_{}", i % 2),
+ video_file_path: format!("/path/to/video_{}.mp4", i % 2),
+ app_name: format!("App{}", i),
+ window_name: format!("Window{}", i),
+ text: format!("OCR text block {}", i),
+ browser_url: None,
+ })
+ .collect();
+
+ let audio_entries: Vec<DbAudioEntry> = (0..num_audio_entries)
+ .map(|i| DbAudioEntry {
+ transcription: format!("Audio transcription {}", i),
+ device_name: format!("microphone_{}", i),
+ is_input: true,
+ audio_file_path: format!("/path/to/audio_{}.mp4", i),
+ duration_secs: 3.0,
+ audio_chunk_id: i as i64,
+ speaker_id: None,
+ speaker_name: None,
+ })
+ .collect();
+
+ FrameData {
+ frame_id: 12345,
+ timestamp: chrono::Utc::now(),
+ offset_index: 0,
+ ocr_entries,
+ audio_entries,
+ }
+ }
+
+ /// TEST: Demonstrate and verify the audio duplication bug is fixed
+ /// With the fix, audio should appear only once, not duplicated per OCR entry
+ #[test]
+ fn test_audio_not_duplicated_per_ocr_entry() {
+ // Create a frame with 10 OCR entries and 1 audio entry
+ let frame_data = create_test_frame_data(10, 1);
+
+ let result = create_time_series_frame(frame_data);
+
+ // Count total audio entries across all DeviceFrames
+ let total_audio_entries: usize = result
+ .frame_data
+ .iter()
+ .map(|df| df.audio_entries.len())
+ .sum();
+
+ let num_device_frames = result.frame_data.len();
+
+ println!("OCR entries: 10, Audio entries: 1");
+ println!("DeviceFrames created: {}", num_device_frames);
+ println!("Total audio entries in result: {}", total_audio_entries);
+
+ // After fix: Should have exactly 1 audio entry total, not 10
+ assert_eq!(num_device_frames, 10, "Should have 10 DeviceFrames");
+ assert_eq!(
+ total_audio_entries, 1,
+ "Audio should appear exactly once, not duplicated per OCR entry"
+ );
+ }
+
+ /// TEST: Multiple audio entries should still work correctly
+ #[test]
+ fn test_multiple_audio_entries_not_duplicated() {
+ // 5 OCR entries, 3 audio entries
+ let frame_data = create_test_frame_data(5, 3);
+
+ let result = create_time_series_frame(frame_data);
+
+ let total_audio_entries: usize = result
+ .frame_data
+ .iter()
+ .map(|df| df.audio_entries.len())
+ .sum();
+
+ println!("OCR entries: 5, Audio entries: 3");
+ println!("DeviceFrames: {}", result.frame_data.len());
+ println!("Total audio entries: {}", total_audio_entries);
+
+ // Should have exactly 3 audio entries, not 15 (5 * 3)
+ assert_eq!(
+ total_audio_entries, 3,
+ "Should have exactly 3 audio entries, not duplicated"
+ );
+ }
+
+ /// TEST: Empty audio entries should work
+ #[test]
+ fn test_no_audio_entries_handled() {
+ let frame_data = create_test_frame_data(5, 0);
+
+ let result = create_time_series_frame(frame_data);
+
+ let total_audio_entries: usize = result
+ .frame_data
+ .iter()
+ .map(|df| df.audio_entries.len())
+ .sum();
+
+ assert_eq!(total_audio_entries, 0, "Should have no audio entries");
+ assert_eq!(result.frame_data.len(), 5, "Should have 5 DeviceFrames");
+ }
}
diff --git a/screenpipe-server/src/video.rs b/screenpipe-server/src/video.rs
index 9a2429129..313e913e2 100644
--- a/screenpipe-server/src/video.rs
+++ b/screenpipe-server/src/video.rs
@@ -50,14 +50,14 @@ impl FrameWriteTracker {
/// Record that a frame was written to video at the given offset.
pub fn record_write(&self, frame_number: u64, offset: u64, video_path: String) {
- self.writes.insert(
- frame_number,
- FrameWriteInfo { offset, video_path },
- );
debug!(
"FrameWriteTracker: recorded frame {} at offset {} in {}",
frame_number, offset, video_path
);
+ self.writes.insert(
+ frame_number,
+ FrameWriteInfo { offset, video_path },
+ );
}
/// Get the video offset for a frame. Returns None if frame wasn't written to video.
@@ -309,6 +309,7 @@ impl VideoCapture {
});
let video_frame_queue_clone = video_frame_queue.clone();
+ let frame_write_tracker_clone = frame_write_tracker.clone();
let output_path = output_path.to_string();
let video_thread = tokio::spawn(async move {
@@ -323,6 +324,7 @@ impl VideoCapture {
new_chunk_callback_clone,
monitor_id,
video_chunk_duration,
+ &frame_write_tracker_clone,
)
.await
{
@@ -372,6 +374,7 @@ impl VideoCapture {
VideoCapture {
video_frame_queue,
ocr_frame_queue,
+ frame_write_tracker,
capture_thread_handle: capture_thread,
queue_thread_handle: queue_thread,
video_thread_handle: video_thread,
@@ -495,6 +498,7 @@ async fn save_frames_as_video(
new_chunk_callback: Arc<dyn Fn(&str) + Send + Sync>,
monitor_id: u32,
video_chunk_duration: Duration,
+ frame_write_tracker: &Arc<FrameWriteTracker>,
) -> Result<(), anyhow::Error> {
info!(
"Starting save_frames_as_video function for monitor {}",
@@ -504,6 +508,7 @@ async fn save_frames_as_video(
let mut frame_count = 0;
let mut current_ffmpeg: Option<Child> = None;
let mut current_stdin: Option<ChildStdin> = None;
+ let mut current_video_path: Option<String> = None;
// Track health metrics
let start_time = std::time::Instant::now();
@@ -529,6 +534,12 @@ async fn save_frames_as_video(
let buffer = encode_frame(&first_frame);
debug!("Got first frame for new chunk for monitor {}", monitor_id);
+ // Clean up old tracker entries to prevent memory bloat
+ // Keep entries from the last ~1000 frames (enough buffer for DB to catch up)
+ if first_frame.frame_number > 1000 {
+ frame_write_tracker.cleanup_before(first_frame.frame_number - 1000);
+ }
+
let output_file = create_output_file(output_path, monitor_id);
info!(
"Starting new video chunk: {} for monitor {}",
@@ -548,6 +559,14 @@ async fn save_frames_as_video(
);
continue;
}
+
+ // Record first frame write in tracker (offset 0)
+ frame_write_tracker.record_write(
+ first_frame.frame_number,
+ 0, // First frame is at offset 0
+ output_file.clone(),
+ );
+
frame_count += 1;
frames_total += 1;
@@ -557,6 +576,7 @@ async fn save_frames_as_video(
current_ffmpeg = Some(child);
current_stdin = Some(stdin);
+ current_video_path = Some(output_file.clone());
info!(
"New FFmpeg process started for file: {} (monitor {})",
output_file, monitor_id
@@ -591,14 +611,18 @@ async fn save_frames_as_video(
"Processing frames for monitor {}, current count: {}/{}",
monitor_id, frame_count, frames_per_video
);
- process_frames(
- frame_queue,
- &mut current_stdin,
- &mut frame_count,
- frames_per_video,
- fps,
- )
- .await;
+ if let Some(ref video_path) = current_video_path {
+ process_frames(
+ frame_queue,
+ &mut current_stdin,
+ &mut frame_count,
+ frames_per_video,
+ fps,
+ frame_write_tracker,
+ video_path,
+ )
+ .await;
+ }
// Update total frame count
frames_total = frames_total.max(frame_count);
@@ -657,18 +681,33 @@ async fn process_frames(
frame_count: &mut usize,
frames_per_video: usize,
fps: f64,
+ frame_write_tracker: &Arc<FrameWriteTracker>,
+ video_path: &str,
) {
let write_timeout = Duration::from_secs_f64(1.0 / fps);
while *frame_count < frames_per_video {
if let Some(frame) = frame_queue.pop() {
+ let frame_number = frame.frame_number;
let buffer = encode_frame(&frame);
if let Some(stdin) = current_stdin.as_mut() {
if let Err(e) = write_frame_with_retry(stdin, &buffer).await {
error!("Failed to write frame to ffmpeg after max retries: {}", e);
break;
}
+
+ // Record this frame write in the tracker
+ // frame_count is 0-indexed offset within this video chunk
+ frame_write_tracker.record_write(
+ frame_number,
+ *frame_count as u64,
+ video_path.to_string(),
+ );
+
*frame_count += 1;
- debug!("Wrote frame {} to FFmpeg", frame_count);
+ debug!(
+ "Wrote frame {} (frame_number={}) to FFmpeg at offset {}",
+ frame_count, frame_number, *frame_count - 1
+ );
flush_ffmpeg_input(stdin, *frame_count, fps).await;
}