Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix(recording): move macOS recording file writes off the capture and async paths
Richie McIlroy4ae45b5aff47
diff --git a/apps/cli/src/selftest/playback.rs b/apps/cli/src/selftest/playback.rsindex 57e997d94..4ba3d03f4 100644--- a/apps/cli/src/selftest/playback.rs+++ b/apps/cli/src/selftest/playback.rs@@ -571,7 +571,7 @@ mod fixture {use cap_recording::{AudioFrame, ChannelAudioSource, ChannelAudioSourceConfig, ChannelVideoSource,ChannelVideoSourceConfig, OutputPipeline,- ffmpeg::{FFmpegVideoFrame, Mp4Muxer, OggMuxer},+ ffmpeg::{FFmpegVideoFrame, Mp4Muxer, OggMuxer, OggMuxerConfig},};use cap_timestamp::{Timestamp, Timestamps};use relative_path::RelativePathBuf;@@ -783,7 +783,7 @@ mod fixture {audio_info, mic_rx,)).with_timestamps(timestamps)- .build::<OggMuxer>(())+ .build::<OggMuxer>(OggMuxerConfig::default()).await.map_err(|e| format!("mic pipeline: {e}"))?;let sys_pipeline = OutputPipeline::builder(audio_path.clone())@@ -794,7 +794,7 @@ mod fixture {// System audio anchors at the recording epoch, exactly like the// studio recorder configures it..with_audio_anchor(cap_recording::AudioAnchor::PipelineEpoch)- .build::<OggMuxer>(())+ .build::<OggMuxer>(OggMuxerConfig::default()).await.map_err(|e| format!("system audio pipeline: {e}"))?;diff --git a/crates/recording/examples/synthetic-test-runner.rs b/crates/recording/examples/synthetic-test-runner.rsindex f2ec2c355..8722e2235 100644--- a/crates/recording/examples/synthetic-test-runner.rs+++ b/crates/recording/examples/synthetic-test-runner.rs@@ -1,5 +1,6 @@use cap_recording::{- Mp4Muxer, OggMuxer, OutputPipeline, SegmentedVideoMuxer, SegmentedVideoMuxerConfig,+ Mp4Muxer, OggMuxer, OggMuxerConfig, OutputPipeline, SegmentedVideoMuxer,+ SegmentedVideoMuxerConfig,test_sources::{AudioGenerator, AudioTestConfig, OutputFormat, RecordingValidator, SyntheticAudioSource,SyntheticAudioSourceConfig, TestConfig, TestPattern, TestPatternVideoSource,@@ -468,7 +469,7 @@ async fn run_audio_only_ogg_recording(let pipeline = OutputPipeline::builder(output_path.to_path_buf()).with_timestamps(timestamps).with_audio_source::<SyntheticAudioSource>(audio_source_config)- .build::<OggMuxer>(())+ .build::<OggMuxer>(OggMuxerConfig::default()).await?;tokio::time::sleep(duration + Duration::from_millis(500)).await;diff --git a/crates/recording/src/instant_recording.rs b/crates/recording/src/instant_recording.rsindex 759025f1f..b0faf8aee 100644--- a/crates/recording/src/instant_recording.rs+++ b/crates/recording/src/instant_recording.rs@@ -810,6 +810,7 @@ async fn create_pipeline(output_pipeline::DashSegmentedAudioMuxerConfig {shared_pause_state: None,segment_tx: segment_tx_for_audio,+ write_behind: cfg!(target_os = "macos"),..Default::default()},)diff --git a/crates/recording/src/output_pipeline/ffmpeg.rs b/crates/recording/src/output_pipeline/ffmpeg.rsindex 1c2f6cbd0..26b6793ae 100644--- a/crates/recording/src/output_pipeline/ffmpeg.rs+++ b/crates/recording/src/output_pipeline/ffmpeg.rs@@ -141,11 +141,24 @@ impl AudioMuxer for Mp4Muxer {pub struct OggMuxer(OggFile);+/// `write_behind` moves file writes off the caller (an async runtime worker)+/// onto a dedicated writer thread. Only macOS recordings opt in.+#[derive(Default)]+pub struct OggMuxerConfig {+ pub write_behind: bool,+}++fn warn_inline_fallback(result: std::io::Result<()>) {+ if let Err(error) = result {+ warn!(%error, "Output write-behind unavailable, muxing inline");+ }+}+impl Muxer for OggMuxer {- type Config = ();+ type Config = OggMuxerConfig;async fn setup(- _: Self::Config,+ config: Self::Config,output_path: PathBuf,_: Option<VideoInfo>,audio_config: Option<AudioInfo>,@@ -158,10 +171,13 @@ impl Muxer for OggMuxer {let audio_config =audio_config.ok_or_else(|| anyhow!("No audio configuration provided"))?;- Ok(Self(- OggFile::init(output_path, |o| OpusEncoder::init(audio_config, o))- .map_err(|e| anyhow!("Failed to initialize Opus encoder: {e}"))?,- ))+ let mut file = OggFile::init(output_path, |o| OpusEncoder::init(audio_config, o))+ .map_err(|e| anyhow!("Failed to initialize Opus encoder: {e}"))?;+ if config.write_behind {+ warn_inline_fallback(file.enable_write_behind());+ }++ Ok(Self(file))}fn finish(&mut self, _: Duration) -> anyhow::Result<anyhow::Result<()>> {@@ -186,6 +202,8 @@ pub struct FragmentedAudioMuxer {#[derive(Default)]pub struct FragmentedAudioMuxerConfig {pub shared_pause_state: Option<SharedPauseState>,+ /// See [`OggMuxerConfig::write_behind`].+ pub write_behind: bool,}impl Muxer for FragmentedAudioMuxer {@@ -205,9 +223,14 @@ impl Muxer for FragmentedAudioMuxer {let audio_config =audio_config.ok_or_else(|| anyhow!("No audio configuration provided"))?;+ let mut encoder = FragmentedAudioFile::init(output_path, audio_config)+ .map_err(|e| anyhow!("Failed to initialize fragmented audio encoder: {e}"))?;+ if config.write_behind {+ warn_inline_fallback(encoder.enable_write_behind());+ }+Ok(Self {- encoder: FragmentedAudioFile::init(output_path, audio_config)- .map_err(|e| anyhow!("Failed to initialize fragmented audio encoder: {e}"))?,+ encoder,pause: config.shared_pause_state,})}@@ -817,6 +840,8 @@ pub struct DashSegmentedAudioMuxerConfig {pub segment_duration: Duration,pub shared_pause_state: Option<SharedPauseState>,pub segment_tx: Option<std::sync::mpsc::Sender<SegmentCompletedEvent>>,+ /// See [`OggMuxerConfig::write_behind`].+ pub write_behind: bool,}impl Default for DashSegmentedAudioMuxerConfig {@@ -825,6 +850,7 @@ impl Default for DashSegmentedAudioMuxerConfig {segment_duration: Duration::from_secs(3),shared_pause_state: None,segment_tx: None,+ write_behind: false,}}}@@ -854,6 +880,9 @@ impl Muxer for DashSegmentedAudioMuxer {},).map_err(|e| anyhow!("Failed to initialize DASH audio segment encoder: {e}"))?;+ if config.write_behind {+ warn_inline_fallback(encoder.enable_write_behind());+ }if let Some(tx) = config.segment_tx {encoder.set_segment_callback(tx);@@ -899,6 +928,76 @@ mod tests {use cap_timestamp::Timestamp;use std::time::Instant;+ mod write_behind_opt_in {+ use super::super::{+ DashSegmentedAudioMuxer, DashSegmentedAudioMuxerConfig, FragmentedAudioMuxer,+ FragmentedAudioMuxerConfig, OggMuxer, OggMuxerConfig,+ };+ use crate::{Muxer, TaskPool};+ use cap_media_info::AudioInfo;+ use std::sync::{Arc, atomic::AtomicBool};++ fn audio_info() -> AudioInfo {+ AudioInfo::new_raw(+ ffmpeg::format::Sample::F32(ffmpeg::format::sample::Type::Packed),+ 48_000,+ 1,+ )+ }++ async fn setup<M: Muxer>(config: M::Config, path: std::path::PathBuf) -> M {+ M::setup(+ config,+ path,+ None,+ Some(audio_info()),+ Arc::new(AtomicBool::new(false)),+ &mut TaskPool::default(),+ )+ .await+ .unwrap()+ }++ #[test]+ fn audio_muxers_write_inline_unless_the_call_site_opts_in() {+ assert!(!FragmentedAudioMuxerConfig::default().write_behind);+ assert!(!DashSegmentedAudioMuxerConfig::default().write_behind);+ assert!(!OggMuxerConfig::default().write_behind);+ }++ #[tokio::test]+ async fn audio_muxers_honour_the_write_behind_flag() {+ ffmpeg::init().unwrap();+ let directory = tempfile::tempdir().unwrap();+ for write_behind in [false, true] {+ let dir = directory.path().join(write_behind.to_string());+ let fragmented = setup::<FragmentedAudioMuxer>(+ FragmentedAudioMuxerConfig {+ shared_pause_state: None,+ write_behind,+ },+ dir.join("audio.m4a"),+ )+ .await;+ assert_eq!(fragmented.encoder.is_write_behind(), write_behind);++ let dash = setup::<DashSegmentedAudioMuxer>(+ DashSegmentedAudioMuxerConfig {+ write_behind,+ ..Default::default()+ },+ dir.join("audio"),+ )+ .await;+ assert_eq!(dash.encoder.is_write_behind(), write_behind);++ let ogg =+ setup::<OggMuxer>(OggMuxerConfig { write_behind }, dir.join("audio.ogg")).await;+ assert_eq!(ogg.0.is_write_behind(), write_behind);+ }+ }+ }+#[test]fn segmented_encoder_preserves_frames_when_a_full_queue_recovers() {let (sender, receiver) = flume::bounded(1);diff --git a/crates/recording/src/output_pipeline/macos_fragmented_m4s.rs b/crates/recording/src/output_pipeline/macos_fragmented_m4s.rsindex 6c490b64e..52a2ca06d 100644--- a/crates/recording/src/output_pipeline/macos_fragmented_m4s.rs+++ b/crates/recording/src/output_pipeline/macos_fragmented_m4s.rs@@ -295,8 +295,11 @@ impl MacOSFragmentedM4SMuxer {prefer_videotoolbox_hw_input: true,};- let mut encoder =- SegmentedVideoEncoder::init(self.base_path.clone(), self.video_config, encoder_config)?;+ let mut encoder = SegmentedVideoEncoder::init_write_behind(+ self.base_path.clone(),+ self.video_config,+ encoder_config,+ )?;if let Some(callback) = &self.disk_space_callback {encoder.set_disk_space_callback(callback.clone());}@@ -682,8 +685,11 @@ impl MacOSFragmentedM4SCameraMuxer {prefer_videotoolbox_hw_input: false,};- let mut encoder =- SegmentedVideoEncoder::init(self.base_path.clone(), self.video_config, encoder_config)?;+ let mut encoder = SegmentedVideoEncoder::init_write_behind(+ self.base_path.clone(),+ self.video_config,+ encoder_config,+ )?;if let Some(callback) = &self.disk_space_callback {encoder.set_disk_space_callback(callback.clone());}diff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rsindex 4917df973..8730061e0 100644--- a/crates/recording/src/studio_recording.rs+++ b/crates/recording/src/studio_recording.rs@@ -16,7 +16,7 @@ use crate::{CursorActor, CursorActorResponse, Cursors, IncrementalCaptureOutputs, spawn_cursor_recorder,},feeds::{camera::CameraFeedLock, microphone::MicrophoneFeedLock},- ffmpeg::{FragmentedAudioMuxer, FragmentedAudioMuxerConfig, OggMuxer},+ ffmpeg::{FragmentedAudioMuxer, FragmentedAudioMuxerConfig, OggMuxer, OggMuxerConfig},output_pipeline::{AudioAnchor, AudioGapSummary, DoneFut, FinishedOutputPipeline, OutputPipeline,PipelineDoneError,@@ -3436,6 +3436,7 @@ async fn create_segment_pipeline(.with_start_gate(start_gate.clone()).build::<FragmentedAudioMuxer>(FragmentedAudioMuxerConfig {shared_pause_state: shared_pause_state.clone(),+ write_behind: cfg!(target_os = "macos"),}).instrument(error_span!("mic-out")).await@@ -3444,7 +3445,9 @@ async fn create_segment_pipeline(.with_audio_source::<sources::Microphone>(mic_feed).with_timestamps(start_time).with_start_gate(start_gate.clone())- .build::<OggMuxer>(())+ .build::<OggMuxer>(OggMuxerConfig {+ write_behind: cfg!(target_os = "macos"),+ }).instrument(error_span!("mic-out")).await};@@ -3468,6 +3471,7 @@ async fn create_segment_pipeline(.with_audio_anchor(AudioAnchor::PipelineEpoch).build::<FragmentedAudioMuxer>(FragmentedAudioMuxerConfig {shared_pause_state: shared_pause_state.clone(),+ write_behind: cfg!(target_os = "macos"),}).instrument(error_span!("system-audio-out")).await@@ -3477,7 +3481,9 @@ async fn create_segment_pipeline(.with_timestamps(start_time).with_start_gate(start_gate.clone()).with_audio_anchor(AudioAnchor::PipelineEpoch)- .build::<OggMuxer>(())+ .build::<OggMuxer>(OggMuxerConfig {+ write_behind: cfg!(target_os = "macos"),+ }).instrument(error_span!("system-audio-out")).await};diff --git a/crates/recording/tests/sync_matrix.rs b/crates/recording/tests/sync_matrix.rsindex f321266bd..1db057022 100644--- a/crates/recording/tests/sync_matrix.rs+++ b/crates/recording/tests/sync_matrix.rs@@ -22,7 +22,8 @@ use cap_recording::{AudioFrame, ChannelAudioSource, ChannelAudioSourceConfig, ChannelVideoSource,ChannelVideoSourceConfig, OutputPipeline,ffmpeg::{- FFmpegVideoFrame, Mp4Muxer, OggMuxer, SegmentedVideoMuxer, SegmentedVideoMuxerConfig,+ FFmpegVideoFrame, Mp4Muxer, OggMuxer, OggMuxerConfig, SegmentedVideoMuxer,+ SegmentedVideoMuxerConfig,},};use cap_timestamp::{Timestamp, Timestamps};@@ -767,7 +768,7 @@ async fn run_audio_case(case: AudioCase) -> Result<String, String> {let pipeline = OutputPipeline::builder(out_path.clone()).with_audio_source::<ChannelAudioSource>(ChannelAudioSourceConfig::new(info, rx)).with_timestamps(timestamps)- .build::<OggMuxer>(())+ .build::<OggMuxer>(OggMuxerConfig::default()).await.map_err(|e| format!("pipeline build: {e}"))?;@@ -996,7 +997,7 @@ async fn run_system_audio_case(case: SystemAudioCase) -> Result<String, String>.with_audio_source::<ChannelAudioSource>(ChannelAudioSourceConfig::new(info, rx)).with_timestamps(timestamps).with_audio_anchor(AudioAnchor::PipelineEpoch)- .build::<OggMuxer>(())+ .build::<OggMuxer>(OggMuxerConfig::default()).await.map_err(|e| format!("pipeline build: {e}"))?;@@ -1078,14 +1079,14 @@ async fn run_mic_with_system_audio_case() -> Result<String, String> {let mic_pipeline = OutputPipeline::builder(mic_path.clone()).with_audio_source::<ChannelAudioSource>(ChannelAudioSourceConfig::new(info, mic_rx)).with_timestamps(timestamps)- .build::<OggMuxer>(())+ .build::<OggMuxer>(OggMuxerConfig::default()).await.map_err(|e| format!("mic pipeline build: {e}"))?;let sys_pipeline = OutputPipeline::builder(sys_path.clone()).with_audio_source::<ChannelAudioSource>(ChannelAudioSourceConfig::new(info, sys_rx)).with_timestamps(timestamps).with_audio_anchor(AudioAnchor::PipelineEpoch)- .build::<OggMuxer>(())+ .build::<OggMuxer>(OggMuxerConfig::default()).await.map_err(|e| format!("system pipeline build: {e}"))?;