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++

Audit native HDR round trips and expose HDR output diagnostics

Veyra Goal Agent813f9f15b2d3
diff --git a/docs/HDR_GRAY_CHAIN_AUDIT_2026-09-15.md b/docs/HDR_GRAY_CHAIN_AUDIT_2026-09-15.md
new file mode 100644
index 00000000..f6c2a4a6
--- /dev/null
+++ b/docs/HDR_GRAY_CHAIN_AUDIT_2026-09-15.md
@@ -0,0 +1,72 @@
+# HDR 发灰链路复核
+
+## 本轮结论与范围
+
+用户要求检查此前HDR发灰是否也是错误曲线,反馈时实际输出模式未知,没有取得反馈者原始HDR媒体或日志。不能从SDR的BT.1886/sRGB错误推出HDR也有同样错误。
+
+本轮检查覆盖原生PQ/HLG的输入范围、YUV矩阵、线性工作单位、输出编码及真实交换链缓冲;同时检查NR基底恢复、NR+视频SR+DLSS FG,以及一个本地合成HDR视频的硬解输入。未修改HDR画面曲线,没有用对比度抵消未知原因。
+
+结论:测试范围内没有发现原生HDR链路的系统性亮度抬升或压暗。HDR转SDR存在固定映射和简单色域裁切的局限;这与已确认的SDR错误不同,尚不能认定为反馈者的根因。原生HDR和转SDR必须分开收集证据。
+
+## 当前实际链路
+
+1. PQ:有限/全范围展开→BT.2020 NCL YUV转RGB→ST2084 EOTF到绝对尼特→BT.2020转线性BT.709→除80,作为scRGB工作单位。
+2. HLG:范围/矩阵转换后,逆HLG OETF恢复场景光,再按1000尼特参考显示、gamma1.2的OOTF得到显示亮度。HLG参考峰值当前固定,不是读取实际显示器峰值。
+3. 无FG原生HDR:FP16 scRGB直接呈现,1代表80尼特,保留负色域分量和大于1的高光。
+4. FG原生HDR:工作色域转回BT.2020并编码PQ,使用RGB10/PQ交换链;参考画面也只在对应边界编码PQ。未发现重复sRGB编码。
+5. HDR转SDR:在线性BT.709域截掉负分量,以203尼特归一化,按固定1000尼特峰值做亮度肩部压缩,最后RGB通道裁切到0至1并编码sRGB。开启增强时先做此转换,再进入SDR增强。
+6. 原生HDR增强:NR/视频SR使用SDR代理供模型处理,把模型改动合成回保留的HDR基底;这不是模型原生HDR推理。零代理改动应保持原基底,测试覆盖了该不变量。
+
+Windows scRGB单位核对:[微软Advanced Color文档](https://learn.microsoft.com/en-us/windows/win32/direct3darticles/high-dynamic-range)。HLG/PQ定义核对:[ITU-R BT.2100](https://www.itu.int/rec/R-REC-BT.2100)。这些标准说明转换定义,不代替本产品测试。
+
+## 新增的独立GPU检查
+
+`tests/integration/HdrNativeRoundTripCases.h`,由 `veyra_hdr_color_tests` 执行:
+
+- PQ输入包含0、0.005、0.1、1、10、80、100、203、400、1000、4000、10000尼特中性块、BT.2020原色和混合颜色;HLG以对应场景信号生成,按BT.2100的参考显示解释。
+- limited/full、P010/平面10bit、scRGB/PQ输出共16种组合。HDR10格式通过关闭NGX而选择FG输出格式来独立验证,不能把这16种格式检查宣称为实际补帧验证。
+- 期望值从量化后的源YUV重新按双精度矩阵和标准公式计算;原生HDR要求还原源亮度,不以固定色调映射代码作预期。
+- 增加 `VideoPresenter::presentedResourceForTest()`,读回真正的HDR交换链缓冲,与图输出精确比较;只被集成测试调用,播放/导出不增加回读。返回引用必须在resize/close前释放。
+
+最终 `logs/hdr-native-hlg-audit-20260915.stdout.log` exit0:
+
+| 输入/输出 | >=1尼特通道最大相对误差 | 图输出→呈现缓冲 |
+| --- | --- | --- |
+| PQ→scRGB | 0.0868% | 完全一致 |
+| PQ→RGB10 PQ | 0.524% | 完全一致 |
+| HLG→scRGB | 0.0893% | 完全一致 |
+| HLG→RGB10 PQ | 0.648% | 完全一致 |
+
+scRGB近零颜色分量(包括高饱和颜色经矩阵抵消后的分量)最大绝对误差0.126尼特,不等于纯黑抬升。FP16/PQ10量化保留在结果里,不宣称数学无损。测试覆盖设备合成前的缓冲,未测量物理屏幕亮度或显示器色彩处理。
+
+## 增强及文件验证
+
+- `veyra_hdr_enhancement_tests.exe 1`:exit0,NR实际20帧,测试高光1003.75尼特;零代理改动、近黑/宽色域基底和JXR回验通过。`logs/hdr-audit-nr-20260915.stdout.log`。
+- `veyra_hdr_enhancement_tests.exe 3`:日志最终 `pass=1`,NR20/SR20/生成18,1000尼特测试高光998.932尼特。`logs/hdr-audit-sr-fg-20260915.stdout.log`。会话工具在用户打断后句柄失效,后续确认进程已退出并读取最终日志;不将无法取回的退出码补写为0。
+- `veyra_hdr_enhancement_tests.exe 1 0 out/hdr-audio-fixtures/pq-tagged-51.mp4 1`:90秒上限,exit0;真实FFmpeg D3D12硬解及NR20帧,高光1003.75尼特,`logs/hdr-audit-file-hardware-20260915.stdout.log`。该视频是项目本地合成fixture,不是反馈者电影。
+- `veyra_hdr_color_tests.exe` 同时完成此前SDR/采集/PQ/HLG色块回归;新用例最长90秒。
+
+中途失败:测试首次调用不存在的makeReadbackBuffer,编译失败后改为显式READBACK资源创建;首次给10000尼特FP16输出设固定0.1尼特中性误差限,超过格式能表达的精度而失败,改为按FP16精度判断相对偏差。原始失败 `logs/hdr-native-audit-20260915.stdout.log` 保留。正式阈值与测量值均在源码及日志列明。未删除失败结果制造通过。
+
+## 确认的局限及后续方案
+
+HDR→SDR无法与HDR屏幕输出保持绝对亮度恒等,必须明确选择色调/色域映射。现有固定映射并非由显示器或每个文件的实际峰值驱动。它对所有素材套用同一压缩,超过参考峰值的颜色可能裁切;把负BT.709分量先截掉也会改变宽色域饱和颜色的亮度和色相。没有实际问题素材时不能仅凭这一缺口宣布全部发灰已定位。
+
+后续若确认反馈走转SDR路径:
+
+1. 取得问题片段及实际输出路由,对照同一帧范围、色域、亮度和裁切比例。
+2. 将MaxCLL、母版峰值和缺失/异常值分别处理,不把母版显示器峰值等同于内容实际最大亮度,也不盲目让元数据控制画面。
+3. 明确目标SDR参考白和输出曲线,采用经过独立参考比对的亮度与色域映射;必要时增加稳定峰值估计,避免逐帧抽动。
+4. 原生HDR旁路必须继续通过本轮恒等检查。转SDR的验收用明确参考实现/已知目标灰阶与彩色映射,而不能仅复写shader公式。
+
+本轮新增诊断:文件首帧记录母版亮度、MaxCLL/MaxFALL及其frame/stream来源;缺失明确为-1。图记录实际PQ/HLG解码、工作单位、HDR/SDR输出和是否套用固定映射。只记录已取得信息,不把缺失值写成真实1000尼特。不修改当前映射策略、运行组件或系统HDR开关。
+
+待验收:反馈者真实文件/采集/PS5;跨显示器HDR状态变化;实际显示亮度;未标记或误标记HDR媒体。不能将本轮通过扩大成全部HDR发灰根治。
+
+## 本地交付
+
+最终全量目标构建 `cmd.exe /c out\build\veyra-build-x64-release.cmd` exit0,`logs/hdr-audit-product-build-20260915.log`(38/38)。`veyra.exe out/hdr-audio-fixtures/pq-tagged-51.mp4 --no-nr --no-sr --no-fg --smoke-seconds 3` 经30秒短测包装exit0,日志 `logs/hdr-audit-gui-20260915.log`。未重复上一轮完整delivery,原因是本轮产品改动只增加日志及测试专用读回接口,未改渲染行为;本轮相关GPU及GUI验证如上。
+
+本机这次GUI实际为 `hdrInput=true hdrOutput=false forceSdrPreview=false`,自动选择转SDR;30帧、failed=false、NR/NVOF均0。说明“打开HDR文件”并不自动代表“正在HDR输出”。这不是反馈发生时的状态证明,也不能单凭此判断Windows开关或显示器硬件原因。
+
+候选仍在 `out/build/audio-continuity-repair-20260915/veyra.exe`,SHA256 `1CAC34939919C19EEF1FF271857159E8786AD2EF1BA7FCA5CBD6EBE394DC6321`,入口 `out/start-user-issues-candidate.cmd`。源码/测试/文档本地提交,不包含SDK、日志、fixture或运行组件;未push、未发布。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index b5c995e7..0f714a80 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -2207,3 +2207,15 @@ WASAPI输入使用共享模式事件采集,按 `IAudioCaptureClient::GetBuffer
再执行 `powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/gates/delivery.ps1 -Root . -BuildDirectory out/build/audio-continuity-repair-20260915` exit0,结果 `logs/delivery/3c32cadc5f774f6eaae43efee5d02211/result.json`,真实NR/NVOF、4K导出等短测通过;不能替代问题设备实测。EXE SHA256 `EFA748C7F7D64DF3E9ECE814CE56D2015BC976192F00195443C2B0E17A8EDA96`,入口 `out/start-user-issues-candidate.cmd`。git diff --check通过;版本、runtime及发布状态不变。
下一步唯一用户验收:同原视频、关闭所有效果对照新候选。未核对其他播放器ICC/驱动视频增强/显示设置,不能宣称所有播放器屏幕像素绝对相同,也不能将本次SDR修复扩大为全部HDR发灰根治。该修复与此前14项候选一并作为当前独立分支的本地可回退记录,原基线6206b5a保留,不push、不发布。
+
+## 2026-09-15 HDR发灰端到端排查
+
+用户要求继续排查HDR,不知道反馈时实际是原生HDR还是转SDR。沿用 `8812e94` 在独立分支施工。新增 `HdrNativeRoundTripCases.h`,16组覆盖PQ/HLG、full/limited、平面10bit/P010、FP16 scRGB/RGB10 PQ,包含近黑、彩色、宽色域与最高10000尼特参考信号。通过 `VideoPresenter::presentedResourceForTest` 读取真实交换链缓冲作数值对照;该接口只供测试,无生产回读。PQ→scRGB最大相对误差0.0868%,PQ→RGB10 0.524%,HLG分别0.0893%/0.648%,图输出与呈现缓冲精确一致。证据 `logs/hdr-native-hlg-audit-20260915.stdout.log`,90秒上限exit0。
+
+增强短测:`veyra_hdr_enhancement_tests.exe 1` exit0、NR20帧、高光1003.75尼特;`... 3` 最终日志pass1、NR20/SR20/生成18、高光998.932尼特,用户中断后工具句柄消失,确认进程退出并读取最终日志,没有虚报无法回取的进程exit码。`... 1 0 out/hdr-audio-fixtures/pq-tagged-51.mp4 1` 90秒上限exit0、实际硬解文件及NR20帧。分别见 `logs/hdr-audit-nr-20260915.stdout.log`、`hdr-audit-sr-fg-20260915.stdout.log`、`hdr-audit-file-hardware-20260915.stdout.log`。NGX执行及基底身份、JXR、有限高光检查真实通过;本地fixture不是反馈者电影,不代表完整实际画质验收。
+
+确认HDR→SDR使用固定1000尼特/203参考白肩部和简单色域裁切,未依据内容峰值调整;这是已有策略的局限,不能直接判成全部HDR发灰根因。原生HDR没有复现SDR先前的BT.1886/sRGB曲线错误。本轮不调整HDR曲线或对比度。新增 `MediaFileSource` 首帧母版亮度/MaxCLL/MaxFALL来源日志,未知-1;`EnhanceGraph` 记录实际HDR输入、工作单位、输出和tone-map策略,不让通用SDR workingTransfer字段误导HDR诊断。
+
+初次新增测试引用不存在的makeReadbackBuffer构建失败后修正;固定0.1尼特中性容差在10000尼特FP16下超出格式精度,改按相对精度阈值,原失败日志保留。完整 `cmd.exe /c out\build\veyra-build-x64-release.cmd` exit0(38/38),日志 `logs/hdr-audit-product-build-20260915.log`。最终GUI无增强HDR文件3秒短测,30秒上限exit0,`logs/hdr-audit-gui-20260915.log`。仅诊断和测试接口变更,未重跑完整delivery;git diff --check通过。
+
+候选EXE SHA256 `1CAC34939919C19EEF1FF271857159E8786AD2EF1BA7FCA5CBD6EBE394DC6321`,原候选入口保持。完整结论及后续有证据再改映射的方案见 `docs/HDR_GRAY_CHAIN_AUDIT_2026-09-15.md`。下一条唯一任务:取得问题HDR片段和新日志,依据hdr-route区分原生HDR/转SDR,量化同帧变化再修映射,不凭主观发灰统一改gamma。未执行反馈者屏幕测光、实卡/PS5或未知HDR素材,未发布或变更运行组件。
diff --git a/include/veyra/engine/VideoPresenter.h b/include/veyra/engine/VideoPresenter.h
index 13e06878..6c02e90f 100644
--- a/include/veyra/engine/VideoPresenter.h
+++ b/include/veyra/engine/VideoPresenter.h
@@ -15,6 +15,9 @@ public:
void close();
// Explicit integration-test capture only; never called by playback/export.
bool readPresentedFrameForTest(gfx::D3D12DeviceContext&,gfx::CommandSlotRing&,sink::RgbaImage&);
+ // Test-only borrowed buffer reference for lossless HDR readback. Caller
+ // drains the queue and releases this before resize/close; no playback use.
+ Microsoft::WRL::ComPtr<ID3D12Resource> presentedResourceForTest() const;
uint64_t submittedCount() const {return sink_.presentCount();}
uint64_t xessGeneratedCount() const {return sink_.xess()?sink_.xess()->generatedCount():0;}
uint64_t xessPresentedCount() const {return sink_.xess()?sink_.xess()->presentedCount():0;}
diff --git a/src/engine/VideoPresenter.cpp b/src/engine/VideoPresenter.cpp
index 221f2e94..b3c7990a 100644
--- a/src/engine/VideoPresenter.cpp
+++ b/src/engine/VideoPresenter.cpp
@@ -102,4 +102,9 @@ bool VideoPresenter::readPresentedFrameForTest(gfx::D3D12DeviceContext& ctx,gfx:
return SUCCEEDED(sink_.swapChain()->GetBuffer(lastBuffer_,IID_PPV_ARGS(&buffer)))&&sink::readRgba8(ctx,ring,buffer.Get(),image);
}
void VideoPresenter::close(){hasPresented_=false;gpuTimer_.close();rtvs_.Reset();pass_={};sink_.shutdown();}
+Microsoft::WRL::ComPtr<ID3D12Resource> VideoPresenter::presentedResourceForTest() const {
+ Microsoft::WRL::ComPtr<ID3D12Resource> buffer;
+ if(hasPresented_&&sink_.swapChain())sink_.swapChain()->GetBuffer(lastBuffer_,IID_PPV_ARGS(&buffer));
+ return buffer;
+}
}
diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cpp
index f9bf8eed..34a2943e 100644
--- a/src/pipeline/EnhanceGraph.cpp
+++ b/src/pipeline/EnhanceGraph.cpp
@@ -714,6 +714,14 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
veyra::log::error("hdr","Unsupported PQ/HLG colorimetry: requires signaled/fallback BT2020 NCL and BT2020 primaries");return false;
}
if(reset||!realFrameIndex_)veyra::log::info("color",std::format("range={} assumed={} matrix={} assumed={} transfer={} assumed={} display709={} preserveSdrCodes={} workingTransfer={}",int(resolved.range),resolved.rangeAssumed,int(resolved.matrix),resolved.matrixAssumed,int(resolved.transfer),resolved.transferAssumed,resolved.displayReferred709,resolved.preserveSdrCodeValues,workingTransferCode(resolved)));
+ if(resolved.isHdrPath()&&(reset||!realFrameIndex_)){
+ veyra::log::info("hdr-route",std::format("input={} range={} matrix=BT2020-NCL primaries=BT2020 decode={} working={} output={} toneMap={} hdrReferenceWhiteNits=203 hlgReferencePeakNits=1000; SDR workingTransfer field is unused for PQ/HLG",
+ resolved.transfer==TransferFunction::HLG?"HLG":"PQ",resolved.range==ColorRange::Full?"full":"limited",
+ resolved.transfer==TransferFunction::HLG?"inverse-OETF+OOTF-gamma1.2":"ST2084-EOTF-absolute-nits",
+ desc_.hdrOutput?"linear-BT709-scRGB-1=80nits":"linear-BT709-SDR-relative",
+ hdr10Output()?"PQ-BT2020-RGB10":desc_.hdrOutput?"scRGB-FP16":"sRGB-RGB8",
+ desc_.hdrOutput?"none":"fixed-luminance-shoulder-1000nits+RGB-gamut-clip"));
+ }
if (resolved.isHdrPath()&&(!desc_.hdrInput||desc_.rgbInput||desc_.yuy2Input)) {
veyra::log::error("graph", "HDR input requires an explicit YUV HDR contract; RGB/YUY2 HDR ingress is unsupported"); return false;
}
diff --git a/src/source/MediaFileSource.cpp b/src/source/MediaFileSource.cpp
index fbcdd721..70d1f6f2 100644
--- a/src/source/MediaFileSource.cpp
+++ b/src/source/MediaFileSource.cpp
@@ -13,6 +13,7 @@ extern "C" {
#include <libavcodec/avcodec.h>
#include <libavutil/pixdesc.h>
#include <libavutil/dovi_meta.h>
+#include <libavutil/mastering_display_metadata.h>
}
namespace veyra::source {
@@ -322,6 +323,23 @@ SourceReadStatus MediaFileSource::read(pipeline::FramePacket& out, const AVFrame
info_.videoCodecName, info_.videoPixelFormatName, decoder_.hardwareActive(), out.colorInfo.isHdrPath(),
static_cast<int>(out.colorInfo.matrix), static_cast<int>(out.colorInfo.transfer),
static_cast<int>(out.colorInfo.range), static_cast<int>(out.colorInfo.chromaLocation)));
+ if(out.colorInfo.isHdrPath()){
+ const auto* parameters=demuxer_.videoCodecParameters();
+ auto side=[&](AVFrameSideDataType frameType,AVPacketSideDataType packetType,size_t minimum,const char*& origin)->const uint8_t*{
+ if(const auto* data=av_frame_get_side_data(frame,frameType);data&&data->size>=minimum){origin="frame";return data->data;}
+ if(parameters)if(const auto* data=av_packet_side_data_get(parameters->coded_side_data,parameters->nb_coded_side_data,packetType);data&&data->size>=minimum){origin="stream";return data->data;}
+ origin="unavailable";return nullptr;
+ };
+ const char *masteringOrigin=nullptr,*contentOrigin=nullptr;double minNits=-1,maxNits=-1;int64_t maxCll=-1,maxFall=-1;
+ if(const auto* data=side(AV_FRAME_DATA_MASTERING_DISPLAY_METADATA,AV_PKT_DATA_MASTERING_DISPLAY_METADATA,sizeof(AVMasteringDisplayMetadata),masteringOrigin)){
+ const auto& value=*reinterpret_cast<const AVMasteringDisplayMetadata*>(data);
+ if(value.has_luminance&&value.min_luminance.den>0&&value.max_luminance.den>0){minNits=av_q2d(value.min_luminance);maxNits=av_q2d(value.max_luminance);}
+ }
+ if(const auto* data=side(AV_FRAME_DATA_CONTENT_LIGHT_LEVEL,AV_PKT_DATA_CONTENT_LIGHT_LEVEL,sizeof(AVContentLightMetadata),contentOrigin)){
+ const auto& value=*reinterpret_cast<const AVContentLightMetadata*>(data);maxCll=value.MaxCLL;maxFall=value.MaxFALL;
+ }
+ log::info("hdr-metadata",std::format("masteringSource={} masteringMinNits={} masteringMaxNits={} contentSource={} maxCLL={} maxFALL={} (-1=unavailable; 0 content level=unspecified); diagnostic only, not applied to fixed SDR tone map",masteringOrigin,minNits,maxNits,contentOrigin,maxCll,maxFall));
+ }
}
out.sourceEpoch = epoch_;
diff --git a/tests/integration/HdrColorTests.cpp b/tests/integration/HdrColorTests.cpp
index b054906e..ac06fdef 100644
--- a/tests/integration/HdrColorTests.cpp
+++ b/tests/integration/HdrColorTests.cpp
@@ -9,6 +9,7 @@
#include "veyra/RuntimePaths.h"
#include "CaptureFormatGpuCases.h"
#include "SdrColorGpuCases.h"
+#include "HdrNativeRoundTripCases.h"
#include <iostream>
#include <cmath>
extern "C" {
@@ -19,7 +20,7 @@ int wmain(int argc,wchar_t** argv){
CoInitializeEx(nullptr,COINIT_MULTITHREADED);
gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;Status st;gfx::DeviceContextDesc dd;
if(!ctx.initialize(dd,st)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),4,st))return 2;
- int failures=captureGpuCases(ctx,ring)+sdrColorGpuCases(ctx,ring);
+ int failures=captureGpuCases(ctx,ring)+sdrColorGpuCases(ctx,ring)+hdrRoundTrip::run(ctx,ring);
for(bool hlg:{false,true})for(bool native:{false,true})for(bool planar:{false,true})for(bool full:{false,true}){
pipeline::EnhanceGraph graph(ctx,ring);pipeline::EnhanceGraphDesc gd;
gd.sourceWidth=gd.workWidth=64;gd.sourceHeight=gd.workHeight=32;gd.enableNr=gd.enableFg=gd.enableSr=false;gd.noFeatures=true;gd.hdrInput=true;gd.hdrOutput=native;
diff --git a/tests/integration/HdrNativeRoundTripCases.h b/tests/integration/HdrNativeRoundTripCases.h
new file mode 100644
index 00000000..910a193c
--- /dev/null
+++ b/tests/integration/HdrNativeRoundTripCases.h
@@ -0,0 +1,75 @@
+#pragma once
+#include <array>
+#include <algorithm>
+#include <cmath>
+#include <cstring>
+
+namespace hdrRoundTrip {
+inline double pq(double nits){const double p=std::pow(std::max(nits,0.0)/10000,2610.0/16384);return std::pow((3424.0/4096+2413.0/128*p)/(1+2392.0/128*p),2523.0/32);}
+inline double nits(double code){const double p=std::pow(std::clamp(code,0.0,1.0),32.0/2523);return 10000*std::pow(std::max(p-3424.0/4096,0.0)/(2413.0/128-2392.0/128*p),16384.0/2610);}
+inline double hlgEncode(double scene){return scene<=1.0/12?std::sqrt(3*scene):.17883277*std::log(12*scene-.28466892)+.55991073;}
+inline double hlgDecode(double code){code=std::clamp(code,0.0,1.0);return code<=.5?code*code/3:(std::exp((code-.55991073)/.17883277)+.28466892)/12;}
+inline bool read(veyra::gfx::D3D12DeviceContext& ctx,veyra::gfx::CommandSlotRing& ring,ID3D12Resource* tex,std::vector<float>& rgb){
+ using namespace veyra;if(!tex)return false;auto d=tex->GetDesc();
+ if(d.Format!=DXGI_FORMAT_R16G16B16A16_FLOAT&&d.Format!=DXGI_FORMAT_R10G10B10A2_UNORM)return false;
+ D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp{};UINT64 bytes;ctx.device()->GetCopyableFootprints(&d,0,1,0,&fp,nullptr,nullptr,&bytes);
+ D3D12_HEAP_PROPERTIES hp{};hp.Type=D3D12_HEAP_TYPE_READBACK;D3D12_RESOURCE_DESC bd{};bd.Dimension=D3D12_RESOURCE_DIMENSION_BUFFER;bd.Width=bytes;bd.Height=1;bd.DepthOrArraySize=bd.MipLevels=1;bd.SampleDesc.Count=1;bd.Layout=D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
+ Microsoft::WRL::ComPtr<ID3D12Resource> buffer;
+ if(FAILED(ctx.device()->CreateCommittedResource(&hp,D3D12_HEAP_FLAG_NONE,&bd,D3D12_RESOURCE_STATE_COPY_DEST,nullptr,IID_PPV_ARGS(&buffer))))return false;
+ if(!buffer)return false;Status st;unsigned slot;auto* list=ring.acquireNext(slot,st);if(!list)return false;
+ D3D12_RESOURCE_BARRIER b{};b.Type=D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;b.Transition={tex,D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,D3D12_RESOURCE_STATE_COMMON,D3D12_RESOURCE_STATE_COPY_SOURCE};list->ResourceBarrier(1,&b);
+ D3D12_TEXTURE_COPY_LOCATION from{},to{};from.pResource=tex;from.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;to.pResource=buffer.Get();to.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;to.PlacedFootprint=fp;list->CopyTextureRegion(&to,0,0,0,&from,nullptr);std::swap(b.Transition.StateBefore,b.Transition.StateAfter);list->ResourceBarrier(1,&b);
+ if(!ring.submitAndSignal(slot)||!ring.waitIdle())return false;void* data;D3D12_RANGE range{0,size_t(bytes)};if(FAILED(buffer->Map(0,&range,&data)))return false;
+ rgb.resize(size_t(d.Width)*d.Height*3);
+ for(unsigned y=0;y<d.Height;++y)for(unsigned x=0;x<d.Width;++x)for(unsigned c=0;c<3;++c){auto* row=static_cast<uint8_t*>(data)+fp.Offset+y*fp.Footprint.RowPitch;
+ rgb[(size_t(y)*d.Width+x)*3+c]=d.Format==DXGI_FORMAT_R16G16B16A16_FLOAT?DirectX::PackedVector::XMConvertHalfToFloat(reinterpret_cast<uint16_t*>(row)[x*4+c]):float((reinterpret_cast<uint32_t*>(row)[x]>>(10*c))&1023)/1023;
+ }
+ D3D12_RANGE none{};buffer->Unmap(0,&none);return true;
+}
+inline int run(veyra::gfx::D3D12DeviceContext& ctx,veyra::gfx::CommandSlotRing& ring){
+ using namespace veyra;int failures=0;
+ constexpr std::array<std::array<double,3>,16> patches={{{0,0,0},{.005,.005,.005},{.1,.1,.1},{1,1,1},{10,10,10},{80,80,80},{100,100,100},{203,203,203},{400,400,400},{1000,1000,1000},{4000,4000,4000},{10000,10000,10000},{1000,0,0},{0,1000,0},{0,0,1000},{400,100,20}}};
+ for(bool hlg:{false,true})for(bool packed:{false,true})for(bool planar:{false,true})for(bool full:{false,true}){
+ AVFrame* f=av_frame_alloc();f->width=64;f->height=16;f->format=planar?AV_PIX_FMT_YUV420P10LE:AV_PIX_FMT_P010;
+ f->color_range=full?AVCOL_RANGE_JPEG:AVCOL_RANGE_MPEG;f->colorspace=AVCOL_SPC_BT2020_NCL;f->color_primaries=AVCOL_PRI_BT2020;f->color_trc=hlg?AVCOL_TRC_ARIB_STD_B67:AVCOL_TRC_SMPTE2084;
+ if(av_frame_get_buffer(f,32)<0){av_frame_free(&f);return failures+1;}
+ std::array<std::array<double,3>,16> expected{};
+ for(unsigned i=0;i<patches.size();++i){
+ const auto encode=[&](double n){return hlg?hlgEncode(n/10000):pq(n);};
+ const double r=encode(patches[i][0]),g=encode(patches[i][1]),b=encode(patches[i][2]);const double y=.2627*r+.678*g+.0593*b;
+ const int yy=int(std::lround((full?0:64)+(full?1023:876)*y)),u=int(std::lround(512+(full?1023:896)*(b-y)/1.8814)),v=int(std::lround(512+(full?1023:896)*(r-y)/1.4746));
+ for(unsigned row=0;row<16;++row)for(unsigned x=i*4;x<i*4+4;++x){reinterpret_cast<uint16_t*>(f->data[0]+row*f->linesize[0])[x]=uint16_t(planar?yy:yy<<6);
+ if(!(row%2)&&!(x%2)){auto* uv=reinterpret_cast<uint16_t*>(f->data[1]+row/2*f->linesize[1]);if(planar){uv[x/2]=uint16_t(u);reinterpret_cast<uint16_t*>(f->data[2]+row/2*f->linesize[2])[x/2]=uint16_t(v);}else{uv[x]=uint16_t(u<<6);uv[x+1]=uint16_t(v<<6);}}
+ }
+ const double l=(yy-(full?0.0:64.0))/(full?1023:876),cb=(u-512.0)/(full?1023:896),cr=(v-512.0)/(full?1023:896);
+ const std::array<double,3> signal={l+1.4746*cr,l-.1645531268436578*cb-.5713531268436578*cr,l+1.8814*cb};
+ if(hlg){
+ const double r=hlgDecode(signal[0]),g=hlgDecode(signal[1]),b=hlgDecode(signal[2]);
+ const double gain=1000*std::pow(.2627*r+.678*g+.0593*b,.2);
+ expected[i]={r*gain,g*gain,b*gain};
+ }else expected[i]={nits(signal[0]),nits(signal[1]),nits(signal[2])};
+ }
+ pipeline::EnhanceGraph graph(ctx,ring);pipeline::EnhanceGraphDesc gd;gd.sourceWidth=gd.workWidth=64;gd.sourceHeight=gd.workHeight=16;
+ gd.hdrInput=gd.hdrOutput=true;gd.noFeatures=gd.noNgx=true;gd.enableNr=gd.enableSr=false;gd.enableFg=packed;
+ pipeline::EnhanceGraph::FrameOutputs out;std::vector<float> output;
+ bool ok=graph.initialize(gd)&&graph.createViews()&&graph.process(f,0,true,out,1)&&read(ctx,ring,graph.videoFrameResource(out.videoSlot),output);
+ double relative=0,nearBlack=0,neutralSpread=0,neutralRelative=0;
+ if(ok)for(unsigned i=0;i<patches.size();++i){const auto* p=output.data()+(i*4+2)*3;std::array<double,3> actual;
+ if(packed)actual={nits(p[0]),nits(p[1]),nits(p[2])};
+ else actual={80*(.627404*p[0]+.329283*p[1]+.043313*p[2]),80*(.069097*p[0]+.919540*p[1]+.011362*p[2]),80*(.016391*p[0]+.088013*p[1]+.895595*p[2])};
+ for(unsigned c=0;c<3;++c){const double e=std::abs(actual[c]-expected[i][c]);if(expected[i][c]>=1)relative=std::max(relative,e/expected[i][c]);else nearBlack=std::max(nearBlack,e);}
+ if(i<12){const double spread=*std::max_element(actual.begin(),actual.end())-*std::min_element(actual.begin(),actual.end());neutralSpread=std::max(neutralSpread,spread);neutralRelative=std::max(neutralRelative,spread/std::max(1.0,expected[i][0]));}
+ }
+ // FP16 has ~0.1% relative precision: a fixed 0.1-nit allowance at
+ // 10000 nits would demand more precision than the working format.
+ ok=ok&&relative<(packed?.012:.003)&&nearBlack<.15&&neutralRelative<.0011;
+ HWND window=CreateWindowExW(0,L"STATIC",L"HDR native round trip",WS_POPUP,0,0,64,16,nullptr,nullptr,GetModuleHandleW(nullptr),nullptr);engine::VideoPresenter presenter;std::vector<float> presented;
+ bool presentOk=window&&presenter.open(ctx,window,graph)&&presenter.present(ctx,ring,graph,out.videoSlot,false);
+ auto buffer=presenter.presentedResourceForTest();presentOk=presentOk&&read(ctx,ring,buffer.Get(),presented)&&presented==output;
+ buffer.Reset();ring.drainQueue();presenter.close();if(window)DestroyWindow(window);
+ std::cout<<"HDR_NATIVE_ROUNDTRIP hlg="<<hlg<<" pqOutput="<<packed<<" planar="<<planar<<" full="<<full<<" relativeError="<<relative<<" nearBlackNits="<<nearBlack<<" neutralSpreadNits="<<neutralSpread<<" neutralRelative="<<neutralRelative<<" presentExact="<<presentOk<<" pass="<<(ok&&presentOk)<<std::endl;
+ failures+=!(ok&&presentOk);out={};ring.drainQueue();graph.shutdown();av_frame_free(&f);
+ }
+ return failures;
+}
+}