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
perf(macos): couple SCK capture width to the user's video_quality setting
Louis Beaumontac49fa6a4cc1
diff --git a/crates/screenpipe-engine/src/vision_manager/manager.rs b/crates/screenpipe-engine/src/vision_manager/manager.rsindex face81ae4..6d87a4c7a 100644--- a/crates/screenpipe-engine/src/vision_manager/manager.rs+++ b/crates/screenpipe-engine/src/vision_manager/manager.rs@@ -361,12 +361,23 @@ impl VisionManager {.as_ref().map(|rx| rx.borrow().jpeg_quality.min(baseline_q)).unwrap_or(baseline_q);+ let max_snapshot_width = video_quality_to_max_snapshot_width(&self.config.video_quality);let snapshot_writer = Arc::new(SnapshotWriter::new(format!("{}/data", output_path),initial_jpeg_quality,- video_quality_to_max_snapshot_width(&self.config.video_quality),+ max_snapshot_width,));+ // Cap the macOS SCK capture stream to the same width as the snapshot+ // writer. The GPU downscales before replayd delivers the framebuffer,+ // saving WindowServer composite + readback cost without affecting+ // anything that wasn't going to be downsized in user space anyway.+ // Text extraction is primarily a11y-tree-driven (unchanged) and OCR+ // runs only as a fallback; both see the same image they'd see after+ // the snapshot-writer downscale.+ #[cfg(target_os = "macos")]+ screenpipe_screen::monitor::set_sck_capture_max_width(max_snapshot_width);+// Create activity feed for this monitorlet activity_feed = ActivityFeed::new();diff --git a/crates/screenpipe-screen/examples/ocr_scale_bench.rs b/crates/screenpipe-screen/examples/ocr_scale_bench.rsnew file mode 100644index 000000000..1f14df931--- /dev/null+++ b/crates/screenpipe-screen/examples/ocr_scale_bench.rs@@ -0,0 +1,139 @@+// OCR quality vs downscale factor — measures how much Apple Vision OCR+// degrades when capture width is capped via sck-rs's new capture_image_scaled.+//+// Method: capture once at native resolution, then synthetically downscale+// in-memory (bilinear, closest to GPU resize) to a range of target widths,+// OCR each, compare against the native OCR text as the baseline.+//+// Why synthetic resize and not multiple SCK captures: the screen changes+// between captures, so per-capture differences would conflate temporal+// noise with downscale impact. In-memory resize isolates the variable.+// As a sanity check we also do one SCK-scaled capture and compare it+// against the same-width synthetic resize.+//+// Run with:+// cargo run --release --example ocr_scale_bench -p screenpipe-screen++use image::imageops::FilterType;+use image::DynamicImage;+use sck_rs::Monitor;+use screenpipe_core::Language;+use screenpipe_screen::apple::perform_ocr_apple;+use std::collections::HashSet;+use std::time::Instant;++fn normalize_words(text: &str) -> HashSet<String> {+ text.split_whitespace()+ .map(|w| {+ w.to_lowercase()+ .trim_matches(|c: char| !c.is_alphanumeric())+ .to_string()+ })+ .filter(|w| w.len() >= 3)+ .collect()+}++fn report(label: &str, baseline_text: &str, baseline_words: &HashSet<String>, text: &str, conf: Option<f64>) {+ let words = normalize_words(text);+ let intersection: usize = baseline_words.intersection(&words).count();+ let recall = if !baseline_words.is_empty() {+ 100.0 * intersection as f64 / baseline_words.len() as f64+ } else {+ 0.0+ };+ // Lost words = baseline - downscaled. Sample first few for spot-checking.+ let lost: Vec<&String> = baseline_words.difference(&words).take(10).collect();+ let edit = strsim::levenshtein(baseline_text, text);+ let ced = 100.0 * edit as f64 / baseline_text.len().max(1) as f64;+ println!(+ " {:14} len={:6} uniq_words={:5} recall={:5.1}% CER≈{:4.1}% conf={:?}",+ label,+ text.len(),+ words.len(),+ recall,+ ced,+ conf.map(|c| (c * 100.0).round() / 100.0)+ );+ if !lost.is_empty() && recall < 99.0 {+ let sample: Vec<String> = lost.iter().take(8).map(|s| (*s).clone()).collect();+ println!(" lost-words sample: {:?}", sample);+ }+}++fn main() {+ let monitors = Monitor::all().expect("Monitor::all (grant Screen Recording)");+ let monitor = monitors+ .into_iter()+ .find(|m| m.is_primary())+ .expect("no primary monitor");+ let native_w = monitor.raw_width();+ let native_h = monitor.raw_height();+ println!("monitor: {} ({}x{} native)\n", monitor.name(), native_w, native_h);++ std::fs::create_dir_all("/tmp/ocr-bench").ok();++ // --- 1. Native capture + OCR baseline ---+ let t = Instant::now();+ let native_rgba = monitor.capture_image().expect("native capture");+ let native_cap = t.elapsed();+ let native_img = DynamicImage::ImageRgba8(native_rgba);++ let t = Instant::now();+ let (native_text, _json, native_conf) =+ perform_ocr_apple(&native_img, &[Language::English]);+ let native_ocr = t.elapsed();+ let baseline_words = normalize_words(&native_text);+ std::fs::write("/tmp/ocr-bench/native.txt", &native_text).ok();++ println!(+ "baseline (native {}x{}): cap={:?} ocr={:?} text_len={} uniq_words={}",+ native_img.width(),+ native_img.height(),+ native_cap,+ native_ocr,+ native_text.len(),+ baseline_words.len()+ );+ println!();++ // --- 2. Synthetic downscale comparisons ---+ println!("synthetic downscale (bilinear in-memory, isolates the downscale variable):");+ let widths = [1920u32, 1280, 960, 768, 480];+ for &max_w in &widths {+ if max_w >= native_w {+ println!(" {:14} (skipped: native already <= {})", format!("{}px", max_w), max_w);+ continue;+ }+ // Preserve aspect; height derived from ratio.+ let target_h = ((max_w as u64 * native_h as u64) / native_w as u64) as u32;+ let scaled = native_img.resize_exact(max_w, target_h, FilterType::Triangle);+ let t = Instant::now();+ let (text, _json, conf) = perform_ocr_apple(&scaled, &[Language::English]);+ let ocr_ms = t.elapsed();+ let label = format!("{}px ({}ms)", max_w, ocr_ms.as_millis());+ report(&label, &native_text, &baseline_words, &text, conf);+ std::fs::write(format!("/tmp/ocr-bench/synthetic_{}.txt", max_w), &text).ok();+ }++ // --- 3. SCK-scaled sanity check (validates synthetic proxy) ---+ println!("\nSCK-scaled capture (validates synthetic resize as a proxy):");+ let cap = 1280u32;+ if cap >= native_w {+ println!(" {}px: skipped (native already <= cap)", cap);+ } else {+ std::thread::sleep(std::time::Duration::from_millis(200));+ let t = Instant::now();+ let sck_rgba = monitor.capture_image_scaled(cap).expect("scaled capture");+ let cap_dur = t.elapsed();+ let sck_img = DynamicImage::ImageRgba8(sck_rgba);+ let t = Instant::now();+ let (text, _json, conf) = perform_ocr_apple(&sck_img, &[Language::English]);+ let ocr_ms = t.elapsed();+ let label = format!("sck_{}px ({}x{}) cap={}ms ocr={}ms",+ cap, sck_img.width(), sck_img.height(), cap_dur.as_millis(), ocr_ms.as_millis());+ report(&label, &native_text, &baseline_words, &text, conf);+ std::fs::write(format!("/tmp/ocr-bench/sck_{}.txt", cap), &text).ok();+ }++ println!("\noutput texts saved in /tmp/ocr-bench/ for spot-checking.");+}diff --git a/crates/screenpipe-screen/src/monitor.rs b/crates/screenpipe-screen/src/monitor.rsindex e6e53e069..34508b6b0 100644--- a/crates/screenpipe-screen/src/monitor.rs+++ b/crates/screenpipe-screen/src/monitor.rs@@ -58,14 +58,32 @@ use sck_rs::Monitor as SckMonitor;// xcap is used on non-macOS platforms, and as fallback on older macOSuse xcap::Monitor as XcapMonitor;-/// Maximum capture width handed to the macOS SCK stream. The GPU downscales-/// to fit before `replayd` delivers the framebuffer, so WindowServer-/// composites a smaller surface. 1280 keeps OCR text legible while saving-/// substantial WindowServer CPU on HiDPI / large displays (measured ~50%-/// reduction on a 1512px display capped to 768px; bigger ratios → bigger-/// savings). No-op when the monitor's native width is at or below this cap.+/// Optional cap on captured width for the macOS SCK stream. The GPU+/// downscales to fit before `replayd` delivers the framebuffer, so+/// WindowServer composites a smaller surface. `0` = no cap (capture at+/// native, the previous default).+///+/// Set by the vision manager from the user's `video_quality` setting via+/// `video_quality_to_max_snapshot_width` so the captured resolution+/// matches the resolution the snapshot writer would downscale to anyway.+/// Coupling these means screenpipe captures exactly the pixels it stores —+/// no wasted GPU readback at native res just to throw it away in user+/// space before JPEG encoding.#[cfg(target_os = "macos")]-const SCK_CAPTURE_MAX_WIDTH: u32 = 1280;+static SCK_CAPTURE_MAX_WIDTH: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);++/// Set the SCK capture-width cap. `0` = no cap. Reads the user's+/// `video_quality` setting via the snapshot-width mapping; called by the+/// vision manager when capture starts and when settings change.+#[cfg(target_os = "macos")]+pub fn set_sck_capture_max_width(max_width: u32) {+ SCK_CAPTURE_MAX_WIDTH.store(max_width, std::sync::atomic::Ordering::Relaxed);+}++#[cfg(target_os = "macos")]+fn sck_capture_max_width() -> u32 {+ SCK_CAPTURE_MAX_WIDTH.load(std::sync::atomic::Ordering::Relaxed)+}#[derive(Clone)]pub struct SafeMonitor {@@ -266,14 +284,17 @@ impl SafeMonitor {return Err("Invalid monitor dimensions".to_string());}- // Cap capture width — GPU downscales before replayd hands the- // frame back, so WindowServer composites a smaller surface.- // Measured ~50% WindowServer CPU reduction at 768px on a- // 1512px display; bigger wins on HiDPI. 1280 keeps OCR-quality- // text legible while still moving the needle on most modern- // displays. No-op when native_width <= cap.- monitor- .capture_image_scaled(SCK_CAPTURE_MAX_WIDTH)+ // Honor the user's video_quality cap at the SCK layer so+ // WindowServer composites + replayd delivers a framebuffer+ // at the same resolution the snapshot writer would write+ // to disk anyway. `0` = no cap (capture native).+ let cap = sck_capture_max_width();+ let result = if cap == 0 {+ monitor.capture_image()+ } else {+ monitor.capture_image_scaled(cap)+ };+ result.map_err(|e| format!("{}", e)).map(DynamicImage::ImageRgba8)} else {@@ -342,8 +363,13 @@ impl SafeMonitor {return Err("Invalid monitor dimensions".to_string());}- monitor- .capture_image_scaled_excluding(SCK_CAPTURE_MAX_WIDTH, &ids)+ let cap = sck_capture_max_width();+ let result = if cap == 0 {+ monitor.capture_image_excluding(&ids)+ } else {+ monitor.capture_image_scaled_excluding(cap, &ids)+ };+ result.map_err(|e| format!("{}", e)).map(DynamicImage::ImageRgba8)} else {