Skip to content

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

fix: race condition with device controls and reduce ffmpeg CPU / memory usage by 3x

Louis Beaumont07cdb823e2cf
diff --git a/screenpipe-audio/benches/record_and_transcribe_benchmark.rs b/screenpipe-audio/benches/record_and_transcribe_benchmark.rs
index 6db272b65..dbc5dc40b 100644
--- a/screenpipe-audio/benches/record_and_transcribe_benchmark.rs
+++ b/screenpipe-audio/benches/record_and_transcribe_benchmark.rs
@@ -1,11 +1,10 @@
use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criterion};
-use dashmap::DashMap;
use screenpipe_audio::vad_engine::VadSensitivity;
use screenpipe_audio::{
create_whisper_channel, default_input_device, record_and_transcribe, AudioInput, AudioStream,
AudioTranscriptionEngine,
};
-use screenpipe_core::AudioDevice;
+use screenpipe_core::{AudioDevice, DeviceManager};
use std::path::PathBuf;
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
@@ -27,7 +26,7 @@ async fn setup_test() -> (
&output_path,
VadSensitivity::High,
vec![],
- DashMap::new(),
+ Arc::new(DeviceManager::default()),
)
.await
.unwrap();
diff --git a/screenpipe-audio/src/bin/screenpipe-audio-forever.rs b/screenpipe-audio/src/bin/screenpipe-audio-forever.rs
index 029d56d2b..fbf5ad13c 100644
--- a/screenpipe-audio/src/bin/screenpipe-audio-forever.rs
+++ b/screenpipe-audio/src/bin/screenpipe-audio-forever.rs
@@ -1,6 +1,5 @@
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;
@@ -13,6 +12,7 @@ use screenpipe_audio::AudioStream;
use screenpipe_audio::AudioTranscriptionEngine;
use screenpipe_audio::VadEngineEnum;
use screenpipe_core::AudioDevice;
+use screenpipe_core::DeviceManager;
use screenpipe_core::Language;
use std::path::PathBuf;
use std::sync::atomic::AtomicBool;
@@ -96,7 +96,7 @@ async fn main() -> Result<()> {
&PathBuf::from("output.mp4"),
VadSensitivity::Medium,
languages,
- DashMap::new(),
+ Arc::new(DeviceManager::default()),
)
.await?;
diff --git a/screenpipe-audio/src/bin/screenpipe-audio.rs b/screenpipe-audio/src/bin/screenpipe-audio.rs
index a05b459cd..733780e64 100644
--- a/screenpipe-audio/src/bin/screenpipe-audio.rs
+++ b/screenpipe-audio/src/bin/screenpipe-audio.rs
@@ -1,6 +1,5 @@
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;
@@ -13,6 +12,7 @@ use screenpipe_audio::AudioStream;
use screenpipe_audio::AudioTranscriptionEngine;
use screenpipe_audio::VadEngineEnum;
use screenpipe_core::AudioDevice;
+use screenpipe_core::DeviceManager;
use screenpipe_core::Language;
use std::path::PathBuf;
use std::sync::atomic::AtomicBool;
@@ -100,7 +100,7 @@ async fn main() -> Result<()> {
&output_path,
VadSensitivity::Medium,
languages,
- DashMap::new(),
+ Arc::new(DeviceManager::default()),
)
.await?;
// Spawn threads for each device
diff --git a/screenpipe-audio/src/stt.rs b/screenpipe-audio/src/stt.rs
index 9df63adbc..99b255308 100644
--- a/screenpipe-audio/src/stt.rs
+++ b/screenpipe-audio/src/stt.rs
@@ -12,11 +12,10 @@ use crate::{
};
use anyhow::{anyhow, Result};
use candle_transformers::models::whisper as m;
-use dashmap::DashMap;
use log::{debug, error};
#[cfg(target_os = "macos")]
use objc::rc::autoreleasepool;
-use screenpipe_core::{AudioDevice, DeviceControl, Language};
+use screenpipe_core::{AudioDevice, DeviceManager, Language};
use std::{
path::Path,
sync::Arc,
@@ -155,7 +154,7 @@ pub async fn create_whisper_channel(
output_path: &Path,
vad_sensitivity: VadSensitivity,
languages: Vec<Language>,
- devices: DashMap<String, DeviceControl>,
+ device_manager: Arc<DeviceManager>,
) -> Result<(
crossbeam::channel::Sender<AudioInput>,
crossbeam::channel::Receiver<TranscriptionResult>,
@@ -195,10 +194,9 @@ pub async fn create_whisper_channel(
match input_result {
Ok(mut audio) => {
// Check device state
- if let Some(device) = devices.get(&audio.device.to_string()) {
+ if let Some(device) = device_manager.get_active_devices().await.get(&audio.device.to_string()) {
if !device.is_running {
debug!("Skipping audio processing for stopped device: {}", audio.device);
- debug!("Device states: {:?}", devices);
continue;
}
}
diff --git a/screenpipe-audio/tests/core_tests.rs b/screenpipe-audio/tests/core_tests.rs
index 1d7d35a57..4fe1b8680 100644
--- a/screenpipe-audio/tests/core_tests.rs
+++ b/screenpipe-audio/tests/core_tests.rs
@@ -2,7 +2,6 @@
mod tests {
use anyhow::anyhow;
use chrono::Utc;
- use dashmap::DashMap;
use log::{debug, LevelFilter};
use screenpipe_audio::pyannote::embedding::EmbeddingExtractor;
use screenpipe_audio::pyannote::identify::EmbeddingManager;
@@ -14,7 +13,7 @@ mod tests {
AudioTranscriptionEngine,
};
use screenpipe_audio::{parse_audio_device, record_and_transcribe};
- use screenpipe_core::Language;
+ use screenpipe_core::{DeviceManager, Language};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::str::FromStr;
@@ -217,7 +216,7 @@ mod tests {
&output_path_2.clone(),
VadSensitivity::High,
vec![],
- DashMap::new(),
+ Arc::new(DeviceManager::default()),
)
.await
.unwrap();
diff --git a/screenpipe-core/Cargo.toml b/screenpipe-core/Cargo.toml
index c6ae00a8e..c77727656 100644
--- a/screenpipe-core/Cargo.toml
+++ b/screenpipe-core/Cargo.toml
@@ -50,6 +50,7 @@ cron = "0.13.0"
chrono = "0.4.38"
sentry = { workspace = true }
zip = "0.6.2"
+tokio-stream = "0.1.17"
[features]
default = ["pipes", "security"]
diff --git a/screenpipe-core/src/devices.rs b/screenpipe-core/src/devices.rs
index ef1788fc7..f3fa2da39 100644
--- a/screenpipe-core/src/devices.rs
+++ b/screenpipe-core/src/devices.rs
@@ -1,7 +1,9 @@
-use std::fmt;
+use std::{collections::HashMap, fmt};
use anyhow::anyhow;
use serde::{Deserialize, Serialize};
+use tokio_stream::{wrappers::UnboundedReceiverStream, Stream};
+use tracing::debug;
#[derive(Clone, Debug)]
pub enum DeviceType {
@@ -9,6 +11,16 @@ pub enum DeviceType {
Vision(u32), // monitor_id
}
+impl DeviceType {
+ pub fn is_vision(&self) -> bool {
+ matches!(self, DeviceType::Vision(_))
+ }
+
+ pub fn is_audio(&self) -> bool {
+ matches!(self, DeviceType::Audio(_))
+ }
+}
+
impl fmt::Display for DeviceType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
@@ -17,6 +29,22 @@ impl fmt::Display for DeviceType {
}
}
}
+
+impl DeviceType {
+ pub fn from_str(s: &str) -> anyhow::Result<Self> {
+ // Check if it's a monitor ID (vision device)
+ if let Ok(monitor_id) = s.parse::<u32>() {
+ return Ok(DeviceType::Vision(monitor_id));
+ }
+
+ // Otherwise try to parse as audio device
+ match AudioDevice::from_name(s) {
+ Ok(audio_device) => Ok(DeviceType::Audio(audio_device)),
+ Err(e) => Err(anyhow!("Failed to parse device string '{}': {}", s, e)),
+ }
+ }
+}
+
#[derive(Clone, Debug)]
pub struct DeviceControl {
pub device: DeviceType,
@@ -92,3 +120,130 @@ impl fmt::Display for AudioDevice {
)
}
}
+
+pub struct DeviceManager {
+ sender: tokio::sync::broadcast::Sender<DeviceControl>,
+ #[allow(dead_code)]
+ _dummy: tokio::sync::broadcast::Receiver<DeviceControl>,
+ state_sender: tokio::sync::mpsc::UnboundedSender<DeviceStateRequest>,
+}
+
+impl Clone for DeviceManager {
+ fn clone(&self) -> Self {
+ DeviceManager {
+ sender: self.sender.clone(),
+ _dummy: self.sender.subscribe(),
+ state_sender: self.state_sender.clone(),
+ }
+ }
+}
+
+#[derive(Debug)]
+enum DeviceStateRequest {
+ Get {
+ respond_to: tokio::sync::oneshot::Sender<HashMap<String, DeviceControl>>,
+ },
+ Update(DeviceControl),
+ Watch {
+ respond_to: tokio::sync::mpsc::UnboundedSender<DeviceStateChange>,
+ },
+}
+
+#[derive(Debug, Clone)]
+pub struct DeviceStateChange {
+ pub device: String,
+ pub control: DeviceControl,
+}
+
+impl DeviceManager {
+ pub fn default() -> Self {
+ let (sender, dummy_receiver) = tokio::sync::broadcast::channel(32);
+ let (state_sender, state_receiver) = tokio::sync::mpsc::unbounded_channel();
+
+ tokio::spawn(async move {
+ Self::manage_state(state_receiver).await;
+ });
+
+ Self {
+ sender,
+ // this ensures that even if devices go to 0 it still stays open
+ _dummy: dummy_receiver,
+ state_sender,
+ }
+ }
+
+ async fn manage_state(mut receiver: tokio::sync::mpsc::UnboundedReceiver<DeviceStateRequest>) {
+ let mut devices = HashMap::new();
+ let mut watchers = Vec::new();
+
+ while let Some(req) = receiver.recv().await {
+ debug!("received device_state_request: {:?}", req);
+ match req {
+ DeviceStateRequest::Get { respond_to } => {
+ debug!("sending get request to {} devices", devices.len());
+ let _ = respond_to.send(devices.clone());
+ }
+ DeviceStateRequest::Update(control) => {
+ let device_id = control.device.to_string();
+ let changed = devices
+ .get(&device_id)
+ .map_or(true, |current| current.is_running != control.is_running);
+
+ if changed {
+ debug!(
+ "updating device '{}' with new control state: {:?}",
+ device_id, control
+ );
+ debug!("notifying watchers of the change: {:?}", watchers);
+ devices.insert(device_id.clone(), control.clone());
+
+ // Notify watchers of the change
+ watchers.retain(
+ |watcher: &tokio::sync::mpsc::UnboundedSender<DeviceStateChange>| {
+ watcher
+ .send(DeviceStateChange {
+ device: device_id.clone(),
+ control: control.clone(),
+ })
+ .is_ok()
+ },
+ );
+ }
+ }
+ DeviceStateRequest::Watch { respond_to } => {
+ debug!("adding a new watcher");
+ watchers.push(respond_to);
+ }
+ }
+ }
+ }
+
+ pub async fn get_active_devices(&self) -> HashMap<String, DeviceControl> {
+ let (tx, rx) = tokio::sync::oneshot::channel();
+ let _ = self
+ .state_sender
+ .send(DeviceStateRequest::Get { respond_to: tx });
+ rx.await
+ .unwrap_or_default()
+ .into_iter()
+ .filter(|(_, control)| control.is_running)
+ .collect()
+ }
+
+ pub async fn watch_devices(&self) -> impl Stream<Item = DeviceStateChange> {
+ let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
+ let _ = self
+ .state_sender
+ .send(DeviceStateRequest::Watch { respond_to: tx });
+ UnboundedReceiverStream::new(rx)
+ }
+
+ pub async fn update_device(&self, control: DeviceControl) -> anyhow::Result<()> {
+ // Update state and broadcast change
+ let _ = self
+ .state_sender
+ .send(DeviceStateRequest::Update(control.clone()));
+ self.sender.send(control)?;
+ Ok(())
+ }
+}
diff --git a/screenpipe-server/Cargo.toml b/screenpipe-server/Cargo.toml
index 08aa39114..d4f3b2f34 100644
--- a/screenpipe-server/Cargo.toml
+++ b/screenpipe-server/Cargo.toml
@@ -74,7 +74,7 @@ clap_complete = "4.2"
# Plugins
tower = { version = "0.5", features = ["util"] }
-futures = "0.3.17"
+futures = { version = "0.3.31", features = ["std"] }
# Directory management
dirs = "5.0"
diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rs
index 311c1c9de..9c3bd1581 100644
--- a/screenpipe-server/src/bin/screenpipe-server.rs
+++ b/screenpipe-server/src/bin/screenpipe-server.rs
@@ -3,18 +3,18 @@ use clap::Parser;
use colored::Colorize;
use dirs::home_dir;
use futures::pin_mut;
+use futures::StreamExt;
use port_check::is_local_ipv4_port_free;
use screenpipe_audio::vad_engine::VadSensitivity;
use screenpipe_audio::{
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_core::{find_ffmpeg_path, DeviceManager};
use screenpipe_server::VisionDeviceControlRequest;
use screenpipe_server::{
cli::{
@@ -48,16 +48,6 @@ use tracing_subscriber::prelude::__tracing_subscriber_SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
use tracing_subscriber::{fmt, EnvFilter};
-fn print_devices(devices: &[AudioDevice]) {
- println!("available audio devices:");
- for device in devices.iter() {
- println!(" {}", device);
- }
-
- #[cfg(target_os = "macos")]
- println!("on macos, it's not intuitive but output devices are your displays");
-}
-
const DISPLAY: &str = r"
_
__________________ ___ ____ ____ (_____ ___
@@ -464,23 +454,10 @@ async fn main() -> anyhow::Result<()> {
let all_audio_devices = list_audio_devices().await?;
let mut devices_status = HashMap::new();
- if cli.list_audio_devices {
- print_devices(&all_audio_devices);
- return Ok(());
- }
let all_monitors = list_monitors().await;
- if cli.list_monitors {
- println!("available monitors:");
- for monitor in all_monitors.iter() {
- println!(" {}. {:?}", monitor.id(), monitor);
- }
- return Ok(());
- }
let mut audio_devices = Vec::new();
- 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 device_manager = Arc::new(DeviceManager::default());
let mut realtime_audio_devices = Vec::new();
// Add all available audio devices to the controls
@@ -505,8 +482,6 @@ async fn main() -> anyhow::Result<()> {
};
devices_status.insert(input_device, device_control);
}
- // audio output only on macos <15.0 atm ?
- // see https://github.com/mediar-ai/screenpipe/pull/106
if let Ok(output_device) = default_output_device() {
audio_devices.push(Arc::new(output_device.clone()));
let device_control = DeviceControl {
@@ -533,12 +508,17 @@ async fn main() -> anyhow::Result<()> {
if audio_devices.is_empty() {
eprintln!("no audio devices available. audio recording will be disabled.");
} else {
- for device in &audio_devices {
+ for (index, device) in audio_devices.iter().enumerate() {
+ if cli.disable_audio {
+ break;
+ }
let device_clone = device.deref().clone();
let sender_clone = device_manager.clone();
- // send signal after everything started
+ // send signal after everything started, with staggered delays
tokio::spawn(async move {
- tokio::time::sleep(Duration::from_secs(15)).await;
+ // Base delay of 15s + 5s for each device index
+ let delay = Duration::from_secs(15) + Duration::from_secs(5 * index as u64);
+ tokio::time::sleep(delay).await;
info!(
"initializing audio device control for device: {}",
device_clone.name
@@ -561,8 +541,6 @@ async fn main() -> anyhow::Result<()> {
if let Ok(input_device) = default_input_device() {
realtime_audio_devices.push(Arc::new(input_device.clone()));
}
- // audio output only on macos <15.0 atm ?
- // see https://github.com/mediar-ai/screenpipe/pull/106
if let Ok(output_device) = default_output_device() {
realtime_audio_devices.push(Arc::new(output_device.clone()));
}
@@ -603,11 +581,16 @@ async fn main() -> anyhow::Result<()> {
// Initialize vision devices control based on user selected monitors
{
- for monitor_id in monitor_ids.clone() {
+ for (index, monitor_id) in monitor_ids.clone().into_iter().enumerate() {
+ if cli.disable_vision {
+ break;
+ }
let device_manager = device_manager.clone();
// Send signal after everything started
tokio::spawn(async move {
- tokio::time::sleep(Duration::from_secs(15)).await;
+ // Base delay of 15s + 5s for each monitor index
+ let delay = Duration::from_secs(15) + Duration::from_secs(5 * index as u64);
+ tokio::time::sleep(delay).await;
info!(
"initializing vision device control for monitor: {}",
monitor_id
@@ -659,6 +642,8 @@ 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 dm_clone = device_manager.clone();
+ let device_manager_clone = device_manager.clone();
let (whisper_sender, whisper_receiver) = if cli.disable_audio {
// Create a dummy channel if no audio devices are available, e.g. audio disabled
@@ -679,7 +664,7 @@ async fn main() -> anyhow::Result<()> {
&PathBuf::from(output_path_clone.as_ref()),
VadSensitivity::from(cli.vad_sensitivity.clone()),
languages.clone(),
- device_manager.devices.clone(),
+ device_manager.clone(),
)
.await?
};
@@ -736,7 +721,7 @@ async fn main() -> anyhow::Result<()> {
realtime_config,
&vision_handle,
&audio_handle,
- device_manager_receiver.clone(),
+ device_manager.clone(),
);
let result = tokio::select! {
@@ -781,7 +766,7 @@ async fn main() -> anyhow::Result<()> {
let server = Server::new(
db_server,
SocketAddr::from(([127, 0, 0, 1], cli.port)),
- device_manager.clone(),
+ dm_clone,
local_data_dir_clone_2,
pipe_manager.clone(),
cli.disable_vision,
@@ -792,19 +777,31 @@ async fn main() -> anyhow::Result<()> {
realtime_vision_sender_clone.clone(),
);
- let device_manager_clone = device_manager.clone();
tokio::spawn(async move {
- while let Ok(_) = device_manager_receiver_control_loop.changed().await {
- debug!("received device update");
- let control = device_manager_receiver_control_loop.borrow().clone();
- if let Err(e) =
- handle_device_update(&control.device, control.clone(), &device_manager_clone).await
+ // Watch for device changes using the new stream API
+ let mut device_changes = device_manager_clone.watch_devices().await;
+
+ while let Some(change) = device_changes.next().await {
+ // ignore if vision disabled and its a vision device
+ if cli.disable_vision && change.control.device.is_vision() {
+ continue;
+ }
+ if cli.disable_audio && change.control.device.is_audio() {
+ continue;
+ }
+ debug!("received device update: {:?}", change);
+ if let Err(e) = handle_device_update(
+ &change.control.device,
+ change.control.clone(),
+ &device_manager_clone,
+ )
+ .await
{
error!("Device update failed: {}", e);
continue;
}
}
- info!("audio device control task stopped");
+ info!("device control task stopped");
});
async fn handle_device_update(
@@ -819,32 +816,35 @@ async fn main() -> anyhow::Result<()> {
match list_audio_devices().await {
Ok(available_devices) => {
if !available_devices.contains(device) {
+ warn!("attempted to control non-existent device: {}", device.name);
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?;
-
+ // Update the device state using new DeviceManager API
+ devices_control.update_device(control).await?;
Ok(())
}
- Err(e) => Err(anyhow::anyhow!("failed to list audio devices: {}", e)),
+ Err(e) => {
+ warn!("failed to list audio devices: {}", 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) {
+ warn!("attempted to control non-existent device: {}", monitor_id);
return Err(anyhow::anyhow!(
"attempted to control non-existent device: {}",
monitor_id
));
}
- // Update the device state using DeviceManager
- devices_control.update_device(control.clone()).await?;
-
+ // Update the device state using new DeviceManager API
+ devices_control.update_device(control).await?;
Ok(())
}
}
diff --git a/screenpipe-server/src/core.rs b/screenpipe-server/src/core.rs
index 4612ce3c8..98767f837 100644
--- a/screenpipe-server/src/core.rs
+++ b/screenpipe-server/src/core.rs
@@ -2,8 +2,8 @@ use crate::cli::{CliVadEngine, CliVadSensitivity};
use crate::db_types::Speaker;
use crate::{DatabaseManager, VideoCapture};
use anyhow::Result;
-use dashmap::DashMap;
use futures::future::join_all;
+use futures::StreamExt;
use log::{debug, error, info, warn};
use screenpipe_audio::realtime::RealtimeTranscriptionEvent;
use screenpipe_audio::{
@@ -11,7 +11,7 @@ use screenpipe_audio::{
};
use screenpipe_audio::{start_realtime_recording, AudioStream};
use screenpipe_core::pii_removal::remove_pii;
-use screenpipe_core::{AudioDevice, DeviceControl, DeviceType, Language};
+use screenpipe_core::{AudioDevice, DeviceManager, DeviceType, Language};
use screenpipe_vision::core::{RealtimeVisionEvent, WindowOcr};
use screenpipe_vision::OcrEngine;
use std::collections::HashMap;
@@ -21,54 +21,6 @@ use std::time::Duration;
use tokio::runtime::Handle;
use tokio::task::JoinHandle;
-#[derive(Clone)]
-pub struct DeviceManager {
- sender: tokio::sync::watch::Sender<DeviceControl>,
- pub devices: DashMap<String, DeviceControl>,
-}
-
-impl DeviceManager {
- pub fn default() -> Self {
- let (sender, _) = tokio::sync::watch::channel(DeviceControl::default());
- Self {
- sender,
- devices: DashMap::new(),
- }
- }
- 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>,
@@ -131,7 +83,7 @@ pub async fn start_continuous_recording(
realtime: RealtimeConfig,
vision_handle: &Handle,
audio_handle: &Handle,
- device_control_receiver: tokio::sync::watch::Receiver<DeviceControl>,
+ device_manager: Arc<DeviceManager>,
) -> Result<()> {
let recording_config = recording;
@@ -139,13 +91,13 @@ pub async fn start_continuous_recording(
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 device_manager_vision = device_manager.clone();
+ let device_manager_audio = device_manager.clone();
let video_task = if !vision.disabled {
vision_handle.spawn(async move {
record_vision(
- device_control_receiver_vision,
+ device_manager_vision,
ocr_engine_clone,
db_clone,
output_path_clone,
@@ -174,7 +126,7 @@ pub async fn start_continuous_recording(
let audio_task = if !audio.disabled {
audio_handle.spawn(async move {
record_audio(
- device_control_receiver_audio,
+ device_manager_audio,
db_manager_audio,
recording_config.audio_chunk_duration,
whisper_sender_clone,
@@ -214,7 +166,7 @@ pub async fn start_continuous_recording(
}
async fn record_vision(
- device_receiver: tokio::sync::watch::Receiver<DeviceControl>,
+ device_manager: Arc<DeviceManager>,
ocr_engine: Arc<OcrEngine>,
db: Arc<DatabaseManager>,
output_path: Arc<String>,
@@ -228,70 +180,86 @@ async fn record_vision(
use_pii_removal: bool,
) -> Result<()> {
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;
- }
+ let mut device_states = device_manager.watch_devices().await;
- if handles.contains_key(&monitor_id) {
- continue;
- }
+ loop {
+ tokio::select! {
+ Some(state_change) = device_states.next() => {
+ match DeviceType::from_str(&state_change.device) {
+ Ok(DeviceType::Vision(monitor_id)) => {
+ debug!("record_vision: vision state change: {:?}", state_change);
+ if !state_change.control.is_running {
+ if let Some(handle) = handles.remove(&monitor_id) {
+ let _ = handle.await;
+ info!("stopped thread for monitor {}", monitor_id);
+ }
+ continue;
+ }
+
+
+ if handles.contains_key(&monitor_id) {
+ continue;
+ }
+
+ info!("starting vision capture thread for monitor: {}", monitor_id);
- 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
- );
+ 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 device_manager_vision_clone = device_manager.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_manager_vision_clone, config).await {
+ error!(
+ "Error in video recording thread for monitor {}: {}",
+ monitor_id, e
+ );
+ }
+ });
+
+ handles.insert(monitor_id, handle);
}
- });
+ _ => continue, // Ignore non-vision devices
+ }
+ }
+ _ = tokio::time::sleep(Duration::from_millis(100)) => {
- handles.insert(monitor_id, handle);
}
- DeviceType::Audio(_) => continue, // Ignore audio devices
}
+
+ handles.retain(|monitor_id, handle| {
+ if handle.is_finished() {
+ info!("handle for monitor {} has finished", monitor_id);
+ false
+ } else {
+ true
+ }
+ });
}
- Ok(())
}
async fn record_video(
- mut device_receiver: tokio::sync::watch::Receiver<DeviceControl>,
+ device_manager: Arc<DeviceManager>,
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_{}", config.monitor_id));
@@ -328,14 +296,22 @@ async fn record_video(
config.capture_unfocused_windows,
);
+ let mut device_states = device_manager.watch_devices().await;
+
loop {
tokio::select! {
- Ok(_) = device_receiver.changed() => {
- debug!("device_receiver changed in record_video");
- let control = device_receiver.borrow().clone();
- if !control.is_running {
- let _ = video_capture.shutdown().await;
- return Ok(());
+ Some(state_change) = device_states.next() => {
+ match DeviceType::from_str(&state_change.device) {
+ Ok(DeviceType::Vision(monitor_id)) if monitor_id == config.monitor_id => {
+ debug!("record_video: vision state change: {:?}", state_change);
+ if !state_change.control.is_running {
+ info!("vision thread for monitor {} received stop signal", monitor_id);
+ let _ = video_capture.shutdown().await;
+ info!("vision thread for monitor {} shutdown complete", monitor_id);
+ return Ok(());
+ }
+ }
+ _ => continue, // Ignore other devices or monitors
}
}
_ = tokio::time::sleep(Duration::from_secs_f64(1.0 / config.fps)) => {
@@ -399,7 +375,7 @@ async fn record_video(
}
async fn record_audio(
- device_receiver: tokio::sync::watch::Receiver<DeviceControl>,
+ device_manager: Arc<DeviceManager>,
db: Arc<DatabaseManager>,
chunk_duration: Duration,
whisper_sender: crossbeam::channel::Sender<AudioInput>,
@@ -412,19 +388,19 @@ async fn record_audio(
deepgram_api_key: Option<String>,
) -> Result<()> {
let mut handles: HashMap<String, JoinHandle<()>> = HashMap::new();
+ let mut device_states = device_manager.watch_devices().await;
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 {
tokio::select! {
- Ok(_) = device_receiver_clone.changed() => {
- let control = device_receiver_clone.borrow().clone();
- match control.device {
- DeviceType::Audio(audio_device) => {
+ Some(state_change) = device_states.next() => {
+ match DeviceType::from_str(&state_change.device) {
+ Ok(DeviceType::Audio(audio_device)) => {
let device_id = audio_device.to_string();
- if !control.is_running {
+ if !state_change.control.is_running {
if let Some(handle) = handles.remove(&device_id) {
handle.abort();
info!("stopped thread for device {}", &audio_device);
@@ -436,6 +412,8 @@ async fn record_audio(
continue;
}
+ info!("starting audio capture thread for device: {}", &audio_device);
+
let whisper_sender_clone = whisper_sender.clone();
let audio_device = Arc::new(audio_device);
@@ -445,40 +423,41 @@ async fn record_audio(
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 = device_manager.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(control.is_running));
+ let audio_device_clone = Arc::clone(&audio_device);
+ let deepgram_api_key = deepgram_api_key_clone.clone();
+ let is_running = Arc::new(AtomicBool::new(state_change.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();
+ let device_id = audio_device_clone.to_string();
- // if device control change to false, set is_running to false
+ // Monitor device state changes
+ let mut device_states = device_receiver_monitor.watch_devices().await;
tokio::spawn(async move {
- loop {
- if !device_receiver_monitor.borrow().is_running {
- is_running_clone.clone().store(false, Ordering::Relaxed);
+ while let Some(state_change) = device_states.next().await {
+ if state_change.device == device_id && !state_change.control.is_running {
+ is_running_clone.store(false, Ordering::Relaxed);
break;
- } // 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 is_running_loop = Arc::clone(&is_running);
let audio_stream = match AudioStream::from_device(
audio_device_clone.clone(),
- Arc::clone(&is_running_loop), // Clone from original Arc
+ Arc::clone(&is_running_loop),
)
.await
{
@@ -545,12 +524,11 @@ async fn record_audio(
join_all(recording_handles).await;
}
-
});
handles.insert(device_id, handle);
}
- DeviceType::Vision(_) => continue, // Ignore vision devices
+ _ => continue,
}
}
_ = tokio::time::sleep(Duration::from_millis(100)) => {
diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rs
index 57721b9af..72a88115e 100644
--- a/screenpipe-server/src/server.rs
+++ b/screenpipe-server/src/server.rs
@@ -10,10 +10,9 @@ use futures::{
Stream,
};
use image::ImageFormat::{self};
-use screenpipe_core::{AudioDevice, AudioDeviceType, DeviceControl};
+use screenpipe_core::{AudioDevice, AudioDeviceType, DeviceControl, DeviceManager};
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},
@@ -830,7 +829,6 @@ async fn get_pipe_info_handler(
}
async fn list_pipes_handler(State(state): State<Arc<AppState>>) -> JsonResponse<Value> {
- debug!("Listing pipes");
let pipes = state.pipe_manager.list_pipes().await;
JsonResponse(json!({
"data": pipes,
diff --git a/screenpipe-server/src/video.rs b/screenpipe-server/src/video.rs
index 6249b3244..d4640c1cd 100644
--- a/screenpipe-server/src/video.rs
+++ b/screenpipe-server/src/video.rs
@@ -67,6 +67,7 @@ impl VideoCapture {
let shutdown_rx_queue = shutdown_rx.clone();
let shutdown_rx_video = shutdown_rx.clone();
+ let result_sender_inner = result_sender.clone();
let capture_handle = tokio::spawn(async move {
let mut rx = shutdown_rx_capture;
loop {
@@ -74,7 +75,7 @@ impl VideoCapture {
info!("shutting down video capture thread");
break;
}
- let result_sender = result_sender.clone();
+ let result_sender = result_sender_inner.clone();
let window_filters_clone = Arc::clone(&window_filters_clone);
tokio::select! {
@@ -88,7 +89,6 @@ impl VideoCapture {
capture_unfocused_windows,
rx.clone(),
) => {
- // If continuous_capture returns, we can continue the loop
debug!("continuous capture completed, restarting");
}
_ = rx.changed() => {
@@ -99,6 +99,8 @@ impl VideoCapture {
}
}
}
+ debug!("exiting capture handle loop, dropping sender");
+ drop(result_sender_inner);
});
handles.push(capture_handle);
@@ -190,7 +192,7 @@ pub async fn start_ffmpeg_process(output_file: &str, fps: f64) -> Result<Child,
"-f",
"image2pipe",
"-vcodec",
- "png",
+ "mjpeg",
"-r",
&fps_str,
"-i",
@@ -306,6 +308,7 @@ async fn save_frames_as_video_with_shutdown(
&mut frame_count,
frames_per_video,
fps,
+ &shutdown_rx,
)
.await;
@@ -371,19 +374,23 @@ async fn process_frames(
frame_count: &mut usize,
frames_per_video: usize,
fps: f64,
+ shutdown_rx: &watch::Receiver<bool>,
) {
let write_timeout = Duration::from_secs_f64(1.0 / fps);
while *frame_count < frames_per_video {
+ if *shutdown_rx.borrow() {
+ info!("process_frames: shutdown signal received, breaking out");
+ break;
+ }
if let Some(frame) = frame_queue.pop() {
let buffer = encode_frame(&frame);
if let Some(stdin) = current_stdin.as_mut() {
if let Err(e) = write_frame_with_retry(stdin, &buffer).await {
- error!("Failed to write frame to ffmpeg after max retries: {}", e);
+ error!("failed to write frame to ffmpeg after max retries: {}", e);
break;
}
*frame_count += 1;
- debug!("Wrote frame {} to FFmpeg", frame_count);
-
+ debug!("wrote frame {} to ffmpeg", frame_count);
flush_ffmpeg_input(stdin, *frame_count, fps).await;
}
} else {
diff --git a/screenpipe-server/src/video_utils.rs b/screenpipe-server/src/video_utils.rs
index fddeb0ab8..39c666537 100644
--- a/screenpipe-server/src/video_utils.rs
+++ b/screenpipe-server/src/video_utils.rs
@@ -57,7 +57,7 @@ pub async fn extract_frame(file_path: &str, offset_index: i64) -> Result<String>
"-f",
"image2pipe",
"-vcodec",
- "png",
+ "mjpeg",
"-",
])
.stdout(std::process::Stdio::piped())
diff --git a/screenpipe-server/tests/endpoint_test.rs b/screenpipe-server/tests/endpoint_test.rs
index 0aa271b49..603d57f8c 100644
--- a/screenpipe-server/tests/endpoint_test.rs
+++ b/screenpipe-server/tests/endpoint_test.rs
@@ -8,7 +8,7 @@ mod tests {
use chrono::{Duration, Utc};
use screenpipe_core::AudioDevice;
use screenpipe_core::AudioDeviceType;
- use screenpipe_server::core::DeviceManager;
+ use screenpipe_core::DeviceManager;
use screenpipe_server::db_types::ContentType;
use screenpipe_server::db_types::SearchResult;
use screenpipe_server::video_cache::FrameCache;
diff --git a/screenpipe-server/tests/tags_test.rs b/screenpipe-server/tests/tags_test.rs
index c0db387d5..a9315366d 100644
--- a/screenpipe-server/tests/tags_test.rs
+++ b/screenpipe-server/tests/tags_test.rs
@@ -4,7 +4,7 @@ use axum::{
Router,
};
use chrono::Utc;
-use screenpipe_core::{AudioDevice, AudioDeviceType};
+use screenpipe_core::{AudioDevice, AudioDeviceType, DeviceManager};
use screenpipe_vision::OcrEngine;
use serde_json::json;
use std::path::PathBuf;
@@ -12,8 +12,8 @@ use std::sync::Arc;
use tower::ServiceExt;
use screenpipe_server::{
- core::DeviceManager, create_router, video_cache::FrameCache, AppState, ContentItem,
- DatabaseManager, PaginatedResponse, PipeManager,
+ create_router, video_cache::FrameCache, AppState, ContentItem, DatabaseManager,
+ PaginatedResponse, PipeManager,
};
// Add this function to initialize the logger
diff --git a/screenpipe-vision/src/core.rs b/screenpipe-vision/src/core.rs
index 7b7817655..c7ea80ad4 100644
--- a/screenpipe-vision/src/core.rs
+++ b/screenpipe-vision/src/core.rs
@@ -21,6 +21,7 @@ use serde::Deserializer;
use serde::Serialize;
use serde::Serializer;
use serde_json;
+use tracing::warn;
use std::sync::Arc;
use std::{
collections::HashMap,
@@ -239,6 +240,10 @@ pub async fn continuous_capture(
previous_image = Some(image);
if let Some(max_avg_frame) = max_average.take() {
+ if max_avg_frame.result_tx.clone().is_closed() {
+ warn!("result_tx is closed, skipping OCR task");
+ return;
+ }
let ocr_task_data = OcrTaskData {
image: max_avg_frame.image,
window_images: max_avg_frame.window_images,