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

Bump app to v2.0.579

Louis Beaumonta93c97804563
diff --git a/apps/screenpipe-app-tauri/components/settings/recording-settings.tsx b/apps/screenpipe-app-tauri/components/settings/recording-settings.tsx
index 837ba2cd9..eb9960927 100644
--- a/apps/screenpipe-app-tauri/components/settings/recording-settings.tsx
+++ b/apps/screenpipe-app-tauri/components/settings/recording-settings.tsx
@@ -1037,11 +1037,10 @@ Your screen is a pipe. Everything you see, hear, and type flows through it. Scre
</Card>
)}
- {/* Transcription Mode - only for local Whisper engines, hidden when weak hardware + large model */}
+ {/* Transcription Mode - only for local Whisper engines */}
{!settings.disableAudio && settings.audioTranscriptionEngine !== "deepgram" &&
settings.audioTranscriptionEngine !== "screenpipe-cloud" &&
- settings.audioTranscriptionEngine !== "disabled" &&
- !(hwCapability?.isWeakForLargeModel && settings.audioTranscriptionEngine.includes("large")) && (
+ settings.audioTranscriptionEngine !== "disabled" && (
<Card className="border-border bg-card">
<CardContent className="px-3 py-2.5">
<div className="flex items-center justify-between">
@@ -1049,17 +1048,17 @@ Your screen is a pipe. Everything you see, hear, and type flows through it. Scre
<Zap className="h-4 w-4 text-muted-foreground shrink-0" />
<div>
<h3 className="text-sm font-medium text-foreground flex items-center gap-1.5">
- Smart transcription
- <HelpTooltip text="When enabled, defers Whisper inference until your system is idle. Useful during video calls (Zoom, Meet, Teams) to avoid slowdowns. Audio capture continues uninterrupted — transcription catches up when you're done." />
+ Batch transcription
+ <HelpTooltip text="Accumulates longer audio chunks (30s-5min) using silence-gap detection before sending to Whisper. Gives the model more context for better transcription quality and speaker diarization." />
</h3>
- <p className="text-xs text-muted-foreground">Pause transcription during heavy workloads</p>
+ <p className="text-xs text-muted-foreground">Longer audio chunks for better transcription quality</p>
</div>
</div>
<Switch
id="transcriptionMode"
- checked={(settings.transcriptionMode ?? "realtime") === "smart"}
+ checked={["smart", "batch"].includes(settings.transcriptionMode ?? "realtime")}
onCheckedChange={(checked) =>
- handleSettingsChange({ transcriptionMode: checked ? "smart" : "realtime" }, true)
+ handleSettingsChange({ transcriptionMode: checked ? "batch" : "realtime" }, true)
}
/>
</div>
diff --git a/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx b/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx
index 53e316c6b..7fa34f413 100644
--- a/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx
+++ b/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx
@@ -92,8 +92,8 @@ export type Settings = SettingsStore & {
adaptiveFps?: boolean;
enableInputCapture?: boolean;
enableAccessibility?: boolean;
- /** Audio transcription scheduling: "realtime" (default) or "smart" (defer to idle) */
- transcriptionMode?: "realtime" | "smart";
+ /** Audio transcription scheduling: "realtime" (default) or "batch" (longer chunks for quality) */
+ transcriptionMode?: "realtime" | "smart" | "batch";
/** User's name for speaker identification — input device audio will be labeled with this name */
userName?: string;
/** When true, screen capture continues but OCR text extraction is skipped (saves CPU) */
diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock b/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
index a0ccd3937..d61b76e4f 100644
--- a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
+++ b/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
@@ -8167,7 +8167,7 @@ dependencies = [
[[package]]
name = "screenpipe-app"
-version = "2.0.577"
+version = "2.0.578"
dependencies = [
"anyhow",
"arboard",
diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.toml b/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
index b50dd9c8e..1a943ca44 100644
--- a/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
+++ b/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "screenpipe-app"
-version = "2.0.578"
+version = "2.0.579"
description = "24/7 memory for your desktop. 100% local."
authors = ["you"]
license = ""
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/embedded_server.rs b/apps/screenpipe-app-tauri/src-tauri/src/embedded_server.rs
index c34d6349d..937b3495e 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/embedded_server.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/embedded_server.rs
@@ -115,9 +115,9 @@ pub async fn start_embedded_server(
// Create meeting detector for smart transcription mode.
// Shared between audio manager (checks state) and UI recorder (feeds events).
let meeting_detector: Option<Arc<MeetingDetector>> =
- if config.transcription_mode == TranscriptionMode::Smart {
+ if config.transcription_mode == TranscriptionMode::Batch {
let detector = Arc::new(MeetingDetector::new());
- info!("smart mode: meeting detector enabled — will defer Whisper during meetings");
+ info!("batch mode: meeting detector enabled — used for metadata only");
Some(detector)
} else {
None
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/store.rs b/apps/screenpipe-app-tauri/src-tauri/src/store.rs
index b8f5c3748..ea42e4588 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/store.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/store.rs
@@ -581,28 +581,7 @@ impl SettingsStore {
audio_transcription_engine: audio_engine_str.parse()
.unwrap_or(AudioTranscriptionEngine::WhisperLargeV3Turbo),
transcription_mode: match self.extra.get("transcriptionMode").and_then(|v| v.as_str()) {
- Some("smart") => {
- // Only block Smart mode when weak hardware is running a large model —
- // the CPU-heavy model saturates the system and the IdleDetector's 70%
- // threshold is never reached, creating an infinite deferral loop.
- // Small models (e.g. whisper-tiny) on weak hardware are fine.
- let engine_is_large = audio_engine_str.contains("large");
- if engine_is_large {
- let hw = crate::hardware::detect_hardware_capability();
- if hw.is_weak_for_large_model {
- tracing::warn!(
- "smart transcription mode disabled: weak hardware ({} cores, {:.1} GB RAM, GPU={}) \
- with large model '{}'. Forcing Realtime to avoid infinite idle-deferral loop.",
- hw.cpu_cores, hw.total_memory_gb, hw.has_gpu, audio_engine_str
- );
- TranscriptionMode::Realtime
- } else {
- TranscriptionMode::Smart
- }
- } else {
- TranscriptionMode::Smart
- }
- }
+ Some("smart") | Some("batch") => TranscriptionMode::Batch,
_ => TranscriptionMode::Realtime,
},
audio_devices: self.audio_devices.clone(),
diff --git a/crates/screenpipe-audio/src/audio_manager/builder.rs b/crates/screenpipe-audio/src/audio_manager/builder.rs
index cf2cfa010..e855d1872 100644
--- a/crates/screenpipe-audio/src/audio_manager/builder.rs
+++ b/crates/screenpipe-audio/src/audio_manager/builder.rs
@@ -26,10 +26,11 @@ pub enum TranscriptionMode {
/// Transcribe immediately as audio is captured (current behavior).
#[default]
Realtime,
- /// Defer local Whisper inference to idle periods (CPU < threshold).
- /// Audio capture continues uninterrupted; only transcription is paused.
+ /// Accumulate audio into longer batches (30s-5min) using silence-gap detection.
+ /// Gives Whisper more context for better transcription quality.
/// Has no effect on Deepgram (cloud) — always realtime.
- Smart,
+ #[serde(alias = "Smart")]
+ Batch,
}
#[derive(Clone)]
@@ -54,9 +55,9 @@ pub struct AudioManagerOptions {
/// and switch when the system default changes (e.g., device plug/unplug)
pub use_system_default_audio: bool,
/// Controls when local Whisper transcription runs.
- /// `Realtime` = immediate (default), `Smart` = defer to idle periods.
+ /// `Realtime` = immediate (default), `Batch` = accumulate longer chunks for quality.
pub transcription_mode: TranscriptionMode,
- /// Meeting detector for smart mode — defers Whisper during detected meetings.
+ /// Meeting detector for batch mode — used for metadata/summaries.
/// Shared with UI recorder which feeds app switch events into it.
pub meeting_detector: Option<Arc<MeetingDetector>>,
/// Custom vocabulary entries for transcription biasing and word replacement.
diff --git a/crates/screenpipe-audio/src/audio_manager/manager.rs b/crates/screenpipe-audio/src/audio_manager/manager.rs
index 97a711c13..b3de3798e 100644
--- a/crates/screenpipe-audio/src/audio_manager/manager.rs
+++ b/crates/screenpipe-audio/src/audio_manager/manager.rs
@@ -31,7 +31,6 @@ use crate::{
record_and_transcribe,
},
device::device_manager::DeviceManager,
- idle_detector::IdleDetector,
meeting_detector::MeetingDetector,
metrics::AudioPipelineMetrics,
segmentation::segmentation_manager::SegmentationManager,
@@ -72,9 +71,8 @@ pub struct AudioManager {
recording_receiver_handle: Arc<RwLock<Option<JoinHandle<()>>>>,
stt_model_path: tokio::sync::watch::Receiver<Option<PathBuf>>,
pub metrics: Arc<AudioPipelineMetrics>,
- idle_detector: Option<Arc<IdleDetector>>,
meeting_detector: Option<Arc<MeetingDetector>>,
- /// Whether transcription is currently paused due to high CPU or meeting (batch/smart mode).
+ /// Whether transcription is currently paused (legacy, always false — deferral removed).
pub transcription_paused: Arc<AtomicBool>,
/// Optional callback invoked after each audio transcription DB insert.
/// Used by the hot frame cache to receive live audio updates.
@@ -126,21 +124,6 @@ impl AudioManager {
whisper_rs::install_logging_hooks();
- // Only create idle detector for Smart mode with local Whisper engines
- let is_local_whisper = !matches!(
- *options.transcription_engine,
- AudioTranscriptionEngine::Deepgram | AudioTranscriptionEngine::Disabled
- );
- let idle_detector = if options.transcription_mode == TranscriptionMode::Smart
- && is_local_whisper
- {
- let detector = Arc::new(IdleDetector::new(70.0));
- info!("batch/smart transcription mode enabled — will defer Whisper during high CPU");
- Some(detector)
- } else {
- None
- };
-
let meeting_detector = options.meeting_detector.clone();
let manager = Self {
@@ -159,7 +142,6 @@ impl AudioManager {
transcription_receiver_handle: Arc::new(RwLock::new(None)),
stt_model_path: stt_model_rx,
metrics: Arc::new(AudioPipelineMetrics::new()),
- idle_detector,
meeting_detector,
transcription_paused: Arc::new(AtomicBool::new(false)),
on_transcription_insert: None,
@@ -193,42 +175,28 @@ impl AudioManager {
*recording_receiver_handle = Some(self.start_audio_receiver_handler().await?);
let self_arc = Arc::new(self.clone());
- // Spawn idle detector refresh task if in Smart mode
- if let Some(ref detector) = self.idle_detector {
- let detector = detector.clone();
- tokio::spawn(async move {
- loop {
- detector.refresh();
- tokio::time::sleep(Duration::from_secs(10)).await;
- }
- });
- }
-
- // Spawn reconciliation sweep for orphaned audio chunks (smart mode only)
- if self.idle_detector.is_some() || self.meeting_detector.is_some() {
+ // Spawn reconciliation sweep for orphaned audio chunks (batch mode only)
+ if self.options.read().await.transcription_mode == TranscriptionMode::Batch {
let db = self.db.clone();
let whisper_ctx_ref = self.whisper_context.clone();
let options = self.options.clone();
- let transcription_paused = self.transcription_paused.clone();
tokio::spawn(async move {
// Wait for Whisper model to load + initial recordings
tokio::time::sleep(Duration::from_secs(120)).await;
loop {
- if !transcription_paused.load(Ordering::Relaxed) {
- if let Some(ref ctx) = *whisper_ctx_ref.read().await {
- let opts = options.read().await;
- let engine = opts.transcription_engine.clone();
- let key = opts.deepgram_api_key.clone();
- let langs = opts.languages.clone();
- let vocab = opts.vocabulary.clone();
- drop(opts);
- let count = super::reconciliation::reconcile_untranscribed(
- &db, ctx, engine, key, langs, &vocab,
- )
- .await;
- if count > 0 {
- info!("reconciliation: transcribed {} orphaned chunks", count);
- }
+ if let Some(ref ctx) = *whisper_ctx_ref.read().await {
+ let opts = options.read().await;
+ let engine = opts.transcription_engine.clone();
+ let key = opts.deepgram_api_key.clone();
+ let langs = opts.languages.clone();
+ let vocab = opts.vocabulary.clone();
+ drop(opts);
+ let count = super::reconciliation::reconcile_untranscribed(
+ &db, ctx, engine, key, langs, &vocab,
+ )
+ .await;
+ if count > 0 {
+ info!("reconciliation: transcribed {} orphaned chunks", count);
}
}
tokio::time::sleep(Duration::from_secs(300)).await;
@@ -368,6 +336,7 @@ impl AudioManager {
let languages = options.languages.clone();
let deepgram_api_key = options.deepgram_api_key.clone();
let realtime_enabled = options.enable_realtime;
+ let transcription_mode = options.transcription_mode.clone();
let device_clone = device.clone();
let metrics = self.metrics.clone();
@@ -378,6 +347,7 @@ impl AudioManager {
recording_sender.clone(),
is_running.clone(),
metrics,
+ transcription_mode,
));
let realtime_handle = if realtime_enabled {
@@ -442,9 +412,7 @@ impl AudioManager {
let whisper_receiver = self.recording_receiver.clone();
let metrics = self.metrics.clone();
let context_param = create_whisper_context_parameters(audio_transcription_engine.clone())?;
- let idle_detector = self.idle_detector.clone();
let meeting_detector = self.meeting_detector.clone();
- let transcription_paused = self.transcription_paused.clone();
let db = self.db.clone();
let quantized_path = {
@@ -536,68 +504,13 @@ impl AudioManager {
None
};
- // Smart mode: defer Whisper during meetings, then check CPU idle
- let mut deferred = false;
-
- // 1. Meeting-based deferral (primary signal)
+ // Meeting detector: log meeting metadata (no deferral)
if let Some(ref meeting) = meeting_detector {
- // Check if grace period expired (handles case where no new
- // app switch events arrive after the user leaves the meeting app)
meeting.check_grace_period().await;
-
- let mut was_paused = false;
- while meeting.is_in_meeting() {
- // Only defer if we can identify the meeting app.
- // Audio-based detection can fire with no app name
- // (e.g. YouTube + ambient mic noise) — skip those.
- let meeting_app = meeting.current_meeting_app().await;
- if meeting_app.is_none() {
- break;
- }
- if !was_paused {
- warn!(
- "smart mode: meeting detected ({}), deferring transcription",
- meeting_app.unwrap_or_default()
- );
- metrics.record_batch_pause();
- was_paused = true;
- }
- metrics.record_segment_deferred();
- transcription_paused.store(true, Ordering::Relaxed);
- tokio::time::sleep(Duration::from_secs(5)).await;
- // Re-check grace period each iteration
- meeting.check_grace_period().await;
- }
- if was_paused {
- info!("smart mode: meeting ended, processing backlog");
- metrics.record_batch_resume();
- deferred = true;
- }
- transcription_paused.store(false, Ordering::Relaxed);
- }
-
- // 2. CPU idle deferral (fallback — only if meeting didn't already defer)
- if !deferred {
- if let Some(ref detector) = idle_detector {
- let mut was_paused = false;
- while !detector.is_idle() {
- if !was_paused {
- warn!(
- "batch mode: deferring transcription ({})",
- detector.paused_reason().unwrap_or_default()
- );
- metrics.record_batch_pause();
- was_paused = true;
- }
- metrics.record_segment_deferred();
- transcription_paused.store(true, Ordering::Relaxed);
- tokio::time::sleep(Duration::from_secs(10)).await;
- }
- if was_paused {
- info!("batch mode: system idle, resuming transcription");
- metrics.record_batch_resume();
+ if meeting.is_in_meeting() {
+ if let Some(app) = meeting.current_meeting_app().await {
+ debug!("batch mode: meeting detected ({}), metadata only", app);
}
- transcription_paused.store(false, Ordering::Relaxed);
}
}
@@ -620,8 +533,6 @@ impl AudioManager {
.await
{
error!("Error processing audio: {:?}", e);
- } else if idle_detector.is_some() {
- metrics.record_segment_batch_processed();
}
}
}))
@@ -678,7 +589,7 @@ impl AudioManager {
self.options.read().await.enabled_devices.clone()
}
- /// Returns a reference to the meeting detector, if smart mode is active.
+ /// Returns a reference to the meeting detector, if batch mode is active.
pub fn meeting_detector(&self) -> Option<&Arc<MeetingDetector>> {
self.meeting_detector.as_ref()
}
diff --git a/crates/screenpipe-audio/src/core/mod.rs b/crates/screenpipe-audio/src/core/mod.rs
index bdffec34a..2b6d4007a 100644
--- a/crates/screenpipe-audio/src/core/mod.rs
+++ b/crates/screenpipe-audio/src/core/mod.rs
@@ -68,6 +68,7 @@ pub async fn record_and_transcribe(
whisper_sender: Arc<crossbeam::channel::Sender<AudioInput>>,
is_running: Arc<AtomicBool>,
metrics: Arc<crate::metrics::AudioPipelineMetrics>,
+ transcription_mode: crate::audio_manager::TranscriptionMode,
) -> Result<()> {
while is_running.load(Ordering::Relaxed) {
match run_record_and_transcribe::run_record_and_transcribe(
@@ -76,6 +77,7 @@ pub async fn record_and_transcribe(
whisper_sender.clone(),
is_running.clone(),
metrics.clone(),
+ transcription_mode.clone(),
)
.await
{
diff --git a/crates/screenpipe-audio/src/core/run_record_and_transcribe.rs b/crates/screenpipe-audio/src/core/run_record_and_transcribe.rs
index b9bf5830d..2c19f0354 100644
--- a/crates/screenpipe-audio/src/core/run_record_and_transcribe.rs
+++ b/crates/screenpipe-audio/src/core/run_record_and_transcribe.rs
@@ -15,6 +15,7 @@ use tokio::sync::broadcast;
use tracing::{debug, error, info, warn};
use crate::{
+ audio_manager::TranscriptionMode,
core::{device::DeviceType, update_device_capture_time},
metrics::AudioPipelineMetrics,
AudioInput,
@@ -27,127 +28,146 @@ use super::AudioStream;
/// by another app (e.g., Wispr Flow taking over the microphone).
const AUDIO_RECEIVE_TIMEOUT_SECS: u64 = 30;
+/// Batch mode: minimum seconds of audio before a silence gap can trigger a flush.
+const MIN_BATCH_SECS: usize = 30;
+/// Batch mode: maximum seconds of audio before forcing a flush regardless of silence.
+const MAX_BATCH_SECS: usize = 300;
+/// Batch mode: seconds of continuous silence required to trigger a flush.
+const SILENCE_GAP_SECS: f32 = 3.0;
+/// Batch mode: RMS threshold below which audio is considered silence.
+const SILENCE_RMS_THRESHOLD: f32 = 0.01;
+
pub async fn run_record_and_transcribe(
audio_stream: Arc<AudioStream>,
duration: Duration,
whisper_sender: Arc<crossbeam::channel::Sender<AudioInput>>,
is_running: Arc<AtomicBool>,
metrics: Arc<AudioPipelineMetrics>,
+ transcription_mode: TranscriptionMode,
) -> Result<()> {
let mut receiver = audio_stream.subscribe().await;
let device_name = audio_stream.device.to_string();
-
- info!(
- "starting continuous recording for {} ({}s segments)",
- device_name,
- duration.as_secs()
- );
+ let sample_rate = audio_stream.device_config.sample_rate().0 as usize;
const OVERLAP_SECONDS: usize = 2;
- let mut collected_audio = Vec::new();
- let sample_rate = audio_stream.device_config.sample_rate().0 as usize;
- let audio_samples_len = sample_rate * duration.as_secs() as usize;
let overlap_samples = OVERLAP_SECONDS * sample_rate;
- let max_samples = audio_samples_len + overlap_samples;
-
- while is_running.load(Ordering::Relaxed)
- && !audio_stream.is_disconnected.load(Ordering::Relaxed)
- {
- while collected_audio.len() < max_samples && is_running.load(Ordering::Relaxed) {
- // Use timeout to detect when audio stream stops sending data
- // This happens when another app hijacks the audio device
- let recv_result = tokio::time::timeout(
- Duration::from_secs(AUDIO_RECEIVE_TIMEOUT_SECS),
- receiver.recv(),
- )
- .await;
-
- match recv_result {
- Ok(Ok(chunk)) => {
- metrics.update_audio_level(&chunk);
- collected_audio.extend(chunk);
- update_device_capture_time(&device_name);
- }
- Ok(Err(broadcast::error::RecvError::Lagged(n))) => {
- // Channel buffer overflow - receiver fell behind producer
- // This is expected under heavy load, continue instead of failing
- debug!(
- "audio channel lagged by {} messages for {}, continuing",
- n, device_name
- );
- continue;
- }
- Ok(Err(e)) => {
- error!("error receiving audio data: {}", e);
- return Err(anyhow!("Audio stream error: {}", e));
- }
- Err(_timeout) => {
- // No audio data received for AUDIO_RECEIVE_TIMEOUT_SECS seconds.
- // For OUTPUT devices (speakers), this is completely normal when
- // nothing is playing — just keep waiting for audio to arrive.
- // For INPUT devices (microphones), this likely means another app
- // hijacked the device, so trigger a reconnect.
- if audio_stream.device.device_type == DeviceType::Output {
- debug!(
- "no audio from output device {} for {}s - idle (normal), continuing",
- device_name, AUDIO_RECEIVE_TIMEOUT_SECS
- );
- continue;
+
+ match transcription_mode {
+ TranscriptionMode::Realtime => {
+ info!(
+ "starting continuous recording for {} ({}s segments, realtime mode)",
+ device_name,
+ duration.as_secs()
+ );
+ let audio_samples_len = sample_rate * duration.as_secs() as usize;
+ let max_samples = audio_samples_len + overlap_samples;
+ let mut collected_audio = Vec::new();
+
+ while is_running.load(Ordering::Relaxed)
+ && !audio_stream.is_disconnected.load(Ordering::Relaxed)
+ {
+ while collected_audio.len() < max_samples && is_running.load(Ordering::Relaxed) {
+ match recv_audio_chunk(
+ &mut receiver,
+ &audio_stream,
+ &device_name,
+ &metrics,
+ )
+ .await?
+ {
+ Some(chunk) => collected_audio.extend(chunk),
+ None => continue, // lagged or idle output device
}
- debug!(
- "no audio received from {} for {}s - stream may be hijacked, triggering reconnect",
- device_name, AUDIO_RECEIVE_TIMEOUT_SECS
- );
- metrics.record_stream_timeout();
- // Mark stream as disconnected so device monitor can restart it
- audio_stream.is_disconnected.store(true, Ordering::Relaxed);
- return Err(anyhow!(
- "Audio stream timeout - no data received for {}s (possible audio hijack)",
- AUDIO_RECEIVE_TIMEOUT_SECS
- ));
}
+
+ flush_audio(
+ &mut collected_audio,
+ overlap_samples,
+ &audio_stream,
+ &whisper_sender,
+ &device_name,
+ &metrics,
+ )
+ .await?;
}
}
+ TranscriptionMode::Batch => {
+ info!(
+ "starting continuous recording for {} (batch mode, {}s-{}s adaptive segments)",
+ device_name, MIN_BATCH_SECS, MAX_BATCH_SECS
+ );
+ let max_samples = MAX_BATCH_SECS * sample_rate + overlap_samples;
+ let min_samples = MIN_BATCH_SECS * sample_rate;
+ // Window size for RMS silence detection: 100ms
+ let silence_window = sample_rate / 10;
+ let silence_gap_samples = (SILENCE_GAP_SECS * sample_rate as f32) as usize;
- if !collected_audio.is_empty() {
- debug!("sending audio segment to audio model");
- let capture_timestamp = SystemTime::now()
- .duration_since(UNIX_EPOCH)
- .expect("Time went backwards")
- .as_secs();
- // Use send_timeout instead of try_send to apply backpressure when the
- // Whisper consumer falls behind. The 30s timeout matches the chunk
- // accumulation duration — if the consumer can't clear one slot in 30s
- // it is truly stuck and dropping is the only option.
- match whisper_sender.send_timeout(
- AudioInput {
- data: Arc::new(collected_audio.clone()),
- device: audio_stream.device.clone(),
- sample_rate: audio_stream.device_config.sample_rate().0,
- channels: audio_stream.device_config.channels(),
- capture_timestamp,
- },
- Duration::from_secs(30),
- ) {
- Ok(_) => {
- debug!("sent audio segment to audio model");
- metrics.record_chunk_sent();
- if collected_audio.len() > overlap_samples {
- collected_audio =
- collected_audio.split_off(collected_audio.len() - overlap_samples);
+ let mut collected_audio = Vec::new();
+ let mut consecutive_silence_samples: usize = 0;
+
+ while is_running.load(Ordering::Relaxed)
+ && !audio_stream.is_disconnected.load(Ordering::Relaxed)
+ {
+ match recv_audio_chunk(
+ &mut receiver,
+ &audio_stream,
+ &device_name,
+ &metrics,
+ )
+ .await?
+ {
+ Some(chunk) => {
+ // Track silence via RMS over 100ms windows
+ let mut offset = 0;
+ while offset + silence_window <= chunk.len() {
+ let window = &chunk[offset..offset + silence_window];
+ let sum_sq: f32 = window.iter().map(|&x| x * x).sum();
+ let rms = (sum_sq / window.len() as f32).sqrt();
+ if rms < SILENCE_RMS_THRESHOLD {
+ consecutive_silence_samples += silence_window;
+ } else {
+ consecutive_silence_samples = 0;
+ }
+ offset += silence_window;
+ }
+ collected_audio.extend(chunk);
}
+ None => continue,
}
- Err(e) => {
- if e.is_disconnected() {
- error!("whisper channel disconnected, restarting recording process");
- return Err(anyhow!("Whisper channel disconnected"));
- } else if e.is_timeout() {
- metrics.record_channel_full();
- warn!(
- "whisper channel still full after 30s, dropping audio segment for {}",
- device_name
- );
- }
+
+ // Flush conditions:
+ // 1. Silence gap detected AND we have enough audio
+ // 2. Max batch size reached (force flush)
+ let should_flush = if collected_audio.len() >= max_samples {
+ debug!(
+ "batch mode: max {}s reached for {}, flushing",
+ MAX_BATCH_SECS, device_name
+ );
+ true
+ } else if collected_audio.len() >= min_samples
+ && consecutive_silence_samples >= silence_gap_samples
+ {
+ debug!(
+ "batch mode: silence gap detected after {:.1}s of audio for {}, flushing",
+ collected_audio.len() as f64 / sample_rate as f64,
+ device_name
+ );
+ true
+ } else {
+ false
+ };
+
+ if should_flush {
+ consecutive_silence_samples = 0;
+ flush_audio(
+ &mut collected_audio,
+ overlap_samples,
+ &audio_stream,
+ &whisper_sender,
+ &device_name,
+ &metrics,
+ )
+ .await?;
}
}
}
@@ -156,3 +176,114 @@ pub async fn run_record_and_transcribe(
info!("stopped recording for {}", device_name);
Ok(())
}
+
+/// Receive one audio chunk from the broadcast channel, handling timeouts and device type logic.
+/// Returns `Ok(Some(chunk))` on data, `Ok(None)` when the caller should continue (lag/idle),
+/// or `Err` on fatal errors.
+async fn recv_audio_chunk(
+ receiver: &mut broadcast::Receiver<Vec<f32>>,
+ audio_stream: &Arc<AudioStream>,
+ device_name: &str,
+ metrics: &Arc<AudioPipelineMetrics>,
+) -> Result<Option<Vec<f32>>> {
+ let recv_result = tokio::time::timeout(
+ Duration::from_secs(AUDIO_RECEIVE_TIMEOUT_SECS),
+ receiver.recv(),
+ )
+ .await;
+
+ match recv_result {
+ Ok(Ok(chunk)) => {
+ metrics.update_audio_level(&chunk);
+ update_device_capture_time(device_name);
+ Ok(Some(chunk))
+ }
+ Ok(Err(broadcast::error::RecvError::Lagged(n))) => {
+ debug!(
+ "audio channel lagged by {} messages for {}, continuing",
+ n, device_name
+ );
+ Ok(None)
+ }
+ Ok(Err(e)) => {
+ error!("error receiving audio data: {}", e);
+ Err(anyhow!("Audio stream error: {}", e))
+ }
+ Err(_timeout) => {
+ if audio_stream.device.device_type == DeviceType::Output {
+ debug!(
+ "no audio from output device {} for {}s - idle (normal), continuing",
+ device_name, AUDIO_RECEIVE_TIMEOUT_SECS
+ );
+ return Ok(None);
+ }
+ debug!(
+ "no audio received from {} for {}s - stream may be hijacked, triggering reconnect",
+ device_name, AUDIO_RECEIVE_TIMEOUT_SECS
+ );
+ metrics.record_stream_timeout();
+ audio_stream
+ .is_disconnected
+ .store(true, Ordering::Relaxed);
+ Err(anyhow!(
+ "Audio stream timeout - no data received for {}s (possible audio hijack)",
+ AUDIO_RECEIVE_TIMEOUT_SECS
+ ))
+ }
+ }
+}
+
+/// Send the collected audio to the Whisper channel and keep the overlap tail.
+/// Clears `collected_audio` down to the overlap on success.
+async fn flush_audio(
+ collected_audio: &mut Vec<f32>,
+ overlap_samples: usize,
+ audio_stream: &Arc<AudioStream>,
+ whisper_sender: &Arc<crossbeam::channel::Sender<AudioInput>>,
+ device_name: &str,
+ metrics: &Arc<AudioPipelineMetrics>,
+) -> Result<()> {
+ if collected_audio.is_empty() {
+ return Ok(());
+ }
+
+ debug!("sending audio segment to audio model");
+ let capture_timestamp = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .expect("Time went backwards")
+ .as_secs();
+
+ match whisper_sender.send_timeout(
+ AudioInput {
+ data: Arc::new(collected_audio.clone()),
+ device: audio_stream.device.clone(),
+ sample_rate: audio_stream.device_config.sample_rate().0,
+ channels: audio_stream.device_config.channels(),
+ capture_timestamp,
+ },
+ Duration::from_secs(30),
+ ) {
+ Ok(_) => {
+ debug!("sent audio segment to audio model");
+ metrics.record_chunk_sent();
+ if collected_audio.len() > overlap_samples {
+ *collected_audio =
+ collected_audio.split_off(collected_audio.len() - overlap_samples);
+ }
+ }
+ Err(e) => {
+ if e.is_disconnected() {
+ error!("whisper channel disconnected, restarting recording process");
+ return Err(anyhow!("Whisper channel disconnected"));
+ } else if e.is_timeout() {
+ metrics.record_channel_full();
+ warn!(
+ "whisper channel still full after 30s, dropping audio segment for {}",
+ device_name
+ );
+ }
+ }
+ }
+
+ Ok(())
+}
diff --git a/crates/screenpipe-server/src/bin/screenpipe-server.rs b/crates/screenpipe-server/src/bin/screenpipe-server.rs
index 7c0a7f6b1..553165883 100644
--- a/crates/screenpipe-server/src/bin/screenpipe-server.rs
+++ b/crates/screenpipe-server/src/bin/screenpipe-server.rs
@@ -628,9 +628,9 @@ async fn main() -> anyhow::Result<()> {
// Create meeting detector for smart transcription mode.
// Shared between audio manager (checks state) and UI recorder (feeds events).
let meeting_detector: Option<Arc<MeetingDetector>> =
- if config.transcription_mode == screenpipe_audio::audio_manager::TranscriptionMode::Smart {
+ if config.transcription_mode == screenpipe_audio::audio_manager::TranscriptionMode::Batch {
let detector = Arc::new(MeetingDetector::new());
- info!("smart mode: meeting detector enabled — will defer Whisper during meetings");
+ info!("batch mode: meeting detector enabled — used for metadata only");
Some(detector)
} else {
None
diff --git a/crates/screenpipe-server/src/cli.rs b/crates/screenpipe-server/src/cli.rs
index f481e4f92..6bed6e2b0 100644
--- a/crates/screenpipe-server/src/cli.rs
+++ b/crates/screenpipe-server/src/cli.rs
@@ -76,16 +76,16 @@ pub enum CliTranscriptionMode {
/// Transcribe immediately as audio is captured (default)
#[clap(name = "realtime")]
Realtime,
- /// Defer local Whisper inference to idle periods (CPU < threshold)
- #[clap(name = "smart")]
- Smart,
+ /// Accumulate longer audio batches for better transcription quality
+ #[clap(name = "batch", alias = "smart")]
+ Batch,
}
impl From<CliTranscriptionMode> for TranscriptionMode {
fn from(cli_mode: CliTranscriptionMode) -> Self {
match cli_mode {
CliTranscriptionMode::Realtime => TranscriptionMode::Realtime,
- CliTranscriptionMode::Smart => TranscriptionMode::Smart,
+ CliTranscriptionMode::Batch => TranscriptionMode::Batch,
}
}
}
@@ -176,7 +176,7 @@ pub struct Cli {
#[arg(long, hide = true)]
pub auto_destruct_pid: Option<u32>,
- /// Audio transcription scheduling mode
+ /// Audio transcription scheduling mode: realtime (default) or batch (longer chunks for quality)
#[arg(long, value_enum, default_value_t = CliTranscriptionMode::Realtime)]
pub transcription_mode: CliTranscriptionMode,
@@ -371,7 +371,7 @@ pub struct RecordArgs {
#[arg(long, hide = true)]
pub auto_destruct_pid: Option<u32>,
- /// Audio transcription scheduling mode: realtime (default) or smart (defer to idle)
+ /// Audio transcription scheduling mode: realtime (default) or batch (longer chunks for quality)
#[arg(long, value_enum, default_value_t = CliTranscriptionMode::Realtime)]
pub transcription_mode: CliTranscriptionMode,
diff --git a/crates/screenpipe-server/src/routes/health.rs b/crates/screenpipe-server/src/routes/health.rs
index 33cbfe63c..ee174875f 100644
--- a/crates/screenpipe-server/src/routes/health.rs
+++ b/crates/screenpipe-server/src/routes/health.rs
@@ -444,7 +444,7 @@ pub async fn health_check(State(state): State<Arc<AppState>>) -> JsonResponse<He
transcription_mode: if audio_snap.segments_deferred > 0
|| audio_snap.segments_batch_processed > 0
{
- Some("smart".to_string())
+ Some("batch".to_string())
} else {
Some("realtime".to_string())
},