Skip to content

Bring PS5 GTA6 to 120FPS with DLSS 5. An advanced Windows video player and capture enhancement tool featuring real-time preview for videos, images, and capture card sources. Combine AI-powered Super Resolution, DLSS5 image enhancement, and Frame Generation to deliver a next-generation visual experience.

C++

feat(color): T2b-b source-side colour stage inside the ingest dispatch (GPU contract verified)

Veyra Goal Agent1d711ea87092
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 3fe519de..ada55676 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -297,6 +297,7 @@ target_link_libraries(veyra_guidance_tests PRIVATE veyra_guidance)
# Grows in R3 as the real GPU graph migrates out of the probes.
add_library(veyra_pipeline STATIC
src/pipeline/ResetCoordinator.cpp
+ src/pipeline/ColorGradeTables.cpp
)
veyra_apply_warnings(veyra_pipeline)
# FFmpeg/NVOF headers are third-party: /WX stays off for this target.
@@ -671,11 +672,20 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
add_executable(veyra_repair_preset_tests tests/unit/RepairPresetTests.cpp src/engine/PresetStore.cpp)
# CPU bake of the colour grade: no GPU, no engine link - the tables the ingest
# shader reads are pure maths and must be verifiable without a device.
- add_executable(veyra_color_grade_tests tests/unit/ColorGradeTableTests.cpp src/pipeline/ColorGradeTables.cpp)
+ add_executable(veyra_color_grade_tests tests/unit/ColorGradeTableTests.cpp)
target_compile_features(veyra_color_grade_tests PRIVATE cxx_std_20)
target_compile_options(veyra_color_grade_tests PRIVATE /utf-8)
target_compile_definitions(veyra_color_grade_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)
target_include_directories(veyra_color_grade_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)
+ target_link_libraries(veyra_color_grade_tests PRIVATE veyra_pipeline)
+ # GPU contract for the v4 colour chain: identity when off/neutral, exposure,
+ # curve, saturation and hue, all through a real graph and its ingest pass.
+ add_executable(veyra_color_grade_gpu_tests tests/integration/ColorGradeGpuTests.cpp)
+ target_compile_features(veyra_color_grade_gpu_tests PRIVATE cxx_std_20)
+ target_compile_options(veyra_color_grade_gpu_tests PRIVATE /utf-8 /WX-)
+ target_compile_definitions(veyra_color_grade_gpu_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)
+ target_include_directories(veyra_color_grade_gpu_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${FFMPEG_INCLUDE_DIRS})
+ target_link_libraries(veyra_color_grade_gpu_tests PRIVATE veyra_pipeline veyra_sinks)
target_compile_features(veyra_repair_preset_tests PRIVATE cxx_std_20)
target_compile_options(veyra_repair_preset_tests PRIVATE /utf-8)
target_compile_definitions(veyra_repair_preset_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index b7ae221e..71c19b47 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -1,5 +1,44 @@
# 2026-09-11 继续修复目标模式执行中
+## 2026-09-17 色彩页 P1:T2b-b 源头侧调色链接入 ingest(GPU 验收通过)
+
+按 v4 计划完成 GPU 接线:调色**不新增 pass**,而是接进现有的 ingest 派发(YUV→线性、
+RGB/打包/YUY2→线性),作用在**所有效果器之前**。
+
+- `shaders/ColorGrade.hlsli`:单一入口 `ColorGradeApply(lin, params)` —— 线性 3×3(白平衡+校准)、
+ 曝光、对数域逐通道曲线表、色相表混色器、亮度表分级/阴影色调、饱和度/自然饱和度;
+ 10 档对数据窗口之外的值直接放行,HDR 高光不被色调表截断;另含 6 例四面体 LUT 采样
+ (`base` 已钳制,避免 coord==dims-1 时越界读);
+- 表数据:CPU 端 `ColorGradeTables::bake()` 烘焙成 3 张 FP32 表(1024/256/256),
+ 经常驻映射的上传缓冲一次拷进纹理;`GpuPassUtils` 为 ingest pass 增加**第二个 SRV 表**
+ (固定寄存器基址 8,t8..t11),不影响其他 pass 的三参数根签名;
+- 总开关:`desc.color.enabled` 决定是否创建表资源;关闭时 ingest shader 直接返回线性值
+ (`flags.x==0`),不采样任何表、不额外派发;开关切换走重建(与 NR/超分同级),
+ 改色彩参数只更新 uniform/表(`applySettings` 接受、不重建);
+- 引擎:`EngineController` 把 `settings.color` 传进图描述与 nextDesc,重建条件加入
+ `color.enabled`;`EnhanceGraphDesc::color` 为唯一数据入口。
+
+**GPU 验收(新目标 `veyra_color_grade_gpu_tests`,RTX 5070,`gd.rgbInput` 路径)**
+
+```
+PASS colour graphs initialise and render
+PASS master off and enabled-neutral are byte-identical to the ungraded path
+PASS a green input stays green through the neutral grade
+PASS +1 EV brightens mid grey by a visible step
+PASS point curve at 0.5 raises the coded value
+PASS saturation -100 collapses the frame to grey
+PASS: colour grade GPU contract (off/neutral identity, exposure, curve, saturation, hue) exit=0
+```
+
+**回归**:`veyra_color_grade_tests` 23/23 PASS;`veyra_repair_preset_tests` exit 0;
+`veyra_ui_contract_tests` exit 0;`veyra_repair_contract_tests` 191/0;
+`veyra_image_dimension_tests`(羽化 2/32/64 + 分块 + 运动序列)exit 0;
+`scripts/gates/delivery.ps1` → `DELIVERY SHORT GATE PASS`
+(`logs/delivery/4d71b79296484248bc370413c09c0ea0/result.json`)。
+
+**未做/待办**:`.cube` 文件导入与 LUT 案例(T5,`setColorLut` 接口已就绪、测试里暂未覆盖);
+色彩页 UI(T3/T4);开调色档位的 GPU 耗时对比(等 UI 能开了在真机量,当前默认关闭=零开销)。
+
## 2026-09-17 色彩页 P1:T2b-a 总开关语义 + CPU 烘焙表(调色前移到源头)
按 v4 计划(调色链**全部前移到所有效果器之前**、单一链路、可完全关闭)落地第一批:
diff --git a/include/veyra/pipeline/ColorGradeTables.h b/include/veyra/pipeline/ColorGradeTables.h
index bdad2ab5..86272695 100644
--- a/include/veyra/pipeline/ColorGradeTables.h
+++ b/include/veyra/pipeline/ColorGradeTables.h
@@ -33,4 +33,17 @@ struct ColorGradeTables {
static float encodeLog(float linear);
static float decodeLog(float encoded);
};
+// Root-constant block consumed by ColorGrade.hlsli: five float4s (rows 0-2,
+// controls, flags). The ingest passes apppend it after their own constants, so
+// nothing existing moves.
+inline constexpr int kColorGradeConstantCount=20;
+inline void packColorGradeConstants(const ColorGradeTables& t,float* out){
+ out[0]=t.matrix[0];out[1]=t.matrix[1];out[2]=t.matrix[2];out[3]=0;
+ out[4]=t.matrix[3];out[5]=t.matrix[4];out[6]=t.matrix[5];out[7]=0;
+ out[8]=t.matrix[6];out[9]=t.matrix[7];out[10]=t.matrix[8];out[11]=0;
+ out[12]=t.exposure;out[13]=t.saturation;out[14]=t.vibrance;out[15]=t.identity?0.0f:t.lutStrength;
+ // "identity" covers both "master switch off" and "every parameter neutral":
+ // in either case the shader must return the input untouched.
+ out[16]=t.identity?0.0f:1.0f;out[17]=float(t.identity?0:t.lutInputSpace);out[18]=0;out[19]=0;
+}
} // namespace veyra::pipeline
diff --git a/include/veyra/pipeline/EnhanceGraph.h b/include/veyra/pipeline/EnhanceGraph.h
index 20277547..cdadf81e 100644
--- a/include/veyra/pipeline/EnhanceGraph.h
+++ b/include/veyra/pipeline/EnhanceGraph.h
@@ -1,5 +1,6 @@
#pragma once
#include "veyra/engine/BackendRecovery.h"
+#include "veyra/pipeline/ColorGradeTables.h"
// EnhanceGraph - the real unified processing graph (Playbook R3.2).
// Chains, per real frame:
@@ -97,6 +98,10 @@ struct EnhanceGraphDesc {
engine::NrSettings model;
engine::ResidualSettings residual;
engine::ProtectionSettings protection;
+ // Colour grade (plan v4). When color.enabled is false the stage does not
+ // exist: no tables are allocated, no constants are packed and the ingest
+ // shaders return their linear RGB untouched.
+ engine::ColorSettings color;
std::wstring runtimeAbsPath; // absolute runtime_local/nvidia path
// Optional stage instrumentation hook (GPU timing experiments).
std::function<void(const char*)> stageMark;
@@ -121,6 +126,9 @@ public:
// created between the two phases - static descriptor views are only
// safe after every allocation in the process has happened.
bool initialize(const EnhanceGraphDesc& desc);
+ // Uploads a .cube payload (size^3 RGB triples, 0..1) into the optional 3D
+ // LUT the ingest shader samples. Without a LUT the strength stays 0.
+ bool setColorLut(const float* rgb,unsigned size);
bool createViews();
struct FrameOutputs {
@@ -323,6 +331,23 @@ private:
float toneMapPeakNits_=0; // latched per graph/source; never varies with frame brightness
ComputePass rgbPass_,hdrVideoSrPass_;
ComputePass downsamplePass_,residualPass_,flowAdaptPass_;
+ // --- colour grade (v4): CPU-baked tables read by the ingest shaders -----
+ bool colorActive_=false;
+ bool colorDirty_=true;
+ ColorGradeTables colorTables_;
+ ComPtr<ID3D12Resource> colorCurveTex_,colorHueTex_,colorLumTex_,colorLutTex_;
+ ComPtr<ID3D12Resource> upColorCurve_,upColorHue_,upColorLum_;
+ float* mappedColorCurve_=nullptr;
+ float* mappedColorHue_=nullptr;
+ float* mappedColorLum_=nullptr;
+ unsigned colorLutSize_=0;
+ std::vector<float> colorLutUpload_;
+ unsigned colorLutPending_=0;
+ std::array<ComPtr<ID3D12Resource>,2> colorLutStaging_{};
+ unsigned colorLutStagingSlot_=0;
+ bool createColorResources();
+ void refreshColorTables();
+ void uploadColorTables(ID3D12GraphicsCommandList* list);
DescriptorStager stager_;
Microsoft::WRL::ComPtr<ID3D12Resource> sourceReferences_[2],baseReferences_[2];
StateTracker tracker_;
diff --git a/include/veyra/pipeline/GpuPassUtils.h b/include/veyra/pipeline/GpuPassUtils.h
index 3bed5509..d0946984 100644
--- a/include/veyra/pipeline/GpuPassUtils.h
+++ b/include/veyra/pipeline/GpuPassUtils.h
@@ -104,6 +104,7 @@ struct ComputePass {
ComPtr<ID3D12PipelineState> pso;
ComPtr<ID3D12DescriptorHeap> heap;
UINT increment = 0, constantCount = 8;
+ bool hasExtraSrv = false;
bool loadShader(const char* name, std::vector<uint8_t>& bytes) const
{
@@ -123,11 +124,15 @@ struct ComputePass {
return !bytes.empty();
}
+ // extraSrvCount adds a second SRV table at a fixed register base (8): the
+ // colour-grade tables. Passes that do not use it keep the original
+ // three-parameter root signature.
bool create(ID3D12Device* device, const std::vector<uint8_t>& cs, UINT heapSlots,
- UINT srvCount = 3, UINT uavCount = 1, UINT constants = 8)
+ UINT srvCount = 3, UINT uavCount = 1, UINT constants = 8, UINT extraSrvCount = 0)
{
if(constants==0||constants>60)return false;
constantCount=constants;
+ hasExtraSrv=extraSrvCount>0;
D3D12_DESCRIPTOR_RANGE1 srvRange{};
srvRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
srvRange.NumDescriptors = srvCount;
@@ -136,7 +141,7 @@ struct ComputePass {
uavRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_UAV;
uavRange.NumDescriptors = uavCount;
uavRange.Flags = D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE;
- D3D12_ROOT_PARAMETER1 rp[3]{};
+ D3D12_ROOT_PARAMETER1 rp[4]{}; // 4th slot is the optional extra SRV table
rp[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
rp[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
rp[0].Constants.ShaderRegister = 0;
@@ -149,19 +154,35 @@ struct ComputePass {
rp[2].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
rp[2].DescriptorTable.NumDescriptorRanges = 1;
rp[2].DescriptorTable.pDescriptorRanges = &uavRange;
+ D3D12_DESCRIPTOR_RANGE1 extraRange{};
+ if(hasExtraSrv){
+ extraRange.RangeType=D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
+ extraRange.NumDescriptors=extraSrvCount;
+ extraRange.BaseShaderRegister=8;
+ extraRange.Flags=D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE;
+ rp[3].ParameterType=D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
+ rp[3].ShaderVisibility=D3D12_SHADER_VISIBILITY_ALL;
+ rp[3].DescriptorTable.NumDescriptorRanges=1;
+ rp[3].DescriptorTable.pDescriptorRanges=&extraRange;
+ }
D3D12_VERSIONED_ROOT_SIGNATURE_DESC rd{};
rd.Version = D3D_ROOT_SIGNATURE_VERSION_1_1;
- rd.Desc_1_1.NumParameters = 3;
+ rd.Desc_1_1.NumParameters = hasExtraSrv?4:3;
rd.Desc_1_1.pParameters = rp;
ComPtr<ID3DBlob> sig, err;
- if (FAILED(D3D12SerializeVersionedRootSignature(&rd, &sig, &err))) return false;
+ const HRESULT serializeHr=D3D12SerializeVersionedRootSignature(&rd, &sig, &err);
+ if (FAILED(serializeHr)) {
+ veyra::log::error("gfx-util",std::format("root signature serialize failed hr=0x{:08X} msg={}",unsigned(serializeHr),
+ err?std::string(static_cast<const char*>(err->GetBufferPointer()),err->GetBufferSize()):std::string()));
+ return false;
+ }
if (FAILED(device->CreateRootSignature(0, sig->GetBufferPointer(),
- sig->GetBufferSize(), IID_PPV_ARGS(&rootSig)))) return false;
+ sig->GetBufferSize(), IID_PPV_ARGS(&rootSig)))) { veyra::log::error("gfx-util","CreateRootSignature failed"); return false; }
D3D12_COMPUTE_PIPELINE_STATE_DESC pd{};
pd.pRootSignature = rootSig.Get();
pd.CS.pShaderBytecode = cs.data();
pd.CS.BytecodeLength = cs.size();
- if (FAILED(device->CreateComputePipelineState(&pd, IID_PPV_ARGS(&pso)))) return false;
+ if (FAILED(device->CreateComputePipelineState(&pd, IID_PPV_ARGS(&pso)))) { veyra::log::error("gfx-util",std::format("CreateComputePipelineState failed constants={} extra={}",constantCount,extraSrvCount)); return false; }
D3D12_DESCRIPTOR_HEAP_DESC hd{};
hd.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
hd.NumDescriptors = heapSlots;
@@ -172,7 +193,7 @@ struct ComputePass {
}
void bind(ID3D12GraphicsCommandList* list, const float* constants,
- uint64_t srvGpu, uint64_t uavGpu) const
+ uint64_t srvGpu, uint64_t uavGpu, uint64_t extraSrvGpu = 0) const
{
ID3D12DescriptorHeap* heaps[] = { heap.Get() };
list->SetDescriptorHeaps(1, heaps);
@@ -183,6 +204,10 @@ struct ComputePass {
const D3D12_GPU_DESCRIPTOR_HANDLE uav{ uavGpu };
list->SetComputeRootDescriptorTable(1, srv);
list->SetComputeRootDescriptorTable(2, uav);
+ if(hasExtraSrv){
+ const D3D12_GPU_DESCRIPTOR_HANDLE extra{ extraSrvGpu };
+ list->SetComputeRootDescriptorTable(3, extra);
+ }
}
};
diff --git a/shaders/ColorGrade.hlsli b/shaders/ColorGrade.hlsli
new file mode 100644
index 00000000..62a31b74
--- /dev/null
+++ b/shaders/ColorGrade.hlsli
@@ -0,0 +1,214 @@
+// Colour grade core (plan v4). It runs inside the existing ingest dispatches, so
+// there is no extra pass and no extra full-frame read/write: the source is
+// decoded to linear and graded by the same thread that writes the working image.
+//
+// Tables, staged by EnhanceGraph in a second SRV table (register base 8):
+// t8 colorCurve : 1024x1 RGBA32F - log-domain input -> per-channel response
+// t9 colorHue : 256x1 RGBA32F - hue -> (shift deg, saturation, luminance)
+// t10 colorLum : 256x1 RGBA32F - tone -> (r,g,b) gains (grading + tint)
+// t11 colorLut : NxNxN RGBA32F - optional .cube LUT, tetrahedral
+//
+// The grade works in normalised scene-linear RGB (1.0 = SDR reference white;
+// HDR sources are normalised by the BT.2408 203-nit reference before the call
+// and scaled back afterwards), and tonal work happens in a Cineon-style log
+// domain because that is where the curve table is indexed.
+#pragma once
+
+Texture2D<float4> colorCurve : register(t8);
+Texture2D<float4> colorHue : register(t9);
+Texture2D<float4> colorLum : register(t10);
+Texture3D<float4> colorLut : register(t11);
+
+// 20 root constants (five float4s), written by
+// veyra::pipeline::packColorGradeConstants.
+struct ColorGradeParams
+{
+ float4 row0; // linear 3x3, row 0 (xyz used)
+ float4 row1;
+ float4 row2;
+ float4 controls; // x=exposure(EV) y=saturation z=vibrance w=lutStrength
+ float4 flags; // x=enabled (0/1) y=lutInputSpace
+};
+
+static const uint kColorCurveEntries = 1024;
+static const uint kColorHueEntries = 256;
+static const uint kColorLumEntries = 256;
+static const float kColorMidGrey = 0.18;
+static const float kColorLogStops = 10.0;
+
+// "linear" is an interpolation modifier in HLSL, so value parameters are named
+// lin throughout this include.
+float3 ColorGradeEncodeLog(float3 lin)
+{
+ return log2(max(lin, 1e-5) / kColorMidGrey) / kColorLogStops + 0.5;
+}
+float3 ColorGradeDecodeLog(float3 encoded)
+{
+ return kColorMidGrey * exp2((encoded - 0.5) * kColorLogStops);
+}
+// Bilinear table reads: the compute passes carry no sampler in their root
+// signature, and a table lookup is exactly what is needed here.
+float4 ColorGradeCurve(float t)
+{
+ const float x = saturate(t) * float(kColorCurveEntries - 1);
+ const uint i0 = uint(floor(x)), i1 = min(i0 + 1, kColorCurveEntries - 1);
+ return lerp(colorCurve.Load(int3(int(i0), 0, 0)), colorCurve.Load(int3(int(i1), 0, 0)), x - float(i0));
+}
+float4 ColorGradeHue(float t)
+{
+ const float x = saturate(t) * float(kColorHueEntries - 1);
+ const uint i0 = uint(floor(x)), i1 = min(i0 + 1, kColorHueEntries - 1);
+ return lerp(colorHue.Load(int3(int(i0), 0, 0)), colorHue.Load(int3(int(i1), 0, 0)), x - float(i0));
+}
+float4 ColorGradeLum(float t)
+{
+ const float x = saturate(t) * float(kColorLumEntries - 1);
+ const uint i0 = uint(floor(x)), i1 = min(i0 + 1, kColorLumEntries - 1);
+ return lerp(colorLum.Load(int3(int(i0), 0, 0)), colorLum.Load(int3(int(i1), 0, 0)), x - float(i0));
+}
+float3 ColorGradeSrgbEncode(float3 lin)
+{
+ const float3 low = lin * 12.92;
+ const float3 high = 1.055 * pow(max(lin, 1e-6), 1.0 / 2.4) - 0.055;
+ return select(lin <= 0.0031308, low, high);
+}
+float3 ColorGradeSrgbDecode(float3 signal)
+{
+ const float3 low = signal / 12.92;
+ const float3 high = pow(max((signal + 0.055) / 1.055, 0.0), 2.4);
+ return select(signal <= 0.04045, low, high);
+}
+float3 ColorGradePqEncode(float3 lin)
+{
+ const float m1 = 2610.0 / 16384.0, m2 = 2523.0 / 32.0;
+ const float c1 = 3424.0 / 4096.0, c2 = 2413.0 / 128.0, c3 = 2392.0 / 128.0;
+ const float3 p = pow(max(lin, 0.0), m1);
+ return pow((c1 + c2 * p) / (1.0 + c3 * p), m2);
+}
+float3 ColorGradePqDecode(float3 signal)
+{
+ const float m1 = 2610.0 / 16384.0, m2 = 2523.0 / 32.0;
+ const float c1 = 3424.0 / 4096.0, c2 = 2413.0 / 128.0, c3 = 2392.0 / 128.0;
+ const float3 p = pow(max(signal, 0.0), 1.0 / m2);
+ return pow(max(p - c1, 0.0) / max(c2 - c3 * p, 1e-6), 1.0 / m1);
+}
+float3 RgbToHsv(float3 c)
+{
+ const float maxc = max(c.r, max(c.g, c.b));
+ const float minc = min(c.r, min(c.g, c.b));
+ const float delta = maxc - minc;
+ float hue = 0.0;
+ if (delta > 1e-6)
+ {
+ if (maxc == c.r) hue = 60.0 * fmod((c.g - c.b) / delta + 6.0, 6.0);
+ else if (maxc == c.g) hue = 60.0 * ((c.b - c.r) / delta + 2.0);
+ else hue = 60.0 * ((c.r - c.g) / delta + 4.0);
+ }
+ return float3(hue, delta / max(maxc, 1e-5), maxc);
+}
+float3 HsvToRgb(float3 hsv)
+{
+ const float h = hsv.x / 60.0;
+ const float c = hsv.z * hsv.y;
+ const float x = c * (1.0 - abs(fmod(h, 2.0) - 1.0));
+ const float m = hsv.z - c;
+ float3 rgb;
+ if (h < 1.0) rgb = float3(c, x, 0);
+ else if (h < 2.0) rgb = float3(x, c, 0);
+ else if (h < 3.0) rgb = float3(0, c, x);
+ else if (h < 4.0) rgb = float3(0, x, c);
+ else if (h < 5.0) rgb = float3(x, 0, c);
+ else rgb = float3(c, 0, x);
+ return rgb + m;
+}
+float ColorGradeLuma(float3 c)
+{
+ return dot(c, float3(0.2126, 0.7152, 0.0722));
+}
+float3 ColorGradeLutSample(float3 uvw)
+{
+ uint3 dims;
+ colorLut.GetDimensions(dims.x, dims.y, dims.z);
+ const float3 coord = saturate(uvw) * float3(dims - 1u);
+ // Clamp the base so the "+1" corners stay inside: at coord == dims-1 a
+ // naive floor would fetch index dims and read out of bounds.
+ const int3 base = int3(min(floor(coord), float3(dims - 2u)));
+ const float3 f = coord - float3(base);
+ const float3 c000 = colorLut.Load(int4(base + int3(0, 0, 0), 0)).rgb;
+ const float3 c100 = colorLut.Load(int4(base + int3(1, 0, 0), 0)).rgb;
+ const float3 c010 = colorLut.Load(int4(base + int3(0, 1, 0), 0)).rgb;
+ const float3 c001 = colorLut.Load(int4(base + int3(0, 0, 1), 0)).rgb;
+ const float3 c110 = colorLut.Load(int4(base + int3(1, 1, 0), 0)).rgb;
+ const float3 c101 = colorLut.Load(int4(base + int3(1, 0, 1), 0)).rgb;
+ const float3 c011 = colorLut.Load(int4(base + int3(0, 1, 1), 0)).rgb;
+ const float3 c111 = colorLut.Load(int4(base + int3(1, 1, 1), 0)).rgb;
+ // Six-case tetrahedral interpolation: four fetches per pixel, no trilinear
+ // diagonal banding on steep LUTs.
+ if (f.x >= f.y)
+ {
+ if (f.y >= f.z) return c000 + f.x * (c100 - c000) + f.y * (c110 - c100) + f.z * (c111 - c110);
+ if (f.x >= f.z) return c000 + f.x * (c100 - c000) + f.z * (c101 - c100) + f.y * (c111 - c101);
+ return c000 + f.z * (c001 - c000) + f.x * (c101 - c001) + f.y * (c111 - c101);
+ }
+ if (f.y >= f.z)
+ {
+ if (f.x >= f.z) return c000 + f.y * (c010 - c000) + f.x * (c110 - c010) + f.z * (c111 - c110);
+ return c000 + f.y * (c010 - c000) + f.z * (c011 - c010) + f.x * (c111 - c011);
+ }
+ return c000 + f.z * (c001 - c000) + f.y * (c011 - c001) + f.x * (c111 - c011);
+}
+// Single entry point: every ingest shader calls this right before writing its
+// linear RGB. Values outside the 10-stop table window pass through untouched so
+// HDR highlights are never clipped by a tone table.
+float3 ColorGradeApply(float3 lin, ColorGradeParams p)
+{
+ if (p.flags.x < 0.5) return lin;
+ const float3x3 matrix = float3x3(p.row0.xyz, p.row1.xyz, p.row2.xyz);
+ const float exposure = p.controls.x, saturation = p.controls.y, vibrance = p.controls.z, lutStrength = p.controls.w;
+ const int lutInputSpace = int(p.flags.y + 0.5);
+ float3 rgb = max(mul(matrix, lin), 0.0) * exp2(exposure);
+
+ // Tone response: per-channel table lookup in the log domain.
+ const float3 encoded = ColorGradeEncodeLog(rgb);
+ const float3 tableOut = float3(
+ ColorGradeCurve(encoded.r).r,
+ ColorGradeCurve(encoded.g).g,
+ ColorGradeCurve(encoded.b).b);
+ const float3 graded = ColorGradeDecodeLog(saturate(tableOut));
+ rgb = select((encoded < 0.0) | (encoded > 1.0), rgb, graded);
+
+ // Hue mixer.
+ const float3 hsv = RgbToHsv(rgb);
+ const float4 hueResponse = ColorGradeHue(hsv.x / 360.0);
+ rgb = HsvToRgb(float3(hsv.x + hueResponse.r, saturate(hsv.y * hueResponse.g), max(hsv.z * hueResponse.b, 0.0)));
+
+ // Luminance-zone grading + calibration shadow tint.
+ const float tone = saturate(ColorGradeEncodeLog(rgb).y);
+ rgb *= ColorGradeLum(tone).rgb;
+
+ // Saturation and vibrance: vibrance scales with how unsaturated the pixel
+ // already is, so skin tones move less than primary colours.
+ const float luma = ColorGradeLuma(rgb);
+ const float maxc = max(rgb.r, max(rgb.g, rgb.b));
+ const float minc = min(rgb.r, min(rgb.g, rgb.b));
+ const float currentSat = saturate((maxc - minc) / max(maxc, 1e-5));
+ const float scale = max(1.0 + saturation / 100.0 + vibrance / 100.0 * (1.0 - currentSat), 0.0);
+ rgb = lerp(luma.xxx, rgb, scale);
+
+ // Optional .cube LUT in its declared input space (importer lands in T5).
+ if (lutStrength > 0.0)
+ {
+ const float3 safe = max(rgb, 0.0);
+ float3 lutInput;
+ if (lutInputSpace == 1) lutInput = ColorGradeSrgbEncode(min(safe, 1.0));
+ else if (lutInputSpace == 2) lutInput = ColorGradePqEncode(safe);
+ else lutInput = saturate(ColorGradeEncodeLog(safe));
+ const float3 lutOutput = ColorGradeLutSample(lutInput);
+ float3 decoded;
+ if (lutInputSpace == 1) decoded = ColorGradeSrgbDecode(lutOutput);
+ else if (lutInputSpace == 2) decoded = ColorGradePqDecode(lutOutput);
+ else decoded = ColorGradeDecodeLog(lutOutput);
+ rgb = lerp(rgb, decoded, saturate(lutStrength));
+ }
+ return max(rgb, 0.0);
+}
diff --git a/shaders/PackedCaptureToLinear.hlsl b/shaders/PackedCaptureToLinear.hlsl
index 97bd0b84..d5fae305 100644
--- a/shaders/PackedCaptureToLinear.hlsl
+++ b/shaders/PackedCaptureToLinear.hlsl
@@ -3,9 +3,11 @@
// UYVY / YVYU with the same color contract as RgbToLinear / Yuy2ToLinear.
// packing: 1 BGR24, 2 RGB555, 3 RGB565, 4 UYVY, 5 YVYU.
#include "HdrColor.hlsli"
+#include "ColorGrade.hlsli"
cbuffer Params : register(b0) {
uint width; uint height; uint transfer; uint limitedU;
float limited; float matrix709; float primaries2020; uint packing;
+ float4 colorRow0; float4 colorRow1; float4 colorRow2; float4 colorControls; float4 colorFlags;
};
Texture2D<float4> packedBytes : register(t0);
RWTexture2D<float4> linearRgb : register(u0);
@@ -47,5 +49,6 @@ void main(uint3 p : SV_DispatchThreadID) {
if (limitedU != 0 && packing <= 3) rgb = saturate((rgb - 16.0 / 255.0) * (255.0 / 219.0));
float3 decoded = float3(decode(rgb.r), decode(rgb.g), decode(rgb.b));
if (primaries2020 > 0.5) decoded = HdrTo709(decoded);
+ if (colorFlags.x > 0.5) { ColorGradeParams grade = { colorRow0, colorRow1, colorRow2, colorControls, colorFlags }; decoded = ColorGradeApply(decoded, grade); }
linearRgb[p.xy] = float4(decoded, 1);
}
diff --git a/shaders/RgbToLinear.hlsl b/shaders/RgbToLinear.hlsl
index bae60e9c..7448cb3f 100644
--- a/shaders/RgbToLinear.hlsl
+++ b/shaders/RgbToLinear.hlsl
@@ -1,5 +1,7 @@
#include "HdrColor.hlsli"
-cbuffer RgbParams : register(b0) { uint width; uint height; uint transfer; uint limited; float2 reserved; float primaries2020; float padding; };
+#include "ColorGrade.hlsli"
+cbuffer RgbParams : register(b0) { uint width; uint height; uint transfer; uint limited; float2 reserved; float primaries2020; float padding;
+ float4 colorRow0; float4 colorRow1; float4 colorRow2; float4 colorControls; float4 colorFlags; };
Texture2D<float4> sourceRgb : register(t0);
RWTexture2D<float4> linearRgb : register(u0);
float decode(float v) {
@@ -16,5 +18,6 @@ void main(uint3 p : SV_DispatchThreadID) {
// Present onto the player's opaque black canvas; never discard RGB chroma.
float3 decoded=float3(decode(c.r),decode(c.g),decode(c.b));
if(primaries2020>0.5)decoded=HdrTo709(decoded);
+ if(colorFlags.x>0.5){ColorGradeParams grade={colorRow0,colorRow1,colorRow2,colorControls,colorFlags};decoded=ColorGradeApply(decoded,grade);}
linearRgb[p.xy]=float4(decoded*c.a,1);
}
diff --git a/shaders/YuvToLinearRgb.hlsl b/shaders/YuvToLinearRgb.hlsl
index 4c95f2d9..7de8ac84 100644
--- a/shaders/YuvToLinearRgb.hlsl
+++ b/shaders/YuvToLinearRgb.hlsl
@@ -4,12 +4,17 @@
// transfer) arrives as root constants set per frame from FFmpeg stream data.
#include "HdrColor.hlsli"
#include "HdrToSdr.hlsli"
+#include "ColorGrade.hlsli"
cbuffer YuvParams : register(b0)
{
float4 colorParams0; // x=limitedRange y=matrix709 z=transferSRGB w=padding
uint4 yuvDimensions; // x=width y=height z=bit0 nativeHDR, bit1 BT2020 primaries; w=chroma location
float4 toneMapParams; // x=validated source peak nits, y=SDR target peak nits
+ // Colour grade (plan v4): appended after the existing constants, packed by
+ // veyra::pipeline::packColorGradeConstants (five float4s).
+ float4 colorRow0; float4 colorRow1; float4 colorRow2;
+ float4 colorControls; float4 colorFlags;
};
Texture2D<float> lumaPlane : register(t0); // R8_UNORM or R16_UNORM
@@ -107,6 +112,9 @@ void main(uint3 dispatchThreadId : SV_DispatchThreadID)
nits=1000.0*scene*pow(max(dot(scene,float3(.2627,.6780,.0593)),0),.2);
}
float3 linear709=mul(float3x3(1.660491,-0.587641,-0.072850,-0.124550,1.132900,-0.008349,-0.018151,-0.100579,1.118730),nits);
+ // Grade in the normalised domain: HDR is referenced to the BT.2408
+ // 203 cd/m2 SDR reference white; SDR paths below are already 0..1.
+ if(colorFlags.x>0.5){ColorGradeParams grade={colorRow0,colorRow1,colorRow2,colorControls,colorFlags};linear709=ColorGradeApply(linear709/203.0,grade)*203.0;}
if((yuvDimensions.z&1)!=0)rgb=linear709/80.0; // scRGB: 1.0 = 80 nits.
else{
rgb=HdrToSdr(linear709,toneMapParams.x,toneMapParams.y);
@@ -121,5 +129,8 @@ void main(uint3 dispatchThreadId : SV_DispatchThreadID)
rgb = float3(SrgbDecode(rgb.r), SrgbDecode(rgb.g), SrgbDecode(rgb.b));
}
if(colorParams0.z<3.5&&(yuvDimensions.z&2)!=0)rgb=HdrTo709(rgb);
+ // SDR paths carry normalised scene-linear RGB here (after any primaries
+ // conversion), which is exactly the domain ColorGradeApply expects.
+ if(colorParams0.z<3.5&&colorFlags.x>0.5){ColorGradeParams grade={colorRow0,colorRow1,colorRow2,colorControls,colorFlags};rgb=ColorGradeApply(rgb,grade);}
linearRgb[dispatchThreadId.xy] = float4(rgb, 1.0);
}
diff --git a/shaders/Yuy2ToLinear.hlsl b/shaders/Yuy2ToLinear.hlsl
index e9951010..e77191e3 100644
--- a/shaders/Yuy2ToLinear.hlsl
+++ b/shaders/Yuy2ToLinear.hlsl
@@ -1,9 +1,11 @@
// Native 4:2:2 capture. One RGBA8 texel stores Y0 U Y1 V for two pixels.
// No CPU RGB expansion, intermediate 8-bit RGB rounding, or 4:2:0 conversion.
#include "HdrColor.hlsli"
+#include "ColorGrade.hlsli"
cbuffer Params : register(b0) {
uint width; uint height; uint transfer; uint reserved;
float limited; float matrix709; float primaries2020; float padding;
+ float4 colorRow0; float4 colorRow1; float4 colorRow2; float4 colorControls; float4 colorFlags;
};
Texture2D<float4> packedYuy2 : register(t0);
RWTexture2D<float4> linearRgb : register(u0);
@@ -28,5 +30,6 @@ void main(uint3 p : SV_DispatchThreadID) {
rgb=saturate(rgb);
float3 decoded=float3(decode(rgb.r),decode(rgb.g),decode(rgb.b));
if(primaries2020>0.5)decoded=HdrTo709(decoded);
+ if(colorFlags.x>0.5){ColorGradeParams grade={colorRow0,colorRow1,colorRow2,colorControls,colorFlags};decoded=ColorGradeApply(decoded,grade);}
linearRgb[p.xy]=float4(decoded,1);
}
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index 64bbd756..ec2840e8 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -264,7 +264,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
const bool nvidiaAdapter=ctx.adapter().isNvidia;
const bool xessFg=presentSinkFrameGeneration(options.settings.frameGenerationBackend);
gd.nrBeforeSr=!isImage&&options.settings.lowLatency&&options.nr&&resolution.srApplied;gd.enableSr=resolution.srApplied&&(nvidiaAdapter||options.settings.videoSrQuality==kVideoSrFsr);gd.videoSrQuality=options.settings.videoSrQuality;gd.enableNr=options.nr&&nvidiaAdapter;gd.nrRuntime=options.settings.nrRuntime;gd.enableFg=options.fg&&(nvidiaAdapter||xessFg);gd.fgMultiplier=options.fgMultiplier;gd.frameGenerationBackend=options.settings.frameGenerationBackend;gd.enableNvofStandalone=gd.enableNr;
- gd.noFeatures=false;gd.model=options.settings.model;gd.residual=options.settings.residual;gd.protection=options.settings.protection;gd.settingsRevision=options.settings.revision;gd.flowQuality=options.settings.flow;gd.contentRate=options.settings.content;
+ gd.noFeatures=false;gd.model=options.settings.model;gd.residual=options.settings.residual;gd.protection=options.settings.protection;gd.color=options.settings.color;gd.settingsRevision=options.settings.revision;gd.flowQuality=options.settings.flow;gd.contentRate=options.settings.content;
gd.opticalFlowBackend=options.settings.opticalFlowBackend;gd.amdFlowHalfResolution=options.settings.amdFlowHalfResolution;
gd.hdrOutput=options.settings.useHdrPreview(gd.hdrInput,gfx::PresentSink::hdrDisplayActive(window));
veyra::log::info("display-color",std::format("hdrInput={} hdrOutput={} forceSdrPreview={}",gd.hdrInput,gd.hdrOutput,options.settings.forceSdrPreview));
@@ -706,10 +706,10 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
const bool nvidiaAdapter=ctx.adapter().isNvidia;
const bool xessFg=presentSinkFrameGeneration(next.settings.frameGenerationBackend);
nextDesc.nrBeforeSr=!isImage&&requested.lowLatency&&requested.nr&&plan.srApplied;nextDesc.enableSr=plan.srApplied&&(nvidiaAdapter||next.settings.videoSrQuality==kVideoSrFsr);nextDesc.videoSrQuality=next.settings.videoSrQuality;nextDesc.enableNr=next.nr&&nvidiaAdapter;nextDesc.nrRuntime=next.settings.nrRuntime;nextDesc.enableFg=next.fg&&(nvidiaAdapter||xessFg);nextDesc.fgMultiplier=next.fgMultiplier;nextDesc.frameGenerationBackend=next.settings.frameGenerationBackend;nextDesc.enableNvofStandalone=nextDesc.enableNr;
- nextDesc.model=requested.model;nextDesc.residual=requested.residual;nextDesc.protection=requested.protection;nextDesc.settingsRevision=requested.revision;nextDesc.flowQuality=requested.flow;nextDesc.contentRate=requested.content;
+ nextDesc.model=requested.model;nextDesc.residual=requested.residual;nextDesc.protection=requested.protection;nextDesc.color=requested.color;nextDesc.settingsRevision=requested.revision;nextDesc.flowQuality=requested.flow;nextDesc.contentRate=requested.content;
nextDesc.opticalFlowBackend=requested.opticalFlowBackend;nextDesc.amdFlowHalfResolution=requested.amdFlowHalfResolution;
nextDesc.hdrOutput=requested.useHdrPreview(nextDesc.hdrInput,gfx::PresentSink::hdrDisplayActive(window));
- const bool rebuild=(!nvidiaAdapter&&(next.nr||next.sr||(next.fg&&!xessFg)))||gd.hdrOutput!=nextDesc.hdrOutput||previous.captureCompatible!=requested.captureCompatible||gd.nrRuntime!=nextDesc.nrRuntime||gd.opticalFlowBackend!=nextDesc.opticalFlowBackend||gd.amdFlowHalfResolution!=nextDesc.amdFlowHalfResolution||gd.enableNr!=nextDesc.enableNr||gd.enableFg!=nextDesc.enableFg||gd.frameGenerationBackend!=nextDesc.frameGenerationBackend||gd.fgMultiplier!=nextDesc.fgMultiplier||gd.videoSrQuality!=nextDesc.videoSrQuality||gd.flowQuality!=nextDesc.flowQuality||gd.nrBeforeSr!=nextDesc.nrBeforeSr||gd.workWidth!=nextDesc.workWidth||gd.workHeight!=nextDesc.workHeight||gd.nrWidth!=nextDesc.nrWidth||gd.nrHeight!=nextDesc.nrHeight||gd.flowWidth!=nextDesc.flowWidth||gd.flowHeight!=nextDesc.flowHeight;
+ const bool rebuild=(!nvidiaAdapter&&(next.nr||next.sr||(next.fg&&!xessFg)))||gd.hdrOutput!=nextDesc.hdrOutput||previous.captureCompatible!=requested.captureCompatible||gd.nrRuntime!=nextDesc.nrRuntime||gd.opticalFlowBackend!=nextDesc.opticalFlowBackend||gd.amdFlowHalfResolution!=nextDesc.amdFlowHalfResolution||gd.enableNr!=nextDesc.enableNr||gd.color.enabled!=nextDesc.color.enabled||gd.enableFg!=nextDesc.enableFg||gd.frameGenerationBackend!=nextDesc.frameGenerationBackend||gd.fgMultiplier!=nextDesc.fgMultiplier||gd.videoSrQuality!=nextDesc.videoSrQuality||gd.flowQuality!=nextDesc.flowQuality||gd.nrBeforeSr!=nextDesc.nrBeforeSr||gd.workWidth!=nextDesc.workWidth||gd.workHeight!=nextDesc.workHeight||gd.nrWidth!=nextDesc.nrWidth||gd.nrHeight!=nextDesc.nrHeight||gd.flowWidth!=nextDesc.flowWidth||gd.flowHeight!=nextDesc.flowHeight;
bool accepted=ring.drainQueue();out={};hasOutput=false;
resetRecord->rebuilt=rebuild;
markResetStage(diagnostics::ResetStage::Drain);
diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cpp
index a7f6c18e..b7d23989 100644
--- a/src/pipeline/EnhanceGraph.cpp
+++ b/src/pipeline/EnhanceGraph.cpp
@@ -101,6 +101,119 @@ EnhanceGraph::~EnhanceGraph()
// ---------------------------------------------------------------------------
// initialize: exact ordering of the proven probe sequence.
// ---------------------------------------------------------------------------
+// ---------------------------------------------------------------------------
+// Colour grade (plan v4): the tables are baked on the CPU, uploaded into small
+// FP32 textures and read by the ingest shaders. Nothing here allocates, copies
+// or dispatches when desc.color.enabled is false, so the "off" path costs zero.
+// ---------------------------------------------------------------------------
+namespace {
+ComPtr<ID3D12Resource> makeColorTable(ID3D12Device* device,uint32_t width){
+ return makeTexture(device,width,1,DXGI_FORMAT_R32G32B32A32_FLOAT,false);
+}
+ComPtr<ID3D12Resource> makeColorLut3D(ID3D12Device* device,uint32_t size){
+ D3D12_HEAP_PROPERTIES hp{};hp.Type=D3D12_HEAP_TYPE_DEFAULT;
+ D3D12_RESOURCE_DESC td{};
+ td.Dimension=D3D12_RESOURCE_DIMENSION_TEXTURE3D;
+ td.Width=size;td.Height=size;td.DepthOrArraySize=UINT16(size);td.MipLevels=1;
+ td.Format=DXGI_FORMAT_R32G32B32A32_FLOAT;td.SampleDesc.Count=1;
+ ComPtr<ID3D12Resource> r;
+ if(FAILED(device->CreateCommittedResource(&hp,D3D12_HEAP_FLAG_NONE,&td,D3D12_RESOURCE_STATE_COMMON,nullptr,IID_PPV_ARGS(&r))))return {};
+ return r;
+}
+}
+bool EnhanceGraph::createColorResources(){
+ if(colorCurveTex_&&colorHueTex_&&colorLumTex_&&colorLutTex_)return true;
+ colorCurveTex_=makeColorTable(context_.device(),ColorGradeTables::kCurveEntries);
+ colorHueTex_=makeColorTable(context_.device(),ColorGradeTables::kHueEntries);
+ colorLumTex_=makeColorTable(context_.device(),ColorGradeTables::kLumEntries);
+ // 1x1x1 placeholder keeps the descriptor valid while no LUT is loaded;
+ // lutStrength stays 0 in that case, so it is never sampled.
+ colorLutTex_=makeColorLut3D(context_.device(),1);
+ colorLutSize_=0;
+ upColorCurve_=makeUploadBuffer(context_.device(),sizeof(float)*4*ColorGradeTables::kCurveEntries);
+ upColorHue_=makeUploadBuffer(context_.device(),sizeof(float)*4*ColorGradeTables::kHueEntries);
+ upColorLum_=makeUploadBuffer(context_.device(),sizeof(float)*4*ColorGradeTables::kLumEntries);
+ if(!colorCurveTex_||!colorHueTex_||!colorLumTex_||!colorLutTex_||!upColorCurve_||!upColorHue_||!upColorLum_){
+ veyra::log::error("color-grade",std::format("colour resources unavailable tables={} lut={}",colorCurveTex_?1:0,colorLutTex_?1:0));
+ return false;
+ }
+ if(FAILED(upColorCurve_->Map(0,nullptr,reinterpret_cast<void**>(&mappedColorCurve_)))||
+ FAILED(upColorHue_->Map(0,nullptr,reinterpret_cast<void**>(&mappedColorHue_)))||
+ FAILED(upColorLum_->Map(0,nullptr,reinterpret_cast<void**>(&mappedColorLum_))))return false;
+ return true;
+}
+void EnhanceGraph::refreshColorTables(){
+ colorTables_=ColorGradeTables::bake(desc_.color);
+ if(!colorActive_||!mappedColorCurve_||!mappedColorHue_||!mappedColorLum_)return;
+ std::copy(colorTables_.curve.begin(),colorTables_.curve.end(),mappedColorCurve_);
+ std::copy(colorTables_.hue.begin(),colorTables_.hue.end(),mappedColorHue_);
+ std::copy(colorTables_.lum.begin(),colorTables_.lum.end(),mappedColorLum_);
+ colorDirty_=true;
+}
+void EnhanceGraph::uploadColorTables(ID3D12GraphicsCommandList* list){
+ if(!colorDirty_)return;
+ auto copyTable=[&](ID3D12Resource* dst,ID3D12Resource* src,UINT width){
+ tracker_.transition(list,dst,D3D12_RESOURCE_STATE_COPY_DEST);
+ D3D12_TEXTURE_COPY_LOCATION d{},s{};
+ d.pResource=dst;d.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;d.SubresourceIndex=0;
+ s.pResource=src;s.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
+ s.PlacedFootprint.Footprint={DXGI_FORMAT_R32G32B32A32_FLOAT,width,1,1,width*16};
+ list->CopyTextureRegion(&d,0,0,0,&s,nullptr);
+ tracker_.transition(list,dst,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
+ };
+ copyTable(colorCurveTex_.Get(),upColorCurve_.Get(),ColorGradeTables::kCurveEntries);
+ copyTable(colorHueTex_.Get(),upColorHue_.Get(),ColorGradeTables::kHueEntries);
+ copyTable(colorLumTex_.Get(),upColorLum_.Get(),ColorGradeTables::kLumEntries);
+ if(colorLutPending_&&!colorLutUpload_.empty()){
+ const unsigned size=colorLutPending_;
+ const uint64_t bytes=uint64_t(size)*size*size*16;
+ auto& staging=colorLutStaging_[colorLutStagingSlot_];
+ colorLutStagingSlot_=(colorLutStagingSlot_+1)%colorLutStaging_.size();
+ staging=makeUploadBuffer(context_.device(),bytes);
+ void* mapped=nullptr;
+ if(staging&&SUCCEEDED(staging->Map(0,nullptr,&mapped))&&mapped){
+ auto* dst=static_cast<float*>(mapped);
+ for(size_t i=0;i<size_t(size)*size*size;++i){
+ dst[i*4+0]=colorLutUpload_[i*3+0];
+ dst[i*4+1]=colorLutUpload_[i*3+1];
+ dst[i*4+2]=colorLutUpload_[i*3+2];
+ dst[i*4+3]=1.0f;
+ }
+ staging->Unmap(0,nullptr);
+ tracker_.transition(list,colorLutTex_.Get(),D3D12_RESOURCE_STATE_COPY_DEST);
+ D3D12_TEXTURE_COPY_LOCATION d{},s{};
+ d.pResource=colorLutTex_.Get();d.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;d.SubresourceIndex=0;
+ s.pResource=staging.Get();s.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
+ s.PlacedFootprint.Footprint={DXGI_FORMAT_R32G32B32A32_FLOAT,size,size,size,size*16};
+ list->CopyTextureRegion(&d,0,0,0,&s,nullptr);
+ tracker_.transition(list,colorLutTex_.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
+ }else{
+ veyra::log::warn("color-grade","lut staging buffer unavailable; keeping the previous table");
+ }
+ colorLutUpload_.clear();
+ colorLutPending_=0;
+ }
+ colorDirty_=false;
+}
+bool EnhanceGraph::setColorLut(const float* rgb,unsigned size){
+ if(!colorActive_||size<2||size>64)return false;
+ if(!createColorResources())return false;
+ colorLutTex_=makeColorLut3D(context_.device(),size);
+ if(!colorLutTex_)return false;
+ colorLutSize_=size;
+ colorLutUpload_.assign(rgb,rgb+std::size_t(size)*size*size*3);
+ colorLutPending_=size;
+ colorDirty_=true;
+ // Callers must have drained the queue: the descriptor is re-staged in place.
+ D3D12_SHADER_RESOURCE_VIEW_DESC lutSrv{};
+ lutSrv.Format=DXGI_FORMAT_R32G32B32A32_FLOAT;
+ lutSrv.ViewDimension=D3D12_SRV_DIMENSION_TEXTURE3D;
+ lutSrv.Shader4ComponentMapping=D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
+ lutSrv.Texture3D.MipLevels=1;
+ for(auto* pass:{&yuvPass_,&rgbPass_})if(pass->heap)stager_.stageSrv(colorLutTex_.Get(),&lutSrv,pass->heap.Get(),11);
+ return true;
+}
+
bool EnhanceGraph::initialize(const EnhanceGraphDesc& desc)
{
failedBackend_=engine::FailedBackend::Infrastructure;
@@ -236,6 +349,15 @@ bool EnhanceGraph::createResources()
baseFlow_=makeTexture(context_.device(),workW_,workH_,DXGI_FORMAT_R16G16_FLOAT,true);
if(presentSinkFg())for(auto& motion:presentMotion_){motion=makeTexture(context_.device(),workW_,workH_,DXGI_FORMAT_R16G16_FLOAT,false);if(!motion)return false;}
if(!nrInput_||!residualRgba_||!nrFlow_||!baseFlow_)return false;
+ // Colour grade tables (v4): only allocated when the stage is enabled.
+ colorActive_=desc_.color.enabled;
+ if(colorActive_){
+ if(!createColorResources())return false;
+ refreshColorTables();
+ veyra::log::info("color-grade",std::format("stage enabled tables={}/{}/{} lutInputSpace={} lut={}",
+ ColorGradeTables::kCurveEntries,ColorGradeTables::kHueEntries,ColorGradeTables::kLumEntries,
+ desc_.color.lutInputSpace,desc_.color.hasLut()?1:0));
+ }
proxyTex_ = makeTexture(context_.device(), nrW_, nrH_, DXGI_FORMAT_R8G8B8A8_UNORM, true);
neuralTex_ = makeTexture(context_.device(), nrW_, nrH_, DXGI_FORMAT_R8G8B8A8_UNORM, true);
finalRgba_ = makeTexture(context_.device(), nrW_, nrH_, DXGI_FORMAT_R16G16B16A16_FLOAT, true);
@@ -884,9 +1006,9 @@ bool EnhanceGraph::createComputePasses()
if(!downsamplePass_.loadShader("NrDownsample.dxil",cs)||!downsamplePass_.create(context_.device(),cs,2,1,1))return false;
if(!residualPass_.loadShader("NrResidualComposite.dxil",cs)||!residualPass_.create(context_.device(),cs,4,3,1,24))return false;
if(!flowAdaptPass_.loadShader("FlowAdapt.dxil",cs)||!flowAdaptPass_.create(context_.device(),cs,3,1,1))return false;
- if (!yuvPass_.loadShader("YuvToLinearRgb.dxil", cs) || !yuvPass_.create(context_.device(), cs, 8, 2, 1, 12)) return false;
+ if (!yuvPass_.loadShader("YuvToLinearRgb.dxil", cs) || !yuvPass_.create(context_.device(), cs, 12, 2, 1, 12+kColorGradeConstantCount, 4)) return false;
const char* rgbShader=desc_.packedInput?"PackedCaptureToLinear.dxil":desc_.yuy2Input?"Yuy2ToLinear.dxil":"RgbToLinear.dxil";
- if((desc_.rgbInput||desc_.yuy2Input||desc_.packedInput)&&(!rgbPass_.loadShader(rgbShader,cs)||!rgbPass_.create(context_.device(),cs,8,1,1)))return false;
+ if((desc_.rgbInput||desc_.yuy2Input||desc_.packedInput)&&(!rgbPass_.loadShader(rgbShader,cs)||!rgbPass_.create(context_.device(),cs,12,1,1,8+kColorGradeConstantCount,4)))return false;
if (!encPass_.loadShader("ParityEncode.dxil", cs) || !encPass_.create(context_.device(), cs, 8, 1, 1)) return false;
if (!decPass_.loadShader("ParityDecode.dxil", cs) || !decPass_.create(context_.device(), cs, 8)) return false;
if (!blitPass_.loadShader("ScaleBlit.dxil", cs) || !blitPass_.create(context_.device(), cs, 19, 1, 1)) return false;
@@ -985,6 +1107,21 @@ bool EnhanceGraph::createViews()
if(videoSrOutput_&&viewsTex)stagedSrv(videoSrOutput_.Get(),DXGI_FORMAT_R8G8B8A8_UNORM,blitPass_,17);
if (viewsTex) stagedSrv(residualRgba_.Get(),DXGI_FORMAT_R16G16B16A16_FLOAT,blitPass_,18);
if (viewsTex) stagedSrv(srcRgba_.Get(), DXGI_FORMAT_R16G16B16A16_FLOAT, blitPass_, 0);
+ // Colour-grade tables: four SRVs at the extra table's fixed register base.
+ if(colorActive_){
+ D3D12_SHADER_RESOURCE_VIEW_DESC lutSrv{};
+ lutSrv.Format=DXGI_FORMAT_R32G32B32A32_FLOAT;
+ lutSrv.ViewDimension=D3D12_SRV_DIMENSION_TEXTURE3D;
+ lutSrv.Shader4ComponentMapping=D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
+ lutSrv.Texture3D.MipLevels=1;
+ for(auto* pass:{&yuvPass_,&rgbPass_}){
+ if(!pass->heap)continue;
+ stager_.stageSrv(colorCurveTex_.Get(),nullptr,pass->heap.Get(),8);
+ stager_.stageSrv(colorHueTex_.Get(),nullptr,pass->heap.Get(),9);
+ stager_.stageSrv(colorLumTex_.Get(),nullptr,pass->heap.Get(),10);
+ stager_.stageSrv(colorLutTex_.Get(),&lutSrv,pass->heap.Get(),11);
+ }
+ }
if (viewsUav) makeUav(context_.device(), workRgba_.Get(), DXGI_FORMAT_R16G16B16A16_FLOAT, cpu(blitPass_, 1));
if (viewsTex) stagedSrv(nrEnabled_&&!desc_.nrBeforeSr ? residualRgba_.Get() : workRgba_.Get(), DXGI_FORMAT_R16G16B16A16_FLOAT, blitPass_, 2);
if (viewsUav) makeUav(context_.device(), videoFrame_[0].Get(), outputFormat(), cpu(blitPass_, 3));
@@ -1271,19 +1408,22 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
if (desc_.stageMark) desc_.stageMark("upload");
// 2. YUV -> RGBA16F.
+ if(colorActive_&&colorDirty_)uploadColorTables(list);
tracker_.transition(list, srcRgba_.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
if(desc_.rgbInput||desc_.yuy2Input||desc_.packedInput){
- const float c[8]={uintBits(srcW_),uintBits(srcH_),uintBits(workingTransferCode(resolved)),uintBits(resolved.range==ColorRange::Limited?1u:0u),
+ float c[8+kColorGradeConstantCount]={uintBits(srcW_),uintBits(srcH_),uintBits(workingTransferCode(resolved)),uintBits(resolved.range==ColorRange::Limited?1u:0u),
resolved.range==ColorRange::Full?0.0f:1.0f,resolved.matrix==YuvMatrix::BT2020NCL?2.0f:resolved.matrix==YuvMatrix::BT601?0.0f:1.0f,resolved.primaries==ColorPrimaries::BT2020?1.0f:0.0f,uintBits(desc_.packedInput)};
- rgbPass_.bind(list,c,gpuHandleOf(rgbPass_,0).ptr,gpuHandleOf(rgbPass_,1).ptr);
+ if(colorActive_)packColorGradeConstants(colorTables_,c+8);
+ rgbPass_.bind(list,c,gpuHandleOf(rgbPass_,0).ptr,gpuHandleOf(rgbPass_,1).ptr,gpuHandleOf(rgbPass_,8).ptr);
list->Dispatch((srcW_+15)/16,(srcH_+15)/16,1);
}else{
- const float constants[12] = { resolved.range==ColorRange::Full?0.0f:1.0f,
+ float constants[12+kColorGradeConstantCount] = { resolved.range==ColorRange::Full?0.0f:1.0f,
resolved.matrix==YuvMatrix::BT2020NCL?2.0f:resolved.matrix==YuvMatrix::BT601?0.0f:1.0f,
resolved.transfer==TransferFunction::HLG?5.0f:resolved.transfer==TransferFunction::PQ?4.0f:float(workingTransferCode(resolved)), (nv12Texture?(nv12Texture->GetDesc().Format==DXGI_FORMAT_P010?1.0f:0.0f):(desc_.captureBitDepth==16?2.0f:desc_.wideYuvInput()?1.0f:0.0f)),
uintBits(srcW_), uintBits(srcH_), uintBits((desc_.hdrOutput?1u:0u)|(resolved.primaries==ColorPrimaries::BT2020?2u:0u)),
uintBits(resolved.reconstructChroma?std::max(1u,unsigned(resolved.chromaLocation)):0u),toneMapPeakNits_,203.0f,0,0 };
- yuvPass_.bind(list, constants, gpuHandleOf(yuvPass_, nv12Texture ? 3 + parity * 2 : 0).ptr, gpuHandleOf(yuvPass_, 2).ptr);
+ if(colorActive_)packColorGradeConstants(colorTables_,constants+12);
+ yuvPass_.bind(list, constants, gpuHandleOf(yuvPass_, nv12Texture ? 3 + parity * 2 : 0).ptr, gpuHandleOf(yuvPass_, 2).ptr,gpuHandleOf(yuvPass_,8).ptr);
list->Dispatch((srcW_ + 15) / 16, (srcH_ + 15) / 16, 1);
}
tracker_.uavBarrier(list, srcRgba_.Get());
@@ -1707,6 +1847,10 @@ bool EnhanceGraph::applySettings(const engine::EnhancementSettings& s){
// XeSS has a fixed 2X proxy swapchain contract. Settings callers must
// rebuild instead of accepting a change that cannot take effect in place.
if(s.nrRuntime!=desc_.nrRuntime||std::max(2u,s.multiplier)!=desc_.fgMultiplier||s.frameGenerationBackend!=desc_.frameGenerationBackend||s.videoSrQuality!=desc_.videoSrQuality||!s.validate().empty()||(s.multiplier>1&&!engine::presentSinkFrameGeneration(s.frameGenerationBackend)&&(!fgCapsAvailable_||s.multiplier-1>uint32_t(fgMultiFrameMax_))))return false;
+ // The colour master switch changes the graph shape (tables + shader branch)
+ // and must rebuild; every other colour field is a live uniform update.
+ if(s.color.enabled!=desc_.color.enabled)return false;
+ if(!(s.color==desc_.color)){desc_.color=s.color;refreshColorTables();}
desc_.contentRate=s.content;desc_.model=s.model;desc_.residual=s.residual;desc_.protection=s.protection;desc_.settingsRevision=s.revision;
desc_.fgMultiplier=std::max(2u,s.multiplier);desc_.enableNvofStandalone=s.nr&&!desc_.stillImage;nvofStandalone_=desc_.enableNvofStandalone;
setNrEnabled(s.nr);setFgEnabled(s.multiplier>1&&!engine::presentSinkFrameGeneration(s.frameGenerationBackend));
diff --git a/tests/integration/ColorGradeGpuTests.cpp b/tests/integration/ColorGradeGpuTests.cpp
new file mode 100644
index 00000000..771a62db
--- /dev/null
+++ b/tests/integration/ColorGradeGpuTests.cpp
@@ -0,0 +1,125 @@
+// GPU acceptance for the v4 colour chain. The grade rides inside the ingest
+// dispatch, so these cases drive a real graph and read the presented frame:
+// * master switch off -> byte-identical to the ungraded baseline
+// * enabled + neutral -> byte-identical to the ungraded baseline (identity)
+// * +1 EV -> clearly brighter coded value
+// * point curve -> the control point lands where the model says
+// * saturation -100 -> a saturated input collapses to grey
+// The optional .cube LUT is exercised once its importer lands (T5).
+#include "veyra/pipeline/EnhanceGraph.h"
+#include "veyra/gfx/D3D12DeviceContext.h"
+#include "veyra/gfx/CommandSlotRing.h"
+#include "veyra/sink/ImageExportSink.h"
+#include "veyra/engine/EnhancementSettings.h"
+#include "veyra/engine/ColorSettings.h"
+#include <cmath>
+#include <cstdio>
+#include <string>
+#include <vector>
+extern "C" {
+#include <libavutil/frame.h>
+#include <libavutil/pixfmt.h>
+}
+namespace {
+using namespace veyra;
+int failures=0;
+void check(bool ok,const std::string& label){
+ std::printf("%s %s\n",ok?"PASS":"FAIL",label.c_str());
+ if(!ok)++failures;
+}
+constexpr int kSize=64;
+
+// One frame of a solid colour, sRGB-coded RGB32 (the still-image / RGB capture
+// ingress path), so the linear value is exactly the sRGB decode of the code.
+struct Frame {
+ AVFrame* frame=nullptr;
+ ~Frame(){if(frame)av_frame_free(&frame);}
+ bool make(uint8_t r,uint8_t g,uint8_t b){
+ frame=av_frame_alloc();
+ frame->format=AV_PIX_FMT_BGR0;frame->width=frame->height=kSize;
+ frame->color_range=AVCOL_RANGE_UNSPECIFIED;frame->color_trc=AVCOL_TRC_IEC61966_2_1;frame->colorspace=AVCOL_SPC_RGB;
+ if(av_frame_get_buffer(frame,32)<0)return false;
+ for(int y=0;y<kSize;++y)for(int x=0;x<kSize;++x){
+ auto* p=frame->data[0]+std::size_t(y)*frame->linesize[0]+std::size_t(x)*4;
+ p[0]=b;p[1]=g;p[2]=r;p[3]=255;
+ }
+ return true;
+ }
+};
+struct Graph {
+ gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;
+ pipeline::EnhanceGraph g{ctx,ring};
+ bool up=false;
+ bool start(bool colorEnabled){
+ gfx::DeviceContextDesc device;Status st;
+ if(!ctx.initialize(device,st)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),4,st))return false;
+ up=true;
+ pipeline::EnhanceGraphDesc gd;
+ gd.sourceWidth=gd.sourceHeight=gd.workWidth=gd.workHeight=kSize;
+ gd.rgbInput=true;gd.stillImage=true;gd.noFeatures=true;gd.enableNr=false;gd.enableSr=false;gd.enableFg=false;
+ gd.color.enabled=colorEnabled;
+ return g.initialize(gd)&&g.createViews();
+ }
+ bool apply(const engine::EnhancementSettings& settings){return g.applySettings(settings);}
+ bool render(Frame& frame,sink::RgbaImage& out){
+ pipeline::EnhanceGraph::FrameOutputs outputs;
+ return g.process(frame.frame,0,true,outputs,1)&&
+ sink::readRgba8(ctx,ring,g.videoFrameResource(outputs.videoSlot),out);
+ }
+ ~Graph(){if(up){ring.drainQueue();g.shutdown();ring.shutdown();ctx.shutdown();}}
+};
+struct Pixel { int r=0,g=0,b=0; };
+Pixel center(const sink::RgbaImage& image){
+ const auto index=(std::size_t(kSize/2)*std::size_t(image.width)+std::size_t(kSize/2))*4;
+ return {image.pixels[index],image.pixels[index+1],image.pixels[index+2]};
+}
+}
+int wmain(){
+ // 1. Master switch off and enabled-neutral are both identity.
+ {
+ Graph off,on;
+ if(!off.start(false)||!on.start(true)){std::printf("FAIL graph init\n");return 1;}
+ Frame f1,f2;
+ sink::RgbaImage baseline,neutral;
+ const bool ready=f1.make(188,96,64)&&f2.make(188,96,64)&&off.render(f1,baseline)&&on.render(f2,neutral);
+ check(ready,"colour graphs initialise and render");
+ if(ready)check(baseline.pixels==neutral.pixels,"master off and enabled-neutral are byte-identical to the ungraded path");
+ }
+ // 2. Exposure, curve, saturation and hue behaviour through the real graph.
+ {
+ Graph graph;
+ if(!graph.start(true)){std::printf("FAIL graph init\n");return 1;}
+ Frame neutral,exposed,curved,grass,desaturated;
+ sink::RgbaImage a,b,c,d,e;
+ if(!(neutral.make(188,188,188)&&exposed.make(188,188,188)&&curved.make(188,188,188)&&
+ grass.make(64,160,64)&&desaturated.make(64,160,64)&&graph.render(neutral,a))){
+ std::printf("FAIL baseline render\n");return 1;
+ }
+ const auto neutralPixel=center(a);
+ {
+ if(!graph.render(grass,d)){std::printf("FAIL colour render\n");return 1;}
+ const auto coloured=center(d);
+ check(coloured.g>coloured.r&&coloured.g>coloured.b,"a green input stays green through the neutral grade");
+ }
+ {
+ engine::EnhancementSettings s;s.color.enabled=true;s.color.exposure=1.0f;
+ if(!graph.apply(s)||!graph.render(exposed,b)){std::printf("FAIL exposure render\n");return 1;}
+ check(center(b).r>neutralPixel.r+20,"+1 EV brightens mid grey by a visible step");
+ }
+ {
+ engine::EnhancementSettings s;s.color.enabled=true;
+ s.color.curves[0].count=3;s.color.curves[0].points[1]={0.5f,0.75f};s.color.curves[0].points[2]={1,1};
+ if(!graph.apply(s)||!graph.render(curved,c)){std::printf("FAIL curve render\n");return 1;}
+ check(center(c).r>neutralPixel.r+10,"point curve at 0.5 raises the coded value");
+ }
+ {
+ engine::EnhancementSettings s;s.color.enabled=true;s.color.saturation=-100.0f;
+ if(!graph.apply(s)||!graph.render(desaturated,e)){std::printf("FAIL saturation render\n");return 1;}
+ const auto pixel=center(e);
+ check(std::abs(pixel.r-pixel.g)<=2&&std::abs(pixel.g-pixel.b)<=2,"saturation -100 collapses the frame to grey");
+ }
+ }
+ if(failures){std::printf("FAIL: colour grade GPU contract (%d checks)\n",failures);return 1;}
+ std::printf("PASS: colour grade GPU contract (off/neutral identity, exposure, curve, saturation, hue)\n");
+ return 0;
+}