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: bunch of stuff

Louis Beaumont43efd4fecdd8
diff --git a/screenpipe-audio/src/bin/screenpipe-audio.rs b/screenpipe-audio/src/bin/screenpipe-audio.rs
index 18bb445f5..6e72300f1 100644
--- a/screenpipe-audio/src/bin/screenpipe-audio.rs
+++ b/screenpipe-audio/src/bin/screenpipe-audio.rs
@@ -5,7 +5,7 @@ use screenpipe_audio::create_whisper_channel;
use screenpipe_audio::default_input_device;
use screenpipe_audio::default_output_device;
use screenpipe_audio::list_audio_devices;
-use screenpipe_audio::parse_device_spec;
+use screenpipe_audio::parse_audio_device;
use screenpipe_audio::record_and_transcribe;
use screenpipe_audio::AudioDevice;
use screenpipe_audio::DeviceControl;
@@ -38,6 +38,8 @@ fn print_devices(devices: &[AudioDevice]) {
}
}
+// TODO - kinda bad cli here
+
fn main() -> Result<()> {
use env_logger::Builder;
use log::LevelFilter;
@@ -61,7 +63,7 @@ fn main() -> Result<()> {
} else {
args.audio_device
.iter()
- .map(|d| parse_device_spec(d))
+ .map(|d| parse_audio_device(d))
.collect::<Result<Vec<_>>>()?
};
diff --git a/screenpipe-audio/src/core.rs b/screenpipe-audio/src/core.rs
index b2276e795..ceb9a1fcc 100644
--- a/screenpipe-audio/src/core.rs
+++ b/screenpipe-audio/src/core.rs
@@ -11,99 +11,93 @@ use std::thread;
use std::time::Duration;
use crate::AudioInput;
+use std::io::Write;
+use std::process::{Command, Stdio};
pub struct DeviceControl {
pub is_running: Arc<AtomicBool>,
pub is_paused: Arc<AtomicBool>,
}
-pub struct AudioCaptureResult {
- pub text: String,
+#[derive(Clone, Eq, PartialEq, Hash, Serialize)]
+pub enum DeviceType {
+ Input,
+ Output,
}
-pub enum DeviceSpec {
- Input(Option<String>),
- Output(Option<String>),
+#[derive(Clone, Eq, PartialEq, Hash, Serialize)]
+pub struct AudioDevice {
+ name: String,
+ device_type: DeviceType,
}
-impl DeviceSpec {
+impl AudioDevice {
+ pub fn new(name: String, device_type: DeviceType) -> Self {
+ AudioDevice { name, device_type }
+ }
+
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(
+ let (name, device_type) = if name.to_lowercase().ends_with("(input)") {
+ (
name.trim_end_matches("(input)").trim().to_string(),
- )))
+ DeviceType::Input,
+ )
} else if name.to_lowercase().ends_with("(output)") {
- Ok(DeviceSpec::Output(Some(
+ (
name.trim_end_matches("(output)").trim().to_string(),
- )))
+ DeviceType::Output,
+ )
} else {
- Err(anyhow!(
+ return Err(anyhow!(
"Device type (input/output) not specified in the name"
- ))
- }
+ ));
+ };
+
+ Ok(AudioDevice::new(name, device_type))
}
}
-// impl display for DeviceSpec
-impl fmt::Display for DeviceSpec {
+impl fmt::Display for AudioDevice {
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,
+ "{} ({})",
+ self.name,
+ match self.device_type {
+ DeviceType::Input => "input",
+ DeviceType::Output => "output",
}
- 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)
+// Helper function to create AudioDevice from a name
+pub fn parse_audio_device(name: &str) -> Result<AudioDevice> {
+ AudioDevice::from_name(name)
}
-use std::io::Write;
-use std::process::{Command, Stdio};
-
fn get_device_and_config(
- device_spec: &DeviceSpec,
+ audio_device: &AudioDevice,
) -> Result<(cpal::Device, cpal::SupportedStreamConfig)> {
- let host = match device_spec {
+ let host = match audio_device.device_type {
#[cfg(target_os = "macos")]
- DeviceSpec::Output(_) => cpal::host_from_id(cpal::HostId::ScreenCaptureKit)?,
+ DeviceType::Output => cpal::host_from_id(cpal::HostId::ScreenCaptureKit)?,
_ => cpal::default_host(),
};
- info!("device: {:?}", device_spec.to_string());
+ info!("device: {:?}", audio_device.to_string());
- let audio_device = if device_spec.to_string() == "default" {
+ let audio_device = if audio_device.to_string() == "default" {
host.default_input_device()
} else {
host.input_devices()?.find(|x| {
x.name()
.map(|y| {
- y == device_spec
+ y == audio_device
.to_string()
.replace(" (input)", "")
.replace(" (output)", "")
@@ -118,16 +112,16 @@ fn get_device_and_config(
}
pub fn record_and_transcribe(
- device_spec: &DeviceSpec,
+ audio_device: &AudioDevice,
duration: Duration,
output_path: PathBuf,
whisper_sender: Sender<AudioInput>,
device_control: Arc<DeviceControl>,
) -> Result<PathBuf> {
- let (audio_device, config) = get_device_and_config(device_spec)?;
+ let (cpal_audio_device, config) = get_device_and_config(audio_device)?;
info!(
"Recording audio device: {}, Config: {:?}",
- audio_device.name()?,
+ cpal_audio_device.name()?,
config
);
@@ -144,7 +138,6 @@ pub fn record_and_transcribe(
let output_path_clone = output_path.clone();
let output_path_clone_2 = output_path.clone();
- let device_spec_clone = device_spec.clone();
let start_time = std::time::Instant::now();
@@ -203,7 +196,7 @@ pub fn record_and_transcribe(
let err_fn = |err| error!("An error occurred on the audio stream: {}", err);
let stream = match config.sample_format() {
- cpal::SampleFormat::F32 => audio_device.build_input_stream(
+ cpal::SampleFormat::F32 => cpal_audio_device.build_input_stream(
&config.into(),
move |data: &[f32], _: &_| {
if is_running_clone_4.load(Ordering::Relaxed) {
@@ -249,7 +242,7 @@ pub fn record_and_transcribe(
if let Err(e) = whisper_sender.send(AudioInput {
path: output_path_clone_2.to_str().unwrap().to_string(),
- device: device_spec_clone.to_string(),
+ device: audio_device.to_string(),
}) {
error!("Failed to send audio to whisper: {}", e);
}
@@ -258,28 +251,13 @@ pub fn record_and_transcribe(
Ok(output_path_clone_2)
}
-#[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(),
- });
+ devices.push(AudioDevice::new(name, DeviceType::Input));
}
}
@@ -288,10 +266,7 @@ pub fn list_audio_devices() -> Result<Vec<AudioDevice>> {
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: "output".to_string(),
- });
+ devices.push(AudioDevice::new(name, DeviceType::Output));
}
}
}
@@ -300,28 +275,26 @@ 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(),
- });
+ devices.push(AudioDevice::new(name, DeviceType::Output));
}
}
}
Ok(devices)
}
+
// function that return default device to record audio
-pub fn default_input_device() -> Result<DeviceSpec> {
+pub fn default_input_device() -> Result<AudioDevice> {
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()?)))
+ Ok(AudioDevice::new(device.name()?, DeviceType::Input))
}
// ! HACK - yes this quite unintuitive ... but it works ...
// function that return default device to record audio
-pub fn default_output_device() -> Result<DeviceSpec> {
+pub fn default_output_device() -> Result<AudioDevice> {
#[cfg(target_os = "macos")]
{
let host = cpal::host_from_id(cpal::HostId::ScreenCaptureKit)?;
@@ -329,7 +302,7 @@ pub fn default_output_device() -> Result<DeviceSpec> {
.default_input_device()
.ok_or_else(|| anyhow!("No default input device found"))?;
info!("Using display capture device: {}", device.name()?);
- return Ok(DeviceSpec::Output(Some(device.name()?)));
+ return Ok(AudioDevice::new(device.name()?, DeviceType::Output));
}
#[cfg(not(target_os = "macos"))]
@@ -339,6 +312,6 @@ pub fn default_output_device() -> Result<DeviceSpec> {
.default_output_device()
.ok_or_else(|| anyhow!("No default output device found"))?;
info!("Using default output device: {}", device.name()?);
- return Ok(DeviceSpec::Output(Some(device.name()?)));
+ return Ok(AudioDevice::new(device.name()?, DeviceType::Output));
}
}
diff --git a/screenpipe-audio/src/lib.rs b/screenpipe-audio/src/lib.rs
index 411c1f97b..93353b37a 100644
--- a/screenpipe-audio/src/lib.rs
+++ b/screenpipe-audio/src/lib.rs
@@ -3,7 +3,7 @@ mod multilingual;
mod pcm_decode;
mod stt;
pub use core::{
- default_input_device, default_output_device, list_audio_devices, parse_device_spec,
- record_and_transcribe, AudioCaptureResult, AudioDevice, DeviceSpec, DeviceControl
+ default_input_device, default_output_device, list_audio_devices, record_and_transcribe,
+ AudioDevice, DeviceControl, parse_audio_device
};
pub use stt::{create_whisper_channel, stt, AudioInput, TranscriptionResult, WhisperModel};
diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rs
index 6d580c58a..5df1f524c 100644
--- a/screenpipe-server/src/bin/screenpipe-server.rs
+++ b/screenpipe-server/src/bin/screenpipe-server.rs
@@ -7,14 +7,27 @@ use std::{
};
use clap::Parser;
+#[allow(unused_imports)]
use colored::Colorize;
-use log::{info, warn, LevelFilter};
+use log::{debug, info, LevelFilter};
use screenpipe_audio::{
- default_input_device, default_output_device, list_audio_devices, parse_device_spec,
- DeviceControl,
+ default_input_device, default_output_device, list_audio_devices, parse_audio_device,
+ AudioDevice, DeviceControl,
};
-use screenpipe_server::{start_continuous_recording, DatabaseManager, ResourceMonitor, Server}; // Import the list_audio_devices function
+use screenpipe_server::{start_continuous_recording, DatabaseManager, ResourceMonitor, Server};
+
+// keep in mind this is the most important feature ever // TODO: add a pipe and a ⭐️ e.g screen | ⭐️ somehow in ascii ♥️🤓
+const DISPLAY: &str = r"
+ _
+ __________________ ___ ____ ____ (_____ ___
+ / ___/ ___/ ___/ _ \/ _ \/ __ \ / __ \/ / __ \/ _ \
+ (__ / /__/ / / __/ __/ / / / / /_/ / / /_/ / __/
+/____/\___/_/ \___/\___/_/ /_/ / .___/_/ .___/\___/
+ /_/ /_/
+
+";
+
#[derive(Parser)]
#[command(author, version, about, long_about = None)]
struct Cli {
@@ -53,6 +66,10 @@ struct Cli {
/// Data directory
#[arg(long, default_value_t = String::from("./data"))]
data_dir: String,
+
+ /// Enable debug logging for screenpipe modules
+ #[arg(long)]
+ debug: bool,
}
#[tokio::main]
@@ -60,12 +77,17 @@ async fn main() -> anyhow::Result<()> {
// Initialize logging
let cli = Cli::parse();
- env_logger::Builder::new()
+ let mut builder = env_logger::Builder::new();
+ builder
.filter(None, LevelFilter::Info)
.filter_module("tokenizers", LevelFilter::Error)
- .filter_module("rusty_tesseract", LevelFilter::Error)
- .init();
+ .filter_module("rusty_tesseract", LevelFilter::Error);
+
+ if cli.debug {
+ builder.filter_module("screenpipe", LevelFilter::Debug);
+ }
+ builder.init();
// Add warning for Linux and Windows users
#[cfg(any(target_os = "linux", target_os = "windows"))]
{
@@ -81,34 +103,71 @@ async fn main() -> anyhow::Result<()> {
.underline()
);
}
+ let all_audio_devices = list_audio_devices()?;
if cli.list_audio_devices {
- let devices = list_audio_devices()?;
println!("Available audio devices:");
- for (i, device) in devices.iter().enumerate() {
+ for (i, device) in all_audio_devices.iter().enumerate() {
println!(" {}. {}", i + 1, device);
}
return Ok(());
}
let mut audio_devices = Vec::new();
+ let audio_devices_control: Arc<RwLock<HashMap<AudioDevice, Arc<DeviceControl>>>> =
+ Arc::new(RwLock::new(HashMap::new()));
+
+ // Add all available audio devices to the controls
+ for device in &all_audio_devices {
+ let device_control = DeviceControl {
+ is_running: Arc::new(AtomicBool::new(false)),
+ is_paused: Arc::new(AtomicBool::new(false)),
+ };
+ audio_devices_control
+ .write()
+ .unwrap()
+ .insert(device.clone(), Arc::new(device_control));
+ }
if !cli.disable_audio {
if cli.audio_device.is_empty() {
- // Add default input device
+ debug!("Using default devices");
+ // Use default devices
if let Ok(input_device) = default_input_device() {
- audio_devices.push(Arc::new(input_device));
+ audio_devices.push(Arc::new(input_device.clone()));
+ if let Some(control) = audio_devices_control
+ .write()
+ .unwrap()
+ .get_mut(&input_device)
+ {
+ control
+ .is_running
+ .store(true, std::sync::atomic::Ordering::SeqCst);
+ }
}
- // Add default output device
if let Ok(output_device) = default_output_device() {
- audio_devices.push(Arc::new(output_device));
+ audio_devices.push(Arc::new(output_device.clone()));
+ if let Some(control) = audio_devices_control
+ .write()
+ .unwrap()
+ .get_mut(&output_device)
+ {
+ control
+ .is_running
+ .store(true, std::sync::atomic::Ordering::SeqCst);
+ }
}
} 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"),
- ));
+ let device = parse_audio_device(d).expect("Failed to parse audio device");
+ audio_devices.push(Arc::new(device.clone()));
+ if let Some(control) = audio_devices_control.write().unwrap().get_mut(&device) {
+ control
+ .is_running
+ .store(true, std::sync::atomic::Ordering::SeqCst);
+ debug!("running audio device: {}", device.to_string());
+ }
}
}
@@ -139,9 +198,7 @@ async fn main() -> anyhow::Result<()> {
// Channel for controlling the recorder ! TODO RENAME SHIT
let (_control_tx, control_rx) = channel();
- let vision_control = Arc::new(AtomicBool::new(false));
- let audio_devices_control: Arc<RwLock<HashMap<String, Arc<DeviceControl>>>> =
- Arc::new(RwLock::new(HashMap::new()));
+ let vision_control = Arc::new(AtomicBool::new(true));
let vision_control_server_clone = vision_control.clone();
let audio_devices_control_server_clone = audio_devices_control.clone();
@@ -158,7 +215,6 @@ async fn main() -> anyhow::Result<()> {
audio_chunk_duration,
control_rx,
!cli.disable_audio,
- audio_devices,
vision_control,
audio_devices_control,
)
@@ -179,6 +235,23 @@ async fn main() -> anyhow::Result<()> {
// Wait for the server to start
info!("Server started on http://localhost:{}", cli.port);
+ // print screenpipe in gradient
+ println!(
+ "\n\n{}",
+ DISPLAY
+ .truecolor(147, 112, 219)
+ .on_truecolor(255, 255, 255)
+ .bold()
+ );
+ println!(
+ "\n{}",
+ "Extend your human memory with LLM".bright_yellow().italic()
+ );
+ println!(
+ "{}\n\n",
+ "Open source | Runs locally | Developer friendly".bright_green()
+ );
+
// Keep the main thread running
loop {
tokio::time::sleep(Duration::from_secs(1)).await;
diff --git a/screenpipe-server/src/core.rs b/screenpipe-server/src/core.rs
index 25e8cdadf..cc7f3bd7b 100644
--- a/screenpipe-server/src/core.rs
+++ b/screenpipe-server/src/core.rs
@@ -4,8 +4,8 @@ use chrono::Utc;
use crossbeam::channel::{Receiver, Sender};
use log::{debug, error, info};
use screenpipe_audio::{
- create_whisper_channel, record_and_transcribe, AudioInput, DeviceControl, DeviceSpec,
- TranscriptionResult,
+ create_whisper_channel, parse_audio_device, record_and_transcribe, AudioDevice, AudioInput,
+ DeviceControl, TranscriptionResult,
};
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
@@ -24,13 +24,12 @@ pub async fn start_continuous_recording(
output_path: Arc<String>,
fps: f64,
audio_chunk_duration: Duration,
- control_rx: std::sync::mpsc::Receiver<RecorderControl>,
+ full_control: std::sync::mpsc::Receiver<RecorderControl>,
enable_audio: bool,
- audio_devices: Vec<Arc<DeviceSpec>>,
vision_control: Arc<AtomicBool>,
- audio_devices_control: Arc<RwLock<HashMap<String, Arc<DeviceControl>>>>,
+ audio_devices_control: Arc<RwLock<HashMap<AudioDevice, Arc<DeviceControl>>>>,
) -> Result<()> {
- info!("Starting continuous recording");
+ info!("Recording now");
if !enable_audio {
info!("Audio recording disabled");
}
@@ -58,7 +57,6 @@ pub async fn start_continuous_recording(
output_path_audio,
audio_chunk_duration,
is_running_audio,
- audio_devices,
whisper_sender,
whisper_receiver,
Arc::clone(&audio_devices_control),
@@ -72,12 +70,11 @@ pub async fn start_continuous_recording(
// Control loop
tokio::spawn(async move {
- while let Ok(ctrl) = control_rx.recv() {
+ 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);
- break;
}
RecorderControl::Pause => {
control_all_devices(&device_controls_clone, RecorderControl::Pause)
@@ -94,7 +91,7 @@ pub async fn start_continuous_recording(
handle.await??;
}
- info!("Continuous recording stopped");
+ info!("Stopped recording");
Ok(())
}
@@ -139,47 +136,39 @@ async fn record_audio(
output_path: Arc<String>,
chunk_duration: Duration,
is_running: Arc<AtomicBool>,
- devices: Vec<Arc<DeviceSpec>>,
whisper_sender: Sender<AudioInput>,
whisper_receiver: Receiver<TranscriptionResult>,
- device_controls: Arc<RwLock<HashMap<String, Arc<DeviceControl>>>>,
+ device_controls: Arc<RwLock<HashMap<AudioDevice, Arc<DeviceControl>>>>,
) -> Result<()> {
let mut handles = vec![];
- for device_spec in devices {
+ let device_specs: Vec<AudioDevice> = device_controls.read().unwrap().keys().cloned().collect();
+ for device_spec in device_specs {
let db_clone = Arc::clone(&db);
let output_path_clone = Arc::clone(&output_path);
let is_running_clone = Arc::clone(&is_running);
- let device_spec_clone = Arc::clone(&device_spec);
+ // let device_spec_clone = Arc::clone(&device_spec);
let whisper_sender_clone = whisper_sender.clone();
let whisper_receiver_clone = whisper_receiver.clone();
- let device_control = Arc::new(DeviceControl {
- is_running: Arc::new(AtomicBool::new(true)),
- is_paused: Arc::new(AtomicBool::new(false)),
- });
-
- device_controls
- .write()
- .unwrap()
- .insert(device_spec.to_string(), Arc::clone(&device_control));
+ let device_control = Arc::clone(&device_controls.read().unwrap()[&device_spec]);
+ if !device_control.is_running.load(Ordering::SeqCst) {
+ continue;
+ }
let handle = tokio::spawn(async move {
- info!(
- "Starting audio capture thread for device: {}",
- &device_spec_clone
- );
+ info!("Starting audio capture thread for device: {}", &device_spec);
let mut iteration = 0;
while is_running_clone.load(Ordering::SeqCst) {
iteration += 1;
info!(
"Starting iteration {} for device {}",
- iteration, &device_spec_clone
+ iteration, device_spec
);
let recording_thread = thread::spawn({
- let device_spec_clone = Arc::clone(&device_spec_clone);
+ let device_spec = device_spec.clone();
let output_path_clone = Arc::clone(&output_path_clone);
let whisper_sender = whisper_sender_clone.clone();
let device_control_clone = Arc::clone(&device_control);
@@ -188,14 +177,14 @@ async fn record_audio(
let new_file_name = Utc::now().format("%Y-%m-%d_%H-%M-%S").to_string();
let file_path = format!(
"{}/{}_{}.mp3",
- output_path_clone, device_spec_clone, new_file_name
+ output_path_clone, device_spec, new_file_name
);
info!(
"Starting record_and_transcribe for device {} (iteration {})",
- device_spec_clone, iteration
+ device_spec, iteration
);
let result = record_and_transcribe(
- device_spec_clone.as_ref(),
+ &device_spec,
chunk_duration,
file_path.into(),
whisper_sender,
@@ -203,7 +192,7 @@ async fn record_audio(
);
info!(
"Finished record_and_transcribe for device {} (iteration {})",
- device_spec_clone, iteration
+ device_spec, iteration
);
result
}
@@ -214,7 +203,7 @@ async fn record_audio(
Ok(Ok(file_path)) => {
info!(
"Recording complete for device {} (iteration {}): {:?}",
- device_spec_clone, iteration, file_path
+ device_spec, iteration, file_path
);
let whisper_receiver = whisper_receiver_clone.clone();
@@ -223,44 +212,41 @@ async fn record_audio(
Ok(transcription) => {
info!(
"Received transcription for device {} (iteration {})",
- device_spec_clone, iteration
+ device_spec, iteration
);
process_audio_result(&db_clone, transcription).await;
}
Err(e) => error!(
"Failed to receive transcription for device {} (iteration {}): {}",
- device_spec_clone, iteration, e
+ device_spec, iteration, e
),
}
}
Ok(Err(e)) => error!(
"Error in record_and_transcribe for device {} (iteration {}): {}",
- device_spec_clone, iteration, e
+ device_spec, iteration, e
),
Err(e) => error!(
"Thread panicked for device {} (iteration {}): {:?}",
- device_spec_clone, iteration, e
+ device_spec, iteration, e
),
}
if !device_control.is_running.load(Ordering::SeqCst) {
info!(
"Device control signaled stop for device {} after iteration {}",
- device_spec_clone, iteration
+ device_spec, iteration
);
break;
}
info!(
"Finished iteration {} for device {}",
- iteration, &device_spec_clone
+ iteration, &device_spec
);
}
- info!(
- "Exiting audio capture thread for device: {}",
- &device_spec_clone
- );
+ info!("Exiting audio capture thread for device: {}", &device_spec);
});
handles.push(handle);
@@ -309,7 +295,7 @@ async fn process_audio_result(db: &DatabaseManager, result: TranscriptionResult)
}
pub fn control_all_devices(
- device_controls: &Arc<RwLock<HashMap<String, Arc<DeviceControl>>>>,
+ device_controls: &Arc<RwLock<HashMap<AudioDevice, Arc<DeviceControl>>>>,
command: RecorderControl,
) {
let controls = device_controls.read();
diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rs
index a7ad5e6df..1c6d9f7fe 100644
--- a/screenpipe-server/src/server.rs
+++ b/screenpipe-server/src/server.rs
@@ -1,5 +1,5 @@
use axum::{
- extract::{Path, Query, State},
+ extract::{Json as JsonExt, Path, Query, State},
http::StatusCode,
response::Json as JsonResponse,
routing::{get, post},
@@ -22,13 +22,18 @@ use tokio::net::TcpListener;
use tower_http::cors::CorsLayer;
use crate::{ContentType, DatabaseManager, SearchResult};
-use screenpipe_audio::DeviceControl;
+use screenpipe_audio::{AudioDevice, DeviceControl};
// App state
pub(crate) struct AppState {
db: Arc<DatabaseManager>,
vision_control: Arc<AtomicBool>,
- audio_devices_control: Arc<RwLock<HashMap<String, Arc<DeviceControl>>>>,
+ audio_devices_control: Arc<RwLock<HashMap<AudioDevice, Arc<DeviceControl>>>>,
+}
+
+#[derive(Deserialize)]
+struct DeviceRequest {
+ device_id: String,
}
// Request structs
@@ -178,15 +183,27 @@ pub(crate) async fn search(
}))
}
pub(crate) async fn start_device(
- Path(device_id): Path<String>,
State(state): State<Arc<AppState>>,
+ JsonExt(payload): JsonExt<DeviceRequest>,
) -> Result<JsonResponse<DeviceStatus>, (StatusCode, JsonResponse<serde_json::Value>)> {
let device_controls = state.audio_devices_control.read().unwrap();
- if let Some(device_control) = device_controls.get(&device_id) {
+
+ // Create an AudioDevice from the device_id string
+ let audio_device = match AudioDevice::from_name(&payload.device_id) {
+ Ok(device) => device,
+ Err(_) => {
+ return Err((
+ StatusCode::BAD_REQUEST,
+ JsonResponse(json!({"error": "Invalid device ID"})),
+ ))
+ }
+ };
+
+ if let Some(device_control) = device_controls.get(&audio_device) {
device_control.is_paused.store(false, Ordering::SeqCst);
device_control.is_running.store(true, Ordering::SeqCst);
Ok(JsonResponse(DeviceStatus {
- id: device_id,
+ id: payload.device_id,
is_running: true,
}))
} else {
@@ -198,15 +215,25 @@ pub(crate) async fn start_device(
}
pub(crate) async fn stop_device(
- Path(device_id): Path<String>,
State(state): State<Arc<AppState>>,
+ JsonExt(payload): JsonExt<DeviceRequest>,
) -> Result<JsonResponse<DeviceStatus>, (StatusCode, JsonResponse<serde_json::Value>)> {
let device_controls = state.audio_devices_control.read().unwrap();
- if let Some(device_control) = device_controls.get(&device_id) {
+ // Create an AudioDevice from the device_id string
+ let audio_device = match AudioDevice::from_name(&payload.device_id) {
+ Ok(device) => device,
+ Err(_) => {
+ return Err((
+ StatusCode::BAD_REQUEST,
+ JsonResponse(json!({"error": "Invalid device ID"})),
+ ))
+ }
+ };
+ if let Some(device_control) = device_controls.get(&audio_device) {
device_control.is_running.store(false, Ordering::SeqCst);
device_control.is_paused.store(true, Ordering::SeqCst);
Ok(JsonResponse(DeviceStatus {
- id: device_id,
+ id: payload.device_id,
is_running: false,
}))
} else {
@@ -239,13 +266,23 @@ pub(crate) async fn get_recording_status(
}
pub(crate) async fn get_device_status(
- Path(device_id): Path<String>,
State(state): State<Arc<AppState>>,
+ JsonExt(payload): JsonExt<DeviceRequest>,
) -> Result<JsonResponse<DeviceStatus>, (StatusCode, JsonResponse<serde_json::Value>)> {
let device_controls = state.audio_devices_control.read().unwrap();
- if let Some(device_control) = device_controls.get(&device_id) {
+ // Create an AudioDevice from the device_id string
+ let audio_device = match AudioDevice::from_name(&payload.device_id) {
+ Ok(device) => device,
+ Err(_) => {
+ return Err((
+ StatusCode::BAD_REQUEST,
+ JsonResponse(json!({"error": "Invalid device ID"})),
+ ))
+ }
+ };
+ if let Some(device_control) = device_controls.get(&audio_device) {
Ok(JsonResponse(DeviceStatus {
- id: device_id,
+ id: payload.device_id,
is_running: device_control.is_running.load(Ordering::SeqCst),
}))
} else {
@@ -256,6 +293,20 @@ pub(crate) async fn get_device_status(
}
}
+pub(crate) async fn get_devices(
+ State(state): State<Arc<AppState>>,
+) -> JsonResponse<Vec<DeviceStatus>> {
+ let device_controls = state.audio_devices_control.read().unwrap();
+ let devices = device_controls
+ .iter()
+ .map(|(id, _)| DeviceStatus {
+ id: id.to_string(),
+ is_running: false,
+ })
+ .collect();
+ JsonResponse(devices)
+}
+
// Helper functions
fn into_content_item(result: SearchResult) -> ContentItem {
match result {
@@ -280,7 +331,7 @@ pub struct Server {
db: Arc<DatabaseManager>,
addr: SocketAddr,
vision_control: Arc<AtomicBool>,
- audio_devices_control: Arc<RwLock<HashMap<String, Arc<DeviceControl>>>>,
+ audio_devices_control: Arc<RwLock<HashMap<AudioDevice, Arc<DeviceControl>>>>,
}
impl Server {
@@ -288,7 +339,7 @@ impl Server {
db: Arc<DatabaseManager>,
addr: SocketAddr,
vision_control: Arc<AtomicBool>,
- audio_devices_control: Arc<RwLock<HashMap<String, Arc<DeviceControl>>>>,
+ audio_devices_control: Arc<RwLock<HashMap<AudioDevice, Arc<DeviceControl>>>>,
) -> Self {
Server {
db,
@@ -307,9 +358,10 @@ impl Server {
let app = Router::new()
.route("/search", get(search))
- .route("/device/:id/start", post(start_device))
- .route("/device/:id/stop", post(stop_device))
- .route("/device/:id/status", get(get_device_status))
+ .route("/device/start", post(start_device))
+ .route("/device/stop", post(stop_device))
+ .route("/device/status", post(get_device_status))
+ .route("/device/list", get(get_devices))
.route("/recording/start", post(start_recording))
.route("/recording/stop", post(stop_recording))
.route("/recording/status", get(get_recording_status))
@@ -351,13 +403,16 @@ impl Server {
// # curl "http://localhost:3030/search?limit=5&offset=0"
// # 7. Start a device
-// # curl -X POST "http://localhost:3030/device/device1/start"
+// # curl -X POST "http://localhost:3030/device/start" -H "Content-Type: application/json" -d '{"device_id": "device1"}'
// # 8. Stop a device
-// # curl -X POST "http://localhost:3030/device/device1/stop"
+// # curl -X POST "http://localhost:3030/device/stop" -H "Content-Type: application/json" -d '{"device_id": "device1"}'
// # 9. Get device status
-// # curl "http://localhost:3030/device/device1/status"
+// # curl "http://localhost:3030/device/status" -H "Content-Type: application/json" -d '{"device_id": "device1"}'
+
+// list devices
+// # curl "http://localhost:3030/device/list"
// # 10. Start recording
// # curl -X POST "http://localhost:3030/recording/start"