Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
Fix audio sync in fragmented m4s
Richie McIlroy9b03f4ed1b57
diff --git a/crates/recording/src/capture_pipeline.rs b/crates/recording/src/capture_pipeline.rsindex d5575bc84..7f745d347 100644--- a/crates/recording/src/capture_pipeline.rs+++ b/crates/recording/src/capture_pipeline.rs@@ -1,4 +1,5 @@use crate::{+ SharedPauseState,feeds::microphone::MicrophoneFeedLock,output_pipeline::*,sources,@@ -50,6 +51,7 @@ pub trait MakeCapturePipeline: ScreenCaptureFormat + std::fmt::Debug + 'static {output_path: PathBuf,start_time: Timestamps,fragmented: bool,+ shared_pause_state: Option<SharedPauseState>,#[cfg(windows)] encoder_preferences: EncoderPreferences,) -> anyhow::Result<OutputPipeline>where@@ -76,6 +78,7 @@ impl MakeCapturePipeline for screen_capture::CMSampleBufferCapture {output_path: PathBuf,start_time: Timestamps,fragmented: bool,+ shared_pause_state: Option<SharedPauseState>,) -> anyhow::Result<OutputPipeline> {if fragmented {let fragments_dir = output_path@@ -86,7 +89,10 @@ impl MakeCapturePipeline for screen_capture::CMSampleBufferCapture {OutputPipeline::builder(fragments_dir).with_video::<screen_capture::VideoSource>(screen_capture).with_timestamps(start_time)- .build::<MacOSFragmentedM4SMuxer>(MacOSFragmentedM4SMuxerConfig::default())+ .build::<MacOSFragmentedM4SMuxer>(MacOSFragmentedM4SMuxerConfig {+ shared_pause_state,+ ..Default::default()+ }).await} else {OutputPipeline::builder(output_path.clone())@@ -130,6 +136,7 @@ impl MakeCapturePipeline for screen_capture::Direct3DCapture {output_path: PathBuf,start_time: Timestamps,fragmented: bool,+ _shared_pause_state: Option<SharedPauseState>,encoder_preferences: EncoderPreferences,) -> anyhow::Result<OutputPipeline> {let d3d_device = screen_capture.d3d_device.clone();diff --git a/crates/recording/src/output_pipeline/core.rs b/crates/recording/src/output_pipeline/core.rsindex 0946b8b1b..13aca3ce2 100644--- a/crates/recording/src/output_pipeline/core.rs+++ b/crates/recording/src/output_pipeline/core.rs@@ -17,7 +17,7 @@ use std::{path::{Path, PathBuf},sync::{Arc,- atomic::{self, AtomicBool},+ atomic::{self, AtomicBool, Ordering},},time::Duration,};@@ -25,6 +25,67 @@ use tokio::task::JoinHandle;use tokio_util::sync::{CancellationToken, DropGuard};use tracing::*;+struct SharedPauseStateInner {+ paused_at: Option<Duration>,+ offset: Duration,+}++#[derive(Clone)]+pub struct SharedPauseState {+ flag: Arc<AtomicBool>,+ inner: Arc<std::sync::Mutex<SharedPauseStateInner>>,+}++impl SharedPauseState {+ pub fn new(flag: Arc<AtomicBool>) -> Self {+ Self {+ flag,+ inner: Arc::new(std::sync::Mutex::new(SharedPauseStateInner {+ paused_at: None,+ offset: Duration::ZERO,+ })),+ }+ }++ pub fn adjust(&self, timestamp: Duration) -> anyhow::Result<Option<Duration>> {+ let mut inner = self+ .inner+ .lock()+ .map_err(|e| anyhow!("Lock poisoned: {e}"))?;++ if self.flag.load(Ordering::Relaxed) {+ if inner.paused_at.is_none() {+ inner.paused_at = Some(timestamp);+ }+ return Ok(None);+ }++ if let Some(start) = inner.paused_at.take() {+ let delta = timestamp.checked_sub(start).ok_or_else(|| {+ anyhow!(+ "Frame timestamp went backward during unpause (resume={start:?}, current={timestamp:?})"+ )+ })?;++ inner.offset = inner.offset.checked_add(delta).ok_or_else(|| {+ anyhow!(+ "Pause offset overflow (offset={:?}, delta={delta:?})",+ inner.offset+ )+ })?;+ }++ let adjusted = timestamp.checked_sub(inner.offset).ok_or_else(|| {+ anyhow!(+ "Adjusted timestamp underflow (timestamp={timestamp:?}, offset={:?})",+ inner.offset+ )+ })?;++ Ok(Some(adjusted))+ }+}+pub struct OnceSender<T>(Option<oneshot::Sender<T>>);impl<T> OnceSender<T> {diff --git a/crates/recording/src/output_pipeline/ffmpeg.rs b/crates/recording/src/output_pipeline/ffmpeg.rsindex 1c8e2fe69..8e9439331 100644--- a/crates/recording/src/output_pipeline/ffmpeg.rs+++ b/crates/recording/src/output_pipeline/ffmpeg.rs@@ -1,5 +1,5 @@use crate::{- TaskPool,+ SharedPauseState, TaskPool,output_pipeline::{AudioFrame, AudioMuxer, Muxer, VideoFrame, VideoMuxer},};use anyhow::{Context, anyhow};@@ -197,16 +197,21 @@ impl AudioMuxer for FragmentedAudioMuxer {}}-pub struct SegmentedAudioMuxer(SegmentedAudioEncoder);+pub struct SegmentedAudioMuxer {+ encoder: SegmentedAudioEncoder,+ pause: Option<SharedPauseState>,+}pub struct SegmentedAudioMuxerConfig {pub segment_duration: Duration,+ pub shared_pause_state: Option<SharedPauseState>,}impl Default for SegmentedAudioMuxerConfig {fn default() -> Self {Self {segment_duration: Duration::from_secs(3),+ shared_pause_state: None,}}}@@ -228,14 +233,19 @@ impl Muxer for SegmentedAudioMuxer {let audio_config =audio_config.ok_or_else(|| anyhow!("No audio configuration provided"))?;- Ok(Self(- SegmentedAudioEncoder::init(output_path, audio_config, config.segment_duration)- .map_err(|e| anyhow!("Failed to initialize segmented audio encoder: {e}"))?,- ))+ Ok(Self {+ encoder: SegmentedAudioEncoder::init(+ output_path,+ audio_config,+ config.segment_duration,+ )+ .map_err(|e| anyhow!("Failed to initialize segmented audio encoder: {e}"))?,+ pause: config.shared_pause_state,+ })}fn finish(&mut self, timestamp: Duration) -> anyhow::Result<anyhow::Result<()>> {- self.0+ self.encoder.finish_with_timestamp(timestamp).map_err(Into::into).map(|_| Ok(()))@@ -244,8 +254,17 @@ impl Muxer for SegmentedAudioMuxer {impl AudioMuxer for SegmentedAudioMuxer {fn send_audio_frame(&mut self, frame: AudioFrame, timestamp: Duration) -> anyhow::Result<()> {- self.0- .queue_frame(frame.inner, timestamp)+ let adjusted_timestamp = if let Some(pause) = &self.pause {+ match pause.adjust(timestamp)? {+ Some(ts) => ts,+ None => return Ok(()),+ }+ } else {+ timestamp+ };++ self.encoder+ .queue_frame(frame.inner, adjusted_timestamp).map_err(|e| anyhow!("Failed to queue audio frame: {e}"))}}diff --git a/crates/recording/src/output_pipeline/macos_fragmented_m4s.rs b/crates/recording/src/output_pipeline/macos_fragmented_m4s.rsindex 484171588..b091b9278 100644--- a/crates/recording/src/output_pipeline/macos_fragmented_m4s.rs+++ b/crates/recording/src/output_pipeline/macos_fragmented_m4s.rs@@ -1,6 +1,6 @@use crate::{- AudioFrame, AudioMuxer, Muxer, TaskPool, VideoMuxer, output_pipeline::NativeCameraFrame,- screen_capture,+ AudioFrame, AudioMuxer, Muxer, SharedPauseState, TaskPool, VideoMuxer,+ output_pipeline::NativeCameraFrame, screen_capture,};use anyhow::{Context, anyhow};use cap_enc_ffmpeg::h264::{H264EncoderBuilder, H264Preset};@@ -10,7 +10,7 @@ use std::{path::PathBuf,sync::{Arc, Mutex,- atomic::{AtomicBool, Ordering},+ atomic::AtomicBool,mpsc::{SyncSender, sync_channel},},thread::JoinHandle,@@ -25,55 +25,6 @@ fn get_muxer_buffer_size() -> usize {.unwrap_or(3)}-struct PauseTracker {- flag: Arc<AtomicBool>,- paused_at: Option<Duration>,- offset: Duration,-}--impl PauseTracker {- fn new(flag: Arc<AtomicBool>) -> Self {- Self {- flag,- paused_at: None,- offset: Duration::ZERO,- }- }-- fn adjust(&mut self, timestamp: Duration) -> anyhow::Result<Option<Duration>> {- if self.flag.load(Ordering::Relaxed) {- if self.paused_at.is_none() {- self.paused_at = Some(timestamp);- }- return Ok(None);- }-- if let Some(start) = self.paused_at.take() {- let delta = timestamp.checked_sub(start).ok_or_else(|| {- anyhow!(- "Frame timestamp went backward during unpause (resume={start:?}, current={timestamp:?})"- )- })?;-- self.offset = self.offset.checked_add(delta).ok_or_else(|| {- anyhow!(- "Pause offset overflow (offset={:?}, delta={delta:?})",- self.offset- )- })?;- }-- let adjusted = timestamp.checked_sub(self.offset).ok_or_else(|| {- anyhow!(- "Adjusted timestamp underflow (timestamp={timestamp:?}, offset={:?})",- self.offset- )- })?;-- Ok(Some(adjusted))- }-}-struct FrameDropTracker {drops_in_window: u32,frames_in_window: u32,@@ -146,7 +97,7 @@ pub struct MacOSFragmentedM4SMuxer {video_config: VideoInfo,segment_duration: Duration,state: Option<EncoderState>,- pause: PauseTracker,+ pause: SharedPauseState,frame_drops: FrameDropTracker,started: bool,}@@ -155,6 +106,7 @@ pub struct MacOSFragmentedM4SMuxerConfig {pub segment_duration: Duration,pub preset: H264Preset,pub output_size: Option<(u32, u32)>,+ pub shared_pause_state: Option<SharedPauseState>,}impl Default for MacOSFragmentedM4SMuxerConfig {@@ -163,6 +115,7 @@ impl Default for MacOSFragmentedM4SMuxerConfig {segment_duration: Duration::from_secs(3),preset: H264Preset::Ultrafast,output_size: None,+ shared_pause_state: None,}}}@@ -187,12 +140,16 @@ impl Muxer for MacOSFragmentedM4SMuxer {std::fs::create_dir_all(&output_path).with_context(|| format!("Failed to create segments directory: {output_path:?}"))?;+ let pause = config+ .shared_pause_state+ .unwrap_or_else(|| SharedPauseState::new(pause_flag));+Ok(Self {base_path: output_path,video_config,segment_duration: config.segment_duration,state: None,- pause: PauseTracker::new(pause_flag),+ pause,frame_drops: FrameDropTracker::new(),started: false,})@@ -602,7 +559,7 @@ pub struct MacOSFragmentedM4SCameraMuxer {video_config: VideoInfo,segment_duration: Duration,state: Option<EncoderState>,- pause: PauseTracker,+ pause: SharedPauseState,frame_drops: FrameDropTracker,started: bool,}@@ -611,6 +568,7 @@ pub struct MacOSFragmentedM4SCameraMuxerConfig {pub segment_duration: Duration,pub preset: H264Preset,pub output_size: Option<(u32, u32)>,+ pub shared_pause_state: Option<SharedPauseState>,}impl Default for MacOSFragmentedM4SCameraMuxerConfig {@@ -619,6 +577,7 @@ impl Default for MacOSFragmentedM4SCameraMuxerConfig {segment_duration: Duration::from_secs(3),preset: H264Preset::Ultrafast,output_size: None,+ shared_pause_state: None,}}}@@ -644,12 +603,16 @@ impl Muxer for MacOSFragmentedM4SCameraMuxer {format!("Failed to create camera segments directory: {output_path:?}")})?;+ let pause = config+ .shared_pause_state+ .unwrap_or_else(|| SharedPauseState::new(pause_flag));+Ok(Self {base_path: output_path,video_config,segment_duration: config.segment_duration,state: None,- pause: PauseTracker::new(pause_flag),+ pause,frame_drops: FrameDropTracker::new(),started: false,})diff --git a/crates/recording/src/recovery.rs b/crates/recording/src/recovery.rsindex 96f24578b..c6512dac1 100644--- a/crates/recording/src/recovery.rs+++ b/crates/recording/src/recovery.rs@@ -766,6 +766,11 @@ impl RecoveryManager {fn build_recovered_meta(recording: &IncompleteRecording,) -> Result<StudioRecordingMeta, RecoveryError> {+ let original_segments = match recording.meta.studio_meta() {+ Some(StudioRecordingMeta::MultipleSegments { inner, .. }) => Some(&inner.segments),+ _ => None,+ };+let segments: Vec<MultipleSegment> = recording.recoverable_segments.iter()@@ -774,6 +779,9 @@ impl RecoveryManager {let segment_base = format!("content/segments/segment-{segment_index}");let segment_dir = recording.project_path.join(&segment_base);+ let original_segment =+ original_segments.and_then(|segs| segs.get(segment_index as usize));+let display_path = segment_dir.join("display.mp4");let fps = get_video_fps(&display_path).unwrap_or(30);@@ -786,13 +794,18 @@ impl RecoveryManager {display: VideoMeta {path: RelativePathBuf::from(format!("{segment_base}/display.mp4")),fps,- start_time: None,+ start_time: original_segment.and_then(|s| s.display.start_time),},camera: if camera_path.exists() {Some(VideoMeta {path: RelativePathBuf::from(format!("{segment_base}/camera.mp4")),- fps: 30,- start_time: None,+ fps: original_segment+ .and_then(|s| s.camera.as_ref())+ .map(|c| c.fps)+ .unwrap_or(30),+ start_time: original_segment+ .and_then(|s| s.camera.as_ref())+ .and_then(|c| c.start_time),})} else {None@@ -800,7 +813,9 @@ impl RecoveryManager {mic: if mic_path.exists() {Some(AudioMeta {path: RelativePathBuf::from(format!("{segment_base}/audio-input.ogg")),- start_time: None,+ start_time: original_segment+ .and_then(|s| s.mic.as_ref())+ .and_then(|m| m.start_time),})} else {None@@ -808,7 +823,9 @@ impl RecoveryManager {system_audio: if system_audio_path.exists() {Some(AudioMeta {path: RelativePathBuf::from(format!("{segment_base}/system_audio.ogg")),- start_time: None,+ start_time: original_segment+ .and_then(|s| s.system_audio.as_ref())+ .and_then(|a| a.start_time),})} else {Nonediff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rsindex f93ab0c87..ae2f50a6e 100644--- a/crates/recording/src/studio_recording.rs+++ b/crates/recording/src/studio_recording.rs@@ -1,5 +1,5 @@use crate::{- ActorError, MediaError, RecordingBaseInputs, RecordingError,+ ActorError, MediaError, RecordingBaseInputs, RecordingError, SharedPauseState,capture_pipeline::{MakeCapturePipeline, ScreenCaptureMethod, Stop, target_to_display_and_crop,},@@ -626,11 +626,8 @@ async fn stop_recording(let segment_metas: Vec<_> = futures::stream::iter(segments).then(async |s| {- let to_start_time = |timestamp: Timestamp| {- timestamp- .duration_since(s.pipeline.start_time)- .as_secs_f64()- };+ let to_start_time =+ |timestamp: Timestamp| timestamp.signed_duration_since_secs(s.pipeline.start_time);MultipleSegment {display: VideoMeta {@@ -870,11 +867,24 @@ async fn create_segment_pipeline(trace!("preparing segment pipeline {index}");+ #[cfg(target_os = "macos")]+ let shared_pause_state = if fragmented {+ Some(SharedPauseState::new(Arc::new(+ std::sync::atomic::AtomicBool::new(false),+ )))+ } else {+ None+ };++ #[cfg(windows)]+ let shared_pause_state: Option<SharedPauseState> = None;+let screen = ScreenCaptureMethod::make_studio_mode_pipeline(capture_source,screen_output_path.clone(),start_time,fragmented,+ shared_pause_state.clone(),#[cfg(windows)]encoder_preferences.clone(),)@@ -889,9 +899,10 @@ async fn create_segment_pipeline(OutputPipeline::builder(fragments_dir).with_video::<sources::NativeCamera>(camera_feed).with_timestamps(start_time)- .build::<MacOSFragmentedM4SCameraMuxer>(- MacOSFragmentedM4SCameraMuxerConfig::default(),- )+ .build::<MacOSFragmentedM4SCameraMuxer>(MacOSFragmentedM4SCameraMuxerConfig {+ shared_pause_state: shared_pause_state.clone(),+ ..Default::default()+ }).instrument(error_span!("camera-out")).await} else {@@ -942,7 +953,10 @@ async fn create_segment_pipeline(OutputPipeline::builder(fragments_dir).with_audio_source::<sources::Microphone>(mic_feed).with_timestamps(start_time)- .build::<SegmentedAudioMuxer>(SegmentedAudioMuxerConfig::default())+ .build::<SegmentedAudioMuxer>(SegmentedAudioMuxerConfig {+ shared_pause_state: shared_pause_state.clone(),+ ..Default::default()+ }).instrument(error_span!("mic-out")).await} else {@@ -964,7 +978,10 @@ async fn create_segment_pipeline(OutputPipeline::builder(fragments_dir).with_audio_source::<screen_capture::SystemAudioSource>(system_audio_source).with_timestamps(start_time)- .build::<SegmentedAudioMuxer>(SegmentedAudioMuxerConfig::default())+ .build::<SegmentedAudioMuxer>(SegmentedAudioMuxerConfig {+ shared_pause_state: shared_pause_state.clone(),+ ..Default::default()+ }).instrument(error_span!("system-audio-out")).await} else {diff --git a/crates/timestamp/src/lib.rs b/crates/timestamp/src/lib.rsindex 47b4b1901..4a37b8295 100644--- a/crates/timestamp/src/lib.rs+++ b/crates/timestamp/src/lib.rs@@ -45,6 +45,31 @@ impl Timestamp {}}+ pub fn signed_duration_since_secs(&self, start: Timestamps) -> f64 {+ match self {+ Self::Instant(instant) => {+ if let Some(duration) = instant.checked_duration_since(start.instant) {+ duration.as_secs_f64()+ } else {+ let reverse = start.instant.duration_since(*instant);+ -(reverse.as_secs_f64())+ }+ }+ Self::SystemTime(time) => match time.duration_since(start.system_time) {+ Ok(duration) => duration.as_secs_f64(),+ Err(e) => -(e.duration().as_secs_f64()),+ },+ #[cfg(windows)]+ Self::PerformanceCounter(counter) => {+ counter.signed_duration_since_secs(start.performance_counter)+ }+ #[cfg(target_os = "macos")]+ Self::MachAbsoluteTime(time) => {+ time.signed_duration_since_secs(start.mach_absolute_time)+ }+ }+ }+pub fn from_cpal(instant: cpal::StreamInstant) -> Self {#[cfg(windows)]{diff --git a/crates/timestamp/src/macos.rs b/crates/timestamp/src/macos.rsindex b72653350..0a2e0539d 100644--- a/crates/timestamp/src/macos.rs+++ b/crates/timestamp/src/macos.rs@@ -39,6 +39,19 @@ impl MachAbsoluteTimestamp {Some(Duration::from_nanos((diff as f64 * freq) as u64))}+ pub fn signed_duration_since_secs(&self, other: Self) -> f64 {+ let info = TimeBaseInfo::new();+ let freq = info.numer as f64 / info.denom as f64;++ let nanos = if self.0 >= other.0 {+ ((self.0 - other.0) as f64 * freq) as i64+ } else {+ -(((other.0 - self.0) as f64 * freq) as i64)+ };++ nanos as f64 / 1_000_000_000.0+ }+pub fn from_cpal(instant: cpal::StreamInstant) -> Self {use cpal::host::coreaudio::StreamInstantExt;diff --git a/crates/timestamp/src/win.rs b/crates/timestamp/src/win.rsindex d3efe2d44..8a111489b 100644--- a/crates/timestamp/src/win.rs+++ b/crates/timestamp/src/win.rs@@ -65,6 +65,12 @@ impl PerformanceCounterTimestamp {}}+ pub fn signed_duration_since_secs(&self, other: Self) -> f64 {+ let freq = perf_freq() as f64;+ let diff = self.0 as f64 - other.0 as f64;+ diff / freq+ }+pub fn now() -> Self {let mut value = 0;unsafe { QueryPerformanceCounter(&mut value).unwrap() };