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.
This commit is contained in:
2026-06-18 13:06:00 +03:00
parent c3f132507a
commit d3418c86df
4 changed files with 504 additions and 39 deletions
+347 -37
View File
@@ -5,6 +5,22 @@ 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,
};
@@ -19,6 +35,10 @@ use windows_capture::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;
@@ -52,10 +72,315 @@ pub struct CaptureHandler {
child: Option<Child>,
width: u32,
height: u32,
scratch: Vec<u8>,
/// 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;
@@ -63,20 +388,19 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
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();
let working_width = if let Some(c) = setup.crop {
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 let Some(limit) = setup.encode_width_limit {
if working_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());
@@ -86,17 +410,11 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
}
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{} pipe_fps={}",
setup.width, setup.height, setup.pipe_fps
);
// Declare the detected refresh rate so ffmpeg accepts all frames from the
// pipe. The actual delivery rate varies; fix_intermediate_fps re-encodes
// with the measured rate after capture.
let mut cmd = Command::new(&setup.ffmpeg_path);
cmd.arg("-y")
.arg("-hide_banner")
@@ -132,18 +450,17 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
use std::io::{BufRead, BufReader};
let reader = BufReader::new(serr);
for line in reader.lines().map_while(Result::ok) {
tracing::debug!("ffmpeg: {line}");
tracing::warn!("ffmpeg: {line}");
}
});
}
let pixels = (setup.width as usize) * (setup.height as usize);
Ok(Self {
stdin: Some(stdin),
child: Some(child),
width: setup.width,
height: setup.height,
scratch: Vec::with_capacity(pixels * 4),
pipeline: None,
frame_count: setup.frame_counter.clone(),
})
}
@@ -157,31 +474,24 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
return Ok(());
};
let buf = frame
.buffer()
.map_err(|e| anyhow!("frame buffer: {e:?}"))?;
let expected = (self.width as usize) * (self.height as usize) * 4;
if buf.has_padding() {
// windows-capture copies padded rows into the provided Vec, but only
// grows it when capacity is too small. Keep len valid.
self.scratch.resize(expected, 0);
} else {
self.scratch.clear();
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)?);
}
let bytes = buf.as_nopadding_buffer(&mut self.scratch);
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}")
})?;
// 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());
@@ -318,7 +628,7 @@ pub fn start(
SecondaryWindowSettings::Default,
MinimumUpdateIntervalSettings::Default,
DirtyRegionSettings::Default,
ColorFormat::Bgra8,
ColorFormat::Rgba16F,
setup,
);