fix capture timing and gif size cap

- capture declares -framerate 999 to accept all frames without dropping
- after capture stops, measure actual delivery rate from frame count / elapsed time
- re-encode intermediate file with correct fps via stream copy (no quality loss)
- same fix applied to pause_capture segments
- gif: remove 15% size tolerance - never exceed target size
This commit is contained in:
2026-05-30 01:14:51 +03:00
parent 67c2a84178
commit 5d312b6b00
3 changed files with 90 additions and 17 deletions
+76 -4
View File
@@ -71,7 +71,11 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
// The capture API delivers frames at the monitor's refresh rate, not the
// user's chosen FPS. We must tell ffmpeg the actual rate so timestamps are
// correct. The fps filter in the export pipeline handles the conversion.
tracing::info!("capture: no declared framerate, size={}x{}", setup.width, setup.height);
tracing::info!("capture: size={}x{}", setup.width, setup.height);
// Use a high declared framerate to accept all frames without dropping.
// We'll measure the actual delivery rate and re-encode after capture.
let declared_fps = 999u32;
let mut cmd = Command::new(&setup.ffmpeg_path);
cmd.arg("-y")
@@ -80,6 +84,7 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
.args(["-f", "rawvideo"])
.args(["-pixel_format", "bgra"])
.args(["-video_size", &format!("{}x{}", setup.width, setup.height)])
.args(["-framerate", &declared_fps.to_string()])
.args(["-i", "-"])
.args(["-vf", &filter])
.args(["-c:v", "libx264"])
@@ -300,9 +305,6 @@ fn compute_output_dims(monitor_w: u32, monitor_h: u32, crop: Option<CaptureRect>
impl CaptureSession {
pub fn stop(self) -> Result<PathBuf> {
// Ignore errors from control.stop() - the last frame write often fails
// with "pipe is being closed" when stopping. If the output file has content,
// the capture was successful.
let _ = self.control.stop();
let meta = std::fs::metadata(&self.output_path)
.with_context(|| format!("checking output file {}", self.output_path.display()))?;
@@ -312,3 +314,73 @@ impl CaptureSession {
Ok(self.output_path)
}
}
/// Re-encode the intermediate file with the correct fps based on actual frame delivery.
/// The capture uses a high declared fps (999) to accept all frames. This function
/// measures the actual delivery rate and re-encodes with correct timing.
pub fn fix_intermediate_fps(
ffmpeg: &std::path::Path,
input: &std::path::Path,
output: &std::path::Path,
elapsed_secs: f64,
) -> Result<()> {
use std::process::Command;
// Count frames in the intermediate file
let probe = Command::new(ffmpeg)
.args(["-hide_banner", "-i", &input.to_string_lossy()])
.output()
.context("probing frame count")?;
let stderr = String::from_utf8_lossy(&probe.stderr);
// Look for "frame= NNN" or "NNN frames" in stderr
let frame_count: u32 = stderr
.lines()
.find_map(|line| {
if line.contains("frames") {
line.split_whitespace()
.find(|w| w.parse::<u32>().is_ok())
.and_then(|w| w.parse().ok())
} else if line.contains("frame=") {
line.split("frame=")
.nth(1)?
.split_whitespace()
.next()?
.parse()
.ok()
} else {
None
}
})
.unwrap_or(0);
if frame_count == 0 || elapsed_secs <= 0.0 {
// Can't determine fps, just copy as-is
let _ = std::fs::rename(input, output);
return Ok(());
}
let actual_fps = frame_count as f64 / elapsed_secs;
tracing::info!(
"capture fix: {frame_count} frames in {elapsed_secs:.1}s = {actual_fps:.1}fps"
);
// Re-encode with correct fps using stream copy (no quality loss)
let status = Command::new(ffmpeg)
.arg("-y")
.arg("-hide_banner")
.args(["-loglevel", "error"])
.args(["-r", &format!("{:.2}", actual_fps)])
.args(["-i", &input.to_string_lossy()])
.args(["-c", "copy"])
.arg(output)
.status()
.context("re-encoding with correct fps")?;
if status.success() {
let _ = std::fs::remove_file(input);
} else {
// Fallback: just rename
let _ = std::fs::rename(input, output);
}
Ok(())
}