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
feat: add ability to select a monitor
Louis Beaumont3b186fbb12c9
diff --git a/screenpipe-audio/src/core.rs b/screenpipe-audio/src/core.rsindex bc65efb62..ca618dc0a 100644--- a/screenpipe-audio/src/core.rs+++ b/screenpipe-audio/src/core.rs@@ -154,16 +154,6 @@ async fn run_ffmpeg(.stdout(Stdio::piped()).stderr(Stdio::piped());- // ! tmp hack shouldnt be needed- // Explicitly set the library paths for the FFmpeg command- // if let Ok(ld_library_path) = std::env::var("LD_LIBRARY_PATH") {- // command.env("LD_LIBRARY_PATH", ld_library_path);- // }- // #[cfg(target_os = "macos")]- // if let Ok(dyld_library_path) = std::env::var("DYLD_LIBRARY_PATH") {- // command.env("DYLD_LIBRARY_PATH", dyld_library_path);- // }-debug!("FFmpeg command: {:?}", command);let mut ffmpeg: tokio::process::Child =diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rsindex f8e4921e1..475a0cb43 100644--- a/screenpipe-server/src/bin/screenpipe-server.rs+++ b/screenpipe-server/src/bin/screenpipe-server.rs@@ -17,7 +17,7 @@ use log::{debug, error, info, LevelFilter};use screenpipe_audio::{default_input_device, list_audio_devices, parse_audio_device, DeviceControl,};-use screenpipe_vision::OcrEngine;+use screenpipe_vision::{monitor::{get_monitor_by_id, list_monitors}, OcrEngine};use std::io::Write;use screenpipe_core::find_ffmpeg_path;@@ -125,6 +125,13 @@ struct Cli {/// UID key for sending data to friend wearable (if not provided, data won't be sent)#[arg(long)]friend_wearable_uid: Option<String>,++ #[arg(long)]+ list_monitors: bool,++ /// Monitor ID to use+ #[arg(long)]+ monitor_id: Option<u32>,}fn get_base_dir(custom_path: Option<String>) -> anyhow::Result<PathBuf> {@@ -208,6 +215,14 @@ async fn main() -> anyhow::Result<()> {}return Ok(());}+ let all_monitors = list_monitors().await;+ if cli.list_monitors {+ println!("Available monitors:");+ for (_, monitor) in all_monitors.iter().enumerate() {+ println!(" {}. {:?}", monitor.id(), monitor);+ }+ return Ok(());+ }let mut audio_devices = Vec::new();@@ -314,6 +329,13 @@ async fn main() -> anyhow::Result<()> {let friend_wearable_uid = cli.friend_wearable_uid.clone();let warning_ocr_engine_clone = cli.ocr_engine.clone();+ let monitor_id = cli.monitor_id.unwrap_or(all_monitors.first().unwrap().id());++ // try to use the monitor selected, if not available throw an error+ get_monitor_by_id(monitor_id).await.unwrap_or_else(|| {+ eprintln!("{}", format!("Monitor with id {} not found. Try 'screenpipe --list-monitors'", monitor_id).red());+ std::process::exit(1);+ });// Function to start or restart the recording tasklet _start_recording = tokio::spawn(async move {@@ -352,6 +374,7 @@ async fn main() -> anyhow::Result<()> {cli.cloud_audio_on,ocr_engine,friend_wearable_uid_clone, // Use the cloned version+ monitor_id).await;diff --git a/screenpipe-server/src/bin/screenpipe-video.rs b/screenpipe-server/src/bin/screenpipe-video.rsindex b472ae9eb..15220f12a 100644--- a/screenpipe-server/src/bin/screenpipe-video.rs+++ b/screenpipe-server/src/bin/screenpipe-video.rs@@ -5,6 +5,7 @@ use image::GenericImageView;use log::info;use screenpipe_server::core::DataOutputWrapper;use screenpipe_server::VideoCapture;+use screenpipe_vision::monitor::list_monitors;use screenpipe_vision::OcrEngine;use serde_json::{json, Value};use std::fs::{File, OpenOptions};@@ -50,6 +51,7 @@ async fn main() {std::fs::create_dir_all("data").unwrap_or_default();info!("Created data directory {}", output_path);let fps = 10.0;+ let monitor_id = list_monitors().await.first().unwrap().id();let new_chunk_callback = {move |file_path: &str| {@@ -63,6 +65,7 @@ async fn main() {new_chunk_callback,save_text_files,Arc::new(OcrEngine::Tesseract),+ monitor_id,); // Pass the cloud_ocr flaglet (_tx, rx): (Sender<()>, Receiver<()>) = channel(32);let rx = Arc::new(Mutex::new(rx));@@ -115,4 +118,4 @@ async fn main() {println!("Video capture completed. Output saved to: {}", output_path);println!("JSON data saved to: {}", json_output_path);-}\ No newline at end of file+}diff --git a/screenpipe-server/src/core.rs b/screenpipe-server/src/core.rsindex 2a87e5cf2..beb3b6cb2 100644--- a/screenpipe-server/src/core.rs+++ b/screenpipe-server/src/core.rs@@ -55,6 +55,7 @@ pub async fn start_continuous_recording(cloud_audio: bool,ocr_engine: Arc<OcrEngine>,friend_wearable_uid: Option<String>,+ monitor_id: u32,) -> Result<()> {info!("Recording now");@@ -87,6 +88,7 @@ pub async fn start_continuous_recording(save_text_files,ocr_engine,friend_wearable_uid_video,+ monitor_id,).await});@@ -127,6 +129,7 @@ async fn record_video(save_text_files: bool,ocr_engine: Arc<OcrEngine>,_friend_wearable_uid: Option<String>, // Add underscore+ monitor_id: u32,) -> Result<()> {debug!("record_video: Starting");let db_chunk_callback = Arc::clone(&db);@@ -148,6 +151,7 @@ async fn record_video(new_chunk_callback,save_text_files,Arc::clone(&ocr_engine),+ monitor_id,);while is_running.load(Ordering::SeqCst) {@@ -365,4 +369,4 @@ async fn process_audio_result(),}Ok(())-}\ No newline at end of file+}diff --git a/screenpipe-server/src/video.rs b/screenpipe-server/src/video.rsindex 37f94fc39..16f947e9c 100644--- a/screenpipe-server/src/video.rs+++ b/screenpipe-server/src/video.rs@@ -2,7 +2,6 @@ use chrono::Utc;use image::ImageFormat::{self};use log::{debug, error, info, warn};use screenpipe_core::find_ffmpeg_path;-use screenpipe_vision::core::get_monitor;use screenpipe_vision::{continuous_capture, CaptureResult, OcrEngine};use std::collections::VecDeque;use std::path::PathBuf;@@ -31,6 +30,7 @@ impl VideoCapture {new_chunk_callback: impl Fn(&str) + Send + Sync + 'static,save_text_files: bool,ocr_engine: Arc<OcrEngine>,+ monitor_id: u32,) -> Self {info!("Starting new video capture");let frame_queue = Arc::new(Mutex::new(VecDeque::new()));@@ -49,7 +49,7 @@ impl VideoCapture {Duration::from_secs_f64(1.0 / fps),save_text_files,ocr_engine,- get_monitor().await,+ monitor_id,).await;});@@ -240,9 +240,12 @@ async fn save_frames_as_video(frame_count += 1;debug!("Wrote frame {} to FFmpeg", frame_count);- // Flush every second- if frame_count % fps as usize == 0 {- debug!("Flushing FFmpeg input");+ // Calculate frames per flush based on fps+ let frames_per_flush = (fps.max(0.1) * 1.0).ceil() as usize;++ // Flush every calculated number of frames+ if frame_count % frames_per_flush == 0 {+ debug!("Flushing FFmpeg input after {} frames", frames_per_flush);if let Err(e) = stdin.flush().await {error!("Failed to flush FFmpeg input: {}", e);}diff --git a/screenpipe-vision/src/bin/screenpipe-vision.rs b/screenpipe-vision/src/bin/screenpipe-vision.rsindex a745ffd17..096276c9a 100644--- a/screenpipe-vision/src/bin/screenpipe-vision.rs+++ b/screenpipe-vision/src/bin/screenpipe-vision.rs@@ -1,5 +1,5 @@use clap::Parser;-use screenpipe_vision::{continuous_capture, core::get_monitor, OcrEngine};+use screenpipe_vision::{continuous_capture, monitor::get_default_monitor, OcrEngine};use std::{sync::Arc, time::Duration};use tokio::sync::mpsc::channel;@@ -23,13 +23,16 @@ async fn main() {let save_text_files = cli.save_text_files;+ let monitor = get_default_monitor().await;+ let id = monitor.id();+let capture_thread = tokio::spawn(async move {continuous_capture(result_tx,Duration::from_secs(1),save_text_files,Arc::new(OcrEngine::Tesseract),- get_monitor().await,+ id,).await});diff --git a/screenpipe-vision/src/core.rs b/screenpipe-vision/src/core.rsindex be66304ab..211f8d5af 100644--- a/screenpipe-vision/src/core.rs+++ b/screenpipe-vision/src/core.rs@@ -8,10 +8,10 @@ use std::{time::{Duration, Instant},};use tokio::sync::mpsc::Sender;-use xcap::{Monitor, Window};#[cfg(target_os = "macos")]use crate::apple::perform_ocr_apple;+use crate::monitor::{get_focused_window, get_monitor_by_id};#[cfg(target_os = "windows")]use crate::utils::perform_ocr_windows;use crate::utils::OcrEngine;@@ -20,11 +20,6 @@ use crate::utils::{};use rusty_tesseract::{Data, DataOutput};use screenpipe_integrations::unstructured_ocr::perform_ocr_cloud;-pub enum ControlMessage {- Pause,- Resume,- Stop,-}pub struct DataOutputWrapper {pub data_output: rusty_tesseract::tesseract::output_data::DataOutput,@@ -98,26 +93,37 @@ pub struct OcrTaskData {pub result_tx: Sender<CaptureResult>,}-pub async fn get_monitor() -> Monitor {- Monitor::all().unwrap().first().unwrap().clone()-}-pub async fn continuous_capture(result_tx: Sender<CaptureResult>,interval: Duration,save_text_files_flag: bool,ocr_engine: Arc<OcrEngine>,- monitor: Monitor,+ monitor_id: u32,) {- debug!("continuous_capture: Starting using monitor: {:?}", monitor);+ debug!(+ "continuous_capture: Starting using monitor: {:?}",+ monitor_id+ );let ocr_task_running = Arc::new(AtomicBool::new(false));let mut frame_counter: u64 = 0;let mut previous_image: Option<Arc<DynamicImage>> = None;let mut max_average: Option<MaxAverageFrame> = None;let mut max_avg_value = 0.0;+ let monitor = get_monitor_by_id(monitor_id).await.unwrap();+ let arc_monitor = Arc::new(monitor.clone());+loop {- let (image, image_hash, _capture_duration) = capture_screenshot(&monitor).await;+ let arc_monitor_one = arc_monitor.clone();++ let app_name = Arc::new(+ get_focused_window(arc_monitor_one)+ .await+ .map(|window| window.app_name().to_lowercase().to_string())+ .unwrap_or_else(|| String::from("unknown")),+ );+ let arc_monitor = arc_monitor.clone();+ let (image, image_hash, _capture_duration) = capture_screenshot(arc_monitor).await;let current_average = compare_with_previous_image(&previous_image,&image,@@ -172,9 +178,9 @@ pub async fn continuous_capture(ocr_task_running.store(true, Ordering::SeqCst);let ocr_engine_clone = ocr_engine.clone();++ let app_name_clone = app_name.clone();tokio::spawn(async move {- let w = Window::all().unwrap().first().unwrap().clone();- let app_name = w.app_name();if let Err(e) = process_ocr_task(ocr_task_data.image,ocr_task_data.frame_number,@@ -182,7 +188,7 @@ pub async fn continuous_capture(ocr_task_data.result_tx,save_text_files_flag,ocr_engine_clone,- app_name.to_string().to_lowercase(),+ app_name_clone.to_string(),).await{diff --git a/screenpipe-vision/src/lib.rs b/screenpipe-vision/src/lib.rsindex 5341cb288..5a7cfe165 100644--- a/screenpipe-vision/src/lib.rs+++ b/screenpipe-vision/src/lib.rs@@ -1,8 +1,9 @@#[cfg(target_os = "macos")]pub mod apple;pub mod core;+pub mod monitor;pub mod utils;#[cfg(target_os = "macos")]pub use apple::perform_ocr_apple;-pub use core::{continuous_capture, process_ocr_task, CaptureResult, ControlMessage};+pub use core::{continuous_capture, process_ocr_task, CaptureResult};pub use utils::{perform_ocr_tesseract, OcrEngine};diff --git a/screenpipe-vision/src/monitor.rs b/screenpipe-vision/src/monitor.rsnew file mode 100644index 000000000..7bbbda839--- /dev/null+++ b/screenpipe-vision/src/monitor.rs@@ -0,0 +1,56 @@+use std::sync::Arc;++use xcap::{Monitor, Window};++// ! logic here: we pick the biggest window and assume it's the one showing the most text that will be grabbed by OCR+// TODO: longer term we should define a data strcture for OCR on specific monitor, window, etc.+pub async fn get_focused_window(monitor: Arc<Monitor>) -> Option<Window> {+ let windows = Window::all().unwrap_or_default();++ let focused_window = windows+ .into_iter()+ .filter(|w| w.current_monitor().id() == monitor.id())+ .filter(|w| !is_system_window(w))+ .filter(|w| is_significant_size(w, &monitor))+ .max_by_key(|w| w.width() * w.height());++ focused_window+}++fn is_system_window(window: &Window) -> bool {+ // TODO linux windows+ let system_apps = ["Dock", "Window Server", "Control Centre", "WindowManager"];+ system_apps.contains(&window.app_name())+}++fn is_significant_size(window: &Window, monitor: &Monitor) -> bool {+ let window_area = window.width() * window.height();+ let monitor_area = monitor.width() * monitor.height();+ let ratio = window_area as f64 / monitor_area as f64;++ // Consider windows that take up between 20% and 100% of the screen+ ratio > 0.2 && ratio <= 1.0+}++pub async fn get_windows_for_monitor(monitor: Monitor) -> Vec<Window> {+ Window::all()+ .unwrap_or_default()+ .into_iter()+ .filter(|w| w.current_monitor().id() == monitor.id())+ .collect()+}++pub async fn list_monitors() -> Vec<Monitor> {+ let monitors = Monitor::all().unwrap();+ return monitors.iter().map(|m| m.clone()).collect();+}++pub async fn get_default_monitor() -> Monitor {+ let monitors = list_monitors().await;+ return monitors.first().unwrap().clone();+}++pub async fn get_monitor_by_id(id: u32) -> Option<Monitor> {+ let monitors = list_monitors().await;+ monitors.iter().find(|m| m.id() == id).cloned()+}diff --git a/screenpipe-vision/src/utils.rs b/screenpipe-vision/src/utils.rsindex 972a9efcb..98ff6b371 100644--- a/screenpipe-vision/src/utils.rs+++ b/screenpipe-vision/src/utils.rs@@ -139,7 +139,7 @@ fn data_output_to_text(data_output: &DataOutput) -> String {text}-pub async fn capture_screenshot(monitor: &Monitor) -> (DynamicImage, u64, Duration) {+pub async fn capture_screenshot(monitor: Arc<Monitor>) -> (DynamicImage, u64, Duration) {let capture_start = Instant::now();let buffer = monitor.capture_image().unwrap();let image = DynamicImage::ImageRgba8(buffer);