use std::io::Write; use std::path::PathBuf; use std::process::{Child, ChildStdin, Command, Stdio}; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; 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, pub fps: u32, pub crop: Option, pub crashed: Arc, } pub struct CaptureHandler { stdin: Option, child: Option, width: u32, height: u32, scratch: Vec, crashed: Arc, } impl GraphicsCaptureApiHandler for CaptureHandler { type Flags = CaptureSetup; type Error = anyhow::Error; fn new(ctx: CaptureContext) -> Result { let setup = ctx.flags; let mut filter_parts: Vec = 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 }; 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(","); 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(["-framerate", &setup.fps.to_string()]) .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::null()); 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"))?; 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), crashed: setup.crashed, }) } 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} - encoder may have crashed"); self.crashed.store(true, Ordering::Release); 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, pub crashed: Arc, control: CaptureControl, } 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)) } /// 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 { 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, fps: u32, ) -> Result { // 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 crashed = Arc::new(AtomicBool::new(false)); let setup = CaptureSetup { output_path: output_path.clone(), ffmpeg_path, width, height, fps, crop, crashed: crashed.clone(), }; 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, crashed, control, }) } fn compute_output_dims(monitor_w: u32, monitor_h: u32, crop: Option) -> (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 has_crashed(&self) -> bool { self.crashed.load(Ordering::Acquire) } pub fn stop(self) -> Result { self.control .stop() .map_err(|e| anyhow!("capture stop: {e}"))?; 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) } }