lint the test targets, make the fps setting real, and stop tonemapping sdr captures

This commit is contained in:
2026-09-21 06:45:23 +03:00
parent 4b850096a1
commit aef64fa4e3
8 changed files with 221 additions and 40 deletions
+21 -12
View File
@@ -24,32 +24,40 @@ fn compile_shaders() {
let fxc = find_fxc();
for (entry, profile) in &[("fullscreen_vs", "vs_5_0"), ("tonemap_ps", "ps_5_0")] {
// (output name, entry point, profile, defines). The pixel shader is built
// twice: an SDR output skips the HDR curve rather than being darkened by it.
let variants: &[(&str, &str, &str, &[&str])] = &[
("fullscreen_vs", "fullscreen_vs", "vs_5_0", &[]),
("tonemap_ps", "tonemap_ps", "ps_5_0", &["TONEMAP=1"]),
("tonemap_ps_sdr", "tonemap_ps", "ps_5_0", &["TONEMAP=0"]),
];
for (name, entry, profile, defines) in variants {
let src = shader_dir.join("tonemap.hlsl");
let dst = out_dir.join(format!("{entry}.cso"));
let dst = out_dir.join(format!("{name}.cso"));
match &fxc {
Some(fxc) => {
let r = Command::new(fxc)
.arg(format!("/T{profile}"))
let mut cmd = Command::new(fxc);
cmd.arg(format!("/T{profile}"))
.arg(format!("/E{entry}"))
.arg("/O3")
.arg("/Fo")
.arg(&dst)
.arg(&src)
.output();
.arg("/O3");
for define in *defines {
cmd.arg(format!("/D{define}"));
}
let r = cmd.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}: {}",
"cargo:warning=fxc failed for {name}: {}",
String::from_utf8_lossy(&o.stderr)
);
drop(std::fs::write(&dst, []));
}
Err(e) => {
println!("cargo:warning=could not run fxc for {entry}: {e}");
println!("cargo:warning=could not run fxc for {name}: {e}");
drop(std::fs::write(&dst, []));
}
}
@@ -70,7 +78,8 @@ fn compile_shaders() {
}
/// 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).
/// SDK isn't installed, in which case the build still succeeds but capture
/// refuses to start until it is rebuilt with the SDK present.
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 {
+20 -2
View File
@@ -49,14 +49,32 @@ float bt709_oetf(float lin) {
return 1.099 * pow(lin, 0.45) - 0.099;
}
// Compiled twice from this one source: TONEMAP=1 for an HDR output, TONEMAP=0
// for SDR. The capture surface is linear scRGB either way, but only HDR content
// reaches above 1.0 in it, so the same curve cannot be right for both.
#ifndef TONEMAP
#define TONEMAP 1
#endif
float4 tonemap_ps(VsOut i) : SV_TARGET {
// captured.rgb is linear scRGB (1.0 = SDR white; HDR highlights >1.0).
// captured.rgb is linear scRGB, where 1.0 is 80 nits.
float4 c = captured.Sample(point_clamp, i.uv);
#if TONEMAP
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).
// output rather than the raw hable value (which is >1). On an HDR desktop
// SDR white sits near 2.5 in these units (203 nits), so normalizing at 4.0
// is what leaves the highlights somewhere to roll off to.
float3 white = hable(float3(4.0, 4.0, 4.0));
float3 sdr = mapped / white;
#else
// SDR: 1.0 is already display white and there is nothing above it to
// compress. Running this through Hable regardless would map white to about
// 0.65 and darken the whole frame by a third.
float3 sdr = saturate(c.rgb);
#endif
// Apply bt709 OETF so the BGRA8 bytes leave the GPU already gamma-encoded,
// matching the SDR capture pipeline's contract.
float3 gamma = float3(
+1 -1
View File
@@ -407,7 +407,7 @@ fn extract_ffmpeg_from_zip(archive_path: &Path, dest: &Path) -> Result<()> {
mod tests {
use super::*;
/// Stands in for the body of extract_ffmpeg_from_7z: it builds a scratch
/// Stands in for the body of `extract_ffmpeg_from_7z`: it builds a scratch
/// directory, arms the guard, then leaves through the `?` the way a failed
/// extraction does.
fn fails_with_guard_alive(scratch: &Path) -> Result<()> {
+161 -20
View File
@@ -36,8 +36,11 @@ use crate::config::CaptureQuality;
use crate::CaptureRect;
// Precompiled shader bytecode (build.rs invokes fxc). See shaders/tonemap.hlsl.
// The pixel shader is compiled twice: the HDR curve for an HDR output, and a
// straight bt709 encode for SDR.
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"));
const TONEMAP_PS_SDR: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/tonemap_ps_sdr.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.
@@ -74,6 +77,8 @@ pub(crate) struct CaptureSetup {
pub crop: Option<CaptureRect>,
pub pipe_fps: u32,
pub encode_width_limit: u32,
/// Whether the captured output is running HDR, which decides the pixel shader.
pub hdr: bool,
pub frame_counter: Arc<std::sync::atomic::AtomicU64>,
}
@@ -82,6 +87,8 @@ pub(crate) struct CaptureHandler {
child: Option<Child>,
width: u32,
height: u32,
/// Carried through to the pipeline, which is built lazily on the first frame.
hdr: bool,
/// GPU tonemap pipeline, lazily initialized on the first frame (needs the
/// D3D11 device/context from the frame). Recreated on resize.
pipeline: Option<TonemapPipeline>,
@@ -103,6 +110,8 @@ struct TonemapPipeline {
staging: ID3D11Texture2D,
width: u32,
height: u32,
/// Which pixel shader this pipeline was built around.
hdr: bool,
}
// The D3D11 descriptors are pure data - no device, no unsafe - so they live
@@ -247,7 +256,7 @@ fn new_input_elements() -> [D3D11_INPUT_ELEMENT_DESC; 2] {
/// once per pipeline rather than left to fail inside `CreateVertexShader`, which
/// reports it as an opaque HRESULT on the first frame of every recording.
fn ensure_shaders_compiled() -> Result<()> {
if FULLSCREEN_VS.is_empty() || TONEMAP_PS.is_empty() {
if FULLSCREEN_VS.is_empty() || TONEMAP_PS.is_empty() || TONEMAP_PS_SDR.is_empty() {
bail!(
"shader bytecode is empty - rebuild with the Windows SDK installed so build.rs can run fxc"
);
@@ -256,7 +265,7 @@ fn ensure_shaders_compiled() -> Result<()> {
}
impl TonemapPipeline {
fn new(device: &ID3D11Device, width: u32, height: u32) -> Result<Self> {
fn new(device: &ID3D11Device, width: u32, height: u32, hdr: bool) -> Result<Self> {
ensure_shaders_compiled()?;
// Vertex shader: fullscreen-triangle pass-through (no vertex buffer).
@@ -300,11 +309,12 @@ impl TonemapPipeline {
let vertex_buffer =
vertex_buffer.ok_or_else(|| anyhow!("CreateBuffer vb returned null"))?;
// Pixel shader: Hable tonemap + bt709 OETF.
// Pixel shader: HDR tonemap, or a straight bt709 encode for SDR.
let ps_bytecode = if hdr { TONEMAP_PS } else { TONEMAP_PS_SDR };
let mut ps = None;
unsafe {
// SAFETY: live device, build-time-embedded bytecode, local out-param.
device.CreatePixelShader(TONEMAP_PS, None, Some(&raw mut ps))?;
device.CreatePixelShader(ps_bytecode, None, Some(&raw mut ps))?;
}
let ps = ps.ok_or_else(|| anyhow!("CreatePixelShader returned null"))?;
@@ -371,6 +381,7 @@ impl TonemapPipeline {
staging,
width,
height,
hdr,
})
}
@@ -403,7 +414,7 @@ impl TonemapPipeline {
desc.Width,
desc.Height
);
*self = Self::new(device, desc.Width, desc.Height)?;
*self = Self::new(device, desc.Width, desc.Height, self.hdr)?;
}
// SRV onto the captured HDR texture.
@@ -627,6 +638,7 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
child: Some(child),
width: setup.width,
height: setup.height,
hdr: setup.hdr,
pipeline: None,
frame_count: setup.frame_counter.clone(),
})
@@ -647,7 +659,12 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
// 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)?);
self.pipeline = Some(TonemapPipeline::new(
device,
self.width,
self.height,
self.hdr,
)?);
}
// process() takes the pipeline by mut ref; inline the Option dance.
let pipeline = self
@@ -711,12 +728,84 @@ fn monitor_refresh_rate(monitor: Monitor) -> u32 {
}
}
/// 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)
/// Whether the named output is running HDR, which is what decides the pixel
/// shader.
///
/// WGC hands back linear scRGB either way, but only HDR content goes above 1.0
/// in it, so one curve cannot serve both: the Hable pipeline rolls HDR
/// highlights off, and on an SDR output it maps white to about 0.65 and darkens
/// the whole frame. DXGI's per-output colour space is the flag Windows itself
/// flips when HDR is switched on, and `device_name` is the same GDI string
/// DXGI reports as `DeviceName`.
///
/// Returns None when the output cannot be found or queried.
fn is_hdr_output(device_name: &str) -> Option<bool> {
use windows::core::Interface;
use windows::Win32::Graphics::Dxgi::Common::{
DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020, DXGI_COLOR_SPACE_RGB_STUDIO_G2084_NONE_P2020,
};
use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory1, IDXGIFactory1, IDXGIOutput6};
if device_name.is_empty() {
return None;
}
// SAFETY: no arguments; the factory is a live COM object borrowed for the
// length of this call.
let factory: IDXGIFactory1 = unsafe { CreateDXGIFactory1() }.ok()?;
// Both loops end on DXGI_ERROR_NOT_FOUND, which is how these enumerators
// report "no more entries".
let mut adapter_index = 0;
loop {
// SAFETY: the factory is live for this scope, and an out-of-range index
// is reported as an error rather than anything unsound.
let Ok(adapter) = (unsafe { factory.EnumAdapters1(adapter_index) }) else {
break;
};
let mut output_index = 0;
loop {
// SAFETY: `adapter` is live, and an out-of-range index is an error.
let Ok(output) = (unsafe { adapter.EnumOutputs(output_index) }) else {
break;
};
if let Ok(output6) = output.cast::<IDXGIOutput6>() {
// SAFETY: `output6` was queried from a live adapter; the
// descriptor is returned by value and owns no pointers.
if let Ok(desc) = unsafe { output6.GetDesc1() } {
// DeviceName is a NUL-terminated fixed array.
let name = desc
.DeviceName
.split(|&c| c == 0)
.next()
.unwrap_or_default();
if String::from_utf16_lossy(name).eq_ignore_ascii_case(device_name) {
return Some(
desc.ColorSpace == DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020
|| desc.ColorSpace == DXGI_COLOR_SPACE_RGB_STUDIO_G2084_NONE_P2020,
);
}
}
}
output_index += 1;
}
adapter_index += 1;
}
None
}
/// Pick the pipe framerate ffmpeg should declare for raw input, and the rate the
/// capture API is throttled to.
///
/// WGC hands over every frame the panel produces, so the user's setting is the
/// only thing that can make this differ from the refresh rate - and a setting
/// that changes nothing is worse than no setting. Asking for more than the panel
/// can deliver is pointless, so the request is capped at the refresh rate. The
/// declared rate has to match the throttled one: get that wrong and
/// `fix_intermediate_fps` rescales every timestamp by the difference, which
/// changes the clip's speed rather than its smoothness.
fn pipe_framerate(requested: u32, refresh_hz: u32) -> u32 {
requested.clamp(1, refresh_hz.max(1))
}
/// Find the monitor containing the given screen point, falling back to the
@@ -747,9 +836,8 @@ pub(crate) fn start(
output_path: PathBuf,
ffmpeg_path: PathBuf,
capture_cursor: bool,
_audio: bool,
crop: Option<CaptureRect>,
_fps: u32,
fps: u32,
quality: CaptureQuality,
) -> Result<CaptureSession> {
// Use the center of the capture region to determine which monitor to capture.
@@ -779,7 +867,24 @@ pub(crate) fn start(
let frame_counter = Arc::new(std::sync::atomic::AtomicU64::new(0));
let pipe_fps = detect_pipe_framerate(monitor);
let refresh_hz = monitor_refresh_rate(monitor);
let pipe_fps = pipe_framerate(fps, refresh_hz);
let update_interval = if pipe_fps < refresh_hz {
MinimumUpdateIntervalSettings::Custom(std::time::Duration::from_secs_f64(
1.0 / f64::from(pipe_fps),
))
} else {
MinimumUpdateIntervalSettings::Default
};
// A monitor showing HDR needs the tone curve; an SDR one must not go through
// it, or white comes out at 0.65. Unknown falls back to the HDR path so a
// failed query cannot change how an existing HDR setup looks.
let device_name = monitor.device_name().unwrap_or_default();
let hdr = is_hdr_output(&device_name).unwrap_or(true);
tracing::info!(
"capture: output {device_name} hdr={hdr} pipe_fps={pipe_fps} (refresh {refresh_hz})"
);
let setup = CaptureSetup {
output_path: output_path.clone(),
@@ -789,6 +894,7 @@ pub(crate) fn start(
crop,
pipe_fps,
encode_width_limit: limit,
hdr,
frame_counter: frame_counter.clone(),
};
@@ -803,7 +909,7 @@ pub(crate) fn start(
cursor_setting,
DrawBorderSettings::Default,
SecondaryWindowSettings::Default,
MinimumUpdateIntervalSettings::Default,
update_interval,
DirtyRegionSettings::Default,
ColorFormat::Rgba16F,
setup,
@@ -996,20 +1102,55 @@ fn capture_timing(frame_count: u64, elapsed_secs: f64, pipe_fps: u32) -> Option<
#[cfg(test)]
mod tests {
// A failing test reports by panicking; that is the harness contract, and the
// asserts below do the same. unwrap and expect are denied to keep panics out
// of the shipping paths, which this is not.
#![allow(clippy::unwrap_used, reason = "a failing test is meant to panic")]
use super::*;
/// The maths under test is a ratio, so a tolerance says what the test means;
/// a strict float compare would be asserting the division is bit-perfect.
fn assert_close(got: f64, want: f64) {
assert!((got - want).abs() < 1e-9, "expected {want}, got {got}");
}
#[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);
assert_close(actual_fps, 60.0);
assert_close(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);
assert_close(actual_fps, 60.0);
assert_close(pts_scale, 2.0);
}
/// The setting has to reach the pipe, or the recording ignores what the user
/// picked and runs at whatever the panel does.
#[test]
fn pipe_rate_follows_the_setting_below_the_refresh_rate() {
assert_eq!(pipe_framerate(30, 60), 30);
assert_eq!(pipe_framerate(15, 60), 15);
assert_eq!(pipe_framerate(60, 60), 60);
}
/// Asking for more frames than the panel produces cannot produce more.
#[test]
fn pipe_rate_never_exceeds_the_panel() {
assert_eq!(pipe_framerate(120, 60), 60);
assert_eq!(pipe_framerate(240, 144), 144);
}
/// A panel that reports 0 Hz would otherwise clamp to a max below the min and
/// panic; the declared rate must stay positive either way.
#[test]
fn pipe_rate_stays_positive_without_a_refresh_rate() {
assert_eq!(pipe_framerate(30, 0), 1);
assert_eq!(pipe_framerate(0, 60), 1);
}
}
+4
View File
@@ -258,6 +258,10 @@ fn sweep_stale_backups(config_path: &Path) {
#[cfg(test)]
mod tests {
// Tests fail by panicking, which is the harness contract; unwrap and expect
// are denied to keep panics out of the shipping paths.
#![allow(clippy::unwrap_used, reason = "a failing test is meant to panic")]
use super::*;
#[test]
+4
View File
@@ -1473,6 +1473,10 @@ fn parse_progress_kv(line: &str) -> Option<(&str, f64)> {
#[cfg(test)]
mod tests {
// Tests fail by panicking, which is the harness contract; unwrap and expect
// are denied to keep panics out of the shipping paths.
#![allow(clippy::unwrap_used, reason = "a failing test is meant to panic")]
use super::*;
fn dummy_request() -> TranscodeRequest {
+6 -3
View File
@@ -586,7 +586,6 @@ fn start_capture(
output,
ffmpeg,
cfg.capture.capture_cursor,
cfg.capture.capture_audio,
crop,
fps,
cfg.capture.capture_quality,
@@ -700,7 +699,7 @@ fn resume_capture(app: AppHandle, state: State<'_, AppState>) -> Result<(), Stri
if !ffmpeg.is_file() {
return Err("ffmpeg.exe not found".to_string());
}
let session = capture::start(output, ffmpeg, capture_cursor, audio, crop, fps, quality)
let session = capture::start(output, ffmpeg, capture_cursor, crop, fps, quality)
.map_err(|e| format!("{e:#}"))?;
let audio_path = audio_segment_path(&state.app_dir, next_idx);
@@ -1118,6 +1117,10 @@ fn estimate_gif_params_table(request: GifTableRequest) -> GifEstimateTable {
#[cfg(test)]
mod tests {
// Tests fail by panicking, which is the harness contract; unwrap and expect
// are denied to keep panics out of the shipping paths.
#![allow(clippy::unwrap_used, reason = "a failing test is meant to panic")]
use super::*;
fn make_request(target_bytes: u64, fps: u32, mode: GifBudgetMode) -> PreviewRequest {
@@ -1136,7 +1139,7 @@ mod tests {
/// Windows keeps whatever case a name was created with, so the temp sweep
/// matches extensions case-insensitively. It used to compare with
/// ends_with(".mp4"), which silently missed an upper-case recording.
/// `ends_with(".mp4")`, which silently missed an upper-case recording.
#[test]
fn extension_match_ignores_case() {
assert!(has_ext("segment-001.mp4", "mp4"));