calibrate gif size, probe codecs, align audio with video
- sample-encode gif calibration before the retry loop - probe ffmpeg encoders and grey out missing codecs in settings - pad audio head with silence so it lines up with video start - cache gif preview palette keyed on colors and sample window - read encode progress from -progress pipe:1 instead of stderr scraping - thread bt709 color metadata through capture, fix, and gif scale - sweep temp on startup - gif estimate table for the ui, interpolated locally on slider drag
This commit is contained in:
+120
-43
@@ -19,6 +19,7 @@ use windows_capture::settings::{
|
||||
use crate::CaptureRect;
|
||||
|
||||
const MAX_ENCODE_WIDTH: u32 = 1920;
|
||||
const FALLBACK_REFRESH_HZ: u32 = 60;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CaptureSetup {
|
||||
@@ -26,9 +27,8 @@ pub struct CaptureSetup {
|
||||
pub ffmpeg_path: PathBuf,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
#[allow(dead_code)]
|
||||
pub fps: u32,
|
||||
pub crop: Option<CaptureRect>,
|
||||
pub pipe_fps: u32,
|
||||
pub frame_counter: Arc<std::sync::atomic::AtomicU64>,
|
||||
}
|
||||
|
||||
@@ -60,10 +60,6 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
|
||||
setup.width
|
||||
};
|
||||
|
||||
// Capture at declared rate, apply fps filter to normalize timestamps.
|
||||
// fix_intermediate_fps re-encodes with measured actual rate after.
|
||||
filter_parts.push(format!("fps={}", setup.fps));
|
||||
|
||||
if working_width > MAX_ENCODE_WIDTH {
|
||||
filter_parts.push(format!("scale={}:-2", MAX_ENCODE_WIDTH));
|
||||
} else {
|
||||
@@ -74,13 +70,14 @@ 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: size={}x{}", setup.width, setup.height);
|
||||
|
||||
// Declare a high-ish framerate so ffmpeg accepts all frames from the pipe.
|
||||
// The actual delivery rate varies; fix_intermediate_fps re-encodes with
|
||||
// the measured rate after capture.
|
||||
let capture_fps = 120u32;
|
||||
tracing::info!(
|
||||
"capture: size={}x{} pipe_fps={}",
|
||||
setup.width, setup.height, setup.pipe_fps
|
||||
);
|
||||
|
||||
// Declare the detected refresh rate so ffmpeg accepts all frames from the
|
||||
// pipe. The actual delivery rate varies; fix_intermediate_fps re-encodes
|
||||
// with the measured rate after capture.
|
||||
let mut cmd = Command::new(&setup.ffmpeg_path);
|
||||
cmd.arg("-y")
|
||||
.arg("-hide_banner")
|
||||
@@ -88,12 +85,15 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
|
||||
.args(["-f", "rawvideo"])
|
||||
.args(["-pixel_format", "bgra"])
|
||||
.args(["-video_size", &format!("{}x{}", setup.width, setup.height)])
|
||||
.args(["-framerate", &capture_fps.to_string()])
|
||||
.args(["-framerate", &setup.pipe_fps.to_string()])
|
||||
.args(["-i", "-"])
|
||||
.args(["-vf", &filter])
|
||||
.args(["-c:v", "libx264"])
|
||||
.args(["-preset", "ultrafast"])
|
||||
.args(["-tune", "zerolatency"])
|
||||
.args(["-color_primaries", "bt709"])
|
||||
.args(["-color_trc", "bt709"])
|
||||
.args(["-colorspace", "bt709"])
|
||||
.args(["-pix_fmt", "yuv420p"])
|
||||
.args(["-movflags", "+faststart"])
|
||||
.arg(&setup.output_path)
|
||||
@@ -118,13 +118,13 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
|
||||
});
|
||||
}
|
||||
|
||||
let frame_size = (setup.width as usize) * (setup.height as usize) * 4;
|
||||
let pixels = (setup.width as usize) * (setup.height as usize);
|
||||
Ok(Self {
|
||||
stdin: Some(stdin),
|
||||
child: Some(child),
|
||||
width: setup.width,
|
||||
height: setup.height,
|
||||
scratch: Vec::with_capacity(frame_size),
|
||||
scratch: Vec::with_capacity(pixels * 4),
|
||||
frame_count: setup.frame_counter.clone(),
|
||||
})
|
||||
}
|
||||
@@ -141,9 +141,15 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
|
||||
let buf = frame
|
||||
.buffer()
|
||||
.map_err(|e| anyhow!("frame buffer: {e:?}"))?;
|
||||
self.scratch.clear();
|
||||
let bytes = buf.as_nopadding_buffer(&mut self.scratch);
|
||||
let expected = (self.width as usize) * (self.height as usize) * 4;
|
||||
if buf.has_padding() {
|
||||
// windows-capture copies padded rows into the provided Vec, but only
|
||||
// grows it when capacity is too small. Keep len valid.
|
||||
self.scratch.resize(expected, 0);
|
||||
} else {
|
||||
self.scratch.clear();
|
||||
}
|
||||
let bytes = buf.as_nopadding_buffer(&mut self.scratch);
|
||||
if bytes.len() < expected {
|
||||
tracing::warn!("frame buffer too small: got {} bytes, expected {}", bytes.len(), expected);
|
||||
return Ok(());
|
||||
@@ -172,6 +178,7 @@ pub struct CaptureSession {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub crop: Option<CaptureRect>,
|
||||
pub pipe_fps: u32,
|
||||
pub frame_counter: Arc<std::sync::atomic::AtomicU64>,
|
||||
control: CaptureControl<CaptureHandler, anyhow::Error>,
|
||||
}
|
||||
@@ -187,23 +194,36 @@ pub fn primary_monitor_dims() -> Result<(u32, u32)> {
|
||||
Ok((w & !1, h & !1))
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
/// Detect the primary monitor's refresh rate in Hz.
|
||||
/// Falls back to 60 if detection fails.
|
||||
fn detect_monitor_refresh_rate() -> u32 {
|
||||
use windows::Win32::Graphics::Gdi::{DEVMODEW, ENUM_CURRENT_SETTINGS, EnumDisplaySettingsW};
|
||||
unsafe {
|
||||
let mut devmode: DEVMODEW = std::mem::zeroed();
|
||||
devmode.dmSize = std::mem::size_of::<DEVMODEW>() as u16;
|
||||
if EnumDisplaySettingsW(None, ENUM_CURRENT_SETTINGS, &mut devmode).as_bool() && devmode.dmDisplayFrequency > 0 {
|
||||
return devmode.dmDisplayFrequency as u32;
|
||||
/// Detect the monitor's refresh rate (Hz) via `Monitor::refresh_rate`, which
|
||||
/// resolves the device name through `GetMonitorInfoW` and queries its current
|
||||
/// settings with `EnumDisplaySettingsW`. Falls back to [`FALLBACK_REFRESH_HZ`]
|
||||
/// on any failure.
|
||||
fn monitor_refresh_rate(monitor: &Monitor) -> u32 {
|
||||
match monitor.refresh_rate() {
|
||||
Ok(0) => {
|
||||
tracing::warn!("monitor reported 0 Hz refresh, using fallback");
|
||||
FALLBACK_REFRESH_HZ
|
||||
}
|
||||
Ok(hz) => hz,
|
||||
Err(e) => {
|
||||
tracing::warn!("refresh rate detection failed ({e:?}), using fallback");
|
||||
FALLBACK_REFRESH_HZ
|
||||
}
|
||||
}
|
||||
60 // fallback
|
||||
}
|
||||
|
||||
/// Pick the pipe framerate ffmpeg should declare for raw input from the
|
||||
/// capture API. WGC delivers frames roughly at the monitor's refresh rate;
|
||||
/// declaring that rate (instead of a fixed high constant) keeps the raw
|
||||
/// timestamps close to real time so `fix_intermediate_fps` only nudges.
|
||||
fn detect_pipe_framerate(monitor: &Monitor) -> u32 {
|
||||
monitor_refresh_rate(monitor)
|
||||
}
|
||||
|
||||
/// Find the monitor containing the given screen point using the Win32 API.
|
||||
/// Falls back to the primary monitor if no monitor is found.
|
||||
/// Resolve the monitor containing the given screen point, falling back to the
|
||||
/// primary monitor on failure.
|
||||
fn monitor_at_point(x: i32, y: i32) -> Result<Monitor> {
|
||||
use windows::Win32::Foundation::POINT;
|
||||
use windows::Win32::Graphics::Gdi::{MonitorFromPoint, MONITOR_DEFAULTTONEAREST};
|
||||
@@ -214,8 +234,7 @@ fn monitor_at_point(x: i32, y: i32) -> Result<Monitor> {
|
||||
bail!("MonitorFromPoint returned null for ({x}, {y})");
|
||||
}
|
||||
// SAFETY: hmonitor is a valid monitor handle from MonitorFromPoint.
|
||||
let monitor = Monitor::from_raw_hmonitor(hmonitor.0 as *mut _);
|
||||
Ok(monitor)
|
||||
Ok(Monitor::from_raw_hmonitor(hmonitor.0))
|
||||
}
|
||||
|
||||
pub fn start(
|
||||
@@ -224,7 +243,7 @@ pub fn start(
|
||||
capture_cursor: bool,
|
||||
_audio: bool,
|
||||
crop: Option<CaptureRect>,
|
||||
fps: u32,
|
||||
_fps: u32,
|
||||
) -> Result<CaptureSession> {
|
||||
// Use the center of the capture region to determine which monitor to capture.
|
||||
// If the region spans monitors, we pick the one containing the center.
|
||||
@@ -252,13 +271,15 @@ pub fn start(
|
||||
|
||||
let frame_counter = Arc::new(std::sync::atomic::AtomicU64::new(0));
|
||||
|
||||
let pipe_fps = detect_pipe_framerate(&monitor);
|
||||
|
||||
let setup = CaptureSetup {
|
||||
output_path: output_path.clone(),
|
||||
ffmpeg_path,
|
||||
width,
|
||||
height,
|
||||
fps,
|
||||
crop,
|
||||
pipe_fps,
|
||||
frame_counter: frame_counter.clone(),
|
||||
};
|
||||
|
||||
@@ -288,6 +309,7 @@ pub fn start(
|
||||
width: out_w,
|
||||
height: out_h,
|
||||
crop,
|
||||
pipe_fps,
|
||||
frame_counter,
|
||||
control,
|
||||
})
|
||||
@@ -327,8 +349,8 @@ impl CaptureSession {
|
||||
}
|
||||
|
||||
/// Re-encode the intermediate file with correct timestamps.
|
||||
/// The capture declares -framerate N and applies fps=M filter.
|
||||
/// This scales PTS to match real-time duration.
|
||||
/// The capture declares a fixed pipe framerate and later scales PTS to match
|
||||
/// real-time duration from the measured frame count.
|
||||
///
|
||||
/// Idempotent: if `input` has already been consumed (e.g. a previous
|
||||
/// pause/resume cycle ran this to completion and removed it), and
|
||||
@@ -339,7 +361,7 @@ pub fn fix_intermediate_fps(
|
||||
output: &std::path::Path,
|
||||
elapsed_secs: f64,
|
||||
frame_count: u64,
|
||||
capture_fps: u32,
|
||||
pipe_fps: u32,
|
||||
) -> Result<()> {
|
||||
use std::process::Command;
|
||||
|
||||
@@ -350,17 +372,31 @@ pub fn fix_intermediate_fps(
|
||||
|
||||
if frame_count == 0 || elapsed_secs <= 0.0 {
|
||||
tracing::warn!("capture fix: no frames counted, keeping original");
|
||||
let _ = std::fs::rename(input, output);
|
||||
return Ok(());
|
||||
return rename_or_copy(input, output);
|
||||
}
|
||||
|
||||
let actual_fps = frame_count as f64 / elapsed_secs;
|
||||
let pts_scale = capture_fps as f64 / actual_fps;
|
||||
let (actual_fps, pts_scale) = capture_timing(frame_count, elapsed_secs, pipe_fps)
|
||||
.expect("frame_count and elapsed_secs were checked above");
|
||||
tracing::info!(
|
||||
"capture fix: {frame_count} frames in {elapsed_secs:.1}s = {actual_fps:.1}fps (declared {capture_fps}), pts_scale={pts_scale:.2}"
|
||||
"capture fix: {frame_count} frames in {elapsed_secs:.1}s = {actual_fps:.1}fps (declared {pipe_fps}), pts_scale={pts_scale:.4}"
|
||||
);
|
||||
|
||||
// Re-encode with scaled PTS to fix timing
|
||||
// If the measured rate already matches the declared pipe rate within 2%,
|
||||
// the timestamps are already correct - the capture API's clock and the
|
||||
// ffmpeg input clock agree. Skip the lossy re-encode and just rename.
|
||||
// This is the common case now that pipe_fps tracks the monitor's refresh
|
||||
// rate instead of a fixed high constant.
|
||||
if (pts_scale - 1.0).abs() <= 0.02 {
|
||||
tracing::debug!(
|
||||
"capture fix: pts_scale={pts_scale:.4} within no-op tolerance, renaming without re-encode"
|
||||
);
|
||||
return rename_or_copy(input, output);
|
||||
}
|
||||
|
||||
// Re-encode with scaled PTS to fix timing.
|
||||
// CRF 18 is visually lossless and avoids a second generation of H264
|
||||
// quantization on top of the segment encode. The preset stays fast so the
|
||||
// re-encode does not stall stop/pause/resume.
|
||||
let status = Command::new(ffmpeg)
|
||||
.arg("-y")
|
||||
.arg("-hide_banner")
|
||||
@@ -368,7 +404,11 @@ pub fn fix_intermediate_fps(
|
||||
.args(["-i", &input.to_string_lossy()])
|
||||
.args(["-vf", &format!("setpts=PTS*{:.4}", pts_scale)])
|
||||
.args(["-c:v", "libx264"])
|
||||
.args(["-preset", "ultrafast"])
|
||||
.args(["-preset", "veryfast"])
|
||||
.args(["-crf", "18"])
|
||||
.args(["-color_primaries", "bt709"])
|
||||
.args(["-color_trc", "bt709"])
|
||||
.args(["-colorspace", "bt709"])
|
||||
.args(["-pix_fmt", "yuv420p"])
|
||||
.arg(output)
|
||||
.status()
|
||||
@@ -378,7 +418,44 @@ pub fn fix_intermediate_fps(
|
||||
let _ = std::fs::remove_file(input);
|
||||
} else {
|
||||
tracing::warn!("capture fix: re-encode failed, keeping original");
|
||||
let _ = std::fs::rename(input, output);
|
||||
let _ = rename_or_copy(input, output);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Move `input` to `output`, falling back to a copy if the rename fails
|
||||
/// (e.g. cross-volume or a handle still holds the file on Windows).
|
||||
fn rename_or_copy(input: &std::path::Path, output: &std::path::Path) -> Result<()> {
|
||||
std::fs::rename(input, output)
|
||||
.or_else(|_| std::fs::copy(input, output).map(|_| ()))
|
||||
.with_context(|| format!("moving {} to {}", input.display(), output.display()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn capture_timing(frame_count: u64, elapsed_secs: f64, pipe_fps: u32) -> Option<(f64, f64)> {
|
||||
if frame_count == 0 || elapsed_secs <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let actual_fps = frame_count as f64 / elapsed_secs;
|
||||
Some((actual_fps, pipe_fps as f64 / actual_fps))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn timing_scale_uses_declared_pipe_rate() {
|
||||
let (actual_fps, pts_scale) = capture_timing(600, 10.0, 60).unwrap();
|
||||
assert_eq!(actual_fps, 60.0);
|
||||
assert_eq!(pts_scale, 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timing_scale_for_high_pipe_rate() {
|
||||
// 600 frames in 10s = 60 actual; pipe declared 120 -> pts scale 2.0
|
||||
let (actual_fps, pts_scale) = capture_timing(600, 10.0, 120).unwrap();
|
||||
assert_eq!(actual_fps, 60.0);
|
||||
assert_eq!(pts_scale, 2.0);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user