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

Add shortcut to toggle audio recording and REST API (#1114)

neo773d193a5af6f31
diff --git a/Cargo.toml b/Cargo.toml
index fd00b38a9..a69c66c0e 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -36,6 +36,7 @@ tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }
tracing-appender = { version = "0.2.3" }
tokio = { version = "1.15", features = ["full", "tracing"] }
crossbeam = "0.8.4"
+dashmap = "6.1.0"
image = "0.25"
reqwest = { version = "0.11", features = ["blocking", "multipart", "json"] }
criterion = { version = "0.5.1", features = ["async_tokio"] }
diff --git a/screenpipe-app-tauri/app/page.tsx b/screenpipe-app-tauri/app/page.tsx
index 533d94c96..4d525570c 100644
--- a/screenpipe-app-tauri/app/page.tsx
+++ b/screenpipe-app-tauri/app/page.tsx
@@ -1,7 +1,7 @@
"use client";
import { Settings } from "@/components/settings";
-import { useSettings } from "@/lib/hooks/use-settings";
+import { getStore, useSettings } from "@/lib/hooks/use-settings";
import {
Card,
CardContent,
@@ -38,8 +38,15 @@ export default function Home() {
const posthog = usePostHog();
const { toast } = useToast();
const { showOnboarding, setShowOnboarding } = useOnboarding();
+ const isProcessingRef = React.useRef(false);
useEffect(() => {
+ const getAudioDevices = async () => {
+ const store = await getStore();
+ const devices = (await store.get("audioDevices")) as string[];
+ return devices;
+ };
+
const unlisten = Promise.all([
listen("shortcut-start-recording", async () => {
await invoke("spawn_screenpipe");
@@ -78,20 +85,64 @@ export default function Home() {
relaunch();
}),
- listen<string>('open-pipe', async (event) => {
+ listen<string>("open-pipe", async (event) => {
const pipeId = event.payload;
const pipeApi = new PipeApi();
const pipeList = await pipeApi.listPipes();
- const pipe = pipeList.find(p => p.id === pipeId);
+ const pipe = pipeList.find((p) => p.id === pipeId);
if (pipe) {
await invoke("open_pipe_window", {
port: pipe.port,
title: pipe.id,
});
}
- })
+ }),
+ listen("shortcut-start-audio", async () => {
+ if (isProcessingRef.current) return;
+ isProcessingRef.current = true;
+ try {
+ const devices = await getAudioDevices();
+ const pipeApi = new PipeApi();
+ console.log("audio-devices", devices);
+ await Promise.all(devices.map(device => pipeApi.startAudio(device)));
+ toast({
+ title: "audio started",
+ description: "audio has been started",
+ });
+ } catch (error) {
+ console.error("error starting audio:", error);
+ toast({
+ title: "error starting audio",
+ description: error instanceof Error ? error.message : "unknown error occurred",
+ variant: "destructive",
+ });
+ } finally {
+ isProcessingRef.current = false;
+ }
+ }),
+
+ listen("shortcut-stop-audio", async (event) => {
+ try {
+ const devices = await getAudioDevices();
+ const pipeApi = new PipeApi();
+ devices.forEach((device) => {
+ pipeApi.stopAudio(device);
+ });
+ toast({
+ title: "audio stopped",
+ description: "audio has been stopped",
+ });
+ } catch (error) {
+ console.error("error stopping audio:", error);
+ toast({
+ title: "error stopping audio",
+ description: error instanceof Error ? error.message : "unknown error occurred",
+ variant: "destructive",
+ });
+ }
+ }),
]);
return () => {
diff --git a/screenpipe-app-tauri/components/settings/shortcut-row.tsx b/screenpipe-app-tauri/components/settings/shortcut-row.tsx
index 4cf99a51e..682da4529 100644
--- a/screenpipe-app-tauri/components/settings/shortcut-row.tsx
+++ b/screenpipe-app-tauri/components/settings/shortcut-row.tsx
@@ -89,6 +89,8 @@ const ShortcutRow = ({
showScreenpipeShortcut: string;
startRecordingShortcut: string;
stopRecordingShortcut: string;
+ startAudioShortcut: string;
+ stopAudioShortcut: string;
profileShortcuts: Record<string, string>;
pipeShortcuts: Record<string, string>;
}) => {
@@ -96,6 +98,8 @@ const ShortcutRow = ({
showShortcut: updatedShortcuts.showScreenpipeShortcut,
startShortcut: updatedShortcuts.startRecordingShortcut,
stopShortcut: updatedShortcuts.stopRecordingShortcut,
+ startAudioShortcut: updatedShortcuts.startAudioShortcut,
+ stopAudioShortcut: updatedShortcuts.stopAudioShortcut,
profileShortcuts: updatedShortcuts.profileShortcuts,
pipeShortcuts: updatedShortcuts.pipeShortcuts,
});
@@ -105,6 +109,8 @@ const ShortcutRow = ({
showShortcut: updatedShortcuts.showScreenpipeShortcut,
startShortcut: updatedShortcuts.startRecordingShortcut,
stopShortcut: updatedShortcuts.stopRecordingShortcut,
+ startAudioShortcut: updatedShortcuts.startAudioShortcut,
+ stopAudioShortcut: updatedShortcuts.stopAudioShortcut,
profileShortcuts: updatedShortcuts.profileShortcuts,
pipeShortcuts: updatedShortcuts.pipeShortcuts,
});
@@ -170,6 +176,7 @@ const ShortcutRow = ({
break;
}
} catch (error) {
+ console.error("error updating shortcut", error);
toast({
title: "error updating shortcut",
description:
diff --git a/screenpipe-app-tauri/components/settings/shortcut-section.tsx b/screenpipe-app-tauri/components/settings/shortcut-section.tsx
index 744fca73f..3a5dd494f 100644
--- a/screenpipe-app-tauri/components/settings/shortcut-section.tsx
+++ b/screenpipe-app-tauri/components/settings/shortcut-section.tsx
@@ -51,6 +51,22 @@ const ShortcutSection = () => {
value={settings.stopRecordingShortcut}
/>
+ <ShortcutRow
+ type="global"
+ shortcut="startAudioShortcut"
+ title="start audio recording"
+ description="global shortcut to start audio recording"
+ value={settings.startAudioShortcut}
+ />
+
+ <ShortcutRow
+ type="global"
+ shortcut="stopAudioShortcut"
+ title="stop audio recording"
+ description="global shortcut to stop audio recording"
+ value={settings.stopAudioShortcut}
+ />
+
{profiles.length > 1 && (
<>
<div className="mt-8 mb-4">
diff --git a/screenpipe-app-tauri/lib/api/index.ts b/screenpipe-app-tauri/lib/api/index.ts
index b8f1aa8bd..04b6d6270 100644
--- a/screenpipe-app-tauri/lib/api/index.ts
+++ b/screenpipe-app-tauri/lib/api/index.ts
@@ -30,7 +30,7 @@ interface PipeShortcut {
export class PipeApi {
private baseUrl: string;
- constructor(baseUrl: string = 'http://localhost:3030') {
+ constructor(baseUrl: string = "http://localhost:3030") {
this.baseUrl = baseUrl;
}
@@ -42,11 +42,69 @@ export class PipeApi {
}
const data: PipeListResponse = await response.json();
if (!data.success) {
- throw new Error('failed to list pipes: api returned success: false');
+ throw new Error("failed to list pipes: api returned success: false");
}
return data.data;
} catch (error) {
- console.error('error listing pipes:', error);
+ console.error("error listing pipes:", error);
+ throw error;
+ }
+ }
+
+ async startAudio(deviceName: string): Promise<void> {
+ try {
+ const type = deviceName.includes("(input)") ? "Input" : "Output";
+ const name = deviceName.replaceAll("(input)", "").replaceAll("(output)", "").trim();
+ const response = await fetch(`${this.baseUrl}/audio/start`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ device_name: name,
+ device_type: type,
+ }),
+ });
+
+ if (!response.ok) {
+ throw new Error(`failed to start audio: ${response.statusText}`);
+ }
+
+ const data = await response.json();
+ if (!data.success) {
+ throw new Error(`failed to start audio: ${data.message}`);
+ }
+ } catch (error) {
+ console.error("error starting audio:", error);
+ throw error;
+ }
+ }
+
+ async stopAudio(deviceName: string): Promise<void> {
+ try {
+ const type = deviceName.includes("(input)") ? "Input" : "Output";
+ const name = deviceName.replaceAll("(input)", "").replaceAll("(output)", "").trim();
+ const response = await fetch(`${this.baseUrl}/audio/stop`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ device_name: name,
+ device_type: type,
+ }),
+ });
+
+ if (!response.ok) {
+ throw new Error(`failed to stop audio: ${response.statusText}`);
+ }
+
+ const data = await response.json();
+ if (!data.success) {
+ throw new Error(`failed to stop audio: ${data.message}`);
+ }
+ } catch (error) {
+ console.error("error stopping audio:", error);
throw error;
}
}
diff --git a/screenpipe-app-tauri/lib/hooks/use-settings.tsx b/screenpipe-app-tauri/lib/hooks/use-settings.tsx
index 476bba3a7..adeca9409 100644
--- a/screenpipe-app-tauri/lib/hooks/use-settings.tsx
+++ b/screenpipe-app-tauri/lib/hooks/use-settings.tsx
@@ -87,6 +87,8 @@ export type Settings = {
showScreenpipeShortcut: string;
startRecordingShortcut: string;
stopRecordingShortcut: string;
+ startAudioShortcut: string;
+ stopAudioShortcut: string;
pipeShortcuts: Record<string, string>;
enableRealtimeAudioTranscription: boolean;
realtimeAudioTranscriptionEngine: string;
@@ -142,6 +144,8 @@ const DEFAULT_SETTINGS: Settings = {
showScreenpipeShortcut: "Super+Alt+S",
startRecordingShortcut: "Super+Alt+R",
stopRecordingShortcut: "Super+Alt+X",
+ startAudioShortcut: "",
+ stopAudioShortcut: "",
pipeShortcuts: {},
enableRealtimeAudioTranscription: false,
realtimeAudioTranscriptionEngine: "whisper-large-v3-turbo",
@@ -220,7 +224,7 @@ let storePromise: Promise<LazyStore> | null = null;
/**
* @warning Do not change autoSave to true, it causes race conditions
*/
-const getStore = async () => {
+export const getStore = async () => {
if (!storePromise) {
storePromise = (async () => {
const dir = await localDataDir();
diff --git a/screenpipe-app-tauri/src-tauri/src/main.rs b/screenpipe-app-tauri/src-tauri/src/main.rs
index 341cd2c3e..df7d272a2 100755
--- a/screenpipe-app-tauri/src-tauri/src/main.rs
+++ b/screenpipe-app-tauri/src-tauri/src/main.rs
@@ -76,6 +76,8 @@ struct ShortcutConfig {
show: String,
start: String,
stop: String,
+ start_audio: String,
+ stop_audio: String,
profile_shortcuts: HashMap<String, String>,
pipe_shortcuts: HashMap<String, String>,
disabled: Vec<String>,
@@ -138,6 +140,14 @@ impl ShortcutConfig {
.get("stopRecordingShortcut")
.and_then(|v| v.as_str().map(String::from))
.unwrap_or_else(|| "Alt+Shift+S".to_string()),
+ start_audio: store
+ .get("startAudioShortcut")
+ .and_then(|v| v.as_str().map(String::from))
+ .unwrap_or_default(),
+ stop_audio: store
+ .get("stopAudioShortcut")
+ .and_then(|v| v.as_str().map(String::from))
+ .unwrap_or_default(),
profile_shortcuts,
pipe_shortcuts,
disabled: store
@@ -183,6 +193,8 @@ async fn update_global_shortcuts(
show_shortcut: String,
start_shortcut: String,
stop_shortcut: String,
+ start_audio_shortcut: String,
+ stop_audio_shortcut: String,
profile_shortcuts: HashMap<String, String>,
pipe_shortcuts: HashMap<String, String>,
) -> Result<(), String> {
@@ -190,6 +202,8 @@ async fn update_global_shortcuts(
show: show_shortcut,
start: start_shortcut,
stop: stop_shortcut,
+ start_audio: start_audio_shortcut,
+ stop_audio: stop_audio_shortcut,
profile_shortcuts,
pipe_shortcuts,
disabled: ShortcutConfig::from_store(&app).await?.disabled,
@@ -262,6 +276,36 @@ async fn apply_shortcuts(app: &AppHandle, config: &ShortcutConfig) -> Result<(),
}
}
+ // Register start audio shortcut
+ register_shortcut(
+ app,
+ &config.start_audio,
+ config.is_disabled("start_audio"),
+ |app| {
+ let store = get_store(app, None).unwrap();
+ store.set("disableAudio", false);
+ store.save().unwrap();
+ let _ = app.emit("shortcut-start-audio", ());
+ info!("start audio shortcut triggered");
+ },
+ )
+ .await?;
+
+ // Register stop audio shortcut
+ register_shortcut(
+ app,
+ &config.stop_audio,
+ config.is_disabled("stop_audio"),
+ |app| {
+ let store = get_store(app, None).unwrap();
+ store.set("disableAudio", true);
+ store.save().unwrap();
+ let _ = app.emit("shortcut-stop-audio", ());
+ info!("stop audio shortcut triggered");
+ },
+ )
+ .await?;
+
info!("pipe_shortcuts: {:?}", config.pipe_shortcuts);
// Register pipe shortcuts
diff --git a/screenpipe-audio/Cargo.toml b/screenpipe-audio/Cargo.toml
index b8ec19844..dd15aaa55 100644
--- a/screenpipe-audio/Cargo.toml
+++ b/screenpipe-audio/Cargo.toml
@@ -65,6 +65,7 @@ screenpipe-core = { path = "../screenpipe-core" }
# crossbeam
crossbeam = { workspace = true }
+dashmap = { workspace = true }
# Directories
dirs = "5.0.1"
diff --git a/screenpipe-audio/benches/record_and_transcribe_benchmark.rs b/screenpipe-audio/benches/record_and_transcribe_benchmark.rs
index b50cb1cdc..ae81a7db3 100644
--- a/screenpipe-audio/benches/record_and_transcribe_benchmark.rs
+++ b/screenpipe-audio/benches/record_and_transcribe_benchmark.rs
@@ -25,6 +25,7 @@ async fn setup_test() -> (
&output_path,
VadSensitivity::High,
vec![],
+ None,
)
.await
.unwrap();
diff --git a/screenpipe-audio/src/bin/screenpipe-audio-forever.rs b/screenpipe-audio/src/bin/screenpipe-audio-forever.rs
index 179bd1af9..073919061 100644
--- a/screenpipe-audio/src/bin/screenpipe-audio-forever.rs
+++ b/screenpipe-audio/src/bin/screenpipe-audio-forever.rs
@@ -95,6 +95,7 @@ async fn main() -> Result<()> {
&PathBuf::from("output.mp4"),
VadSensitivity::Medium,
languages,
+ None,
)
.await?;
diff --git a/screenpipe-audio/src/bin/screenpipe-audio.rs b/screenpipe-audio/src/bin/screenpipe-audio.rs
index 755fe61f6..22c3222b7 100644
--- a/screenpipe-audio/src/bin/screenpipe-audio.rs
+++ b/screenpipe-audio/src/bin/screenpipe-audio.rs
@@ -99,6 +99,7 @@ async fn main() -> Result<()> {
&output_path,
VadSensitivity::Medium,
languages,
+ None
)
.await?;
// Spawn threads for each device
diff --git a/screenpipe-audio/src/core.rs b/screenpipe-audio/src/core.rs
index 46f6d5071..ba0e8e266 100644
--- a/screenpipe-audio/src/core.rs
+++ b/screenpipe-audio/src/core.rs
@@ -50,7 +50,7 @@ impl Default for AudioTranscriptionEngine {
}
}
-#[derive(Clone)]
+#[derive(Clone, Debug)]
pub struct DeviceControl {
pub is_running: bool,
pub is_paused: bool,
diff --git a/screenpipe-audio/src/stt.rs b/screenpipe-audio/src/stt.rs
index 1da8caf98..0a6712382 100644
--- a/screenpipe-audio/src/stt.rs
+++ b/screenpipe-audio/src/stt.rs
@@ -2,7 +2,7 @@ use crate::audio_processing::write_audio_to_file;
use crate::deepgram::transcribe_with_deepgram;
use crate::pyannote::models::{get_or_download_model, PyannoteModel};
use crate::pyannote::segment::SpeechSegment;
-use crate::resample;
+use crate::{resample, DeviceControl};
pub use crate::segments::prepare_segments;
use crate::{
pyannote::{embedding::EmbeddingExtractor, identify::EmbeddingManager},
@@ -24,6 +24,7 @@ use std::{
time::{SystemTime, UNIX_EPOCH},
};
use tokio::sync::Mutex;
+use dashmap::DashMap;
pub fn stt_sync(
audio: &[f32],
@@ -155,6 +156,7 @@ pub async fn create_whisper_channel(
output_path: &PathBuf,
vad_sensitivity: VadSensitivity,
languages: Vec<Language>,
+ audio_devices_control: Option<Arc<DashMap<AudioDevice, DeviceControl>>>,
) -> Result<(
crossbeam::channel::Sender<AudioInput>,
crossbeam::channel::Receiver<TranscriptionResult>,
@@ -202,6 +204,17 @@ pub async fn create_whisper_channel(
recv(input_receiver) -> input_result => {
match input_result {
Ok(mut audio) => {
+ // Check if device should be recording
+ if let Some(control) = audio_devices_control.as_ref().unwrap().get(&audio.device) {
+ if !control.is_running {
+ debug!("Skipping audio processing for stopped device: {}", audio.device);
+ continue;
+ }
+ } else {
+ debug!("Device not found in control list: {}", audio.device);
+ continue;
+ }
+
debug!("Received input from input_receiver");
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
diff --git a/screenpipe-audio/tests/core_tests.rs b/screenpipe-audio/tests/core_tests.rs
index 56971b90e..765e6a62d 100644
--- a/screenpipe-audio/tests/core_tests.rs
+++ b/screenpipe-audio/tests/core_tests.rs
@@ -216,6 +216,7 @@ mod tests {
&output_path_2.clone(),
VadSensitivity::High,
vec![],
+ None,
)
.await
.unwrap();
diff --git a/screenpipe-server/Cargo.toml b/screenpipe-server/Cargo.toml
index 553a8c05c..1b62caf97 100644
--- a/screenpipe-server/Cargo.toml
+++ b/screenpipe-server/Cargo.toml
@@ -92,6 +92,7 @@ reqwest = { workspace = true }
# Concurrency
crossbeam = { workspace = true }
+dashmap = { workspace = true }
# filtering
ndarray = "0.15.6"
diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rs
index ecce67de6..8d2c028b6 100644
--- a/screenpipe-server/src/bin/screenpipe-server.rs
+++ b/screenpipe-server/src/bin/screenpipe-server.rs
@@ -1,7 +1,7 @@
use clap::Parser;
#[allow(unused_imports)]
use colored::Colorize;
-use crossbeam::queue::SegQueue;
+use dashmap::DashMap;
use dirs::home_dir;
use futures::pin_mut;
use port_check::is_local_ipv4_port_free;
@@ -320,8 +320,8 @@ async fn main() -> anyhow::Result<()> {
let mut audio_devices = Vec::new();
- let audio_devices_control = Arc::new(SegQueue::new());
-
+ let audio_devices_control = Arc::new(DashMap::new());
+ let audio_devices_control_recording = audio_devices_control.clone();
let audio_devices_control_server = audio_devices_control.clone();
let mut realtime_audio_devices = Vec::new();
@@ -382,7 +382,7 @@ async fn main() -> anyhow::Result<()> {
// send signal after everything started
tokio::spawn(async move {
tokio::time::sleep(Duration::from_secs(15)).await;
- sender_clone.push((device_clone, device_control));
+ sender_clone.insert(device_clone, device_control);
});
}
}
@@ -484,15 +484,15 @@ async fn main() -> anyhow::Result<()> {
let realtime_vision_sender_clone = realtime_vision_sender.clone();
let vad_engine_clone = vad_engine.clone(); // Clone it here for each iteration
let mut shutdown_rx = shutdown_tx_clone.subscribe();
- let realtime_transcription_sender_clone = realtime_transcription_sender.clone(); // Clone inside the loop
+ let realtime_transcription_sender_clone = realtime_transcription_sender.clone();
let recording_future = start_continuous_recording(
db_clone.clone(),
output_path_clone.clone(),
fps,
- audio_chunk_duration, // use the new setting
+ audio_chunk_duration,
Duration::from_secs(cli.video_chunk_duration),
vision_control_clone.clone(),
- audio_devices_control.clone(),
+ audio_devices_control_recording.clone(),
cli.disable_audio,
Arc::new(cli.audio_transcription_engine.clone().into()),
Arc::new(cli.ocr_engine.clone().into()),
@@ -553,13 +553,16 @@ async fn main() -> anyhow::Result<()> {
}
};
+ let (audio_devices_tx, _) = broadcast::channel(100);
+ let audio_devices_tx_clone = Arc::new(audio_devices_tx.clone());
+
let realtime_vision_sender_clone = realtime_vision_sender_clone.clone();
// TODO: Add SSE stream for realtime audio transcription
let server = Server::new(
db_server,
SocketAddr::from(([127, 0, 0, 1], cli.port)),
vision_control_server_clone,
- audio_devices_control_server,
+ audio_devices_tx_clone,
local_data_dir_clone_2,
pipe_manager.clone(),
cli.disable_vision,
@@ -570,6 +573,46 @@ async fn main() -> anyhow::Result<()> {
realtime_vision_sender_clone.clone(),
);
+ let mut rx = audio_devices_tx.subscribe();
+ let audio_devices_control_for_spawn = audio_devices_control.clone();
+ tokio::spawn(async move {
+ while let Ok((device, control)) = rx.recv().await {
+ if let Err(e) =
+ handle_device_update(&device, control, &audio_devices_control_for_spawn).await
+ {
+ error!("Device update failed: {}", e);
+ continue;
+ }
+ }
+ info!("Device monitoring task completed");
+ });
+
+ async fn handle_device_update(
+ device: &AudioDevice,
+ control: DeviceControl,
+ devices_control: &DashMap<AudioDevice, DeviceControl>,
+ ) -> anyhow::Result<()> {
+ match list_audio_devices().await {
+ Ok(available_devices) => {
+ if !available_devices.contains(&device) {
+ return Err(anyhow::anyhow!(
+ "attempted to control non-existent device: {}",
+ device.name
+ ));
+ }
+
+ // Update the device state
+ devices_control.insert(device.clone(), control.clone());
+ info!(
+ "Device state changed: {} - running: {}",
+ device.name, control.is_running
+ );
+ Ok(())
+ }
+ Err(e) => Err(anyhow::anyhow!("failed to list audio devices: {}", e)),
+ }
+ }
+
// print screenpipe in gradient
println!("\n\n{}", DISPLAY.truecolor(147, 112, 219).bold());
println!(
diff --git a/screenpipe-server/src/core.rs b/screenpipe-server/src/core.rs
index 87cedd5d6..5e02357b1 100644
--- a/screenpipe-server/src/core.rs
+++ b/screenpipe-server/src/core.rs
@@ -2,7 +2,7 @@ use crate::cli::{CliVadEngine, CliVadSensitivity};
use crate::db_types::Speaker;
use crate::{DatabaseManager, VideoCapture};
use anyhow::Result;
-use crossbeam::queue::SegQueue;
+use dashmap::DashMap;
use futures::future::join_all;
use log::{debug, error, info, warn};
use screenpipe_audio::realtime::RealtimeTranscriptionEvent;
@@ -16,7 +16,7 @@ use screenpipe_core::pii_removal::remove_pii;
use screenpipe_core::Language;
use screenpipe_vision::core::{RealtimeVisionEvent, WindowOcr};
use screenpipe_vision::OcrEngine;
-use std::collections::HashMap;
+use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
@@ -32,7 +32,7 @@ pub async fn start_continuous_recording(
audio_chunk_duration: Duration,
video_chunk_duration: Duration,
vision_control: Arc<AtomicBool>,
- audio_devices_control: Arc<SegQueue<(AudioDevice, DeviceControl)>>,
+ audio_devices_control: Arc<DashMap<AudioDevice, DeviceControl>>,
audio_disabled: bool,
audio_transcription_engine: Arc<AudioTranscriptionEngine>,
ocr_engine: Arc<OcrEngine>,
@@ -120,6 +120,7 @@ pub async fn start_continuous_recording(
&PathBuf::from(output_path.as_ref()),
VadSensitivity::from(vad_sensitivity),
languages.clone(),
+ Some(audio_devices_control.clone()),
)
.await?
};
@@ -292,7 +293,7 @@ async fn record_audio(
chunk_duration: Duration,
whisper_sender: crossbeam::channel::Sender<AudioInput>,
whisper_receiver: crossbeam::channel::Receiver<TranscriptionResult>,
- audio_devices_control: Arc<SegQueue<(AudioDevice, DeviceControl)>>,
+ audio_devices_control: Arc<DashMap<AudioDevice, DeviceControl>>,
audio_transcription_engine: Arc<AudioTranscriptionEngine>,
realtime_audio_enabled: bool,
realtime_audio_devices: Vec<Arc<AudioDevice>>,
@@ -306,16 +307,27 @@ async fn record_audio(
let mut previous_transcript_id: Option<i64> = None;
let realtime_transcription_sender_clone = realtime_transcription_sender.clone();
loop {
- while let Some((audio_device, device_control)) = audio_devices_control.pop() {
- debug!("Received audio device: {}", &audio_device);
+ // Iterate over DashMap entries and process each device
+ for entry in audio_devices_control.iter() {
+ let audio_device = entry.key().clone();
+ let device_control = entry.value().clone();
let device_id = audio_device.to_string();
+ // Skip if we're already handling this device
+ if handles.contains_key(&device_id) {
+ continue;
+ }
+
+ info!("Received audio 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.abort();
info!("Stopped thread for device {}", &audio_device);
}
+ // Remove from DashMap
+ audio_devices_control.remove(&audio_device);
continue;
}
diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rs
index 6eb866ba1..920d6e77f 100644
--- a/screenpipe-server/src/server.rs
+++ b/screenpipe-server/src/server.rs
@@ -5,7 +5,6 @@ use axum::{
routing::{get, post},
serve, Router,
};
-use crossbeam::queue::SegQueue;
use futures::{
future::{try_join, try_join_all},
Stream,
@@ -46,7 +45,7 @@ use std::{
time::Duration,
};
-use tokio::net::TcpListener;
+use tokio::{net::TcpListener, sync::broadcast};
use tower_http::{cors::Any, trace::TraceLayer};
use tower_http::{cors::CorsLayer, trace::DefaultMakeSpan};
@@ -61,7 +60,7 @@ use std::str::FromStr;
pub struct AppState {
pub db: Arc<DatabaseManager>,
pub vision_control: Arc<AtomicBool>,
- pub audio_devices_control: Arc<SegQueue<(AudioDevice, DeviceControl)>>,
+ pub audio_devices_tx: Arc<broadcast::Sender<(AudioDevice, DeviceControl)>>,
pub devices_status: HashMap<AudioDevice, DeviceControl>,
pub app_start_time: DateTime<Utc>,
pub screenpipe_dir: PathBuf,
@@ -800,7 +799,7 @@ pub struct Server {
db: Arc<DatabaseManager>,
addr: SocketAddr,
vision_control: Arc<AtomicBool>,
- audio_devices_control: Arc<SegQueue<(AudioDevice, DeviceControl)>>,
+ audio_devices_tx: Arc<tokio::sync::broadcast::Sender<(AudioDevice, DeviceControl)>>,
screenpipe_dir: PathBuf,
pipe_manager: Arc<PipeManager>,
vision_disabled: bool,
@@ -817,7 +816,7 @@ impl Server {
db: Arc<DatabaseManager>,
addr: SocketAddr,
vision_control: Arc<AtomicBool>,
- audio_devices_control: Arc<SegQueue<(AudioDevice, DeviceControl)>>,
+ audio_devices_tx: Arc<tokio::sync::broadcast::Sender<(AudioDevice, DeviceControl)>>,
screenpipe_dir: PathBuf,
pipe_manager: Arc<PipeManager>,
vision_disabled: bool,
@@ -831,7 +830,7 @@ impl Server {
db,
addr,
vision_control,
- audio_devices_control,
+ audio_devices_tx,
screenpipe_dir,
pipe_manager,
vision_disabled,
@@ -855,7 +854,7 @@ impl Server {
let app_state = Arc::new(AppState {
db: self.db.clone(),
vision_control: self.vision_control,
- audio_devices_control: self.audio_devices_control,
+ audio_devices_tx: self.audio_devices_tx,
devices_status: device_status,
app_start_time: Utc::now(),
screenpipe_dir: self.screenpipe_dir.clone(),
@@ -1611,6 +1610,98 @@ async fn sse_transcription_handler(
))
}
+
+#[derive(Deserialize)]
+pub struct AudioDeviceControlRequest {
+ device_name: String,
+ #[serde(default)]
+ device_type: Option<DeviceType>,
+}
+
+#[derive(Serialize)]
+pub struct AudioDeviceControlResponse {
+ success: bool,
+ message: String,
+}
+
+// Add these new handler functions before create_router()
+async fn start_audio_device(
+ State(state): State<Arc<AppState>>,
+ Json(payload): Json<AudioDeviceControlRequest>,
+) -> Result<JsonResponse<AudioDeviceControlResponse>, (StatusCode, JsonResponse<Value>)> {
+ let device = AudioDevice {
+ name: payload.device_name.clone(),
+ device_type: payload.device_type.unwrap_or(DeviceType::Input),
+ };
+
+ // Validate device exists
+ let available_devices = list_audio_devices().await.map_err(|e| {
+ (StatusCode::INTERNAL_SERVER_ERROR,
+ JsonResponse(json!({
+ "error": format!("failed to list audio devices: {}", e),
+ "success": false
+ })))
+ })?;
+
+ if !available_devices.contains(&device) {
+ return Err((StatusCode::BAD_REQUEST,
+ JsonResponse(json!({
+ "error": format!("device not found: {}", device.name),
+ "success": false
+ }))));
+ }
+
+ let control = DeviceControl {
+ is_running: true,
+ is_paused: false
+ };
+
+ let _ = state.audio_devices_tx.send((device.clone(), control));
+
+ Ok(JsonResponse(AudioDeviceControlResponse {
+ success: true,
+ message: format!("started audio device: {}", device.name),
+ }))
+}
+
+async fn stop_audio_device(
+ State(state): State<Arc<AppState>>,
+ Json(payload): Json<AudioDeviceControlRequest>,
+) -> Result<JsonResponse<AudioDeviceControlResponse>, (StatusCode, JsonResponse<Value>)> {
+ let device = AudioDevice {
+ name: payload.device_name.clone(),
+ device_type: payload.device_type.unwrap_or(DeviceType::Input),
+ };
+
+ // Validate device exists
+ let available_devices = list_audio_devices().await.map_err(|e| {
+ (StatusCode::INTERNAL_SERVER_ERROR,
+ JsonResponse(json!({
+ "error": format!("failed to list audio devices: {}", e),
+ "success": false
+ })))
+ })?;
+
+ if !available_devices.contains(&device) {
+ return Err((StatusCode::BAD_REQUEST,
+ JsonResponse(json!({
+ "error": format!("device not found: {}", device.name),
+ "success": false
+ }))));
+ }
+
+ let _ = state.audio_devices_tx.send((device.clone(), DeviceControl {
+ is_running: false,
+ is_paused: false,
+ }));
+
+ Ok(JsonResponse(AudioDeviceControlResponse {
+ success: true,
+ message: format!("stopped audio device: {}", device.name),
+ }))
+}
+
+
#[derive(Deserialize)]
struct VisionSSEQuery {
images: Option<bool>,
@@ -1657,6 +1748,7 @@ async fn sse_vision_handler(
.interval(Duration::from_secs(1))
.text("keep-alive-text"),
))
+
}
pub fn create_router() -> Router<Arc<AppState>> {
@@ -1701,6 +1793,8 @@ pub fn create_router() -> Router<Arc<AppState>> {
.route("/experimental/frames/merge", post(merge_frames_handler))
.route("/experimental/validate/media", get(validate_media_handler))
.route("/sse/transcriptions", get(sse_transcription_handler))
+ .route("/audio/start", post(start_audio_device))
+ .route("/audio/stop", post(stop_audio_device))
.route("/sse/vision", get(sse_vision_handler))
.layer(cors);
@@ -1916,6 +2010,13 @@ curl 'http://localhost:3030/search?offset=0&limit=10&start_time=2024-08-12T04%3A
+
+
+
+
+
+
+
# First, search for Rust-related content
curl "http://localhost:3030/search?q=debug&limit=5&offset=0&content_type=ocr"
@@ -1925,6 +2026,8 @@ curl -X POST "http://localhost:3030/tags/vision/626" \
-d '{"tags": ["debug"]}'
+
+
# List all pipes
curl "http://localhost:3030/pipes/list" | jq
@@ -1952,6 +2055,7 @@ curl -X POST "http://localhost:3030/pipes/enable" \
-d '{"pipe_id": "pipe-stream-ocr-text"}' | jq
+
curl -X POST "http://localhost:3030/pipes/enable" \
-H "Content-Type: application/json" \
-d '{"pipe_id": "pipe-security-check"}' | jq
@@ -1974,6 +2078,8 @@ curl -X POST "http://localhost:3030/pipes/update" \
+
+
# Basic search with min_length and max_length
curl "http://localhost:3030/search?q=test&limit=10&offset=0&min_length=5&max_length=50" | jq
diff --git a/screenpipe-server/tests/endpoint_test.rs b/screenpipe-server/tests/endpoint_test.rs
index af6825867..041d76e28 100644
--- a/screenpipe-server/tests/endpoint_test.rs
+++ b/screenpipe-server/tests/endpoint_test.rs
@@ -34,7 +34,7 @@ mod tests {
let app_state = Arc::new(AppState {
db: db.clone(),
vision_control: Arc::new(AtomicBool::new(false)),
- audio_devices_control: Arc::new(SegQueue::new()),
+ audio_devices_tx: Arc::new(tokio::sync::broadcast::channel(1000).0),
devices_status: HashMap::new(),
app_start_time: Utc::now(),
screenpipe_dir: PathBuf::from(""),
diff --git a/screenpipe-server/tests/tags_test.rs b/screenpipe-server/tests/tags_test.rs
index 69d6f05ee..e36854389 100644
--- a/screenpipe-server/tests/tags_test.rs
+++ b/screenpipe-server/tests/tags_test.rs
@@ -31,7 +31,7 @@ async fn setup_test_app() -> (Router, Arc<AppState>) {
vision_disabled: false,
audio_disabled: false,
vision_control: Arc::new(AtomicBool::new(false)),
- audio_devices_control: Arc::new(SegQueue::new()),
+ audio_devices_tx: Arc::new(tokio::sync::broadcast::channel(1000).0),
devices_status: HashMap::new(),
app_start_time: Utc::now(),
screenpipe_dir: PathBuf::from(""),