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: vision
Louis Beaumontb9fc5e0afa96
diff --git a/.cargo/config.toml b/.cargo/config.tomlnew file mode 100644index 000000000..a0d71950e--- /dev/null+++ b/.cargo/config.toml@@ -0,0 +1,3 @@+[build]+# for console_subscriber+rustflags = ["--cfg", "tokio_unstable"]diff --git a/Cargo.toml b/Cargo.tomlindex 74a7c0677..e50c9f2f8 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -18,3 +18,5 @@ candle-nn = { package = "candle-nn", version = "0.6.0" }candle-transformers = { package = "candle-transformers", version = "0.6.0" }tokenizers = "0.19.1"tracing = "0.1.37"+tokio = { version = "1.15", features = ["full", "tracing"] }+diff --git a/screenpipe-audio/Cargo.toml b/screenpipe-audio/Cargo.tomlindex ebea93c27..f82753fac 100644--- a/screenpipe-audio/Cargo.toml+++ b/screenpipe-audio/Cargo.toml@@ -59,6 +59,9 @@ crossbeam = "0.8"# Bytesbytemuck = "1.16.1"+# Async+tokio = { workspace = true }+[dev-dependencies]tempfile = "3.3.0"infer = "0.15"diff --git a/screenpipe-audio/src/bin/screenpipe-audio.rs b/screenpipe-audio/src/bin/screenpipe-audio.rsindex 6e72300f1..ed63659ca 100644--- a/screenpipe-audio/src/bin/screenpipe-audio.rs+++ b/screenpipe-audio/src/bin/screenpipe-audio.rs@@ -9,11 +9,9 @@ use screenpipe_audio::parse_audio_device;use screenpipe_audio::record_and_transcribe;use screenpipe_audio::AudioDevice;use screenpipe_audio::DeviceControl;-use std::collections::HashMap;use std::path::PathBuf;use std::sync::atomic::AtomicBool;use std::sync::Arc;-use std::sync::RwLock;use std::thread;use std::time::Duration;@@ -78,9 +76,6 @@ fn main() -> Result<()> {let chunk_duration = Duration::from_secs(5);let output_path = PathBuf::from("output.mp3");let (whisper_sender, whisper_receiver) = create_whisper_channel()?;- let device_controls: Arc<RwLock<HashMap<String, Arc<DeviceControl>>>> =- Arc::new(RwLock::new(HashMap::new()));-// Spawn threads for each devicelet recording_threads: Vec<_> = devices.into_iter()@@ -88,20 +83,14 @@ fn main() -> Result<()> {.map(|(i, device)| {let whisper_sender = whisper_sender.clone();let output_path = output_path.with_file_name(format!("output_{}.mp3", i));- let device_control = Arc::new(DeviceControl {- is_running: Arc::new(AtomicBool::new(true)),- is_paused: Arc::new(AtomicBool::new(false)),- });-- device_controls- .write()- .unwrap()- .insert(device.to_string(), Arc::clone(&device_control));+ let device_control = Arc::new(AtomicBool::new(true));+ let device_clone = device.clone();+thread::spawn(move || {let device_control_clone = Arc::clone(&device_control);record_and_transcribe(- &device,+ &device_clone,chunk_duration,output_path,whisper_sender,diff --git a/screenpipe-audio/src/core.rs b/screenpipe-audio/src/core.rsindex ceb9a1fcc..e3cd160ff 100644--- a/screenpipe-audio/src/core.rs+++ b/screenpipe-audio/src/core.rs@@ -7,16 +7,17 @@ use std::fmt;use std::path::PathBuf;use std::sync::atomic::{AtomicBool, Ordering};use std::sync::Arc;-use std::thread;use std::time::Duration;+use tokio::io::AsyncWriteExt;use crate::AudioInput;-use std::io::Write;-use std::process::{Command, Stdio};+use std::process::Stdio;+use tokio::process::Command;+#[derive(Clone)]pub struct DeviceControl {- pub is_running: Arc<AtomicBool>,- pub is_paused: Arc<AtomicBool>,+ pub is_running: bool,+ pub is_paused: bool,}#[derive(Clone, Eq, PartialEq, Hash, Serialize)]@@ -111,12 +112,12 @@ fn get_device_and_config(Ok((audio_device, config))}-pub fn record_and_transcribe(+pub async fn record_and_transcribe(audio_device: &AudioDevice,duration: Duration,output_path: PathBuf,whisper_sender: Sender<AudioInput>,- device_control: Arc<DeviceControl>,+ is_running: Arc<AtomicBool>,) -> Result<PathBuf> {let (cpal_audio_device, config) = get_device_and_config(audio_device)?;info!(@@ -130,19 +131,15 @@ pub fn record_and_transcribe(let (audio_sender, audio_receiver): (Sender<Vec<u8>>, Receiver<Vec<u8>>) =crossbeam::channel::unbounded();- let audio_sender_clone = audio_sender.clone();- let is_running_clone = Arc::clone(&device_control.is_running);- let is_running_clone_4 = Arc::clone(&device_control.is_running);- // TODO what the diff between pause/stop ?- let _is_paused_clone = Arc::clone(&device_control.is_paused);-+ let is_running_clone = Arc::clone(&is_running);+ let is_running_clone_2 = Arc::clone(&is_running);let output_path_clone = output_path.clone();let output_path_clone_2 = output_path.clone();let start_time = std::time::Instant::now();// Spawn FFmpeg process in a separate thread- let ffmpeg_handle = thread::spawn(move || {+ let ffmpeg_handle = tokio::spawn(async move {let mut ffmpeg = Command::new("ffmpeg").args(&["-f",@@ -173,7 +170,7 @@ pub fn record_and_transcribe(while is_running_clone.load(Ordering::Relaxed) {if let Ok(data) = audio_receiver.recv_timeout(Duration::from_millis(100)) {- if let Err(e) = stdin.write_all(&data) {+ if let Err(e) = stdin.write_all(&data).await {error!("Failed to write audio data to FFmpeg: {}", e);break;}@@ -181,13 +178,15 @@ pub fn record_and_transcribe(if start_time.elapsed() >= duration {break;}+ // sleep for 100ms+ tokio::time::sleep(Duration::from_millis(100)).await;}// Close stdin to signal EOF to FFmpegdrop(stdin);// Wait for FFmpeg to finish- match ffmpeg.wait() {+ match ffmpeg.wait().await {Ok(status) => debug!("FFmpeg process exited with status: {}", status),Err(e) => error!("Failed to wait for FFmpeg process: {}", e),}@@ -199,7 +198,7 @@ pub fn record_and_transcribe(cpal::SampleFormat::F32 => cpal_audio_device.build_input_stream(&config.into(),move |data: &[f32], _: &_| {- if is_running_clone_4.load(Ordering::Relaxed) {+ if is_running.load(Ordering::Relaxed) {if let Err(e) = audio_sender.try_send(bytemuck::cast_slice(data).to_vec()) {warn!("Failed to send audio data: {}", e);}@@ -215,11 +214,11 @@ pub fn record_and_transcribe(stream.play()?;info!("Recording for {} seconds", duration.as_secs());- while device_control.is_running.load(Ordering::Relaxed) {+ while is_running_clone_2.load(Ordering::Relaxed) {if start_time.elapsed() >= duration {break;}- thread::sleep(Duration::from_millis(100));+ tokio::time::sleep(Duration::from_millis(100)).await;}info!(@@ -230,14 +229,8 @@ pub fn record_and_transcribe(// Stop the stream and signal the recording to stopstream.pause()?;- // Wait for a short time to ensure all data is processed- // thread::sleep(Duration::from_millis(100));-- // Close the sender to signal the FFmpeg thread to finish- // drop(audio_sender_clone);-// Wait for the FFmpeg thread to finish- ffmpeg_handle.join().expect("Failed to join FFmpeg thread");+ ffmpeg_handle.await.expect("Failed to join FFmpeg thread");debug!("FFmpeg thread finished");if let Err(e) = whisper_sender.send(AudioInput {diff --git a/screenpipe-audio/src/stt.rs b/screenpipe-audio/src/stt.rsindex 2e9564e72..6a44c5363 100644--- a/screenpipe-audio/src/stt.rs+++ b/screenpipe-audio/src/stt.rs@@ -1,12 +1,8 @@-use std::{- thread,- time::{SystemTime, UNIX_EPOCH},-};+use std::time::{SystemTime, UNIX_EPOCH};use anyhow::{Error as E, Result};use candle::{Device, IndexOp, Tensor};use candle_nn::{ops::softmax, VarBuilder};-use crossbeam::channel::{self, Receiver, Sender};use hf_hub::{api::sync::Api, Repo, RepoType};use log::{error, info};use rand::{distributions::Distribution, SeedableRng};@@ -16,6 +12,7 @@ use candle_transformers::models::whisper::{self as m, audio, Config};use rubato::{Resampler, SincFixedIn, SincInterpolationParameters, SincInterpolationType, WindowFunction,};+use tokio::sync::mpsc::{Receiver, Sender};use crate::{multilingual, pcm_decode::pcm_decode};@@ -492,7 +489,8 @@ pub struct TranscriptionResult {pub timestamp: u64,pub error: Option<String>,}-pub fn create_whisper_channel() -> Result<(Sender<AudioInput>, Receiver<TranscriptionResult>)> {+pub async fn create_whisper_channel() -> Result<(Sender<AudioInput>, Receiver<TranscriptionResult>)>+{let whisper_model = WhisperModel::new()?;let (input_sender, input_receiver): (Sender<AudioInput>, Receiver<AudioInput>) =channel::unbounded();@@ -501,8 +499,8 @@ pub fn create_whisper_channel() -> Result<(Sender<AudioInput>, Receiver<TranscriReceiver<TranscriptionResult>,) = channel::unbounded();- thread::spawn(move || {- while let Ok(input) = input_receiver.recv() {+ tokio::spawn(async move {+ while let Ok(input) = input_receiver.recv().await {let timestamp = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time went backwards")@@ -533,5 +531,3 @@ pub fn create_whisper_channel() -> Result<(Sender<AudioInput>, Receiver<TranscriOk((input_sender, output_receiver))}--diff --git a/screenpipe-server/Cargo.toml b/screenpipe-server/Cargo.tomlindex a2fbe5075..f5b5a9689 100644--- a/screenpipe-server/Cargo.toml+++ b/screenpipe-server/Cargo.toml@@ -51,9 +51,11 @@ rubato = "0.15.0"# Serveraxum = "0.7.5"-tokio = { version = "1.15.0", features = ["full"] }+tokio = { version = "1.15", features = ["full", "tracing"] }hyper = "1.4"-tower-http = { version = "0.5.2", features = ["cors"] }+tower-http = { version = "0.5.2", features = ["cors", "trace"] }+tracing-subscriber = "0.3.18"+console-subscriber = "0.3.0"# Loglog = { workspace = true }diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rsindex 5df1f524c..1f1e0a78e 100644--- a/screenpipe-server/src/bin/screenpipe-server.rs+++ b/screenpipe-server/src/bin/screenpipe-server.rs@@ -2,8 +2,8 @@ use std::{collections::HashMap,fs,net::SocketAddr,- sync::{atomic::AtomicBool, mpsc::channel, Arc, RwLock},- time::Duration,+ sync::{atomic::AtomicBool, mpsc::channel, Arc},+ time::{Duration, Instant},};use clap::Parser;@@ -12,7 +12,7 @@ use colored::Colorize;use log::{debug, info, LevelFilter};use screenpipe_audio::{default_input_device, default_output_device, list_audio_devices, parse_audio_device,- AudioDevice, DeviceControl,+ DeviceControl,};use screenpipe_server::{start_continuous_recording, DatabaseManager, ResourceMonitor, Server};@@ -24,7 +24,7 @@ const DISPLAY: &str = r"/ ___/ ___/ ___/ _ \/ _ \/ __ \ / __ \/ / __ \/ _ \(__ / /__/ / / __/ __/ / / / / /_/ / / /_/ / __//____/\___/_/ \___/\___/_/ /_/ / .___/_/ .___/\___/- /_/ /_/+ /_/ /_/";@@ -88,6 +88,9 @@ async fn main() -> anyhow::Result<()> {}builder.init();+ // tokio-console+ // console_subscriber::init();+// Add warning for Linux and Windows users#[cfg(any(target_os = "linux", target_os = "windows"))]{@@ -104,7 +107,7 @@ async fn main() -> anyhow::Result<()> {);}let all_audio_devices = list_audio_devices()?;-+ let mut devices_status = HashMap::new();if cli.list_audio_devices {println!("Available audio devices:");for (i, device) in all_audio_devices.iter().enumerate() {@@ -114,19 +117,25 @@ async fn main() -> anyhow::Result<()> {}let mut audio_devices = Vec::new();- let audio_devices_control: Arc<RwLock<HashMap<AudioDevice, Arc<DeviceControl>>>> =- Arc::new(RwLock::new(HashMap::new()));+ let (audio_devices_control_sender, audio_devices_control_receiver) =+ crossbeam::channel::unbounded();++ let audio_devices_control_sender_server = audio_devices_control_sender.clone();++ info!("Available audio devices:");// Add all available audio devices to the controlsfor device in &all_audio_devices {let device_control = DeviceControl {- is_running: Arc::new(AtomicBool::new(false)),- is_paused: Arc::new(AtomicBool::new(false)),+ is_running: false,+ is_paused: false,};- audio_devices_control- .write()- .unwrap()- .insert(device.clone(), Arc::new(device_control));+ let _ = audio_devices_control_sender.send_deadline(+ (device.clone(), device_control.clone()),+ Instant::now() + Duration::from_secs(10),+ );+ devices_status.insert(device.clone(), device_control);+ info!(" {}", device);}if !cli.disable_audio {@@ -135,39 +144,42 @@ async fn main() -> anyhow::Result<()> {// Use default devicesif let Ok(input_device) = default_input_device() {audio_devices.push(Arc::new(input_device.clone()));- if let Some(control) = audio_devices_control- .write()- .unwrap()- .get_mut(&input_device)- {- control- .is_running- .store(true, std::sync::atomic::Ordering::SeqCst);- }+ let device_control = DeviceControl {+ is_running: true,+ is_paused: false,+ };+ let _ = audio_devices_control_sender.send_deadline(+ (input_device.clone(), device_control.clone()),+ Instant::now() + Duration::from_secs(15),+ );+ devices_status.insert(input_device, device_control);}if let Ok(output_device) = default_output_device() {audio_devices.push(Arc::new(output_device.clone()));- if let Some(control) = audio_devices_control- .write()- .unwrap()- .get_mut(&output_device)- {- control- .is_running- .store(true, std::sync::atomic::Ordering::SeqCst);- }+ let device_control = DeviceControl {+ is_running: true,+ is_paused: false,+ };+ let _ = audio_devices_control_sender.send_deadline(+ (output_device.clone(), device_control.clone()),+ Instant::now() + Duration::from_secs(15),+ );+ devices_status.insert(output_device, device_control);}} else {// Use specified devicesfor d in &cli.audio_device {let device = parse_audio_device(d).expect("Failed to parse audio device");audio_devices.push(Arc::new(device.clone()));- if let Some(control) = audio_devices_control.write().unwrap().get_mut(&device) {- control- .is_running- .store(true, std::sync::atomic::Ordering::SeqCst);- debug!("running audio device: {}", device.to_string());- }+ let device_control = DeviceControl {+ is_running: true,+ is_paused: false,+ };+ let _ = audio_devices_control_sender.send_deadline(+ (device.clone(), device_control.clone()),+ Instant::now() + Duration::from_secs(15),+ );+ devices_status.insert(device, device_control);}}@@ -181,8 +193,8 @@ async fn main() -> anyhow::Result<()> {}}- ResourceMonitor::new(cli.memory_threshold, cli.runtime_threshold)- .start_monitoring(Duration::from_secs(10)); // Log every 10 seconds+ let resource_monitor = ResourceMonitor::new(cli.memory_threshold, cli.runtime_threshold);+ resource_monitor.start_monitoring(Duration::from_secs(10)); // Log every 10 secondslet local_data_dir = cli.data_dir; // TODO: Use $HOME/.screenpipe/datafs::create_dir_all(&local_data_dir)?;@@ -193,6 +205,10 @@ async fn main() -> anyhow::Result<()> {.await.unwrap(),);+ info!(+ "Database initialized, will store files in {}",+ local_data_dir+ );let db_record = db.clone();let db_server = db.clone();@@ -201,7 +217,6 @@ async fn main() -> anyhow::Result<()> {let vision_control = Arc::new(AtomicBool::new(true));let vision_control_server_clone = vision_control.clone();- let audio_devices_control_server_clone = audio_devices_control.clone();// Start continuous recording in a separate tasklet _recording_task = tokio::spawn({@@ -214,9 +229,8 @@ async fn main() -> anyhow::Result<()> {cli.fps,audio_chunk_duration,control_rx,- !cli.disable_audio,vision_control,- audio_devices_control,+ audio_devices_control_receiver,).await}@@ -227,9 +241,9 @@ async fn main() -> anyhow::Result<()> {db_server,SocketAddr::from(([0, 0, 0, 0], cli.port)),vision_control_server_clone,- audio_devices_control_server_clone,+ audio_devices_control_sender_server,);- server.start().await.unwrap();+ server.start(devices_status).await.unwrap();});// Wait for the server to startdiff --git a/screenpipe-server/src/bin/screenpipe-video.rs b/screenpipe-server/src/bin/screenpipe-video.rsindex 33ba0925f..02ada77e0 100644--- a/screenpipe-server/src/bin/screenpipe-video.rs+++ b/screenpipe-server/src/bin/screenpipe-video.rs@@ -18,7 +18,8 @@ fn write_json_frame(writer: &mut BufWriter<File>, frame_data: &Value) -> std::iowriter.flush()}-fn main() {+#[tokio::main]+async fn main() {env_logger::Builder::from_env(Env::default().default_filter_or("info")).init();let time = Utc::now();@@ -53,7 +54,6 @@ fn main() {let json_file = OpenOptions::new().create(true)-.append(true).open(&json_output_path).expect("Failed to create JSON file");@@ -62,7 +62,7 @@ fn main() {let mut frame_count = 0;loop {- if let Some(frame) = video_capture.get_latest_frame() {+ if let Some(frame) = video_capture.get_latest_frame().await {info!("Captured frame size: {:?}", frame.image.dimensions());info!("OCR Text len: {}", frame.text.len());@@ -86,7 +86,7 @@ fn main() {}}- video_capture.stop();+ video_capture.stop().await;println!("Video capture completed. Output saved to: {}", output_path);println!("JSON data saved to: {}", json_output_path);}diff --git a/screenpipe-server/src/cache.rs b/screenpipe-server/src/cache.rsdeleted file mode 100644index 11b8b6bb7..000000000--- a/screenpipe-server/src/cache.rs+++ /dev/null@@ -1,138 +0,0 @@-// use crate::core::{extract_all_frames_from_video, extract_frames_from_video};-// use image::DynamicImage;-// use lru::LruCache;-// use std::collections::HashMap;-// use std::num::NonZeroUsize;-// use std::sync::{Arc, Mutex, RwLock};-// use std::thread;-//-// pub struct FrameCache {-// cache: Arc<RwLock<LruCache<String, CacheEntry>>>,-// max_size: usize,-// }-//-// struct CacheEntry {-// frames: HashMap<usize, FrameData>,-// is_being_processed: bool,-// }-//-// struct FrameData {-// image: DynamicImage,-// }-//-// impl FrameCache {-// fn new(max_size: usize) -> Self {-// let size = NonZeroUsize::new(max_size).expect("max_size must be greater than 0");-// FrameCache {-// cache: Arc::new(RwLock::new(LruCache::new(size))),-// max_size,-// }-// }-//-// // Function to get or load a frame-// fn get_or_load_frame(&mut self, video_id: &str, frame_index: usize) -> FrameData {-// let entry = { self.cache.read().unwrap().contains(video_id) };-//-// if has_entry {-// let cache_clone = self.cache.clone();-// let maybe_entry = {-// let mut lock = cache_clone.read().unwrap();-// lock.get(video_id)-// };-// if let Some(entry) = maybe_entry {-// if let Some(frame) = entry.frames.get(&frame_index) {-// return FrameData {-// image: frame.image.clone(),-// };-// }-// }-// } else {-// self.cache.write().unwrap().put(-// video_id.to_string(),-// CacheEntry {-// frames: HashMap::new(),-// is_being_processed: false,-// },-// );-// }-//-// self.load_frame(&self.cache, video_id, frame_index)-// }-//-// fn load_frame(-// &self,-// cache: &Arc<RwLock<LruCache<String, CacheEntry>>>,-// video_id: &str,-// frame_index: usize,-// ) -> FrameData {-// let is_being_processed = {-// self.cache-// .read()-// .unwrap()-// .get(video_id)-// .unwrap()-// .is_being_processed-// };-// if !is_being_processed {-// let video_id_clone = video_id.to_string();-//-// let cache_clone = self.cache.clone();-// thread::spawn(move || {-// // Hold the write lock to say we're processing so we don't spawn multiple threads-// {-// cache_clone-// .write()-// .unwrap()-// .get_mut(&video_id_clone)-// .unwrap()-// .is_being_processed = true;-// }-// // Let it go as extracting frames can take a while-//-// // Call to the function to extract all frames-// let frames = extract_all_frames_from_video(&video_id_clone)-// .expect("Failed to extract frames");-//-// // Reacquire the lock to update the cache-// {-// let mut lock = cache_clone.write().unwrap();-// let mut_entry = lock.get_mut(&video_id_clone).unwrap();-//-// // Update cache with new frames-// for (index, frame) in frames.into_iter().enumerate() {-// mut_entry.frames.insert(index, FrameData { image: frame });-// }-//-// mut_entry.is_being_processed = true;-// }-// });-// }-//-// let cache_clone = self.cache.clone();-// // If the requested frame is already in the cache, return it.-// // Otherwise, extract and return the specific frame.-// let maybe_frame_data = {-// cache_clone-// .read()-// .unwrap()-// .get(video_id)-// .unwrap()-// .frames-// .get(&frame_index)-// .map(|frame| FrameData {-// image: frame.image.clone(),-// })-// };-// // Release the read-lock and return the frame, or extract the frame-//-// maybe_frame_data.unwrap_or_else(|| {-// // Extract specific frame-// let frame = extract_frames_from_video(&video_id, &[frame_index as i64])-// .expect("Failed to extract frame")-// .into_iter()-// .next()-// .unwrap();-// FrameData { image: frame }-// })-// }-// }diff --git a/screenpipe-server/src/core.rs b/screenpipe-server/src/core.rsindex cc7f3bd7b..48c59e8b5 100644--- a/screenpipe-server/src/core.rs+++ b/screenpipe-server/src/core.rs@@ -2,14 +2,13 @@ use crate::{DatabaseManager, VideoCapture};use anyhow::Result;use chrono::Utc;use crossbeam::channel::{Receiver, Sender};-use log::{debug, error, info};+use log::{debug, error, info, warn};use screenpipe_audio::{- create_whisper_channel, parse_audio_device, record_and_transcribe, AudioDevice, AudioInput,- DeviceControl, TranscriptionResult,+ create_whisper_channel, record_and_transcribe, AudioDevice, AudioInput, DeviceControl,+ TranscriptionResult,};-use std::collections::HashMap;use std::sync::atomic::{AtomicBool, Ordering};-use std::sync::{Arc, RwLock};+use std::sync::Arc;use std::thread;use std::time::Duration;use tokio::runtime::Runtime;@@ -25,14 +24,10 @@ pub async fn start_continuous_recording(fps: f64,audio_chunk_duration: Duration,full_control: std::sync::mpsc::Receiver<RecorderControl>,- enable_audio: bool,vision_control: Arc<AtomicBool>,- audio_devices_control: Arc<RwLock<HashMap<AudioDevice, Arc<DeviceControl>>>>,+ audio_devices_control_receiver: Receiver<(AudioDevice, DeviceControl)>,) -> Result<()> {info!("Recording now");- if !enable_audio {- info!("Audio recording disabled");- }let (whisper_sender, whisper_receiver) = create_whisper_channel()?;@@ -41,7 +36,6 @@ pub async fn start_continuous_recording(let is_running_video = Arc::clone(&vision_control);let is_running_audio = Arc::clone(&vision_control);- let device_controls_clone = Arc::clone(&audio_devices_control);let output_path_video = Arc::clone(&output_path);let output_path_audio = Arc::clone(&output_path);@@ -50,46 +44,41 @@ pub async fn start_continuous_recording(record_video(db_manager_video, output_path_video, fps, is_running_video).await});- let audio_handle = if enable_audio {- let handle = tokio::spawn(async move {- record_audio(- db_manager_audio,- output_path_audio,- audio_chunk_duration,- is_running_audio,- whisper_sender,- whisper_receiver,- Arc::clone(&audio_devices_control),- )- .await- });- Some(handle)- } else {- None- };+ let audio_handle = tokio::spawn(async move {+ record_audio(+ db_manager_audio,+ output_path_audio,+ audio_chunk_duration,+ is_running_audio,+ whisper_sender,+ whisper_receiver,+ audio_devices_control_receiver,+ )+ .await+ });+ // TODO// Control loop- tokio::spawn(async move {- while let Ok(ctrl) = full_control.recv() {- match ctrl {- RecorderControl::Stop => {- vision_control.store(false, Ordering::SeqCst);- control_all_devices(&device_controls_clone, RecorderControl::Stop);- }- RecorderControl::Pause => {- control_all_devices(&device_controls_clone, RecorderControl::Pause)- }- RecorderControl::Resume => {- control_all_devices(&device_controls_clone, RecorderControl::Resume)- }- }- }- });+ // let control_handle = tokio::spawn(async move {+ // while let Ok(ctrl) = full_control.recv() {+ // match ctrl {+ // RecorderControl::Stop => {+ // vision_control.store(false, Ordering::SeqCst);+ // // control_all_devices(&device_controls_clone, RecorderControl::Stop);+ // }+ // RecorderControl::Pause => {+ // // control_all_devices(&device_controls_clone, RecorderControl::Pause)+ // }+ // RecorderControl::Resume => {+ // // control_all_devices(&device_controls_clone, RecorderControl::Resume)+ // }+ // }+ // }+ // });video_handle.await??;- if let Some(handle) = audio_handle {- handle.await??;- }+ audio_handle.await??;+ // control_handle.await?;info!("Stopped recording");Ok(())@@ -102,16 +91,20 @@ async fn record_video(is_running: Arc<AtomicBool>,) -> Result<()> {let db_chunk_callback = Arc::clone(&db);+ let rt = tokio::runtime::Handle::current();let new_chunk_callback = move |file_path: &str| {- let rt = Runtime::new().expect("Failed to create runtime");- if let Err(e) = rt.block_on(db_chunk_callback.insert_video_chunk(file_path)) {- error!("Failed to insert new video chunk: {}", e);- }+ let db_chunk_callback = Arc::clone(&db_chunk_callback);+ let file_path = file_path.to_string();+ rt.spawn(async move {+ if let Err(e) = db_chunk_callback.insert_video_chunk(&file_path).await {+ error!("Failed to insert new video chunk: {}", e);+ }+ });};let video_capture = VideoCapture::new(&output_path, fps, new_chunk_callback);while is_running.load(Ordering::SeqCst) {- if let Some(frame) = video_capture.get_latest_frame() {+ if let Some(frame) = video_capture.get_latest_frame().await {match db.insert_frame().await {Ok(frame_id) => {if let Err(e) = db.insert_ocr_text(frame_id, &frame.text).await {@@ -120,14 +113,17 @@ async fn record_video(debug!("Inserted frame {} with OCR text", frame_id);}Err(e) => {- error!("Failed to insert frame: {}", e);+ warn!("Failed to insert frame: {}", e);+ // Add a small delay before retrying+ tokio::time::sleep(Duration::from_millis(100)).await;+ continue; // Skip to the next iteration}}}tokio::time::sleep(Duration::from_secs_f64(1.0 / fps)).await;}- video_capture.stop();+ video_capture.stop().await;Ok(())}@@ -138,61 +134,67 @@ async fn record_audio(is_running: Arc<AtomicBool>,whisper_sender: Sender<AudioInput>,whisper_receiver: Receiver<TranscriptionResult>,- device_controls: Arc<RwLock<HashMap<AudioDevice, Arc<DeviceControl>>>>,+ audio_devices_control_receiver: Receiver<(AudioDevice, DeviceControl)>,) -> Result<()> {let mut handles = vec![];- let device_specs: Vec<AudioDevice> = device_controls.read().unwrap().keys().cloned().collect();- for device_spec in device_specs {+ while let Ok((audio_device, device_control)) = audio_devices_control_receiver.recv() {+ info!("Received audio device: {}", &audio_device);let db_clone = Arc::clone(&db);let output_path_clone = Arc::clone(&output_path);let is_running_clone = Arc::clone(&is_running);- // let device_spec_clone = Arc::clone(&device_spec);let whisper_sender_clone = whisper_sender.clone();let whisper_receiver_clone = whisper_receiver.clone();- let device_control = Arc::clone(&device_controls.read().unwrap()[&device_spec]);-- if !device_control.is_running.load(Ordering::SeqCst) {+ if !device_control.is_running {+ info!("Device control signaled stop for device {}", &audio_device);continue;}++ let audio_device = Arc::new(audio_device);+ let device_control = Arc::new(device_control);let handle = tokio::spawn(async move {- info!("Starting audio capture thread for device: {}", &device_spec);+ let audio_device_clone = Arc::clone(&audio_device);+ let device_control_clone = Arc::clone(&device_control);+ info!(+ "Starting audio capture thread for device: {}",+ &audio_device+ );let mut iteration = 0;while is_running_clone.load(Ordering::SeqCst) {iteration += 1;info!("Starting iteration {} for device {}",- iteration, device_spec+ iteration, audio_device_clone);+ // TODO: tokiolet recording_thread = thread::spawn({- let device_spec = device_spec.clone();let output_path_clone = Arc::clone(&output_path_clone);let whisper_sender = whisper_sender_clone.clone();- let device_control_clone = Arc::clone(&device_control);-+ let audio_device_clone = audio_device_clone.clone();+ let device_control_clone = device_control_clone.clone();move || {let new_file_name = Utc::now().format("%Y-%m-%d_%H-%M-%S").to_string();let file_path = format!("{}/{}_{}.mp3",- output_path_clone, device_spec, new_file_name+ output_path_clone, audio_device_clone, new_file_name);info!("Starting record_and_transcribe for device {} (iteration {})",- device_spec, iteration+ audio_device_clone, iteration);let result = record_and_transcribe(- &device_spec,+ &audio_device_clone,chunk_duration,file_path.into(),whisper_sender,- device_control_clone,+ Arc::new(AtomicBool::new(device_control_clone.is_running)),);info!("Finished record_and_transcribe for device {} (iteration {})",- device_spec, iteration+ audio_device_clone, iteration);result}@@ -203,7 +205,7 @@ async fn record_audio(Ok(Ok(file_path)) => {info!("Recording complete for device {} (iteration {}): {:?}",- device_spec, iteration, file_path+ audio_device, iteration, file_path);let whisper_receiver = whisper_receiver_clone.clone();@@ -212,41 +214,41 @@ async fn record_audio(Ok(transcription) => {info!("Received transcription for device {} (iteration {})",- device_spec, iteration+ audio_device, iteration);process_audio_result(&db_clone, transcription).await;}Err(e) => error!("Failed to receive transcription for device {} (iteration {}): {}",- device_spec, iteration, e+ audio_device, iteration, e),}}Ok(Err(e)) => error!("Error in record_and_transcribe for device {} (iteration {}): {}",- device_spec, iteration, e+ audio_device, iteration, e),Err(e) => error!("Thread panicked for device {} (iteration {}): {:?}",- device_spec, iteration, e+ audio_device, iteration, e),}- if !device_control.is_running.load(Ordering::SeqCst) {+ if !device_control.is_running {info!("Device control signaled stop for device {} after iteration {}",- device_spec, iteration+ audio_device, iteration);break;}info!("Finished iteration {} for device {}",- iteration, &device_spec+ iteration, &audio_device);}- info!("Exiting audio capture thread for device: {}", &device_spec);+ info!("Exiting audio capture thread for device: {}", &audio_device);});handles.push(handle);@@ -293,17 +295,3 @@ async fn process_audio_result(db: &DatabaseManager, result: TranscriptionResult)),}}--pub fn control_all_devices(- device_controls: &Arc<RwLock<HashMap<AudioDevice, Arc<DeviceControl>>>>,- command: RecorderControl,-) {- let controls = device_controls.read();- for control in controls.unwrap().values() {- match command {- RecorderControl::Pause => control.is_paused.store(true, Ordering::SeqCst),- RecorderControl::Resume => control.is_paused.store(false, Ordering::SeqCst),- RecorderControl::Stop => control.is_running.store(false, Ordering::SeqCst),- }- }-}diff --git a/screenpipe-server/src/resource_monitor.rs b/screenpipe-server/src/resource_monitor.rsindex a0d59dc0c..ab90b9710 100644--- a/screenpipe-server/src/resource_monitor.rs+++ b/screenpipe-server/src/resource_monitor.rs@@ -93,6 +93,7 @@ impl ResourceMonitor {}pub fn start_monitoring(self: &Arc<Self>, interval: Duration) {let monitor = Arc::clone(self);+ // TODO tokiothread::spawn(move || {let mut sys = System::new_all();loop {diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rsindex 1c6d9f7fe..b77220ea5 100644--- a/screenpipe-server/src/server.rs+++ b/screenpipe-server/src/server.rs@@ -1,13 +1,17 @@use axum::{- extract::{Json as JsonExt, Path, Query, State},+ extract::{Json as JsonExt, Query, State},http::StatusCode,response::Json as JsonResponse,routing::{get, post},serve, Router,};+use tracing::Level;+use crate::{ContentType, DatabaseManager, SearchResult};use chrono::{DateTime, Utc};+use crossbeam::channel::Sender;use log::{error, info};+use screenpipe_audio::{AudioDevice, DeviceControl};use serde::{Deserialize, Serialize};use serde_json::json;use std::{@@ -15,24 +19,27 @@ use std::{net::SocketAddr,sync::{atomic::{AtomicBool, Ordering},- Arc, RwLock,+ Arc,},};use tokio::net::TcpListener;-use tower_http::cors::CorsLayer;--use crate::{ContentType, DatabaseManager, SearchResult};-use screenpipe_audio::{AudioDevice, DeviceControl};+use tower_http::trace::TraceLayer;+use tower_http::{+ cors::CorsLayer,+ trace::{DefaultMakeSpan, DefaultOnRequest, DefaultOnResponse},+ LatencyUnit,+};// App statepub(crate) struct AppState {db: Arc<DatabaseManager>,vision_control: Arc<AtomicBool>,- audio_devices_control: Arc<RwLock<HashMap<AudioDevice, Arc<DeviceControl>>>>,+ audio_devices_control_sender: Sender<(AudioDevice, DeviceControl)>,+ devices_status: HashMap<AudioDevice, DeviceControl>,}#[derive(Deserialize)]-struct DeviceRequest {+pub(crate) struct DeviceRequest {device_id: String,}@@ -66,9 +73,12 @@ where#[derive(Deserialize)]struct DateRangeQuery {+ #[allow(dead_code)] // TODOstart_date: Option<DateTime<Utc>>,+ #[allow(dead_code)]end_date: Option<DateTime<Utc>>,#[serde(flatten)]+ #[allow(dead_code)]pagination: PaginationQuery,}@@ -112,7 +122,7 @@ struct AudioContent {}#[derive(Serialize)]-struct DeviceStatus {+pub(crate) struct DeviceStatus {id: String,is_running: bool,}@@ -186,8 +196,6 @@ pub(crate) async fn start_device(State(state): State<Arc<AppState>>,JsonExt(payload): JsonExt<DeviceRequest>,) -> Result<JsonResponse<DeviceStatus>, (StatusCode, JsonResponse<serde_json::Value>)> {- let device_controls = state.audio_devices_control.read().unwrap();-// Create an AudioDevice from the device_id stringlet audio_device = match AudioDevice::from_name(&payload.device_id) {Ok(device) => device,@@ -199,18 +207,25 @@ pub(crate) async fn start_device(}};- if let Some(device_control) = device_controls.get(&audio_device) {- device_control.is_paused.store(false, Ordering::SeqCst);- device_control.is_running.store(true, Ordering::SeqCst);- Ok(JsonResponse(DeviceStatus {- id: payload.device_id,- is_running: true,- }))- } else {+ let device_control = DeviceControl {+ is_running: true,+ is_paused: false,+ };++ if let Err(e) = state+ .audio_devices_control_sender+ .send((audio_device, device_control))+ {+ error!("failed to start audio device: {}", e);Err((StatusCode::NOT_FOUND,JsonResponse(json!({"error": "Device not found"})),))+ } else {+ Ok(JsonResponse(DeviceStatus {+ id: payload.device_id,+ is_running: true,+ }))}}@@ -218,7 +233,6 @@ pub(crate) async fn stop_device(State(state): State<Arc<AppState>>,JsonExt(payload): JsonExt<DeviceRequest>,) -> Result<JsonResponse<DeviceStatus>, (StatusCode, JsonResponse<serde_json::Value>)> {- let device_controls = state.audio_devices_control.read().unwrap();// Create an AudioDevice from the device_id stringlet audio_device = match AudioDevice::from_name(&payload.device_id) {Ok(device) => device,@@ -229,18 +243,25 @@ pub(crate) async fn stop_device())}};- if let Some(device_control) = device_controls.get(&audio_device) {- device_control.is_running.store(false, Ordering::SeqCst);- device_control.is_paused.store(true, Ordering::SeqCst);- Ok(JsonResponse(DeviceStatus {- id: payload.device_id,- is_running: false,- }))- } else {+ let device_control = DeviceControl {+ is_running: false,+ is_paused: false,+ };++ if let Err(e) = state+ .audio_devices_control_sender+ .send((audio_device, device_control))+ {+ error!("failed to stop audio device: {}", e);Err((StatusCode::NOT_FOUND,JsonResponse(json!({"error": "Device not found"})),))+ } else {+ Ok(JsonResponse(DeviceStatus {+ id: payload.device_id,+ is_running: false,+ }))}}@@ -269,7 +290,6 @@ pub(crate) async fn get_device_status(State(state): State<Arc<AppState>>,JsonExt(payload): JsonExt<DeviceRequest>,) -> Result<JsonResponse<DeviceStatus>, (StatusCode, JsonResponse<serde_json::Value>)> {- let device_controls = state.audio_devices_control.read().unwrap();// Create an AudioDevice from the device_id stringlet audio_device = match AudioDevice::from_name(&payload.device_id) {Ok(device) => device,@@ -280,10 +300,10 @@ pub(crate) async fn get_device_status())}};- if let Some(device_control) = device_controls.get(&audio_device) {+ if let Some(device_control) = state.devices_status.get(&audio_device) {Ok(JsonResponse(DeviceStatus {id: payload.device_id,- is_running: device_control.is_running.load(Ordering::SeqCst),+ is_running: device_control.is_running,}))} else {Err((@@ -296,12 +316,12 @@ pub(crate) async fn get_device_status(pub(crate) async fn get_devices(State(state): State<Arc<AppState>>,) -> JsonResponse<Vec<DeviceStatus>> {- let device_controls = state.audio_devices_control.read().unwrap();- let devices = device_controls+ let devices = state+ .devices_status.iter()- .map(|(id, _)| DeviceStatus {- id: id.to_string(),- is_running: false,+ .map(|(audio_device, device_control)| DeviceStatus {+ id: audio_device.to_string(),+ is_running: device_control.is_running,}).collect();JsonResponse(devices)@@ -331,7 +351,7 @@ pub struct Server {db: Arc<DatabaseManager>,addr: SocketAddr,vision_control: Arc<AtomicBool>,- audio_devices_control: Arc<RwLock<HashMap<AudioDevice, Arc<DeviceControl>>>>,+ audio_devices_control_sender: Sender<(AudioDevice, DeviceControl)>,}impl Server {@@ -339,36 +359,57 @@ impl Server {db: Arc<DatabaseManager>,addr: SocketAddr,vision_control: Arc<AtomicBool>,- audio_devices_control: Arc<RwLock<HashMap<AudioDevice, Arc<DeviceControl>>>>,+ audio_devices_control_sender: Sender<(AudioDevice, DeviceControl)>,) -> Self {Server {db,addr,vision_control,- audio_devices_control,+ audio_devices_control_sender,}}- pub async fn start(self) -> Result<(), std::io::Error> {+ pub async fn start(+ self,+ device_status: HashMap<AudioDevice, DeviceControl>,+ ) -> Result<(), std::io::Error> {+ // TODO could init w audio deviceslet app_state = Arc::new(AppState {db: self.db,vision_control: self.vision_control,- audio_devices_control: self.audio_devices_control,+ audio_devices_control_sender: self.audio_devices_control_sender,+ devices_status: device_status.clone(),});+ // https://github.com/tokio-rs/consolelet app = Router::new().route("/search", get(search))- .route("/device/start", post(start_device))- .route("/device/stop", post(stop_device))- .route("/device/status", post(get_device_status))- .route("/device/list", get(get_devices))- .route("/recording/start", post(start_recording))- .route("/recording/stop", post(stop_recording))- .route("/recording/status", get(get_recording_status))+ .route("/audio/start", post(start_device))+ .route("/audio/stop", post(stop_device))+ .route("/audio/status", post(get_device_status))+ .route("/audio/list", get(get_devices))+ .route("/vision/start", post(start_recording))+ .route("/vision/stop", post(stop_recording))+ .route("/vision/status", get(get_recording_status)).layer(CorsLayer::permissive())+ .layer(+ // https://github.com/tokio-rs/axum/blob/main/examples/tracing-aka-logging/src/main.rs+ TraceLayer::new_for_http()+ .make_span_with(DefaultMakeSpan::new().include_headers(true))+ .on_request(DefaultOnRequest::new().level(Level::INFO))+ .on_response(+ DefaultOnResponse::new()+ .level(Level::INFO)+ .latency_unit(LatencyUnit::Micros),+ ),+ ).with_state(app_state);info!("Starting server on {}", self.addr);+ info!("Audio devices:");+ for (device, control) in device_status.iter() {+ info!("{}: {}", device, control.is_running);+ }match serve(TcpListener::bind(self.addr).await?, app.into_make_service()).await {Ok(_) => {@@ -403,22 +444,29 @@ impl Server {// # curl "http://localhost:3030/search?limit=5&offset=0"// # 7. Start a device-// # curl -X POST "http://localhost:3030/device/start" -H "Content-Type: application/json" -d '{"device_id": "device1"}'+// # curl -X POST "http://localhost:3030/audio/start" -H "Content-Type: application/json" -d '{"device_id": "device1"}'// # 8. Stop a device-// # curl -X POST "http://localhost:3030/device/stop" -H "Content-Type: application/json" -d '{"device_id": "device1"}'+// # curl -X POST "http://localhost:3030/audio/stop" -H "Content-Type: application/json" -d '{"device_id": "device1"}'// # 9. Get device status-// # curl "http://localhost:3030/device/status" -H "Content-Type: application/json" -d '{"device_id": "device1"}'+// # curl "http://localhost:3030/audio/status" -H "Content-Type: application/json" -d '{"device_id": "device1"}'// list devices-// # curl "http://localhost:3030/device/list"+// # curl "http://localhost:3030/audio/list" | jq++// start the first device in the list that has "Microphone (input)"" in the id+// 1. list+// 2. start the first device in the list that has "Microphone (input)"" in the id+// DEVICE=$(curl "http://localhost:3030/audio/list" | grep "Microphone (input)" | jq -r '.[0].id')+// curl -X POST "http://localhost:3030/audio/start" -H "Content-Type: application/json" -d '{"device_id": "$DEVICE"}' | jq+// curl -X POST "http://localhost:3030/audio/stop" -H "Content-Type: application/json" -d '{"device_id": "$DEVICE"}' | jq// # 10. Start recording-// # curl -X POST "http://localhost:3030/recording/start"+// # curl -X POST "http://localhost:3030/vision/start"// # 11. Stop recording-// # curl -X POST "http://localhost:3030/recording/stop"+// # curl -X POST "http://localhost:3030/vision/stop"// # 12. Get recording status-// # curl "http://localhost:3030/recording/status"+// # curl "http://localhost:3030/vision/status"diff --git a/screenpipe-server/src/video.rs b/screenpipe-server/src/video.rsindex 74d5d2341..8bfca26e8 100644--- a/screenpipe-server/src/video.rs+++ b/screenpipe-server/src/video.rs@@ -7,12 +7,17 @@ use image::{DynamicImage, ImageBuffer, Rgb};use log::{debug, error, info, warn};use screenpipe_vision::{continuous_capture, CaptureResult, ControlMessage};use std::collections::{BTreeSet, VecDeque};-use std::io::BufRead;use std::io::Write;use std::path::PathBuf;-use std::process::{Command, Stdio};-use std::sync::mpsc::{channel, Receiver, Sender};-use std::sync::{Arc, Mutex};+use std::process::Stdio;+use tokio::io::AsyncWriteExt;+use tokio::io::{AsyncBufReadExt, BufReader};+use tokio::process::{Child, ChildStdin, Command};++use std::sync::Arc;+use tokio::sync::mpsc::{channel, Receiver, Sender};+use tokio::sync::Mutex;+use std::time::Duration;use std::{env, thread};use threadpool::ThreadPool;@@ -118,7 +123,7 @@ fn seek_to_frame(pub struct VideoCapture {control_tx: Sender<ControlMessage>,frame_queue: Arc<Mutex<VecDeque<CaptureResult>>>,- ffmpeg_handle: Arc<Mutex<Option<std::process::Child>>>,+ ffmpeg_handle: Arc<Mutex<Option<Child>>>,is_running: Arc<Mutex<bool>>,}@@ -129,7 +134,7 @@ impl VideoCapture {new_chunk_callback: impl Fn(&str) + Send + Sync + 'static,) -> Self {info!("Starting new video capture");- let (control_tx, control_rx) = channel();+ let (control_tx, mut control_rx) = channel(512);let frame_queue = Arc::new(Mutex::new(VecDeque::new()));let ffmpeg_handle = Arc::new(Mutex::new(None));let is_running = Arc::new(Mutex::new(true));@@ -138,22 +143,26 @@ impl VideoCapture {let capture_frame_queue = frame_queue.clone();let capture_thread_is_running = is_running.clone();- let (result_sender, result_receiver) = channel();- let _capture_thread = thread::spawn(move || {+ let (result_sender, mut result_receiver) = channel(512);+ let _capture_thread = tokio::spawn(async move {continuous_capture(- control_rx,+ &mut control_rx,result_sender,Duration::from_secs_f64(1.0 / fps),- );+ )+ .await;});info!("Started capture thread");// Spawn another thread to handle receiving and queueing the results- let _queue_thread = thread::spawn(move || {- while *capture_thread_is_running.lock().unwrap() {- if let Ok(result) = result_receiver.recv() {- capture_frame_queue.lock().unwrap().push_back(result);+ let _queue_thread = tokio::spawn(async move {+ while *capture_thread_is_running.lock().await {+ if let Some(result) = result_receiver.recv().await {+ debug!("Received result from capture thread: frame_number: {:?}", result.frame_number);+ debug!("Received result from capture thread: timestamp: {:?}", result.timestamp);+ // debug!("Received result from capture thread: text: {:?}", result.text);+ capture_frame_queue.lock().await.push_back(result);}}});@@ -161,14 +170,15 @@ impl VideoCapture {let video_frame_queue = frame_queue.clone();let video_thread_is_running = is_running.clone();let output_path = output_path.to_string();- let _video_thread = thread::spawn(move || {+ let _video_thread = tokio::spawn(async move {save_frames_as_video(&video_frame_queue,&output_path,fps,video_thread_is_running,- new_chunk_callback_clone.as_ref(),- );+ new_chunk_callback_clone,+ )+ .await;});VideoCapture {@@ -179,58 +189,60 @@ impl VideoCapture {}}- pub fn pause(&self) {- self.control_tx.send(ControlMessage::Pause).unwrap();+ pub async fn pause(&self) {+ self.control_tx.send(ControlMessage::Pause).await.unwrap();}- pub fn resume(&self) {- self.control_tx.send(ControlMessage::Resume).unwrap();+ pub async fn resume(&self) {+ self.control_tx.send(ControlMessage::Resume).await.unwrap();}- pub fn stop(&self) {- self.control_tx.send(ControlMessage::Stop).unwrap();- *self.is_running.lock().unwrap() = false;- if let Some(mut child) = self.ffmpeg_handle.lock().unwrap().take() {- child.wait().expect("Failed to wait for ffmpeg process");+ pub async fn stop(&self) {+ self.control_tx.send(ControlMessage::Stop).await.unwrap();+ *self.is_running.lock().await = false;+ if let Some(mut child) = self.ffmpeg_handle.lock().await.take() {+ child+ .wait()+ .await+ .expect("Failed to wait for ffmpeg process");}}- pub fn get_latest_frame(&self) -> Option<CaptureResult> {- self.frame_queue.lock().unwrap().pop_front()+ pub async fn get_latest_frame(&self) -> Option<CaptureResult> {+ self.frame_queue.lock().await.pop_front()}}-fn save_frames_as_video(+async fn save_frames_as_video(frame_queue: &Arc<Mutex<VecDeque<CaptureResult>>>,output_path: &str,fps: f64,is_running: Arc<Mutex<bool>>,- new_chunk_callback: &dyn Fn(&str),+ new_chunk_callback: Arc<dyn Fn(&str) + Send + Sync>,) {+ debug!("Starting save_frames_as_video function");let frames_per_video = 30; // Adjust this value as neededlet 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();+ let (sender, mut receiver): (Sender<Vec<u8>>, Receiver<Vec<u8>>) = channel(512);let sender = Arc::new(sender);- let mut current_ffmpeg: Option<std::process::Child> = None;- let mut current_stdin: Option<std::process::ChildStdin> = None;+ let mut current_ffmpeg: Option<Child> = None;+ let mut current_stdin: Option<ChildStdin> = None;- while *is_running.lock().unwrap() {+ while *is_running.lock().await {if frame_count % frames_per_video == 0 || current_ffmpeg.is_none() {+ debug!("Starting new FFmpeg process");// Close previous FFmpeg process if existsif let Some(mut child) = current_ffmpeg.take() {drop(current_stdin.take()); // Ensure stdin is closed- child.wait().expect("ffmpeg process failed");+ child.wait().await.expect("ffmpeg process failed");}// Wait for at least one frame before starting a new FFmpeg processlet first_frame = loop {- if let Some(result) = frame_queue.lock().unwrap().pop_front() {+ if let Some(result) = frame_queue.lock().await.pop_front() {+ debug!("Got first frame for new chunk");break result;}- thread::sleep(Duration::from_millis(10));+ tokio::time::sleep(Duration::from_millis(10)).await;};// Encode the first frame@@ -246,7 +258,7 @@ fn save_frames_as_video(let output_file = format!("{}/{}.mp4", output_path, formatted_time);// Call the callback with the new video chunk file path- new_chunk_callback(&output_file); // TODO better error handling+ new_chunk_callback(&output_file);let mut child = start_ffmpeg_process(&output_file, fps);let mut stdin = child.stdin.take().expect("Failed to open stdin");@@ -255,45 +267,52 @@ fn save_frames_as_video(// Write the first frame to FFmpegstdin.write_all(&buffer)+ .await.expect("Failed to write first frame to ffmpeg");frame_count += 1;- // Spawn a thread to log FFmpeg's stderr- thread::spawn(move || {- let reader = std::io::BufReader::new(stderr);- for line in reader.lines() {- if let Ok(line) = line {- debug!("FFmpeg: {}", line);- }+ // Spawn a task to log FFmpeg's stderr+ tokio::spawn(async move {+ let reader = BufReader::new(stderr);+ let mut lines = reader.lines();+ while let Ok(Some(line)) = lines.next_line().await {+ debug!("FFmpeg: {}", line);}});current_ffmpeg = Some(child);current_stdin = Some(stdin);+ debug!("New FFmpeg process started for file: {}", output_file);}- if let Some(result) = frame_queue.lock().unwrap().pop_front() {+ if let Some(result) = frame_queue.lock().await.pop_front() {+ debug!("Processing frame {}", frame_count + 1);let sender = Arc::clone(&sender);- pool.execute(move || {++ tokio::spawn(async move {let mut buffer = Vec::new();match result.image.write_to(&mut std::io::Cursor::new(&mut buffer), ImageFormat::Png){Ok(_) => {- sender.send(buffer).expect("Failed to send encoded frame");+ sender+ .send(buffer)+ .await+ .expect("Failed to send encoded frame");}Err(e) => error!("Failed to encode image as PNG: {}", e),}});} else {- thread::sleep(Duration::from_millis(10));+ // debug!("No frames in queue, waiting...");+ tokio::time::sleep(Duration::from_millis(10)).await;}// Write encoded frames to FFmpeg- for buffer in receiver.try_iter() {+ while let Ok(buffer) = receiver.try_recv() {if let Some(stdin) = current_stdin.as_mut() {- if let Err(e) = stdin.write_all(&buffer) {+ if let Err(e) = stdin.write_all(buffer.as_slice()).await {error!("Failed to write frame to ffmpeg: {}", e);break;}@@ -302,18 +321,24 @@ fn save_frames_as_video(// Flush every secondif frame_count % fps as usize == 0 {- if let Err(e) = stdin.flush() {+ debug!("Flushing FFmpeg input");+ if let Err(e) = stdin.flush().await {error!("Failed to flush FFmpeg input: {}", e);}}}}++ // Yield to other tasks periodically+ if frame_count % 100 == 0 {+ tokio::task::yield_now().await;+ }}// Close the final FFmpeg processif let Some(mut child) = current_ffmpeg.take() {drop(current_stdin.take()); // Ensure stdin is closed- child.wait().expect("ffmpeg process failed");+ child.wait().await.expect("ffmpeg process failed");}}@@ -341,7 +366,8 @@ fn get_ffmpeg_path() -> PathBuf {}}-fn start_ffmpeg_process(output_file: &str, fps: f64) -> std::process::Child {+// TODO: use tokio::process::Command instead+fn start_ffmpeg_process(output_file: &str, fps: f64) -> Child {// overrriding fps with max fps if over the max and warning userlet mut fps = fps;if fps > MAX_FPS {diff --git a/screenpipe-server/tests/start_stop.rs b/screenpipe-server/tests/start_stop.rsdeleted file mode 100644index d5449a567..000000000--- a/screenpipe-server/tests/start_stop.rs+++ /dev/null@@ -1,208 +0,0 @@-use axum::{- body::Body,- http::{Request, StatusCode},- routing::Router,-};-use screenpipe_server::RecorderControl;-use screenpipe_server::{- get_device_status, get_recording_status, start_device, start_recording, stop_device,- stop_recording, AppState,-};-use serde_json::json;-use std::collections::HashMap;-use std::sync::atomic::{AtomicBool, Ordering};-use std::sync::{Arc, RwLock};-use tower::util::ServiceExt;--// Mock DeviceControl for testing-struct MockDeviceControl {- is_running: AtomicBool,- sender: Option<std::sync::mpsc::Sender<RecorderControl>>,-}--impl DeviceControl {- fn new() -> Self {- let (sender, _receiver) = std::sync::mpsc::channel();- Self {- is_running: AtomicBool::new(false),- sender: Some(sender),- }- }-- fn is_running(&self) -> bool {- self.is_running.load(Ordering::SeqCst)- }-- fn sender(&self) -> Option<&std::sync::mpsc::Sender<RecorderControl>> {- self.sender.as_ref()- }-}--fn create_test_app() -> Router {- let db = Arc::new(DatabaseManager::new("test_db_url").unwrap());- let is_running = Arc::new(AtomicBool::new(false));- let device_controls = Arc::new(RwLock::new(HashMap::new()));- device_controls- .write()- .unwrap()- .insert("test_device".to_string(), Arc::new(DeviceControl::new()));-- let app_state = Arc::new(AppState {- db,- is_running,- device_controls,- });-- Router::new()- .route("/device/:id/start", axum::routing::post(start_device))- .route("/device/:id/stop", axum::routing::post(stop_device))- .route("/device/:id/status", axum::routing::get(get_device_status))- .route("/recording/start", axum::routing::post(start_recording))- .route("/recording/stop", axum::routing::post(stop_recording))- .route(- "/recording/status",- axum::routing::get(get_recording_status),- )- .with_state(app_state)-}--#[tokio::test]-async fn test_start_device() {- let app = create_test_app();-- let response = app- .oneshot(- Request::builder()- .method("POST")- .uri("/device/test_device/start")- .body(Body::empty())- .unwrap(),- )- .await- .unwrap();-- assert_eq!(response.status(), StatusCode::OK);-- let body = hyper::body::to_bytes(response.into_body()).await.unwrap();- let json: serde_json::Value = serde_json::from_slice(&body).unwrap();-- assert_eq!(json["id"], "test_device");- assert_eq!(json["is_running"], true);-}--#[tokio::test]-async fn test_stop_device() {- let app = create_test_app();-- let response = app- .oneshot(- Request::builder()- .method("POST")- .uri("/device/test_device/stop")- .body(Body::empty())- .unwrap(),- )- .await- .unwrap();-- assert_eq!(response.status(), StatusCode::OK);-- let body = hyper::body::to_bytes(response.into_body()).await.unwrap();- let json: serde_json::Value = serde_json::from_slice(&body).unwrap();-- assert_eq!(json["id"], "test_device");- assert_eq!(json["is_running"], false);-}--#[tokio::test]-async fn test_get_device_status() {- let app = create_test_app();-- let response = app- .oneshot(- Request::builder()- .method("GET")- .uri("/device/test_device/status")- .body(Body::empty())- .unwrap(),- )- .await- .unwrap();-- assert_eq!(response.status(), StatusCode::OK);-- let body = hyper::body::to_bytes(response.into_body()).await.unwrap();- let json: serde_json::Value = serde_json::from_slice(&body).unwrap();-- assert_eq!(json["id"], "test_device");- assert!(json["is_running"].is_boolean());-}--#[tokio::test]-async fn test_start_recording() {- let app = create_test_app();-- let response = app- .oneshot(- Request::builder()- .method("POST")- .uri("/recording/start")- .body(Body::empty())- .unwrap(),- )- .await- .unwrap();-- assert_eq!(response.status(), StatusCode::OK);-- let body = hyper::body::to_bytes(response.into_body()).await.unwrap();- let json: serde_json::Value = serde_json::from_slice(&body).unwrap();-- assert_eq!(json["is_running"], true);-}--#[tokio::test]-async fn test_stop_recording() {- let app = create_test_app();-- let response = app- .oneshot(- Request::builder()- .method("POST")- .uri("/recording/stop")- .body(Body::empty())- .unwrap(),- )- .await- .unwrap();-- assert_eq!(response.status(), StatusCode::OK);-- let body = hyper::body::to_bytes(response.into_body()).await.unwrap();- let json: serde_json::Value = serde_json::from_slice(&body).unwrap();-- assert_eq!(json["is_running"], false);-}--#[tokio::test]-async fn test_get_recording_status() {- let app = create_test_app();-- let response = app- .oneshot(- Request::builder()- .method("GET")- .uri("/recording/status")- .body(Body::empty())- .unwrap(),- )- .await- .unwrap();-- assert_eq!(response.status(), StatusCode::OK);-- let body = hyper::body::to_bytes(response.into_body()).await.unwrap();- let json: serde_json::Value = serde_json::from_slice(&body).unwrap();-- assert!(json["is_running"].is_boolean());-}diff --git a/screenpipe-vision/Cargo.toml b/screenpipe-vision/Cargo.tomlindex 6f2c01047..97a008699 100644--- a/screenpipe-vision/Cargo.toml+++ b/screenpipe-vision/Cargo.toml@@ -21,6 +21,9 @@ xcap = "0.0.10"threadpool = "1.8.1"num_cpus = "1.0"+# async+tokio = { workspace = true }+# Image processingimage = "0.25.0"diff --git a/screenpipe-vision/src/bin/screenpipe-vision.rs b/screenpipe-vision/src/bin/screenpipe-vision.rsindex 61bfad473..4a682bcf7 100644--- a/screenpipe-vision/src/bin/screenpipe-vision.rs+++ b/screenpipe-vision/src/bin/screenpipe-vision.rs@@ -1,37 +1,33 @@-use std::thread;--use image::GenericImageView;use screenpipe_vision::{continuous_capture, ControlMessage};use std::time::Duration;+use tokio::sync::mpsc::channel;-fn main() {- use std::sync::mpsc::channel;-- let (control_tx, control_rx) = channel();- let (result_tx, result_rx) = channel();+#[tokio::main]+async fn main() {+ let (control_tx, mut control_rx) = channel(512);+ let (result_tx, mut result_rx) = channel(512);- let capture_thread = thread::spawn(move || {- continuous_capture(control_rx, result_tx, Duration::from_secs(1));+ let capture_thread = tokio::spawn(async move {+ continuous_capture(&mut control_rx, result_tx, Duration::from_secs(1)).await});// Example: Process results for 10 seconds, then pause for 5 seconds, then stoplet start_time = std::time::Instant::now();loop {- if let Ok(result) = result_rx.try_recv() {- println!("Captured image size: {:?}", result.image.dimensions());+ if let Some(result) = result_rx.recv().await {println!("OCR Text length: {}", result.text.len());}let elapsed = start_time.elapsed();if elapsed >= Duration::from_secs(10) && elapsed < Duration::from_secs(15) {- control_tx.send(ControlMessage::Pause).unwrap();+ control_tx.send(ControlMessage::Pause).await.unwrap();} else if elapsed >= Duration::from_secs(15) {- control_tx.send(ControlMessage::Stop).unwrap();+ control_tx.send(ControlMessage::Stop).await.unwrap();break;}- thread::sleep(Duration::from_millis(100));+ tokio::time::sleep(Duration::from_millis(100)).await;}- capture_thread.join().unwrap();+ capture_thread.await.unwrap();}diff --git a/screenpipe-vision/src/core.rs b/screenpipe-vision/src/core.rsindex e4b6ac9aa..b0e19b036 100644--- a/screenpipe-vision/src/core.rs+++ b/screenpipe-vision/src/core.rs@@ -1,17 +1,18 @@use image::DynamicImage;-use log::info;+use log::{debug, error, info, warn};use rusty_tesseract::{Args, Image};-use threadpool::ThreadPool;+use tokio::sync::broadcast;+use tokio::sync::broadcast::error::RecvError;use xcap::Monitor;use std::collections::HashMap;-use std::hash::DefaultHasher;-use std::hash::Hash;-use std::hash::Hasher;-use std::sync::mpsc::{Receiver, Sender};-use std::sync::{Arc, Mutex};-use std::thread;-use std::time::Duration;+use std::hash::{DefaultHasher, Hash, Hasher};+use std::sync::Arc;+use std::time::{Duration, Instant};+use tokio::sync::mpsc::{Receiver, Sender};+use tokio::sync::Mutex;+use tokio::task;+pub enum ControlMessage {Pause,Resume,@@ -21,12 +22,16 @@ pub enum ControlMessage {pub struct CaptureResult {pub image: Arc<DynamicImage>,pub text: String,+ pub frame_number: u64,+ pub timestamp: Instant,}-const MAX_THREADS: usize = 8; // Adjust based on your needs+const MAX_THREADS: usize = 4; // Adjust based on your needs+const MAX_QUEUE_SIZE: usize = 6; // Maximum number of frames to keep in the queue. 64/8 ocr task = 8+// seems kinda counter intuitive but less threads for OCR = more CPU usage = less frame dropping-pub fn continuous_capture(- control_rx: Receiver<ControlMessage>,+pub async fn continuous_capture(+ control_rx: &mut Receiver<ControlMessage>,result_tx: Sender<CaptureResult>,interval: Duration,) {@@ -36,71 +41,160 @@ pub fn continuous_capture(let pool_size = (cpu_count as f32 * 1.2) as usize;let pool_size = std::cmp::min(pool_size, MAX_THREADS);- info!("Will use {} threads for OCR", pool_size);-- let ocr_pool = ThreadPool::new(pool_size);+ info!("Will use {} tasks for OCR", pool_size);let is_paused = Arc::new(Mutex::new(false));let should_stop = Arc::new(Mutex::new(false));let cache = Arc::new(Mutex::new(HashMap::<u64, String>::new()));- loop {++ let (ocr_tx, _) =+ broadcast::channel::<(Arc<DynamicImage>, u64, u64, Instant, Sender<CaptureResult>)>(64);+ let ocr_tx = Arc::new(ocr_tx);++ // Spawn OCR tasks+ let ocr_handles: Vec<_> = (0..pool_size)+ .map(|id| {+ let mut ocr_rx = ocr_tx.subscribe();+ let cache = Arc::clone(&cache);+ let should_stop = Arc::clone(&should_stop);+ task::spawn(async move {+ while !*should_stop.lock().await {+ match ocr_rx.recv().await {+ Ok((image_arc, image_hash, frame_number, timestamp, result_tx)) => {+ // Only process if the frame number modulo pool_size equals this task's id+ if frame_number % pool_size as u64 == id as u64 {+ let start_time = Instant::now();+ let mut cache = cache.lock().await;+ let text = if let Some(cached_text) = cache.get(&image_hash) {+ cached_text.clone()+ } else {+ let new_text = perform_ocr(&image_arc);+ cache.insert(image_hash, new_text.clone());+ new_text+ };++ if let Err(e) = result_tx+ .send(CaptureResult {+ image: image_arc.into(),+ text,+ frame_number,+ timestamp,+ })+ .await+ {+ error!("Failed to send OCR result: {}", e);+ }+ let duration = start_time.elapsed();+ debug!(+ "OCR task {} processed frame {} in {:?}",+ id, frame_number, duration+ );+ }+ }+ Err(e) => match e {+ RecvError::Lagged(_) => {+ debug!("OCR task {} lagged behind: {}", id, e);+ }+ _ => {+ error!("OCR channel error for task {}: {}", id, e);+ break;+ }+ },+ }+ }+ })+ })+ .collect();++ let mut frame_counter: u64 = 0;+ let start_time = Instant::now();+ let mut last_processed_frame = 0;++ while !*should_stop.lock().await {// Check for control messagesif let Ok(message) = control_rx.try_recv() {match message {- ControlMessage::Pause => *is_paused.lock().unwrap() = true,- ControlMessage::Resume => *is_paused.lock().unwrap() = false,+ ControlMessage::Pause => *is_paused.lock().await = true,+ ControlMessage::Resume => *is_paused.lock().await = false,ControlMessage::Stop => {- *should_stop.lock().unwrap() = true;+ *should_stop.lock().await = true;break;}}}- if *is_paused.lock().unwrap() {- thread::sleep(Duration::from_millis(100));+ if *is_paused.lock().await {+ tokio::time::sleep(Duration::from_millis(100)).await;continue;}// Capture screenshot+ let capture_start = Instant::now();let buffer = monitor.capture_image().unwrap();let image = DynamicImage::ImageRgba8(buffer);+ let capture_duration = capture_start.elapsed();// Generate hash for the imagelet image_hash = calculate_hash(&image);- // Clone necessary values for the OCR thread+ // Clone necessary values for the OCR tasklet result_tx_clone = result_tx.clone();let image_arc = Arc::new(image);- let cache_clone = Arc::clone(&cache);-- // Perform OCR in a separate thread- ocr_pool.execute(move || {- let mut cache = cache_clone.lock().unwrap();- let text = if let Some(cached_text) = cache.get(&image_hash) {- cached_text.clone()- } else {- let new_text = perform_ocr(&image_arc);- cache.insert(image_hash, new_text.clone());- new_text- };-- result_tx_clone- .send(CaptureResult {- image: image_arc,- text,- })- .unwrap();- });-- thread::sleep(interval);-- if *should_stop.lock().unwrap() {- break;++ // Check if we need to drop this frame+ let queue_size = ocr_tx.receiver_count() as u64;+ // debug!("OCR queue size: {}", queue_size);+ if queue_size >= MAX_QUEUE_SIZE as u64 {+ let frames_to_skip = queue_size - MAX_QUEUE_SIZE as u64 + 1;+ if frame_counter - last_processed_frame <= frames_to_skip {+ debug!("Dropping frame {} due to OCR backlog", frame_counter);+ frame_counter += 1;+ continue;+ }+ }++ // Send image for OCR processing+ let send_start = Instant::now();+ if let Err(e) = ocr_tx.send((+ image_arc,+ image_hash,+ frame_counter,+ capture_start,+ result_tx_clone,+ )) {+ error!("Failed to send image for OCR processing: {}", e);+ } else {+ last_processed_frame = frame_counter;}+ let send_duration = send_start.elapsed();++ frame_counter += 1;+ debug!(+ "Frame {}: Capture time: {:?}, Send time: {:?}, Receiver count: {}",+ frame_counter,+ capture_duration,+ send_duration,+ ocr_tx.receiver_count()+ );++ tokio::time::sleep(interval).await;}- ocr_pool.join();-}+ // Signal OCR tasks to stop+ *should_stop.lock().await = true;+ // Wait for all OCR tasks to complete+ for handle in ocr_handles {+ handle.await.unwrap();+ }++ let total_duration = start_time.elapsed();+ info!(+ "Capture completed. Total frames: {}, Total time: {:?}, Avg FPS: {:.2}",+ frame_counter,+ total_duration,+ frame_counter as f64 / total_duration.as_secs_f64()+ );+}fn calculate_hash(image: &DynamicImage) -> u64 {let mut hasher = DefaultHasher::new();image.as_bytes().hash(&mut hasher);