nv12: convert with the source colorspace matrix (not hardcoded BT.709)

The NV12→RGB pass hardcoded BT.709, so SD (BT.601) clips had slightly wrong hues.
Read each frame's AVColorSpace in the importer and derive the Y'CbCr→R'G'B'
matrix (BT.709/601/240M/2020; Unspecified guessed by height like swscale/players),
carry the four coefficients on GpuVideoFrame, and apply them in the shader.

- core: GpuVideoFrame.coeffs + ycbcr_coeffs(kr, kb) helper.
- hw_video.rs: map AVColorSpace → (kr, kb) → coeffs.
- nv12_blit{.rs,.wgsl}: uniform grows to 80 bytes (adds a coeffs vec4); the matrix
  multiply uses params.coeffs instead of literals.

BT.2020's transfer is still approximated as sRGB. The DRM-modifier-without-SAMPLED case stays a graceful software fallback.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Skyler Lehmkuhl
2026-06-26 02:32:57 -04:00
co-authored by Claude Opus 4.8
parent 1c537d99da
commit 6348e57de0
5 changed files with 57 additions and 10 deletions
@@ -14,8 +14,10 @@ struct Nv12Params {
col0: vec4<f32>,
col1: vec4<f32>,
col2: vec4<f32>,
// .x = full_range flag; .yzw padding. A vec4 keeps the struct 64 bytes (matching the Rust
// `u32 + [u32; 3]`); a bare u32 + vec3 would round up to 80 and mismatch the bound buffer.
// Y'CbCr→R'G'B' matrix from the source colorspace: [Cr→R, Cb→G, Cr→G, Cb→B].
coeffs: vec4<f32>,
// .x = full_range flag; .yzw padding. A vec4 keeps each block 16-aligned and the struct size
// matching the Rust `[f32;4] + u32 + [u32;3]` (80 bytes).
flags: vec4<u32>,
}
@@ -73,10 +75,10 @@ fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
Cr = (cbcr.g * 255.0 - 128.0) / 224.0;
}
// BT.709 Y'CbCr → gamma-encoded R'G'B'.
let r = Y + 1.5748 * Cr;
let g = Y - 0.1873 * Cb - 0.4681 * Cr;
let b = Y + 1.8556 * Cb;
// Y'CbCr → gamma-encoded R'G'B' using the source colorspace's matrix.
let r = Y + params.coeffs.x * Cr;
let g = Y + params.coeffs.y * Cb + params.coeffs.z * Cr;
let b = Y + params.coeffs.w * Cb;
let rgb_gamma = clamp(vec3<f32>(r, g, b), vec3<f32>(0.0), vec3<f32>(1.0));
// R'G'B' is gamma-encoded; the HDR target is linear → undo the transfer.
@@ -1703,7 +1703,7 @@ impl egui_wgpu::CallbackTrait for VelloCallback {
let y_view = gpu.y.create_view(&Default::default());
let uv_view = gpu.uv.create_view(&Default::default());
shared.nv12_blit.blit(
device, queue, &y_view, &uv_view, hdr_layer_view, &bt, gpu.full_range,
device, queue, &y_view, &uv_view, hdr_layer_view, &bt, gpu.full_range, gpu.coeffs,
);
} else {
// Reuse the GPU texture for this frame if it's unchanged (a