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
fix: audio streaming, optimise perfs
Louis Beaumont2aded350e088
diff --git a/screenpipe-audio/Cargo.toml b/screenpipe-audio/Cargo.tomlindex ce76ee033..fd47bed1f 100644--- a/screenpipe-audio/Cargo.toml+++ b/screenpipe-audio/Cargo.toml@@ -24,7 +24,7 @@ chrono = { version = "0.4.31", features = ["serde"] }candle = { package = "candle-core", version = "0.3.2" } # atm got seg fault w features = ["metal"] ♥️candle-nn = "0.3.2"candle-transformers = "0.3.2"-tokenizers = "0.15.0"+tokenizers = "0.19.1"lazy_static = "1.4.0"base64 = "0.21.7"anyhow = "1.0.86"@@ -34,6 +34,10 @@ symphonia = "0.5.4"rand = "0.8.5"rubato = "0.15.0"+# Log+log = { workspace = true }+env_logger = "0.10"+[dev-dependencies]tempfile = "3.3.0"diff --git a/screenpipe-audio/src/bin/screenpipe-audio.rs b/screenpipe-audio/src/bin/screenpipe-audio.rsindex 249a440ce..518acaa18 100644--- a/screenpipe-audio/src/bin/screenpipe-audio.rs+++ b/screenpipe-audio/src/bin/screenpipe-audio.rs@@ -1,15 +1,21 @@use anyhow::Result;-use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};-use hound::WavWriter;+use env_logger::Env;+use log::info;use screenpipe_audio::{continuous_audio_capture, ControlMessage};-use std::sync::mpsc::{Receiver, Sender};-use std::sync::{Arc, Mutex};use std::thread;use std::time::Duration;fn main() -> Result<()> {+ use env_logger::Builder;+ use log::LevelFilter;use std::sync::mpsc;+ let _ = Builder::new()+ .filter(None, LevelFilter::Info)+ .filter_module("tokenizers", LevelFilter::Error)+ .init();++let (control_tx, control_rx) = mpsc::channel();let (result_tx, result_rx) = mpsc::channel();let chunk_duration = Duration::from_secs(5);@@ -17,10 +23,9 @@ fn main() -> Result<()> {let capture_thread =thread::spawn(move || continuous_audio_capture(control_rx, result_tx, chunk_duration));- // Example: Run for 30 seconds, then stop- for _ in 0..6 {+ while true {if let Ok(result) = result_rx.recv_timeout(Duration::from_secs(5)) {- println!("Transcription: {}", result.text);+ info!("Transcription: {}", result.text);}}diff --git a/screenpipe-audio/src/core.rs b/screenpipe-audio/src/core.rsindex d1fb99792..0e6f25753 100644--- a/screenpipe-audio/src/core.rs+++ b/screenpipe-audio/src/core.rs@@ -1,6 +1,7 @@use anyhow::Result;use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};use hound::WavWriter;+use log::{error, info};use std::sync::mpsc::{Receiver, Sender};use std::sync::{Arc, Mutex};use std::thread;@@ -26,6 +27,7 @@ pub fn continuous_audio_capture(let sample_rate = config.sample_rate().0;let channels = config.channels() as usize;+ info!("Sample rate: {}, Channels: {}", sample_rate, channels);let audio_buffer = Arc::new(Mutex::new(Vec::new()));let audio_buffer_clone = audio_buffer.clone();@@ -41,17 +43,21 @@ pub fn continuous_audio_capture(audio_buffer_clone.lock().unwrap().extend_from_slice(data);}},- |err| eprintln!("An error occurred on the input audio stream: {}", err),+ |err| error!("An error occurred on the input audio stream: {}", err),None,)?;- stream.play()?;+ match stream.play() {+ Ok(_) => info!("Successfully started audio stream"),+ Err(e) => error!("Failed to start audio stream: {}", e),+ }let is_paused_clone = is_paused.clone();let should_stop_clone = should_stop.clone();let process_audio = move || -> Result<()> {loop {+ info!("Processing audio...");// Check for control messagesif let Ok(message) = control_rx.try_recv() {match message {@@ -63,15 +69,20 @@ pub fn continuous_audio_capture(}}}+ info!("Processing audio2...");if *is_paused_clone.lock().unwrap() {thread::sleep(Duration::from_millis(100));continue;}+ info!("Processing audio3...");thread::sleep(chunk_duration);+ info!("Processing audio4...");let mut audio_data = audio_buffer.lock().unwrap();+ info!("audio_data len: {:?}", audio_data.len());+if !audio_data.is_empty() {let chunk = audio_data.clone();audio_data.clear();@@ -94,6 +105,9 @@ pub fn continuous_audio_capture(let transcription = stt(temp_file.to_str().unwrap())?;std::fs::remove_file(temp_file)?;+ info!("Transcription: {}", transcription);+ info!("Chunk size: {:?}", chunk.len());+result_tx.send(CaptureResult {audio: chunk,text: transcription,@@ -120,15 +134,20 @@ pub enum ControlMessage {// a function to save an audio to filepub fn save_audio_to_file(audio: &[f32], file_path: &str) -> Result<()> {let spec = hound::WavSpec {- channels: 1,+ channels: 1, // TODOsample_rate: 44100,bits_per_sample: 32,sample_format: hound::SampleFormat::Float,};- let mut writer = WavWriter::create(file_path, spec)?;+ let mut writer = WavWriter::create(file_path, spec)+ .map_err(|e| anyhow::anyhow!("Failed to create WavWriter: {}", e))?;for sample in audio.iter() {- writer.write_sample(*sample)?;+ writer+ .write_sample(*sample)+ .map_err(|e| anyhow::anyhow!("Failed to write sample: {}", e))?;}- writer.finalize()?;+ writer+ .finalize()+ .map_err(|e| anyhow::anyhow!("Failed to finalize WavWriter: {}", e))?;Ok(())}diff --git a/screenpipe-audio/src/multilingual.rs b/screenpipe-audio/src/multilingual.rsindex f77607b49..e3a7c4d18 100644--- a/screenpipe-audio/src/multilingual.rs+++ b/screenpipe-audio/src/multilingual.rs@@ -1,5 +1,6 @@use candle::{IndexOp, Result, Tensor, D};use candle_transformers::models::whisper::SOT_TOKEN;+use log::info;use tokenizers::Tokenizer;const LANGUAGES: [(&str, &str); 99] = [@@ -133,7 +134,7 @@ pub fn detect_language(let mut probs = LANGUAGES.iter().zip(probs.iter()).collect::<Vec<_>>();probs.sort_by(|(_, p1), (_, p2)| p2.total_cmp(p1));for ((_, language), p) in probs.iter().take(5) {- println!("{language}: {p}")+ info!("{language}: {p}")}let language = super::stt::token_id(tokenizer, &format!("<|{}|>", probs[0].0 .0))?;Ok(language)diff --git a/screenpipe-audio/src/pcm_decode.rs b/screenpipe-audio/src/pcm_decode.rsindex e75d3ffd6..1a770aa1b 100644--- a/screenpipe-audio/src/pcm_decode.rs+++ b/screenpipe-audio/src/pcm_decode.rs@@ -1,3 +1,4 @@+use log::info;use symphonia::core::audio::{AudioBufferRef, Signal};use symphonia::core::codecs::{DecoderOptions, CODEC_TYPE_NULL};use symphonia::core::conv::FromSample;@@ -45,6 +46,7 @@ pub(crate) fn pcm_decode<P: AsRef<std::path::Path>>(path: P) -> anyhow::Result<(.expect("unsupported codec");let track_id = track.id;let sample_rate = track.codec_params.sample_rate.unwrap_or(0);+ info!("Sample rate: {}", sample_rate);let mut pcm_data = Vec::new();// The decode loop.while let Ok(packet) = format.next_packet() {diff --git a/screenpipe-audio/src/stt.rs b/screenpipe-audio/src/stt.rsindex 182438574..b6feb874c 100644--- a/screenpipe-audio/src/stt.rs+++ b/screenpipe-audio/src/stt.rs@@ -2,6 +2,7 @@ use anyhow::{Error as E, Result};use candle::{Device, IndexOp, Tensor};use candle_nn::ops::softmax;use hf_hub::{api::sync::Api, Repo, RepoType};+use log::{error, info};use rand::{distributions::Distribution, SeedableRng};use tokenizers::Tokenizer;@@ -12,6 +13,8 @@ use rubato::{use crate::{multilingual, pcm_decode::pcm_decode};+// TODO: improve model loading strategy+pub enum Model {Normal(m::model::Whisper),Quantized(m::quantized_model::Whisper),@@ -149,7 +152,7 @@ impl Decoder {let model = &mut self.model;let audio_features = model.encoder_forward(mel, true)?;if self.verbose {- println!("audio features: {:?}", audio_features.dims());+ info!("audio features: {:?}", audio_features.dims());}let sample_len = model.config().max_target_positions / 2;let mut sum_logprob = 0f64;@@ -247,7 +250,7 @@ impl Decoder {}}Err(err) => {- println!("Error running at {t}: {err}")+ error!("Error running at {t}: {err}")}}}@@ -267,7 +270,7 @@ impl Decoder {let dr = self.decode_with_fallback(&mel_segment)?;seek += segment_size;if dr.no_speech_prob > m::NO_SPEECH_THRESHOLD && dr.avg_logprob < m::LOGPROB_THRESHOLD {- println!("no speech detected, skipping {seek} {dr:?}");+ info!("no speech detected, skipping {seek} {dr:?}");continue;}let segment = Segment {@@ -276,7 +279,7 @@ impl Decoder {dr,};if self.timestamps {- println!(+ info!("{:.1}s -- {:.1}s",segment.start,segment.start + segment.duration,@@ -295,7 +298,7 @@ impl Decoder {.tokenizer.decode(&tokens_to_decode, true).map_err(E::msg)?;- println!(" {:.1}s-{:.1}s: {}", prev_timestamp_s, timestamp_s, text);+ info!(" {:.1}s-{:.1}s: {}", prev_timestamp_s, timestamp_s, text);tokens_to_decode.clear()}prev_timestamp_s = timestamp_s;@@ -309,12 +312,12 @@ impl Decoder {.decode(&tokens_to_decode, true).map_err(E::msg)?;if !text.is_empty() {- println!(" {:.1}s-...: {}", prev_timestamp_s, text);+ info!(" {:.1}s-...: {}", prev_timestamp_s, text);}tokens_to_decode.clear()}} else {- println!(+ info!("{:.1}s -- {:.1}s: {}",segment.start,segment.start + segment.duration,@@ -322,7 +325,7 @@ impl Decoder {)}if self.verbose {- println!("{seek}: {segment:?}, in {:?}", start.elapsed());+ info!("{seek}: {segment:?}, in {:?}", start.elapsed());}segments.push(segment)}@@ -400,10 +403,10 @@ impl WhichModel {}pub fn stt(input: &str) -> Result<String> {- println!("Starting speech to text");+ info!("Starting speech to text");// ! hack assuming device on 0 and that everyone wants to use AI acceleratorlet device = Device::new_metal(0).unwrap_or(Device::new_cuda(0).unwrap_or(Device::Cpu));- println!("device = {:?}", device);+ info!("device = {:?}", device);let (default_model, default_revision) = ("lmz/candle-whisper", "main");let default_model = default_model.to_string();let default_revision = default_revision.to_string();@@ -416,7 +419,7 @@ pub fn stt(input: &str) -> Result<String> {default_revision,));let sample = std::path::PathBuf::from(input);- println!("sample = {:?}", sample);+ info!("sample = {:?}", sample);let config = repo.get("config-tiny.json")?;let tokenizer = repo.get("tokenizer-tiny.json")?;let model = repo.get("model-tiny-q80.gguf")?;@@ -436,7 +439,7 @@ pub fn stt(input: &str) -> Result<String> {let (mut pcm_data, sample_rate) = pcm_decode(input)?;// Resample if necessaryif sample_rate != m::SAMPLE_RATE as u32 {- println!(+ info!("Resampling from {} Hz to {} Hz",sample_rate,m::SAMPLE_RATE@@ -444,7 +447,7 @@ pub fn stt(input: &str) -> Result<String> {pcm_data = resample(pcm_data, sample_rate, m::SAMPLE_RATE as u32)?;}- println!("pcm data loaded {}", pcm_data.len());+ info!("pcm data loaded {}", pcm_data.len());let mel = audio::pcm_to_mel(&config, &pcm_data, &mel_filters);let mel_len = mel.len();let mel = Tensor::from_vec(@@ -452,26 +455,34 @@ pub fn stt(input: &str) -> Result<String> {(1, config.num_mel_bins, mel_len / config.num_mel_bins),&device,)?;- println!("loaded mel: {:?}", mel.dims());+ info!("loaded mel: {:?}", mel.dims());let vb = candle_transformers::quantized_var_builder::VarBuilder::from_gguf(&weights_filename,&device,)?;+ info!("loading model");let mut model = Model::Quantized(m::quantized_model::Whisper::load(&vb, config)?);-- let language_token = Some(multilingual::detect_language(&mut model, &tokenizer, &mel)?);+ info!("loaded model");+ info!("detecting language");+ // TODO: disabled seems slow as fuck+ // let language_token = Some(multilingual::detect_language(&mut model, &tokenizer, &mel)?);+ // info!("detected language: {:?}", language_token);+ info!("creating decoder");let mut dc = Decoder::new(model,tokenizer,42,&device,- language_token,+ // language_token,+ None,Some(Task::Transcribe),false,false,)?;+ info!("Decoding...");let segments = dc.run(&mel)?;+ info!("Decoding done {:?}", segments);Ok(segments.iter().map(|s| s.dr.text.clone())@@ -480,6 +491,7 @@ pub fn stt(input: &str) -> Result<String> {}fn resample(input: Vec<f32>, from_sample_rate: u32, to_sample_rate: u32) -> Result<Vec<f32>> {+ info!("Resampling from {} to {}", from_sample_rate, to_sample_rate);let params = SincInterpolationParameters {sinc_len: 256,f_cutoff: 0.95,diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rsindex 07cce9c80..7546051d9 100644--- a/screenpipe-server/src/bin/screenpipe-server.rs+++ b/screenpipe-server/src/bin/screenpipe-server.rs@@ -3,7 +3,6 @@ use std::{sync::{mpsc::channel, Arc, Mutex},};-use chrono::Utc;use tokio::sync::oneshot;use tokio::time::Duration;@@ -13,7 +12,14 @@ use screenpipe_server::{start_continuous_recording, DatabaseManager, RecorderCon#[tokio::main]async fn main() -> anyhow::Result<()> {// Initialize logging- env_logger::init();+ use env_logger::Builder;+ use log::LevelFilter;++ let _ = Builder::new()+ .filter(None, LevelFilter::Info)+ .filter_module("tokenizers", LevelFilter::Error)+ .filter_module("rusty_tesseract", LevelFilter::Error)+ .init();let local_data_dir = ensure_local_data_dir()?;let local_data_dir_clone = local_data_dir.clone();diff --git a/screenpipe-server/src/core.rs b/screenpipe-server/src/core.rsindex b6f384348..d618006d2 100644--- a/screenpipe-server/src/core.rs+++ b/screenpipe-server/src/core.rs@@ -25,9 +25,7 @@ pub fn start_continuous_recording(let db_manager = Arc::new(Mutex::new(DatabaseManager::new(db_path)?));let db_manager_clone = db_manager.clone();- let time = Utc::now();- let video_output_path = format!("{}/{}.mp4", output_path, time);- let video_capture = VideoCapture::new(&video_output_path, fps);+ let video_capture = VideoCapture::new(&output_path, fps);let control_rx = Arc::new(Mutex::new(control_rx));let control_rx_video = Arc::clone(&control_rx);@@ -62,18 +60,19 @@ pub fn start_continuous_recording(if !is_paused {if let Some(frame) = video_capture.get_latest_frame() {- match db_manager.lock().unwrap().insert_frame() {+ let mut db = db_manager.lock().unwrap();+ match db.insert_frame() {Ok(frame_id) => {- if let Err(e) = db_manager- .lock()- .unwrap()- .insert_text_for_frame(frame_id, &frame.text)- {+ if let Err(e) = db.insert_text_for_frame(frame_id, &frame.text) {error!("Failed to insert OCR text: {}", e);+ return Err(e.into());}debug!("Inserted frame {} with OCR text", frame_id);}- Err(e) => error!("Failed to insert frame: {}", e),+ Err(e) => {+ error!("Failed to insert frame: {}", e);+ return Err(e.into());+ }}}}@@ -105,28 +104,40 @@ pub fn start_continuous_recording(}if !is_paused {- if let Ok(result) = audio_result_rx.recv() {- // Create an audio file- let time = Utc::now();- let file_path = format!("{}/{}.wav", output_path_clone, time);- save_audio_to_file(&result.audio, &file_path)?;+ match audio_result_rx.recv() {+ Ok(result) => {+ info!("Received audio chunk, processing...");+ info!("Audio chunk size: {}", result.audio.len());+ // Create an audio file+ let time = Utc::now();+ let file_path = format!("{}/{}.wav", output_path_clone, time);+ info!("Saving audio chunk to {}", file_path);+ match save_audio_to_file(&result.audio, &file_path) {+ Ok(_) => info!("Successfully saved audio file"),+ Err(e) => error!("Failed to save audio file: {}", e),+ }- match db_manager_clone- .lock()- .unwrap()- .insert_audio_chunk(&file_path)- {- Ok(audio_chunk_id) => {- if let Err(e) = db_manager_clone- .lock()- .unwrap()- .insert_audio_transcription(audio_chunk_id, &result.text, 0)- {- error!("Failed to insert audio transcription: {}", e);+ let db = db_manager_clone.lock().unwrap();+ match db.insert_audio_chunk(&file_path) {+ Ok(audio_chunk_id) => {+ debug!("Inserted audio chunk with id: {}", audio_chunk_id);+ if let Err(e) =+ db.insert_audio_transcription(audio_chunk_id, &result.text, 0)+ // TODO offset+ {+ error!("Failed to insert audio transcription: {}", e);+ } else {+ debug!(+ "Inserted audio transcription for chunk {}",+ audio_chunk_id+ );+ }}- debug!("Inserted audio chunk {} with transcription", audio_chunk_id);+ Err(e) => error!("Failed to insert audio chunk: {}", e),}- Err(e) => error!("Failed to insert audio chunk: {}", e),+ }+ Err(e) => {+ error!("Failed to receive audio chunk: {}", e);}}}diff --git a/screenpipe-server/src/db.rs b/screenpipe-server/src/db.rsindex 630c9f288..6cbabe81f 100644--- a/screenpipe-server/src/db.rs+++ b/screenpipe-server/src/db.rs@@ -227,8 +227,7 @@ impl DatabaseManager {// Method to insert a frame and return its IDpub fn insert_frame(&mut self) -> Result<i64> {- // println!("inserting frame... {:?}", Utc::now().naive_utc());- let frame_id = self.conn.execute(+ self.conn.execute("INSERT INTO frames (video_chunk_id, offset_index, timestamp)VALUES (?1, ?2, ?3)",params![@@ -239,18 +238,18 @@ impl DatabaseManager {)?;self.current_frame_offset += 1;- self.last_frame_id = frame_id as i64;+ self.last_frame_id = self.conn.last_insert_rowid();Ok(self.last_frame_id)}// Method to insert text for a frame- pub fn insert_text_for_frame(&self, frame_id: i64, text: &str) -> Result<()> {+ pub fn insert_text_for_frame(&self, frame_id: i64, text: &str) -> Result<i64> {self.conn.execute("INSERT INTO ocr_text (frame_id, text) VALUES (?1, ?2)",params![frame_id, text],)?;- Ok(())+ Ok(self.conn.last_insert_rowid())}// Method to get a frame by index@@ -607,3 +606,30 @@ mod tests {Ok(())}}++// Debugging:+// # 1. List all tables+// sqlite3 data/db.sqlite ".tables"++// # 2. Dump entire database content+// sqlite3 data/db.sqlite ".dump"++// # 3. Show schema for all tables+// sqlite3 data/db.sqlite ".schema"++// # 4. Query recent frames with OCR text+// sqlite3 data/db.sqlite "SELECT f.id, f.timestamp, o.text FROM frames f JOIN ocr_text o ON f.id = o.frame_id ORDER BY f.timestamp DESC LIMIT 10;"++// # 5. Query recent audio transcriptions+// sqlite3 data/db.sqlite "SELECT at.audio_chunk_id, at.timestamp, at.transcription FROM audio_transcriptions at ORDER BY at.timestamp DESC LIMIT 10;"++// # 6. Just list a table content+// sqlite3 data/db.sqlite "SELECT * FROM frames"++// sqlite3 data/db.sqlite "SELECT * FROM audio_chunks"++// sqlite3 data/db.sqlite "SELECT * FROM video_chunks"++// sqlite3 data/db.sqlite "SELECT * FROM ocr_text"++// sqlite3 data/db.sqlite "SELECT * FROM audio_transcriptions"diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rsindex fae4795fd..efe3d7f2f 100644--- a/screenpipe-server/src/server.rs+++ b/screenpipe-server/src/server.rs@@ -195,3 +195,19 @@ pub async fn start_frame_server(// Send signal that the server has startedlet _ = tx.send(());}++// # 1. Search for text with pagination+// curl "http://localhost:3030/text?search=e&limit=10&offset=0"++// # 2. Get recent results without search term+// curl "http://localhost:3030/text?limit=20&offset=0"++// # 3. Get frame image (non-thumbnail) // ! does not work+// curl -o frame.png "http://localhost:3030/frames/100"++// # 4. Get frame thumbnail+// curl -o thumbnail.png "http://localhost:3030/frames/100?thumbnail=true"++// # 5. Get text by date range+// curl "http://localhost:3030/text_by_date?start_date=2024-07-02T00:00:00&end_date=2024-07-02T23:59:59&limit=15&offset=0"+diff --git a/screenpipe-server/src/video.rs b/screenpipe-server/src/video.rsindex 9ae5b8cb9..67917f9aa 100644--- a/screenpipe-server/src/video.rs+++ b/screenpipe-server/src/video.rs@@ -4,7 +4,7 @@ use ffmpeg_next::sys::AVSEEK_FLAG_FRAME;use ffmpeg_next::{format, format::Pixel, media, software::scaling, util::frame::video::Video};use image::ImageFormat::{self, Png};use image::{DynamicImage, ImageBuffer, Rgb};-use log::{error, info};+use log::{debug, error, info, warn};use screenpipe_vision::{continuous_capture, CaptureResult, ControlMessage};use std::collections::{BTreeSet, VecDeque};use std::io::BufRead;@@ -16,6 +16,9 @@ use std::thread;use std::time::Duration;use threadpool::ThreadPool;+const MAX_THREADS: usize = 16; // Adjust based on your needs+const MAX_FPS: f64 = 30.0; // Adjust based on your needs+pub fn extract_frames_from_video(video_path: &str,frame_numbers: &[i64],@@ -253,6 +256,7 @@ fn save_frames_as_video(let mut frame_count = 0;let cpu_count = num_cpus::get();let pool_size = (cpu_count as f32 * 1.2) as usize;+ let pool_size = std::cmp::min(pool_size, MAX_THREADS);let pool = ThreadPool::new(pool_size);let (sender, receiver): (Sender<Vec<u8>>, Receiver<Vec<u8>>) = channel();@@ -300,7 +304,7 @@ fn save_frames_as_video(let reader = std::io::BufReader::new(stderr);for line in reader.lines() {if let Ok(line) = line {- info!("FFmpeg: {}", line);+ debug!("FFmpeg: {}", line);}}});@@ -335,7 +339,7 @@ fn save_frames_as_video(break;}frame_count += 1;- info!("Wrote frame {} to FFmpeg", frame_count);+ debug!("Wrote frame {} to FFmpeg", frame_count);// Flush every secondif frame_count % fps as usize == 0 {@@ -355,6 +359,13 @@ fn save_frames_as_video(}fn start_ffmpeg_process(output_file: &str, fps: f64) -> std::process::Child {+ // overrriding fps with max fps if over the max and warning user+ let mut fps = fps;+ if fps > MAX_FPS {+ warn!("Overriding FPS to {}", MAX_FPS);+ fps = MAX_FPS;+ }+info!("Starting FFmpeg process for file: {}", output_file);Command::new("ffmpeg").args([diff --git a/screenpipe-vision/src/core.rs b/screenpipe-vision/src/core.rsindex 5dbbbd1e6..6b001ba62 100644--- a/screenpipe-vision/src/core.rs+++ b/screenpipe-vision/src/core.rs@@ -19,6 +19,8 @@ pub struct CaptureResult {pub text: String,}+const MAX_THREADS: usize = 16; // Adjust based on your needs+pub fn continuous_capture(control_rx: Receiver<ControlMessage>,result_tx: Sender<CaptureResult>,@@ -27,10 +29,11 @@ pub fn continuous_capture(let monitor = Monitor::all().unwrap().first().unwrap().clone();let cpu_count = num_cpus::get();let pool_size = (cpu_count as f32 * 1.2) as usize;+ let pool_size = std::cmp::min(pool_size, MAX_THREADS);+let ocr_pool = ThreadPool::new(pool_size);let is_paused = Arc::new(Mutex::new(false));let should_stop = Arc::new(Mutex::new(false));-loop {// Check for control messagesif let Ok(message) = control_rx.try_recv() {