use std::io::Write; use std::path::PathBuf; use std::process::{Child, ChildStdin, Command, Stdio}; use std::time::Instant; use anyhow::{anyhow, 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 struct CaptureHandler { stdin: Option, child: Option, width: u32, height: u32, scratch: Vec, } 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), }) } 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; let slice = if bytes.len() >= expected { &bytes[..expected] } else { bytes }; let _ = stdin.write_all(slice); 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, control: CaptureControl, } pub fn start( output_path: PathBuf, ffmpeg_path: PathBuf, capture_cursor: bool, _audio: bool, crop: Option, fps: u32, ) -> Result { let monitor = Monitor::primary().map_err(|e| anyhow!("primary monitor: {e:?}"))?; 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) -> (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 { self.control .stop() .map_err(|e| anyhow!("capture stop: {e}"))?; Ok(self.output_path) } }