track frame count directly in capture handler, use for fps correction

The frame count is now tracked via Arc<AtomicU64> in the capture handler,
incremented on each frame arrival. fix_intermediate_fps uses this count
along with elapsed time to calculate the actual delivery rate, then
re-encodes the intermediate with correct fps via stream copy.
This commit is contained in:
2026-05-30 02:04:36 +03:00
parent 151220a4f7
commit 3c5acdce68
2 changed files with 16 additions and 30 deletions
+12 -28
View File
@@ -1,7 +1,7 @@
use std::io::Write;
use std::path::PathBuf;
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::Arc;
use std::time::Instant;
use anyhow::{anyhow, bail, Context, Result};
@@ -29,6 +29,7 @@ pub struct CaptureSetup {
#[allow(dead_code)]
pub fps: u32,
pub crop: Option<CaptureRect>,
pub frame_counter: Arc<std::sync::atomic::AtomicU64>,
}
pub struct CaptureHandler {
@@ -37,6 +38,7 @@ pub struct CaptureHandler {
width: u32,
height: u32,
scratch: Vec<u8>,
frame_count: Arc<std::sync::atomic::AtomicU64>,
}
impl GraphicsCaptureApiHandler for CaptureHandler {
@@ -123,6 +125,7 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
width: setup.width,
height: setup.height,
scratch: Vec::with_capacity(frame_size),
frame_count: setup.frame_counter.clone(),
})
}
@@ -149,6 +152,7 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
tracing::error!("ffmpeg stdin write failed: {e}");
anyhow!("ffmpeg encoder stopped unexpectedly: {e}")
})?;
self.frame_count.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
Ok(())
}
}
@@ -168,6 +172,7 @@ pub struct CaptureSession {
pub width: u32,
pub height: u32,
pub crop: Option<CaptureRect>,
pub frame_counter: Arc<std::sync::atomic::AtomicU64>,
control: CaptureControl<CaptureHandler, anyhow::Error>,
}
@@ -245,6 +250,8 @@ pub fn start(
let (out_w, out_h) = compute_output_dims(width, height, crop);
let frame_counter = Arc::new(std::sync::atomic::AtomicU64::new(0));
let setup = CaptureSetup {
output_path: output_path.clone(),
ffmpeg_path,
@@ -252,6 +259,7 @@ pub fn start(
height,
fps,
crop,
frame_counter: frame_counter.clone(),
};
let cursor_setting = if capture_cursor {
@@ -280,6 +288,7 @@ pub fn start(
width: out_w,
height: out_h,
crop,
frame_counter,
control,
})
}
@@ -318,42 +327,17 @@ impl CaptureSession {
}
/// 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,
frame_count: u64,
) -> Result<()> {
use std::process::Command;
// Count frames by running ffmpeg with null output
let probe = Command::new(ffmpeg)
.args(["-hide_banner", "-loglevel", "error",
"-i", &input.to_string_lossy(),
"-map", "0:v:0", "-c", "copy", "-f", "null", "-"])
.output()
.context("counting frames with ffmpeg")?;
let stderr = String::from_utf8_lossy(&probe.stderr);
// stderr contains: "frame= NNN fps=..."
let frame_count: u32 = stderr
.lines()
.filter_map(|line| {
let line = line.trim();
if line.starts_with("frame=") {
let after = line.strip_prefix("frame=")?.trim_start();
let num_str: String = after.chars().take_while(|c| c.is_ascii_digit()).collect();
num_str.parse().ok()
} else {
None
}
})
.last()
.unwrap_or(0);
if frame_count == 0 || elapsed_secs <= 0.0 {
tracing::warn!("capture fix: could not count frames, keeping original");
tracing::warn!("capture fix: no frames counted, keeping original");
let _ = std::fs::rename(input, output);
return Ok(());
}
+4 -2
View File
@@ -432,10 +432,11 @@ 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 frames = session.frame_counter.load(std::sync::atomic::Ordering::Relaxed);
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)
capture::fix_intermediate_fps(&ffmpeg, &raw_path, &fixed_path, elapsed, frames)
.map_err(|e| format!("fixing fps: {e:#}"))?;
let path = if fixed_path.exists() { fixed_path } else { raw_path };
@@ -519,10 +520,11 @@ fn stop_capture(app: AppHandle, state: State<'_, AppState>) -> Result<RecordedCl
let live = lock(&state.capture).take();
if let Some(session) = live {
let elapsed = session.started_at.elapsed().as_secs_f64();
let frames = session.frame_counter.load(std::sync::atomic::Ordering::Relaxed);
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)
capture::fix_intermediate_fps(&ffmpeg, &raw_path, &fixed_path, elapsed, frames)
.map_err(|e| format!("fixing fps: {e:#}"))?;
let final_path = if fixed_path.exists() { fixed_path } else { raw_path };
ss.segments.push(final_path);