Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Fix A/V sync timestamp bugs across recording, encoding and playback

Richie McIlroy10f86db07804
diff --git a/crates/enc-ffmpeg/src/audio/base.rs b/crates/enc-ffmpeg/src/audio/base.rs
index 5f352188d..44ac33659 100644
--- a/crates/enc-ffmpeg/src/audio/base.rs
+++ b/crates/enc-ffmpeg/src/audio/base.rs
@@ -24,8 +24,11 @@ impl AudioEncoderBase {
timestamp: Duration,
output: &mut format::context::Output,
) -> Result<(), ffmpeg::Error> {
+ // Input frames are stamped in input-rate units; BufferedResampler
+ // rescales them to the encoder's output rate.
+ let input_rate = f64::from(self.resampler.input().rate);
self.inner
- .update_pts(&mut frame, timestamp, &mut self.encoder);
+ .update_pts_with_rate(&mut frame, timestamp, input_rate);
self.resampler.add_frame(frame);
diff --git a/crates/enc-ffmpeg/src/audio/buffered_resampler.rs b/crates/enc-ffmpeg/src/audio/buffered_resampler.rs
index d35092085..4b6065327 100644
--- a/crates/enc-ffmpeg/src/audio/buffered_resampler.rs
+++ b/crates/enc-ffmpeg/src/audio/buffered_resampler.rs
@@ -42,8 +42,10 @@ impl BufferedResampler {
};
for buffer in self.buffer.iter().skip(1) {
- // fill in gap
- remaining_samples += (buffer.1 - pts) as usize;
+ // Fill in gaps between buffered frames. Non-integer rate ratios
+ // (44.1k -> 48k) can round consecutive pts to overlap by a sample,
+ // making the difference negative; that is an overlap, not a gap.
+ remaining_samples += (buffer.1 - pts).max(0) as usize;
remaining_samples += buffer.0.samples();
pts += buffer.0.samples() as i64;
}
@@ -55,6 +57,10 @@ impl BufferedResampler {
*self.resampler.output()
}
+ pub fn input(&self) -> resampling::context::Definition {
+ *self.resampler.input()
+ }
+
pub fn add_frame(&mut self, mut frame: ffmpeg::frame::Audio) {
if let Some(min_next_pts) = self.min_next_pts
&& let Some(pts) = frame.pts()
diff --git a/crates/enc-ffmpeg/src/audio/opus.rs b/crates/enc-ffmpeg/src/audio/opus.rs
index 1b9c14462..34e1902da 100644
--- a/crates/enc-ffmpeg/src/audio/opus.rs
+++ b/crates/enc-ffmpeg/src/audio/opus.rs
@@ -67,6 +67,11 @@ impl OpusEncoder {
let mut output_config = input_config;
output_config.sample_format = Self::SAMPLE_FORMAT;
output_config.sample_rate = rate as u32;
+ // libopus rejects surround layouts without an explicit mapping
+ // family; multichannel interfaces (5.1 mics) would fail to start a
+ // recording at all. Voice capture doesn't need surround: downmix to
+ // stereo via the resampler instead.
+ output_config.channels = output_config.channels.min(2);
let resampler = BufferedResampler::new(input_config, output_config)
.map_err(OpusEncoderError::Resampler)?;
diff --git a/crates/enc-ffmpeg/src/base.rs b/crates/enc-ffmpeg/src/base.rs
index 88ffbef5b..60179c8fa 100644
--- a/crates/enc-ffmpeg/src/base.rs
+++ b/crates/enc-ffmpeg/src/base.rs
@@ -66,6 +66,44 @@ impl EncoderBase {
}
}
+ /// Stamps the frame's pts from its capture timestamp using an explicit
+ /// tick rate. Audio input frames must be stamped in *input sample rate*
+ /// units — the resampler rescales them to the encoder's output rate —
+ /// whereas [`Self::update_pts`] uses the encoder's own (output) time
+ /// base. Mixing the two conventions plays non-48kHz microphones at the
+ /// wrong speed.
+ pub fn update_pts_with_rate(
+ &mut self,
+ frame: &mut frame::Frame,
+ timestamp: Duration,
+ rate: f64,
+ ) {
+ if timestamp != Duration::MAX {
+ let pts = (timestamp.as_secs_f64() * rate).round() as i64;
+ let first_pts = *self.first_pts.get_or_insert(pts);
+ let mut pts = pts - first_pts;
+ if let Some(last) = self.last_frame_pts
+ && pts <= last
+ {
+ pts = last + 1;
+ }
+ self.last_frame_pts = Some(pts);
+ frame.set_pts(Some(pts));
+ } else if let Some(pts) = frame.pts() {
+ let first_pts = *self.first_pts.get_or_insert(pts);
+ let mut pts = pts - first_pts;
+ if let Some(last) = self.last_frame_pts
+ && pts <= last
+ {
+ pts = last + 1;
+ }
+ self.last_frame_pts = Some(pts);
+ frame.set_pts(Some(pts));
+ } else {
+ tracing::error!("Frame has no pts");
+ }
+ }
+
pub fn send_frame(
&mut self,
frame: &frame::Frame,
diff --git a/crates/enc-ffmpeg/src/mux/segmented_stream.rs b/crates/enc-ffmpeg/src/mux/segmented_stream.rs
index 5605044b4..f6ec79014 100644
--- a/crates/enc-ffmpeg/src/mux/segmented_stream.rs
+++ b/crates/enc-ffmpeg/src/mux/segmented_stream.rs
@@ -84,7 +84,6 @@ pub struct SegmentedVideoEncoder {
segment_start_time: Option<Duration>,
last_frame_timestamp: Option<Duration>,
frames_in_segment: u32,
- encoded_frame_count: u64,
completed_segments: Vec<VideoSegmentInfo>,
@@ -281,7 +280,6 @@ impl SegmentedVideoEncoder {
segment_start_time: None,
last_frame_timestamp: None,
frames_in_segment: 0,
- encoded_frame_count: 0,
completed_segments: Vec::new(),
pending_segment_indices: Vec::new(),
frames_since_pending_flush: 0,
@@ -341,10 +339,12 @@ impl SegmentedVideoEncoder {
self.last_frame_timestamp = Some(timestamp);
- let encoder_timestamp = self.next_encoder_timestamp();
+ // Encode with the frame's real capture-derived timestamp. The encoder
+ // anchors pts at the first frame, so capture gaps (static content,
+ // stream restarts, dropped frames) stay in the timeline instead of
+ // compressing it and drifting video ahead of audio.
self.encoder
- .queue_frame(frame, encoder_timestamp, &mut self.output)?;
- self.encoded_frame_count += 1;
+ .queue_frame(frame, timestamp, &mut self.output)?;
self.frames_in_segment += 1;
if is_first_frame {
@@ -367,12 +367,6 @@ impl SegmentedVideoEncoder {
Ok(())
}
- fn next_encoder_timestamp(&self) -> Duration {
- let frame_rate_num = self.codec_info.frame_rate_num.max(1) as f64;
- let frame_rate_den = self.codec_info.frame_rate_den.max(1) as f64;
- Duration::from_secs_f64(self.encoded_frame_count as f64 * frame_rate_den / frame_rate_num)
- }
-
fn notify_segment(&self, event: SegmentCompletedEvent) {
if let Some(tx) = &self.segment_tx
&& let Err(e) = tx.send(event)
@@ -995,6 +989,88 @@ mod tests {
assert!(all_video, "all events should be video type");
}
+ #[test]
+ fn encoded_pts_preserve_capture_timestamps_across_gaps() {
+ ffmpeg::init().ok();
+
+ let temp = tempfile::tempdir().unwrap();
+ let base_path = temp.path().to_path_buf();
+
+ let mut encoder = SegmentedVideoEncoder::init(
+ base_path.clone(),
+ test_video_info(),
+ SegmentedVideoEncoderConfig {
+ segment_duration: Duration::from_millis(500),
+ ..Default::default()
+ },
+ )
+ .unwrap();
+
+ // Three frames at ~30fps, a 1.9s capture gap (static screen /
+ // stream restart), then three more frames. The encoded pts must
+ // reflect the gap instead of collapsing to a frame-counter grid,
+ // otherwise every dropped frame desyncs video from audio.
+ let timestamps_ms: [u64; 6] = [0, 33, 66, 2000, 2033, 2066];
+ for ts_ms in timestamps_ms {
+ let frame = create_test_frame(320, 240);
+ encoder
+ .queue_frame(frame, Duration::from_millis(ts_ms))
+ .unwrap();
+ }
+
+ encoder.finish().unwrap();
+
+ // fMP4 segments concatenated after the init segment form a valid mp4.
+ let mut segment_paths: Vec<PathBuf> = std::fs::read_dir(&base_path)
+ .unwrap()
+ .filter_map(|e| e.ok().map(|e| e.path()))
+ .filter(|p| p.extension().is_some_and(|ext| ext == "m4s"))
+ .collect();
+ segment_paths.sort();
+ assert!(
+ !segment_paths.is_empty(),
+ "encoder should have produced media segments"
+ );
+
+ let concat_path = base_path.join("concat_test.mp4");
+ let mut concatenated = std::fs::read(base_path.join(INIT_SEGMENT_NAME)).unwrap();
+ for segment in &segment_paths {
+ concatenated.extend(std::fs::read(segment).unwrap());
+ }
+ std::fs::write(&concat_path, concatenated).unwrap();
+
+ let mut input = format::input(&concat_path).unwrap();
+ let stream_index = input
+ .streams()
+ .best(ffmpeg::media::Type::Video)
+ .unwrap()
+ .index();
+ let time_base = input.stream(stream_index).unwrap().time_base();
+ let tb = time_base.numerator() as f64 / time_base.denominator() as f64;
+
+ let mut pts_secs: Vec<f64> = input
+ .packets()
+ .filter_map(|(stream, packet)| {
+ (stream.index() == stream_index)
+ .then_some(packet.pts())
+ .flatten()
+ })
+ .map(|pts| pts as f64 * tb)
+ .collect();
+ pts_secs.sort_by(|a, b| a.partial_cmp(b).unwrap());
+
+ assert_eq!(pts_secs.len(), timestamps_ms.len());
+
+ for (pts, expected_ms) in pts_secs.iter().zip(timestamps_ms) {
+ let expected = expected_ms as f64 / 1000.0;
+ assert!(
+ (pts - expected).abs() < 0.005,
+ "encoded pts {pts:.3}s should match capture timestamp {expected:.3}s \
+ (all pts: {pts_secs:?})"
+ );
+ }
+ }
+
#[test]
fn manifest_updated_on_segment_boundary() {
ffmpeg::init().ok();
diff --git a/crates/recording/src/output_pipeline/core.rs b/crates/recording/src/output_pipeline/core.rs
index 42390d899..7df3de225 100644
--- a/crates/recording/src/output_pipeline/core.rs
+++ b/crates/recording/src/output_pipeline/core.rs
@@ -636,32 +636,57 @@ impl AudioTimestampGenerator {
}
fn from_master_clock(master_clock: Arc<MasterClock>) -> Self {
+ let rate = master_clock.sample_rate();
+ Self::from_master_clock_with_rate(master_clock, rate)
+ }
+
+ /// The generator converts counted samples into time, so it must run at
+ /// the audio source's real sample rate. The shared master clock may run
+ /// at a different (default 48kHz) rate: counting a 44.1kHz mic's samples
+ /// against a 48kHz clock makes the audio timeline lag real time and the
+ /// gap tracker "corrects" the difference with bogus silence — the
+ /// recording then plays at the wrong speed.
+ fn from_master_clock_with_rate(master_clock: Arc<MasterClock>, sample_rate: u32) -> Self {
Self {
- sample_rate: master_clock.sample_rate(),
+ sample_rate: if sample_rate > 0 {
+ sample_rate
+ } else {
+ master_clock.sample_rate()
+ },
total_samples: 0,
master_clock: Some(master_clock),
}
}
+ fn advance_clock(&self, samples: u64) {
+ 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
+ } else {
+ (samples as u128 * clock.sample_rate() as u128 / u128::from(self.sample_rate.max(1)))
+ as u64
+ };
+ clock.advance_samples(clock_samples);
+ }
+
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;
- if let Some(clock) = &self.master_clock
- && frame_samples > 0
- {
- clock.advance_samples(frame_samples);
- }
+ self.advance_clock(frame_samples);
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;
- if let Some(clock) = &self.master_clock
- && samples > 0
- {
- clock.advance_samples(samples);
- }
+ self.advance_clock(samples);
samples
}
}
@@ -1134,21 +1159,20 @@ impl TimestampAnomalyTracker {
self.max_forward_skew_secs = jump_secs;
}
- let expected_increment = Duration::from_millis(33);
- let adjusted = last.saturating_add(expected_increment);
-
- let compensation_secs = current.as_secs_f64() - adjusted.as_secs_f64();
- self.accumulated_compensation_secs -= compensation_secs;
- self.resync_count += 1;
- self.did_resync = true;
-
if wall_clock_confirmed {
+ // Frame delivery paused for about as long as the timestamp jump:
+ // this is a real gap (static screen, stream restart, sleep/wake),
+ // not a source-clock glitch. The gap must stay in the timeline —
+ // collapsing it desyncs video from audio whenever it happens
+ // before the wall-clock anchor exists to re-expand it.
let wall_clock_gap_secs = self
.last_valid_wall_clock
.map(|wc| now.duration_since(wc).as_secs_f64())
.unwrap_or(0.0);
self.wall_clock_confirmed_jumps += 1;
+ self.consecutive_anomalies = 0;
+ self.last_valid_duration = Some(current);
info!(
stream = self.stream_name,
@@ -1158,9 +1182,21 @@ impl TimestampAnomalyTracker {
current_ms = current.as_millis(),
resync_count = self.resync_count,
confirmed_jumps = self.wall_clock_confirmed_jumps,
- "Wall-clock-confirmed forward jump (system sleep/wake), accepting new baseline"
+ "Wall-clock-confirmed forward jump (gap in frame delivery), accepting new baseline"
);
- } else {
+
+ return Ok(current);
+ }
+
+ let expected_increment = Duration::from_millis(33);
+ let adjusted = last.saturating_add(expected_increment);
+
+ let compensation_secs = current.as_secs_f64() - adjusted.as_secs_f64();
+ self.accumulated_compensation_secs -= compensation_secs;
+ self.resync_count += 1;
+ self.did_resync = true;
+
+ {
self.anomaly_count += 1;
let wall_clock_gap_secs = self
@@ -1595,6 +1631,7 @@ impl<TVideo: VideoSource> OutputPipelineBuilder<HasVideo<TVideo>> {
let shared_pause = SharedWallClockPause::new(build_ctx.pause_flag.clone());
let video_frame_count = Arc::new(AtomicU64::new(0));
+ let video_timestamp_span = Arc::new(VideoTimestampSpan::default());
let video_start_gate = has_audio_sources.then(VideoStartGate::new);
@@ -1608,6 +1645,7 @@ impl<TVideo: VideoSource> OutputPipelineBuilder<HasVideo<TVideo>> {
timestamps,
shared_pause.clone(),
video_frame_count.clone(),
+ video_timestamp_span.clone(),
master_clock.clone(),
video_info,
video_start_gate.clone(),
@@ -1641,6 +1679,7 @@ impl<TVideo: VideoSource> OutputPipelineBuilder<HasVideo<TVideo>> {
pause_flag: build_ctx.pause_flag,
cancel_token: build_ctx.stop_token,
video_frame_count,
+ video_timestamp_span,
health_rx: Some(build_ctx.health_rx),
audio_gap_summary,
})
@@ -1724,6 +1763,7 @@ impl OutputPipelineBuilder<NoVideo> {
pause_flag: build_ctx.pause_flag,
cancel_token: build_ctx.stop_token,
video_frame_count: Arc::new(AtomicU64::new(0)),
+ video_timestamp_span: Arc::new(VideoTimestampSpan::default()),
health_rx: Some(build_ctx.health_rx),
audio_gap_summary,
})
@@ -1890,6 +1930,42 @@ fn estimate_video_frame_duration_ns(video_info: &VideoInfo) -> u64 {
1_000_000_000 / fps as u64
}
+/// Span of the video timestamps actually sent to the muxer, used to report
+/// the real encoded media duration. Capture is VFR (static screens, dropped
+/// frames), so `frame_count / fps` under-reports the duration by the length
+/// of every gap.
+#[derive(Debug)]
+pub struct VideoTimestampSpan {
+ first_ns: AtomicU64,
+ last_ns: AtomicU64,
+}
+
+impl Default for VideoTimestampSpan {
+ fn default() -> Self {
+ Self {
+ first_ns: AtomicU64::new(u64::MAX),
+ last_ns: AtomicU64::new(0),
+ }
+ }
+}
+
+impl VideoTimestampSpan {
+ fn record(&self, timestamp: Duration) {
+ let ns = timestamp.as_nanos().min(u64::MAX as u128) as u64;
+ self.first_ns.fetch_min(ns, Ordering::AcqRel);
+ self.last_ns.fetch_max(ns, Ordering::AcqRel);
+ }
+
+ pub fn get(&self) -> Option<(Duration, Duration)> {
+ let first = self.first_ns.load(Ordering::Acquire);
+ if first == u64::MAX {
+ return None;
+ }
+ let last = self.last_ns.load(Ordering::Acquire).max(first);
+ Some((Duration::from_nanos(first), Duration::from_nanos(last)))
+ }
+}
+
#[allow(clippy::too_many_arguments)]
fn spawn_video_encoder<TMutex: VideoMuxer<VideoFrame = TVideo::Frame>, TVideo: VideoSource>(
setup_ctx: &mut SetupCtx,
@@ -1901,6 +1977,7 @@ fn spawn_video_encoder<TMutex: VideoMuxer<VideoFrame = TVideo::Frame>, TVideo: V
timestamps: Timestamps,
shared_pause: SharedWallClockPause,
frame_counter: Arc<AtomicU64>,
+ timestamp_span: Arc<VideoTimestampSpan>,
master_clock: Arc<MasterClock>,
video_info: VideoInfo,
video_start_gate: Option<VideoStartGate>,
@@ -1999,6 +2076,7 @@ fn spawn_video_encoder<TMutex: VideoMuxer<VideoFrame = TVideo::Frame>, TVideo: V
let raw_wall_clock = timestamps.instant().elapsed();
let wall_clock_elapsed = raw_wall_clock.saturating_sub(total_pause_duration);
let duration = drift_tracker.calculate_timestamp(raw_duration, wall_clock_elapsed);
+ timestamp_span.record(duration);
if frame_count.is_multiple_of(300) {
let drift_ratio = if raw_duration.as_secs_f64() > 0.0 {
@@ -2092,6 +2170,7 @@ fn spawn_video_encoder<TMutex: VideoMuxer<VideoFrame = TVideo::Frame>, TVideo: V
let wall_clock_elapsed = raw_wall_clock.saturating_sub(total_pause);
let duration =
drift_tracker.calculate_timestamp(raw_duration, wall_clock_elapsed);
+ timestamp_span.record(duration);
match muxer.lock().await.send_video_frame(frame, duration) {
Ok(()) => {}
@@ -2191,8 +2270,10 @@ impl PreparedAudioSources {
let stop_token = stop_token.child_token();
let muxer = muxer.clone();
async move {
- let mut timestamp_generator =
- AudioTimestampGenerator::from_master_clock(master_clock.clone());
+ let mut timestamp_generator = AudioTimestampGenerator::from_master_clock_with_rate(
+ master_clock.clone(),
+ audio_info.sample_rate,
+ );
let sample_rate = audio_info.sample_rate;
let mut dropped_during_pause: u64 = 0;
let mut frame_count: u64 = 0;
@@ -2741,6 +2822,7 @@ pub struct OutputPipeline {
pause_flag: Arc<AtomicBool>,
cancel_token: CancellationToken,
video_frame_count: Arc<AtomicU64>,
+ video_timestamp_span: Arc<VideoTimestampSpan>,
health_rx: Option<HealthReceiver>,
audio_gap_summary: Arc<OnceLock<AudioGapSummary>>,
}
@@ -2750,6 +2832,9 @@ pub struct FinishedOutputPipeline {
pub first_timestamp: Timestamp,
pub video_info: Option<VideoInfo>,
pub video_frame_count: u64,
+ /// First and last video timestamps sent to the muxer; the real encoded
+ /// media span for VFR content.
+ pub video_timestamp_span: Option<(Duration, Duration)>,
pub audio_gap_summary: Option<AudioGapSummary>,
}
@@ -2842,6 +2927,7 @@ impl OutputPipeline {
first_timestamp,
video_info: self.video_info,
video_frame_count: self.video_frame_count.load(Ordering::Acquire),
+ video_timestamp_span: self.video_timestamp_span.get(),
audio_gap_summary: self.audio_gap_summary.get().copied(),
})
}
@@ -3805,11 +3891,17 @@ mod tests {
tracker.last_valid_wall_clock = Instant::now().checked_sub(Duration::from_secs(3));
let jump_ts = make_timestamp(timestamps, Duration::from_millis(4 * 33 + 3000));
- tracker.process_timestamp(jump_ts, timestamps).unwrap();
+ let accepted = tracker.process_timestamp(jump_ts, timestamps).unwrap();
+ // A wall-clock-confirmed jump is a real gap in frame delivery and
+ // passes through unmodified — it is not a resync.
assert!(
- tracker.take_resync_flag(),
- "Resync flag should be set after wall-clock-confirmed jump"
+ !tracker.take_resync_flag(),
+ "Confirmed gap must not be treated as a timeline resync"
+ );
+ assert!(
+ (accepted.as_secs_f64() - (4.0 * 0.033 + 3.0)).abs() < 0.05,
+ "confirmed gap must pass through, got {accepted:?}"
);
let next_ts =
@@ -3851,7 +3943,10 @@ mod tests {
assert_eq!(tracker.anomaly_count, 0);
assert_eq!(tracker.wall_clock_confirmed_jumps, 2);
- assert_eq!(tracker.resync_count, 2);
+ assert_eq!(
+ tracker.resync_count, 0,
+ "confirmed gaps pass through; they are not timeline resyncs"
+ );
}
#[test]
@@ -5279,5 +5374,53 @@ mod tests {
"video drifted from the wall clock by {max_skew:?} (correction failed)"
);
}
+
+ // A static screen (or a capture-stream restart) stops frame delivery
+ // entirely. The gap must survive into the output timeline: collapsing
+ // it compresses video relative to audio and desyncs the recording.
+ #[test]
+ fn video_timeline_preserves_capture_gaps() {
+ let mut video = VideoDriftTracker::new();
+ let interval = 1.0 / 30.0;
+
+ let mut outs = Vec::new();
+ for v in 0..150u64 {
+ let t = Duration::from_secs_f64(v as f64 * interval);
+ outs.push(video.calculate_timestamp(t, t));
+ }
+ // 4s with no frames delivered, then delivery resumes with
+ // timestamps that include the gap.
+ for v in 150..300u64 {
+ let t = Duration::from_secs_f64(v as f64 * interval + 4.0);
+ outs.push(video.calculate_timestamp(t, t));
+ }
+
+ let gap = outs[150].saturating_sub(outs[149]);
+ assert!(
+ gap >= Duration::from_secs_f64(3.5),
+ "capture gap collapsed to {gap:?} in the output timeline"
+ );
+
+ let span = outs[299].saturating_sub(outs[0]);
+ let real = 299.0 * interval + 4.0;
+ assert!(
+ (span.as_secs_f64() - real).abs() < 0.3,
+ "output span {span:?} does not match real elapsed time {real:.2}s"
+ );
+ }
+
+ #[test]
+ fn video_timestamp_span_reports_first_and_last_sent() {
+ let span = VideoTimestampSpan::default();
+ assert!(span.get().is_none(), "unset span must be None");
+
+ span.record(Duration::from_millis(100));
+ span.record(Duration::from_millis(133));
+ span.record(Duration::from_millis(4000)); // across a capture gap
+
+ let (first, last) = span.get().expect("span should be set");
+ assert_eq!(first, Duration::from_millis(100));
+ assert_eq!(last, Duration::from_millis(4000));
+ }
}
}
diff --git a/crates/recording/src/output_validation.rs b/crates/recording/src/output_validation.rs
index 72da56a4d..2ed21049b 100644
--- a/crates/recording/src/output_validation.rs
+++ b/crates/recording/src/output_validation.rs
@@ -103,3 +103,46 @@ pub fn validate_instant_recording(
output_duration,
}
}
+
+/// Tolerated difference between the display track's container duration and the
+/// media span the recorder persisted, before the recording is flagged as
+/// having suspicious sync. Generous enough for muxer rounding and trailing
+/// keyframe padding; far below the hundreds of milliseconds a real timestamp
+/// bug produces.
+const SYNC_SPAN_TOLERANCE_SECS: f64 = 0.5;
+const SYNC_SPAN_TOLERANCE_RATIO: f64 = 0.03;
+
+/// Cross-checks a finalized display track against the media duration the
+/// recorder derived from the capture timestamps it actually muxed.
+///
+/// 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.
+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 tolerance =
+ (expected.as_secs_f64() * SYNC_SPAN_TOLERANCE_RATIO).max(SYNC_SPAN_TOLERANCE_SECS);
+ if delta > 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 \
+ the muxed timestamp span; this recording may have desynced audio/video"
+ );
+ Some(delta)
+ } 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"
+ );
+ None
+ }
+}
diff --git a/crates/recording/src/recovery.rs b/crates/recording/src/recovery.rs
index e542718b0..572d4b10f 100644
--- a/crates/recording/src/recovery.rs
+++ b/crates/recording/src/recovery.rs
@@ -757,6 +757,28 @@ impl RecoveryManager {
if total.is_zero() { None } else { Some(total) }
}
+ /// Reads the display media duration the recorder persisted into the
+ /// project's default timeline, used to cross-check the remuxed container.
+ fn expected_display_duration_from_config(
+ project_path: &Path,
+ segment_index: u32,
+ ) -> Option<std::time::Duration> {
+ let config = std::fs::read_to_string(project_path.join("project-config.json")).ok()?;
+ let value: serde_json::Value = serde_json::from_str(&config).ok()?;
+ let segments = value.get("timeline")?.get("segments")?.as_array()?;
+ let segment = segments.iter().find(|s| {
+ s.get("recordingSegment")
+ .and_then(serde_json::Value::as_u64)
+ == Some(u64::from(segment_index))
+ })?;
+ let end = segment.get("end")?.as_f64()?;
+ let start = segment
+ .get("start")
+ .and_then(serde_json::Value::as_f64)
+ .unwrap_or(0.0);
+ (end > start && end.is_finite()).then(|| std::time::Duration::from_secs_f64(end - start))
+ }
+
pub fn recover(recording: &IncompleteRecording) -> Result<RecoveredRecording, RecoveryError> {
Self::finalize_with_purpose(recording, RecoveryPurpose::Recover)
}
@@ -828,6 +850,17 @@ impl RecoveryManager {
}
}
+ // Sync invariant: the remuxed display track must match the media
+ // span the recorder persisted from its capture timestamps.
+ if display_output.is_file()
+ && let Some(expected) = Self::expected_display_duration_from_config(
+ &recording.project_path,
+ segment.index,
+ )
+ {
+ crate::output_validation::check_display_sync_span(&display_output, expected);
+ }
+
if let Some(camera_frags) = &segment.camera_fragments {
let camera_output = segment_dir.join("camera.mp4");
let camera_dir = segment_dir.join("camera");
diff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rs
index 30352fb08..b79278a41 100644
--- a/crates/recording/src/studio_recording.rs
+++ b/crates/recording/src/studio_recording.rs
@@ -1002,17 +1002,39 @@ async fn stop_recording(
);
DEFAULT_FPS
});
- // Use the encoded display-media duration (frame_count / fps), not the wall-clock
- // recording span which includes pipeline-drain latency. This is the timeline the
- // recorder persists to project-config.json, so it is what un-edited recordings use; the
- // editor/export fallbacks only synthesize a timeline when none is present and read the
- // muxed container duration, which this closely (not bit-exactly) matches.
- let display_media_duration = if display_fps > 0 {
- s.pipeline.screen.video_frame_count as f64 / f64::from(display_fps)
- } else {
- 0.0
+ // Use the encoded display-media span (first to last muxed timestamp plus one
+ // nominal frame), not the wall-clock recording span which includes
+ // pipeline-drain latency, and not frame_count / fps, which under-reports VFR
+ // content by the length of every capture gap (static screens, dropped frames).
+ // This is the timeline the recorder persists to project-config.json, so it is
+ // what un-edited recordings use.
+ let display_media_duration = match s.pipeline.screen.video_timestamp_span {
+ Some((first, last)) if display_fps > 0 => {
+ (last - first).as_secs_f64() + 1.0 / f64::from(display_fps)
+ }
+ _ if display_fps > 0 => {
+ s.pipeline.screen.video_frame_count as f64 / f64::from(display_fps)
+ }
+ _ => 0.0,
};
+ // Non-fragmented recordings have their final display file already;
+ // verify the muxed container matches the timestamps we sent it.
+ // Fragmented recordings get the same check after remux in recovery.
+ if s.pipeline
+ .screen
+ .path
+ .extension()
+ .is_some_and(|e| e == "mp4")
+ && s.pipeline.screen.path.is_file()
+ && display_media_duration > 0.0
+ {
+ crate::output_validation::check_display_sync_span(
+ &s.pipeline.screen.path,
+ Duration::from_secs_f64(display_media_duration),
+ );
+ }
+
SegmentOutput {
meta: MultipleSegment {
display: VideoMeta {
@@ -1809,6 +1831,7 @@ mod tests {
first_timestamp,
video_info,
video_frame_count,
+ video_timestamp_span: None,
audio_gap_summary: None,
}
}
diff --git a/crates/rendering/src/decoder/avassetreader.rs b/crates/rendering/src/decoder/avassetreader.rs
index 26fd3f08c..92acdb0fd 100644
--- a/crates/rendering/src/decoder/avassetreader.rs
+++ b/crates/rendering/src/decoder/avassetreader.rs
@@ -761,12 +761,31 @@ impl AVAssetReaderDecoder {
.next_back()
.or_else(|| cache.range(req.frame..).next());
+ // Always answer with the nearest available frame. A frame
+ // at-or-before the request is the true content for that
+ // time in a VFR recording (a pts gap means the frame stayed
+ // on screen); a later frame is the best remaining answer.
+ // Leaving the request unanswered makes the loop keep pulling
+ // frames forward, evicting the hold frame from the cache and
+ // wedging every later request behind the cache floor.
if let Some((&frame_num, cached)) = nearest {
- let distance = req.frame.abs_diff(frame_num);
- if distance <= req.max_fallback_distance {
- let _ =
- req.sender.send(cached.data().to_decoded_frame());
+ if frame_num > req.frame
+ && req.frame.abs_diff(frame_num)
+ > req.max_fallback_distance
+ {
+ tracing::debug!(
+ req_frame = req.frame,
+ nearest_frame = frame_num,
+ "serving forward frame across pts gap"
+ );
}
+ let _ = req.sender.send(cached.data().to_decoded_frame());
+ } else {
+ tracing::warn!(
+ req_frame = req.frame,
+ current_frame,
+ "dropping overshot request: cache empty"
+ );
}
}
} else {
@@ -901,20 +920,20 @@ impl AVAssetReaderDecoder {
.or_else(|| cache.range(req.frame..).next());
if let Some((&frame_num, cached)) = nearest {
- let distance = req.frame.abs_diff(frame_num);
- if distance <= fallback_distance {
- let _ = req.sender.send(cached.data().to_decoded_frame());
- } else if allow_relaxed_fallback
- && let Some(ref last) = *last_sent_frame.borrow()
+ // Always answer with the nearest available frame: at-or-before
+ // the request it is the true VFR hold content, after the request
+ // it is the best remaining answer. Dropping the request instead
+ // starves the render loop and wedges gap playback/export.
+ if frame_num > req.frame
+ && req.frame.abs_diff(frame_num) > fallback_distance
{
- let _ = req.sender.send(last.to_decoded_frame());
- } else if allow_relaxed_fallback
- && let Some(ref first) = *first_ever_frame.borrow()
- {
- let _ = req.sender.send(first.to_decoded_frame());
- } else {
- unfulfilled_count += 1;
+ tracing::debug!(
+ req_frame = req.frame,
+ nearest_frame = frame_num,
+ "serving forward frame across pts gap"
+ );
}
+ let _ = req.sender.send(cached.data().to_decoded_frame());
} else if allow_relaxed_fallback
&& let Some(ref last) = *last_sent_frame.borrow()
{
diff --git a/crates/rendering/src/decoder/ffmpeg.rs b/crates/rendering/src/decoder/ffmpeg.rs
index 1e26eeb25..81469316a 100644
--- a/crates/rendering/src/decoder/ffmpeg.rs
+++ b/crates/rendering/src/decoder/ffmpeg.rs
@@ -70,7 +70,6 @@ struct PendingRequest {
}
const MAX_FRAME_LOOKBACK_TOLERANCE: u32 = 2;
-const MAX_FRAME_FALLBACK_DISTANCE: u32 = 90;
fn extract_yuv_planes(frame: &frame::Video) -> Option<(Vec<u8>, PixelFormat, u32, u32)> {
let height = frame.height();
@@ -513,12 +512,11 @@ impl FfmpegDecoder {
if current_frame > requested_frame && respond.is_some() {
let last_sent_frame_clone = sw_last_sent_frame.borrow().clone();
+ // A frame at-or-before the request is the true content for
+ // that time in a VFR recording: a pts gap means the frame
+ // stayed on screen, however long the gap is.
if let Some((respond, last_frame)) = last_sent_frame_clone
- .filter(|l| {
- l.number <= requested_frame
- && requested_frame.saturating_sub(l.number)
- <= MAX_FRAME_FALLBACK_DISTANCE
- })
+ .filter(|l| l.number <= requested_frame)
.and_then(|l| Some((respond.take()?, l)))
{
(respond)(last_frame);
@@ -539,13 +537,11 @@ impl FfmpegDecoder {
sw_last_active_frame = Some(requested_frame);
if let Some(respond) = respond.take() {
+ // The newest cached frame at-or-before the request is always
+ // a valid VFR hold, regardless of how far back it is.
let best_cached = sw_cache
.range(..=requested_frame)
.next_back()
- .filter(|(k, _)| {
- requested_frame.saturating_sub(**k)
- <= MAX_FRAME_FALLBACK_DISTANCE
- })
.map(|(_, v)| v);
if let Some(cached) = best_cached {
@@ -824,12 +820,11 @@ impl FfmpegDecoder {
if current_frame > requested_frame && respond.is_some() {
let last_sent_frame_clone = last_sent_frame.borrow().clone();
+ // A frame at-or-before the request is the true content for
+ // that time in a VFR recording: a pts gap means the frame
+ // stayed on screen, however long the gap is.
if let Some((respond, last_frame)) = last_sent_frame_clone
- .filter(|l| {
- l.number <= requested_frame
- && requested_frame.saturating_sub(l.number)
- <= MAX_FRAME_FALLBACK_DISTANCE
- })
+ .filter(|l| l.number <= requested_frame)
.and_then(|l| Some((respond.take()?, l)))
{
(respond)(last_frame);
@@ -850,13 +845,10 @@ impl FfmpegDecoder {
last_active_frame = Some(requested_frame);
if let Some(respond) = respond.take() {
- let best_cached = cache
- .range(..=requested_frame)
- .next_back()
- .filter(|(k, _)| {
- requested_frame.saturating_sub(**k) <= MAX_FRAME_FALLBACK_DISTANCE
- })
- .map(|(_, v)| v);
+ // The newest cached frame at-or-before the request is always a
+ // valid VFR hold, regardless of how far back it is.
+ let best_cached =
+ cache.range(..=requested_frame).next_back().map(|(_, v)| v);
if let Some(cached) = best_cached {
let output = cached.clone().produce(&mut converter);
diff --git a/crates/rendering/src/decoder/mod.rs b/crates/rendering/src/decoder/mod.rs
index 44456cea0..cac4f9e90 100644
--- a/crates/rendering/src/decoder/mod.rs
+++ b/crates/rendering/src/decoder/mod.rs
@@ -505,6 +505,10 @@ impl AsyncVideoDecoderHandle {
))
.is_err()
{
+ tracing::warn!(
+ time = adjusted_time,
+ "decoder thread is gone; frame request dropped"
+ );
return None;
}
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index e46b0f68e..f5b3edb9c 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -393,6 +393,10 @@ impl RecordingSegmentDecoders {
let camera_frame = camera.flatten();
+ if screen.is_none() {
+ tracing::warn!(segment_time, "screen decoder returned no frame");
+ }
+
Some(DecodedSegmentFrames {
screen_frame: Some(screen?),
camera_frame,