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:
@@ -71,7 +71,11 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
|
|||||||
// The capture API delivers frames at the monitor's refresh rate, not the
|
// 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
|
// 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.
|
// 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);
|
let mut cmd = Command::new(&setup.ffmpeg_path);
|
||||||
cmd.arg("-y")
|
cmd.arg("-y")
|
||||||
@@ -80,6 +84,7 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
|
|||||||
.args(["-f", "rawvideo"])
|
.args(["-f", "rawvideo"])
|
||||||
.args(["-pixel_format", "bgra"])
|
.args(["-pixel_format", "bgra"])
|
||||||
.args(["-video_size", &format!("{}x{}", setup.width, setup.height)])
|
.args(["-video_size", &format!("{}x{}", setup.width, setup.height)])
|
||||||
|
.args(["-framerate", &declared_fps.to_string()])
|
||||||
.args(["-i", "-"])
|
.args(["-i", "-"])
|
||||||
.args(["-vf", &filter])
|
.args(["-vf", &filter])
|
||||||
.args(["-c:v", "libx264"])
|
.args(["-c:v", "libx264"])
|
||||||
@@ -300,9 +305,6 @@ fn compute_output_dims(monitor_w: u32, monitor_h: u32, crop: Option<CaptureRect>
|
|||||||
|
|
||||||
impl CaptureSession {
|
impl CaptureSession {
|
||||||
pub fn stop(self) -> Result<PathBuf> {
|
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 _ = self.control.stop();
|
||||||
let meta = std::fs::metadata(&self.output_path)
|
let meta = std::fs::metadata(&self.output_path)
|
||||||
.with_context(|| format!("checking output file {}", self.output_path.display()))?;
|
.with_context(|| format!("checking output file {}", self.output_path.display()))?;
|
||||||
@@ -312,3 +314,73 @@ impl CaptureSession {
|
|||||||
Ok(self.output_path)
|
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(())
|
||||||
|
}
|
||||||
|
|||||||
+1
-10
@@ -397,16 +397,7 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
// Only adjust DOWN when file is too big
|
// Only adjust DOWN when file is too big - never exceed target
|
||||||
// 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(());
|
|
||||||
}
|
|
||||||
|
|
||||||
// File is too big - scale down based on budget priority
|
// File is too big - scale down based on budget priority
|
||||||
match req.gif_budget_mode {
|
match req.gif_budget_mode {
|
||||||
GifBudgetMode::Resolution => {
|
GifBudgetMode::Resolution => {
|
||||||
|
|||||||
+13
-3
@@ -432,7 +432,12 @@ fn pause_capture(state: State<'_, AppState>) -> Result<(), String> {
|
|||||||
.take()
|
.take()
|
||||||
.ok_or_else(|| "no capture in progress".to_string())?;
|
.ok_or_else(|| "no capture in progress".to_string())?;
|
||||||
let elapsed = session.started_at.elapsed().as_secs_f64();
|
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)
|
let audio_path = lock(&state.audio)
|
||||||
.take()
|
.take()
|
||||||
@@ -514,8 +519,13 @@ fn stop_capture(app: AppHandle, state: State<'_, AppState>) -> Result<RecordedCl
|
|||||||
let live = lock(&state.capture).take();
|
let live = lock(&state.capture).take();
|
||||||
if let Some(session) = live {
|
if let Some(session) = live {
|
||||||
let elapsed = session.started_at.elapsed().as_secs_f64();
|
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:#}"))?;
|
||||||
ss.segments.push(path);
|
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 final_path = if fixed_path.exists() { fixed_path } else { raw_path };
|
||||||
|
ss.segments.push(final_path);
|
||||||
ss.total_recorded_secs += elapsed;
|
ss.total_recorded_secs += elapsed;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user