fix capture timing: re-encode with setpts to scale timestamps
Stream copy doesn't fix timestamps. Now uses setpts=PTS*scale filter to stretch timestamps from declared 120fps to actual delivery rate. The scale factor is declared_fps / actual_fps (e.g. 120/44.3 = 2.71).
This commit is contained in:
@@ -326,7 +326,9 @@ impl CaptureSession {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Re-encode the intermediate file with the correct fps based on actual frame delivery.
|
/// Re-encode the intermediate file with correct timestamps.
|
||||||
|
/// The capture declares -framerate 120 but delivers at a lower rate.
|
||||||
|
/// This scales PTS to match real-time duration.
|
||||||
pub fn fix_intermediate_fps(
|
pub fn fix_intermediate_fps(
|
||||||
ffmpeg: &std::path::Path,
|
ffmpeg: &std::path::Path,
|
||||||
input: &std::path::Path,
|
input: &std::path::Path,
|
||||||
@@ -342,26 +344,31 @@ pub fn fix_intermediate_fps(
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let declared_fps = 120.0f64;
|
||||||
let actual_fps = frame_count as f64 / elapsed_secs;
|
let actual_fps = frame_count as f64 / elapsed_secs;
|
||||||
|
let pts_scale = declared_fps / actual_fps;
|
||||||
tracing::info!(
|
tracing::info!(
|
||||||
"capture fix: {frame_count} frames in {elapsed_secs:.1}s = {actual_fps:.1}fps"
|
"capture fix: {frame_count} frames in {elapsed_secs:.1}s = {actual_fps:.1}fps, pts_scale={pts_scale:.2}"
|
||||||
);
|
);
|
||||||
|
|
||||||
// Re-encode with correct fps using stream copy (no quality loss)
|
// Re-encode with scaled PTS to fix timing
|
||||||
let status = Command::new(ffmpeg)
|
let status = Command::new(ffmpeg)
|
||||||
.arg("-y")
|
.arg("-y")
|
||||||
.arg("-hide_banner")
|
.arg("-hide_banner")
|
||||||
.args(["-loglevel", "error"])
|
.args(["-loglevel", "error"])
|
||||||
.args(["-r", &format!("{:.2}", actual_fps)])
|
|
||||||
.args(["-i", &input.to_string_lossy()])
|
.args(["-i", &input.to_string_lossy()])
|
||||||
.args(["-c", "copy"])
|
.args(["-vf", &format!("setpts=PTS*{:.4}", pts_scale)])
|
||||||
|
.args(["-c:v", "libx264"])
|
||||||
|
.args(["-preset", "ultrafast"])
|
||||||
|
.args(["-pix_fmt", "yuv420p"])
|
||||||
.arg(output)
|
.arg(output)
|
||||||
.status()
|
.status()
|
||||||
.context("re-encoding with correct fps")?;
|
.context("re-encoding with corrected timestamps")?;
|
||||||
|
|
||||||
if status.success() {
|
if status.success() {
|
||||||
let _ = std::fs::remove_file(input);
|
let _ = std::fs::remove_file(input);
|
||||||
} else {
|
} else {
|
||||||
|
tracing::warn!("capture fix: re-encode failed, keeping original");
|
||||||
let _ = std::fs::rename(input, output);
|
let _ = std::fs::rename(input, output);
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|||||||
Reference in New Issue
Block a user