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: support multiple audio device

Louis Beaumontc612c0bb8236
diff --git a/screenpipe-audio/Cargo.toml b/screenpipe-audio/Cargo.toml
index beb2339b9..970f3425b 100644
--- a/screenpipe-audio/Cargo.toml
+++ b/screenpipe-audio/Cargo.toml
@@ -45,6 +45,9 @@ rubato = "0.15.0"
log = { workspace = true }
env_logger = "0.10"
+# File
+tempfile = "3"
+
[dev-dependencies]
tempfile = "3.3.0"
diff --git a/screenpipe-audio/src/audio.rs b/screenpipe-audio/src/audio.rs
deleted file mode 100644
index b103d87c4..000000000
--- a/screenpipe-audio/src/audio.rs
+++ /dev/null
@@ -1,66 +0,0 @@
-use cpal::Sample;
-use std::fs::File;
-use std::io::BufWriter;
-use std::sync::{Arc, Mutex};
-
-use anyhow::Result;
-use cpal::traits::{DeviceTrait, HostTrait};
-
-pub fn wav_spec_from_config(config: &cpal::SupportedStreamConfig) -> hound::WavSpec {
- hound::WavSpec {
- channels: config.channels() as _,
- sample_rate: config.sample_rate().0 as _,
- bits_per_sample: 16,
- sample_format: hound::SampleFormat::Int,
- }
-}
-
-pub fn write_input_data<T>(
- input: &[T],
- writer: &Arc<Mutex<Option<hound::WavWriter<BufWriter<File>>>>>,
- is_paused: &Arc<Mutex<bool>>,
-) where
- T: Sample + SampleToI16,
-{
- if !*is_paused.lock().unwrap() {
- if let Ok(mut guard) = writer.try_lock() {
- if let Some(writer) = guard.as_mut() {
- for &sample in input.iter() {
- let sample_to_write: i16 = sample.to_i16();
- writer.write_sample(sample_to_write).ok();
- }
- }
- }
- }
-}
-
-trait SampleToI16 {
- fn to_i16(&self) -> i16;
-}
-
-impl SampleToI16 for f32 {
- fn to_i16(&self) -> i16 {
- (self.clamp(-1.0, 1.0) * i16::MAX as f32) as i16
- }
-}
-
-impl SampleToI16 for i16 {
- fn to_i16(&self) -> i16 {
- *self
- }
-}
-
-impl SampleToI16 for u16 {
- fn to_i16(&self) -> i16 {
- (*self as i32 - i16::MAX as i32) as i16
- }
-}
-
-pub fn list_audio_devices() -> Result<Vec<String>> {
- let host = cpal::default_host();
- let devices = host
- .input_devices()?
- .filter_map(|d| d.name().ok())
- .collect::<Vec<_>>();
- Ok(devices)
-}
diff --git a/screenpipe-audio/src/bin/screenpipe-audio.rs b/screenpipe-audio/src/bin/screenpipe-audio.rs
index 317f8312e..9d051f1b1 100644
--- a/screenpipe-audio/src/bin/screenpipe-audio.rs
+++ b/screenpipe-audio/src/bin/screenpipe-audio.rs
@@ -4,6 +4,8 @@ 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::AudioDevice;
use std::thread;
use std::time::Duration;
@@ -17,8 +19,8 @@ struct Args {
list_devices: bool,
}
-fn print_devices(devices: &[String]) {
- println!("Available input devices:");
+fn print_devices(devices: &[AudioDevice]) {
+ println!("Available audio devices:");
for (i, device) in devices.iter().enumerate() {
println!(" {}. {}", i + 1, device);
}
@@ -44,16 +46,16 @@ fn main() -> Result<()> {
}
let device = match args.device {
- Some(d) => d,
+ Some(d) => parse_device_spec(&d).unwrap(),
None => {
if devices.is_empty() {
return Err(anyhow!("No audio input devices found"));
}
eprintln!("No audio device specified. Available devices are:");
print_devices(&devices);
- eprintln!("\nPlease specify a device with:");
+ eprintln!("\nPlease specify one or more devices with:");
eprintln!(
- " {} --device \"Device Name\"",
+ " {} --audio-device \"Device Name (input)\" [--audio-device \"Another Device (output)\"]",
std::env::args().next().unwrap()
);
return Err(anyhow!("No device specified"));
@@ -64,7 +66,7 @@ fn main() -> Result<()> {
let (result_tx, result_rx) = mpsc::channel();
let chunk_duration = Duration::from_secs(5);
let _capture_thread = thread::spawn(move || {
- continuous_audio_capture(Some(device), control_rx, result_tx, chunk_duration)
+ continuous_audio_capture(&device, control_rx, result_tx, chunk_duration)
});
loop {
diff --git a/screenpipe-audio/src/core.rs b/screenpipe-audio/src/core.rs
index f7e548d85..7f43c7a27 100644
--- a/screenpipe-audio/src/core.rs
+++ b/screenpipe-audio/src/core.rs
@@ -1,11 +1,14 @@
-use anyhow::Result;
+use anyhow::{anyhow, Result};
+
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use hound::WavWriter;
-use log::{debug, error, info};
+use log::{error, info};
+use serde::Serialize;
use std::sync::mpsc::{Receiver, Sender};
use std::sync::{Arc, Mutex};
-use std::thread;
-use std::time::Duration;
+use std::time::{Duration, Instant};
+use std::{fmt, thread};
+use tempfile::NamedTempFile;
use crate::stt::stt;
@@ -14,32 +17,120 @@ pub struct CaptureResult {
pub text: String,
}
+pub enum DeviceSpec {
+ Input(Option<String>),
+ Output(Option<String>),
+}
+
+impl DeviceSpec {
+ pub fn from_name(name: &str) -> Result<Self> {
+ if name.trim().is_empty() {
+ return Err(anyhow!("Device name cannot be empty"));
+ }
+
+ if name.to_lowercase().ends_with("(input)") {
+ Ok(DeviceSpec::Input(Some(
+ name.trim_end_matches("(input)").trim().to_string(),
+ )))
+ } else if name.to_lowercase().ends_with("(output)") {
+ Ok(DeviceSpec::Output(Some(
+ name.trim_end_matches("(output)").trim().to_string(),
+ )))
+ } else {
+ Err(anyhow!(
+ "Device type (input/output) not specified in the name"
+ ))
+ }
+ }
+}
+
+// impl display for DeviceSpec
+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()))
+ }
+ DeviceSpec::Output(name) => write!(
+ f,
+ "Output: {}",
+ name.as_ref().unwrap_or(&"None".to_string())
+ ),
+ }
+ }
+}
+
+// impl copy for DeviceSpec
+impl Clone for DeviceSpec {
+ fn clone(&self) -> Self {
+ match self {
+ DeviceSpec::Input(name) => DeviceSpec::Input(name.clone()),
+ DeviceSpec::Output(name) => DeviceSpec::Output(name.clone()),
+ }
+ }
+}
+
+// Helper function to create DeviceSpec from a name or None
+pub fn parse_device_spec(name: &str) -> Result<DeviceSpec> {
+ DeviceSpec::from_name(name)
+}
+
pub fn continuous_audio_capture(
- device_name: Option<String>,
+ device_spec: &DeviceSpec,
control_rx: Receiver<ControlMessage>,
result_tx: Sender<CaptureResult>,
chunk_duration: Duration,
) -> Result<()> {
let host = cpal::default_host();
- let device = match device_name {
- Some(name) => host
- .devices()?
- .find(|d| d.name().map(|n| n == name).unwrap_or(false))
- .ok_or_else(|| anyhow::anyhow!("Specified device '{}' not found", name))?,
- None => host
- .default_input_device()
- .ok_or_else(|| anyhow::anyhow!("No default input device available"))?,
+
+ 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)
+ }
+ 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 = device.default_input_config()?;
+ 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()?
+ };
let sample_rate = config.sample_rate().0;
let channels = config.channels() as usize;
info!(
- "Sample rate: {}, Channels: {}, Device: {}",
+ "Sample rate: {}, Channels: {}, Device: \"{}\", Config: {:?}, Type: {}",
sample_rate,
channels,
- device.name().unwrap()
+ device.name().unwrap(),
+ config,
+ if is_input { "Input" } else { "Output" }
);
let audio_buffer = Arc::new(Mutex::new(Vec::new()));
@@ -49,16 +140,37 @@ pub fn continuous_audio_capture(
let should_stop = Arc::new(Mutex::new(false));
let is_paused_clone = is_paused.clone();
- let stream = 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),
- None,
- )?;
+ let stream = if is_input {
+ info!("Building input stream");
+ 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),
+ None,
+ )?
+ } else {
+ info!("Building output stream");
+ let err_fn = |err| error!("An error occurred on the output audio stream: {}", err);
+ device.build_output_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);
+ }
+ },
+ err_fn,
+ None,
+ )?
+ };
match stream.play() {
Ok(_) => info!("Successfully started audio stream"),
@@ -69,8 +181,10 @@ pub fn continuous_audio_capture(
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 {
- info!("Processing audio...");
// Check for control messages
if let Ok(message) = control_rx.try_recv() {
match message {
@@ -88,40 +202,64 @@ pub fn continuous_audio_capture(
continue;
}
- thread::sleep(chunk_duration);
+ let now = Instant::now();
+ if now.duration_since(last_process_time) < chunk_duration {
+ thread::sleep(Duration::from_millis(100));
+ continue;
+ }
let mut audio_data = audio_buffer.lock().unwrap();
- info!("audio_data len: {:?}", audio_data.len());
-
- if !audio_data.is_empty() {
- let chunk = audio_data.clone();
- audio_data.clear();
+ 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 = std::env::temp_dir().join("temp_audio.wav");
+ 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: 32,
- sample_format: hound::SampleFormat::Float,
+ bits_per_sample: 16,
+ sample_format: hound::SampleFormat::Int,
};
- let mut writer = WavWriter::create(&temp_file, spec)?;
+ let mut writer = WavWriter::create(temp_path, spec)?;
for sample in chunk.iter() {
- writer.write_sample(*sample)?;
+ writer.write_sample((sample * 32767.0) as i16)?;
}
writer.finalize()?;
- let transcription = stt(temp_file.to_str().unwrap())?;
- std::fs::remove_file(temp_file)?;
+ info!("Starting transcription for file: {}", temp_path);
+ match stt(temp_path) {
+ Ok(transcription) => {
+ // info!("Transcription successful: {}", transcription);
- info!("Transcription: {}", transcription);
- debug!("Chunk size: {:?}", chunk.len());
+ if !transcription.is_empty() {
+ if !full_transcription.is_empty() {
+ full_transcription.push(' ');
+ }
+ full_transcription.push_str(&transcription);
+ }
- result_tx.send(CaptureResult {
- audio: chunk,
- text: transcription,
- })?;
+ result_tx.send(CaptureResult {
+ audio: chunk,
+ text: full_transcription.clone(),
+ })?;
+ }
+ Err(e) => {
+ error!("Transcription failed: {}", e);
+ continue;
+ }
+ }
+ std::fs::remove_file(temp_path)?;
+
+ last_process_time = now;
+ } else {
+ thread::sleep(Duration::from_millis(100));
}
if *should_stop_clone.lock().unwrap() {
@@ -161,3 +299,40 @@ pub fn save_audio_to_file(audio: &[f32], file_path: &str) -> Result<()> {
.map_err(|e| anyhow::anyhow!("Failed to finalize WavWriter: {}", e))?;
Ok(())
}
+
+#[derive(Serialize)]
+pub struct AudioDevice {
+ name: String,
+ device_type: String,
+}
+
+impl fmt::Display for AudioDevice {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "{} ({})", self.name, self.device_type)
+ }
+}
+
+pub fn list_audio_devices() -> Result<Vec<AudioDevice>> {
+ let host = cpal::default_host();
+ let mut devices = Vec::new();
+
+ for device in host.input_devices()? {
+ if let Ok(name) = device.name() {
+ devices.push(AudioDevice {
+ name,
+ device_type: "input".to_string(),
+ });
+ }
+ }
+
+ for device in host.output_devices()? {
+ if let Ok(name) = device.name() {
+ devices.push(AudioDevice {
+ name,
+ device_type: "output".to_string(),
+ });
+ }
+ }
+
+ Ok(devices)
+}
diff --git a/screenpipe-audio/src/lib.rs b/screenpipe-audio/src/lib.rs
index e91b13874..837f1a8dd 100644
--- a/screenpipe-audio/src/lib.rs
+++ b/screenpipe-audio/src/lib.rs
@@ -1,8 +1,9 @@
-mod audio;
mod core;
mod multilingual;
mod pcm_decode;
mod stt;
-pub use audio::list_audio_devices;
-pub use core::{continuous_audio_capture, save_audio_to_file, ControlMessage};
+pub use core::{
+ continuous_audio_capture, list_audio_devices, parse_device_spec, save_audio_to_file,
+ AudioDevice, ControlMessage, DeviceSpec,
+};
diff --git a/screenpipe-audio/src/multilingual.rs b/screenpipe-audio/src/multilingual.rs
index e3a7c4d18..78f3c5172 100644
--- a/screenpipe-audio/src/multilingual.rs
+++ b/screenpipe-audio/src/multilingual.rs
@@ -137,5 +137,6 @@ pub fn detect_language(
info!("{language}: {p}")
}
let language = super::stt::token_id(tokenizer, &format!("<|{}|>", probs[0].0 .0))?;
+ info!("detected language: {:?}", probs[0].0);
Ok(language)
}
diff --git a/screenpipe-audio/src/stt.rs b/screenpipe-audio/src/stt.rs
index e8fcd485c..65303fdba 100644
--- a/screenpipe-audio/src/stt.rs
+++ b/screenpipe-audio/src/stt.rs
@@ -1,5 +1,5 @@
use anyhow::{Error as E, Result};
-use candle::{Device, IndexOp, Tensor};
+use candle::{Device, IndexOp, Tensor, D};
use candle_nn::ops::softmax;
use hf_hub::{api::sync::Api, Repo, RepoType};
use log::{error, info};
@@ -11,16 +11,13 @@ use rubato::{
Resampler, SincFixedIn, SincInterpolationParameters, SincInterpolationType, WindowFunction,
};
-use crate::pcm_decode::pcm_decode;
-
-// TODO: improve model loading strategy
+use crate::{multilingual, pcm_decode::pcm_decode};
pub enum Model {
Normal(m::model::Whisper),
Quantized(m::quantized_model::Whisper),
}
-// Maybe we should use some traits rather than doing the dispatch for all these.
impl Model {
pub fn config(&self) -> &Config {
match self {
@@ -56,7 +53,6 @@ impl Model {
}
}
-#[allow(dead_code)]
#[derive(Debug, Clone)]
struct DecodingResult {
tokens: Vec<u32>,
@@ -67,7 +63,6 @@ struct DecodingResult {
compression_ratio: f64,
}
-#[allow(dead_code)]
#[derive(Debug, Clone)]
struct Segment {
start: f64,
@@ -105,8 +100,6 @@ impl Decoder {
verbose: bool,
) -> Result<Self> {
let no_timestamps_token = token_id(&tokenizer, m::NO_TIMESTAMPS_TOKEN)?;
- // Suppress the notimestamps token when in timestamps mode.
- // https://github.com/openai/whisper/blob/e8622f9afc4eba139bf796c210f5c01081000472/whisper/decoding.py#L452
let suppress_tokens: Vec<f32> = (0..model.config().vocab_size as u32)
.map(|i| {
if model.config().suppress_tokens.contains(&i)
@@ -155,7 +148,6 @@ impl Decoder {
info!("audio features: {:?}", audio_features.dims());
}
let sample_len = model.config().max_target_positions / 2;
- let mut sum_logprob = 0f64;
let mut no_speech_prob = f64::NAN;
let mut tokens = vec![self.sot_token];
if let Some(language_token) = self.language_token {
@@ -168,16 +160,15 @@ impl Decoder {
if !self.timestamps {
tokens.push(self.no_timestamps_token);
}
+
+ let mut sum_logprob = 0f64;
+ let mut last_token_was_timestamp = false;
+
for i in 0..sample_len {
let tokens_t = Tensor::new(tokens.as_slice(), mel.device())?;
-
- // The model expects a batch dim but this inference loop does not handle
- // it so we add it at this point.
let tokens_t = tokens_t.unsqueeze(0)?;
let ys = model.decoder_forward(&tokens_t, &audio_features, i == 0)?;
- // Extract the no speech probability on the first iteration by looking at the first
- // token logits and the probability for the according token.
if i == 0 {
let logits = model.decoder_final_linear(&ys.i(..1)?)?.i(0)?.i(0)?;
no_speech_prob = softmax(&logits, 0)?
@@ -190,14 +181,16 @@ impl Decoder {
.decoder_final_linear(&ys.i((..1, seq_len - 1..))?)?
.i(0)?
.i(0)?;
- // TODO: Besides suppress tokens, we should apply the heuristics from
- // ApplyTimestampRules, i.e.:
- // - Timestamps come in pairs, except before EOT.
- // - Timestamps should be non-decreasing.
- // - If the sum of the probabilities of timestamps is higher than any other tokens,
- // only consider timestamps when sampling.
- // https://github.com/openai/whisper/blob/e8622f9afc4eba139bf796c210f5c01081000472/whisper/decoding.py#L439
+
let logits = logits.broadcast_add(&self.suppress_tokens)?;
+
+ let logits = if last_token_was_timestamp {
+ let mask = Tensor::zeros_like(&logits)?;
+ let eot_mask = mask.get(self.eot_token as usize)?;
+ logits.broadcast_add(&eot_mask)?
+ } else {
+ logits
+ };
let next_token = if t > 0f64 {
let prs = softmax(&(&logits / t)?, 0)?;
let logits_v: Vec<f32> = prs.to_vec1()?;
@@ -212,15 +205,21 @@ impl Decoder {
.map(|(i, _)| i as u32)
.unwrap()
};
+
tokens.push(next_token);
let prob = softmax(&logits, candle::D::Minus1)?
.i(next_token as usize)?
.to_scalar::<f32>()? as f64;
+
+ sum_logprob += prob.ln();
+
if next_token == self.eot_token || tokens.len() > model.config().max_target_positions {
break;
}
- sum_logprob += prob.ln();
+
+ last_token_was_timestamp = next_token > self.no_timestamps_token;
}
+
let text = self.tokenizer.decode(&tokens, true).map_err(E::msg)?;
let avg_logprob = sum_logprob / tokens.len() as f64;
@@ -240,7 +239,6 @@ impl Decoder {
if i == m::TEMPERATURES.len() - 1 {
return dr;
}
- // On errors, we try again with a different temperature.
match dr {
Ok(dr) => {
let needs_fallback = dr.compression_ratio > m::COMPRESSION_RATIO_THRESHOLD
@@ -290,7 +288,6 @@ impl Decoder {
if token == self.sot_token || token == self.eot_token {
continue;
}
- // The no_timestamp_token is the last before the timestamp ones.
if token > self.no_timestamps_token {
let timestamp_s = (token - self.no_timestamps_token + 1) as f32 / 50.;
if !tokens_to_decode.is_empty() {
@@ -348,7 +345,6 @@ enum Task {
pub fn stt(input: &str) -> Result<String> {
info!("Starting speech to text");
- // ! hack assuming device on 0 and that everyone wants to use AI accelerator
let device = Device::new_metal(0).unwrap_or(Device::new_cuda(0).unwrap_or(Device::Cpu));
info!("device = {:?}", device);
let (default_model, default_revision) = ("lmz/candle-whisper", "main");
@@ -381,7 +377,6 @@ pub fn stt(input: &str) -> Result<String> {
<byteorder::LittleEndian as byteorder::ByteOrder>::read_f32_into(mel_bytes, &mut mel_filters);
let (mut pcm_data, sample_rate) = pcm_decode(input)?;
- // Resample if necessary
if sample_rate != m::SAMPLE_RATE as u32 {
info!(
"Resampling from {} Hz to {} Hz",
@@ -405,26 +400,22 @@ pub fn stt(input: &str) -> Result<String> {
weights_filename,
&device,
)?;
- let model = Model::Quantized(m::quantized_model::Whisper::load(&vb, config)?);
- // info!("detecting language");
- // TODO: disabled seems slow as fuck
- // let language_token = Some(multilingual::detect_language(&mut model, &tokenizer, &mel)?);
- // info!("detected language: {:?}", language_token);
- info!("Creating decoder");
+ let mut model = Model::Quantized(m::quantized_model::Whisper::load(&vb, config)?);
+ let language_token = Some(multilingual::detect_language(&mut model, &tokenizer, &mel)?);
+ // info!("Creating decoder");
let mut dc = Decoder::new(
model,
tokenizer,
42,
&device,
- // language_token,
- None,
+ language_token,
Some(Task::Transcribe),
- false,
+ true,
false,
)?;
info!("Decoding...");
let segments = dc.run(&mel)?;
- info!("Decoding done {:?}", segments);
+ // info!("Decoding done {:?}", segments);
Ok(segments
.iter()
.map(|s| s.dr.text.clone())
@@ -433,7 +424,6 @@ pub fn stt(input: &str) -> Result<String> {
}
fn resample(input: Vec<f32>, from_sample_rate: u32, to_sample_rate: u32) -> Result<Vec<f32>> {
- info!("Resampling from {} to {}", from_sample_rate, to_sample_rate);
let params = SincInterpolationParameters {
sinc_len: 256,
f_cutoff: 0.95,
diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rs
index 05551ac67..29f55af29 100644
--- a/screenpipe-server/src/bin/screenpipe-server.rs
+++ b/screenpipe-server/src/bin/screenpipe-server.rs
@@ -7,7 +7,7 @@ use std::{
use clap::Parser;
use log::{info, LevelFilter};
-use screenpipe_audio::list_audio_devices;
+use screenpipe_audio::{list_audio_devices, parse_device_spec};
use screenpipe_server::{start_continuous_recording, DatabaseManager, ResourceMonitor, Server}; // Import the list_audio_devices function
#[derive(Parser)]
@@ -66,6 +66,8 @@ async fn main() -> anyhow::Result<()> {
return Ok(());
}
+ 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:");
@@ -74,10 +76,27 @@ async fn main() -> anyhow::Result<()> {
}
eprintln!("\nPlease specify one or more devices with:");
eprintln!(
- " {} --audio-device \"Device Name\" [--audio-device \"Another Device\"]",
+ " {} --audio-device \"Device Name (input)\" [--audio-device \"Another Device (output)\"]",
std::env::args().next().unwrap()
);
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);
+ }
+ });
+
+ cli.audio_device.iter().for_each(|d| {
+ audio_devices.push(Arc::new(
+ parse_device_spec(d).expect("Failed to parse audio device specification"),
+ ))
+ });
}
ResourceMonitor::new(cli.memory_threshold, cli.runtime_threshold)
@@ -108,10 +127,7 @@ async fn main() -> anyhow::Result<()> {
audio_chunk_duration,
control_rx,
!cli.disable_audio,
- cli.audio_device
- .iter()
- .map(|d| Arc::new(d.to_string()))
- .collect(),
+ audio_devices,
)
.await
}
diff --git a/screenpipe-server/src/core.rs b/screenpipe-server/src/core.rs
index 190c28ba8..7daafd4e2 100644
--- a/screenpipe-server/src/core.rs
+++ b/screenpipe-server/src/core.rs
@@ -3,7 +3,7 @@ use anyhow::Result;
use chrono::Utc;
use log::{debug, error, info};
use screenpipe_audio::{
- continuous_audio_capture, save_audio_to_file, ControlMessage as AudioControlMessage,
+ continuous_audio_capture, save_audio_to_file, ControlMessage as AudioControlMessage, DeviceSpec,
};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{self, Receiver};
@@ -24,7 +24,7 @@ pub async fn start_continuous_recording(
audio_chunk_duration: Duration,
control_rx: Receiver<RecorderControl>,
enable_audio: bool,
- audio_devices: Vec<Arc<String>>,
+ audio_devices: Vec<Arc<DeviceSpec>>,
) -> Result<()> {
info!("Starting continuous recording");
if !enable_audio {
@@ -125,28 +125,35 @@ async fn record_audio(
output_path: Arc<String>,
chunk_duration: Duration,
is_running: Arc<AtomicBool>,
- devices: Vec<Arc<String>>,
+ devices: Vec<Arc<DeviceSpec>>,
) -> Result<()> {
let mut handles = vec![];
- for device_name in devices {
+ for device_spec in devices {
let db_clone = Arc::clone(&db);
let output_path_clone = Arc::clone(&output_path);
let is_running_clone = Arc::clone(&is_running);
- let device_name_clone = Arc::clone(&device_name);
+ 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 audio_thread = thread::spawn(move || {
- info!("Starting audio capture thread for device: {}", device_name);
+ info!(
+ "Starting audio capture thread for device: {}",
+ &device_spec_clone
+ );
if let Err(e) = continuous_audio_capture(
- Some(device_name.to_string()),
+ device_spec_clone.as_ref(),
audio_control_rx,
audio_result_tx,
chunk_duration,
) {
- error!("Audio capture failed for device {}: {}", device_name, e);
+ error!(
+ "Audio capture failed for device {}: {}",
+ device_spec_clone, e
+ );
}
});
@@ -155,11 +162,11 @@ async fn record_audio(
Ok(result) => {
let time = Utc::now();
let file_path =
- format!("{}/{}_{}.wav", output_path_clone, device_name_clone, time);
+ 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_name_clone, e
+ device_spec, e
);
continue;
}
@@ -172,18 +179,18 @@ async fn record_audio(
{
error!(
"Failed to insert audio transcription for device {}: {}",
- device_name_clone, e
+ device_spec, e
);
} else {
debug!(
"Inserted audio transcription for chunk {} from device {}",
- audio_chunk_id, device_name_clone
+ audio_chunk_id, device_spec
);
}
}
Err(e) => error!(
"Failed to insert audio chunk for device {}: {}",
- device_name_clone, e
+ device_spec, e
),
}
}
@@ -191,7 +198,7 @@ async fn record_audio(
Err(e) => {
error!(
"Failed to receive audio chunk for device {}: {}",
- device_name_clone, e
+ device_spec, e
);
break;
}