Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Excise pauses from the video timeline and harden sync checks and tests

Richie McIlroy48236f2a7bb5
diff --git a/crates/enc-ffmpeg/src/audio/buffered_resampler.rs b/crates/enc-ffmpeg/src/audio/buffered_resampler.rs
index 4b6065327..34924bb4d 100644
--- a/crates/enc-ffmpeg/src/audio/buffered_resampler.rs
+++ b/crates/enc-ffmpeg/src/audio/buffered_resampler.rs
@@ -357,6 +357,61 @@ mod test {
let last = bufferer.buffer.back().unwrap();
assert_eq!(last.1 + last.0.samples() as i64, 600);
}
+
+ #[test]
+ fn overlapping_resampled_pts_treated_as_zero_gap() {
+ // Non-integer rate ratios (44.1k -> 48k) round consecutive
+ // resampled pts so a frame can start a sample before the previous
+ // frame ends. The overlap must count as zero gap — the unclamped
+ // subtraction used to wrap to a huge unsigned "gap" and blow up
+ // frame retrieval.
+ let mut bufferer = create_resampler(IN_RATE);
+
+ bufferer.buffer.push_back((make_input_frame(100, 0), 0));
+ bufferer.buffer.push_back((make_input_frame(100, 0), 99));
+
+ assert_eq!(bufferer.remaining_samples(), 200);
+
+ let out_frame = bufferer.get_frame(200).expect("both frames are buffered");
+ assert_eq!(out_frame.samples(), 200);
+ assert_eq!(out_frame.pts(), Some(0));
+ }
+
+ #[test]
+ fn non_integer_ratio_stream_preserves_duration() {
+ // Real-world 44.1k -> 48k with device-sized buffers: pts rounding
+ // must neither panic nor lose samples over a sustained stream.
+ let mut bufferer = BufferedResampler::new(
+ AudioInfo::new_raw(format::Sample::U8(cap_media_info::Type::Packed), 44_100, 1),
+ AudioInfo::new_raw(format::Sample::U8(cap_media_info::Type::Packed), 48_000, 1),
+ )
+ .unwrap();
+
+ let mut total = 0usize;
+ for k in 0..64i64 {
+ let mut frame = ffmpeg::frame::Audio::new(
+ cap_media_info::Sample::U8(cap_media_info::Type::Packed),
+ 1024,
+ ChannelLayout::MONO,
+ );
+ frame.data_mut(0).fill(69);
+ frame.set_rate(44_100);
+ frame.set_pts(Some(k * 1024));
+ bufferer.add_frame(frame);
+ while let Some(out) = bufferer.get_frame(960) {
+ total += out.samples();
+ }
+ }
+ while let Some(out) = bufferer.flush(960) {
+ total += out.samples();
+ }
+
+ let expected = (64.0 * 1024.0 * 48_000.0 / 44_100.0) as isize;
+ assert!(
+ ((total as isize) - expected).abs() < 2_000,
+ "drained {total} output samples, expected about {expected}"
+ );
+ }
}
mod get_frame {
diff --git a/crates/recording/src/output_pipeline/core.rs b/crates/recording/src/output_pipeline/core.rs
index 7df3de225..fd7465b9b 100644
--- a/crates/recording/src/output_pipeline/core.rs
+++ b/crates/recording/src/output_pipeline/core.rs
@@ -620,6 +620,7 @@ fn video_mux_send_error(frame_count: u64, error: anyhow::Error) -> anyhow::Error
pub(crate) struct AudioTimestampGenerator {
sample_rate: u32,
total_samples: u64,
+ clock_samples_advanced: u64,
master_clock: Option<Arc<MasterClock>>,
}
@@ -631,10 +632,12 @@ impl AudioTimestampGenerator {
Self {
sample_rate,
total_samples: 0,
+ clock_samples_advanced: 0,
master_clock: None,
}
}
+ #[cfg(test)]
fn from_master_clock(master_clock: Arc<MasterClock>) -> Self {
let rate = master_clock.sample_rate();
Self::from_master_clock_with_rate(master_clock, rate)
@@ -654,39 +657,44 @@ impl AudioTimestampGenerator {
master_clock.sample_rate()
},
total_samples: 0,
+ clock_samples_advanced: 0,
master_clock: Some(master_clock),
}
}
- fn advance_clock(&self, samples: u64) {
+ fn advance_clock(&mut self) {
let Some(clock) = &self.master_clock else {
return;
};
- if samples == 0 {
- return;
- }
// Convert source-rate samples into clock-rate samples so the shared
- // clock advances by real time regardless of the source's rate.
- let clock_samples = if clock.sample_rate() == self.sample_rate {
- samples
+ // clock advances by real time regardless of the source's rate. The
+ // conversion runs on the cumulative total: converting each buffer
+ // independently truncates up to one clock sample per call, which
+ // accumulates into real drift for non-integer ratios (44.1k -> 48k).
+ let target = if clock.sample_rate() == self.sample_rate {
+ self.total_samples
} else {
- (samples as u128 * clock.sample_rate() as u128 / u128::from(self.sample_rate.max(1)))
- as u64
+ (self.total_samples as u128 * clock.sample_rate() as u128
+ / u128::from(self.sample_rate.max(1))) as u64
};
- clock.advance_samples(clock_samples);
+ let delta = target.saturating_sub(self.clock_samples_advanced);
+ self.clock_samples_advanced = target;
+ if delta > 0 {
+ clock.advance_samples(delta);
+ }
}
fn next_timestamp(&mut self, frame_samples: u64) -> Duration {
let timestamp_nanos = samples_to_nanos(self.total_samples, self.sample_rate);
self.total_samples += frame_samples;
- self.advance_clock(frame_samples);
+ self.advance_clock();
Duration::from_nanos(timestamp_nanos)
}
fn advance_by_duration(&mut self, duration: Duration) -> u64 {
let samples = (duration.as_secs_f64() * self.sample_rate as f64).round() as u64;
self.total_samples += samples;
- self.advance_clock(samples);
+ self.advance_clock();
samples
}
}
@@ -2052,8 +2060,16 @@ fn spawn_video_encoder<TMutex: VideoMuxer<VideoFrame = TVideo::Frame>, TVideo: V
);
}
+ // Excise accumulated pause time from the content timeline
+ // before anomaly tracking. Audio already excises pauses
+ // (paused frames are dropped and sample counting carries
+ // on), and wall_clock_elapsed below subtracts pauses too;
+ // leaving the pause in the video timestamps would make a
+ // resume look like a wall-clock-confirmed capture gap and
+ // poison the drift anchor with pause-inflated time.
let remapped_ts = Timestamp::Instant(
- timestamps.instant() + remap.duration(),
+ timestamps.instant()
+ + remap.duration().saturating_sub(total_pause_duration),
);
let raw_duration = match anomaly_tracker.process_timestamp(remapped_ts, timestamps) {
@@ -2149,8 +2165,13 @@ fn spawn_video_encoder<TMutex: VideoMuxer<VideoFrame = TVideo::Frame>, TVideo: V
"Published video start timestamp to encoder-pair gate (drain path)"
);
}
+ // Excise pauses exactly like the main loop above, so
+ // drained tail frames stay on the same content timeline.
let remapped_ts = Timestamp::Instant(
- timestamps.instant() + remap.duration(),
+ timestamps.instant()
+ + remap
+ .duration()
+ .saturating_sub(shared_pause.total_pause_duration()),
);
let raw_duration =
diff --git a/crates/recording/src/output_validation.rs b/crates/recording/src/output_validation.rs
index 2ed21049b..3e045b3a4 100644
--- a/crates/recording/src/output_validation.rs
+++ b/crates/recording/src/output_validation.rs
@@ -117,31 +117,34 @@ const SYNC_SPAN_TOLERANCE_RATIO: f64 = 0.03;
///
/// The two are produced independently: the expected duration comes from the
/// pipeline's timestamp span, the container duration from what the encoder
-/// and muxer wrote. If they disagree by more than the tolerance, timestamps
-/// were mangled between the pipeline and the file — the class of bug that
-/// silently desyncs audio from video. Non-fatal: logs a structured warning
-/// and returns the mismatch so callers can surface it.
+/// and muxer wrote. A container SHORTER than the span means timestamps were
+/// mangled between the pipeline and the file — the class of bug that
+/// silently desyncs audio/video. A LONGER container is legitimate for VFR
+/// content: muxers extend the final frame through any trailing static-screen
+/// hold (AVFoundation ends the session at the wall-clock stop time), so that
+/// direction is only noted at debug level. Non-fatal: logs a structured
+/// warning and returns the mismatch so callers can surface it.
pub fn check_display_sync_span(display_path: &Path, expected: Duration) -> Option<f64> {
let container = get_media_duration(display_path)?;
- let delta = (container.as_secs_f64() - expected.as_secs_f64()).abs();
+ let shortfall = expected.as_secs_f64() - container.as_secs_f64();
let tolerance =
(expected.as_secs_f64() * SYNC_SPAN_TOLERANCE_RATIO).max(SYNC_SPAN_TOLERANCE_SECS);
- if delta > tolerance {
+ if shortfall > tolerance {
tracing::error!(
path = %display_path.display(),
container_secs = container.as_secs_f64(),
expected_secs = expected.as_secs_f64(),
- delta_secs = delta,
- "SYNC INVARIANT VIOLATION: display track duration does not match \
+ delta_secs = shortfall,
+ "SYNC INVARIANT VIOLATION: display track duration is shorter than \
the muxed timestamp span; this recording may have desynced audio/video"
);
- Some(delta)
+ Some(shortfall)
} else {
debug!(
path = %display_path.display(),
container_secs = container.as_secs_f64(),
expected_secs = expected.as_secs_f64(),
- "display track duration matches muxed timestamp span"
+ "display track duration consistent with muxed timestamp span"
);
None
}
diff --git a/crates/recording/tests/sync_matrix.rs b/crates/recording/tests/sync_matrix.rs
index 61b6544d1..57005dc3e 100644
--- a/crates/recording/tests/sync_matrix.rs
+++ b/crates/recording/tests/sync_matrix.rs
@@ -335,6 +335,122 @@ async fn run_video_case(case: VideoCase) -> Result<String, String> {
))
}
+/// A mid-recording pause (instant mode): emission continues in real time but
+/// the pipeline drops frames while paused. The pause must be EXCISED from the
+/// output timeline — video pts must stay continuous across it (matching how
+/// audio drops paused samples and how the wall clock subtracts pauses), and
+/// the container must contain only the unpaused content. A regression here
+/// previously poisoned the drift anchor with pause-inflated time whenever the
+/// pause began before the ~2s warmup anchor existed.
+async fn run_video_pause_case() -> Result<String, String> {
+ const PRE_PAUSE_SECS: f64 = 1.0;
+ const PAUSE_SECS: f64 = 2.5;
+ const POST_PAUSE_SECS: f64 = 2.0;
+ const FPS: u32 = 30;
+
+ let temp = tempfile::tempdir().map_err(|e| format!("tempdir: {e}"))?;
+ let out_path = temp.path().join("display.mp4");
+
+ let info = VideoInfo::from_raw(cap_media_info::RawVideoFormat::Bgra, 160, 120, FPS);
+ let (tx, rx) = flume::bounded::<FFmpegVideoFrame>(32);
+ let timestamps = Timestamps::now();
+
+ let total_secs = PRE_PAUSE_SECS + PAUSE_SECS + POST_PAUSE_SECS;
+ let emit = {
+ let base = timestamps.instant();
+ let mut rng = Rng(7);
+ tokio::spawn(async move {
+ let period = 1.0 / f64::from(FPS);
+ let count = (total_secs * f64::from(FPS)) as u64;
+ for k in 0..count {
+ let ts = k as f64 * period;
+ tokio::time::sleep_until((base + Duration::from_secs_f64(ts)).into()).await;
+ let frame = FFmpegVideoFrame {
+ inner: make_video_frame(160, 120, k, Content::Flat, &mut rng),
+ timestamp: Timestamp::Instant(base + Duration::from_secs_f64(ts)),
+ };
+ if tx.send_async(frame).await.is_err() {
+ break;
+ }
+ }
+ })
+ };
+
+ let pipeline = OutputPipeline::builder(out_path.clone())
+ .with_video::<ChannelVideoSource<FFmpegVideoFrame>>(ChannelVideoSourceConfig::new(info, rx))
+ .with_timestamps(timestamps)
+ .build::<Mp4Muxer>(())
+ .await
+ .map_err(|e| format!("pipeline build: {e}"))?;
+
+ tokio::time::sleep(Duration::from_secs_f64(PRE_PAUSE_SECS)).await;
+ pipeline.pause();
+ tokio::time::sleep(Duration::from_secs_f64(PAUSE_SECS)).await;
+ pipeline.resume();
+
+ emit.await.map_err(|e| format!("emit join: {e}"))?;
+ tokio::time::sleep(Duration::from_millis(500)).await;
+ pipeline.stop().await.map_err(|e| format!("stop: {e}"))?;
+
+ let pts = read_video_pts(&out_path)?;
+ if pts.len() < 8 {
+ return Err(format!("only {} frames muxed", pts.len()));
+ }
+
+ // The pause is excised: the muxed span must cover roughly the unpaused
+ // content, not the wall-clock run.
+ let span = pts.last().unwrap() - pts[0];
+ let expected = PRE_PAUSE_SECS + POST_PAUSE_SECS;
+ if (span - expected).abs() > 0.6 {
+ return Err(format!(
+ "muxed span {span:.2}s should be about the unpaused content {expected:.2}s \
+ (pause leaked into the timeline)"
+ ));
+ }
+
+ // And no single pts step may contain the pause.
+ let max_gap = pts.windows(2).map(|w| w[1] - w[0]).fold(0.0, f64::max);
+ if max_gap > PAUSE_SECS * 0.8 {
+ return Err(format!(
+ "pause survived as a {max_gap:.2}s pts gap in the container"
+ ));
+ }
+
+ // Post-resume continuity is the discriminating check: without the pause
+ // excision the anomaly tracker accepts the pause as a confirmed jump and
+ // the drift tracker's wall cap re-pins the post-resume segment ~one
+ // tolerance late (measured +0.13s vs +0.03s with the fix). The median
+ // over the whole segment is immune to per-frame scheduler jitter.
+ let period = 1.0 / f64::from(FPS);
+ let split = pts
+ .windows(2)
+ .position(|w| w[1] - w[0] == max_gap)
+ .unwrap_or(0);
+ let pre_last = pts[split];
+ let mut post_offsets: Vec<f64> = pts[split + 1..]
+ .iter()
+ .enumerate()
+ .map(|(k, &p)| p - (pre_last + (k as f64 + 1.0) * period))
+ .collect();
+ post_offsets.sort_by(|a, b| a.partial_cmp(b).unwrap());
+ let continuity = post_offsets
+ .get(post_offsets.len() / 2)
+ .copied()
+ .unwrap_or(0.0);
+ if continuity.abs() > 0.08 {
+ return Err(format!(
+ "post-resume frames resume {continuity:+.3}s off the pre-pause timeline \
+ (pause bled into the drift anchor)"
+ ));
+ }
+
+ Ok(format!(
+ "{} frames, span {span:.2}s (expected ~{expected:.2}s), max pts gap {max_gap:.2}s, \
+ post-resume continuity {continuity:+.3}s",
+ pts.len()
+ ))
+}
+
#[derive(Clone, Copy)]
struct AudioCase {
rate: u32,
@@ -671,6 +787,12 @@ async fn synthetic_device_matrix_preserves_sync() {
record(&mut results, name, outcome);
}
+ record(
+ &mut results,
+ "video/30fps/pause-resume/mp4".to_string(),
+ run_video_pause_case().await,
+ );
+
let audio_cases: Vec<(u32, u16)> = vec![
(8_000, 2),
(16_000, 2),