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: audio output now supported/tested on macos at least (should work on linux/windows but untested). Also use default audio devices now for ease
Louis Beaumont93e465c5210f
diff --git a/screenpipe-audio/Cargo.toml b/screenpipe-audio/Cargo.tomlindex 970f3425b..85518177d 100644--- a/screenpipe-audio/Cargo.toml+++ b/screenpipe-audio/Cargo.toml@@ -15,7 +15,10 @@ serde = { version = "1.0", features = ["derive"] }serde_json = "1.0"# Cross-platform audio capture-cpal = "0.15.2"+# cpal = "0.15.2"+# Temporary hack check https://github.com/RustAudio/cpal/pull/894+cpal = { git = "https://github.com/Kree0/cpal.git", rev = "dfca186" }+# Wav encodinghound = "3.5"@@ -57,5 +60,5 @@ cuda = ["candle/cuda", "candle-nn/cuda", "candle-transformers/cuda"][[bin]]-name = "pipe-audio"+name = "screenpipe-audio"path = "src/bin/screenpipe-audio.rs"diff --git a/screenpipe-audio/src/bin/screenpipe-audio.rs b/screenpipe-audio/src/bin/screenpipe-audio.rsindex 9d051f1b1..c0186d330 100644--- a/screenpipe-audio/src/bin/screenpipe-audio.rs+++ b/screenpipe-audio/src/bin/screenpipe-audio.rs@@ -1,11 +1,11 @@use anyhow::{anyhow, Result};use clap::Parser;-use cpal::traits::{DeviceTrait, HostTrait};use log::info;-use screenpipe_audio::continuous_audio_capture;use screenpipe_audio::list_audio_devices;use screenpipe_audio::parse_device_spec;+use screenpipe_audio::record_and_transcribe;use screenpipe_audio::AudioDevice;+use std::path::PathBuf;use std::thread;use std::time::Duration;@@ -13,10 +13,10 @@ use std::time::Duration;#[clap(author, version, about, long_about = None)]struct Args {#[clap(short, long, help = "Audio device name")]- device: Option<String>,+ audio_device: Option<String>,#[clap(long, help = "List available audio devices")]- list_devices: bool,+ list_audio_devices: bool,}fn print_devices(devices: &[AudioDevice]) {@@ -40,12 +40,12 @@ fn main() -> Result<()> {let devices = list_audio_devices()?;- if args.list_devices {+ if args.list_audio_devices {print_devices(&devices);return Ok(());}- let device = match args.device {+ let device = match args.audio_device {Some(d) => parse_device_spec(&d).unwrap(),None => {if devices.is_empty() {@@ -62,16 +62,34 @@ fn main() -> Result<()> {}};- let (_control_tx, control_rx) = mpsc::channel();let (result_tx, result_rx) = mpsc::channel();- let chunk_duration = Duration::from_secs(5);- let _capture_thread = thread::spawn(move || {- continuous_audio_capture(&device, control_rx, result_tx, chunk_duration)+ let chunk_duration = Duration::from_secs(30);+ let output_path = PathBuf::from("output.wav");+ // Spawn a thread to handle the recording and transcription+ let recording_thread = thread::spawn(move || {+ record_and_transcribe(&device, chunk_duration, result_tx, output_path)});+ // Main loop to receive and print transcriptionsloop {- if let Ok(result) = result_rx.recv_timeout(Duration::from_secs(5)) {- info!("Transcription: {}", result.text);+ match result_rx.recv_timeout(Duration::from_secs(5)) {+ Ok(result) => {+ info!("Transcription: {}", result.text);+ }+ Err(mpsc::RecvTimeoutError::Timeout) => {+ // No transcription received in 5 seconds, continue waiting+ continue;+ }+ Err(mpsc::RecvTimeoutError::Disconnected) => {+ // Sender has been dropped, recording is complete+ break;+ }}}++ // Wait for the recording thread to finish+ let file_path = recording_thread.join().unwrap()?;+ println!("Recording complete: {:?}", file_path);++ Ok(())}diff --git a/screenpipe-audio/src/core.rs b/screenpipe-audio/src/core.rsindex 7f43c7a27..afee39de8 100644--- a/screenpipe-audio/src/core.rs+++ b/screenpipe-audio/src/core.rs@@ -1,19 +1,20 @@use anyhow::{anyhow, Result};-use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};-use hound::WavWriter;+use cpal::{FromSample, Sample};+use hound::WavSpec;use log::{error, info};use serde::Serialize;-use std::sync::mpsc::{Receiver, Sender};+use std::fmt;+use std::fs::File;+use std::path::PathBuf;+use std::sync::mpsc::Sender;use std::sync::{Arc, Mutex};use std::time::{Duration, Instant};-use std::{fmt, thread};-use tempfile::NamedTempFile;+use std::{io::BufWriter, thread};use crate::stt::stt;-pub struct CaptureResult {- pub audio: Vec<f32>,+pub struct AudioCaptureResult {pub text: String,}@@ -49,11 +50,15 @@ impl fmt::Display for DeviceSpec {fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {match self {DeviceSpec::Input(name) => {- write!(f, "Input: {}", name.as_ref().unwrap_or(&"None".to_string()))+ write!(+ f,+ "{} (input)",+ name.as_ref().unwrap_or(&"None".to_string())+ )}DeviceSpec::Output(name) => write!(f,- "Output: {}",+ "{} (output)",name.as_ref().unwrap_or(&"None".to_string())),}@@ -72,232 +77,173 @@ impl Clone for DeviceSpec {// Helper function to create DeviceSpec from a name or Nonepub fn parse_device_spec(name: &str) -> Result<DeviceSpec> {- DeviceSpec::from_name(name)+ DeviceSpec::from_name(&name)}-pub fn continuous_audio_capture(+pub fn record_and_transcribe(device_spec: &DeviceSpec,- control_rx: Receiver<ControlMessage>,- result_tx: Sender<CaptureResult>,- chunk_duration: Duration,-) -> Result<()> {- let host = cpal::default_host();-- let (device, is_input) = match device_spec {- DeviceSpec::Input(name) => {- let device = match name {- Some(name) => host- .devices()?- .find(|d| d.name().map(|n| n == *name).unwrap_or(false))- .ok_or_else(|| {- anyhow::anyhow!("Specified input device '{}' not found", name)- })?,- None => host- .default_input_device()- .ok_or_else(|| anyhow::anyhow!("No default input device available"))?,- };- (device, true)+ duration: Duration,+ result_tx: Sender<AudioCaptureResult>,+ output_path: PathBuf,+) -> Result<PathBuf> {+ let host = if cfg!(target_os = "macos") {+ match device_spec {+ // https://github.com/RustAudio/cpal/pull/894+ DeviceSpec::Output(_) => cpal::host_from_id(cpal::HostId::ScreenCaptureKit)?,+ _ => cpal::default_host(),}- DeviceSpec::Output(name) => {- let device = match name {- Some(name) => host- .devices()?- .find(|d| d.name().map(|n| n == *name).unwrap_or(false))- .ok_or_else(|| {- anyhow::anyhow!("Specified output device '{}' not found", name)- })?,- None => host- .default_output_device()- .ok_or_else(|| anyhow::anyhow!("No default output device available"))?,- };- (device, false)- }- };-- let config = if is_input {- info!("Device is input, using input config");- device.default_input_config()?} else {- info!("Device is output, using output config");- device.default_output_config()?+ cpal::default_host()};- let sample_rate = config.sample_rate().0;- let channels = config.channels() as usize;- info!(- "Sample rate: {}, Channels: {}, Device: \"{}\", Config: {:?}, Type: {}",- sample_rate,- channels,- device.name().unwrap(),- config,- if is_input { "Input" } else { "Output" }- );+ info!("device: {:?}", device_spec.to_string());- let audio_buffer = Arc::new(Mutex::new(Vec::new()));- let audio_buffer_clone = audio_buffer.clone();+ let device = if device_spec.to_string() == "default" {+ host.default_input_device()+ } else {+ host.input_devices()?.find(|x| {+ x.name()+ .map(|y| {+ y == device_spec+ .to_string()+ .replace(" (input)", "")+ .replace(" (output)", "")+ })+ .unwrap_or(false)+ })+ }+ .ok_or_else(|| anyhow!("Device not found"))?;++ let config = device.default_input_config()?;+ info!("Recording device: {}, Config: {:?}", device.name()?, config);- let is_paused = Arc::new(Mutex::new(false));- let should_stop = Arc::new(Mutex::new(false));+ let spec = wav_spec_from_config(&config);+ let writer = hound::WavWriter::create(&output_path, spec)?;+ let writer = Arc::new(Mutex::new(Some(writer)));+ let writer_2 = writer.clone();+ let err_fn = |err| error!("An error occurred on the audio stream: {}", err);- let is_paused_clone = is_paused.clone();- let stream = if is_input {- info!("Building input stream");- device.build_input_stream(+ let stream = match config.sample_format() {+ cpal::SampleFormat::I8 => device.build_input_stream(&config.into(),- move |data: &[f32], _: &_| {- if !*is_paused_clone.lock().unwrap() {- audio_buffer_clone.lock().unwrap().extend_from_slice(data);- }- },- |err| error!("An error occurred on the input audio stream: {}", err),+ move |data, _: &_| write_input_data::<i8, i8>(data, &writer_2),+ err_fn,None,- )?- } else {- info!("Building output stream");- let err_fn = |err| error!("An error occurred on the output audio stream: {}", err);- device.build_output_stream(+ )?,+ cpal::SampleFormat::I16 => device.build_input_stream(&config.into(),- move |data: &mut [f32], _: &_| {- if !*is_paused_clone.lock().unwrap() {- // For output devices, we need to fill the buffer with silence- // and capture what would have been played- for sample in data.iter_mut() {- *sample = 0.0; // Fill with silence- }- audio_buffer_clone.lock().unwrap().extend_from_slice(data);- }- },+ move |data, _: &_| write_input_data::<i16, i16>(data, &writer_2),err_fn,None,- )?+ )?,+ cpal::SampleFormat::I32 => device.build_input_stream(+ &config.into(),+ move |data, _: &_| write_input_data::<i32, i32>(data, &writer_2),+ err_fn,+ None,+ )?,+ cpal::SampleFormat::F32 => device.build_input_stream(+ &config.into(),+ move |data, _: &_| write_input_data::<f32, f32>(data, &writer_2),+ err_fn,+ None,+ )?,+ sample_format => return Err(anyhow!("Unsupported sample format '{}'", sample_format)),};- match stream.play() {- Ok(_) => info!("Successfully started audio stream"),- Err(e) => error!("Failed to start audio stream: {}", e),- }+ stream.play()?;+ info!(+ "Will write an audio file every {} seconds",+ duration.as_secs()+ );- let is_paused_clone = is_paused.clone();- let should_stop_clone = should_stop.clone();-- let process_audio = move || -> Result<()> {- let mut last_process_time = Instant::now();- let mut full_transcription = String::new();-- loop {- // Check for control messages- if let Ok(message) = control_rx.try_recv() {- match message {- ControlMessage::Pause => *is_paused_clone.lock().unwrap() = true,- ControlMessage::Resume => *is_paused_clone.lock().unwrap() = false,- ControlMessage::Stop => {- *should_stop_clone.lock().unwrap() = true;- break;- }- }- }+ let start_time = Instant::now();+ let chunk_duration = Duration::from_secs(5); // Adjust as needed+ let mut next_chunk_time = start_time + chunk_duration;- if *is_paused_clone.lock().unwrap() {- thread::sleep(Duration::from_millis(100));- continue;- }+ while start_time.elapsed() < duration {+ let now = Instant::now();- let now = Instant::now();- if now.duration_since(last_process_time) < chunk_duration {- thread::sleep(Duration::from_millis(100));- continue;- }+ if now >= next_chunk_time {+ // Stop the stream temporarily+ stream.pause()?;- let mut audio_data = audio_buffer.lock().unwrap();- let required_samples = sample_rate as usize * (chunk_duration.as_secs() as usize);- // sample_rate as usize * channels * (chunk_duration.as_secs() as usize);- // TODO: dont think we should multiply by channels here- if audio_data.len() >= required_samples {- info!("Processing audio... Buffer size: {}", audio_data.len());- let chunk = audio_data.drain(..required_samples).collect::<Vec<f32>>();- drop(audio_data);-- // Process the audio chunk (save to file and transcribe)- let temp_file = NamedTempFile::new()?;- let temp_path = temp_file.path().to_str().unwrap();-- let spec = hound::WavSpec {- channels: channels as u16,- sample_rate,- bits_per_sample: 16,- sample_format: hound::SampleFormat::Int,- };- let mut writer = WavWriter::create(temp_path, spec)?;- for sample in chunk.iter() {- writer.write_sample((sample * 32767.0) as i16)?;- }- writer.finalize()?;-- info!("Starting transcription for file: {}", temp_path);- match stt(temp_path) {- Ok(transcription) => {- // info!("Transcription successful: {}", transcription);-- if !transcription.is_empty() {- if !full_transcription.is_empty() {- full_transcription.push(' ');- }- full_transcription.push_str(&transcription);- }+ {+ let mut writer_guard = writer.lock().unwrap();+ if let Some(writer) = writer_guard.as_mut() {+ writer.flush()?;- result_tx.send(CaptureResult {- audio: chunk,- text: full_transcription.clone(),- })?;- }- Err(e) => {- error!("Transcription failed: {}", e);- continue;+ // Transcribe the current audio chunk+ match stt(output_path.to_str().unwrap()) {+ Ok(transcription) => {+ result_tx.send(AudioCaptureResult {+ text: transcription,+ })?;+ }+ Err(e) => error!("Transcription failed: {}", e),}}- std::fs::remove_file(temp_path)?;-- last_process_time = now;- } else {- thread::sleep(Duration::from_millis(100));}- if *should_stop_clone.lock().unwrap() {- break;+ // Resume the stream+ stream.play()?;+ next_chunk_time = now + chunk_duration;+ }++ thread::sleep(Duration::from_millis(100));+ }++ // Final flush and transcription+ {+ let mut writer_guard = writer.lock().unwrap();+ if let Some(writer) = writer_guard.as_mut() {+ writer.flush()?;++ match stt(output_path.to_str().unwrap()) {+ Ok(transcription) => {+ result_tx.send(AudioCaptureResult {+ text: transcription,+ })?;+ }+ Err(e) => error!("Final transcription failed: {}", e),}}- Ok(())- };+ }- process_audio()?;- Ok(())+ Ok(output_path)}-pub enum ControlMessage {- Pause,- Resume,- Stop,+fn wav_spec_from_config(config: &cpal::SupportedStreamConfig) -> WavSpec {+ WavSpec {+ channels: config.channels() as _,+ sample_rate: config.sample_rate().0 as _,+ bits_per_sample: (config.sample_format().sample_size() * 8) as _,+ sample_format: sample_format(config.sample_format()),+ }+}+type WavWriterHandle = Arc<Mutex<Option<hound::WavWriter<BufWriter<File>>>>>;++fn write_input_data<T, U>(input: &[T], writer: &WavWriterHandle)+where+ T: Sample,+ U: Sample + hound::Sample + FromSample<T>,+{+ if let Ok(mut guard) = writer.try_lock() {+ if let Some(writer) = guard.as_mut() {+ for &sample in input.iter() {+ let sample: U = U::from_sample(sample);+ writer.write_sample(sample).ok();+ }+ }+ }}-// a function to save an audio to file-pub fn save_audio_to_file(audio: &[f32], file_path: &str) -> Result<()> {- let spec = hound::WavSpec {- channels: 1, // TODO- sample_rate: 44100,- bits_per_sample: 32,- sample_format: hound::SampleFormat::Float,- };- let mut writer = WavWriter::create(file_path, spec)- .map_err(|e| anyhow::anyhow!("Failed to create WavWriter: {}", e))?;- for sample in audio.iter() {- writer- .write_sample(*sample)- .map_err(|e| anyhow::anyhow!("Failed to write sample: {}", e))?;+fn sample_format(format: cpal::SampleFormat) -> hound::SampleFormat {+ if format.is_float() {+ hound::SampleFormat::Float+ } else {+ hound::SampleFormat::Int}- writer- .finalize()- .map_err(|e| anyhow::anyhow!("Failed to finalize WavWriter: {}", e))?;- Ok(())}#[derive(Serialize)]@@ -325,14 +271,53 @@ pub fn list_audio_devices() -> Result<Vec<AudioDevice>> {}}- for device in host.output_devices()? {- if let Ok(name) = device.name() {- devices.push(AudioDevice {- name,- device_type: "output".to_string(),- });+ // on macos only+ if cfg!(target_os = "macos") {+ let host = cpal::host_from_id(cpal::HostId::ScreenCaptureKit)?;+ for device in host.input_devices()? {+ if let Ok(name) = device.name() {+ devices.push(AudioDevice {+ name,+ device_type: "input".to_string(),+ });+ }+ }+ } else {+ for device in host.output_devices()? {+ if let Ok(name) = device.name() {+ devices.push(AudioDevice {+ name,+ device_type: "output".to_string(),+ });+ }}}Ok(devices)}++// function that return default device to record audio+pub fn default_input_device() -> Result<DeviceSpec> {+ let host = cpal::default_host();+ let device = host.default_input_device().unwrap();+ info!("Using default input device: {}", device.name()?);+ Ok(DeviceSpec::Input(Some(device.name()?)))+}++// ! HACK - yes this quite unintuitive ... but it works ...++// function that return default device to record audio+pub fn default_output_device() -> Result<DeviceSpec> {+ let host = cpal::default_host();+ // on mac pick the display capture device+ if cfg!(target_os = "macos") {+ let host = cpal::host_from_id(cpal::HostId::ScreenCaptureKit)?;+ let device = host.default_input_device().unwrap();+ info!("Using display capture device: {}", device.name()?);+ Ok(DeviceSpec::Output(Some(device.name()?)))+ } else {+ let device = host.default_output_device().unwrap();+ info!("Using default output device: {}", device.name()?);+ Ok(DeviceSpec::Output(Some(device.name()?)))+ }+}diff --git a/screenpipe-audio/src/lib.rs b/screenpipe-audio/src/lib.rsindex 837f1a8dd..04729f805 100644--- a/screenpipe-audio/src/lib.rs+++ b/screenpipe-audio/src/lib.rs@@ -4,6 +4,6 @@ mod pcm_decode;mod stt;pub use core::{- continuous_audio_capture, list_audio_devices, parse_device_spec, save_audio_to_file,- AudioDevice, ControlMessage, DeviceSpec,+ default_input_device, default_output_device, list_audio_devices, parse_device_spec,+ record_and_transcribe, AudioCaptureResult, AudioDevice, DeviceSpec,};diff --git a/screenpipe-audio/tests/core_tests.rs b/screenpipe-audio/tests/core_tests.rsnew file mode 100644index 000000000..2ccfc5696--- /dev/null+++ b/screenpipe-audio/tests/core_tests.rs@@ -0,0 +1,21 @@+#[cfg(test)]+mod tests {+ use screenpipe_audio::{list_audio_devices, parse_device_spec};++ use super::*;++ // ! what happen in github action?+ #[test]+ fn test_list_audio_devices() {+ let devices = list_audio_devices().unwrap();+ assert!(!devices.is_empty());+ }++ #[test]+ fn test_parse_device_spec() {+ let spec = parse_device_spec("Test Device (input)").unwrap();+ assert_eq!(spec.to_string(), "Test Device (input)");+ }++ // Add more tests for other functions+}diff --git a/screenpipe-server/Cargo.toml b/screenpipe-server/Cargo.tomlindex 5621c128d..edcc98293 100644--- a/screenpipe-server/Cargo.toml+++ b/screenpipe-server/Cargo.toml@@ -65,12 +65,19 @@ clap = { version = "4.3", features = ["derive"] }# Memory watchdogsysinfo = "0.29.0"+# Color+colored = "2.0"+[dev-dependencies]tempfile = "3.3.0"[features]static-ffmpeg = ["ffmpeg-next/static"]+metal = ["candle/metal", "candle-nn/metal", "candle-transformers/metal"]+cuda = ["candle/cuda", "candle-nn/cuda", "candle-transformers/cuda"]++[[bin]]name = "screenpipe"path = "src/bin/screenpipe-server.rs"diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rsindex 79bd568d4..577a0836b 100644--- a/screenpipe-server/src/bin/screenpipe-server.rs+++ b/screenpipe-server/src/bin/screenpipe-server.rs@@ -7,9 +7,12 @@ use std::{use clap::Parser;use log::{info, LevelFilter};-use screenpipe_audio::{list_audio_devices, parse_device_spec};-use screenpipe_server::{start_continuous_recording, DatabaseManager, ResourceMonitor, Server}; // Import the list_audio_devices function+use screenpipe_audio::{+ default_input_device, default_output_device, list_audio_devices, parse_device_spec,+};+use colored::*;+use screenpipe_server::{start_continuous_recording, DatabaseManager, ResourceMonitor, Server}; // Import the list_audio_devices function#[derive(Parser)]#[command(author, version, about, long_about = None)]struct Cli {@@ -57,6 +60,19 @@ async fn main() -> anyhow::Result<()> {.filter_module("rusty_tesseract", LevelFilter::Error).init();+ // Add warning for Linux and Windows users+ #[cfg(any(target_os = "linux", target_os = "windows"))]+ {+ warn!("Screenpipe hasn't been extensively tested on this OS. We'd love your feedback!");+ println!("{}", "Would love your feedback on the UX, let's a 15 min call soon:".bright_yellow());+ println!(+ "{}",+ "https://cal.com/louis030195/screenpipe"+ .bright_blue()+ .underline()+ );+ }+if cli.list_audio_devices {let devices = list_audio_devices()?;println!("Available audio devices:");@@ -68,36 +84,33 @@ async fn main() -> anyhow::Result<()> {let mut audio_devices = Vec::new();- if !cli.disable_audio && cli.audio_device.is_empty() {- let devices = list_audio_devices()?;- eprintln!("No audio devices specified. Available devices are:");- for (i, device) in devices.iter().enumerate() {- eprintln!(" {}. {}", i + 1, device);- }- eprintln!("\nPlease specify one or more devices with:");- eprintln!(- " {} --audio-device \"Device Name (input)\" [--audio-device \"Another Device (output)\"]",- std::env::args().next().unwrap()- );- eprintln!("ATM only input devices are supported");- return Err(anyhow::anyhow!("No audio devices specified"));- } else {- // if audio device contains (output) throw error say not implemented yet and link to https://github.com/louis030195/screen-pipe/issues/24- cli.audio_device.iter().for_each(|d| {- if d.contains("(output)") {- eprintln!("Output audio devices are not supported yet.");- eprintln!(- "Please help on this issue at https://github.com/louis030195/screen-pipe/issues/24"- );- std::process::exit(1);+ if !cli.disable_audio {+ if cli.audio_device.is_empty() {+ // Add default input device+ if let Ok(input_device) = default_input_device() {+ audio_devices.push(Arc::new(input_device));+ }+ // Add default output device+ if let Ok(output_device) = default_output_device() {+ audio_devices.push(Arc::new(output_device));+ }+ } else {+ // Use specified devices+ for d in &cli.audio_device {+ audio_devices.push(Arc::new(+ parse_device_spec(d).expect("Failed to parse audio device specification"),+ ));}- });+ }- cli.audio_device.iter().for_each(|d| {- audio_devices.push(Arc::new(- parse_device_spec(d).expect("Failed to parse audio device specification"),- ))- });+ if audio_devices.is_empty() {+ eprintln!("No audio devices available. Audio recording will be disabled.");+ } else {+ info!("Using audio devices:");+ for device in &audio_devices {+ info!(" {}", device);+ }+ }}ResourceMonitor::new(cli.memory_threshold, cli.runtime_threshold)diff --git a/screenpipe-server/src/core.rs b/screenpipe-server/src/core.rsindex 7daafd4e2..bad14bdf8 100644--- a/screenpipe-server/src/core.rs+++ b/screenpipe-server/src/core.rs@@ -2,14 +2,13 @@ use crate::{DatabaseManager, VideoCapture};use anyhow::Result;use chrono::Utc;use log::{debug, error, info};-use screenpipe_audio::{- continuous_audio_capture, save_audio_to_file, ControlMessage as AudioControlMessage, DeviceSpec,-};+use screenpipe_audio::{record_and_transcribe, AudioCaptureResult, DeviceSpec};+use screenpipe_vision::CaptureResult;use std::sync::atomic::{AtomicBool, Ordering};use std::sync::mpsc::{self, Receiver};use std::sync::Arc;-use std::thread;use std::time::Duration;+use std::{fs, thread};use tokio::runtime::Runtime;pub enum RecorderControl {Pause,@@ -136,77 +135,54 @@ async fn record_audio(let device_spec_clone = Arc::clone(&device_spec);let handle = tokio::spawn(async move {- let (audio_control_tx, audio_control_rx) = mpsc::channel();- let (audio_result_tx, audio_result_rx) = mpsc::channel();+ let (result_tx, result_rx) = mpsc::channel();- let audio_thread = thread::spawn(move || {- info!(- "Starting audio capture thread for device: {}",- &device_spec_clone- );- if let Err(e) = continuous_audio_capture(- device_spec_clone.as_ref(),- audio_control_rx,- audio_result_tx,- chunk_duration,- ) {- error!(- "Audio capture failed for device {}: {}",- device_spec_clone, e- );- }- });+ info!(+ "Starting audio capture thread for device: {}",+ &device_spec_clone+ );while is_running_clone.load(Ordering::SeqCst) {- match audio_result_rx.recv_timeout(Duration::from_secs(1)) {- Ok(result) => {- let time = Utc::now();- let file_path =- format!("{}/{}_{}.wav", output_path_clone, device_spec.clone(), time);- if let Err(e) = save_audio_to_file(&result.audio, &file_path) {- error!(- "Failed to save audio file for device {}: {}",- device_spec, e- );- continue;- }-- match db_clone.insert_audio_chunk(&file_path).await {- Ok(audio_chunk_id) => {- if let Err(e) = db_clone- .insert_audio_transcription(audio_chunk_id, &result.text, 0)- .await- {- error!(- "Failed to insert audio transcription for device {}: {}",- device_spec, e- );- } else {- debug!(- "Inserted audio transcription for chunk {} from device {}",- audio_chunk_id, device_spec- );- }- }- Err(e) => error!(- "Failed to insert audio chunk for device {}: {}",- device_spec, e- ),- }+ let recording_thread = thread::spawn({+ let device_spec_clone = Arc::clone(&device_spec_clone);+ let result_tx = result_tx.clone();+ let output_path_clone = Arc::clone(&output_path_clone);+ move || {+ let new_file_name = Utc::now().format("%Y-%m-%d_%H-%M-%S").to_string();+ let file_path = format!(+ "{}/{}_{}.wav",+ output_path_clone, device_spec_clone, new_file_name+ );+ record_and_transcribe(+ device_spec_clone.as_ref(),+ chunk_duration,+ result_tx,+ file_path.into(),+ )}- Err(mpsc::RecvTimeoutError::Timeout) => continue,- Err(e) => {- error!(- "Failed to receive audio chunk for device {}: {}",- device_spec, e+ });++ match recording_thread.join() {+ Ok(Ok(file_path)) => {+ info!(+ "Recording complete for device {}: {:?}",+ device_spec_clone, file_path);- break;+ // Process the recorded chunk+ while let Ok(result) = result_rx.try_recv() {+ process_audio_result(+ &db_clone,+ &file_path.to_str().unwrap(),+ &device_spec_clone,+ result,+ )+ .await;+ }}+ Ok(Err(e)) => error!("Error in record_and_transcribe: {}", e),+ Err(e) => error!("Thread panicked: {:?}", e),}}-- audio_control_tx.send(AudioControlMessage::Stop).unwrap();- let _ = audio_thread.join().expect("Failed to join audio thread");});handles.push(handle);@@ -220,3 +196,34 @@ async fn record_audio(Ok(())}++async fn process_audio_result(+ db: &DatabaseManager,+ output_path: &str,+ device_spec: &DeviceSpec,+ result: AudioCaptureResult,+) {+ info!("Inserting audio chunk: {}", output_path);+ match db.insert_audio_chunk(&output_path).await {+ Ok(audio_chunk_id) => {+ if let Err(e) = db+ .insert_audio_transcription(audio_chunk_id, &result.text, 0)+ .await+ {+ error!(+ "Failed to insert audio transcription for device {}: {}",+ device_spec, e+ );+ } else {+ debug!(+ "Inserted audio transcription for chunk {} from device {}",+ audio_chunk_id, device_spec+ );+ }+ }+ Err(e) => error!(+ "Failed to insert audio chunk for device {}: {}",+ device_spec, e+ ),+ }+}diff --git a/screenpipe-server/tests/audio_vision_integration_test.rs b/screenpipe-server/tests/audio_vision_integration_test.rsnew file mode 100644index 000000000..9f7075ff3--- /dev/null+++ b/screenpipe-server/tests/audio_vision_integration_test.rs@@ -0,0 +1,8 @@+use std::{sync::mpsc, thread, time::Duration};++use screenpipe_server::VideoCapture;++#[test]+fn test_audio_video_capture() {+ assert!(true) // TODO+}diff --git a/screenpipe-vision/Cargo.toml b/screenpipe-vision/Cargo.tomlindex b33219604..6f2c01047 100644--- a/screenpipe-vision/Cargo.toml+++ b/screenpipe-vision/Cargo.toml@@ -50,5 +50,5 @@ tempfile = "3.3.0"[[bin]]-name = "pipe-vision"+name = "screenpipe-vision"path = "src/bin/screenpipe-vision.rs"