From 5d312b6b006726e3481c3fcf9862e6f93b35b126 Mon Sep 17 00:00:00 2001 From: lashman Date: Sat, 30 May 2026 01:14:51 +0300 Subject: [PATCH] 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 --- src-tauri/src/capture.rs | 80 ++++++++++++++++++++++++++++++++++++++-- src-tauri/src/encode.rs | 11 +----- src-tauri/src/lib.rs | 16 ++++++-- 3 files changed, 90 insertions(+), 17 deletions(-) diff --git a/src-tauri/src/capture.rs b/src-tauri/src/capture.rs index 92d38b4..9723ede 100644 --- a/src-tauri/src/capture.rs +++ b/src-tauri/src/capture.rs @@ -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 impl CaptureSession { pub fn stop(self) -> Result { - // 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::().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(()) +} diff --git a/src-tauri/src/encode.rs b/src-tauri/src/encode.rs index dd8791f..1a53f10 100644 --- a/src-tauri/src/encode.rs +++ b/src-tauri/src/encode.rs @@ -397,16 +397,7 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> { return Ok(()); } - // Only adjust DOWN when file is too big - // Accept within 15% over target - if ratio >= 0.85 { - tracing::info!( - "gif encode done on attempt {}: {} bytes (target {} - close enough)", - attempt + 1, actual, target - ); - return Ok(()); - } - + // Only adjust DOWN when file is too big - never exceed target // File is too big - scale down based on budget priority match req.gif_budget_mode { GifBudgetMode::Resolution => { diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index f929789..731665c 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -432,7 +432,12 @@ fn pause_capture(state: State<'_, AppState>) -> Result<(), String> { .take() .ok_or_else(|| "no capture in progress".to_string())?; let elapsed = session.started_at.elapsed().as_secs_f64(); - let path = session.stop().map_err(|e| format!("{e:#}"))?; + let raw_path = session.stop().map_err(|e| format!("{e:#}"))?; + let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir); + let fixed_path = raw_path.with_extension("fixed.mp4"); + capture::fix_intermediate_fps(&ffmpeg, &raw_path, &fixed_path, elapsed) + .map_err(|e| format!("fixing fps: {e:#}"))?; + let path = if fixed_path.exists() { fixed_path } else { raw_path }; let audio_path = lock(&state.audio) .take() @@ -514,8 +519,13 @@ fn stop_capture(app: AppHandle, state: State<'_, AppState>) -> Result