382 lines
12 KiB
Rust
382 lines
12 KiB
Rust
use std::io::Write;
|
|
use std::path::PathBuf;
|
|
use std::process::{Child, ChildStdin, Command, Stdio};
|
|
|
|
use std::time::Instant;
|
|
|
|
use anyhow::{anyhow, bail, Context, Result};
|
|
use windows_capture::capture::{
|
|
CaptureControl, Context as CaptureContext, GraphicsCaptureApiHandler,
|
|
};
|
|
use windows_capture::frame::Frame;
|
|
use windows_capture::graphics_capture_api::InternalCaptureControl;
|
|
use windows_capture::monitor::Monitor;
|
|
use windows_capture::settings::{
|
|
ColorFormat, CursorCaptureSettings, DirtyRegionSettings, DrawBorderSettings,
|
|
MinimumUpdateIntervalSettings, SecondaryWindowSettings, Settings,
|
|
};
|
|
|
|
use crate::CaptureRect;
|
|
|
|
const MAX_ENCODE_WIDTH: u32 = 1920;
|
|
|
|
#[derive(Debug, Clone)]
|
|
pub struct CaptureSetup {
|
|
pub output_path: PathBuf,
|
|
pub ffmpeg_path: PathBuf,
|
|
pub width: u32,
|
|
pub height: u32,
|
|
#[allow(dead_code)]
|
|
pub fps: u32,
|
|
pub crop: Option<CaptureRect>,
|
|
}
|
|
|
|
pub struct CaptureHandler {
|
|
stdin: Option<ChildStdin>,
|
|
child: Option<Child>,
|
|
width: u32,
|
|
height: u32,
|
|
scratch: Vec<u8>,
|
|
}
|
|
|
|
impl GraphicsCaptureApiHandler for CaptureHandler {
|
|
type Flags = CaptureSetup;
|
|
type Error = anyhow::Error;
|
|
|
|
fn new(ctx: CaptureContext<Self::Flags>) -> Result<Self, Self::Error> {
|
|
let setup = ctx.flags;
|
|
|
|
let mut filter_parts: Vec<String> = Vec::new();
|
|
let working_width = if let Some(c) = setup.crop {
|
|
let x = c.x.max(0);
|
|
let y = c.y.max(0);
|
|
let w = c.width.min(setup.width.saturating_sub(x as u32));
|
|
let h = c.height.min(setup.height.saturating_sub(y as u32));
|
|
filter_parts.push(format!("crop={}:{}:{}:{}", w, h, x, y));
|
|
w
|
|
} else {
|
|
setup.width
|
|
};
|
|
|
|
// Capture all frames at the rate they arrive. No fps filter in capture -
|
|
// the export pipeline handles frame rate conversion.
|
|
|
|
if working_width > MAX_ENCODE_WIDTH {
|
|
filter_parts.push(format!("scale={}:-2", MAX_ENCODE_WIDTH));
|
|
} else {
|
|
filter_parts.push("scale=trunc(iw/2)*2:trunc(ih/2)*2".to_string());
|
|
}
|
|
let filter = filter_parts.join(",");
|
|
|
|
// 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);
|
|
|
|
let mut cmd = Command::new(&setup.ffmpeg_path);
|
|
cmd.arg("-y")
|
|
.arg("-hide_banner")
|
|
.args(["-loglevel", "error"])
|
|
.args(["-f", "rawvideo"])
|
|
.args(["-pixel_format", "bgra"])
|
|
.args(["-video_size", &format!("{}x{}", setup.width, setup.height)])
|
|
.args(["-i", "-"])
|
|
.args(["-vf", &filter])
|
|
.args(["-c:v", "libx264"])
|
|
.args(["-preset", "ultrafast"])
|
|
.args(["-tune", "zerolatency"])
|
|
.args(["-pix_fmt", "yuv420p"])
|
|
.args(["-movflags", "+faststart"])
|
|
.arg(&setup.output_path)
|
|
.stdin(Stdio::piped())
|
|
.stdout(Stdio::null())
|
|
.stderr(Stdio::piped());
|
|
|
|
let mut child = cmd.spawn().map_err(|e| anyhow!("spawning ffmpeg: {e}"))?;
|
|
let stdin = child
|
|
.stdin
|
|
.take()
|
|
.ok_or_else(|| anyhow!("ffmpeg stdin not captured"))?;
|
|
// Read stderr in background to capture ffmpeg errors
|
|
let stderr = child.stderr.take();
|
|
if let Some(serr) = stderr {
|
|
std::thread::spawn(move || {
|
|
use std::io::{BufRead, BufReader};
|
|
let reader = BufReader::new(serr);
|
|
for line in reader.lines().map_while(Result::ok) {
|
|
tracing::debug!("ffmpeg: {line}");
|
|
}
|
|
});
|
|
}
|
|
|
|
let frame_size = (setup.width as usize) * (setup.height as usize) * 4;
|
|
Ok(Self {
|
|
stdin: Some(stdin),
|
|
child: Some(child),
|
|
width: setup.width,
|
|
height: setup.height,
|
|
scratch: Vec::with_capacity(frame_size),
|
|
})
|
|
}
|
|
|
|
fn on_frame_arrived(
|
|
&mut self,
|
|
frame: &mut Frame<'_>,
|
|
_capture_control: InternalCaptureControl,
|
|
) -> Result<(), Self::Error> {
|
|
let Some(stdin) = self.stdin.as_mut() else {
|
|
return Ok(());
|
|
};
|
|
|
|
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 bytes.len() < expected {
|
|
tracing::warn!("frame buffer too small: got {} bytes, expected {}", bytes.len(), expected);
|
|
return Ok(());
|
|
}
|
|
stdin.write_all(&bytes[..expected]).map_err(|e| {
|
|
tracing::error!("ffmpeg stdin write failed: {e}");
|
|
anyhow!("ffmpeg encoder stopped unexpectedly: {e}")
|
|
})?;
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
impl Drop for CaptureHandler {
|
|
fn drop(&mut self) {
|
|
drop(self.stdin.take());
|
|
if let Some(mut child) = self.child.take() {
|
|
let _ = child.wait();
|
|
}
|
|
}
|
|
}
|
|
|
|
pub struct CaptureSession {
|
|
pub output_path: PathBuf,
|
|
pub started_at: Instant,
|
|
pub width: u32,
|
|
pub height: u32,
|
|
pub crop: Option<CaptureRect>,
|
|
control: CaptureControl<CaptureHandler, anyhow::Error>,
|
|
}
|
|
|
|
pub fn primary_monitor_dims() -> Result<(u32, u32)> {
|
|
let monitor = Monitor::primary().map_err(|e| anyhow!("primary monitor: {e:?}"))?;
|
|
let w = monitor
|
|
.width()
|
|
.map_err(|e| anyhow!("monitor width: {e:?}"))?;
|
|
let h = monitor
|
|
.height()
|
|
.map_err(|e| anyhow!("monitor height: {e:?}"))?;
|
|
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;
|
|
}
|
|
}
|
|
60 // fallback
|
|
}
|
|
|
|
/// Find the monitor containing the given screen point using the Win32 API.
|
|
/// Falls back to the primary monitor if no monitor is found.
|
|
fn monitor_at_point(x: i32, y: i32) -> Result<Monitor> {
|
|
use windows::Win32::Foundation::POINT;
|
|
use windows::Win32::Graphics::Gdi::{MonitorFromPoint, MONITOR_DEFAULTTONEAREST};
|
|
|
|
let pt = POINT { x, y };
|
|
let hmonitor = unsafe { MonitorFromPoint(pt, MONITOR_DEFAULTTONEAREST) };
|
|
if hmonitor.0.is_null() {
|
|
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)
|
|
}
|
|
|
|
pub fn start(
|
|
output_path: PathBuf,
|
|
ffmpeg_path: PathBuf,
|
|
capture_cursor: bool,
|
|
_audio: bool,
|
|
crop: Option<CaptureRect>,
|
|
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.
|
|
let monitor = if let Some(ref c) = crop {
|
|
let cx = c.x.saturating_add(c.width as i32 / 2);
|
|
let cy = c.y.saturating_add(c.height as i32 / 2);
|
|
tracing::info!("capture center=({cx}, {cy}), selecting monitor");
|
|
monitor_at_point(cx, cy).unwrap_or_else(|_| {
|
|
tracing::warn!("no monitor at ({cx}, {cy}), falling back to primary");
|
|
Monitor::primary().expect("primary monitor always available")
|
|
})
|
|
} else {
|
|
Monitor::primary().expect("primary monitor always available")
|
|
};
|
|
let raw_width = monitor
|
|
.width()
|
|
.map_err(|e| anyhow!("monitor width: {e:?}"))?;
|
|
let raw_height = monitor
|
|
.height()
|
|
.map_err(|e| anyhow!("monitor height: {e:?}"))?;
|
|
let width = raw_width & !1;
|
|
let height = raw_height & !1;
|
|
|
|
let (out_w, out_h) = compute_output_dims(width, height, crop);
|
|
|
|
let setup = CaptureSetup {
|
|
output_path: output_path.clone(),
|
|
ffmpeg_path,
|
|
width,
|
|
height,
|
|
fps,
|
|
crop,
|
|
};
|
|
|
|
let cursor_setting = if capture_cursor {
|
|
CursorCaptureSettings::WithCursor
|
|
} else {
|
|
CursorCaptureSettings::WithoutCursor
|
|
};
|
|
|
|
let settings = Settings::new(
|
|
monitor,
|
|
cursor_setting,
|
|
DrawBorderSettings::Default,
|
|
SecondaryWindowSettings::Default,
|
|
MinimumUpdateIntervalSettings::Default,
|
|
DirtyRegionSettings::Default,
|
|
ColorFormat::Bgra8,
|
|
setup,
|
|
);
|
|
|
|
let control = CaptureHandler::start_free_threaded(settings)
|
|
.map_err(|e| anyhow!("capture start: {e}"))?;
|
|
|
|
Ok(CaptureSession {
|
|
output_path,
|
|
started_at: Instant::now(),
|
|
width: out_w,
|
|
height: out_h,
|
|
crop,
|
|
control,
|
|
})
|
|
}
|
|
|
|
fn compute_output_dims(monitor_w: u32, monitor_h: u32, crop: Option<CaptureRect>) -> (u32, u32) {
|
|
let (raw_w, raw_h) = match crop {
|
|
Some(c) => {
|
|
let x = c.x.max(0) as u32;
|
|
let y = c.y.max(0) as u32;
|
|
(
|
|
c.width.min(monitor_w.saturating_sub(x)),
|
|
c.height.min(monitor_h.saturating_sub(y)),
|
|
)
|
|
}
|
|
None => (monitor_w, monitor_h),
|
|
};
|
|
if raw_w > MAX_ENCODE_WIDTH {
|
|
let scale = MAX_ENCODE_WIDTH as f64 / raw_w as f64;
|
|
let nh = (raw_h as f64 * scale).round() as u32;
|
|
(MAX_ENCODE_WIDTH, (nh / 2) * 2)
|
|
} else {
|
|
((raw_w / 2) * 2, (raw_h / 2) * 2)
|
|
}
|
|
}
|
|
|
|
impl CaptureSession {
|
|
pub fn stop(self) -> Result<PathBuf> {
|
|
let _ = self.control.stop();
|
|
let meta = std::fs::metadata(&self.output_path)
|
|
.with_context(|| format!("checking output file {}", self.output_path.display()))?;
|
|
if meta.len() == 0 {
|
|
bail!("capture output file is empty - ffmpeg may have crashed during recording");
|
|
}
|
|
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(())
|
|
}
|