use std::io::Write; use std::path::PathBuf; use std::process::{Child, ChildStdin, Command, Stdio}; use std::sync::Arc; use std::time::Instant; use anyhow::{anyhow, bail, Context, Result}; use windows::Win32::Graphics::Direct3D::{ D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, D3D_SRV_DIMENSION_TEXTURE2D, }; use windows::Win32::Graphics::Direct3D11::{ ID3D11Buffer, ID3D11Device, ID3D11DeviceContext, ID3D11InputLayout, ID3D11PixelShader, ID3D11RasterizerState, ID3D11RenderTargetView, ID3D11SamplerState, ID3D11ShaderResourceView, ID3D11Texture2D, ID3D11VertexShader, D3D11_BIND_RENDER_TARGET, D3D11_BIND_SHADER_RESOURCE, D3D11_BIND_VERTEX_BUFFER, D3D11_BUFFER_DESC, D3D11_CPU_ACCESS_READ, D3D11_CULL_NONE, D3D11_FILL_SOLID, D3D11_FILTER_MIN_MAG_MIP_POINT, D3D11_INPUT_ELEMENT_DESC, D3D11_INPUT_PER_VERTEX_DATA, D3D11_MAP_READ, D3D11_MAPPED_SUBRESOURCE, D3D11_RASTERIZER_DESC, D3D11_RENDER_TARGET_VIEW_DESC, D3D11_RTV_DIMENSION_TEXTURE2D, D3D11_SAMPLER_DESC, D3D11_SHADER_RESOURCE_VIEW_DESC, D3D11_SUBRESOURCE_DATA, D3D11_TEXTURE2D_DESC, D3D11_TEXTURE_ADDRESS_CLAMP, D3D11_TEX2D_RTV, D3D11_TEX2D_SRV, D3D11_USAGE_DEFAULT, D3D11_USAGE_IMMUTABLE, D3D11_USAGE_STAGING, D3D11_VIEWPORT, }; use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_SAMPLE_DESC}; 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::config::CaptureQuality; use crate::CaptureRect; // Precompiled shader bytecode (build.rs invokes fxc). See shaders/tonemap.hlsl. const FULLSCREEN_VS: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/fullscreen_vs.cso")); const TONEMAP_PS: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/tonemap_ps.cso")); /// Hard ceiling for the Full quality mode so a 4K recording can't balloon to /// 8K on exotic hardware. Auto mode caps at `AUTO_ENCODE_WIDTH` instead. const MAX_ENCODE_WIDTH: u32 = 3840; const AUTO_ENCODE_WIDTH: u32 = 1920; const FALLBACK_REFRESH_HZ: u32 = 60; /// The cap to apply to the encode width in pixels. /// Auto keeps the historic 1920 cap so nothing changes for existing users; /// Full records at native res up to `MAX_ENCODE_WIDTH` (3840). fn encode_width_limit(quality: CaptureQuality) -> u32 { match quality { CaptureQuality::Auto => AUTO_ENCODE_WIDTH, CaptureQuality::Full => MAX_ENCODE_WIDTH, } } #[derive(Debug, Clone)] pub(crate) struct CaptureSetup { pub output_path: PathBuf, pub ffmpeg_path: PathBuf, pub width: u32, pub height: u32, pub crop: Option, pub pipe_fps: u32, pub encode_width_limit: u32, pub frame_counter: Arc, } pub(crate) struct CaptureHandler { stdin: Option, child: Option, width: u32, height: u32, /// GPU tonemap pipeline, lazily initialized on the first frame (needs the /// D3D11 device/context from the frame). Recreated on resize. pipeline: Option, frame_count: Arc, } /// Persistent D3D11 state for the HDR->SDR tonemap pass. Owns the render /// target, sampler, shaders, and a staging texture sized to the capture. /// Built once per capture session and rebuilt if the frame dimensions change. struct TonemapPipeline { vs: ID3D11VertexShader, ps: ID3D11PixelShader, input_layout: ID3D11InputLayout, vertex_buffer: ID3D11Buffer, sampler: ID3D11SamplerState, rasterizer: ID3D11RasterizerState, render_target: ID3D11Texture2D, rtv: ID3D11RenderTargetView, staging: ID3D11Texture2D, width: u32, height: u32, } // One D3D11 object per descriptor, in the order the API documents them; the // length is the API's, not ours, and splitting it would scatter a single // initialization sequence across helpers that each need half the locals. #[allow( clippy::too_many_lines, reason = "linear D3D11 resource setup: each step needs the previous object in scope" )] impl TonemapPipeline { fn new(device: &ID3D11Device, width: u32, height: u32) -> Result { // Vertex shader: fullscreen-triangle pass-through (no vertex buffer). let mut vs = None; unsafe { // SAFETY: `device` is the live ID3D11Device owned by the capture // frame. FULLSCREEN_VS is bytecode embedded at build time, and the // out-param points at a local Option the call writes through. device.CreateVertexShader(FULLSCREEN_VS, None, Some(&raw mut vs))?; } let vs = vs.ok_or_else(|| anyhow!("CreateVertexShader returned null"))?; // Input layout matching the VS signature (POSITION float2, TEXCOORD float2). // Validated against the VS bytecode by CreateInputLayout. let input_elements = [ D3D11_INPUT_ELEMENT_DESC { SemanticName: windows::core::PCSTR(c"POSITION".as_ptr().cast()), SemanticIndex: 0, Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32G32_FLOAT, InputSlot: 0, AlignedByteOffset: 0, InputSlotClass: D3D11_INPUT_PER_VERTEX_DATA, InstanceDataStepRate: 0, }, D3D11_INPUT_ELEMENT_DESC { SemanticName: windows::core::PCSTR(c"TEXCOORD".as_ptr().cast()), SemanticIndex: 0, Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32G32_FLOAT, InputSlot: 0, AlignedByteOffset: 8, InputSlotClass: D3D11_INPUT_PER_VERTEX_DATA, InstanceDataStepRate: 0, }, ]; let mut input_layout = None; unsafe { // SAFETY: the element descriptions and the vertex-shader bytecode // are both valid for the duration of the call; CreateInputLayout // validates that they match and errors if they do not. device.CreateInputLayout( &input_elements, FULLSCREEN_VS, Some(&raw mut input_layout), )?; } let input_layout = input_layout.ok_or_else(|| anyhow!("CreateInputLayout returned null"))?; // 3-vertex buffer for a fullscreen triangle. Each vertex is pos.xy + uv.xy // (4 floats = 16 bytes). Triangle covers clip space (-1..1) with UV 0..1. // Winding is clockwise for default D3D11 front-face (FrontCounterClockwise=false). let verts: [f32; 12] = [ // pos.x pos.y u v -1.0, -1.0, 0.0, 1.0, // bottom-left 3.0, -1.0, 2.0, 1.0, // bottom-right (off-screen, completes the triangle) -1.0, 3.0, 0.0, -1.0, // top-left (off-screen) ]; let vb_desc = D3D11_BUFFER_DESC { // verts is a 12-float array, so the size is a compile-time constant // well inside u32. ByteWidth: u32::try_from(size_of_val(&verts)).unwrap_or(0), Usage: D3D11_USAGE_IMMUTABLE, BindFlags: D3D11_BIND_VERTEX_BUFFER.0 as u32, CPUAccessFlags: 0, MiscFlags: 0, StructureByteStride: 0, }; let vb_init = D3D11_SUBRESOURCE_DATA { pSysMem: verts.as_ptr().cast::(), SysMemPitch: 0, SysMemSlicePitch: 0, }; let mut vertex_buffer = None; unsafe { // SAFETY: both descriptions are stack locals that outlive the call, // and vb_init.pSysMem points at the `verts` array declared above. device.CreateBuffer(&raw const vb_desc, Some(&raw const vb_init), Some(&raw mut vertex_buffer))?; } let vertex_buffer = vertex_buffer.ok_or_else(|| anyhow!("CreateBuffer vb returned null"))?; // Pixel shader: Hable tonemap + bt709 OETF. let mut ps = None; unsafe { // SAFETY: live device, build-time-embedded bytecode, local out-param. device.CreatePixelShader(TONEMAP_PS, None, Some(&raw mut ps))?; } let ps = ps.ok_or_else(|| anyhow!("CreatePixelShader returned null"))?; // Point-clamp sampler - 1:1 screen-space sampling of the captured frame. let sampler_desc = D3D11_SAMPLER_DESC { Filter: D3D11_FILTER_MIN_MAG_MIP_POINT, AddressU: D3D11_TEXTURE_ADDRESS_CLAMP, AddressV: D3D11_TEXTURE_ADDRESS_CLAMP, AddressW: D3D11_TEXTURE_ADDRESS_CLAMP, MipLODBias: 0.0, MaxAnisotropy: 0, ComparisonFunc: windows::Win32::Graphics::Direct3D11::D3D11_COMPARISON_NEVER, BorderColor: [0.0; 4], MinLOD: 0.0, MaxLOD: 0.0, }; let mut sampler = None; unsafe { // SAFETY: sampler_desc is a fully-initialized stack local and the // out-param is a local Option. device.CreateSamplerState(&raw const sampler_desc, Some(&raw mut sampler))?; } let sampler = sampler.ok_or_else(|| anyhow!("CreateSamplerState returned null"))?; // Rasterizer with no culling. The default rasterizer state culls // back faces, which silently killed the fullscreen triangle (the // winding vs FrontCounterClockwise interaction culls the whole tri). // CULL_NONE removes that variable entirely. let rasterizer_desc = D3D11_RASTERIZER_DESC { FillMode: D3D11_FILL_SOLID, CullMode: D3D11_CULL_NONE, FrontCounterClockwise: windows::core::BOOL::default(), DepthBias: 0, DepthBiasClamp: 0.0, SlopeScaledDepthBias: 0.0, DepthClipEnable: windows::core::BOOL::default(), ScissorEnable: windows::core::BOOL(1), MultisampleEnable: windows::core::BOOL::default(), AntialiasedLineEnable: windows::core::BOOL::default(), }; let mut rasterizer = None; unsafe { // SAFETY: rasterizer_desc is a fully-initialized stack local and the // out-param is a local Option. device.CreateRasterizerState(&raw const rasterizer_desc, Some(&raw mut rasterizer))?; } let rasterizer = rasterizer.ok_or_else(|| anyhow!("CreateRasterizerState returned null"))?; // SDR render target (BGRA8). The shader writes gamma-encoded bt709 here. let rt_desc = D3D11_TEXTURE2D_DESC { Width: width, Height: height, MipLevels: 1, ArraySize: 1, Format: DXGI_FORMAT_B8G8R8A8_UNORM, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, Usage: D3D11_USAGE_DEFAULT, BindFlags: (D3D11_BIND_RENDER_TARGET.0 | D3D11_BIND_SHADER_RESOURCE.0) as u32, CPUAccessFlags: 0, MiscFlags: 0, }; let mut render_target = None; unsafe { // SAFETY: rt_desc is a fully-initialized stack local and the // out-param is a local Option. device.CreateTexture2D(&raw const rt_desc, None, Some(&raw mut render_target))?; } let render_target = render_target.ok_or_else(|| anyhow!("CreateTexture2D rt returned null"))?; let view_desc = D3D11_RENDER_TARGET_VIEW_DESC { Format: DXGI_FORMAT_B8G8R8A8_UNORM, ViewDimension: D3D11_RTV_DIMENSION_TEXTURE2D, Anonymous: windows::Win32::Graphics::Direct3D11::D3D11_RENDER_TARGET_VIEW_DESC_0 { Texture2D: D3D11_TEX2D_RTV { MipSlice: 0 }, }, }; let mut rtv = None; unsafe { // SAFETY: render_target was just created on this device and // view_desc describes a valid subresource of it. device.CreateRenderTargetView(&render_target, Some(&raw const view_desc), Some(&raw mut rtv))?; } let rtv = rtv.ok_or_else(|| anyhow!("CreateRenderTargetView returned null"))?; // Staging texture for CPU readback. Same format as the RT. let staging_desc = D3D11_TEXTURE2D_DESC { Width: width, Height: height, MipLevels: 1, ArraySize: 1, Format: DXGI_FORMAT_B8G8R8A8_UNORM, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, Usage: D3D11_USAGE_STAGING, BindFlags: 0, CPUAccessFlags: D3D11_CPU_ACCESS_READ.0 as u32, MiscFlags: 0, }; let mut staging = None; unsafe { // SAFETY: staging_desc is a fully-initialized stack local and the // out-param is a local Option. device.CreateTexture2D(&raw const staging_desc, None, Some(&raw mut staging))?; } let staging = staging.ok_or_else(|| anyhow!("CreateTexture2D staging returned null"))?; Ok(Self { vs, ps, input_layout, vertex_buffer, sampler, rasterizer, render_target, rtv, staging, width, height, }) } /// Run the tonemap shader on `src` (the captured HDR texture) and write /// the resulting BGRA8 bytes to `out`. One GPU draw + one staging readback. /// Recreates itself if `src` dimensions differ from the cached RT. // The draw sequence, the bind state and the readback all have to happen in // one call on the frame's own context; the length is the sequence. #[allow( clippy::too_many_lines, reason = "the GPU draw and its readback share one context and one mapped buffer" )] fn process( &mut self, device: &ID3D11Device, context: &ID3D11DeviceContext, src: &ID3D11Texture2D, out: &mut dyn Write, ) -> Result<()> { let mut desc = D3D11_TEXTURE2D_DESC::default(); // SAFETY: `desc` is a zero-initialized local that GetDesc fully writes; // `src` is the captured texture owned by this frame. unsafe { src.GetDesc(&raw mut desc) }; if desc.Width != self.width || desc.Height != self.height { // Resize - rebuild the RT/staging at the new dimensions. tracing::info!( "tonemap pipeline resize: {}x{} -> {}x{}", self.width, self.height, desc.Width, desc.Height ); *self = Self::new(device, desc.Width, desc.Height)?; } // SRV onto the captured HDR texture. let srv_desc = D3D11_SHADER_RESOURCE_VIEW_DESC { Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R16G16B16A16_FLOAT, ViewDimension: D3D_SRV_DIMENSION_TEXTURE2D, Anonymous: windows::Win32::Graphics::Direct3D11::D3D11_SHADER_RESOURCE_VIEW_DESC_0 { Texture2D: D3D11_TEX2D_SRV { MostDetailedMip: 0, MipLevels: 1, }, }, }; let mut srv: Option = None; // SAFETY: `src` is the live capture texture and was resized to match the // pipeline above; srv_desc is a stack local describing one mip. unsafe { device.CreateShaderResourceView(src, Some(&raw const srv_desc), Some(&raw mut srv))?; } let srv = srv.ok_or_else(|| anyhow!("CreateShaderResourceView returned null"))?; let vb = [Some(self.vertex_buffer.clone())]; let strides = [16u32]; let offsets = [0u32]; // Capture dimensions are at most 4K (well under f32's 2^24 exact-integer // limit), so the cast is lossless for every value this can hold. #[allow( clippy::cast_precision_loss, reason = "capture width/height are bounded by MAX_ENCODE_WIDTH (3840), exactly representable in f32" )] let viewport = [D3D11_VIEWPORT { TopLeftX: 0.0, TopLeftY: 0.0, Width: self.width as f32, Height: self.height as f32, MinDepth: 0.0, MaxDepth: 1.0, }]; // Scissor covering the whole RT (rasterizer has ScissorEnable=true). let scissor = [windows::Win32::Foundation::RECT { left: 0, top: 0, right: self.width.cast_signed(), bottom: self.height.cast_signed(), }]; // Canonical bind sequence: IA -> shaders -> resources -> output merger // -> viewport+scissor -> draw. Every stage is set explicitly because the // frame's device/context still carries state from prior frames. // #[allow( clippy::multiple_unsafe_ops_per_block, reason = "the bind sequence only makes sense as one unit; splitting it would imply the intermediate states are reachable" )] // SAFETY: every resource bound here was created on this same device and // is kept alive by `self` for the duration of the draw; the slices and // viewport/scissor arrays are stack locals that outlive each call. unsafe { context.IASetInputLayout(&self.input_layout); context.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); context.IASetVertexBuffers( 0, 1, Some(vb.as_ptr()), Some(strides.as_ptr()), Some(offsets.as_ptr()), ); context.VSSetShader(&self.vs, None); context.PSSetShader(&self.ps, None); context.PSSetShaderResources(0, Some(&[Some(srv.clone())])); context.PSSetSamplers(0, Some(&[Some(self.sampler.clone())])); context.OMSetRenderTargets(Some(&[Some(self.rtv.clone())]), None); context.RSSetState(&self.rasterizer); context.RSSetViewports(Some(&viewport)); context.RSSetScissorRects(Some(&scissor)); context.Draw(3, 0); } // Copy to the SDR staging texture and read it back. let row_bytes = self.width * 4; #[allow( clippy::multiple_unsafe_ops_per_block, reason = "copy/map/read/unmap must stay paired; the map guard has to be released in the same scope" )] // SAFETY: both textures live on this device and share dimensions and // format, so the copy is well-defined; `mapped` is a zeroed local that // Map fills before any field of it is read, and the slice is sized from // the mapped pitch and this pipeline's own height. unsafe { context.CopyResource(&self.staging, &self.render_target); let mut mapped = D3D11_MAPPED_SUBRESOURCE::default(); context.Map(&self.staging, 0, D3D11_MAP_READ, 0, Some(&raw mut mapped))?; let src_slice = std::slice::from_raw_parts( mapped.pData.cast::(), (mapped.RowPitch as usize) * (self.height as usize), ); // RowPitch may exceed width*4 (alignment); copy row by row. Every // slice is built from the mapped pitch and this pipeline's own // height, and a short buffer yields an error rather than a panic. let packed = (row_bytes as usize) * (self.height as usize); if mapped.RowPitch == row_bytes { let Some(frame) = src_slice.get(..packed) else { return Err(anyhow!("mapped frame smaller than expected")); }; out.write_all(frame) .map_err(|e| anyhow!("writing tonemapped frame: {e}"))?; } else { let pitch = mapped.RowPitch as usize; for y in 0..(self.height as usize) { let Some(row) = src_slice.get(y * pitch..y * pitch + row_bytes as usize) else { return Err(anyhow!("mapped row {y} outside the mapped buffer")); }; out.write_all(row) .map_err(|e| anyhow!("writing tonemapped frame: {e}"))?; } } context.Unmap(&self.staging, 0); } Ok(()) } } impl GraphicsCaptureApiHandler for CaptureHandler { type Flags = CaptureSetup; type Error = anyhow::Error; fn new(ctx: CaptureContext) -> Result { let setup = ctx.flags; // Capture-side filter is now just crop + scale-to-even/width-limit - // the HDR->SDR tonemap happens on the GPU before this pipe, so ffmpeg // receives plain SDR BGRA8 already in bt709/tv range. let mut filter_parts: Vec = Vec::new(); 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.cast_unsigned())); let h = c.height.min(setup.height.saturating_sub(y.cast_unsigned())); filter_parts.push(format!("crop={w}:{h}:{x}:{y}")); } let limit = setup.encode_width_limit; if setup.width > limit { filter_parts.push(format!("scale={limit}:-2")); } else { filter_parts.push("scale=trunc(iw/2)*2:trunc(ih/2)*2".to_string()); } let filter = filter_parts.join(","); tracing::info!( "capture: size={}x{} pipe_fps={}", setup.width, setup.height, setup.pipe_fps ); 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.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) .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::warn!("ffmpeg: {line}"); } }); } Ok(Self { stdin: Some(stdin), child: Some(child), width: setup.width, height: setup.height, pipeline: None, frame_count: setup.frame_counter.clone(), }) } 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 device = frame.device(); let context = frame.device_context(); let src = frame.as_raw_texture(); // Lazily build the GPU pipeline on the first frame (needs the device). if self.pipeline.is_none() { self.pipeline = Some(TonemapPipeline::new(device, self.width, self.height)?); } // process() takes the pipeline by mut ref; inline the Option dance. let pipeline = self .pipeline .as_mut() .ok_or_else(|| anyhow!("tonemap pipeline missing after initialization"))?; pipeline.process(device, context, src, stdin)?; self.frame_count.fetch_add(1, std::sync::atomic::Ordering::Relaxed); Ok(()) } } impl Drop for CaptureHandler { fn drop(&mut self) { drop(self.stdin.take()); if let Some(mut child) = self.child.take() { drop(child.wait()); } } } pub struct CaptureSession { pub output_path: PathBuf, pub started_at: Instant, pub width: u32, pub height: u32, pub crop: Option, pub pipe_fps: u32, pub frame_counter: Arc, control: CaptureControl, } pub(crate) 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)) } /// 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 } } } /// 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 { use windows::Win32::Foundation::POINT; use windows::Win32::Graphics::Gdi::{MonitorFromPoint, MONITOR_DEFAULTTONEAREST}; let pt = POINT { x, y }; let hmonitor = unsafe { // SAFETY: MonitorFromPoint writes nothing and only reads the POINT by // value; it returns the nearest monitor or null, which is checked next. 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. Ok(Monitor::from_raw_hmonitor(hmonitor.0)) } #[allow( clippy::expect_used, clippy::unwrap_in_result, reason = "Windows always has a primary monitor; if enumeration fails there is nothing sensible to capture instead" )] pub(crate) fn start( output_path: PathBuf, ffmpeg_path: PathBuf, capture_cursor: bool, _audio: bool, crop: Option, _fps: u32, quality: CaptureQuality, ) -> 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.cast_signed() / 2); let cy = c.y.saturating_add(c.height.cast_signed() / 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 limit = encode_width_limit(quality); let (out_w, out_h) = compute_output_dims(width, height, crop, limit); 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, crop, pipe_fps, encode_width_limit: limit, frame_counter: frame_counter.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::Rgba16F, 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, pipe_fps, frame_counter, control, }) } fn compute_output_dims( monitor_w: u32, monitor_h: u32, crop: Option, width_limit: u32, ) -> (u32, u32) { let (raw_w, raw_h) = match crop { Some(c) => { let x = c.x.max(0).cast_unsigned(); let y = c.y.max(0).cast_unsigned(); ( c.width.min(monitor_w.saturating_sub(x)), c.height.min(monitor_h.saturating_sub(y)), ) } None => (monitor_w, monitor_h), }; let cap = width_limit; if raw_w > cap { let scale = f64::from(cap) / f64::from(raw_w); let nh = crate::encode::round_u32(f64::from(raw_h) * scale); (cap, (nh / 2) * 2) } else { ((raw_w / 2) * 2, (raw_h / 2) * 2) } } impl CaptureSession { pub fn stop(self) -> Result { drop(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 correct timestamps. /// 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 /// `output` exists, returns Ok without re-running ffmpeg. #[allow( clippy::expect_used, clippy::unwrap_in_result, reason = "callers rule out the None case that capture_timing returns None for" )] pub(crate) fn fix_intermediate_fps( ffmpeg: &std::path::Path, input: &std::path::Path, output: &std::path::Path, elapsed_secs: f64, frame_count: u64, pipe_fps: u32, ) -> Result<()> { use std::process::Command; if !input.is_file() && output.is_file() { tracing::debug!("capture fix: input already consumed, output exists, skipping"); return Ok(()); } if frame_count == 0 || elapsed_secs <= 0.0 { tracing::warn!("capture fix: no frames counted, keeping original"); return rename_or_copy(input, output); } 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 {pipe_fps}), pts_scale={pts_scale:.4}" ); // 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); } // First try a stream copy with -itsscale: it rescales the input timestamps // without re-encoding, so no second generation of H264 quantization. The // segment encode uses ultrafast (no B-frames), so PTS stays monotonic and // -c copy + -itsscale is safe. If ffmpeg rejects it for some reason, fall // back to the lossy re-encode below. let copy_status = Command::new(ffmpeg) .arg("-y") .arg("-hide_banner") .args(["-loglevel", "error"]) .args(["-itsscale", &format!("{pts_scale:.6}")]) .args(["-i", &input.to_string_lossy()]) .args(["-c", "copy"]) .arg(output) .status() .context("stream-copy timestamp fix")?; if copy_status.success() && output.is_file() { tracing::debug!("capture fix: stream copy with -itsscale succeeded, no re-encode"); drop(std::fs::remove_file(input)); return Ok(()); } tracing::warn!("capture fix: -itsscale copy failed, falling back to re-encode"); drop(std::fs::remove_file(output)); // Fallback: re-encode with scaled PTS to fix timing. // CRF 18 is visually lossless; preset veryfast keeps stop/pause/resume snappy. let status = Command::new(ffmpeg) .arg("-y") .arg("-hide_banner") .args(["-loglevel", "error"]) .args(["-i", &input.to_string_lossy()]) .args(["-vf", &format!("setpts=PTS*{pts_scale:.4}")]) .args(["-c:v", "libx264"]) .args(["-preset", "veryfast"]) .args(["-crf", "18"]) .args(["-color_primaries", "bt709"]) .args(["-color_trc", "bt709"]) .args(["-colorspace", "bt709"]) .args(["-pix_fmt", "yuv420p"]) .arg(output) .status() .context("re-encoding with corrected timestamps")?; if status.success() { drop(std::fs::remove_file(input)); } else { tracing::warn!("capture fix: re-encode failed, keeping original"); drop(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; } // A frame count high enough to lose f64 precision would be ~2^53 frames, // which is centuries of capture; f64 handles this ratio exactly enough. #[allow( clippy::cast_precision_loss, reason = "frame counts that could lose f64 precision are unreachable in a recording session" )] let actual_fps = frame_count as f64 / elapsed_secs; Some((actual_fps, f64::from(pipe_fps) / 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); } }