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
feat: stop listening to audio device on disconnection
Louis Beaumont1f3f19a5b513
diff --git a/screenpipe-audio/src/core.rs b/screenpipe-audio/src/core.rsindex d223c8285..e583c5c37 100644--- a/screenpipe-audio/src/core.rs+++ b/screenpipe-audio/src/core.rs@@ -1,7 +1,7 @@use anyhow::{anyhow, Result};use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};+use cpal::StreamError;use crossbeam::channel::{Receiver, Sender};-use crossbeam::epoch::Atomic;use log::{debug, error, info, warn};use serde::Serialize;use std::fmt;@@ -134,6 +134,7 @@ pub fn record_and_transcribe(crossbeam::channel::unbounded();let is_running_clone = Arc::clone(&is_running);let is_running_clone_2 = Arc::clone(&is_running);+ let is_running_clone_3 = Arc::clone(&is_running);let output_path_clone = output_path.clone();let output_path_clone_2 = output_path.clone();@@ -193,7 +194,13 @@ pub fn record_and_transcribe(}});- let err_fn = |err| error!("An error occurred on the audio stream: {}", err);+ let err_fn = move |err: StreamError| {+ error!("An error occurred on the audio stream: {}", err);+ if err.to_string().contains("device is no longer valid") {+ warn!("Audio device disconnected. Stopping recording.");+ is_running_clone_3.store(false, Ordering::Relaxed);+ }+ };let stream = match config.sample_format() {cpal::SampleFormat::F32 => cpal_audio_device.build_input_stream(diff --git a/screenpipe-audio/tests/core_tests.rs b/screenpipe-audio/tests/core_tests.rsindex 34536738a..eed25c611 100644--- a/screenpipe-audio/tests/core_tests.rs+++ b/screenpipe-audio/tests/core_tests.rs@@ -1,13 +1,10 @@#[cfg(test)]mod tests {use chrono::Utc;- use cpal::traits::StreamTrait;use crossbeam::channel;use log::{debug, LevelFilter};- use screenpipe_audio::record_and_transcribe;- use screenpipe_audio::{- default_output_device, list_audio_devices, parse_device_spec, stt, WhisperModel,- };+ use screenpipe_audio::{default_output_device, list_audio_devices, stt, WhisperModel};+ use screenpipe_audio::{parse_audio_device, record_and_transcribe};use std::path::PathBuf;use std::process::Command;use std::str::FromStr;@@ -37,8 +34,8 @@ mod tests {}#[test]- fn test_parse_device_spec() {- let spec = parse_device_spec("Test Device (input)").unwrap();+ fn test_parse_audio_device() {+ let spec = parse_audio_device("Test Device (input)").unwrap();assert_eq!(spec.to_string(), "Test Device (input)");}diff --git a/screenpipe-server/src/core.rs b/screenpipe-server/src/core.rsindex 47032fc67..81dba70b2 100644--- a/screenpipe-server/src/core.rs+++ b/screenpipe-server/src/core.rs@@ -127,8 +127,6 @@ async fn record_video(Ok(())}-use crossbeam::channel::TryRecvError;-async fn record_audio(db: Arc<DatabaseManager>,output_path: Arc<String>,@@ -139,143 +137,125 @@ async fn record_audio() -> Result<()> {let mut handles: HashMap<String, JoinHandle<()>> = HashMap::new();- loop {- match audio_devices_control_receiver.try_recv() {- Ok((audio_device, device_control)) => {- info!("Received audio device: {}", &audio_device);- let device_id = audio_device.to_string();+ while let Ok((audio_device, device_control)) = audio_devices_control_receiver.recv() {+ info!("Received audio device: {}", &audio_device);+ let device_id = audio_device.to_string();- let db_clone = Arc::clone(&db);- let output_path_clone = Arc::clone(&output_path);- let whisper_sender_clone = whisper_sender.clone();- let whisper_receiver_clone = whisper_receiver.clone();+ let db_clone = Arc::clone(&db);+ let output_path_clone = Arc::clone(&output_path);+ let whisper_sender_clone = whisper_sender.clone();+ let whisper_receiver_clone = whisper_receiver.clone();- if !device_control.is_running {- info!("Device control signaled stop for device {}", &audio_device);- if let Some(handle) = handles.remove(&device_id) {- handle.await.unwrap();- info!("Stopped thread for device {}", &audio_device);- }- continue;- }+ if !device_control.is_running {+ info!("Device control signaled stop for device {}", &audio_device);+ if let Some(handle) = handles.remove(&device_id) {+ handle.await.unwrap();+ info!("Stopped thread for device {}", &audio_device);+ }+ continue;+ }- let audio_device = Arc::new(audio_device);- let device_control = Arc::new(device_control);- let handle = tokio::spawn(async move {- let audio_device_clone = Arc::clone(&audio_device);- let device_control_clone = Arc::clone(&device_control);- info!(- "Starting audio capture thread for device: {}",- &audio_device- );+ let audio_device = Arc::new(audio_device);+ let device_control = Arc::new(device_control);+ let handle = tokio::spawn(async move {+ let audio_device_clone = Arc::clone(&audio_device);+ let device_control_clone = Arc::clone(&device_control);+ info!(+ "Starting audio capture thread for device: {}",+ &audio_device+ );++ let mut iteration = 0;+ loop {+ iteration += 1;+ info!(+ "Starting iteration {} for device {}",+ iteration, audio_device_clone+ );- let mut iteration = 0;- loop {- iteration += 1;+ // TODO: tokio this is bad to mix tokio/os thread+ let recording_thread = thread::spawn({+ let output_path_clone = Arc::clone(&output_path_clone);+ let whisper_sender = whisper_sender_clone.clone();+ let audio_device_clone = audio_device_clone.clone();+ let device_control_clone = device_control_clone.clone();+ move || {+ let new_file_name = Utc::now().format("%Y-%m-%d_%H-%M-%S").to_string();+ let file_path = format!(+ "{}/{}_{}.mp3",+ output_path_clone, audio_device_clone, new_file_name+ );+ info!(+ "Starting record_and_transcribe for device {} (iteration {})",+ audio_device_clone, iteration+ );+ let result = record_and_transcribe(+ &audio_device_clone,+ chunk_duration,+ file_path.into(),+ whisper_sender,+ Arc::new(AtomicBool::new(device_control_clone.is_running)),+ );info!(- "Starting iteration {} for device {}",- iteration, audio_device_clone+ "Finished record_and_transcribe for device {} (iteration {})",+ audio_device_clone, iteration);+ result+ }+ });- // TODO: tokio this is bad to mix tokio/os thread- let recording_thread = thread::spawn({- let output_path_clone = Arc::clone(&output_path_clone);- let whisper_sender = whisper_sender_clone.clone();- let audio_device_clone = audio_device_clone.clone();- let device_control_clone = device_control_clone.clone();- move || {- let new_file_name =- Utc::now().format("%Y-%m-%d_%H-%M-%S").to_string();- let file_path = format!(- "{}/{}_{}.mp3",- output_path_clone, audio_device_clone, new_file_name- );- info!(- "Starting record_and_transcribe for device {} (iteration {})",- audio_device_clone, iteration- );- let result = record_and_transcribe(- &audio_device_clone,- chunk_duration,- file_path.into(),- whisper_sender,- Arc::new(AtomicBool::new(device_control_clone.is_running)),- );- info!(- "Finished record_and_transcribe for device {} (iteration {})",- audio_device_clone, iteration- );- result- }- });+ // Handle the recording thread result+ match recording_thread.join() {+ Ok(Ok(file_path)) => {+ info!(+ "Recording complete for device {} (iteration {}): {:?}",+ audio_device, iteration, file_path+ );+ let whisper_receiver = whisper_receiver_clone.clone();- // Handle the recording thread result- match recording_thread.join() {- Ok(Ok(file_path)) => {+ // Process the recorded chunk+ match whisper_receiver.recv() {+ Ok(transcription) => {info!(- "Recording complete for device {} (iteration {}): {:?}",- audio_device, iteration, file_path+ "Received transcription for device {} (iteration {})",+ audio_device, iteration);- let whisper_receiver = whisper_receiver_clone.clone();-- // Process the recorded chunk- match whisper_receiver.recv() {- Ok(transcription) => {- info!(- "Received transcription for device {} (iteration {})",- audio_device, iteration- );- process_audio_result(&db_clone, transcription).await;- }- Err(e) => error!(- "Failed to receive transcription for device {} (iteration {}): {}",- audio_device, iteration, e- ),- }+ process_audio_result(&db_clone, transcription).await;}- Ok(Err(e)) => error!(- "Error in record_and_transcribe for device {} (iteration {}): {}",- audio_device, iteration, e- ),Err(e) => error!(- "Thread panicked for device {} (iteration {}): {:?}",+ "Failed to receive transcription for device {} (iteration {}): {}",audio_device, iteration, e),}-- info!(- "Finished iteration {} for device {}",- iteration, &audio_device+ }+ Ok(Err(e)) => {+ error!(+ "Error in record_and_transcribe for device {} (iteration {}): {}, stopping thread",+ audio_device, iteration, e);+ break; // Stop the loop on first error}- });+ Err(e) => {+ error!(+ "Thread panicked for device {} (iteration {}): {:?}, stopping thread",+ audio_device, iteration, e+ );+ break; // Stop the loop on first error+ }+ }- handles.insert(device_id, handle);- }- Err(TryRecvError::Empty) => {- // No new messages, continue with other tasks- }- Err(TryRecvError::Disconnected) => {- // Channel is closed, exit the loop- break;+ info!(+ "Finished iteration {} for device {}",+ iteration, &audio_device+ );}- }- // Process existing audio devices- handles.retain(|device_id, handle| {- if handle.is_finished() {- info!("Audio capture thread for device {} has finished", device_id);- false // Remove this handle from the map- } else {- true // Keep this handle in the map- }+ info!("Exiting audio capture thread for device: {}", &audio_device);});- // Short sleep to prevent busy-waiting- tokio::time::sleep(Duration::from_millis(100)).await;+ handles.insert(device_id, handle);}- // Wait for all remaining handles to completefor (device_id, handle) in handles {if let Err(e) = handle.await {error!(@@ -287,7 +267,6 @@ async fn record_audio(Ok(())}-async fn process_audio_result(db: &DatabaseManager, result: TranscriptionResult) {info!("Inserting audio chunk: {:?}", result.transcription);if result.error.is_some() || result.transcription.is_none() {diff --git a/screenpipe-server/src/lib.rs b/screenpipe-server/src/lib.rsindex 925f4dc8c..4225c8df2 100644--- a/screenpipe-server/src/lib.rs+++ b/screenpipe-server/src/lib.rs@@ -8,4 +8,4 @@ pub use core::{start_continuous_recording, RecorderControl};pub use db::{ContentType, DatabaseManager, SearchResult};pub use resource_monitor::ResourceMonitor;pub use server::Server;-pub use video::{extract_frames_from_video, VideoCapture};+pub use video::VideoCapture;diff --git a/screenpipe-server/src/video.rs b/screenpipe-server/src/video.rsindex 8bfca26e8..ca14ded04 100644--- a/screenpipe-server/src/video.rs+++ b/screenpipe-server/src/video.rs@@ -1,13 +1,8 @@use chrono::Utc;-use ffmpeg_next as ffmpeg;-use ffmpeg_next::sys::AVSEEK_FLAG_FRAME;-use ffmpeg_next::{format, format::Pixel, media, software::scaling, util::frame::video::Video};use image::ImageFormat::{self};-use image::{DynamicImage, ImageBuffer, Rgb};use log::{debug, error, info, warn};use screenpipe_vision::{continuous_capture, CaptureResult, ControlMessage};-use std::collections::{BTreeSet, VecDeque};-use std::io::Write;+use std::collections::VecDeque;use std::path::PathBuf;use std::process::Stdio;use tokio::io::AsyncWriteExt;@@ -18,108 +13,11 @@ use std::sync::Arc;use tokio::sync::mpsc::{channel, Receiver, Sender};use tokio::sync::Mutex;+use std::env;use std::time::Duration;-use std::{env, thread};-use threadpool::ThreadPool;-const MAX_THREADS: usize = 8; // Adjust based on your needsconst MAX_FPS: f64 = 30.0; // Adjust based on your needs-pub fn extract_frames_from_video(- video_path: &str,- frame_numbers: &[i64],-) -> Result<Vec<DynamicImage>, ffmpeg::Error> {- ffmpeg::init()?;-- let mut images = Vec::new();- let mut ictx = format::input(&video_path)?;- let input_stream = ictx- .streams()- .best(media::Type::Video)- .ok_or(ffmpeg::Error::StreamNotFound)?;- let video_stream_index = input_stream.index();-- let context_decoder =- ffmpeg::codec::context::Context::from_parameters(input_stream.parameters())?;- let mut decoder = context_decoder.decoder().video()?;-- let mut scaler = scaling::Context::get(- decoder.format(),- decoder.width(),- decoder.height(),- Pixel::RGB24,- decoder.width(),- decoder.height(),- scaling::Flags::BILINEAR,- // scaling::Flags::LANCZOS,- )?;-- let mut sorted_frame_numbers: BTreeSet<_> = frame_numbers.iter().copied().collect();- let mut frame_index = 0i64;-- let now = std::time::Instant::now();- println!("Starting at {}ms", now.elapsed().as_millis());-- 'frames: while let Some(&target_frame_number) = sorted_frame_numbers.iter().next() {- // Seek to the nearest keyframe- seek_to_frame(&mut ictx, target_frame_number)?;-- while frame_index <= target_frame_number {- for (stream, packet) in ictx.packets() {- if stream.index() == video_stream_index {- decoder.send_packet(&packet)?;- let mut decoded = Video::empty();- while decoder.receive_frame(&mut decoded).is_ok() {- if frame_index == target_frame_number {- let mut rgb_frame = Video::empty();- scaler.run(&decoded, &mut rgb_frame)?;- let frame_data = rgb_frame.data(0);- let img = ImageBuffer::<Rgb<u8>, Vec<u8>>::from_raw(- decoder.width() as u32,- decoder.height() as u32,- frame_data.to_vec(),- )- .ok_or(ffmpeg::Error::InvalidData)?;- images.push(DynamicImage::ImageRgb8(img));- sorted_frame_numbers.remove(&target_frame_number);- if sorted_frame_numbers.is_empty() {- break 'frames;- }- }- frame_index += 1;- }- }- }- }- }-- println!("Done in {}ms", now.elapsed().as_millis());-- Ok(images)-}--fn seek_to_frame(- ictx: &mut format::context::Input,- frame_number: i64,-) -> Result<(), ffmpeg::Error> {- unsafe {- let ret = ffmpeg::sys::avformat_seek_file(- ictx.as_mut_ptr(),- -1, // Stream index -1 for default stream time base- i64::MIN, // Minimum timestamp- frame_number, // Target frame number as timestamp- i64::MAX, // Maximum timestamp- AVSEEK_FLAG_FRAME, // Seeking by frame number- );-- if ret < 0 {- Err(ffmpeg::Error::from(ret))- } else {- Ok(())- }- }-}-pub struct VideoCapture {control_tx: Sender<ControlMessage>,frame_queue: Arc<Mutex<VecDeque<CaptureResult>>>,@@ -159,8 +57,14 @@ impl VideoCapture {let _queue_thread = tokio::spawn(async move {while *capture_thread_is_running.lock().await {if let Some(result) = result_receiver.recv().await {- debug!("Received result from capture thread: frame_number: {:?}", result.frame_number);- debug!("Received result from capture thread: timestamp: {:?}", result.timestamp);+ debug!(+ "Received result from capture thread: frame_number: {:?}",+ result.frame_number+ );+ debug!(+ "Received result from capture thread: timestamp: {:?}",+ result.timestamp+ );// debug!("Received result from capture thread: text: {:?}", result.text);capture_frame_queue.lock().await.push_back(result);}