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:
@@ -18,7 +18,7 @@ tauri = { version = "2.11", features = ["protocol-asset"] }
|
|||||||
tauri-plugin-dialog = "2"
|
tauri-plugin-dialog = "2"
|
||||||
tauri-plugin-global-shortcut = "2"
|
tauri-plugin-global-shortcut = "2"
|
||||||
windows-capture = "2.0"
|
windows-capture = "2.0"
|
||||||
windows = { version = "0.62", features = ["Win32_UI_WindowsAndMessaging", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Shell", "Win32_UI_HiDpi", "Win32_Foundation", "Win32_Graphics_Dwm", "Win32_Graphics_Gdi", "Win32_System_SystemInformation", "Win32_Media_Audio", "Win32_Media_Multimedia", "Win32_System_Com", "Win32_System_Com_StructuredStorage", "Win32_System_Threading", "Win32_System_Variant"] }
|
windows = { version = "0.62", features = ["Win32_UI_WindowsAndMessaging", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Shell", "Win32_UI_HiDpi", "Win32_Foundation", "Win32_Graphics_Dwm", "Win32_Graphics_Gdi", "Win32_Graphics_Direct3D", "Win32_Graphics_Direct3D11", "Win32_Graphics_Dxgi", "Win32_Graphics_Dxgi_Common", "Win32_System_SystemInformation", "Win32_Media_Audio", "Win32_Media_Multimedia", "Win32_System_Com", "Win32_System_Com_StructuredStorage", "Win32_System_Threading", "Win32_System_Variant"] }
|
||||||
tokio = { version = "1.47", features = ["rt-multi-thread", "macros"] }
|
tokio = { version = "1.47", features = ["rt-multi-thread", "macros"] }
|
||||||
serde = { version = "1.0", features = ["derive"] }
|
serde = { version = "1.0", features = ["derive"] }
|
||||||
serde_json = "1.0"
|
serde_json = "1.0"
|
||||||
|
|||||||
+88
-1
@@ -1,3 +1,90 @@
|
|||||||
|
use std::path::PathBuf;
|
||||||
|
use std::process::Command;
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
tauri_build::build()
|
tauri_build::build();
|
||||||
|
compile_shaders();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Compile the HDR tonemap HLSL to bytecode at build time so we can embed it
|
||||||
|
/// via include_bytes! and avoid a runtime dependency on d3dcompiler_47.dll.
|
||||||
|
/// Looks for fxc.exe in the installed Windows SDK. If fxc is unavailable the
|
||||||
|
/// .cso files are emitted empty and capture.rs falls back to runtime
|
||||||
|
/// D3DCompile (so a clean checkout without the SDK still builds).
|
||||||
|
fn compile_shaders() {
|
||||||
|
let out_dir = PathBuf::from(std::env::var("OUT_DIR").expect("OUT_DIR"));
|
||||||
|
let shader_dir = PathBuf::from("shaders");
|
||||||
|
|
||||||
|
let fxc = find_fxc();
|
||||||
|
|
||||||
|
for (entry, profile) in &[("fullscreen_vs", "vs_5_0"), ("tonemap_ps", "ps_5_0")] {
|
||||||
|
let src = shader_dir.join("tonemap.hlsl");
|
||||||
|
let dst = out_dir.join(format!("{entry}.cso"));
|
||||||
|
match &fxc {
|
||||||
|
Some(fxc) => {
|
||||||
|
let r = Command::new(fxc)
|
||||||
|
.arg(format!("/T{profile}"))
|
||||||
|
.arg(format!("/E{entry}"))
|
||||||
|
.arg("/O3")
|
||||||
|
.arg("/Fo")
|
||||||
|
.arg(&dst)
|
||||||
|
.arg(&src)
|
||||||
|
.output();
|
||||||
|
match r {
|
||||||
|
Ok(o) if o.status.success() => {
|
||||||
|
println!("cargo:rerun-if-changed={}", src.display());
|
||||||
|
}
|
||||||
|
Ok(o) => {
|
||||||
|
println!(
|
||||||
|
"cargo:warning=fxc failed for {entry}: {}",
|
||||||
|
String::from_utf8_lossy(&o.stderr)
|
||||||
|
);
|
||||||
|
let _ = std::fs::write(&dst, []);
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
println!("cargo:warning=could not run fxc for {entry}: {e}");
|
||||||
|
let _ = std::fs::write(&dst, []);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
// No SDK on the build machine - emit an empty .cso; capture.rs
|
||||||
|
// detects the zero size and compiles the HLSL at runtime.
|
||||||
|
let _ = std::fs::write(&dst, []);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if fxc.is_none() {
|
||||||
|
println!("cargo:warning=fxc.exe not found - shaders will be compiled at runtime");
|
||||||
|
}
|
||||||
|
println!("cargo:rerun-if-changed=shaders/tonemap.hlsl");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Locate the newest fxc.exe under the Windows Kits SDK. Returns None if the
|
||||||
|
/// SDK isn't installed (build still succeeds via the runtime-compile fallback).
|
||||||
|
fn find_fxc() -> Option<PathBuf> {
|
||||||
|
let root = PathBuf::from(r"C:\Program Files (x86)\Windows Kits\10\bin");
|
||||||
|
let Ok(entries) = std::fs::read_dir(&root) else {
|
||||||
|
return None;
|
||||||
|
};
|
||||||
|
// Pick the highest-versioned SDK with an x64 fxc.exe.
|
||||||
|
let mut best: Option<(String, PathBuf)> = None;
|
||||||
|
for entry in entries.flatten() {
|
||||||
|
let name = match entry.file_name().into_string() {
|
||||||
|
Ok(s) => s,
|
||||||
|
Err(_) => continue,
|
||||||
|
};
|
||||||
|
// Skip non-version dirs (arm64, x64, x86 at the root level).
|
||||||
|
if !name.starts_with("10.") {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let fxc = entry.path().join("x64").join("fxc.exe");
|
||||||
|
if fxc.is_file() {
|
||||||
|
if best.as_ref().map_or(true, |(b, _)| name.as_str() > b.as_str()) {
|
||||||
|
best = Some((name, fxc));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
best.map(|(_, p)| p)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,68 @@
|
|||||||
|
// HDR -> SDR tonemap for ByteSize screen capture. Hable filmic curve.
|
||||||
|
//
|
||||||
|
// Input: R16G16B16A16_FLOAT texture from Windows Graphics Capture, holding
|
||||||
|
// linear scRGB values (1.0 = SDR white ~80 nits, >1.0 = HDR highlights).
|
||||||
|
// Output: R8G8B8A8_UNORM render target, bt709-gamma-encoded SDR ready for the
|
||||||
|
// ffmpeg bgra pipe (matches what downstream encode.rs filters assume:
|
||||||
|
// in_transfer=bt709, tv range).
|
||||||
|
|
||||||
|
struct VsIn {
|
||||||
|
float2 pos : POSITION;
|
||||||
|
float2 uv : TEXCOORD0;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct VsOut {
|
||||||
|
float4 pos : SV_POSITION;
|
||||||
|
float2 uv : TEXCOORD0;
|
||||||
|
};
|
||||||
|
|
||||||
|
VsOut fullscreen_vs(VsIn i) {
|
||||||
|
VsOut o;
|
||||||
|
o.pos = float4(i.pos, 0.0, 1.0);
|
||||||
|
o.uv = i.uv;
|
||||||
|
return o;
|
||||||
|
}
|
||||||
|
|
||||||
|
Texture2D<float4> captured : register(t0);
|
||||||
|
SamplerState point_clamp : register(s0);
|
||||||
|
|
||||||
|
// Hable filmic tonemap (Uncharted 2). Better midtone contrast than ACES for
|
||||||
|
// modest HDR ranges (our source peaks around 3x SDR white), so highlights
|
||||||
|
// roll off gradually instead of clamping flat near 1.0.
|
||||||
|
float3 hable(float3 x) {
|
||||||
|
const float A = 0.15; // shoulder strength
|
||||||
|
const float B = 0.50; // linear strength
|
||||||
|
const float C = 0.10; // linear angle
|
||||||
|
const float D = 0.20; // toe strength
|
||||||
|
const float E = 0.02; // toe numerator
|
||||||
|
const float F = 0.30; // toe denominator
|
||||||
|
return ((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F;
|
||||||
|
}
|
||||||
|
|
||||||
|
// bt709 OETF: linear light -> gamma-encoded signal. This is the exact ITU-R
|
||||||
|
// bt709 transfer, not the 1/2.2 approximation, so the output matches what
|
||||||
|
// ffmpeg's out_transfer=bt709 would produce.
|
||||||
|
float bt709_oetf(float lin) {
|
||||||
|
if (lin <= 0.018) {
|
||||||
|
return 4.5 * lin;
|
||||||
|
}
|
||||||
|
return 1.099 * pow(lin, 0.45) - 0.099;
|
||||||
|
}
|
||||||
|
|
||||||
|
float4 tonemap_ps(VsOut i) : SV_TARGET {
|
||||||
|
// captured.rgb is linear scRGB (1.0 = SDR white; HDR highlights >1.0).
|
||||||
|
float4 c = captured.Sample(point_clamp, i.uv);
|
||||||
|
float3 mapped = hable(c.rgb);
|
||||||
|
// Normalize by hable at the white point so 1.0 SDR white maps to ~1.0
|
||||||
|
// output rather than the raw hable value (which is >1).
|
||||||
|
float3 white = hable(float3(4.0, 4.0, 4.0));
|
||||||
|
float3 sdr = mapped / white;
|
||||||
|
// Apply bt709 OETF so the BGRA8 bytes leave the GPU already gamma-encoded,
|
||||||
|
// matching the SDR capture pipeline's contract.
|
||||||
|
float3 gamma = float3(
|
||||||
|
bt709_oetf(sdr.r),
|
||||||
|
bt709_oetf(sdr.g),
|
||||||
|
bt709_oetf(sdr.b)
|
||||||
|
);
|
||||||
|
return float4(gamma, 1.0);
|
||||||
|
}
|
||||||
+347
-37
@@ -5,6 +5,22 @@ use std::sync::Arc;
|
|||||||
use std::time::Instant;
|
use std::time::Instant;
|
||||||
|
|
||||||
use anyhow::{anyhow, bail, Context, Result};
|
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::{
|
use windows_capture::capture::{
|
||||||
CaptureControl, Context as CaptureContext, GraphicsCaptureApiHandler,
|
CaptureControl, Context as CaptureContext, GraphicsCaptureApiHandler,
|
||||||
};
|
};
|
||||||
@@ -19,6 +35,10 @@ use windows_capture::settings::{
|
|||||||
use crate::config::CaptureQuality;
|
use crate::config::CaptureQuality;
|
||||||
use crate::CaptureRect;
|
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
|
/// 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.
|
/// 8K on exotic hardware. Auto mode caps at AUTO_ENCODE_WIDTH instead.
|
||||||
const MAX_ENCODE_WIDTH: u32 = 3840;
|
const MAX_ENCODE_WIDTH: u32 = 3840;
|
||||||
@@ -52,10 +72,315 @@ pub struct CaptureHandler {
|
|||||||
child: Option<Child>,
|
child: Option<Child>,
|
||||||
width: u32,
|
width: u32,
|
||||||
height: 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>,
|
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 {
|
impl GraphicsCaptureApiHandler for CaptureHandler {
|
||||||
type Flags = CaptureSetup;
|
type Flags = CaptureSetup;
|
||||||
type Error = anyhow::Error;
|
type Error = anyhow::Error;
|
||||||
@@ -63,20 +388,19 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
|
|||||||
fn new(ctx: CaptureContext<Self::Flags>) -> Result<Self, Self::Error> {
|
fn new(ctx: CaptureContext<Self::Flags>) -> Result<Self, Self::Error> {
|
||||||
let setup = ctx.flags;
|
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 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 x = c.x.max(0);
|
||||||
let y = c.y.max(0);
|
let y = c.y.max(0);
|
||||||
let w = c.width.min(setup.width.saturating_sub(x as u32));
|
let w = c.width.min(setup.width.saturating_sub(x as u32));
|
||||||
let h = c.height.min(setup.height.saturating_sub(y as u32));
|
let h = c.height.min(setup.height.saturating_sub(y as u32));
|
||||||
filter_parts.push(format!("crop={}:{}:{}:{}", w, h, x, y));
|
filter_parts.push(format!("crop={}:{}:{}:{}", w, h, x, y));
|
||||||
w
|
}
|
||||||
} else {
|
|
||||||
setup.width
|
|
||||||
};
|
|
||||||
|
|
||||||
if let Some(limit) = setup.encode_width_limit {
|
if let Some(limit) = setup.encode_width_limit {
|
||||||
if working_width > limit {
|
if setup.width > limit {
|
||||||
filter_parts.push(format!("scale={}:-2", limit));
|
filter_parts.push(format!("scale={}:-2", limit));
|
||||||
} else {
|
} else {
|
||||||
filter_parts.push("scale=trunc(iw/2)*2:trunc(ih/2)*2".to_string());
|
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(",");
|
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!(
|
tracing::info!(
|
||||||
"capture: size={}x{} pipe_fps={}",
|
"capture: size={}x{} pipe_fps={}",
|
||||||
setup.width, setup.height, setup.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);
|
let mut cmd = Command::new(&setup.ffmpeg_path);
|
||||||
cmd.arg("-y")
|
cmd.arg("-y")
|
||||||
.arg("-hide_banner")
|
.arg("-hide_banner")
|
||||||
@@ -132,18 +450,17 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
|
|||||||
use std::io::{BufRead, BufReader};
|
use std::io::{BufRead, BufReader};
|
||||||
let reader = BufReader::new(serr);
|
let reader = BufReader::new(serr);
|
||||||
for line in reader.lines().map_while(Result::ok) {
|
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 {
|
Ok(Self {
|
||||||
stdin: Some(stdin),
|
stdin: Some(stdin),
|
||||||
child: Some(child),
|
child: Some(child),
|
||||||
width: setup.width,
|
width: setup.width,
|
||||||
height: setup.height,
|
height: setup.height,
|
||||||
scratch: Vec::with_capacity(pixels * 4),
|
pipeline: None,
|
||||||
frame_count: setup.frame_counter.clone(),
|
frame_count: setup.frame_counter.clone(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -157,31 +474,24 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
};
|
};
|
||||||
|
|
||||||
let buf = frame
|
let device = frame.device();
|
||||||
.buffer()
|
let context = frame.device_context();
|
||||||
.map_err(|e| anyhow!("frame buffer: {e:?}"))?;
|
let src = frame.as_raw_texture();
|
||||||
let expected = (self.width as usize) * (self.height as usize) * 4;
|
|
||||||
if buf.has_padding() {
|
// Lazily build the GPU pipeline on the first frame (needs the device).
|
||||||
// windows-capture copies padded rows into the provided Vec, but only
|
if self.pipeline.is_none() {
|
||||||
// grows it when capacity is too small. Keep len valid.
|
self.pipeline = Some(TonemapPipeline::new(device, self.width, self.height)?);
|
||||||
self.scratch.resize(expected, 0);
|
|
||||||
} else {
|
|
||||||
self.scratch.clear();
|
|
||||||
}
|
}
|
||||||
let bytes = buf.as_nopadding_buffer(&mut self.scratch);
|
// process() takes the pipeline by mut ref; inline the Option dance.
|
||||||
if bytes.len() < expected {
|
let pipeline = self.pipeline.as_mut().expect("just initialized");
|
||||||
tracing::warn!("frame buffer too small: got {} bytes, expected {}", bytes.len(), expected);
|
pipeline.process(device, context, src, stdin)?;
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
stdin.write_all(&bytes[..expected]).map_err(|e| {
|
|
||||||
tracing::error!("ffmpeg stdin write failed: {e}");
|
|
||||||
anyhow!("ffmpeg encoder stopped unexpectedly: {e}")
|
|
||||||
})?;
|
|
||||||
self.frame_count.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
self.frame_count.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
impl Drop for CaptureHandler {
|
impl Drop for CaptureHandler {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
drop(self.stdin.take());
|
drop(self.stdin.take());
|
||||||
@@ -318,7 +628,7 @@ pub fn start(
|
|||||||
SecondaryWindowSettings::Default,
|
SecondaryWindowSettings::Default,
|
||||||
MinimumUpdateIntervalSettings::Default,
|
MinimumUpdateIntervalSettings::Default,
|
||||||
DirtyRegionSettings::Default,
|
DirtyRegionSettings::Default,
|
||||||
ColorFormat::Bgra8,
|
ColorFormat::Rgba16F,
|
||||||
setup,
|
setup,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user