Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(desktop): mute microphone during instant recordings from the recording bar

Richie McIlroyfe5aeb28bf0e
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 826fb2bfd..3f85c7c3b 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -4825,6 +4825,7 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {
recording::pause_recording,
recording::resume_recording,
recording::toggle_pause_recording,
+ recording::set_mic_recording_muted,
recording::restart_recording,
recording::delete_recording,
recording::take_screenshot,
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index 86ff90f49..f71312bd1 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -2378,6 +2378,39 @@ pub async fn resume_recording(app: AppHandle, state: MutableState<'_, App>) -> R
Ok(())
}
+#[tauri::command]
+#[specta::specta]
+#[instrument(skip(state))]
+pub async fn set_mic_recording_muted(
+ state: MutableState<'_, App>,
+ muted: bool,
+) -> Result<(), String> {
+ let state = state.read().await;
+
+ let Some(recording) = state.current_recording() else {
+ return Err("No recording in progress".to_string());
+ };
+
+ let mic_feed = match recording {
+ InProgressRecording::Instant { mic_feed, .. } => mic_feed.as_ref(),
+ // Studio records the mic as an editable track; muting would silently
+ // bake zeros into it. The bar only offers mute for instant mode —
+ // enforce the same contract here so no future caller can corrupt a
+ // studio track.
+ InProgressRecording::Studio { .. } => {
+ return Err("Mic mute is only available for instant recordings".to_string());
+ }
+ };
+
+ let Some(mic_feed) = mic_feed else {
+ return Err("Recording has no microphone".to_string());
+ };
+
+ mic_feed.set_recording_muted(muted);
+ info!(muted, "Recording microphone mute set");
+ Ok(())
+}
+
#[tauri::command]
#[specta::specta]
#[instrument(skip(app, state))]
diff --git a/apps/desktop/src/routes/in-progress-recording.tsx b/apps/desktop/src/routes/in-progress-recording.tsx
index 7489b74ef..7afd88628 100644
--- a/apps/desktop/src/routes/in-progress-recording.tsx
+++ b/apps/desktop/src/routes/in-progress-recording.tsx
@@ -118,6 +118,10 @@ function InProgressRecordingInner() {
const [startingDismissed, setStartingDismissed] = createSignal(false);
const [stopRequested, setStopRequested] = createSignal(false);
const [teardownInFlight, setTeardownInFlight] = createSignal(false);
+ // Mirrors the backend's recording-scoped mic mute. The backend flag lives
+ // on the per-recording microphone lock, so every new recording starts
+ // unmuted — this signal must be reset wherever a new session begins.
+ const [micMuted, setMicMuted] = createSignal(false);
const [interactiveAreaRef, setInteractiveAreaRef] =
createSignal<HTMLDivElement | null>(null);
let settingsButtonRef: HTMLButtonElement | undefined;
@@ -202,6 +206,7 @@ function InProgressRecordingInner() {
setDegradedReason(null);
setPauseResumes([]);
setStopRequested(false);
+ setMicMuted(false);
setState({
variant: "countdown",
from: payload.value,
@@ -216,6 +221,7 @@ function InProgressRecordingInner() {
setDegradedReason(null);
setPauseResumes([]);
setStopRequested(false);
+ setMicMuted(false);
aborted = false;
// This window is reused across recordings, so `start`/`time` still
// hold the previous session's values here. Effects (the free-plan
@@ -311,6 +317,7 @@ function InProgressRecordingInner() {
setDegradedReason(null);
setPauseResumes([]);
setStopRequested(false);
+ setMicMuted(false);
aborted = false;
if (recording.status === "recording") {
setStart(Date.now());
@@ -330,6 +337,7 @@ function InProgressRecordingInner() {
setRecordingFailure(null);
setDegradedReason(null);
setPauseResumes([]);
+ setMicMuted(false);
aborted = false;
setStart(Date.now());
setTime(Date.now());
@@ -480,6 +488,31 @@ function InProgressRecordingInner() {
},
}));
+ // Muting zeroes the mic samples backend-side while the stream keeps its
+ // normal cadence, so the recording timeline is unaffected. Only exposed for
+ // instant mode: studio records the mic as an editable track, where muted
+ // spans would silently bake zeros into it.
+ const canToggleMicMute = createMemo(
+ () =>
+ recordingMode() === "instant" &&
+ optionsQuery.rawOptions.micName != null &&
+ !disconnectedInputs.microphone &&
+ (state().variant === "recording" || state().variant === "paused"),
+ );
+
+ const toggleMicMute = createMutation(() => ({
+ mutationFn: async () => {
+ const next = !micMuted();
+ setMicMuted(next);
+ try {
+ await commands.setMicRecordingMuted(next);
+ } catch (error) {
+ setMicMuted(!next);
+ throw error;
+ }
+ },
+ }));
+
const restartRecording = createMutation(() => ({
mutationFn: async () => {
const shouldRestart = await dialog.confirm(
@@ -845,13 +878,55 @@ function InProgressRecordingInner() {
</Show>
<div class="flex items-center gap-1">
- <div
- class="relative flex h-8 w-8 items-center justify-center"
- title={microphoneTitle()}
+ <Show
+ when={canToggleMicMute()}
+ fallback={
+ <div
+ class="relative flex h-8 w-8 items-center justify-center"
+ title={microphoneTitle()}
+ >
+ {optionsQuery.rawOptions.micName != null ? (
+ disconnectedInputs.microphone ? (
+ <IconLucideMicOff class="size-5 text-amber-11" />
+ ) : (
+ <>
+ <IconCapMicrophone class="size-5 text-gray-12" />
+ <div class="absolute bottom-1 left-1 right-1 h-0.5 overflow-hidden rounded-full bg-gray-10">
+ <div
+ class="absolute inset-0 bg-blue-9 transition-transform duration-100"
+ style={{
+ transform: `translateX(-${
+ (1 - audioLevel()) * 100
+ }%)`,
+ }}
+ />
+ </div>
+ </>
+ )
+ ) : (
+ <IconLucideMicOff
+ class="size-5 text-gray-7"
+ data-tauri-drag-region
+ />
+ )}
+ </div>
+ }
>
- {optionsQuery.rawOptions.micName != null ? (
- disconnectedInputs.microphone ? (
- <IconLucideMicOff class="size-5 text-amber-11" />
+ <button
+ type="button"
+ class="relative flex h-8 w-8 items-center justify-center rounded-lg transition-colors duration-100 hover:bg-gray-12/6 active:bg-gray-12/10 disabled:opacity-50 disabled:hover:bg-transparent dark:hover:bg-white/8 dark:active:bg-white/12"
+ disabled={toggleMicMute.isPending}
+ onClick={() => toggleMicMute.mutate()}
+ title={
+ micMuted() ? "Unmute microphone" : "Mute microphone"
+ }
+ aria-pressed={micMuted() ? "true" : "false"}
+ aria-label={
+ micMuted() ? "Unmute microphone" : "Mute microphone"
+ }
+ >
+ {micMuted() ? (
+ <IconLucideMicOff class="size-5 text-red-9" />
) : (
<>
<IconCapMicrophone class="size-5 text-gray-12" />
@@ -866,14 +941,9 @@ function InProgressRecordingInner() {
/>
</div>
</>
- )
- ) : (
- <IconLucideMicOff
- class="size-5 text-gray-7"
- data-tauri-drag-region
- />
- )}
- </div>
+ )}
+ </button>
+ </Show>
<Show when={hasCameraInput() && disconnectedInputs.camera}>
<div
class="flex h-8 w-8 items-center justify-center"
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index f7fd0df82..6a5eba18f 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -47,6 +47,9 @@ async resumeRecording() : Promise<null> {
async togglePauseRecording() : Promise<null> {
return await TAURI_INVOKE("toggle_pause_recording");
},
+async setMicRecordingMuted(muted: boolean) : Promise<null> {
+ return await TAURI_INVOKE("set_mic_recording_muted", { muted });
+},
async restartRecording() : Promise<RecordingAction> {
return await TAURI_INVOKE("restart_recording");
},
diff --git a/crates/recording/src/feeds/microphone.rs b/crates/recording/src/feeds/microphone.rs
index 224b17540..0d9709381 100644
--- a/crates/recording/src/feeds/microphone.rs
+++ b/crates/recording/src/feeds/microphone.rs
@@ -17,7 +17,7 @@ use std::{
ops::Deref,
sync::{
Arc, Weak,
- atomic::{AtomicU64, Ordering},
+ atomic::{AtomicBool, AtomicU64, Ordering},
mpsc::{self, SyncSender},
},
time::{Duration, Instant},
@@ -1011,6 +1011,11 @@ pub struct MicrophoneFeedLock {
buffer_size_frames: Option<u32>,
drop_tx: Option<oneshot::Sender<()>>,
device_name: String,
+ // Recording-scoped mute. The stream keeps flowing at its normal cadence —
+ // the recording source zeroes sample payloads while this is set — so
+ // timestamps, resampler state, and the muxer timeline are untouched by
+ // muting. A fresh lock (i.e. every new recording) always starts unmuted.
+ recording_muted: Arc<AtomicBool>,
_token: Arc<()>,
}
@@ -1034,6 +1039,18 @@ impl MicrophoneFeedLock {
pub async fn dropped_message_count(&self) -> u64 {
self.actor.ask(GetDroppedMessageCount).await.unwrap_or(0)
}
+
+ pub fn set_recording_muted(&self, muted: bool) {
+ self.recording_muted.store(muted, Ordering::Relaxed);
+ }
+
+ pub fn is_recording_muted(&self) -> bool {
+ self.recording_muted.load(Ordering::Relaxed)
+ }
+
+ pub fn recording_muted_handle(&self) -> Arc<AtomicBool> {
+ self.recording_muted.clone()
+ }
}
impl Deref for MicrophoneFeedLock {
@@ -1481,6 +1498,7 @@ impl Message<Lock> for MicrophoneFeed {
buffer_size_frames,
drop_tx: Some(drop_tx),
device_name,
+ recording_muted: Arc::new(AtomicBool::new(false)),
_token: token,
})
}
diff --git a/crates/recording/src/sources/microphone.rs b/crates/recording/src/sources/microphone.rs
index c6764d465..a479b19da 100644
--- a/crates/recording/src/sources/microphone.rs
+++ b/crates/recording/src/sources/microphone.rs
@@ -227,6 +227,8 @@ impl AudioSource for Microphone {
"Microphone source configured"
);
+ let recording_muted = feed_lock.recording_muted_handle();
+
tokio::spawn({
let frame_counter = mic_frame_counter.clone();
let drop_counter = mic_drop_counter.clone();
@@ -235,6 +237,7 @@ impl AudioSource for Microphone {
let device_name = device_name.clone();
let health_tx = health_tx.clone();
let cancel = cancel.clone();
+ let recording_muted = recording_muted.clone();
async move {
let mut resampler: Option<MicResampler> = None;
let mut silence_mode = false;
@@ -331,11 +334,19 @@ impl AudioSource for Microphone {
))
};
- let Some(audio_frame) = audio_frame else {
+ let Some(mut audio_frame) = audio_frame else {
drop_counter.fetch_add(1, Ordering::Relaxed);
continue;
};
+ // Mute by zeroing the payload, never by withholding the
+ // frame: cadence, sample counts, and timestamps must stay
+ // identical to the unmuted stream so the muxer timeline
+ // and the stall/keepalive machinery see no difference.
+ if recording_muted.load(Ordering::Relaxed) {
+ silence_frame_payload(&mut audio_frame.inner);
+ }
+
let sample_count = audio_frame.samples();
last_frame_duration = Duration::from_secs_f64(
sample_count as f64 / audio_info.rate() as f64,
@@ -586,6 +597,17 @@ fn create_silence_frame(info: &AudioInfo, sample_count: usize) -> ffmpeg::frame:
frame
}
+/// Zero a frame's sample data in place, leaving format, sample count, rate,
+/// layout, and timestamp untouched. All-zero bytes are exact silence for every
+/// sample format cpal/ffmpeg feed through here except U8 — and U8 device input
+/// is resampled to the F32 mixer format before reaching this point, so zeroed
+/// bytes are always true silence for the frames we emit.
+fn silence_frame_payload(frame: &mut ffmpeg::frame::Audio) {
+ for i in 0..frame.planes() {
+ frame.data_mut(i).fill(0);
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -817,6 +839,66 @@ mod tests {
}
}
+ #[test]
+ fn muted_frames_keep_geometry_but_zero_payload() {
+ use cap_timestamp::Timestamp;
+ use std::time::Instant;
+
+ let target = AudioInfo::new_raw(Sample::F32(Type::Packed), 48000, 1);
+ let mut resampler =
+ MicResampler::create(44100, 2, SampleFormat::F32, &target).expect("resampler");
+
+ const FRAME_SAMPLES: usize = 1024;
+ const CHANNELS: usize = 2;
+ let mut payload = Vec::with_capacity(FRAME_SAMPLES * CHANNELS * 4);
+ for i in 0..(FRAME_SAMPLES * CHANNELS) {
+ let value = 0.5f32 * ((i % 7) as f32 - 3.0);
+ payload.extend_from_slice(&value.to_le_bytes());
+ }
+
+ let ts_instant = Instant::now();
+ let ts = Timestamp::Instant(ts_instant);
+ let mut frame = None;
+ for _ in 0..4 {
+ if let Some(f) = resampler.resample(&payload, 44100, 2, SampleFormat::F32, ts) {
+ frame = Some(f);
+ }
+ }
+ let mut frame = frame.expect("resampler produced a frame");
+
+ let samples_before = frame.samples();
+ let rate_before = frame.rate();
+ assert!(samples_before > 0);
+
+ let had_energy = frame
+ .inner
+ .data(0)
+ .chunks_exact(4)
+ .take(samples_before)
+ .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
+ .any(|s| s.abs() > 0.001);
+ assert!(had_energy, "test signal should be non-silent before muting");
+
+ silence_frame_payload(&mut frame.inner);
+
+ // Muting must be a pure payload transformation: geometry, rate, and
+ // timestamp identical, every sample exactly zero.
+ assert_eq!(frame.samples(), samples_before);
+ assert_eq!(frame.rate(), rate_before);
+ match frame.timestamp {
+ Timestamp::Instant(i) => assert_eq!(i, ts_instant),
+ other => panic!("unexpected timestamp variant {other:?}"),
+ }
+ let all_zero = frame
+ .inner
+ .data(0)
+ .chunks_exact(4)
+ .take(frame.samples())
+ .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
+ .all(|s| s == 0.0);
+ assert!(all_zero, "muted frame must be exact digital silence");
+ }
+
#[test]
fn resampled_frame_timestamps_are_monotonic_and_unshifted() {
// Regression: timestamping resampled frames with `capture − swr_delay` pulled