Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Improve audio drift correction and error handling

Richie McIlroy794dd9fffd21
diff --git a/crates/enc-avfoundation/src/mp4.rs b/crates/enc-avfoundation/src/mp4.rs
index ab7ee8f17..fce29a2de 100644
--- a/crates/enc-avfoundation/src/mp4.rs
+++ b/crates/enc-avfoundation/src/mp4.rs
@@ -25,6 +25,7 @@ pub struct MP4Encoder {
timestamp_offset: Duration,
is_writing: bool,
is_paused: bool,
+ writer_failed: bool,
video_frames_appended: usize,
audio_frames_appended: usize,
last_timestamp: Option<Duration>,
@@ -272,6 +273,7 @@ impl MP4Encoder {
timestamp_offset: Duration::ZERO,
is_writing: false,
is_paused: false,
+ writer_failed: false,
video_frames_appended: 0,
audio_frames_appended: 0,
last_timestamp: None,
@@ -285,6 +287,10 @@ impl MP4Encoder {
frame: arc::R<cm::SampleBuf>,
timestamp: Duration,
) -> Result<(), QueueFrameError> {
+ if self.writer_failed {
+ return Err(QueueFrameError::Failed);
+ }
+
if self.is_paused {
return Ok(());
};
@@ -344,7 +350,14 @@ impl MP4Encoder {
let new_frame = frame.copy_with_new_timing(&[timing]).unwrap();
drop(frame);
- append_sample_buf(&mut self.video_input, &self.asset_writer, &new_frame)?;
+ match append_sample_buf(&mut self.video_input, &self.asset_writer, &new_frame) {
+ Ok(()) => {}
+ Err(QueueFrameError::WriterFailed(err)) => {
+ self.writer_failed = true;
+ return Err(QueueFrameError::WriterFailed(err));
+ }
+ Err(e) => return Err(e),
+ }
self.video_frames_appended += 1;
self.last_timestamp = Some(timestamp);
@@ -357,6 +370,10 @@ impl MP4Encoder {
frame: &frame::Audio,
timestamp: Duration,
) -> Result<(), QueueFrameError> {
+ if self.writer_failed {
+ return Err(QueueFrameError::Failed);
+ }
+
if self.is_paused || !self.is_writing {
return Ok(());
}
@@ -498,7 +515,14 @@ impl MP4Encoder {
)
.map_err(QueueFrameError::Construct)?;
- append_sample_buf(audio_input, &self.asset_writer, &buffer)?;
+ match append_sample_buf(audio_input, &self.asset_writer, &buffer) {
+ Ok(()) => {}
+ Err(QueueFrameError::WriterFailed(err)) => {
+ self.writer_failed = true;
+ return Err(QueueFrameError::WriterFailed(err));
+ }
+ Err(e) => return Err(e),
+ }
self.audio_frames_appended += 1;
self.last_timestamp = Some(timestamp);
@@ -756,18 +780,31 @@ fn append_sample_buf(
writer: &av::AssetWriter,
frame: &cm::SampleBuf,
) -> Result<(), QueueFrameError> {
+ let status = writer.status();
+ if status == av::asset::writer::Status::Failed {
+ return Err(match writer.error() {
+ Some(err) => QueueFrameError::WriterFailed(err),
+ None => QueueFrameError::Failed,
+ });
+ }
+ if status != av::asset::writer::Status::Writing {
+ return Err(QueueFrameError::Failed);
+ }
+
match input.append_sample_buf(frame) {
Ok(true) => {}
Ok(false) => {
- if writer.status() == av::asset::writer::Status::Failed {
+ let status = writer.status();
+ if status == av::asset::writer::Status::Failed {
return Err(match writer.error() {
Some(err) => QueueFrameError::WriterFailed(err),
None => QueueFrameError::Failed,
});
}
- if writer.status() == av::asset::writer::Status::Writing {
+ if status == av::asset::writer::Status::Writing {
return Err(QueueFrameError::NotReadyForMore);
}
+ return Err(QueueFrameError::Failed);
}
Err(e) => return Err(QueueFrameError::AppendError(e.retained())),
}
diff --git a/crates/recording/src/output_pipeline/core.rs b/crates/recording/src/output_pipeline/core.rs
index cdc7e0b54..5e4409697 100644
--- a/crates/recording/src/output_pipeline/core.rs
+++ b/crates/recording/src/output_pipeline/core.rs
@@ -35,6 +35,7 @@ struct AudioTimestampGenerator {
}
const VIDEO_WALL_CLOCK_TOLERANCE_SECS: f64 = 0.1;
+const AUDIO_WALL_CLOCK_TOLERANCE_SECS: f64 = 0.05;
impl AudioTimestampGenerator {
fn new(sample_rate: u32) -> Self {
@@ -51,6 +52,84 @@ impl AudioTimestampGenerator {
}
}
+struct AudioDriftTracker {
+ baseline_offset_secs: Option<f64>,
+ drift_warning_logged: bool,
+ last_corrected_secs: f64,
+}
+
+impl AudioDriftTracker {
+ fn new() -> Self {
+ Self {
+ baseline_offset_secs: None,
+ drift_warning_logged: false,
+ last_corrected_secs: 0.0,
+ }
+ }
+
+ fn calculate_timestamp(
+ &mut self,
+ sample_based_duration: Duration,
+ wall_clock_elapsed: Duration,
+ ) -> Duration {
+ let sample_secs = sample_based_duration.as_secs_f64();
+ let wall_clock_secs = wall_clock_elapsed.as_secs_f64();
+ let max_allowed_secs = wall_clock_secs + AUDIO_WALL_CLOCK_TOLERANCE_SECS;
+
+ if wall_clock_secs < 2.0 || sample_secs < 2.0 {
+ let result_secs = sample_secs
+ .min(max_allowed_secs)
+ .max(self.last_corrected_secs);
+ self.last_corrected_secs = result_secs;
+ return Duration::from_secs_f64(result_secs);
+ }
+
+ if self.baseline_offset_secs.is_none() {
+ let offset = sample_secs - wall_clock_secs;
+ debug!(
+ wall_clock_secs,
+ sample_secs,
+ baseline_offset_secs = offset,
+ "AudioDriftTracker: Capturing baseline offset after warmup"
+ );
+ self.baseline_offset_secs = Some(offset);
+ }
+
+ let baseline = self.baseline_offset_secs.unwrap_or(0.0);
+ let adjusted_sample_secs = (sample_secs - baseline).max(0.0);
+
+ let drift_ratio = if adjusted_sample_secs > 0.0 {
+ wall_clock_secs / adjusted_sample_secs
+ } else {
+ 1.0
+ };
+
+ let corrected_secs = if !(0.95..=1.05).contains(&drift_ratio) {
+ if !self.drift_warning_logged {
+ warn!(
+ drift_ratio,
+ wall_clock_secs,
+ adjusted_sample_secs,
+ baseline,
+ "AudioDriftTracker: Significant audio clock drift detected, clamping"
+ );
+ self.drift_warning_logged = true;
+ }
+ let clamped_ratio = drift_ratio.clamp(0.98, 1.02);
+ adjusted_sample_secs * clamped_ratio
+ } else {
+ adjusted_sample_secs * drift_ratio
+ };
+
+ let final_secs = corrected_secs
+ .min(max_allowed_secs)
+ .max(self.last_corrected_secs);
+ self.last_corrected_secs = final_secs;
+
+ Duration::from_secs_f64(final_secs)
+ }
+}
+
struct VideoDriftTracker {
baseline_offset_secs: Option<f64>,
capped_frame_count: u64,
@@ -1082,6 +1161,7 @@ impl PreparedAudioSources {
let muxer = muxer.clone();
async move {
let mut timestamp_generator = AudioTimestampGenerator::new(sample_rate);
+ let mut drift_tracker = AudioDriftTracker::new();
let mut dropped_during_pause: u64 = 0;
let mut frame_count: u64 = 0;
@@ -1102,19 +1182,32 @@ impl PreparedAudioSources {
let frame_samples = frame.inner.samples() as u64;
frame_count += 1;
- let timestamp = timestamp_generator.next_timestamp(frame_samples);
+ let raw_wall_clock = timestamps.instant().elapsed();
+ let wall_clock_elapsed =
+ raw_wall_clock.saturating_sub(total_pause_duration);
+
+ let sample_based_timestamp =
+ timestamp_generator.next_timestamp(frame_samples);
+ let timestamp = drift_tracker
+ .calculate_timestamp(sample_based_timestamp, wall_clock_elapsed);
if frame_count.is_multiple_of(500) {
- let raw_wall_clock = timestamps.instant().elapsed();
- let effective_wall_clock =
- raw_wall_clock.saturating_sub(total_pause_duration);
+ let drift_ratio = if sample_based_timestamp.as_secs_f64() > 0.0 {
+ wall_clock_elapsed.as_secs_f64()
+ / sample_based_timestamp.as_secs_f64()
+ } else {
+ 1.0
+ };
debug!(
- wall_clock_secs = effective_wall_clock.as_secs_f64(),
- sample_based_secs = timestamp.as_secs_f64(),
- total_samples = timestamp_generator.total_samples,
frame_count,
+ wall_clock_secs = wall_clock_elapsed.as_secs_f64(),
+ sample_based_secs = sample_based_timestamp.as_secs_f64(),
+ corrected_secs = timestamp.as_secs_f64(),
+ drift_ratio,
+ baseline_offset = drift_tracker.baseline_offset_secs,
+ total_samples = timestamp_generator.total_samples,
total_pause_ms = total_pause_duration.as_millis(),
- "Audio timestamp status"
+ "Audio drift correction status"
);
}