YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
fix audio device
Louis Beaumont7affe52e8332
diff --git a/screenpipe-audio/src/core.rs b/screenpipe-audio/src/core.rsindex e3cd160ff..d223c8285 100644--- a/screenpipe-audio/src/core.rs+++ b/screenpipe-audio/src/core.rs@@ -1,18 +1,19 @@use anyhow::{anyhow, Result};use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};use crossbeam::channel::{Receiver, Sender};+use crossbeam::epoch::Atomic;use log::{debug, error, info, warn};use serde::Serialize;use std::fmt;use std::path::PathBuf;use std::sync::atomic::{AtomicBool, Ordering};use std::sync::Arc;+use std::thread;use std::time::Duration;-use tokio::io::AsyncWriteExt;use crate::AudioInput;-use std::process::Stdio;-use tokio::process::Command;+use std::io::Write;+use std::process::{Command, Stdio};#[derive(Clone)]pub struct DeviceControl {@@ -112,7 +113,7 @@ fn get_device_and_config(Ok((audio_device, config))}-pub async fn record_and_transcribe(+pub fn record_and_transcribe(audio_device: &AudioDevice,duration: Duration,output_path: PathBuf,@@ -139,7 +140,7 @@ pub async fn record_and_transcribe(let start_time = std::time::Instant::now();// Spawn FFmpeg process in a separate thread- let ffmpeg_handle = tokio::spawn(async move {+ let ffmpeg_handle = thread::spawn(move || {let mut ffmpeg = Command::new("ffmpeg").args(&["-f",@@ -170,7 +171,7 @@ pub async fn record_and_transcribe(while is_running_clone.load(Ordering::Relaxed) {if let Ok(data) = audio_receiver.recv_timeout(Duration::from_millis(100)) {- if let Err(e) = stdin.write_all(&data).await {+ if let Err(e) = stdin.write_all(&data) {error!("Failed to write audio data to FFmpeg: {}", e);break;}@@ -179,14 +180,14 @@ pub async fn record_and_transcribe(break;}// sleep for 100ms- tokio::time::sleep(Duration::from_millis(100)).await;+ thread::sleep(Duration::from_millis(100));}// Close stdin to signal EOF to FFmpegdrop(stdin);// Wait for FFmpeg to finish- match ffmpeg.wait().await {+ match ffmpeg.wait() {Ok(status) => debug!("FFmpeg process exited with status: {}", status),Err(e) => error!("Failed to wait for FFmpeg process: {}", e),}@@ -218,7 +219,7 @@ pub async fn record_and_transcribe(if start_time.elapsed() >= duration {break;}- tokio::time::sleep(Duration::from_millis(100)).await;+ thread::sleep(Duration::from_millis(100));}info!(@@ -229,8 +230,14 @@ pub async fn record_and_transcribe(// Stop the stream and signal the recording to stopstream.pause()?;+ // Wait for a short time to ensure all data is processed+ // thread::sleep(Duration::from_millis(100));++ // Close the sender to signal the FFmpeg thread to finish+ // drop(audio_sender_clone);+// Wait for the FFmpeg thread to finish- ffmpeg_handle.await.expect("Failed to join FFmpeg thread");+ ffmpeg_handle.join().expect("Failed to join FFmpeg thread");debug!("FFmpeg thread finished");if let Err(e) = whisper_sender.send(AudioInput {diff --git a/screenpipe-audio/src/stt.rs b/screenpipe-audio/src/stt.rsindex 6a44c5363..2e9564e72 100644--- a/screenpipe-audio/src/stt.rs+++ b/screenpipe-audio/src/stt.rs@@ -1,8 +1,12 @@-use std::time::{SystemTime, UNIX_EPOCH};+use std::{+ thread,+ time::{SystemTime, UNIX_EPOCH},+};use anyhow::{Error as E, Result};use candle::{Device, IndexOp, Tensor};use candle_nn::{ops::softmax, VarBuilder};+use crossbeam::channel::{self, Receiver, Sender};use hf_hub::{api::sync::Api, Repo, RepoType};use log::{error, info};use rand::{distributions::Distribution, SeedableRng};@@ -12,7 +16,6 @@ use candle_transformers::models::whisper::{self as m, audio, Config};use rubato::{Resampler, SincFixedIn, SincInterpolationParameters, SincInterpolationType, WindowFunction,};-use tokio::sync::mpsc::{Receiver, Sender};use crate::{multilingual, pcm_decode::pcm_decode};@@ -489,8 +492,7 @@ pub struct TranscriptionResult {pub timestamp: u64,pub error: Option<String>,}-pub async fn create_whisper_channel() -> Result<(Sender<AudioInput>, Receiver<TranscriptionResult>)>-{+pub fn create_whisper_channel() -> Result<(Sender<AudioInput>, Receiver<TranscriptionResult>)> {let whisper_model = WhisperModel::new()?;let (input_sender, input_receiver): (Sender<AudioInput>, Receiver<AudioInput>) =channel::unbounded();@@ -499,8 +501,8 @@ pub async fn create_whisper_channel() -> Result<(Sender<AudioInput>, Receiver<TrReceiver<TranscriptionResult>,) = channel::unbounded();- tokio::spawn(async move {- while let Ok(input) = input_receiver.recv().await {+ thread::spawn(move || {+ while let Ok(input) = input_receiver.recv() {let timestamp = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time went backwards")@@ -531,3 +533,5 @@ pub async fn create_whisper_channel() -> Result<(Sender<AudioInput>, Receiver<TrOk((input_sender, output_receiver))}++diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rsindex 1f1e0a78e..8515f831a 100644--- a/screenpipe-server/src/bin/screenpipe-server.rs+++ b/screenpipe-server/src/bin/screenpipe-server.rs@@ -2,6 +2,7 @@ use std::{collections::HashMap,fs,net::SocketAddr,+ ops::Deref,sync::{atomic::AtomicBool, mpsc::channel, Arc},time::{Duration, Instant},};@@ -81,7 +82,8 @@ async fn main() -> anyhow::Result<()> {builder.filter(None, LevelFilter::Info).filter_module("tokenizers", LevelFilter::Error)- .filter_module("rusty_tesseract", LevelFilter::Error);+ .filter_module("rusty_tesseract", LevelFilter::Error)+ .filter_module("symphonia", LevelFilter::Error);if cli.debug {builder.filter_module("screenpipe", LevelFilter::Debug);@@ -130,10 +132,10 @@ async fn main() -> anyhow::Result<()> {is_running: false,is_paused: false,};- let _ = audio_devices_control_sender.send_deadline(- (device.clone(), device_control.clone()),- Instant::now() + Duration::from_secs(10),- );+ // let _ = audio_devices_control_sender.send_deadline(+ // (device.clone(), device_control.clone()),+ // Instant::now() + Duration::from_secs(10),+ // );devices_status.insert(device.clone(), device_control);info!(" {}", device);}@@ -148,10 +150,10 @@ async fn main() -> anyhow::Result<()> {is_running: true,is_paused: false,};- let _ = audio_devices_control_sender.send_deadline(- (input_device.clone(), device_control.clone()),- Instant::now() + Duration::from_secs(15),- );+ // let _ = audio_devices_control_sender.send_deadline(+ // (input_device.clone(), device_control.clone()),+ // Instant::now() + Duration::from_secs(15),+ // );devices_status.insert(input_device, device_control);}if let Ok(output_device) = default_output_device() {@@ -160,10 +162,10 @@ async fn main() -> anyhow::Result<()> {is_running: true,is_paused: false,};- let _ = audio_devices_control_sender.send_deadline(- (output_device.clone(), device_control.clone()),- Instant::now() + Duration::from_secs(15),- );+ // let _ = audio_devices_control_sender.send_deadline(+ // (output_device.clone(), device_control.clone()),+ // Instant::now() + Duration::from_secs(15),+ // );devices_status.insert(output_device, device_control);}} else {@@ -175,10 +177,10 @@ async fn main() -> anyhow::Result<()> {is_running: true,is_paused: false,};- let _ = audio_devices_control_sender.send_deadline(- (device.clone(), device_control.clone()),- Instant::now() + Duration::from_secs(15),- );+ // let _ = audio_devices_control_sender.send_deadline(+ // (device.clone(), device_control.clone()),+ // Instant::now() + Duration::from_secs(15),+ // );devices_status.insert(device, device_control);}}@@ -189,6 +191,15 @@ async fn main() -> anyhow::Result<()> {info!("Using audio devices:");for device in &audio_devices {info!(" {}", device);++ let device_control = DeviceControl {+ is_running: true,+ is_paused: false,+ };+ let _ = audio_devices_control_sender.send_deadline(+ (device.deref().clone(), device_control),+ Instant::now() + Duration::from_secs(15),+ );}}}@@ -243,6 +254,8 @@ async fn main() -> anyhow::Result<()> {vision_control_server_clone,audio_devices_control_sender_server,);+ // TODO+ // server.start(HashMap::new()).await.unwrap();server.start(devices_status).await.unwrap();});diff --git a/screenpipe-server/src/core.rs b/screenpipe-server/src/core.rsindex 48c59e8b5..47032fc67 100644--- a/screenpipe-server/src/core.rs+++ b/screenpipe-server/src/core.rs@@ -7,11 +7,12 @@ use screenpipe_audio::{create_whisper_channel, record_and_transcribe, AudioDevice, AudioInput, DeviceControl,TranscriptionResult,};+use std::collections::HashMap;use std::sync::atomic::{AtomicBool, Ordering};use std::sync::Arc;use std::thread;use std::time::Duration;-use tokio::runtime::Runtime;+use tokio::task::JoinHandle;pub enum RecorderControl {Pause,Resume,@@ -35,7 +36,6 @@ pub async fn start_continuous_recording(let db_manager_audio = Arc::clone(&db);let is_running_video = Arc::clone(&vision_control);- let is_running_audio = Arc::clone(&vision_control);let output_path_video = Arc::clone(&output_path);let output_path_audio = Arc::clone(&output_path);@@ -49,7 +49,6 @@ pub async fn start_continuous_recording(db_manager_audio,output_path_audio,audio_chunk_duration,- is_running_audio,whisper_sender,whisper_receiver,audio_devices_control_receiver,@@ -57,28 +56,29 @@ pub async fn start_continuous_recording(.await});- // TODO// Control loop- // let control_handle = tokio::spawn(async move {- // while let Ok(ctrl) = full_control.recv() {- // match ctrl {- // RecorderControl::Stop => {- // vision_control.store(false, Ordering::SeqCst);- // // control_all_devices(&device_controls_clone, RecorderControl::Stop);- // }- // RecorderControl::Pause => {- // // control_all_devices(&device_controls_clone, RecorderControl::Pause)- // }- // RecorderControl::Resume => {- // // control_all_devices(&device_controls_clone, RecorderControl::Resume)- // }- // }- // }- // });+ let control_handle = tokio::spawn(async move {+ while let Ok(ctrl) = full_control.recv() {+ match ctrl {+ RecorderControl::Stop => {+ vision_control.store(false, Ordering::SeqCst);+ // stop all audio devices+ // TODO not implemented+ }+ RecorderControl::Pause => {+ // pause all audio devices+ }+ RecorderControl::Resume => {+ vision_control.store(true, Ordering::SeqCst);+ // resume all audio devices+ }+ }+ }+ });video_handle.await??;audio_handle.await??;- // control_handle.await?;+ control_handle.await?;info!("Stopped recording");Ok(())@@ -127,141 +127,167 @@ async fn record_video(Ok(())}+use crossbeam::channel::TryRecvError;+async fn record_audio(db: Arc<DatabaseManager>,output_path: Arc<String>,chunk_duration: Duration,- is_running: Arc<AtomicBool>,whisper_sender: Sender<AudioInput>,whisper_receiver: Receiver<TranscriptionResult>,audio_devices_control_receiver: Receiver<(AudioDevice, DeviceControl)>,) -> Result<()> {- let mut handles = vec![];+ let mut handles: HashMap<String, JoinHandle<()>> = HashMap::new();- while let Ok((audio_device, device_control)) = audio_devices_control_receiver.recv() {- info!("Received audio device: {}", &audio_device);- let db_clone = Arc::clone(&db);- let output_path_clone = Arc::clone(&output_path);- let is_running_clone = Arc::clone(&is_running);- let whisper_sender_clone = whisper_sender.clone();- let whisper_receiver_clone = whisper_receiver.clone();+ 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();- if !device_control.is_running {- info!("Device control signaled stop for device {}", &audio_device);- continue;- }+ 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 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- );+ 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 mut iteration = 0;- while is_running_clone.load(Ordering::SeqCst) {- iteration += 1;- info!(- "Starting iteration {} for device {}",- iteration, audio_device_clone- );+ 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+ );- // TODO: tokio- 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)),- );+ let mut iteration = 0;+ loop {+ iteration += 1;info!(- "Finished record_and_transcribe for device {} (iteration {})",- audio_device_clone, iteration+ "Starting iteration {} for device {}",+ iteration, audio_device_clone);- 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();+ // 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+ }+ });- // Process the recorded chunk- match whisper_receiver.recv() {- Ok(transcription) => {+ // Handle the recording thread result+ match recording_thread.join() {+ Ok(Ok(file_path)) => {info!(- "Received transcription for device {} (iteration {})",- audio_device, iteration+ "Recording complete for device {} (iteration {}): {:?}",+ audio_device, iteration, file_path);- process_audio_result(&db_clone, transcription).await;+ 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+ ),+ }}+ Ok(Err(e)) => error!(+ "Error in record_and_transcribe for device {} (iteration {}): {}",+ audio_device, iteration, e+ ),Err(e) => error!(- "Failed to receive transcription for device {} (iteration {}): {}",+ "Thread panicked for device {} (iteration {}): {:?}",audio_device, iteration, e),}- }- Ok(Err(e)) => error!(- "Error in record_and_transcribe for device {} (iteration {}): {}",- audio_device, iteration, e- ),- Err(e) => error!(- "Thread panicked for device {} (iteration {}): {:?}",- audio_device, iteration, e- ),- }- if !device_control.is_running {- info!(- "Device control signaled stop for device {} after iteration {}",- audio_device, iteration- );- break;- }+ info!(+ "Finished iteration {} for device {}",+ iteration, &audio_device+ );+ }+ });- info!(- "Finished iteration {} for device {}",- iteration, &audio_device- );+ 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!("Exiting audio capture thread for device: {}", &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+ }});- handles.push(handle);+ // Short sleep to prevent busy-waiting+ tokio::time::sleep(Duration::from_millis(100)).await;}- for handle in handles {+ // Wait for all remaining handles to complete+ for (device_id, handle) in handles {if let Err(e) = handle.await {- error!("Error in audio recording task: {}", e);+ error!(+ "Error in audio recording task for device {}: {}",+ device_id, e+ );}}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/server.rs b/screenpipe-server/src/server.rsindex b77220ea5..a606cabf5 100644--- a/screenpipe-server/src/server.rs+++ b/screenpipe-server/src/server.rs@@ -378,7 +378,7 @@ impl Server {db: self.db,vision_control: self.vision_control,audio_devices_control_sender: self.audio_devices_control_sender,- devices_status: device_status.clone(),+ devices_status: device_status,});// https://github.com/tokio-rs/console@@ -406,10 +406,10 @@ impl Server {.with_state(app_state);info!("Starting server on {}", self.addr);- info!("Audio devices:");- for (device, control) in device_status.iter() {- info!("{}: {}", device, control.is_running);- }+ // info!("Audio devices:");+ // for (device, control) in device_status.iter() {+ // info!("{}: {}", device, control.is_running);+ // }match serve(TcpListener::bind(self.addr).await?, app.into_make_service()).await {Ok(_) => {