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
[looking for testers urgently] start and stop vision device on demand through /vision/start (#1237)
Louis Beaumont7d31420a4f61
diff --git a/screenpipe-audio/src/bin/screenpipe-audio-forever.rs b/screenpipe-audio/src/bin/screenpipe-audio-forever.rsindex 073919061..029d56d2b 100644--- a/screenpipe-audio/src/bin/screenpipe-audio-forever.rs+++ b/screenpipe-audio/src/bin/screenpipe-audio-forever.rs@@ -1,5 +1,6 @@use anyhow::{anyhow, Result};use clap::Parser;+use dashmap::DashMap;use log::info;use screenpipe_audio::create_whisper_channel;use screenpipe_audio::default_input_device;@@ -8,10 +9,10 @@ use screenpipe_audio::list_audio_devices;use screenpipe_audio::parse_audio_device;use screenpipe_audio::record_and_transcribe;use screenpipe_audio::vad_engine::VadSensitivity;-use screenpipe_audio::AudioDevice;use screenpipe_audio::AudioStream;use screenpipe_audio::AudioTranscriptionEngine;use screenpipe_audio::VadEngineEnum;+use screenpipe_core::AudioDevice;use screenpipe_core::Language;use std::path::PathBuf;use std::sync::atomic::AtomicBool;@@ -88,14 +89,14 @@ async fn main() -> Result<()> {}let chunk_duration = Duration::from_secs_f32(args.audio_chunk_duration);- let (whisper_sender, whisper_receiver, _) = create_whisper_channel(+ let (whisper_sender, whisper_receiver) = create_whisper_channel(Arc::new(AudioTranscriptionEngine::WhisperDistilLargeV3),VadEngineEnum::Silero, // Or VadEngineEnum::WebRtc, hardcoded for nowargs.deepgram_api_key,&PathBuf::from("output.mp4"),VadSensitivity::Medium,languages,- None,+ DashMap::new(),).await?;diff --git a/screenpipe-audio/src/bin/screenpipe-audio.rs b/screenpipe-audio/src/bin/screenpipe-audio.rsindex 22c3222b7..a05b459cd 100644--- a/screenpipe-audio/src/bin/screenpipe-audio.rs+++ b/screenpipe-audio/src/bin/screenpipe-audio.rs@@ -1,5 +1,6 @@use anyhow::{anyhow, Result};use clap::Parser;+use dashmap::DashMap;use log::info;use screenpipe_audio::create_whisper_channel;use screenpipe_audio::default_input_device;@@ -8,10 +9,10 @@ use screenpipe_audio::list_audio_devices;use screenpipe_audio::parse_audio_device;use screenpipe_audio::record_and_transcribe;use screenpipe_audio::vad_engine::VadSensitivity;-use screenpipe_audio::AudioDevice;use screenpipe_audio::AudioStream;use screenpipe_audio::AudioTranscriptionEngine;use screenpipe_audio::VadEngineEnum;+use screenpipe_core::AudioDevice;use screenpipe_core::Language;use std::path::PathBuf;use std::sync::atomic::AtomicBool;@@ -92,14 +93,14 @@ async fn main() -> Result<()> {let chunk_duration = Duration::from_secs(10);let output_path = PathBuf::from("output.mp4");- let (whisper_sender, whisper_receiver, _) = create_whisper_channel(+ let (whisper_sender, whisper_receiver) = create_whisper_channel(Arc::new(AudioTranscriptionEngine::WhisperDistilLargeV3),VadEngineEnum::WebRtc, // Or VadEngineEnum::WebRtc, hardcoded for nowdeepgram_api_key,&output_path,VadSensitivity::Medium,languages,- None+ DashMap::new(),).await?;// Spawn threads for each devicediff --git a/screenpipe-audio/src/core.rs b/screenpipe-audio/src/core.rsindex 1d33ac988..e40f04cbd 100644--- a/screenpipe-audio/src/core.rs+++ b/screenpipe-audio/src/core.rs@@ -6,8 +6,7 @@ use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};use cpal::StreamError;use lazy_static::lazy_static;use log::{debug, error, info, warn};-use screenpipe_core::Language;-use serde::{Deserialize, Serialize};+use screenpipe_core::{AudioDevice, AudioDeviceType, Language};use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};use std::sync::mpsc;use std::sync::Arc;@@ -45,68 +44,6 @@ impl fmt::Display for AudioTranscriptionEngine {}}-#[derive(Clone, Debug)]-pub struct DeviceControl {- pub is_running: bool,- pub is_paused: bool,-}--#[derive(Clone, Eq, PartialEq, Hash, Serialize, Debug, Deserialize)]-pub enum DeviceType {- Input,- Output,-}--#[derive(Clone, Eq, PartialEq, Hash, Serialize, Debug)]-pub struct AudioDevice {- pub name: String,- pub device_type: DeviceType,-}--impl AudioDevice {- pub fn new(name: String, device_type: DeviceType) -> Self {- AudioDevice { name, device_type }- }-- pub fn from_name(name: &str) -> Result<Self> {- if name.trim().is_empty() {- return Err(anyhow!("Device name cannot be empty"));- }-- let (name, device_type) = if name.to_lowercase().ends_with("(input)") {- (- name.trim_end_matches("(input)").trim().to_string(),- DeviceType::Input,- )- } else if name.to_lowercase().ends_with("(output)") {- (- name.trim_end_matches("(output)").trim().to_string(),- DeviceType::Output,- )- } else {- return Err(anyhow!(- "Device type (input/output) not specified in the name"- ));- };-- Ok(AudioDevice::new(name, device_type))- }-}--impl fmt::Display for AudioDevice {- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {- write!(- f,- "{} ({})",- self.name,- match self.device_type {- DeviceType::Input => "input",- DeviceType::Output => "output",- }- )- }-}-pub fn parse_audio_device(name: &str) -> Result<AudioDevice> {AudioDevice::from_name(name)}@@ -116,18 +53,18 @@ pub async fn get_device_and_config() -> Result<(cpal::Device, cpal::SupportedStreamConfig)> {let host = cpal::default_host();- let is_output_device = audio_device.device_type == DeviceType::Output;+ let is_output_device = audio_device.device_type == AudioDeviceType::Output;let is_display = audio_device.to_string().contains("Display");let cpal_audio_device = if audio_device.to_string() == "default" {match audio_device.device_type {- DeviceType::Input => host.default_input_device(),- DeviceType::Output => host.default_output_device(),+ AudioDeviceType::Input => host.default_input_device(),+ AudioDeviceType::Output => host.default_output_device(),}} else {let mut devices = match audio_device.device_type {- DeviceType::Input => host.input_devices()?,- DeviceType::Output => host.output_devices()?,+ AudioDeviceType::Input => host.input_devices()?,+ AudioDeviceType::Output => host.output_devices()?,};#[cfg(target_os = "macos")]@@ -152,7 +89,7 @@ pub async fn get_device_and_config(.unwrap_or(false)})}- .ok_or_else(|| anyhow!("Audio device not found"))?;+ .ok_or_else(|| anyhow!("audio device not found"))?;// if output device and windows, using output configlet config = if is_output_device && !is_display {@@ -315,7 +252,7 @@ pub async fn list_audio_devices() -> Result<Vec<AudioDevice>> {for device in host.input_devices()? {if let Ok(name) = device.name() {- devices.push(AudioDevice::new(name, DeviceType::Input));+ devices.push(AudioDevice::new(name, AudioDeviceType::Input));}}@@ -342,7 +279,7 @@ pub async fn list_audio_devices() -> Result<Vec<AudioDevice>> {for device in host.input_devices()? {if let Ok(name) = device.name() {if should_include_output_device(&name) {- devices.push(AudioDevice::new(name, DeviceType::Output));+ devices.push(AudioDevice::new(name, AudioDeviceType::Output));}}}@@ -353,7 +290,7 @@ pub async fn list_audio_devices() -> Result<Vec<AudioDevice>> {for device in host.output_devices()? {if let Ok(name) = device.name() {if should_include_output_device(&name) {- devices.push(AudioDevice::new(name, DeviceType::Output));+ devices.push(AudioDevice::new(name, AudioDeviceType::Output));}}}@@ -365,7 +302,10 @@ pub async fn list_audio_devices() -> Result<Vec<AudioDevice>> {&& should_include_output_device(&device.name().unwrap()){// TODO: not sure if it can be input, usually aggregate or multi output- devices.push(AudioDevice::new(device.name().unwrap(), DeviceType::Output));+ devices.push(AudioDevice::new(+ device.name().unwrap(),+ AudioDeviceType::Output,+ ));}}@@ -377,7 +317,7 @@ pub fn default_input_device() -> Result<AudioDevice> {let device = host.default_input_device().ok_or(anyhow!("No default input device detected"))?;- Ok(AudioDevice::new(device.name()?, DeviceType::Input))+ Ok(AudioDevice::new(device.name()?, AudioDeviceType::Input))}// this should be optional ?pub fn default_output_device() -> Result<AudioDevice> {@@ -387,7 +327,7 @@ pub fn default_output_device() -> Result<AudioDevice> {if let Ok(host) = cpal::host_from_id(cpal::HostId::ScreenCaptureKit) {if let Some(device) = host.default_input_device() {if let Ok(name) = device.name() {- return Ok(AudioDevice::new(name, DeviceType::Output));+ return Ok(AudioDevice::new(name, AudioDeviceType::Output));}}}@@ -395,7 +335,7 @@ pub fn default_output_device() -> Result<AudioDevice> {let device = host.default_output_device().ok_or_else(|| anyhow!("No default output device found"))?;- Ok(AudioDevice::new(device.name()?, DeviceType::Output))+ Ok(AudioDevice::new(device.name()?, AudioDeviceType::Output))}#[cfg(not(target_os = "macos"))]@@ -404,7 +344,7 @@ pub fn default_output_device() -> Result<AudioDevice> {let device = host.default_output_device().ok_or_else(|| anyhow!("No default output device found"))?;- return Ok(AudioDevice::new(device.name()?, DeviceType::Output));+ return Ok(AudioDevice::new(device.name()?, AudioDeviceType::Output));}}diff --git a/screenpipe-audio/src/deepgram/realtime.rs b/screenpipe-audio/src/deepgram/realtime.rsindex a5949fd5a..3442af38f 100644--- a/screenpipe-audio/src/deepgram/realtime.rs+++ b/screenpipe-audio/src/deepgram/realtime.rs@@ -1,7 +1,6 @@use crate::{deepgram::CUSTOM_DEEPGRAM_API_TOKEN, realtime::RealtimeTranscriptionEvent, AudioStream,};-use crate::{AudioDevice, DeviceType};use anyhow::Result;use bytes::BufMut;use bytes::Bytes;@@ -11,6 +10,8 @@ use deepgram::common::options::Encoding;use deepgram::common::stream_response::StreamResponse;use futures::channel::mpsc::{self, Receiver as FuturesReceiver};use futures::{SinkExt, TryStreamExt};+use screenpipe_core::AudioDevice;+use screenpipe_core::AudioDeviceType;use screenpipe_core::Language;use std::sync::{atomic::AtomicBool, Arc};use std::time::Duration;@@ -126,7 +127,7 @@ async fn handle_transcription({let res = channel.alternatives.first().unwrap();let text = res.transcript.clone();- let is_input = device.device_type == DeviceType::Input;+ let is_input = device.device_type == AudioDeviceType::Input;if !text.is_empty() {match realtime_transcription_sender.send(RealtimeTranscriptionEvent {diff --git a/screenpipe-audio/src/lib.rs b/screenpipe-audio/src/lib.rsindex 6251b3100..0cd10da33 100644--- a/screenpipe-audio/src/lib.rs+++ b/screenpipe-audio/src/lib.rs@@ -14,8 +14,7 @@ pub use audio_processing::resample;pub use core::{default_input_device, default_output_device, get_device_and_config, list_audio_devices,parse_audio_device, record_and_transcribe, start_realtime_recording, trigger_audio_permission,- AudioDevice, AudioStream, AudioTranscriptionEngine, DeviceControl, DeviceType,- LAST_AUDIO_CAPTURE,+ AudioStream, AudioTranscriptionEngine, LAST_AUDIO_CAPTURE,};pub mod realtime;pub use encode::encode_single_audio;diff --git a/screenpipe-audio/src/stt.rs b/screenpipe-audio/src/stt.rsindex 077e5bfd2..9df63adbc 100644--- a/screenpipe-audio/src/stt.rs+++ b/screenpipe-audio/src/stt.rs@@ -2,22 +2,21 @@ use crate::audio_processing::write_audio_to_file;use crate::deepgram::transcribe_with_deepgram;use crate::pyannote::models::{get_or_download_model, PyannoteModel};use crate::pyannote::segment::SpeechSegment;+use crate::resample;pub use crate::segments::prepare_segments;use crate::{pyannote::{embedding::EmbeddingExtractor, identify::EmbeddingManager},vad_engine::{SileroVad, VadEngine, VadEngineEnum, VadSensitivity, WebRtcVad},whisper::{process_with_whisper, WhisperModel},- AudioDevice, AudioTranscriptionEngine,+ AudioTranscriptionEngine,};-use crate::{resample, DeviceControl};use anyhow::{anyhow, Result};use candle_transformers::models::whisper as m;use dashmap::DashMap;-use log::{debug, error, info};+use log::{debug, error};#[cfg(target_os = "macos")]use objc::rc::autoreleasepool;-use screenpipe_core::Language;-use std::sync::atomic::{AtomicBool, Ordering};+use screenpipe_core::{AudioDevice, DeviceControl, Language};use std::{path::Path,sync::Arc,@@ -156,11 +155,10 @@ pub async fn create_whisper_channel(output_path: &Path,vad_sensitivity: VadSensitivity,languages: Vec<Language>,- audio_devices_control: Option<Arc<DashMap<AudioDevice, DeviceControl>>>,+ devices: DashMap<String, DeviceControl>,) -> Result<(crossbeam::channel::Sender<AudioInput>,crossbeam::channel::Receiver<TranscriptionResult>,- Arc<AtomicBool>, // Shutdown flag)> {let mut whisper_model = WhisperModel::new(&audio_transcription_engine)?;let (input_sender, input_receiver): (@@ -177,8 +175,6 @@ pub async fn create_whisper_channel(};vad_engine.set_sensitivity(vad_sensitivity);let vad_engine = Arc::new(Mutex::new(vad_engine));- let shutdown_flag = Arc::new(AtomicBool::new(false));- let shutdown_flag_clone = shutdown_flag.clone();let output_path = output_path.to_path_buf();let embedding_model_path = get_or_download_model(PyannoteModel::Embedding).await?;@@ -194,25 +190,17 @@ pub async fn create_whisper_channel(tokio::spawn(async move {loop {- if shutdown_flag_clone.load(Ordering::Relaxed) {- info!("Whisper channel shutting down");- break;- }- debug!("Waiting for input from input_receiver");-crossbeam::select! {recv(input_receiver) -> input_result => {match input_result {Ok(mut audio) => {- // Check if device should be recording- if let Some(control) = audio_devices_control.as_ref().unwrap().get(&audio.device) {- if !control.is_running {+ // Check device state+ if let Some(device) = devices.get(&audio.device.to_string()) {+ if !device.is_running {debug!("Skipping audio processing for stopped device: {}", audio.device);+ debug!("Device states: {:?}", devices);continue;}- } else {- debug!("Device not found in control list: {}", audio.device);- continue;}debug!("Received input from input_receiver");@@ -287,18 +275,15 @@ pub async fn create_whisper_channel(},Err(e) => {error!("Error receiving input: {:?}", e);- // Depending on the error type, you might want to break the loop or continue- // For now, we'll continue to the next iterationbreak;}}},}}- // Cleanup code here (if needed)});- Ok((input_sender, output_receiver, shutdown_flag))+ Ok((input_sender, output_receiver))}#[allow(clippy::too_many_arguments)]diff --git a/screenpipe-audio/src/whisper/model.rs b/screenpipe-audio/src/whisper/model.rsindex ad6d22952..ffdda1126 100644--- a/screenpipe-audio/src/whisper/model.rs+++ b/screenpipe-audio/src/whisper/model.rs@@ -3,7 +3,7 @@ use candle::{Device, Tensor};use candle_nn::VarBuilder;use candle_transformers::models::whisper::{self as m, Config};use hf_hub::{api::sync::Api, Repo, RepoType};-use log::{debug, info};+use log::debug;use tokenizers::Tokenizer;#[derive(Clone)]@@ -17,7 +17,7 @@ impl WhisperModel {pub fn new(engine: &crate::AudioTranscriptionEngine) -> Result<Self> {debug!("Initializing WhisperModel");let device = Device::new_metal(0).unwrap_or(Device::new_cuda(0).unwrap_or(Device::Cpu));- info!("device = {:?}", device);+ debug!("device = {:?}", device);debug!("Fetching model files");let (config_filename, tokenizer_filename, weights_filename) = {diff --git a/screenpipe-core/src/devices.rs b/screenpipe-core/src/devices.rsnew file mode 100644index 000000000..ef1788fc7--- /dev/null+++ b/screenpipe-core/src/devices.rs@@ -0,0 +1,94 @@+use std::fmt;++use anyhow::anyhow;+use serde::{Deserialize, Serialize};++#[derive(Clone, Debug)]+pub enum DeviceType {+ Audio(AudioDevice),+ Vision(u32), // monitor_id+}++impl fmt::Display for DeviceType {+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {+ match self {+ DeviceType::Audio(audio_device) => write!(f, "{}", audio_device),+ DeviceType::Vision(monitor_id) => write!(f, "{}", monitor_id),+ }+ }+}+#[derive(Clone, Debug)]+pub struct DeviceControl {+ pub device: DeviceType,+ pub is_running: bool,+ pub is_paused: bool,+}++impl Default for DeviceControl {+ fn default() -> Self {+ Self {+ device: DeviceType::Audio(AudioDevice::new(+ "default".to_string(),+ AudioDeviceType::Input,+ )),+ is_running: false,+ is_paused: false,+ }+ }+}++#[derive(Clone, Eq, PartialEq, Hash, Serialize, Debug, Deserialize)]+pub enum AudioDeviceType {+ Input,+ Output,+}++#[derive(Clone, Eq, PartialEq, Hash, Serialize, Debug)]+pub struct AudioDevice {+ pub name: String,+ pub device_type: AudioDeviceType,+}++impl AudioDevice {+ pub fn new(name: String, device_type: AudioDeviceType) -> Self {+ AudioDevice { name, device_type }+ }++ pub fn from_name(name: &str) -> anyhow::Result<Self> {+ if name.trim().is_empty() {+ return Err(anyhow!("Device name cannot be empty"));+ }++ let (name, device_type) = if name.to_lowercase().ends_with("(input)") {+ (+ name.trim_end_matches("(input)").trim().to_string(),+ AudioDeviceType::Input,+ )+ } else if name.to_lowercase().ends_with("(output)") {+ (+ name.trim_end_matches("(output)").trim().to_string(),+ AudioDeviceType::Output,+ )+ } else {+ return Err(anyhow!(+ "Device type (input/output) not specified in the name"+ ));+ };++ Ok(AudioDevice::new(name, device_type))+ }+}++impl fmt::Display for AudioDevice {+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {+ write!(+ f,+ "{} ({})",+ self.name,+ match self.device_type {+ AudioDeviceType::Input => "input",+ AudioDeviceType::Output => "output",+ }+ )+ }+}diff --git a/screenpipe-core/src/lib.rs b/screenpipe-core/src/lib.rsindex ddfb9a6e4..bf1f1401e 100644--- a/screenpipe-core/src/lib.rs+++ b/screenpipe-core/src/lib.rs@@ -39,3 +39,6 @@ pub mod network;pub use network::*;pub use language::{Language, TESSERACT_LANGUAGES};++pub mod devices;+pub use devices::*;diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rsindex 5b365da75..f649ab89c 100644--- a/screenpipe-server/src/bin/screenpipe-server.rs+++ b/screenpipe-server/src/bin/screenpipe-server.rs@@ -1,17 +1,23 @@use clap::Parser;#[allow(unused_imports)]use colored::Colorize;-use dashmap::DashMap;use dirs::home_dir;use futures::pin_mut;use port_check::is_local_ipv4_port_free;+use screenpipe_audio::vad_engine::VadSensitivity;use screenpipe_audio::{- default_input_device, default_output_device, list_audio_devices, parse_audio_device,- AudioDevice, DeviceControl,+ create_whisper_channel, default_input_device, default_output_device, list_audio_devices,+ parse_audio_device, VadEngineEnum,};+use screenpipe_audio::{AudioInput, TranscriptionResult};use screenpipe_core::find_ffmpeg_path;+use screenpipe_core::AudioDevice;+use screenpipe_core::DeviceControl;+use screenpipe_core::DeviceType;+use screenpipe_server::core::DeviceManager;use screenpipe_server::{cli::{Cli, CliAudioTranscriptionEngine, CliOcrEngine, Command, OutputFormat, PipeCommand},+ core::{AudioConfig, RealtimeConfig, RecordingConfig, VisionConfig},handle_index_command,pipe_manager::PipeInfo,start_continuous_recording, watch_pid, DatabaseManager, PipeManager, ResourceMonitor, Server,@@ -21,14 +27,8 @@ use screenpipe_vision::monitor::list_monitors;use screenpipe_vision::run_ui;use serde_json::{json, Value};use std::{- collections::HashMap,- env, fs,- io::Write,- net::SocketAddr,- ops::Deref,- path::PathBuf,- sync::{atomic::AtomicBool, Arc},- time::Duration,+ collections::HashMap, env, fs, io::Write, net::SocketAddr, ops::Deref, path::PathBuf,+ sync::Arc, time::Duration,};use tokio::{runtime::Runtime, signal, sync::broadcast};use tracing::{debug, error, info, warn};@@ -373,15 +373,15 @@ async fn main() -> anyhow::Result<()> {}let mut audio_devices = Vec::new();-- let audio_devices_control = Arc::new(DashMap::new());- let audio_devices_control_recording = audio_devices_control.clone();-+ let (device_manager, device_manager_receiver) = DeviceManager::new();+ let mut device_manager_receiver_control_loop = device_manager_receiver.clone();+ let device_manager = Arc::new(device_manager);let mut realtime_audio_devices = Vec::new();// Add all available audio devices to the controlsfor device in &all_audio_devices {let device_control = DeviceControl {+ device: screenpipe_core::DeviceType::Audio(device.clone()),is_running: false,is_paused: false,};@@ -394,6 +394,7 @@ async fn main() -> anyhow::Result<()> {if let Ok(input_device) = default_input_device() {audio_devices.push(Arc::new(input_device.clone()));let device_control = DeviceControl {+ device: screenpipe_core::DeviceType::Audio(input_device.clone()),is_running: true,is_paused: false,};@@ -404,6 +405,7 @@ async fn main() -> anyhow::Result<()> {if let Ok(output_device) = default_output_device() {audio_devices.push(Arc::new(output_device.clone()));let device_control = DeviceControl {+ device: screenpipe_core::DeviceType::Audio(output_device.clone()),is_running: true,is_paused: false,};@@ -415,6 +417,7 @@ async fn main() -> anyhow::Result<()> {let device = parse_audio_device(d).expect("failed to parse audio device");audio_devices.push(Arc::new(device.clone()));let device_control = DeviceControl {+ device: screenpipe_core::DeviceType::Audio(device.clone()),is_running: true,is_paused: false,};@@ -426,16 +429,23 @@ async fn main() -> anyhow::Result<()> {eprintln!("no audio devices available. audio recording will be disabled.");} else {for device in &audio_devices {- let device_control = DeviceControl {- is_running: true,- is_paused: false,- };let device_clone = device.deref().clone();- let sender_clone = audio_devices_control.clone();+ let sender_clone = device_manager.clone();// send signal after everything startedtokio::spawn(async move {tokio::time::sleep(Duration::from_secs(15)).await;- sender_clone.insert(device_clone, device_control);+ info!(+ "initializing audio device control for device: {}",+ device_clone.name+ );++ let _ = sender_clone+ .update_device(DeviceControl {+ device: screenpipe_core::DeviceType::Audio(device_clone),+ is_running: true,+ is_paused: false,+ })+ .await;});}}@@ -478,11 +488,6 @@ async fn main() -> anyhow::Result<()> {let db_server = db.clone();- // Channel for controlling the recorder ! TODO RENAME SHIT- let vision_control = Arc::new(AtomicBool::new(true));-- let vision_control_server_clone = vision_control.clone();-let warning_ocr_engine_clone = cli.ocr_engine.clone();let warning_audio_transcription_engine_clone = cli.audio_transcription_engine.clone();let monitor_ids = if cli.monitor_id.is_empty() {@@ -491,6 +496,29 @@ async fn main() -> anyhow::Result<()> {cli.monitor_id.clone()};+ // Initialize vision devices control based on user selected monitors+ {+ for monitor_id in monitor_ids.clone() {+ let device_manager = device_manager.clone();+ // Send signal after everything started+ tokio::spawn(async move {+ tokio::time::sleep(Duration::from_secs(15)).await;+ info!(+ "initializing vision device control for monitor: {}",+ monitor_id+ );+ let device_control = DeviceControl {+ device: DeviceType::Vision(monitor_id),+ is_running: true,+ is_paused: false,+ };+ if let Err(e) = device_manager.update_device(device_control).await {+ warn!("failed to initialize vision device control: {}", e);+ }+ });+ }+ }+let languages = cli.unique_languages().unwrap();let languages_clone = languages.clone();@@ -508,9 +536,7 @@ async fn main() -> anyhow::Result<()> {let db_clone = Arc::clone(&db);let output_path_clone = Arc::new(local_data_dir.join("data").to_string_lossy().into_owned());- let vision_control_clone = Arc::clone(&vision_control);let shutdown_tx_clone = shutdown_tx.clone();- let monitor_ids_clone = monitor_ids.clone();let ignored_windows_clone = cli.ignored_windows.clone();let included_windows_clone = cli.included_windows.clone();let realtime_audio_devices_clone = realtime_audio_devices.clone();@@ -528,6 +554,31 @@ async fn main() -> anyhow::Result<()> {let (realtime_vision_sender, _) = tokio::sync::broadcast::channel(1000);let realtime_vision_sender = Arc::new(realtime_vision_sender.clone());let realtime_vision_sender_clone = realtime_vision_sender.clone();++ let (whisper_sender, whisper_receiver) = if cli.disable_audio {+ // Create a dummy channel if no audio devices are available, e.g. audio disabled+ let (input_sender, _): (+ crossbeam::channel::Sender<AudioInput>,+ crossbeam::channel::Receiver<AudioInput>,+ ) = crossbeam::channel::bounded(100);+ let (_, output_receiver): (+ crossbeam::channel::Sender<TranscriptionResult>,+ crossbeam::channel::Receiver<TranscriptionResult>,+ ) = crossbeam::channel::bounded(100);+ (input_sender, output_receiver)+ } else {+ create_whisper_channel(+ Arc::new(cli.audio_transcription_engine.clone().into()),+ VadEngineEnum::from(cli.vad_engine),+ cli.deepgram_api_key.clone(),+ &PathBuf::from(output_path_clone.as_ref()),+ VadSensitivity::from(cli.vad_sensitivity.clone()),+ languages.clone(),+ device_manager.devices.clone(),+ )+ .await?+ };+let handle = {let runtime = &tokio::runtime::Handle::current();runtime.spawn(async move {@@ -536,33 +587,51 @@ async fn main() -> anyhow::Result<()> {let vad_engine_clone = vad_engine.clone(); // Clone it here for each iterationlet mut shutdown_rx = shutdown_tx_clone.subscribe();let realtime_transcription_sender_clone = realtime_transcription_sender.clone();- let recording_future = start_continuous_recording(- db_clone.clone(),- output_path_clone.clone(),++ // Create the configs+ let recording_config = RecordingConfig {+ output_path: output_path_clone.clone(),fps,audio_chunk_duration,- Duration::from_secs(cli.video_chunk_duration),- vision_control_clone.clone(),- audio_devices_control_recording.clone(),- cli.disable_audio,- Arc::new(cli.audio_transcription_engine.clone().into()),- Arc::new(cli.ocr_engine.clone().into()),- monitor_ids_clone.clone(),- cli.use_pii_removal,- cli.disable_vision,- vad_engine_clone,+ video_chunk_duration: Duration::from_secs(cli.video_chunk_duration),+ use_pii_removal: cli.use_pii_removal,+ capture_unfocused_windows: cli.capture_unfocused_windows,+ languages: languages.clone(),+ };++ let audio_config = AudioConfig {+ disabled: cli.disable_audio,+ transcription_engine: Arc::new(cli.audio_transcription_engine.clone().into()),+ vad_engine: vad_engine_clone,+ vad_sensitivity: cli.vad_sensitivity.clone(),+ deepgram_api_key: cli.deepgram_api_key.clone(),+ realtime_enabled: cli.enable_realtime_audio_transcription,+ realtime_devices: realtime_audio_devices.clone(),+ whisper_sender: whisper_sender.clone(),+ whisper_receiver: whisper_receiver.clone(),+ };++ let vision_config = VisionConfig {+ disabled: cli.disable_vision,+ ocr_engine: Arc::new(cli.ocr_engine.clone().into()),+ ignored_windows: cli.ignored_windows.clone(),+ include_windows: cli.included_windows.clone(),+ };++ let realtime_config = RealtimeConfig {+ transcription_sender: Arc::new(realtime_transcription_sender_clone),+ vision_sender: realtime_vision_sender_clone,+ };++ let recording_future = start_continuous_recording(+ db_clone.clone(),+ recording_config,+ audio_config,+ vision_config,+ realtime_config,&vision_handle,&audio_handle,- &cli.ignored_windows,- &cli.included_windows,- cli.deepgram_api_key.clone(),- cli.vad_sensitivity.clone(),- languages.clone(),- cli.capture_unfocused_windows,- realtime_audio_devices.clone(),- cli.enable_realtime_audio_transcription,- Arc::new(realtime_transcription_sender_clone), // Use the cloned sender- realtime_vision_sender_clone,+ device_manager_receiver.clone(),);let result = tokio::select! {@@ -603,16 +672,11 @@ async fn main() -> anyhow::Result<()> {}};- let (audio_devices_tx, _) = broadcast::channel(100);- let audio_devices_tx_clone = Arc::new(audio_devices_tx.clone());-let realtime_vision_sender_clone = realtime_vision_sender_clone.clone();- // TODO: Add SSE stream for realtime audio transcriptionlet server = Server::new(db_server,SocketAddr::from(([127, 0, 0, 1], cli.port)),- vision_control_server_clone,- audio_devices_tx_clone,+ device_manager.clone(),local_data_dir_clone_2,pipe_manager.clone(),cli.disable_vision,@@ -623,43 +687,69 @@ async fn main() -> anyhow::Result<()> {realtime_vision_sender_clone.clone(),);- let mut rx = audio_devices_tx.subscribe();- let audio_devices_control_for_spawn = audio_devices_control.clone();+ let device_manager_clone = device_manager.clone();tokio::spawn(async move {- while let Ok((device, control)) = rx.recv().await {+ while let Ok(_) = device_manager_receiver_control_loop.changed().await {+ info!("received device update");+ let control = device_manager_receiver_control_loop.borrow().clone();if let Err(e) =- handle_device_update(&device, control, &audio_devices_control_for_spawn).await+ handle_device_update(&control.device, control.clone(), &device_manager_clone).await{error!("Device update failed: {}", e);continue;}}- info!("Device monitoring task completed");+ info!("audio device control task stopped");});async fn handle_device_update(- device: &AudioDevice,+ device: &DeviceType,control: DeviceControl,- devices_control: &DashMap<AudioDevice, DeviceControl>,+ devices_control: &Arc<DeviceManager>,) -> anyhow::Result<()> {- match list_audio_devices().await {- Ok(available_devices) => {- if !available_devices.contains(device) {+ info!("received device update");++ match device {+ DeviceType::Audio(device) => {+ match list_audio_devices().await {+ Ok(available_devices) => {+ if !available_devices.contains(device) {+ return Err(anyhow::anyhow!(+ "attempted to control non-existent device: {}",+ device.name+ ));+ }++ // Update the device state using DeviceManager+ devices_control.update_device(control.clone()).await?;++ info!(+ "audio device state changed: {} - running: {}",+ device.name, control.is_running+ );+ Ok(())+ }+ Err(e) => Err(anyhow::anyhow!("failed to list audio devices: {}", e)),+ }+ }+ DeviceType::Vision(monitor_id) => {+ let monitors = list_monitors().await;+ if !monitors.iter().any(|m| m.id() == *monitor_id) {return Err(anyhow::anyhow!("attempted to control non-existent device: {}",- device.name+ monitor_id));}- // Update the device state- devices_control.insert(device.clone(), control.clone());+ // Update the device state using DeviceManager+ devices_control.update_device(control.clone()).await?;+info!(- "Device state changed: {} - running: {}",- device.name, control.is_running+ "vision device state changed: {} - running: {}",+ monitor_id, control.is_running);Ok(())}- Err(e) => Err(anyhow::anyhow!("failed to list audio devices: {}", e)),}}@@ -950,7 +1040,7 @@ async fn main() -> anyhow::Result<()> {}}- let server_future = server.start(devices_status, api_plugin, cli.enable_frame_cache);+ let server_future = server.start(api_plugin, cli.enable_frame_cache);pin_mut!(server_future);// Add auto-destruct watcherdiff --git a/screenpipe-server/src/core.rs b/screenpipe-server/src/core.rsindex d4c4e90aa..8fb49f24c 100644--- a/screenpipe-server/src/core.rs+++ b/screenpipe-server/src/core.rs@@ -6,140 +6,178 @@ use dashmap::DashMap;use futures::future::join_all;use log::{debug, error, info, warn};use screenpipe_audio::realtime::RealtimeTranscriptionEvent;-use screenpipe_audio::vad_engine::VadSensitivity;use screenpipe_audio::{- create_whisper_channel, record_and_transcribe, vad_engine::VadEngineEnum, AudioDevice,- AudioInput, AudioTranscriptionEngine, DeviceControl, TranscriptionResult,+ record_and_transcribe, AudioInput, AudioTranscriptionEngine, TranscriptionResult,};use screenpipe_audio::{start_realtime_recording, AudioStream};use screenpipe_core::pii_removal::remove_pii;-use screenpipe_core::Language;+use screenpipe_core::{AudioDevice, DeviceControl, DeviceType, Language};use screenpipe_vision::core::{RealtimeVisionEvent, WindowOcr};use screenpipe_vision::OcrEngine;use std::collections::HashMap;-use std::path::PathBuf;use std::sync::atomic::{AtomicBool, Ordering};use std::sync::Arc;use std::time::Duration;use tokio::runtime::Handle;use tokio::task::JoinHandle;-#[allow(clippy::too_many_arguments)]+#[derive(Clone)]+pub struct DeviceManager {+ sender: tokio::sync::watch::Sender<DeviceControl>,+ pub devices: DashMap<String, DeviceControl>,+}++impl DeviceManager {+ pub fn new() -> (Self, tokio::sync::watch::Receiver<DeviceControl>) {+ let (sender, receiver) = tokio::sync::watch::channel(DeviceControl::default());+ (+ Self {+ sender,+ devices: DashMap::new(),+ },+ receiver,+ )+ }++ pub async fn update_device(&self, control: DeviceControl) -> anyhow::Result<()> {+ debug!("updating device: {:?}", control);+ // check if there is an actual change, otherwise ignore+ if let Some(device) = self.devices.get(&control.device.to_string()) {+ if device.is_running == control.is_running {+ return Ok(());+ }+ }++ info!("updating device: {:?}", control);+ self.sender.send(control.clone())?;+ self.devices.insert(control.device.to_string(), control);+ Ok(())+ }++ pub async fn get_device(&self, device_id: &str) -> anyhow::Result<DeviceControl> {+ self.devices+ .get(device_id)+ .map(|r| r.value().clone())+ .ok_or(anyhow::anyhow!("device not found: {}", device_id))+ }+}++#[derive(Clone)]+pub struct RecordingConfig {+ pub output_path: Arc<String>,+ pub fps: f64,+ pub audio_chunk_duration: Duration,+ pub video_chunk_duration: Duration,+ pub use_pii_removal: bool,+ pub capture_unfocused_windows: bool,+ pub languages: Vec<Language>,+}++#[derive(Clone)]+pub struct AudioConfig {+ pub disabled: bool,+ pub transcription_engine: Arc<AudioTranscriptionEngine>,+ pub vad_engine: CliVadEngine,+ pub vad_sensitivity: CliVadSensitivity,+ pub deepgram_api_key: Option<String>,+ pub realtime_enabled: bool,+ pub realtime_devices: Vec<Arc<AudioDevice>>,+ pub whisper_sender: crossbeam::channel::Sender<AudioInput>,+ pub whisper_receiver: crossbeam::channel::Receiver<TranscriptionResult>,+}++#[derive(Clone)]+pub struct VisionConfig {+ pub disabled: bool,+ pub ocr_engine: Arc<OcrEngine>,+ pub ignored_windows: Vec<String>,+ pub include_windows: Vec<String>,+}++#[derive(Clone)]+pub struct RealtimeConfig {+ pub transcription_sender: Arc<tokio::sync::broadcast::Sender<RealtimeTranscriptionEvent>>,+ pub vision_sender: Arc<tokio::sync::broadcast::Sender<RealtimeVisionEvent>>,+}++#[derive(Clone)]+pub struct VideoRecordingConfig {+ pub db: Arc<DatabaseManager>,+ pub output_path: Arc<String>,+ pub fps: f64,+ pub ocr_engine: Arc<OcrEngine>,+ pub monitor_id: u32,+ pub use_pii_removal: bool,+ pub ignored_windows: Vec<String>,+ pub include_windows: Vec<String>,+ pub video_chunk_duration: Duration,+ pub languages: Vec<Language>,+ pub capture_unfocused_windows: bool,+ pub realtime_vision_sender: Arc<tokio::sync::broadcast::Sender<RealtimeVisionEvent>>,+}+pub async fn start_continuous_recording(db: Arc<DatabaseManager>,- output_path: Arc<String>,- fps: f64,- audio_chunk_duration: Duration,- video_chunk_duration: Duration,- vision_control: Arc<AtomicBool>,- audio_devices_control: Arc<DashMap<AudioDevice, DeviceControl>>,- audio_disabled: bool,- audio_transcription_engine: Arc<AudioTranscriptionEngine>,- ocr_engine: Arc<OcrEngine>,- monitor_ids: Vec<u32>,- use_pii_removal: bool,- vision_disabled: bool,- vad_engine: CliVadEngine,+ recording: RecordingConfig,+ audio: AudioConfig,+ vision: VisionConfig,+ realtime: RealtimeConfig,vision_handle: &Handle,audio_handle: &Handle,- ignored_windows: &[String],- include_windows: &[String],- deepgram_api_key: Option<String>,- vad_sensitivity: CliVadSensitivity,- languages: Vec<Language>,- capture_unfocused_windows: bool,- realtime_audio_devices: Vec<Arc<AudioDevice>>,- realtime_audio_enabled: bool,- realtime_transcription_sender: Arc<tokio::sync::broadcast::Sender<RealtimeTranscriptionEvent>>,- realtime_vision_sender: Arc<tokio::sync::broadcast::Sender<RealtimeVisionEvent>>,+ device_control_receiver: tokio::sync::watch::Receiver<DeviceControl>,) -> Result<()> {- debug!("Starting video recording for monitor {:?}", monitor_ids);- let video_tasks = if !vision_disabled {- monitor_ids- .iter()- .map(|&monitor_id| {- let db_manager_video = Arc::clone(&db);- let output_path_video = Arc::clone(&output_path);- let is_running_video = Arc::clone(&vision_control);- let ocr_engine = Arc::clone(&ocr_engine);- let ignored_windows_video = ignored_windows.to_vec();- let include_windows_video = include_windows.to_vec();- let realtime_vision_sender_clone = realtime_vision_sender.clone();-- let languages = languages.clone();-- debug!("Starting video recording for monitor {}", monitor_id);- vision_handle.spawn(async move {- record_video(- db_manager_video,- output_path_video,- fps,- is_running_video,- ocr_engine,- monitor_id,- use_pii_removal,- &ignored_windows_video,- &include_windows_video,- video_chunk_duration,- languages.clone(),- capture_unfocused_windows,- realtime_vision_sender_clone,- )- .await- })- })- .collect::<Vec<_>>()+ let recording_config = recording;++ let output_path_clone = recording_config.output_path.clone();+ let languages_clone = recording_config.languages.clone();+ let db_clone = db.clone();+ let ocr_engine_clone = vision.ocr_engine.clone();+ let device_control_receiver_vision = device_control_receiver.clone();+ let device_control_receiver_audio = device_control_receiver.clone();++ let video_task = if !vision.disabled {+ vision_handle.spawn(async move {+ record_vision(+ device_control_receiver_vision,+ ocr_engine_clone,+ db_clone,+ output_path_clone,+ recording_config.fps,+ languages_clone,+ recording_config.capture_unfocused_windows,+ realtime.vision_sender,+ vision.ignored_windows,+ vision.include_windows,+ recording_config.video_chunk_duration,+ recording_config.use_pii_removal,+ )+ .await+ })} else {- vec![vision_handle.spawn(async move {+ vision_handle.spawn(async move {tokio::time::sleep(Duration::from_secs(60)).await;Ok(())- })]+ })};- let (whisper_sender, whisper_receiver, whisper_shutdown_flag) = if audio_disabled {- // Create a dummy channel if no audio devices are available, e.g. audio disabled- let (input_sender, _): (- crossbeam::channel::Sender<AudioInput>,- crossbeam::channel::Receiver<AudioInput>,- ) = crossbeam::channel::bounded(100);- let (_, output_receiver): (- crossbeam::channel::Sender<TranscriptionResult>,- crossbeam::channel::Receiver<TranscriptionResult>,- ) = crossbeam::channel::bounded(100);- (- input_sender,- output_receiver,- Arc::new(AtomicBool::new(false)),- )- } else {- create_whisper_channel(- audio_transcription_engine.clone(),- VadEngineEnum::from(vad_engine),- deepgram_api_key.clone(),- &PathBuf::from(output_path.as_ref()),- VadSensitivity::from(vad_sensitivity),- languages.clone(),- Some(audio_devices_control.clone()),- )- .await?- };- let whisper_sender_clone = whisper_sender.clone();+ let whisper_sender_clone = audio.whisper_sender.clone();+ let whisper_receiver_clone = audio.whisper_receiver.clone();let db_manager_audio = Arc::clone(&db);- let audio_task = if !audio_disabled {+ let audio_task = if !audio.disabled {audio_handle.spawn(async move {record_audio(+ device_control_receiver_audio,db_manager_audio,- audio_chunk_duration,- whisper_sender,- whisper_receiver,- audio_devices_control,- audio_transcription_engine,- realtime_audio_enabled,- realtime_audio_devices,- languages,- realtime_transcription_sender,- deepgram_api_key,+ recording_config.audio_chunk_duration,+ whisper_sender_clone,+ whisper_receiver_clone,+ audio.transcription_engine,+ audio.realtime_enabled,+ audio.realtime_devices,+ recording_config.languages,+ realtime.transcription_sender,+ audio.deepgram_api_key,).await})@@ -150,22 +188,15 @@ pub async fn start_continuous_recording(})};- // Join all video tasks- let video_results = join_all(video_tasks);-- // Handle any errors from the tasks- for (i, result) in video_results.await.into_iter().enumerate() {- if let Err(e) = result {- error!("Video recording error for monitor {}: {:?}", i, e);- }+ if let Err(e) = video_task.await {+ error!("Video recording error: {:?}", e);}if let Err(e) = audio_task.await {error!("Audio recording error: {:?}", e);}// Shutdown the whisper channel- whisper_shutdown_flag.store(true, Ordering::Relaxed);- drop(whisper_sender_clone); // Close the sender channel+ drop(audio.whisper_sender); // Close the sender channel// TODO: process any remaining audio chunks// TODO: wait a bit for whisper to finish processing@@ -175,26 +206,89 @@ pub async fn start_continuous_recording(Ok(())}-#[allow(clippy::too_many_arguments)]-async fn record_video(+async fn record_vision(+ device_receiver: tokio::sync::watch::Receiver<DeviceControl>,+ ocr_engine: Arc<OcrEngine>,db: Arc<DatabaseManager>,output_path: Arc<String>,fps: f64,- is_running: Arc<AtomicBool>,- ocr_engine: Arc<OcrEngine>,- monitor_id: u32,- use_pii_removal: bool,- ignored_windows: &[String],- include_windows: &[String],- video_chunk_duration: Duration,languages: Vec<Language>,capture_unfocused_windows: bool,realtime_vision_sender: Arc<tokio::sync::broadcast::Sender<RealtimeVisionEvent>>,+ ignored_windows: Vec<String>,+ include_windows: Vec<String>,+ video_chunk_duration: Duration,+ use_pii_removal: bool,) -> Result<()> {- debug!("record_video: Starting");- let db_chunk_callback = Arc::clone(&db);+ info!("record_vision: Starting");+ let mut handles: HashMap<u32, JoinHandle<()>> = HashMap::new();+ let mut device_receiver_clone = device_receiver.clone();++ while let Ok(_) = device_receiver_clone.changed().await {+ let control = device_receiver_clone.borrow().clone();+ let device_receiver_video = device_receiver_clone.clone();+ match control.device {+ DeviceType::Vision(monitor_id) => {+ if !control.is_running {+ if let Some(handle) = handles.remove(&monitor_id) {+ handle.abort();+ info!("stopped thread for monitor {}", monitor_id);+ }+ continue;+ }++ if handles.contains_key(&monitor_id) {+ continue;+ }++ let db_manager_video = Arc::clone(&db);+ let output_path_video = Arc::clone(&output_path);+ let ocr_engine = Arc::clone(&ocr_engine);+ let ignored_windows_video = ignored_windows.to_vec();+ let include_windows_video = include_windows.to_vec();+ let realtime_vision_sender_clone = realtime_vision_sender.clone();+ let languages = languages.clone();++ let handle = tokio::spawn(async move {+ let config = VideoRecordingConfig {+ db: db_manager_video,+ output_path: output_path_video,+ fps,+ ocr_engine,+ monitor_id,+ use_pii_removal,+ ignored_windows: ignored_windows_video,+ include_windows: include_windows_video,+ video_chunk_duration,+ languages,+ capture_unfocused_windows,+ realtime_vision_sender: realtime_vision_sender_clone,+ };++ if let Err(e) = record_video(device_receiver_video, config).await {+ error!(+ "Error in video recording thread for monitor {}: {}",+ monitor_id, e+ );+ }+ });++ handles.insert(monitor_id, handle);+ }+ DeviceType::Audio(_) => continue, // Ignore audio devices+ }+ }+ Ok(())+}++async fn record_video(+ mut device_receiver: tokio::sync::watch::Receiver<DeviceControl>,+ config: VideoRecordingConfig,+) -> Result<()> {+ info!("record_video: Starting");+ let db_chunk_callback = Arc::clone(&config.db);let rt = Handle::current();- let device_name = Arc::new(format!("monitor_{}", monitor_id));+ let device_name = Arc::new(format!("monitor_{}", config.monitor_id));let new_chunk_callback = {let db_chunk_callback = Arc::clone(&db_chunk_callback);@@ -216,82 +310,94 @@ async fn record_video(};let video_capture = VideoCapture::new(- &output_path,- fps,- video_chunk_duration,+ &config.output_path,+ config.fps,+ config.video_chunk_duration,new_chunk_callback,- Arc::clone(&ocr_engine),- monitor_id,- ignored_windows,- include_windows,- languages,- capture_unfocused_windows,+ Arc::clone(&config.ocr_engine),+ config.monitor_id,+ config.ignored_windows,+ config.include_windows,+ config.languages,+ config.capture_unfocused_windows,);- while is_running.load(Ordering::SeqCst) {- if let Some(frame) = video_capture.ocr_frame_queue.pop() {- for window_result in &frame.window_ocr_results {- match db.insert_frame(&device_name, None).await {- Ok(frame_id) => {- let text_json =- serde_json::to_string(&window_result.text_json).unwrap_or_default();-- let text = if use_pii_removal {- &remove_pii(&window_result.text)- } else {- &window_result.text- };-- let _ = realtime_vision_sender.send(RealtimeVisionEvent::Ocr(WindowOcr {- image: Some(frame.image.clone()),- text: text.clone(),- text_json: window_result.text_json.clone(),- app_name: window_result.app_name.clone(),- window_name: window_result.window_name.clone(),- focused: window_result.focused,- confidence: window_result.confidence,- timestamp: frame.timestamp,- }));- if let Err(e) = db- .insert_ocr_text(- frame_id,- text,- &text_json,- &window_result.app_name,- &window_result.window_name,- Arc::clone(&ocr_engine),- window_result.focused, // Add this line- )- .await- {- error!(- "Failed to insert OCR text: {}, skipping window {} of frame {}",- e, window_result.window_name, frame_id- );- continue;+ loop {+ tokio::select! {+ Ok(_) = device_receiver.changed() => {+ info!("device_receiver changed in record_video");+ let control = device_receiver.borrow().clone();+ if !control.is_running {+ let _ = video_capture.shutdown().await;+ return Ok(());+ }+ }+ _ = tokio::time::sleep(Duration::from_secs_f64(1.0 / config.fps)) => {+ if let Some(frame) = video_capture.ocr_frame_queue.pop() {+ for window_result in &frame.window_ocr_results {+ match config.db.insert_frame(&device_name, None).await {+ Ok(frame_id) => {+ let text_json =+ serde_json::to_string(&window_result.text_json).unwrap_or_default();++ let text = if config.use_pii_removal {+ &remove_pii(&window_result.text)+ } else {+ &window_result.text+ };++ let _ = config.realtime_vision_sender.send(RealtimeVisionEvent::Ocr(+ WindowOcr {+ image: Some(frame.image.clone()),+ text: text.clone(),+ text_json: window_result.text_json.clone(),+ app_name: window_result.app_name.clone(),+ window_name: window_result.window_name.clone(),+ focused: window_result.focused,+ confidence: window_result.confidence,+ timestamp: frame.timestamp,+ },+ ));++ if let Err(e) = config+ .db+ .insert_ocr_text(+ frame_id,+ text,+ &text_json,+ &window_result.app_name,+ &window_result.window_name,+ Arc::clone(&config.ocr_engine),+ window_result.focused,+ )+ .await+ {+ error!(+ "Failed to insert OCR text: {}, skipping window {} of frame {}",+ e, window_result.window_name, frame_id+ );+ continue;+ }+ }+ Err(e) => {+ warn!("Failed to insert frame: {}", e);+ tokio::time::sleep(Duration::from_millis(100)).await;+ continue;+ }}}- Err(e) => {- warn!("Failed to insert frame: {}", e);- tokio::time::sleep(Duration::from_millis(100)).await;- continue;- }}}}- tokio::time::sleep(Duration::from_secs_f64(1.0 / fps)).await;}-- Ok(())}-#[allow(clippy::too_many_arguments)]async fn record_audio(+ device_receiver: tokio::sync::watch::Receiver<DeviceControl>,db: Arc<DatabaseManager>,chunk_duration: Duration,whisper_sender: crossbeam::channel::Sender<AudioInput>,whisper_receiver: crossbeam::channel::Receiver<TranscriptionResult>,- audio_devices_control: Arc<DashMap<AudioDevice, DeviceControl>>,audio_transcription_engine: Arc<AudioTranscriptionEngine>,realtime_audio_enabled: bool,realtime_audio_devices: Vec<Arc<AudioDevice>>,@@ -303,139 +409,158 @@ async fn record_audio(let mut previous_transcript = "".to_string();let mut previous_transcript_id: Option<i64> = None;let realtime_transcription_sender_clone = realtime_transcription_sender.clone();+ let mut device_receiver_clone = device_receiver.clone();loop {- // Iterate over DashMap entries and process each device- for entry in audio_devices_control.iter() {- let audio_device = entry.key().clone();- let device_control = entry.value().clone();- let device_id = audio_device.to_string();-- // Skip if we're already handling this device- if handles.contains_key(&device_id) {- continue;- }-- info!("Received audio device: {}", &audio_device);-- if !device_control.is_running {- info!("Device control signaled stop for device {}", &audio_device);- if let Some(handle) = handles.remove(&device_id) {- handle.abort();- info!("Stopped thread for device {}", &audio_device);- }- // Remove from DashMap- audio_devices_control.remove(&audio_device);- continue;- }-- let whisper_sender_clone = whisper_sender.clone();+ tokio::select! {+ Ok(_) = device_receiver_clone.changed() => {+ let control = device_receiver_clone.borrow().clone();+ match control.device {+ DeviceType::Audio(audio_device) => {+ let device_id = audio_device.to_string();++ if !control.is_running {+ if let Some(handle) = handles.remove(&device_id) {+ handle.abort();+ info!("stopped thread for device {}", &audio_device);+ }+ continue;+ }- let audio_device = Arc::new(audio_device);- let device_control = Arc::new(device_control);+ if handles.contains_key(&device_id) {+ continue;+ }- let realtime_audio_devices_clone = realtime_audio_devices.clone();- let languages_clone = languages.clone();- let realtime_transcription_sender_clone = realtime_transcription_sender_clone.clone();- let deepgram_api_key_clone = deepgram_api_key.clone();- let handle = tokio::spawn(async move {- let audio_device_clone = Arc::clone(&audio_device);- let deepgram_api_key = deepgram_api_key_clone.clone();- debug!(- "Starting audio capture thread for device: {}",- &audio_device- );+ let whisper_sender_clone = whisper_sender.clone();++ let audio_device = Arc::new(audio_device);++ let realtime_audio_devices_clone = realtime_audio_devices.clone();+ let languages_clone = languages.clone();+ let realtime_transcription_sender_clone =+ realtime_transcription_sender_clone.clone();+ let deepgram_api_key_clone = deepgram_api_key.clone();+ let device_receiver_clone = device_receiver.clone();+ let device_receiver_clone_clone = device_receiver_clone.clone();+ let handle = tokio::spawn(async move {+ let audio_device_clone = Arc::clone(&audio_device);+ let deepgram_api_key = deepgram_api_key_clone.clone();+ info!(+ "starting audio capture thread for device: {}",+ &audio_device+ );- let mut did_warn = false;- let is_running = Arc::new(AtomicBool::new(device_control.is_running));+ let mut did_warn = false;+ let is_running = Arc::new(AtomicBool::new(control.is_running));+++ while is_running.load(Ordering::Relaxed) {+ let is_running_clone = is_running.clone();+ let device_receiver_monitor = device_receiver_clone_clone.clone();++ // if device control change to false, set is_running to false+ tokio::spawn(async move {+ loop {+ if !device_receiver_monitor.borrow().is_running {+ is_running_clone.clone().store(false, Ordering::Relaxed);+ } // KINDa spaghetti code here - should be uniefied on the device manager thing / receive+ // also UX real time device vs non real time device is weird+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+ });+ let deepgram_api_key = deepgram_api_key.clone();+ let is_running_loop = Arc::clone(&is_running); // Create separate reference for the loop+ let audio_stream = match AudioStream::from_device(+ audio_device_clone.clone(),+ Arc::clone(&is_running_loop), // Clone from original Arc+ )+ .await+ {+ Ok(stream) => stream,+ Err(e) => {+ if e.to_string().contains("audio device not found") {+ if !did_warn {+ warn!("audio device not found: {}", audio_device.name);+ did_warn = true;+ }+ tokio::time::sleep(Duration::from_secs(1)).await;+ continue;+ } else {+ error!("failed to create audio stream: {}", e);+ return;+ }+ }+ };++ let mut recording_handles: Vec<JoinHandle<()>> = vec![];++ let audio_stream = Arc::new(audio_stream);+ let whisper_sender_clone = whisper_sender_clone.clone();+ let audio_stream_clone = audio_stream.clone();+ let is_running_loop_clone = is_running_loop.clone();+ let record_handle = Some(tokio::spawn(async move {+ let _ = record_and_transcribe(+ audio_stream,+ chunk_duration,+ whisper_sender_clone.clone(),+ is_running_loop_clone.clone(),+ )+ .await;+ }));++ if let Some(handle) = record_handle {+ recording_handles.push(handle);+ }- while is_running.load(Ordering::Relaxed) {- let deepgram_api_key = deepgram_api_key.clone();- let is_running_loop = Arc::clone(&is_running); // Create separate reference for the loop- let audio_stream = match AudioStream::from_device(- audio_device_clone.clone(),- Arc::clone(&is_running_loop), // Clone from original Arc- )- .await- {- Ok(stream) => stream,- Err(e) => {- if e.to_string().contains("Audio device not found") {- if !did_warn {- warn!("Audio device not found: {}", audio_device.name);- did_warn = true;+ let audio_device_clone = audio_device_clone.clone();+ let realtime_audio_devices_clone = realtime_audio_devices_clone.clone();+ let languages_clone = languages_clone.clone();+ let is_running_loop = is_running_loop.clone();+ let realtime_transcription_sender_clone =+ realtime_transcription_sender_clone.clone();+ let live_transcription_handle = Some(tokio::spawn(async move {+ if realtime_audio_enabled+ && realtime_audio_devices_clone.contains(&audio_device_clone)+ {+ let _ = start_realtime_recording(+ audio_stream_clone,+ languages_clone.clone(),+ is_running_loop.clone(),+ realtime_transcription_sender_clone.clone(),+ deepgram_api_key.clone(),+ )+ .await;+ }+ }));++ if let Some(handle) = live_transcription_handle {+ recording_handles.push(handle);}- tokio::time::sleep(Duration::from_secs(1)).await;- continue;- } else {- error!("Failed to create audio stream: {}", e);- return;- }- }- };- let mut recording_handles: Vec<JoinHandle<()>> = vec![];-- let audio_stream = Arc::new(audio_stream);- let whisper_sender_clone = whisper_sender_clone.clone();- let audio_stream_clone = audio_stream.clone();- let is_running_loop_clone = is_running_loop.clone();- let record_handle = Some(tokio::spawn(async move {- let _ = record_and_transcribe(- audio_stream,- chunk_duration,- whisper_sender_clone.clone(),- is_running_loop_clone.clone(),- )- .await;- }));-- if let Some(handle) = record_handle {- recording_handles.push(handle);- }+ join_all(recording_handles).await;+ }- let audio_device_clone = audio_device_clone.clone();- let realtime_audio_devices_clone = realtime_audio_devices_clone.clone();- let languages_clone = languages_clone.clone();- let is_running_loop = is_running_loop.clone();- let realtime_transcription_sender_clone =- realtime_transcription_sender_clone.clone();- let live_transcription_handle = Some(tokio::spawn(async move {- if realtime_audio_enabled- && realtime_audio_devices_clone.contains(&audio_device_clone)- {- let _ = start_realtime_recording(- audio_stream_clone,- languages_clone.clone(),- is_running_loop.clone(),- realtime_transcription_sender_clone.clone(),- deepgram_api_key.clone(),- )- .await;- }- }));+ });- if let Some(handle) = live_transcription_handle {- recording_handles.push(handle);+ handles.insert(device_id, handle);}-- join_all(recording_handles).await;+ DeviceType::Vision(_) => continue, // Ignore vision devices}+ }+ _ = tokio::time::sleep(Duration::from_millis(100)) => {- info!("exiting audio capture thread for device: {}", &audio_device);- });-- handles.insert(device_id, handle);+ }}-+ // Handle cleanup of finished handleshandles.retain(|device_id, handle| {if handle.is_finished() {- info!("Handle for device {} has finished", device_id);+ info!("handle for device {} has finished", device_id);false} else {true}});+ // Process transcription resultswhile let Ok(mut transcription) = whisper_receiver.try_recv() {info!("device {} received transcription {:?}",@@ -476,12 +601,10 @@ async fn record_audio().await{- Err(e) => error!("Error processing audio result: {}", e),+ Err(e) => error!("error processing audio result: {}", e),Ok(id) => previous_transcript_id = id,}}-- tokio::time::sleep(Duration::from_millis(100)).await;}}@@ -494,7 +617,7 @@ async fn process_audio_result() -> Result<Option<i64>, anyhow::Error> {if result.error.is_some() || result.transcription.is_none() {error!(- "Error in audio recording: {}. Not inserting audio result",+ "error in audio recording: {}. not inserting audio result",result.error.unwrap_or_default());return Ok(None);@@ -502,7 +625,7 @@ async fn process_audio_result(let speaker = get_or_create_speaker_from_embedding(db, &result.speaker_embedding).await?;- info!("Detected speaker: {:?}", speaker);+ info!("detected speaker: {:?}", speaker);let transcription = result.transcription.unwrap();let transcription_engine = audio_transcription_engine.to_string();@@ -520,7 +643,7 @@ async fn process_audio_result({Ok(_) => {}Err(e) => error!(- "Failed to update transcription for {}: audio_chunk_id {}",+ "failed to update transcription for {}: audio_chunk_id {}",result.input.device, e),}@@ -546,20 +669,20 @@ async fn process_audio_result(.await{error!(- "Failed to insert audio transcription for device {}: {}",+ "failed to insert audio transcription for device {}: {}",result.input.device, e);return Ok(Some(audio_chunk_id));} else {debug!(- "Inserted audio transcription for chunk {} from device {} using {}",+ "inserted audio transcription for chunk {} from device {} using {}",audio_chunk_id, result.input.device, transcription_engine);chunk_id = Some(audio_chunk_id);}}Err(e) => error!(- "Failed to insert audio chunk for device {}: {}",+ "failed to insert audio chunk for device {}: {}",result.input.device, e),}@@ -594,6 +717,6 @@ pub async fn merge_speakers(.await{Ok(speaker) => Ok(speaker),- Err(e) => Err(anyhow::anyhow!("Failed to merge speakers: {}", e)),+ Err(e) => Err(anyhow::anyhow!("failed to merge speakers: {}", e)),}}diff --git a/screenpipe-server/src/db.rs b/screenpipe-server/src/db.rsindex 60f71c50c..81b50f47a 100644--- a/screenpipe-server/src/db.rs+++ b/screenpipe-server/src/db.rs@@ -2,7 +2,7 @@ use chrono::{DateTime, Utc};use image::DynamicImage;use libsqlite3_sys::sqlite3_auto_extension;use log::{debug, error, warn};-use screenpipe_audio::{AudioDevice, DeviceType};+use screenpipe_core::{AudioDevice, AudioDeviceType};use screenpipe_vision::OcrEngine;use sqlite_vec::sqlite3_vec_init;use sqlx::migrate::MigrateDatabase;@@ -146,7 +146,7 @@ impl DatabaseManager {.bind(Utc::now()).bind(transcription_engine).bind(&device.name)- .bind(device.device_type == DeviceType::Input)+ .bind(device.device_type == AudioDeviceType::Input).bind(speaker_id).bind(start_time).bind(end_time)@@ -902,9 +902,9 @@ impl DatabaseManager {.unwrap_or_default(),device_name: raw.device_name,device_type: if raw.is_input_device {- DeviceType::Input+ AudioDeviceType::Input} else {- DeviceType::Output+ AudioDeviceType::Output},speaker,start_time: raw.start_time,diff --git a/screenpipe-server/src/db_types.rs b/screenpipe-server/src/db_types.rsindex 42d095e56..6c5352e8b 100644--- a/screenpipe-server/src/db_types.rs+++ b/screenpipe-server/src/db_types.rs@@ -1,5 +1,5 @@use chrono::{DateTime, Utc};-use screenpipe_audio::DeviceType;+use screenpipe_core::AudioDeviceType;use serde::{Deserialize, Serialize};use sqlx::FromRow;use std::error::Error as StdError;@@ -105,7 +105,7 @@ pub struct AudioResult {pub transcription_engine: String,pub tags: Vec<String>,pub device_name: String,- pub device_type: DeviceType,+ pub device_type: AudioDeviceType,pub speaker: Option<Speaker>,pub start_time: Option<f64>,pub end_time: Option<f64>,diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rsindex 42f0ed419..66894443f 100644--- a/screenpipe-server/src/server.rs+++ b/screenpipe-server/src/server.rs@@ -10,8 +10,10 @@ use futures::{Stream,};use image::ImageFormat::{self};+use screenpipe_core::{AudioDevice, AudioDeviceType, DeviceControl};use crate::{+ core::DeviceManager,db_types::{ContentType, SearchResult, Speaker, TagContentType},pipe_manager::PipeManager,video::{finish_ffmpeg_process, start_ffmpeg_process, write_frame_to_ffmpeg, MAX_FPS},@@ -27,25 +29,21 @@ use chrono::{DateTime, Utc};use log::{debug, error, info};use screenpipe_audio::{default_input_device, default_output_device, list_audio_devices,- realtime::RealtimeTranscriptionEvent, AudioDevice, DeviceControl, DeviceType,+ realtime::RealtimeTranscriptionEvent,};use screenpipe_vision::OcrEngine;use screenpipe_vision::{core::RealtimeVisionEvent, monitor::list_monitors};use serde::{Deserialize, Deserializer, Serialize};use serde_json::{json, Value};use std::{- collections::HashMap,convert::Infallible,net::SocketAddr,path::PathBuf,- sync::{- atomic::{AtomicBool, Ordering},- Arc,- },+ sync::{atomic::Ordering, Arc},time::Duration,};-use tokio::{net::TcpListener, sync::broadcast};+use tokio::net::TcpListener;use tower_http::{cors::Any, trace::TraceLayer};use tower_http::{cors::CorsLayer, trace::DefaultMakeSpan};@@ -61,9 +59,7 @@ use crate::text_embeds::generate_embedding;pub struct AppState {pub db: Arc<DatabaseManager>,- pub vision_control: Arc<AtomicBool>,- pub audio_devices_tx: Arc<broadcast::Sender<(AudioDevice, DeviceControl)>>,- pub devices_status: HashMap<AudioDevice, DeviceControl>,+ pub device_manager: Arc<DeviceManager>,pub app_start_time: DateTime<Utc>,pub screenpipe_dir: PathBuf,pub pipe_manager: Arc<PipeManager>,@@ -193,7 +189,7 @@ pub struct AudioContent {pub offset_index: i64,pub tags: Vec<String>,pub device_name: String,- pub device_type: DeviceType,+ pub device_type: AudioDeviceType,pub speaker: Option<Speaker>,pub start_time: Option<f64>,pub end_time: Option<f64>,@@ -696,7 +692,11 @@ async fn download_pipe_private_handler(State(state): State<Arc<AppState>>,JsonResponse(payload): JsonResponse<DownloadPipePrivateRequest>,) -> Result<JsonResponse<serde_json::Value>, (StatusCode, JsonResponse<Value>)> {- match state.pipe_manager.download_pipe_private(&payload.url, &payload.pipe_name, &payload.pipe_id).await {+ match state+ .pipe_manager+ .download_pipe_private(&payload.url, &payload.pipe_name, &payload.pipe_id)+ .await+ {Ok(pipe_dir) => Ok(JsonResponse(json!({"data": {"pipe_id": pipe_dir,@@ -841,8 +841,7 @@ async fn list_pipes_handler(State(state): State<Arc<AppState>>) -> JsonResponse<pub struct Server {db: Arc<DatabaseManager>,addr: SocketAddr,- vision_control: Arc<AtomicBool>,- audio_devices_tx: Arc<tokio::sync::broadcast::Sender<(AudioDevice, DeviceControl)>>,+ device_manager: Arc<DeviceManager>,screenpipe_dir: PathBuf,pipe_manager: Arc<PipeManager>,vision_disabled: bool,@@ -858,8 +857,7 @@ impl Server {pub fn new(db: Arc<DatabaseManager>,addr: SocketAddr,- vision_control: Arc<AtomicBool>,- audio_devices_tx: Arc<tokio::sync::broadcast::Sender<(AudioDevice, DeviceControl)>>,+ device_manager: Arc<DeviceManager>,screenpipe_dir: PathBuf,pipe_manager: Arc<PipeManager>,vision_disabled: bool,@@ -872,8 +870,7 @@ impl Server {Server {db,addr,- vision_control,- audio_devices_tx,+ device_manager,screenpipe_dir,pipe_manager,vision_disabled,@@ -887,7 +884,6 @@ impl Server {pub async fn start<F>(self,- device_status: HashMap<AudioDevice, DeviceControl>,api_plugin: F,enable_frame_cache: bool,) -> Result<(), std::io::Error>@@ -896,9 +892,7 @@ impl Server {{let app_state = Arc::new(AppState {db: self.db.clone(),- vision_control: self.vision_control,- audio_devices_tx: self.audio_devices_tx,- devices_status: device_status,+ device_manager: self.device_manager.clone(),app_start_time: Utc::now(),screenpipe_dir: self.screenpipe_dir.clone(),pipe_manager: self.pipe_manager,@@ -1126,7 +1120,7 @@ async fn add_transcription_to_db(let device = AudioDevice {name: device_name.to_string(),- device_type: DeviceType::Input,+ device_type: AudioDeviceType::Input,};let dummy_audio_chunk_id = db.insert_audio_chunk("").await?;@@ -1657,7 +1651,7 @@ async fn sse_transcription_handler(pub struct AudioDeviceControlRequest {device_name: String,#[serde(default)]- device_type: Option<DeviceType>,+ device_type: Option<AudioDeviceType>,}#[derive(Serialize)]@@ -1673,7 +1667,7 @@ async fn start_audio_device() -> Result<JsonResponse<AudioDeviceControlResponse>, (StatusCode, JsonResponse<Value>)> {let device = AudioDevice {name: payload.device_name.clone(),- device_type: payload.device_type.unwrap_or(DeviceType::Input),+ device_type: payload.device_type.unwrap_or(AudioDeviceType::Input),};// Validate device exists@@ -1698,11 +1692,12 @@ async fn start_audio_device(}let control = DeviceControl {+ device: screenpipe_core::DeviceType::Audio(device.clone()),is_running: true,is_paused: false,};- let _ = state.audio_devices_tx.send((device.clone(), control));+ let _ = state.device_manager.update_device(control).await;Ok(JsonResponse(AudioDeviceControlResponse {success: true,@@ -1716,7 +1711,7 @@ async fn stop_audio_device() -> Result<JsonResponse<AudioDeviceControlResponse>, (StatusCode, JsonResponse<Value>)> {let device = AudioDevice {name: payload.device_name.clone(),- device_type: payload.device_type.unwrap_or(DeviceType::Input),+ device_type: payload.device_type.unwrap_or(AudioDeviceType::Input),};// Validate device exists@@ -1740,13 +1735,14 @@ async fn stop_audio_device());}- let _ = state.audio_devices_tx.send((- device.clone(),- DeviceControl {+ let _ = state+ .device_manager+ .update_device(DeviceControl {+ device: screenpipe_core::DeviceType::Audio(device.clone()),is_running: false,is_paused: false,- },- ));+ })+ .await;Ok(JsonResponse(AudioDeviceControlResponse {success: true,@@ -1853,6 +1849,84 @@ async fn semantic_search_handler(}}+#[derive(Deserialize)]+pub struct VisionDeviceControlRequest {+ device_id: u32,+}++#[derive(Serialize)]+pub struct VisionDeviceControlResponse {+ success: bool,+ message: String,+}++async fn start_vision_device(+ State(state): State<Arc<AppState>>,+ Json(payload): Json<VisionDeviceControlRequest>,+) -> Result<JsonResponse<VisionDeviceControlResponse>, (StatusCode, JsonResponse<Value>)> {+ debug!("starting vision device: {}", payload.device_id);+ // Validate device exists+ let monitors = list_monitors().await;+ if !monitors.iter().any(|m| m.id() == payload.device_id) {+ return Err((+ StatusCode::BAD_REQUEST,+ JsonResponse(json!({+ "error": format!("monitor not found: {}", payload.device_id),+ "success": false+ })),+ ));+ }++ debug!("starting vision device: {}", payload.device_id);+ let _ = state+ .device_manager+ .update_device(DeviceControl {+ device: screenpipe_core::DeviceType::Vision(payload.device_id),+ is_running: true,+ is_paused: false,+ })+ .await;++ Ok(JsonResponse(VisionDeviceControlResponse {+ success: true,+ message: format!("started vision device: {}", payload.device_id),+ }))+}++async fn stop_vision_device(+ State(state): State<Arc<AppState>>,+ Json(payload): Json<VisionDeviceControlRequest>,+) -> Result<JsonResponse<VisionDeviceControlResponse>, (StatusCode, JsonResponse<Value>)> {+ debug!("stopping vision device: {}", payload.device_id);+ // Validate device exists+ let monitors = list_monitors().await;+ if !monitors.iter().any(|m| m.id() == payload.device_id) {+ return Err((+ StatusCode::BAD_REQUEST,+ JsonResponse(json!({+ "error": format!("monitor not found: {}", payload.device_id),+ "success": false+ })),+ ));+ }++ debug!("stopping vision device: {}", payload.device_id);++ let _ = state+ .device_manager+ .update_device(DeviceControl {+ device: screenpipe_core::DeviceType::Vision(payload.device_id),+ is_running: false,+ is_paused: false,+ })+ .await;++ Ok(JsonResponse(VisionDeviceControlResponse {+ success: true,+ message: format!("stopped vision device: {}", payload.device_id),+ }))+}+pub fn create_router() -> Router<Arc<AppState>> {let cors = CorsLayer::new().allow_origin(Any)@@ -1866,7 +1940,7 @@ pub fn create_router() -> Router<Arc<AppState>> {let router = Router::new().route("/search", get(search)).route("/audio/list", get(api_list_audio_devices))- .route("/vision/list", post(api_list_monitors))+ .route("/vision/list", get(api_list_monitors)).route("/tags/:content_type/:id",post(add_tags).delete(remove_tags),@@ -1874,7 +1948,10 @@ pub fn create_router() -> Router<Arc<AppState>> {.route("/pipes/info/:pipe_id", get(get_pipe_info_handler)).route("/pipes/list", get(list_pipes_handler)).route("/pipes/download", post(download_pipe_handler))- .route("/pipes/download-private", post(download_pipe_private_handler))+ .route(+ "/pipes/download-private",+ post(download_pipe_private_handler),+ ).route("/pipes/enable", post(run_pipe_handler)).route("/pipes/disable", post(stop_pipe_handler)).route("/pipes/update", post(update_pipe_config_handler))@@ -1900,6 +1977,8 @@ pub fn create_router() -> Router<Arc<AppState>> {.route("/audio/stop", post(stop_audio_device)).route("/sse/vision", get(sse_vision_handler)).route("/semantic-search", get(semantic_search_handler))+ .route("/vision/start", post(start_vision_device))+ .route("/vision/stop", post(stop_vision_device)).layer(cors);#[cfg(feature = "experimental")]@@ -2033,221 +2112,3 @@ struct MergeSpeakersRequest {speaker_to_keep_id: i64,speaker_to_merge_id: i64,}-/*--Curl commands for reference:-# 1. Basic search query-curl "http://localhost:3030/search?q=test&limit=5&offset=0" | jq--# 2. Search with content type filter (OCR)-curl "http://localhost:3030/search?q=test&limit=5&offset=0&content_type=ocr" | jq--# 3. Search with content type filter (Audio)-curl "http://localhost:3030/search?q=test&limit=5&offset=0&content_type=audio" | jq--# 4. Search with pagination-curl "http://localhost:3030/search?q=test&limit=10&offset=20" | jq--# 6. Search with no query (should return all results)-curl "http://localhost:3030/search?limit=5&offset=0"--// list devices-// # curl "http://localhost:3030/audio/list" | jq---echo "Listing audio devices:"-curl "http://localhost:3030/audio/list" | jq---echo "Searching for content:"-curl "http://localhost:3030/search?q=test&limit=5&offset=0&content_type=all" | jq-curl "http://localhost:3030/search?limit=5&offset=0&content_type=ocr" | jq--curl "http://localhost:3030/search?q=libmp3&limit=5&offset=0&content_type=all" | jq--# last 5 w frames-curl "http://localhost:3030/search?limit=5&offset=0&content_type=all&include_frames=true&start_time=$(date -u -v-5M +%Y-%m-%dT%H:%M:%SZ)" | jq--# 30 min to 25 min ago-curl "http://localhost:3030/search?limit=5&offset=0&content_type=all&include_frames=true&start_time=$(date -u -v-30M +%Y-%m-%dT%H:%M:%SZ)&end_time=$(date -u -v-25M +%Y-%m-%dT%H:%M:%SZ)" | jq--curl "http://localhost:3030/search?limit=1&offset=0&content_type=all&include_frames=true&start_time=$(date -u -v-30M +%Y-%m-%dT%H:%M:%SZ)&end_time=$(date -u -v-25M +%Y-%m-%dT%H:%M:%SZ)" | jq -r '.data[0].content.frame' | base64 --decode > /tmp/frame.png && open /tmp/frame.png--# Search for content from the last 30 minutes-curl "http://localhost:3030/search?q=test&limit=5&offset=0&content_type=all&start_time=$(date -u -v-30M +%Y-%m-%dT%H:%M:%SZ)&end_time=$(date -u -v-25M +%Y-%m-%dT%H:%M:%SZ)" | jq--# Search for content up to 1 hour ago-curl "http://localhost:3030/search?q=test&limit=5&offset=0&content_type=all&end_time=$(date -u -v-1H +%Y-%m-%dT%H:%M:%SZ)" | jq--# Search for content between 2 hours ago and 1 hour ago-curl "http://localhost:3030/search?q=test&limit=5&offset=0&content_type=all&start_time=$(date -u -v-2H +%Y-%m-%dT%H:%M:%SZ)&end_time=$(date -u -v-1H +%Y-%m-%dT%H:%M:%SZ)" | jq--# Search for OCR content from yesterday-curl "http://localhost:3030/search?q=test&limit=5&offset=0&content_type=ocr&start_time=$(date -u -v-1d -v0H -v0M -v0S +%Y-%m-%dT%H:%M:%SZ)&end_time=$(date -u -v-1d -v23H -v59M -v59S +%Y-%m-%dT%H:%M:%SZ)" | jq--# Search for audio content with a keyword from the beginning of the current month-curl "http://localhost:3030/search?q=libmp3&limit=5&offset=0&content_type=audio&start_time=$(date -u -v1d -v0H -v0M -v0S +%Y-%m-01T%H:%M:%SZ)" | jq--curl "http://localhost:3030/search?app_name=cursor"-curl "http://localhost:3030/search?content_type=audio&min_length=20"--curl "http://localhost:3030/search?q=Matt&offset=0&limit=50&start_time=$(date -u -v-2H +%Y-%m-%dT%H:%M:%SZ)&end_time=$(date -u -v-1H +%Y-%m-%dT%H:%M:%SZ)" | jq .---curl "http://localhost:3030/search?limit=50&offset=0&content_type=all&start_time=$(date -u -v-2H +%Y-%m-%dT%H:%M:%SZ)&end_time=$(date -u -v-1H +%Y-%m-%dT%H:%M:%SZ)" | jq--date -u -v-2H +%Y-%m-%dT%H:%M:%SZ-2024-08-12T06:51:54Z-date -u -v-1H +%Y-%m-%dT%H:%M:%SZ-2024-08-12T07:52:17Z--curl 'http://localhost:3030/search?limit=50&offset=0&content_type=all&start_time=2024-08-12T06:48:18Z&end_time=2024-08-12T07:48:34Z' | jq .---curl "http://localhost:3030/search?q=Matt&offset=0&limit=10&start_time=2024-08-12T04:00:00Z&end_time=2024-08-12T05:00:00Z&content_type=all" | jq .--curl "http://localhost:3030/search?q=Matt&offset=0&limit=10&start_time=2024-08-12T06:43:53Z&end_time=2024-08-12T08:43:53Z&content_type=all" | jq .--curl 'http://localhost:3030/search?offset=0&limit=10&start_time=2024-08-12T04%3A00%3A00Z&end_time=2024-08-12T05%3A00%3A00Z&content_type=all' | jq .------------# First, search for Rust-related content-curl "http://localhost:3030/search?q=debug&limit=5&offset=0&content_type=ocr"--# Then, assuming you found a relevant item with id 123, tag it-curl -X POST "http://localhost:3030/tags/vision/626" \- -H "Content-Type: application/json" \- -d '{"tags": ["debug"]}'-----# List all pipes-curl "http://localhost:3030/pipes/list" | jq--# Download a new pipe-curl -X POST "http://localhost:3030/pipes/download" \- -H "Content-Type: application/json" \- -d '{"url": "./pipes/pipe-stream-ocr-text"}' | jq--curl -X POST "http://localhost:3030/pipes/download" \- -H "Content-Type: application/json" \- -d '{"url": "./pipes/pipe-security-check"}' | jq---curl -X POST "http://localhost:3030/pipes/download" \- -H "Content-Type: application/json" \- -d '{"url": "https://github.com/mediar-ai/screenpipe/tree/main/pipes/pipe-stream-ocr-text"}' | jq---# Get info for a specific pipe-curl "http://localhost:3030/pipes/info/pipe-stream-ocr-text" | jq--# Run a pipe-curl -X POST "http://localhost:3030/pipes/enable" \- -H "Content-Type: application/json" \- -d '{"pipe_id": "pipe-stream-ocr-text"}' | jq---- curl -X POST "http://localhost:3030/pipes/enable" \- -H "Content-Type: application/json" \- -d '{"pipe_id": "pipe-security-check"}' | jq--# Stop a pipe-curl -X POST "http://localhost:3030/pipes/disable" \- -H "Content-Type: application/json" \- -d '{"pipe_id": "pipe-stream-ocr-text"}' | jq--# Update pipe configuration-curl -X POST "http://localhost:3030/pipes/update" \- -H "Content-Type: application/json" \- -d '{- "pipe_id": "pipe-stream-ocr-text",- "config": {- "key": "value",- "another_key": "another_value"- }- }' | jq------# Basic search with min_length and max_length-curl "http://localhost:3030/search?q=test&limit=10&offset=0&min_length=5&max_length=50" | jq--# Search for OCR content with length constraints-curl "http://localhost:3030/search?q=code&content_type=ocr&limit=5&offset=0&min_length=20&max_length=100" | jq--# Search for audio content with length constraints-curl "http://localhost:3030/search?q=meeting&content_type=audio&limit=5&offset=0&min_length=50&max_length=200" | jq--# Search with time range and length constraints-curl "http://localhost:3030/search?q=project&limit=10&offset=0&min_length=10&max_length=100&start_time=$(date -u -v-1H +%Y-%m-%dT%H:%M:%SZ)&end_time=$(date -u +%Y-%m-%dT%H:%M:%SZ)" | jq--# Search with app_name and length constraints-curl "http://localhost:3030/search?app_name=cursor&limit=5&offset=0&min_length=15&max_length=150" | jq--# Search with window_name and length constraints-curl "http://localhost:3030/search?window_name=alacritty&min_length=5&max_length=50" | jq--# Search for very short content-curl "http://localhost:3030/search?q=&limit=10&offset=0&max_length=10" | jq--# Search for very long content-curl "http://localhost:3030/search?q=&limit=10&offset=0&min_length=500" | jq---curl "http://localhost:3030/search?limit=10&offset=0&min_length=500&content_type=audio" | jq---# read random data and generate a clip using the merge endpoint---# Perform the search and store the response--# First, let's search for some recent video content-SEARCH_RESPONSE1=$(curl -s "http://localhost:3030/search?q=&limit=5&offset=0&content_type=ocr&start_time=$(date -u -v-30M +%Y-%m-%dT%H:%M:%SZ)&end_time=$(date -u -v-25M +%Y-%m-%dT%H:%M:%SZ)")-SEARCH_RESPONSE2=$(curl -s "http://localhost:3030/search?q=&limit=5&offset=0&content_type=ocr&start_time=$(date -u -v-40M +%Y-%m-%dT%H:%M:%SZ)&end_time=$(date -u -v-35M +%Y-%m-%dT%H:%M:%SZ)")-SEARCH_RESPONSE3=$(curl -s "http://localhost:3030/search?q=&limit=5&offset=0&content_type=ocr&start_time=$(date -u -v-50M +%Y-%m-%dT%H:%M:%SZ)&end_time=$(date -u -v-45M +%Y-%m-%dT%H:%M:%SZ)")--# Extract the file paths from the search results without creating JSON arrays-VIDEO_PATHS1=$(echo "$SEARCH_RESPONSE1" | jq -r '.data[].content.file_path' | sort -u)-VIDEO_PATHS2=$(echo "$SEARCH_RESPONSE2" | jq -r '.data[].content.file_path' | sort -u)-VIDEO_PATHS3=$(echo "$SEARCH_RESPONSE3" | jq -r '.data[].content.file_path' | sort -u)--# Merge the video paths and create a single JSON array-MERGED_VIDEO_PATHS=$(echo "$VIDEO_PATHS1"$'\n'"$VIDEO_PATHS2"$'\n'"$VIDEO_PATHS3" | sort -u | jq -R -s -c 'split("\n") | map(select(length > 0))')--# Create the JSON payload for merging videos-MERGE_PAYLOAD=$(jq -n \- --argjson video_paths "$MERGED_VIDEO_PATHS" \- '{- video_paths: $video_paths- }')--echo "Merge Payload: $MERGE_PAYLOAD"--# Send the merge request and store the response-MERGE_RESPONSE=$(curl -s -X POST "http://localhost:3030/experimental/frames/merge" \- -H "Content-Type: application/json" \- -d "$MERGE_PAYLOAD")--echo "Merge Response: $MERGE_RESPONSE"--# Extract the merged video path from the response-MERGED_VIDEO_PATH=$(echo "$MERGE_RESPONSE" | jq -r '.video_path')--echo "Merged Video Path: $MERGED_VIDEO_PATH"--*/diff --git a/screenpipe-server/src/video.rs b/screenpipe-server/src/video.rsindex 24fe68e54..6249b3244 100644--- a/screenpipe-server/src/video.rs+++ b/screenpipe-server/src/video.rs@@ -16,6 +16,8 @@ use tokio::io::AsyncWriteExt;use tokio::io::BufReader;use tokio::process::{Child, ChildStderr, ChildStdin, ChildStdout, Command};use tokio::sync::mpsc::channel;+use tokio::sync::watch;+use tokio::task::JoinHandle;use tokio::time::sleep;pub(crate) const MAX_FPS: f64 = 30.0; // Adjust based on your needs@@ -25,10 +27,11 @@ pub struct VideoCapture {#[allow(unused)]video_frame_queue: Arc<ArrayQueue<Arc<CaptureResult>>>,pub ocr_frame_queue: Arc<ArrayQueue<Arc<CaptureResult>>>,+ shutdown_tx: watch::Sender<bool>,+ handles: Vec<JoinHandle<()>>,}impl VideoCapture {- #[allow(clippy::too_many_arguments)]pub fn new(output_path: &str,fps: f64,@@ -36,8 +39,8 @@ impl VideoCapture {new_chunk_callback: impl Fn(&str) + Send + Sync + 'static,ocr_engine: Arc<OcrEngine>,monitor_id: u32,- ignore_list: &[String],- include_list: &[String],+ ignore_list: Vec<String>,+ include_list: Vec<String>,languages: Vec<Language>,capture_unfocused_windows: bool,) -> Self {@@ -56,48 +59,58 @@ impl VideoCapture {let capture_video_frame_queue = video_frame_queue.clone();let capture_ocr_frame_queue = ocr_frame_queue.clone();let (result_sender, mut result_receiver) = channel(512);- let window_filters = Arc::new(WindowFilters::new(ignore_list, include_list));+ let window_filters = Arc::new(WindowFilters::new(&ignore_list, &include_list));let window_filters_clone = Arc::clone(&window_filters);- let _capture_thread = tokio::spawn(async move {- continuous_capture(- result_sender,- interval,- (*ocr_engine).clone(),- monitor_id,- window_filters_clone,- languages.clone(),- capture_unfocused_windows,- )- .await;- });-- // In the _queue_thread- let _queue_thread = tokio::spawn(async move {- // Helper function to push to queue and handle errors- fn push_to_queue(- queue: &ArrayQueue<Arc<CaptureResult>>,- result: &Arc<CaptureResult>,- queue_name: &str,- ) -> bool {- if queue.push(Arc::clone(result)).is_err() {- if queue.pop().is_none() {- error!("{} queue is in an inconsistent state", queue_name);- return false;+ let (shutdown_tx, shutdown_rx) = watch::channel(false);+ let mut handles = Vec::new();+ let shutdown_rx_capture = shutdown_rx.clone();+ let shutdown_rx_queue = shutdown_rx.clone();+ let shutdown_rx_video = shutdown_rx.clone();++ let capture_handle = tokio::spawn(async move {+ let mut rx = shutdown_rx_capture;+ loop {+ if *rx.borrow() {+ info!("shutting down video capture thread");+ break;+ }+ let result_sender = result_sender.clone();+ let window_filters_clone = Arc::clone(&window_filters_clone);++ tokio::select! {+ _ = continuous_capture(+ result_sender,+ interval,+ (*ocr_engine).clone(),+ monitor_id,+ window_filters_clone,+ languages.clone(),+ capture_unfocused_windows,+ rx.clone(),+ ) => {+ // If continuous_capture returns, we can continue the loop+ debug!("continuous capture completed, restarting");}- if queue.push(Arc::clone(result)).is_err() {- error!(- "Failed to push to {} queue after removing oldest frame",- queue_name- );- return false;+ _ = rx.changed() => {+ if *rx.borrow() {+ info!("shutting down video capture thread");+ break;+ }}- debug!("{} queue was full, dropped oldest frame", queue_name);}- true}+ });+ handles.push(capture_handle);++ let queue_handle = tokio::spawn(async move {+ let rx = shutdown_rx_queue;while let Some(result) = result_receiver.recv().await {+ if *rx.borrow() {+ info!("shutting down video queue thread");+ break;+ }let frame_number = result.frame_number;- debug!("Received frame {} for queueing", frame_number);+ debug!("received frame {} for queueing", frame_number);let result = Arc::new(result);@@ -106,45 +119,63 @@ impl VideoCapture {if !video_pushed || !ocr_pushed {error!(- "Failed to push frame {} to one or more queues",+ "failed to push frame {} to one or more queues",frame_number);continue; // Skip to next iteration instead of crashing}debug!(- "Frame {} pushed to queues. Queue lengths: {}, {}",+ "frame {} pushed to queues. Queue lengths: {}, {}",frame_number,capture_video_frame_queue.len(),capture_ocr_frame_queue.len());}});+ handles.push(queue_handle);let video_frame_queue_clone = video_frame_queue.clone();let output_path = output_path.to_string();- let _video_thread = tokio::spawn(async move {- save_frames_as_video(+ let video_handle = tokio::spawn(async move {+ let rx = shutdown_rx_video;+ save_frames_as_video_with_shutdown(&video_frame_queue_clone,&output_path,fps,new_chunk_callback_clone,monitor_id,video_chunk_duration,+ rx,).await;});+ handles.push(video_handle);VideoCapture {video_frame_queue,ocr_frame_queue,+ shutdown_tx,+ handles,+ }+ }++ pub async fn shutdown(self) -> Result<(), anyhow::Error> {+ info!("shutting down video capture");+ self.shutdown_tx.send(true)?;++ for handle in self.handles {+ if let Err(e) = handle.await {+ error!("error joining handle: {}", e);+ }}++ Ok(())}}pub async fn start_ffmpeg_process(output_file: &str, fps: f64) -> Result<Child, anyhow::Error> {- // Overriding fps with max fps if over the max and warning userlet fps = if fps > MAX_FPS {warn!("Overriding FPS from {} to {}", fps, MAX_FPS);MAX_FPS@@ -152,7 +183,7 @@ pub async fn start_ffmpeg_process(output_file: &str, fps: f64) -> Result<Child,fps};- info!("Starting FFmpeg process for file: {}", output_file);+ info!("starting FFmpeg process for file: {}", output_file);let fps_str = fps.to_string();let mut command = Command::new(find_ffmpeg_path().unwrap());let mut args = vec![@@ -211,21 +242,30 @@ async fn log_ffmpeg_output(stream: impl AsyncBufReadExt + Unpin, stream_name: &s}}-async fn save_frames_as_video(+async fn save_frames_as_video_with_shutdown(frame_queue: &Arc<ArrayQueue<Arc<CaptureResult>>>,output_path: &str,fps: f64,new_chunk_callback: Arc<dyn Fn(&str) + Send + Sync>,monitor_id: u32,video_chunk_duration: Duration,+ mut shutdown_rx: watch::Receiver<bool>,) {- debug!("Starting save_frames_as_video function");+ debug!("starting save_frames_as_video function");let frames_per_video = (fps * video_chunk_duration.as_secs_f64()).ceil() as usize;let mut frame_count = 0;let mut current_ffmpeg: Option<Child> = None;let mut current_stdin: Option<ChildStdin> = None;loop {+ if *shutdown_rx.borrow() {+ info!("shutting down video capture thread");+ if let Some(child) = current_ffmpeg.take() {+ finish_ffmpeg_process(child, current_stdin.take()).await;+ }+ break;+ }+if frame_count >= frames_per_video || current_ffmpeg.is_none() {if let Some(child) = current_ffmpeg.take() {finish_ffmpeg_process(child, current_stdin.take()).await;@@ -244,17 +284,17 @@ async fn save_frames_as_video(spawn_ffmpeg_loggers(child.stderr.take(), child.stdout.take());if let Err(e) = write_frame_to_ffmpeg(&mut stdin, &buffer).await {- error!("Failed to write first frame to ffmpeg: {}", e);+ error!("failed to write first frame to ffmpeg: {}", e);continue;}frame_count += 1;current_ffmpeg = Some(child);current_stdin = Some(stdin);- debug!("New FFmpeg process started for file: {}", output_file);+ debug!("new FFmpeg process started for file: {}", output_file);}Err(e) => {- error!("Failed to start FFmpeg process: {}", e);+ error!("failed to start FFmpeg process: {}", e);continue;}}@@ -269,7 +309,19 @@ async fn save_frames_as_video().await;- tokio::task::yield_now().await;+ tokio::select! {+ _ = shutdown_rx.changed() => {+ if *shutdown_rx.borrow() {+ if let Some(child) = current_ffmpeg.take() {+ finish_ffmpeg_process(child, current_stdin.take()).await;+ }+ break;+ }+ }+ _ = tokio::time::sleep(Duration::from_millis(10)) => {+ // Continue with normal processing+ }+ }}}@@ -392,3 +444,26 @@ pub async fn finish_ffmpeg_process(child: Child, stdin: Option<ChildStdin>) {Err(e) => error!("Failed to wait for FFmpeg process: {}", e),}}++fn push_to_queue(+ queue: &ArrayQueue<Arc<CaptureResult>>,+ result: &Arc<CaptureResult>,+ queue_name: &str,+) -> bool {+ match queue.push(Arc::clone(result)) {+ Ok(_) => {+ debug!(+ "{} queue: Successfully pushed frame {}",+ queue_name, result.frame_number+ );+ true+ }+ Err(_) => {+ warn!(+ "{} queue full, dropping frame {}",+ queue_name, result.frame_number+ );+ false+ }+ }+}diff --git a/screenpipe-vision/src/bin/screenpipe-vision.rs b/screenpipe-vision/src/bin/screenpipe-vision.rsindex 7c777096b..bc1d02834 100644--- a/screenpipe-vision/src/bin/screenpipe-vision.rs+++ b/screenpipe-vision/src/bin/screenpipe-vision.rs@@ -5,7 +5,7 @@ use screenpipe_vision::{OcrEngine,};use std::{sync::Arc, time::Duration};-use tokio::sync::mpsc::channel;+use tokio::sync::{mpsc::channel, watch};use tracing_subscriber::{fmt::format::FmtSpan, EnvFilter};#[derive(Parser)]@@ -39,6 +39,8 @@ async fn main() {let id = monitor.id();let window_filters = WindowFilters::new(&[], &[]);+ let (_, shutdown_rx) = watch::channel(false);+tokio::spawn(async move {continuous_capture(result_tx,@@ -48,6 +50,7 @@ async fn main() {Arc::new(window_filters),languages.clone(),false,+ shutdown_rx,).await});diff --git a/screenpipe-vision/src/core.rs b/screenpipe-vision/src/core.rsindex 6640f38d2..cda7926f6 100644--- a/screenpipe-vision/src/core.rs+++ b/screenpipe-vision/src/core.rs@@ -29,7 +29,8 @@ use std::{use tokio::fs::File;use tokio::io::{AsyncBufReadExt, BufReader};use tokio::sync::mpsc::Sender;-use tokio::time::sleep;+use tokio::sync::watch;+use tracing::info;#[cfg(target_os = "macos")]use xcap_macos::Monitor;@@ -138,6 +139,7 @@ pub async fn continuous_capture(window_filters: Arc<WindowFilters>,languages: Vec<Language>,capture_unfocused_windows: bool,+ mut shutdown_rx: watch::Receiver<bool>,) {let mut frame_counter: u64 = 0;let mut previous_image: Option<DynamicImage> = None;@@ -149,102 +151,119 @@ pub async fn continuous_capture(monitor_id);+ let monitor = get_monitor_by_id(monitor_id).await.unwrap();+loop {- let monitor = match get_monitor_by_id(monitor_id).await {- Some(m) => m,- None => {- sleep(Duration::from_secs(1)).await;- continue;- }- };- let capture_result =- match capture_screenshot(&monitor, &window_filters, capture_unfocused_windows).await {- Ok((image, window_images, image_hash, _capture_duration)) => {- debug!(- "Captured screenshot on monitor {} with hash: {}",- monitor_id, image_hash- );- Some((image, window_images, image_hash))- }- Err(e) => {- error!("Failed to capture screenshot: {}", e);- None- }- };-- if let Some((image, window_images, image_hash)) = capture_result {- let current_average = match compare_with_previous_image(- previous_image.as_ref(),- &image,- &mut max_average,- frame_counter,- &mut max_avg_value,- )- .await- {- Ok(avg) => avg,- Err(e) => {- error!("Error comparing images: {}", e);- 0.0- }- };-- let current_average = if previous_image.is_none() {- 1.0- } else {- current_average- };-- if current_average < 0.006 {- debug!(- "Skipping frame {} due to low average difference: {:.3}",- frame_counter, current_average- );- frame_counter += 1;- tokio::time::sleep(interval).await;- continue;- }+ // Check shutdown signal+ if *shutdown_rx.borrow() {+ info!(+ "continuous_capture: received shutdown signal for monitor {}",+ monitor_id+ );+ break;+ }- if current_average > max_avg_value {- max_average = Some(MaxAverageFrame {- image: image.clone(),- window_images: window_images.clone(),- image_hash,- frame_number: frame_counter,- timestamp: Instant::now(),- result_tx: result_tx.clone(),- average: current_average,- });- max_avg_value = current_average;+ // Use tokio::select! to handle both capture and shutdown+ tokio::select! {+ _ = shutdown_rx.changed() => {+ if *shutdown_rx.borrow() {+ info!("continuous_capture: shutdown signal received for monitor {}", monitor_id);+ break;+ }}-- previous_image = Some(image);-- if let Some(max_avg_frame) = max_average.take() {- let ocr_task_data = OcrTaskData {- image: max_avg_frame.image,- window_images: max_avg_frame.window_images,- frame_number: max_avg_frame.frame_number,- timestamp: max_avg_frame.timestamp,- result_tx: max_avg_frame.result_tx,+ _ = async {+ let capture_result = match capture_screenshot(&monitor, &window_filters, capture_unfocused_windows).await {+ Ok((image, window_images, image_hash, _capture_duration)) => {+ debug!(+ "captured screenshot on monitor {} with hash: {}",+ monitor.id(),+ image_hash+ );+ Some((image, window_images, image_hash))+ }+ Err(e) => {+ error!("Failed to capture screenshot: {}", e);+ None+ }};- if let Err(e) =- process_ocr_task(ocr_task_data, &ocr_engine, languages.clone()).await- {- error!("Error processing OCR task: {}", e);+ if let Some((image, window_images, image_hash)) = capture_result {+ let current_average = match compare_with_previous_image(+ previous_image.as_ref(),+ &image,+ &mut max_average,+ frame_counter,+ &mut max_avg_value,+ )+ .await+ {+ Ok(avg) => avg,+ Err(e) => {+ error!("Error comparing images: {}", e);+ 0.0+ }+ };++ let current_average = if previous_image.is_none() {+ 1.0+ } else {+ current_average+ };++ if current_average < 0.006 {+ debug!(+ "Skipping frame {} due to low average difference: {:.3}",+ frame_counter, current_average+ );+ frame_counter += 1;+ tokio::time::sleep(interval).await;+ return;+ }++ if current_average > max_avg_value {+ max_average = Some(MaxAverageFrame {+ image: image.clone(),+ window_images: window_images.clone(),+ image_hash,+ frame_number: frame_counter,+ timestamp: Instant::now(),+ result_tx: result_tx.clone(),+ average: current_average,+ });+ max_avg_value = current_average;+ }++ previous_image = Some(image);++ if let Some(max_avg_frame) = max_average.take() {+ let ocr_task_data = OcrTaskData {+ image: max_avg_frame.image,+ window_images: max_avg_frame.window_images,+ frame_number: max_avg_frame.frame_number,+ timestamp: max_avg_frame.timestamp,+ result_tx: max_avg_frame.result_tx,+ };++ if let Err(e) =+ process_ocr_task(ocr_task_data, &ocr_engine, languages.clone()).await+ {+ error!("Error processing OCR task: {}", e);+ }++ frame_counter = 0;+ max_avg_value = 0.0;+ }+ } else {+ debug!("Skipping frame {} due to capture failure", frame_counter);}- frame_counter = 0;- max_avg_value = 0.0;- }- } else {- debug!("Skipping frame {} due to capture failure", frame_counter);+ frame_counter += 1;+ tokio::time::sleep(interval).await;+ } => {}}-- frame_counter += 1;- tokio::time::sleep(interval).await;}++ debug!("Continuous capture stopped for monitor {}", monitor_id);}pub struct MaxAverageFrame {diff --git a/screenpipe-vision/src/monitor.rs b/screenpipe-vision/src/monitor.rsindex c48f07a48..f96196751 100644--- a/screenpipe-vision/src/monitor.rs+++ b/screenpipe-vision/src/monitor.rs@@ -4,6 +4,7 @@ use xcap_macos::Monitor;#[cfg(not(target_os = "macos"))]use xcap::Monitor;+pub async fn list_monitors() -> Vec<Monitor> {Monitor::all().unwrap().to_vec()}