Files
bytesize/src-tauri/src/capture.rs
T
lashman d3418c86df tonemap hdr captures on the gpu
firefox playing hdr youtube renders the desktop in linear scrgb, and
capturing it as bgra8 clamps the >1.0 highlights to pure white. capture
in r16g16b16a16_float instead and run a hable filmic + bt709 pixel
shader directly on the captured d3d11 texture (which windows-capture
already exposes via frame.as_raw_texture), then read back bgra8 so the
ffmpeg pipe stays unchanged from the sdr path.

the shader is compiled offline with fxc at build time and embedded. the
fullscreen-triangle draw needs an explicit cull-none rasterizer state
since the default back-face cull silently drops it.
2026-06-18 13:06:00 +03:00

821 lines
31 KiB
Rust

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;
/// Returns the cap to apply to the encode width, or None for native res.
/// 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) -> Option<u32> {
match quality {
CaptureQuality::Auto => Some(AUTO_ENCODE_WIDTH),
CaptureQuality::Full => Some(MAX_ENCODE_WIDTH),
}
}
#[derive(Debug, Clone)]
pub struct CaptureSetup {
pub output_path: PathBuf,
pub ffmpeg_path: PathBuf,
pub width: u32,
pub height: u32,
pub crop: Option<CaptureRect>,
pub pipe_fps: u32,
pub encode_width_limit: Option<u32>,
pub frame_counter: Arc<std::sync::atomic::AtomicU64>,
}
pub struct CaptureHandler {
stdin: Option<ChildStdin>,
child: Option<Child>,
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<TonemapPipeline>,
frame_count: Arc<std::sync::atomic::AtomicU64>,
}
/// 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,
}
impl TonemapPipeline {
fn new(device: &ID3D11Device, width: u32, height: u32) -> Result<Self> {
// Vertex shader: fullscreen-triangle pass-through (no vertex buffer).
let mut vs = None;
unsafe {
device.CreateVertexShader(FULLSCREEN_VS, None, Some(&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(b"POSITION\0".as_ptr()),
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(b"TEXCOORD\0".as_ptr()),
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 {
device.CreateInputLayout(
&input_elements,
FULLSCREEN_VS,
Some(&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 {
ByteWidth: std::mem::size_of_val(&verts) as u32,
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() as *const _,
SysMemPitch: 0,
SysMemSlicePitch: 0,
};
let mut vertex_buffer = None;
unsafe {
device.CreateBuffer(&vb_desc as *const _, Some(&vb_init as *const _), Some(&mut vertex_buffer))?;
}
let vertex_buffer = vertex_buffer.ok_or_else(|| anyhow!("CreateBuffer vb returned null"))?;
// Pixel shader: ACES tonemap + bt709 OETF.
let mut ps = None;
unsafe {
device.CreatePixelShader(TONEMAP_PS, None, Some(&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 {
device.CreateSamplerState(&sampler_desc, Some(&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 {
device.CreateRasterizerState(&rasterizer_desc, Some(&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 {
device.CreateTexture2D(&rt_desc, None, Some(&mut render_target))?;
}
let render_target = render_target.ok_or_else(|| anyhow!("CreateTexture2D rt returned null"))?;
let rtv_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 {
device.CreateRenderTargetView(&render_target, Some(&rtv_desc), Some(&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 {
device.CreateTexture2D(&staging_desc, None, Some(&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.
fn process(
&mut self,
device: &ID3D11Device,
context: &ID3D11DeviceContext,
src: &ID3D11Texture2D,
out: &mut dyn Write,
) -> Result<()> {
let mut desc = D3D11_TEXTURE2D_DESC::default();
unsafe { src.GetDesc(&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)?;
}
unsafe {
// 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<ID3D11ShaderResourceView> = None;
device.CreateShaderResourceView(src, Some(&srv_desc), Some(&mut srv))?;
let srv = srv.ok_or_else(|| anyhow!("CreateShaderResourceView returned null"))?;
// Canonical bind sequence: IA -> shaders -> resources -> output
// merger -> viewport+scissor -> draw. Every stage explicit because
// the frame's device/context carries state from prior frames.
context.IASetInputLayout(&self.input_layout);
context.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
let vb = [Some(self.vertex_buffer.clone())];
let strides = [16u32];
let offsets = [0u32];
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(&[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).
context.RSSetScissorRects(Some(&[windows::Win32::Foundation::RECT {
left: 0,
top: 0,
right: self.width as i32,
bottom: self.height as i32,
}]));
context.Draw(3, 0);
// Copy to staging and read back.
context.CopyResource(&self.staging, &self.render_target);
let mut mapped = D3D11_MAPPED_SUBRESOURCE::default();
context.Map(&self.staging, 0, D3D11_MAP_READ, 0, Some(&mut mapped))?;
let row_bytes = self.width * 4;
let src_slice = std::slice::from_raw_parts(
mapped.pData as *const u8,
(mapped.RowPitch as usize) * (self.height as usize),
);
// RowPitch may exceed width*4 (alignment); copy row by row.
if mapped.RowPitch as u32 == row_bytes {
out.write_all(&src_slice[..(row_bytes as usize) * (self.height as usize)])
.map_err(|e| anyhow!("writing tonemapped frame: {e}"))?;
} else {
let pitch = mapped.RowPitch as usize;
for y in 0..(self.height as usize) {
let row = &src_slice[y * pitch..y * pitch + row_bytes as usize];
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<Self::Flags>) -> Result<Self, Self::Error> {
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<String> = 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 as u32));
let h = c.height.min(setup.height.saturating_sub(y as u32));
filter_parts.push(format!("crop={}:{}:{}:{}", w, h, x, y));
}
if let Some(limit) = setup.encode_width_limit {
if setup.width > limit {
filter_parts.push(format!("scale={}:-2", limit));
} else {
filter_parts.push("scale=trunc(iw/2)*2:trunc(ih/2)*2".to_string());
}
} 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().expect("just initialized");
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() {
let _ = child.wait();
}
}
}
pub struct CaptureSession {
pub output_path: PathBuf,
pub started_at: Instant,
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>,
}
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))
}
/// 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<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.
Ok(Monitor::from_raw_hmonitor(hmonitor.0))
}
pub fn start(
output_path: PathBuf,
ffmpeg_path: PathBuf,
capture_cursor: bool,
_audio: bool,
crop: Option<CaptureRect>,
_fps: u32,
quality: CaptureQuality,
) -> 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 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<CaptureRect>,
width_limit: Option<u32>,
) -> (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),
};
let cap = width_limit.unwrap_or(u32::MAX);
if raw_w > cap {
let scale = cap as f64 / raw_w as f64;
let nh = (raw_h as f64 * scale).round() as u32;
(cap, (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 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.
pub 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!("{:.6}", pts_scale)])
.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");
let _ = std::fs::remove_file(input);
return Ok(());
}
tracing::warn!("capture fix: -itsscale copy failed, falling back to re-encode");
let _ = 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*{:.4}", pts_scale)])
.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() {
let _ = std::fs::remove_file(input);
} else {
tracing::warn!("capture fix: re-encode failed, keeping original");
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);
}
}