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

Fix live MFG subframe readiness and HDR to SDR mapping

Veyra Goal Agent14b6ee0fb5c1
diff --git a/apps/veyra/ui/AppShell.cpp b/apps/veyra/ui/AppShell.cpp
index aca88d49..b3127b36 100644
--- a/apps/veyra/ui/AppShell.cpp
+++ b/apps/veyra/ui/AppShell.cpp
@@ -449,7 +449,7 @@ if(smokeStep==4&&elapsed>5200&&GetEnvironmentVariableW(L"VEYRA_TEST_LARGE_IMAGE_
}auto s=engine.snapshot();const auto subtitleText=uiState.subtitles&&!(showDiagnostics&&uiState.mode==veyra::ui::Mode::Professional&&!full)?veyra::engine::subtitleAt(subtitles,s.position):L"";veyra::ui::updateSubtitleOverlay(subtitleLabel,subtitleText,subtitlePixels);
const double submittedFps=s.submissionFps.value_or(0.0);
const bool xessRate=s.applied.frameGenerationBackend==veyra::engine::FrameGenerationBackend::XeSS&&s.applied.multiplier>1;
-veyra::ui::setText(GetDlgItem(hwnd,FpsLabel),s.running&&!s.image&&s.transport==veyra::engine::TransportState::Playing&&!s.metrics.flow.rateWindowReady?std::wstring(L"帧率采样中"):std::format(L"{} {:.1f} fps",xessRate?L"SDK提交":L"处理产出",xessRate?s.metrics.flow.xessSdkSubmitFps:s.metrics.flow.outputCompletedFps));
+veyra::ui::setText(GetDlgItem(hwnd,FpsLabel),s.running&&!s.image&&s.transport==veyra::engine::TransportState::Playing&&!s.metrics.flow.rateWindowReady?std::wstring(L"帧率采样中"):std::format(L"{} {:.1f} fps",xessRate?L"SDK提交":L"显示提交",xessRate?s.metrics.flow.xessSdkSubmitFps:s.metrics.flow.presentSubmitFps));
auto text=s.remotePlay?std::format(L"{}\r\nPS5 接收 {:.1f} / 解码 {:.1f} / 处理 {:.1f} fps | 解码后跳过 {} | 入队丢弃 {}",s.status,s.remoteReceivedFps,s.remoteDecodedFps,s.fps,s.remotePlaySkipped,s.remoteIngressDropped):s.capture?std::format(L"{}\r\n输入 {:.1f} / 已处理 {:.1f} / 显示提交 {:.1f}fps | 回调至Present返回p95 {:.1f}ms(非总延迟)| 丢弃 {} | 有效生成 {}",s.status,s.captureFps,s.fps,submittedFps,s.captureAgeP95Ms,s.captureDropped,s.generated):std::format(L"{}\r\n{:.1f} / {:.1f}秒 已处理 {:.1f}fps 提交迟到 {:+.1f}ms 源帧 {} / 有效生成 {}",s.status,s.position,s.duration,s.fps,s.lateMs,s.frames,s.generated);
if(smokeZoom&&startTick&&s.frames>0){const auto elapsed=GetTickCount64()-startTick;
if(zoomStep==0&&elapsed>1300){if(uiState.mode==veyra::ui::Mode::Daily)switchMode();zoomBefore=s;RECT r{};GetWindowRect(video,&r);const LPARAM point=MAKELPARAM(r.left+(r.right-r.left)*7/10,r.top+(r.bottom-r.top)/2);if(smokeHover){SetFocus(GetDlgItem(hwnd,ModeSwitch));PostMessageW(hwnd,WM_MOUSEWHEEL,MAKEWPARAM(0,WHEEL_DELTA*3),point);hoverPostedTick=GetTickCount64();zoomStep=4;}else{SendMessageW(video,WM_MOUSEWHEEL,MAKEWPARAM(0,WHEEL_DELTA*3),point);zoomStep=std::abs(engine.previewView().zoom-1.728f)<.001f?1:-1;}}
diff --git a/apps/veyra/ui/LiveStatusPanel.h b/apps/veyra/ui/LiveStatusPanel.h
index c0948ac5..f19ab47d 100644
--- a/apps/veyra/ui/LiveStatusPanel.h
+++ b/apps/veyra/ui/LiveStatusPanel.h
@@ -40,7 +40,8 @@ inline LRESULT CALLBACK proc(HWND h,UINT message,WPARAM wp,LPARAM lp){
rows.emplace_back(L"处理范围",xess?L"不含XeSS内部FG":L"不含输入颜色、输出、声音和呈现等待");
rows.emplace_back(L"平均范围",L"总计按源帧;单项按执行次数");
rows.emplace_back(L"光流范围",L"含光流GPU依赖等待");
- rows.emplace_back(L"实际呈现",fps(xess?f.xessSdkSubmitFps:f.presentSubmitFps));
+ rows.emplace_back(xess?L"SDK提交(非屏幕实测)":L"显示提交(非屏幕实测)",fps(xess?f.xessSdkSubmitFps:f.presentSubmitFps));
+ if(!xess)rows.emplace_back(L"原帧 / 生成帧提交",std::format(L"{:.1f} / {:.1f} fps",f.realPresentFps,f.generatedPresentFps));
rows.emplace_back(L"请求目标(非实测)",s.nominalSourceFps>0?std::format(L"{:.1f} fps",s.nominalSourceFps*(s.captureHalfRate?.5:1)*s.applied.multiplier):L"未确定");
std::wstring progress=!playing?s.status:s.applying?L"正在应用设置":s.fgBudgetLimited?L"部分补帧未达截止时间":L"播放中";
if(playing&&!s.applying&&s.remotePlay){
@@ -103,7 +104,7 @@ inline LRESULT CALLBACK proc(HWND h,UINT message,WPARAM wp,LPARAM lp){
rows.emplace_back(L"原帧软件驻留 · 平均",playing?ms(f.softwareLatencyMs):L"未测");
rows.emplace_back(L"原帧软件驻留 · P95",playing?ms(f.softwareLatencyP95Ms):L"未测");
rows.emplace_back(L"估计基线",L"理想直接播放 · 非双路实测");
- rows.emplace_back(L"GPU完成产出",fps(f.outputCompletedFps));
+ rows.emplace_back(L"GPU完成产出(含过期)",fps(f.outputCompletedFps));
rows.emplace_back(L"源帧处理完成",fps(f.sourceCompletedFps));
rows.emplace_back(L"有效生成(含过期)",xess?L"SDK内部不可测":fps(f.validGeneratedFps));
rows.emplace_back(L"采集覆盖 / 补帧过期",std::format(L"{} / {}",f.counters.mailboxOverwritten,f.counters.generatedExpiredAfterEval));
diff --git a/cmake/VeyraShaders.cmake b/cmake/VeyraShaders.cmake
index ad2ef091..1d1708e5 100644
--- a/cmake/VeyraShaders.cmake
+++ b/cmake/VeyraShaders.cmake
@@ -34,11 +34,11 @@ function(veyra_add_compute_shader target_name shader_name)
OUTPUT "${output}"
COMMAND "${DXC_EXE}" -T cs_6_0 -E main ${config_flags}
-Fo "${output}" "${source}"
- DEPENDS "${source}" "${CMAKE_CURRENT_SOURCE_DIR}/shaders/HdrColor.hlsli"
+ DEPENDS "${source}" "${CMAKE_CURRENT_SOURCE_DIR}/shaders/HdrColor.hlsli" "${CMAKE_CURRENT_SOURCE_DIR}/shaders/HdrToSdr.hlsli"
COMMENT "dxc ${shader_name}.hlsl (${CMAKE_BUILD_TYPE})"
VERBATIM)
add_custom_target(${target_name} DEPENDS "${output}")
- set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${source}" "${CMAKE_CURRENT_SOURCE_DIR}/shaders/HdrColor.hlsli")
+ set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${source}" "${CMAKE_CURRENT_SOURCE_DIR}/shaders/HdrColor.hlsli" "${CMAKE_CURRENT_SOURCE_DIR}/shaders/HdrToSdr.hlsli")
endfunction()
# Compiles a vertex+pixel shader pair (entry vsMain/psMain) into two DXIL
diff --git a/docs/FG_OUTPUT_RATE_AUDIT_2026-09-15.md b/docs/FG_OUTPUT_RATE_AUDIT_2026-09-15.md
new file mode 100644
index 00000000..e59427d5
--- /dev/null
+++ b/docs/FG_OUTPUT_RATE_AUDIT_2026-09-15.md
@@ -0,0 +1,51 @@
+# 补帧受限与180fps显示矛盾排查
+
+用户报告补帧受限但右侧显示180fps。本轮优先排查该反馈,保留未提交的HDR转SDR修复,不发布。
+
+## 确认的事实
+
+原始日志 `logs/veyra-app.log`,2026-09-15T10:56:57Z至10:57:04Z(本地18:56至18:57),session=3 / revision=556,实际DLSS采集链路:源帧处理约60fps,有效生成120fps;同期Present提交141、148、160、163、165、170fps。关闭时累计有效生成2780,生成帧提交2420,生成后过期360,约12.95%。这不是“完全没补帧”,也不能把180当实际屏幕帧率。
+
+UI `AppShell.cpp` 右侧原先读取 outputCompletedFps,即GPU完成原帧与有效生成帧合计,包含稍后过期的帧。DashboardHistory却读取presentSubmitFps(XeSS读取SDK报告提交),连续8次250ms采样低于目标95%显示受限、连续8次恢复后消除。不同口径加上状态滞后,能产生用户所见的矛盾。
+
+`EngineController.cpp` 的实时呈现路径在完成整批生成后,对每个生成帧检查 `timeline.expired(pts, now, 100000)`,即晚于时间线10ms则丢弃。60fps的3X每5.56ms有一个输出机会;稳定的平均产出不保证各张帧及时就绪。日志已证明过期丢弃,但没有逐帧GPU就绪、调度唤醒和各子帧过期时差,无法进一步断言是显卡算力、整批等待还是调度竞争独占责任。
+
+本机此前同时运行过另一轮GPU测试,可能影响其中一段性能;不能未经对照将整个用户问题归因于并行测试。也不能用放宽10ms丢弃阈值、堆积队列或只改状态颜色冒充修复。
+
+## 本轮改动
+
+- 右侧改成“显示提交”,读取与状态判定相同的presentSubmitFps;XeSS继续明确SDK提交,非物理扫描实测。
+- 详细面板明确“显示提交(非屏幕实测)”,增加全部来源的原帧/生成帧提交速率;GPU产出明确标注含过期。
+- 不修改补帧算法、倍率、过期阈值、音频或真实计数。
+
+## 下一步
+
+180fps口径错误已改。采集3X过期问题仍需同一设置下独立复现,增加限频记录的子帧就绪/截止/过期时差,再决定调整逐子帧就绪调度或实际预算。不能称为已根治补帧受限。
+
+## 本次验证
+
+`cmd.exe /c out\build\veyra-build-x64-release.cmd` exit0,日志 `logs/fg-rate-display-build-20260915.log`。`powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/gates/delivery.ps1 -Root . -BuildDirectory out/build/audio-continuity-repair-20260915` exit0,结果 `logs/delivery/6bade0b84d8449d89198cffa37453a2d/result.json`。这次未同时运行用户采集,NR/NVOF/4K、播放控制、图片、视频导出与取消回归通过;不代表采集3X已验收。`git diff --check` exit0(仅CRLF提示)。
+
+标准候选 `out/build/audio-continuity-repair-20260915/veyra.exe` 当前SHA256 `02BBC51FF46A8DEBCCA9961BEC48500E2AA77FE62B238174172D4E238ACA6401`,入口 `out/start-user-issues-candidate.cmd`。包含保留的HDR映射改动;未发布、未上传运行组件。
+
+## 后续实卡定位与逐帧修复
+
+用户明确要求继续修复。先只增加限频fg-deadline记录,每批各lease栅栏首次CPU观测时间、子帧截止时间、决定时间和整批就绪状态;每秒至多一条,不做像素回读,也不称为精确GPU执行终点或屏幕时刻。
+
+同一物理采集 `capture:0:0:0 --nr --video-sr 2 --fg-multiplier 3 --smoke-seconds 32`,对应1080p60采集、4K输出、1080p NR、SR质量2、3X DLSS。每次用 `scripts/run-short-test.ps1` 限制55秒,单独执行,无并行GPU任务。
+
+修前日志 `logs/fg-deadline-baseline-capture-20260915.log`,exit0但复现掉帧:有效生成3480、实际生成帧提交3060、过期420;末段170fps。batch442第一张生成帧在截止后8.546ms已经观测到就绪,实际决定却在10.588ms,等待2.043ms后超过既有10ms容差而丢弃。
+
+根因:`EnhanceGraph::resolveGeneration` / 播放CompletionWatch以整批全部fence为屏障。MFG各子帧已有独立lease和readyFence,但实时呈现被最后一张生成帧阻挡,导致先完成的帧跨过自己的截止线。这是可复现的软件调度缺陷,不等于显卡完全没有性能限制。
+
+修复:新增共享 `EnhanceGraph::resolveFrame`,仅在对应lease栅栏完成后读取其4字节SDK有效性状态,Pending转Valid/Disabled只执行一次;实时采集/串流呈现逐张检查、依PTS顺序输出。原完整resolveGeneration复用该函数,文件/导出仍等整批完成并精确统计。保留2批容量、资源lease和consumer fence、原时间线与10ms过期阈值;不延后源锚点、不增加播放缓冲、不复制/混合帧冒充生成。
+
+修后日志 `logs/fg-progressive-capture-20260915.log`,同样32秒exit0:有效生成3478、生成帧提交3478、过期0,稳定段180fps。batch1226第一张生成帧readyObservedLate=7.851ms、decisionLate=7.854ms、batchReady=false,直接证明不再等第二张完成才处理第一张。这里的180是显示提交而非显示器扫描实测;不承诺任意效果、显卡或4X都能满帧。
+
+构建 `logs/fg-deadline-baseline-build-20260915.log` 与 `logs/fg-progressive-build-20260915.log` 均exit0。初次用WindowsPowerShell -File跨进程传数组时--nr被误当脚本参数,未启动应用;改为当前PowerShell用 `& scripts/run-short-test.ps1 -Arguments @(...)` 后正常测试,不将参数错误当产品失败。
+
+`veyra_presentation_worker_tests.exe`、`veyra_live_timing_tests.exe` exit0,日志 `logs/fg-progressive-worker-tests-20260915.log`、`logs/fg-progressive-timing-tests-20260915.log`。最终delivery exit0,结果 `logs/delivery/90feb52b7ed84cf19d92d64596d79f10/result.json`;实际NR/NVOF、4K、GUI播放/暂停seek、图片、H.264/HEVC导出与取消回归通过。采集3X长测已通过,但实机用户验收仍需保留。
+
+120秒实卡日志 `logs/fg-progressive-capture-long-20260915.log`:源帧7062、有效生成14050、生成帧提交14050、生成后过期0,末段显示提交180fps;启动及预算恢复期间另有68个候选未执行,不计作有效生成。NR CreateFeature18返回0x1 Success、NVOF CreateInstanceD3D12状态0。上述两个单元测试是既有调度/时序回归,本轮新增逐帧行为由实卡日志验证,未宣称新增独立单元覆盖。
+
+没有增加缓冲或修改延迟目标,不等于已经证明实测延迟下降:原帧回调至Present返回P95在修前32秒为44.606ms、修后32秒为50.328ms、120秒为50.837ms,包含启动与更多实际呈现工作。本轮通过证据是消除已复现的整批等待过期,不承诺屏幕延迟降低、完美帧间距或所有设备满帧。GPU队列中的后续工作仍可能影响物理输出;软件提交时间不能替代扫描实测。
diff --git a/docs/HDR_GRAY_CHAIN_AUDIT_2026-09-15.md b/docs/HDR_GRAY_CHAIN_AUDIT_2026-09-15.md
index f6c2a4a6..c6e62371 100644
--- a/docs/HDR_GRAY_CHAIN_AUDIT_2026-09-15.md
+++ b/docs/HDR_GRAY_CHAIN_AUDIT_2026-09-15.md
@@ -1,5 +1,7 @@
# HDR 发灰链路复核
+后续施工:用户已授权替换HDR→SDR映射,当前实现、专项结果和待完成整包验收见 [HDR→SDR修复记录](HDR_TO_SDR_MAPPING_REPAIR_2026-09-15.md)。以下是此前审计,保留追溯,不代表新映射尚未施工。
+
## 本轮结论与范围
用户要求检查此前HDR发灰是否也是错误曲线,反馈时实际输出模式未知,没有取得反馈者原始HDR媒体或日志。不能从SDR的BT.1886/sRGB错误推出HDR也有同样错误。
diff --git a/docs/HDR_TO_SDR_MAPPING_REPAIR_2026-09-15.md b/docs/HDR_TO_SDR_MAPPING_REPAIR_2026-09-15.md
new file mode 100644
index 00000000..4f7a9890
--- /dev/null
+++ b/docs/HDR_TO_SDR_MAPPING_REPAIR_2026-09-15.md
@@ -0,0 +1,58 @@
+# HDR→SDR 色调与色域映射修复
+
+前置提交 aa40381;沿用 codex/user-issues-repair-20260915 本地修复分支。用户授权接着修 HDR→SDR,不发布、不变更系统 HDR。原生 HDR、SDR代码值保留、NR HDR代理/基底还原合同保持。
+
+## 证据与设计
+
+旧 YuvToLinearRgb:所有输入用1000尼特峰值的肩部;先把转换为BT.709后的负分量截断,再按亮度压缩并逐通道saturate。这会改变宽色域颜色的原始亮度和色相。此前原生PQ/HLG数值往返已通过,不能把转SDR问题扩大成所有HDR路径错误。
+
+采用公开BT.2390 EETF的PQ域Hermite肩部,目标理想黑0、SDR峰值203尼特;输出为相对于目标峰值的linear709,经已有输出只编码一次sRGB。源峰值与目标峰值相同则不压缩;不把较暗素材拉到全白。203是软件的明确映射参考,不是测得用户显示器亮度,也不是保证HDR漫反射白映射到SDR满白。
+
+峰值优先有效MaxCLL(0视未知,MaxFALL不能大于MaxCLL);其次有效母版显示峰值(仅标作fallback,不能称内容实测);再用显式1000尼特假设。范围外/NaN拒绝,低于203的有效峰值按203处理防止放大。HLG保持已有1000尼特参考OOTF,不用PQ静态标签更改HLG显示定义。每个图首次HDR帧锁定峰值,不跟随逐帧亮度;动态峰值扫描和动态元数据不在本轮。
+
+色域映射保留有符号linear709分量,用同一色度倍率向同亮度灰轴压缩;在目标色域边界90%处开始连续肩部,内部颜色不动。不独立裁RGB三通道,保留线性RGB色度方向和映射后的Y。这里的色相方向是线性RGB几何定义,不宣称感知空间的完美等色相。
+
+参考:ITU-R BT.2390-3 §5 的PQ归一化、knee和Hermite公式,https://www.itu.int/dms_pub/itu-r/opb/rep/R-REP-BT.2390-3-2017-PDF-E.pdf 。BT.2390-6 PDF读取超时,未冒充读过;没有复制第三方项目源码。
+
+## 实现清单
+
+- FramePacket/ColorMetadata/MediaFileSource:传递并读取帧/流静态亮度元数据,记录来源;HdrToneMap.h单独决定有效峰值及fallback。
+- EnhanceGraph:每图锁定选择值,YUV shader常量由8扩到12,记录映射路由和峰值出处;结束清除。
+- HdrToSdr.hlsli/YuvToLinearRgb:替换旧肩部和逐通道裁切,共享现有GPU pass,不增加CPU回读/帧等待/额外处理循环。
+- VeyraShaders.cmake:新增include依赖,防止增量构建沿用旧shader。
+- HdrToneMapGpuCases:标准参考用独立Bezier/de Casteljau表达,避免把生产Hermite展开式原封不动复写成测试。覆盖PQ/HLG、有限/全范围、203/400/1000/4000/10000峰值、灰阶/高饱和色,以及Y保持、色度方向、有限范围、单调性。
+- HdrColorTests:保留原生HDR、SDR和采集格式检查,替换旧色调映射期望;文件软/硬解和真实增强继续回归。
+
+## 验收计划
+
+构建→独立GPU颜色/原生HDR回归→真实元数据文件软硬解对照→NR/SR/FG下的HDR转SDR→完整delivery。单次测试不超过300秒。记录失败原因,用户屏幕/原始问题电影未提供,不以合成信号宣称全部素材主观验收。最终结果随后补记。
+
+## 已执行的颜色与文件验证
+
+`scripts/run-short-test.ps1 -Exe out/build/audio-continuity-repair-20260915/veyra_hdr_color_tests.exe -Arguments @('out/hdr-audio-fixtures/pq-static-2000-20260915.mp4','2000') -TimeoutSeconds 150 -LogPrefix logs/hdr-tonemap-file-c-20260915` exit0。包括20组新映射GPU色块、元数据有效性/继承、同图reset稳定性、原有16组原生HDR往返及其真实呈现缓冲、SDR/采集格式/旧HDR输出组合;全部通过。
+
+本地合成PQ/HEVC fixture为1280×720、30帧、内容峰值MaxCLL=2000、MaxFALL=400、母版显示峰值4000,使用FFmpeg/libx265独立编码,命令输出 `logs/hdr-tonemap-fixture-20260915.log`。软件/硬解均读出并选中2000,整帧无增强RGB8输出最大差0个代码值;并非只是文件能打开。
+
+同一文件运行6组真实增强:软/硬解各做NR、SR→NR→FG、NR→SR→FG;每组NR Evaluate=12,后四组SR=12且generated=11,日志全部pass1。NGX Init/CreateFeature返回0x1 Success,NVOF执行见同日志。测试同时包含4K工作输出,不等于4070/所有硬件实测性能。
+
+失败记录:首次扩常量时误把ComputePass的描述符槽参数8改成12,实际根常量仍为8,GPU测试检测转SDR黑输出并exit1(`hdr-tonemap-colors-a`)。修正为8个描述符槽、12个根常量后`hdr-tonemap-colors-b`及最终file-c测试通过,未改测试阈值掩盖黑图。build-c/build-d因用户重新打开的Veyra锁住EXE而LNK1104,独立测试目标已构建,不能把这些整包构建标为成功;等待关闭后重链。旧诊断media_probe同步扩根常量到12,避免使用新shader时ABI不匹配。
+
+## 已知边界
+
+静态元数据错误或缺失时不能知道真实内容峰值;仍明确回退1000而非宣称已测量,超过所选峰值的高光会到输出白点。没有逐帧动态亮度扫描、HDR10+/DV动态元数据、显示器测光或反馈者原始电影对照。本轮解决的是固定映射缺少元数据及逐通道裁切的确定局限,不宣称HDR→SDR可以无损保留HDR全部亮度/色域。
+
+## 当前可续接状态
+
+新映射20组最大linear Y误差0.000526118、色度方向误差0.000390535;16组原生HDR往返保持通过,实际呈现缓冲一致。用户18:49重新启动的Veyra PID11576持续播放capture2采集,标准EXE被锁,未强制关闭。
+
+为继续独立验证,采用Ninja给出的实际链接命令,只将输出EXE/LIB/PDB名字换成veyra-hdr-tonemap,`out/hdr-tonemap-link-alternate.cmd` 成功;全部最新应用对象与库正常链接,未复制或更换运行组件。独立候选 `out/build/audio-continuity-repair-20260915/veyra-hdr-tonemap.exe` SHA256 `07FF8C78BB20724DE16EF4302AC56CF3E1267B7562C66F4C56B1774EDA68CE99`,单独入口 `out/start-hdr-tonemap-candidate.cmd`。常用入口仍指向未最终替换的veyra.exe。media_probe同步ABI后经 `out/hdr-tonemap-build-probe.cmd` 构建通过,本轮未运行该历史probe。
+
+整体gate命令 `powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/gates/delivery.ps1 -Root . -BuildDirectory out/build/audio-continuity-repair-20260915 -PlayerExe out/build/audio-continuity-repair-20260915/veyra-hdr-tonemap.exe` **失败**,`logs/delivery/4579d1c0b0e3407d84b0f74c8fdf11ee/result.json`。实际NR/NVOF和原生4K前项通过,但player-sync时差P95=80.15ms,超过50ms,processed43FPS、generated1。另一份Veyra同期开着采集可能竞争GPU;这只是待排除因素,不能未经独立复测归因。未运行后续gate项、不标全包验收通过。
+
+下一步:收到用户停止现有采集的回复后,正常构建替换veyra.exe并在无并行采集时重跑delivery;若仍失败,比较SDR分支计时和运行负载再定位。当前颜色专项通过,整包性能验收与常用入口替换未完成,不发布。
+
+### 后续标准候选替换完成
+
+用户随后报告补帧受限却显示180fps;检查时Veyra已退出。保留HDR修复,并修正主帧率显示口径后,标准构建 `logs/fg-rate-display-build-20260915.log` exit0,完整delivery `logs/delivery/6bade0b84d8449d89198cffa37453a2d/result.json` PASS。这次无并行用户采集,前次player-sync失败未再次出现;单次通过不构成并行负载因果证明。
+
+常用入口 `out/start-user-issues-candidate.cmd` 已指向含本轮全部HDR改动的标准veyra.exe,SHA256 `888BC5E1ED098AD1E3A4C0188D58100452E31364DF45826267FAADB9C01C24E6`。颜色专项证据沿用本文件file-c(其后未再改颜色算法),全包验证补齐;采集3X生成后过期是新增未闭环问题,见FG_OUTPUT_RATE_AUDIT。未发布。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index 54b7d511..725ac21f 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -2265,3 +2265,23 @@ CaptureAudioDsp增加调度储备约束,CaptureAudioSession将输入/PCM/端
完整delivery同上命令exit0,`logs/delivery/3c3099c2022d4272a439d63b3062363b/result.json`,46.48秒,实际NR/NVOF/原生4K/播放控制/图片/导出音轨通过。候选EXE SHA256 `912FECDF30FE385BC33F1A6272EF8DF8E695B43F1D76F650AC2B521422CEBF93`,`out/start-user-issues-candidate.cmd`。运行组件/SDK/配置/录音不提交Git,没有push或发布。本机回录消除了已复现的间隙,用户最终听感及其他卡型号尚未验收。
持续漂移 `veyra_capture_audio_tests.exe --drift-slow` 经run-short-test、150秒上限,日志 `logs/audio-buzz-drift-slow-20260915.stdout.log` exit0。实际120秒/输入慢0.1%/静音WASAPI,软件时差绝对值P95=4.279ms,missing=0、resets=1(启动)、队列高水位89.646ms、稳态underrun=0,未出现累计多秒延迟。不是声学延迟证明。下一步仅交用户试听确认本次采集杂音,不据此宣称所有卡已修好。
+
+## 2026-09-15 HDR映射候选完成与补帧产出/提交口径排查
+
+HDR修改ColorMetadata/FramePacket/MediaFileSource静态元数据继承,HdrToneMap源峰值选择与图内固定,YuvToLinearRgb/HdrToSdr亮度映射及同亮度色域压缩,EnhanceGraph根常量合同、CMake依赖及media_probe ABI;新增GPU颜色测试。详细命令、失败和SDK证据见 `docs/HDR_TO_SDR_MAPPING_REPAIR_2026-09-15.md`。首轮根常量参数错误导致黑输出并测试失败,已修正;file-c经150秒上限exit0,20组映射最大Y误差0.000526118、色度方向0.000390535,16组原生HDR通过;PQ2000nit软硬解一致,6组真实NR/SR/FG执行通过,NGX Init/CreateFeature 0x1 Success。此前EXE锁定链接失败和并行采集期间player-sync gate失败均保留记录,未冒充通过。
+
+用户反馈“受限却180fps”后,原日志session3/revision556证明GPU原帧60+生成120,但显示提交141至170fps,累计2780有效生成有360过期丢弃。AppShell主标签原读outputCompletedFps,状态判定读presentSubmitFps;本轮将标签统一为显示提交,LiveStatusPanel明确非屏幕实测/原帧与生成帧提交/产出含过期。没有改丢弃阈值掩盖欠速,实际采集3X过期原因仍待逐子帧时间验证,见 `docs/FG_OUTPUT_RATE_AUDIT_2026-09-15.md`。
+
+最终标准构建 `cmd.exe /c out\build\veyra-build-x64-release.cmd` exit0,日志 `logs/fg-rate-display-build-20260915.log`。完整delivery命令沿用上文,exit0,`logs/delivery/6bade0b84d8449d89198cffa37453a2d/result.json`,原始应用日志 `logs/fg-rate-display-delivery-20260915.log`。实际NR/NVOF/4K/GUI/导出等通过,本次未运行用户并行采集;不冒充采集3X根治或其他硬件验收。`git diff --check` exit0,仅换行提示。
+
+标准候选SHA256 `888BC5E1ED098AD1E3A4C0188D58100452E31364DF45826267FAADB9C01C24E6`,入口 `out/start-user-issues-candidate.cmd`。运行组件/SDK/本机媒体保持源码Git外;未发布。下一项是采集3X补帧生成后过期的调度专项,不是重复改HDR对比度。
+
+### 2026-09-15 补帧受限与180fps口径修复
+
+用户反馈3X补帧受限但右侧180fps。`logs/fg-deadline-baseline-capture-20260915.log` 用同一采集参数 `capture:0:0:0 --nr --video-sr 2 --fg-multiplier 3 --smoke-seconds 32` 复现:有效生成3480、生成提交3060、过期420;batch442第一张已在截止后8.546ms就绪,决定时10.588ms,因整批resolve等待后续子帧而越过10ms容差。UI原先右侧读 `outputCompletedFps`,含过期产出;已改为 `presentSubmitFps`,详细面板明确显示提交与含过期产出。
+
+实现 `EnhanceGraph::resolveFrame`,按每个MFG子帧lease/fence独立解析有效状态;实时采集/串流按子帧就绪、PTS顺序提交,文件/导出仍使用完整 `resolveGeneration`。保留2批队列、consumer fence、原10ms过期规则和GPU资源状态,不放宽阈值或增加缓冲;不宣称实测延迟没有变化。新增 `fg-deadline`限频日志只记录CPU首次观测栅栏、截止/决定时间和是否整批ready,不冒充GPU精确终点或屏幕扫描率。
+
+修后同参数32秒 `logs/fg-progressive-capture-20260915.log` exit0:生成3478、提交3478、过期0、显示提交180fps;120秒持续采集 `logs/fg-progressive-capture-long-20260915.log` exit0:源7062、生成14050、提交14050、过期0、显示提交180fps,`failed=false`,无错误。既有 `veyra_presentation_worker_tests.exe`、`veyra_live_timing_tests.exe` 回归exit0,日志 `logs/fg-progressive-worker-tests-20260915.log`、`logs/fg-progressive-timing-tests-20260915.log`;新增逐帧行为由实卡对照验证。最终delivery exit0,结果 `logs/delivery/90feb52b7ed84cf19d92d64596d79f10/result.json`,47.91秒;未发布。
+
+最终候选SHA256 `02BBC51FF46A8DEBCCA9961BEC48500E2AA77FE62B238174172D4E238ACA6401`,入口沿用 `out/start-user-issues-candidate.cmd`。详细文件/命令/SDK结果及边界见FG_OUTPUT_RATE_AUDIT。回调至Present返回P95前后44.606/50.328ms,不能从丢帧改善推论屏幕延迟降低;真实屏幕与帧间均匀性尚未测量,下一步交用户同一组合游玩验收。HDR改动一同保留为本地可回退记录,运行库/SDK/媒体未入Git。
diff --git a/include/veyra/pipeline/ColorMetadata.h b/include/veyra/pipeline/ColorMetadata.h
index 666d41ce..62585335 100644
--- a/include/veyra/pipeline/ColorMetadata.h
+++ b/include/veyra/pipeline/ColorMetadata.h
@@ -4,9 +4,18 @@ extern "C" {
#include <libavutil/frame.h>
#include <libavutil/pixfmt.h>
#include <libavutil/pixdesc.h>
+#include <libavutil/mastering_display_metadata.h>
}
namespace veyra::pipeline {
inline ColorDescription resolveFrameColor(const AVFrame& frame,ColorDescription c={}){
+ if(const auto* data=av_frame_get_side_data(&frame,AV_FRAME_DATA_MASTERING_DISPLAY_METADATA);data&&data->size>=sizeof(AVMasteringDisplayMetadata)){
+ const auto* m=reinterpret_cast<const AVMasteringDisplayMetadata*>(data->data);
+ if(m->has_luminance&&m->max_luminance.den>0){const double n=av_q2d(m->max_luminance);if(n>0&&n<=10000)c.hdrMasteringPeakNits=float(n);}
+ }
+ if(const auto* data=av_frame_get_side_data(&frame,AV_FRAME_DATA_CONTENT_LIGHT_LEVEL);data&&data->size>=sizeof(AVContentLightMetadata)){
+ const auto* m=reinterpret_cast<const AVContentLightMetadata*>(data->data);
+ if(m->MaxCLL>0&&m->MaxCLL<=10000&&m->MaxFALL<=m->MaxCLL){c.hdrMaxCllNits=float(m->MaxCLL);c.hdrMaxFallNits=float(m->MaxFALL);}
+ }
switch(frame.chroma_location){
case AVCHROMA_LOC_LEFT:c.chromaLocation=ChromaLocation::Left;break;
case AVCHROMA_LOC_CENTER:c.chromaLocation=ChromaLocation::Center;break;
diff --git a/include/veyra/pipeline/EnhanceGraph.h b/include/veyra/pipeline/EnhanceGraph.h
index dd0f3be1..ea0399c3 100644
--- a/include/veyra/pipeline/EnhanceGraph.h
+++ b/include/veyra/pipeline/EnhanceGraph.h
@@ -148,6 +148,9 @@ public:
// Nonblocking. The scheduler polls at a GPU-ready/deadline boundary; no
// full image readback and no waits inside the graph's individual passes.
bool resolveGeneration(FrameOutputs& out);
+ // Resolve one leased frame without waiting for later MFG subframes.
+ // Full-batch consumers (export/file accounting) still use resolveGeneration.
+ bool resolveFrame(FrameOutputs& out,uint32_t index);
bool applySettings(const engine::EnhancementSettings&);
// s10 ownership-order teardown: NVOF fence drain must happen BEFORE this
@@ -288,6 +291,7 @@ private:
std::vector<uint8_t> nv12Buf_;
ComputePass yuvPass_, encPass_, decPass_, blitPass_, uploadPass_, densifyPass_;
+ float toneMapPeakNits_=0; // latched per graph/source; never varies with frame brightness
ComputePass rgbPass_,hdrVideoSrPass_;
ComputePass downsamplePass_,residualPass_,flowAdaptPass_;
DescriptorStager stager_;
diff --git a/include/veyra/pipeline/FramePacket.h b/include/veyra/pipeline/FramePacket.h
index b8d769dc..71e02bc5 100644
--- a/include/veyra/pipeline/FramePacket.h
+++ b/include/veyra/pipeline/FramePacket.h
@@ -105,6 +105,9 @@ struct ColorDescription {
// PS5 opt-in reconstruction; legacy file/capture/export sampling is unchanged.
ChromaLocation chromaLocation = ChromaLocation::Unknown;
bool reconstructChroma = false;
+ // Static HDR metadata in cd/m2; zero means absent/unspecified. These are
+ // declarations, not measured frame peaks or dynamic Dolby Vision metadata.
+ float hdrMaxCllNits = 0, hdrMaxFallNits = 0, hdrMasteringPeakNits = 0;
bool isHdrPath() const {
return transfer == TransferFunction::PQ || transfer == TransferFunction::HLG;
diff --git a/include/veyra/pipeline/HdrToneMap.h b/include/veyra/pipeline/HdrToneMap.h
new file mode 100644
index 00000000..4c6c17a9
--- /dev/null
+++ b/include/veyra/pipeline/HdrToneMap.h
@@ -0,0 +1,18 @@
+#pragma once
+#include "veyra/pipeline/FramePacket.h"
+#include <algorithm>
+#include <cmath>
+namespace veyra::pipeline {
+struct HdrToneMapPeak {float nits;const char* source;};
+inline HdrToneMapPeak hdrToneMapPeak(const ColorDescription& c){
+ // HLG's existing reference OOTF defines a 1000-nit reference display.
+ if(c.transfer==TransferFunction::HLG)return {1000,"HLG-reference"};
+ const auto valid=[](float n){return std::isfinite(n)&&n>0&&n<=10000;};
+ if(valid(c.hdrMaxCllNits)&&(!valid(c.hdrMaxFallNits)||c.hdrMaxFallNits<=c.hdrMaxCllNits))
+ return {std::max(203.0f,c.hdrMaxCllNits),"MaxCLL"};
+ // Mastering display capability is only an explicit fallback, not a
+ // measurement of the content. Never amplify a dim source up to the target.
+ if(valid(c.hdrMasteringPeakNits))return {std::max(203.0f,c.hdrMasteringPeakNits),"mastering-fallback"};
+ return {1000,"assumed-fallback"};
+}
+}
diff --git a/shaders/HdrToSdr.hlsli b/shaders/HdrToSdr.hlsli
new file mode 100644
index 00000000..5e06d830
--- /dev/null
+++ b/shaders/HdrToSdr.hlsli
@@ -0,0 +1,43 @@
+// BT.2390 EETF, ideal black, PQ-domain Hermite shoulder. Target peak is
+// explicitly SDR display white; output is relative linear BT.709 for the
+// existing single sRGB encoding stage. Not used by native HDR or NR proxies.
+float TonePq(float nits) {
+ float p=pow(saturate(nits/10000.0),2610.0/16384.0);
+ return pow((3424.0/4096.0+(2413.0/128.0)*p)/(1+(2392.0/128.0)*p),2523.0/32.0);
+}
+float ToneNits(float code) {
+ float p=pow(saturate(code),32.0/2523.0);
+ return 10000.0*pow(max(p-3424.0/4096.0,0)/max(2413.0/128.0-(2392.0/128.0)*p,1e-6),16384.0/2610.0);
+}
+float ToneLuminance(float nits,float sourcePeak,float targetPeak) {
+ if(nits<=0)return 0;
+ if(sourcePeak<=targetPeak)return min(nits/targetPeak,1.0);
+ float black=TonePq(0),span=TonePq(sourcePeak)-black;
+ float x=saturate((TonePq(nits)-black)/span);
+ float top=(TonePq(targetPeak)-black)/span;
+ float knee=1.5*top-.5;
+ if(x>=knee){
+ float t=(x-knee)/(1-knee),t2=t*t,t3=t2*t;
+ x=(2*t3-3*t2+1)*knee+(t3-2*t2+t)*(1-knee)+(-2*t3+3*t2)*top;
+ }
+ return saturate(ToneNits(x*span+black)/targetPeak);
+}
+float3 ToneGamut(float3 rgb,float y) {
+ // Retain signed out-of-gamut components until a common chroma scale can
+ // be found. Move along the RGB chroma ray toward neutral, preserving Y;
+ // independent channel clipping would change both luminance and hue.
+ if(y<=0)return 0;if(y>=1)return 1;
+ float3 chroma=rgb-y;
+ float3 occupancy=select(chroma>=0,chroma/max(1-y,1e-7),-chroma/max(y,1e-7));
+ float extent=max(occupancy.r,max(occupancy.g,occupancy.b));
+ // Smooth shoulder begins at 90% of the target gamut boundary. All
+ // interior colors below that point remain unchanged; no hard hue bends.
+ if(extent>.9){float compressed=.9+.1*(1-exp(-(extent-.9)/.1));chroma*=compressed/extent;}
+ return y+chroma;
+}
+float3 HdrToSdr(float3 linear709Nits,float sourcePeak,float targetPeak) {
+ float y=dot(linear709Nits,float3(.212639,.715169,.072192));
+ if(y<=0)return 0;
+ float mapped=ToneLuminance(y,sourcePeak,targetPeak);
+ return ToneGamut(linear709Nits*(mapped/y),mapped);
+}
diff --git a/shaders/YuvToLinearRgb.hlsl b/shaders/YuvToLinearRgb.hlsl
index 4ac1637f..4c95f2d9 100644
--- a/shaders/YuvToLinearRgb.hlsl
+++ b/shaders/YuvToLinearRgb.hlsl
@@ -3,11 +3,13 @@
// SRVs; the dispatch covers the full frame. Color metadata (range/matrix/
// transfer) arrives as root constants set per frame from FFmpeg stream data.
#include "HdrColor.hlsli"
+#include "HdrToSdr.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
};
Texture2D<float> lumaPlane : register(t0); // R8_UNORM or R16_UNORM
@@ -107,11 +109,7 @@ void main(uint3 dispatchThreadId : SV_DispatchThreadID)
float3 linear709=mul(float3x3(1.660491,-0.587641,-0.072850,-0.124550,1.132900,-0.008349,-0.018151,-0.100579,1.118730),nits);
if((yuvDimensions.z&1)!=0)rgb=linear709/80.0; // scRGB: 1.0 = 80 nits.
else{
- // Stable luminance shoulder, fixed 1000-nit reference peak.
- // This is SDR mapping, never advertised as native HDR output.
- float3 c=max(linear709/203.0,0.0);float lum=dot(c,float3(.2126,.7152,.0722));
- float peak=1000.0/203.0;float mapped=lum*(1.0+lum/(peak*peak))/(1.0+lum);
- rgb=saturate(c*(mapped/max(lum,1e-6)));
+ rgb=HdrToSdr(linear709,toneMapParams.x,toneMapParams.y);
}
} else if (colorParams0.z > 2.5) {
rgb = pow(rgb, 2.4); // BT.1886 EOTF, ideal black SDR display intent.
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index e198acb0..ad1ce2ab 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -340,7 +340,9 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
bool real=false;
std::atomic<bool> ready=false;
Clock::time_point readyObserved{};
+ std::array<int64_t,4> frameReadyObserved{};
};
+ int64_t nextFgDeadlineLog=0;
std::vector<std::shared_ptr<CompletionWatch>> pendingCompletions;
std::shared_ptr<FrameFlowWindow> frameFlow;
const uint64_t runSessionId=[&]{std::lock_guard lock(mutex_);return snapshot_.sessionId;}();
@@ -401,6 +403,10 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
collectTimings();
for(auto it=pendingCompletions.begin();it!=pendingCompletions.end();){
auto& watch=**it;auto& batch=watch.output;
+ const auto completedFence=ctx.fence()->GetCompletedValue();
+ for(unsigned i=0;i<batch.batch.count;++i){const auto& item=batch.batch.frames[i];
+ if(!watch.frameReadyObserved[i]&&item.lease&&completedFence>=item.lease->readyFence)watch.frameReadyObserved[i]=host100ns();
+ }
if(!graph.resolveGeneration(batch)){++it;continue;}
// The GPU may finish between the first poll and resolve.
// Collect its timestamps before removing this watch.
@@ -907,11 +913,11 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
unsigned left=0;for(unsigned i=s.next;i<batch.batch.count;++i)if(batch.batch.frames[i].kind!=pipeline::FrameKind::Generated||batch.batch.frames[i].validity==pipeline::GenerationValidity::Valid)++left;
flow->update([&](auto& m){if(left>s.remaining)m.pendingOutputFrames+=left-s.remaining;else m.pendingOutputFrames-=std::min(m.pendingOutputFrames,s.remaining-left);});s.remaining=left;
};std::unique_ptr<LiveStepState,decltype(updatePending)> pendingUpdate(&s,updatePending);
- if(!watch->ready){
+ if(!isCapture&&!watch->ready){
if(elapsedMs(s.readyStart)>2000){veyra::log::error("capture-present","GPU ready timeout");return {State::Failed};}
return {State::Pending,now+2000};
}
- if(!s.readyReported){s.readyMs=std::max(0.0,std::chrono::duration<double,std::milli>(watch->readyObserved-s.readyStart).count());s.readyReported=true;flow->cpu(diagnostics::CpuStage::ReadyWait,s.readyMs,host100ns());}
+ if(watch->ready&&!s.readyReported){s.readyMs=std::max(0.0,std::chrono::duration<double,std::milli>(watch->readyObserved-s.readyStart).count());s.readyReported=true;flow->cpu(diagnostics::CpuStage::ReadyWait,s.readyMs,host100ns());}
if(!isCapture&&fileAwaitingVideo&&!seekPreviewPending&&!fileInputEnded&&
(liveScheduler->occupancy()<2||!pendingCompletions.empty()))return {State::Pending,now+2000};
if(!isCapture&&audioStarted&&fileAudioAlignPending){
@@ -922,10 +928,22 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
}
while(s.next<batch.batch.count){auto& item=batch.batch.frames[s.next];const bool generated=item.kind==pipeline::FrameKind::Generated;
if(stop_||(paused_&&!seekPreviewPending)||seekSeconds_>=0)return {State::Complete};
+ if(isCapture&&!graph.resolveFrame(batch,s.next)){
+ if(elapsedMs(s.readyStart)>2000){veyra::log::error("capture-present","GPU frame ready timeout");return {State::Failed};}
+ return {State::Pending,host100ns()+2000};
+ }
+ if(isCapture&&!s.readyReported){s.readyMs=elapsedMs(s.readyStart);s.readyReported=true;flow->cpu(diagnostics::CpuStage::ReadyWait,s.readyMs,host100ns());}
if(generated&&item.validity!=pipeline::GenerationValidity::Valid){++s.handled;++s.next;continue;}
if(generated&&(comparisonMode_!=0||!generatedPresentationCurrent(jobGeneration,presentationGeneration.load()))){++presentationSkippedGenerated;++s.next;continue;}
const double itemPtsMs=double(item.pts100ns)/10000;
- if(generated&&(isCapture?timeline.expired(item.pts100ns,host100ns(),100000):!fileAwaitingVideo&&previewGeneratedExpired(nowMs(),itemPtsMs))){++s.dropped;++s.handled;++s.next;s.deadlineStart.reset();continue;}
+ const auto decisionTime=host100ns();
+ const bool generationExpired=generated&&(isCapture?timeline.expired(item.pts100ns,decisionTime,100000):!fileAwaitingVideo&&previewGeneratedExpired(nowMs(),itemPtsMs));
+ if(generated&&isCapture&&decisionTime>=nextFgDeadlineLog){
+ nextFgDeadlineLog=decisionTime+10000000;
+ const auto ready=watch->frameReadyObserved[s.next];
+ veyra::log::info("fg-deadline",std::format("revision={} batch={} subframe={} expired={} readyObservedLateMs={:.3f} decisionLateMs={:.3f} observedReadyToDecisionMs={:.3f} batchReady={} (CPU fence observations, not scanout)",item.identity.settingsRevision,batch.batch.batchId,item.subframe,generationExpired,double(ready-timeline.deadline(item.pts100ns))/10000,double(decisionTime-timeline.deadline(item.pts100ns))/10000,ready?double(decisionTime-ready)/10000:-1,watch->ready.load()));
+ }
+ if(generationExpired){++s.dropped;++s.handled;++s.next;s.deadlineStart.reset();continue;}
if(!s.deadlineStart)s.deadlineStart=Clock::now();
if(isCapture){if(host100ns()<timeline.deadline(item.pts100ns))return {State::Pending,timeline.deadline(item.pts100ns)};}
else if(!fileAwaitingVideo){
diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cpp
index 34a2943e..83ee9999 100644
--- a/src/pipeline/EnhanceGraph.cpp
+++ b/src/pipeline/EnhanceGraph.cpp
@@ -1,4 +1,5 @@
#include "veyra/pipeline/ColorMetadata.h"
+#include "veyra/pipeline/HdrToneMap.h"
// EnhanceGraph implementation - the real GPU chain migrated from
// tools/player_probe main.cpp (R3.2). Ordering constraints preserved from the
// injected-layer era evidence: committed resources and NGX/NVOF objects are
@@ -536,7 +537,7 @@ 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)) return false;
+ if (!yuvPass_.loadShader("YuvToLinearRgb.dxil", cs) || !yuvPass_.create(context_.device(), cs, 8, 2, 1, 12)) return false;
if((desc_.rgbInput||desc_.yuy2Input)&&(!rgbPass_.loadShader(desc_.yuy2Input?"Yuy2ToLinear.dxil":"RgbToLinear.dxil",cs)||!rgbPass_.create(context_.device(),cs,8,1,1)))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;
@@ -706,6 +707,10 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
return false;
}
const auto resolved=resolveFrameColor(*frame,color?*color:ColorDescription{});
+ if(resolved.isHdrPath()&&!desc_.hdrOutput&&!toneMapPeakNits_){
+ const auto peak=hdrToneMapPeak(resolved);toneMapPeakNits_=peak.nits;
+ log::info("hdr-tone-map",std::format("method=BT2390-luminance sourcePeakNits={} peakSource={} targetPeakNits=203 blackNits=0 gamut=neutral-ray-soft-knee staticPerGraph=1",peak.nits,peak.source));
+ }
if(desc_.hdrInput&&!resolved.isHdrPath()){
veyra::log::error("hdr","HDR source transfer changed to SDR; reopen/rebuild required");return false;
}
@@ -720,7 +725,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
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"));
+ desc_.hdrOutput?"none":"BT2390-luminance+neutral-ray-gamut-compression"));
}
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;
@@ -921,11 +926,11 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
rgbPass_.bind(list,c,gpuHandleOf(rgbPass_,0).ptr,gpuHandleOf(rgbPass_,1).ptr);
list->Dispatch((srcW_+15)/16,(srcH_+15)/16,1);
}else{
- const float constants[8] = { resolved.range==ColorRange::Full?0.0f:1.0f,
+ const float constants[12] = { 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) };
+ 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);
list->Dispatch((srcW_ + 15) / 16, (srcH_ + 15) / 16, 1);
}
@@ -1288,30 +1293,37 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
return true;
}
-bool EnhanceGraph::resolveGeneration(FrameOutputs& out)
+bool EnhanceGraph::resolveFrame(FrameOutputs& out,uint32_t index)
{
- // Real-only batches also need a completed GPU fence before a consumer
- // can report completed processing. This is a nonblocking poll.
- const auto completed=context_.fence()->GetCompletedValue();
- for(uint32_t i=0;i<out.batch.count;++i)
- if(out.batch.frames[i].lease&&completed<out.batch.frames[i].lease->readyFence)return false;
- if(!out.hasGenerated)return true;
- if(context_.fence()->GetCompletedValue()<out.genFenceValue)return false;
- bool anyValid=false;
- for(uint32_t i=0;i<out.batch.count;++i){
- auto& frame=out.batch.frames[i];if(frame.kind!=FrameKind::Generated)continue;
- if(frame.validity!=GenerationValidity::Pending){anyValid|=frame.validity==GenerationValidity::Valid;continue;}
+ if(index>=out.batch.count)return false;
+ auto& frame=out.batch.frames[index];
+ if(!frame.lease||context_.fence()->GetCompletedValue()<frame.lease->readyFence)return false;
+ if(frame.kind!=FrameKind::Generated||frame.validity!=GenerationValidity::Pending)return true;
void* data=nullptr;D3D12_RANGE range{0,4};
HRESULT hr=fgDisableReadback_[frame.lease->slot]->Map(0,&range,&data);
- if(FAILED(hr)){frame.validity=GenerationValidity::Failed;out.hasGenerated=false;veyra::log::error("fg-status",std::format("Map hr=0x{:X}",unsigned(hr)));return true;}
+ if(FAILED(hr)){frame.validity=GenerationValidity::Failed;veyra::log::error("fg-status",std::format("Map hr=0x{:X}",unsigned(hr)));return true;}
const bool disabled=*static_cast<uint8_t*>(data)!=0;
const bool rejected=disabled||out.contentDuplicate;
D3D12_RANGE written{0,0};fgDisableReadback_[frame.lease->slot]->Unmap(0,&written);
frame.validity=rejected?GenerationValidity::Disabled:GenerationValidity::Valid;
- anyValid|=!rejected;if(rejected)++metrics_.fgDisabledFrames;else ++metrics_.fgGeneratedFrames;
+ if(rejected)++metrics_.fgDisabledFrames;else ++metrics_.fgGeneratedFrames;
if(veyra::log::verboseFrameLogs())veyra::log::info("fg-status",std::format("batch={} frame={} epoch={} revision={} subframe={} fence={} disable={} valid={}",out.batch.batchId,out.realFrameIndex,out.batch.identity.epoch,out.batch.identity.settingsRevision,frame.subframe,frame.lease->readyFence,disabled,!rejected));
+ return true;
+}
+
+bool EnhanceGraph::resolveGeneration(FrameOutputs& out)
+{
+ bool complete=true,anyValid=false;
+ for(uint32_t i=0;i<out.batch.count;++i){
+ if(!resolveFrame(out,i))complete=false;
+ const auto& frame=out.batch.frames[i];
+ anyValid|=frame.kind==FrameKind::Generated&&frame.validity==GenerationValidity::Valid;
}
- out.hasGenerated=anyValid;return true;
+ // Warmup evaluates may have no exposed generated leases, but their status
+ // and resources must finish before full-batch completion is reported.
+ if(context_.fence()->GetCompletedValue()<out.genFenceValue)complete=false;
+ if(complete)out.hasGenerated=anyValid;
+ return complete;
}
bool EnhanceGraph::applySettings(const engine::EnhancementSettings& s){
@@ -1434,6 +1446,7 @@ void EnhanceGraph::shutdown()
encPass_ = ComputePass{};
blitPass_ = ComputePass{};hdrVideoSrPass_={};
yuvPass_ = ComputePass{};
+ toneMapPeakNits_=0;
densifyPass_ = ComputePass{};
confTex_.Reset();
flowTex_.Reset();
diff --git a/src/source/MediaFileSource.cpp b/src/source/MediaFileSource.cpp
index 70d1f6f2..ef937311 100644
--- a/src/source/MediaFileSource.cpp
+++ b/src/source/MediaFileSource.cpp
@@ -112,6 +112,13 @@ pipeline::ColorDescription MediaFileSource::parseColor(const AVCodecParameters*
// expansion and YUV matrix conversion. Match the working decode to the
// sink encode; don't apply a reference-monitor gamma adjustment here.
cd.preserveSdrCodeValues = true;
+ if(const auto* data=av_packet_side_data_get(params->coded_side_data,params->nb_coded_side_data,AV_PKT_DATA_MASTERING_DISPLAY_METADATA);data&&data->size>=sizeof(AVMasteringDisplayMetadata)){
+ const auto* m=reinterpret_cast<const AVMasteringDisplayMetadata*>(data->data);
+ if(m->has_luminance&&m->max_luminance.den>0)cd.hdrMasteringPeakNits=float(av_q2d(m->max_luminance));
+ }
+ if(const auto* data=av_packet_side_data_get(params->coded_side_data,params->nb_coded_side_data,AV_PKT_DATA_CONTENT_LIGHT_LEVEL);data&&data->size>=sizeof(AVContentLightMetadata)){
+ const auto* m=reinterpret_cast<const AVContentLightMetadata*>(data->data);cd.hdrMaxCllNits=float(m->MaxCLL);cd.hdrMaxFallNits=float(m->MaxFALL);
+ }
AVFrame metadata{};metadata.format=params->format;metadata.height=info_.height;metadata.color_range=params->color_range;metadata.colorspace=params->color_space;metadata.color_trc=params->color_trc;
return pipeline::resolveFrameColor(metadata,cd);
}
@@ -338,7 +345,7 @@ SourceReadStatus MediaFileSource::read(pipeline::FramePacket& out, const AVFrame
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));
+ log::info("hdr-metadata",std::format("masteringSource={} masteringMinNits={} masteringMaxNits={} contentSource={} maxCLL={} maxFALL={} (-1=unavailable; 0 content level=unspecified); SDR mapping validates peak declarations separately",masteringOrigin,minNits,maxNits,contentOrigin,maxCll,maxFall));
}
}
out.sourceEpoch = epoch_;
diff --git a/tests/integration/HdrColorTests.cpp b/tests/integration/HdrColorTests.cpp
index ac06fdef..fe57c9e2 100644
--- a/tests/integration/HdrColorTests.cpp
+++ b/tests/integration/HdrColorTests.cpp
@@ -10,6 +10,7 @@
#include "CaptureFormatGpuCases.h"
#include "SdrColorGpuCases.h"
#include "HdrNativeRoundTripCases.h"
+#include "HdrToneMapGpuCases.h"
#include <iostream>
#include <cmath>
extern "C" {
@@ -20,7 +21,22 @@ 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)+hdrRoundTrip::run(ctx,ring);
+ int failures=captureGpuCases(ctx,ring)+sdrColorGpuCases(ctx,ring)+hdrRoundTrip::run(ctx,ring)+hdrToneTests::run(ctx,ring);
+ if(argc>1){
+ std::vector<uint8_t> software;const float expectedPeak=argc>2?float(_wtof(argv[2])):0;
+ for(bool hardware:{false,true}){
+ source::MediaFileSource source;source::SourceOpenDesc sd;sd.path=argv[1];sd.preferHardwareDecode=hardware;sd.d3d12Device=ctx.device();sd.d3d12Queue=ctx.directQueue();
+ bool ok=source.open(sd);pipeline::FramePacket packet;const AVFrame* frame=nullptr;
+ if(ok)ok=source.read(packet,&frame)==source::SourceReadStatus::Frame;
+ pipeline::EnhanceGraph graph(ctx,ring);pipeline::EnhanceGraphDesc gd;gd.sourceWidth=gd.workWidth=source.info().width;gd.sourceHeight=gd.workHeight=source.info().height;
+ gd.hdrInput=true;gd.enableNr=gd.enableSr=gd.enableFg=false;gd.noFeatures=true;
+ pipeline::EnhanceGraph::FrameOutputs out;sink::RgbaImage image;float selected=0;
+ if(ok){selected=pipeline::hdrToneMapPeak(packet.colorInfo).nits;ok=(frame->format==AV_PIX_FMT_D3D12)==hardware&&(!expectedPeak||selected==expectedPeak)&&graph.initialize(gd)&&graph.createViews()&&graph.process(frame,0,true,out,1,&packet.colorInfo)&&sink::readRgba8(ctx,ring,graph.videoFrameResource(out.videoSlot),image);}
+ unsigned maxDifference=0;if(ok){if(!hardware)software=image.pixels;else{ok=software.size()==image.pixels.size();if(ok)for(size_t i=0;i<software.size();++i)maxDifference=std::max(maxDifference,unsigned(std::abs(int(software[i])-int(image.pixels[i]))));ok&=maxDifference<=1;}}
+ std::cout<<"HDR_TONE_FILE hardware="<<hardware<<" selectedPeak="<<selected<<" expectedPeak="<<expectedPeak<<" softHardwareMaxCodeDifference="<<maxDifference<<" pass="<<ok<<std::endl;
+ failures+=!ok;out={};ring.drainQueue();graph.shutdown();source.close();
+ }
+ }
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;
@@ -34,7 +50,7 @@ int wmain(int argc,wchar_t** argv){
if(planar)for(unsigned y=0;y<16;++y)for(unsigned x=0;x<32;++x)reinterpret_cast<uint16_t*>(f->data[2]+y*f->linesize[2])[x]=512;
pipeline::ColorDescription color;color.pixelFormat=pipeline::SourcePixelFormat::P010;color.transfer=hlg?pipeline::TransferFunction::HLG:pipeline::TransferFunction::PQ;color.matrix=pipeline::YuvMatrix::BT2020NCL;
pipeline::EnhanceGraph::FrameOutputs out;bool ok=graph.process(f,0,true,out,1,&color);double error=0;
- if(ok&&!native){sink::RgbaImage image;ok=sink::readRgba8(ctx,ring,graph.videoFrameResource(out.videoSlot),image);if(ok){for(unsigned i=0;i<3;++i){double l=nits[i]/203.0,p=1000.0/203.0,m=std::clamp(l*(1+l/(p*p))/(1+l),0.0,1.0);double expected=m<=.0031308?12.92*m:1.055*pow(m,1/2.4)-.055;double actual=image.pixels[(i*22+5)*4]/255.0;error=std::max(error,std::abs(expected-actual));}ok=error<.012;}}
+ if(ok&&!native){sink::RgbaImage image;ok=sink::readRgba8(ctx,ring,graph.videoFrameResource(out.videoSlot),image);if(ok){for(unsigned i=0;i<3;++i){double m=hdrToneTests::luminance(nits[i],1000);double expected=m<=.0031308?12.92*m:1.055*pow(m,1/2.4)-.055;double actual=image.pixels[(i*22+5)*4]/255.0;error=std::max(error,std::abs(expected-actual));}ok=error<.012;}}
if(ok&&native){
auto* texture=graph.videoFrameResource(out.videoSlot);auto desc=texture->GetDesc();D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{};UINT64 size=0;ctx.device()->GetCopyableFootprints(&desc,0,1,0,&footprint,nullptr,nullptr,&size);
D3D12_HEAP_PROPERTIES hp{};hp.Type=D3D12_HEAP_TYPE_READBACK;D3D12_RESOURCE_DESC bd{};bd.Dimension=D3D12_RESOURCE_DIMENSION_BUFFER;bd.Width=size;bd.Height=1;bd.DepthOrArraySize=1;bd.MipLevels=1;bd.SampleDesc.Count=1;bd.Layout=D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
diff --git a/tests/integration/HdrToneMapGpuCases.h b/tests/integration/HdrToneMapGpuCases.h
new file mode 100644
index 00000000..b64bf485
--- /dev/null
+++ b/tests/integration/HdrToneMapGpuCases.h
@@ -0,0 +1,92 @@
+#pragma once
+#include "veyra/pipeline/HdrToneMap.h"
+#include <limits>
+namespace hdrToneTests {
+// Independent BT.2390 reference: cubic Bezier evaluated by de Casteljau,
+// rather than the shader's expanded Hermite polynomial. ST2084 utilities
+// belong to the separately verified native HDR round-trip reference.
+inline double luminance(double y,double peak){
+ if(y<=0)return 0;if(peak<=203)return std::min(y/203,1.0);
+ const double black=hdrRoundTrip::pq(0),span=hdrRoundTrip::pq(peak)-black;
+ const double top=(hdrRoundTrip::pq(203)-black)/span,k=1.5*top-.5;
+ double x=std::clamp((hdrRoundTrip::pq(y)-black)/span,0.0,1.0);
+ if(x>=k){
+ const double t=(x-k)/(1-k);
+ std::array<double,4> p={k,k+(1-k)/3,top,top};
+ for(unsigned n=3;n>0;--n)for(unsigned i=0;i<n;++i)p[i]=std::lerp(p[i],p[i+1],t);
+ x=p[0];
+ }
+ return std::clamp(hdrRoundTrip::nits(x*span+black)/203,0.0,1.0);
+}
+inline int run(veyra::gfx::D3D12DeviceContext& ctx,veyra::gfx::CommandSlotRing& ring){
+ using namespace veyra;int failures=0;
+ pipeline::ColorDescription policy;policy.transfer=pipeline::TransferFunction::PQ;
+ bool metadata=pipeline::hdrToneMapPeak(policy).nits==1000;
+ policy.hdrMasteringPeakNits=4000;metadata&=pipeline::hdrToneMapPeak(policy).nits==4000;
+ policy.hdrMaxCllNits=600;metadata&=pipeline::hdrToneMapPeak(policy).nits==600;
+ policy.hdrMaxFallNits=700;metadata&=pipeline::hdrToneMapPeak(policy).nits==4000;
+ policy.hdrMaxCllNits=std::numeric_limits<float>::quiet_NaN();metadata&=pipeline::hdrToneMapPeak(policy).nits==4000;
+ policy.hdrMasteringPeakNits=20000;metadata&=pipeline::hdrToneMapPeak(policy).nits==1000;
+ policy.hdrMaxCllNits=50;policy.hdrMaxFallNits=0;metadata&=pipeline::hdrToneMapPeak(policy).nits==203;
+ policy.transfer=pipeline::TransferFunction::HLG;metadata&=pipeline::hdrToneMapPeak(policy).nits==1000;
+ AVFrame* metadataFrame=av_frame_alloc();auto* cll=av_content_light_metadata_create_side_data(metadataFrame);
+ if(!cll){av_frame_free(&metadataFrame);return 1;}
+ policy.hdrMaxCllNits=600;policy.hdrMaxFallNits=100;
+ metadata&=pipeline::resolveFrameColor(*metadataFrame,policy).hdrMaxCllNits==600;
+ cll->MaxCLL=4000;cll->MaxFALL=300;
+ metadata&=pipeline::resolveFrameColor(*metadataFrame,policy).hdrMaxCllNits==4000;
+ cll->MaxFALL=5000;metadata&=pipeline::resolveFrameColor(*metadataFrame,policy).hdrMaxCllNits==600;
+ av_frame_free(&metadataFrame);
+ std::cout<<"HDR_TONE_METADATA pass="<<metadata<<std::endl;failures+=!metadata;
+ for(bool hlg:{false,true})for(double declared:{203.,400.,1000.,4000.,10000.})for(bool full:{false,true}){
+ constexpr unsigned count=128,width=count*4,height=16;const double peak=hlg?1000:declared;
+ AVFrame* f=av_frame_alloc();f->format=AV_PIX_FMT_YUV420P10LE;f->width=width;f->height=height;
+ 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)return failures+1;
+ std::array<std::array<double,3>,count> linear{};
+ for(unsigned i=0;i<count;++i){
+ const double level=i==0?0:std::pow(10.,-3.+7.*std::min(i,103u)/103.);
+ std::array<double,3> n={level,level,level};
+ if(i>=104){const unsigned j=i-104;n={double((j*37)%100+1)*10,double((j*61)%100+1)*10,double((j*17)%100+1)*10};if(j<3){n={0,0,0};n[j]=1000;}}
+ std::array<double,3> signal;for(unsigned c=0;c<3;++c)signal[c]=hlg?hdrRoundTrip::hlgEncode(n[c]/10000):hdrRoundTrip::pq(n[c]);
+ const double y=.2627*signal[0]+.6780*signal[1]+.0593*signal[2];
+ const int yy=int(std::lround((full?0:64)+(full?1023:876)*y)),u=int(std::lround(512+(full?1023:896)*(signal[2]-y)/1.8814)),v=int(std::lround(512+(full?1023:896)*(signal[0]-y)/1.4746));
+ for(unsigned row=0;row<height;++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(yy);
+ if(!(row%2)&&!(x%2)){reinterpret_cast<uint16_t*>(f->data[1]+row/2*f->linesize[1])[x/2]=uint16_t(u);reinterpret_cast<uint16_t*>(f->data[2]+row/2*f->linesize[2])[x/2]=uint16_t(v);}}
+ const double l=(yy-(full?0.:64.))/(full?1023:876),cb=(u-512.)/(full?1023:896),cr=(v-512.)/(full?1023:896);
+ signal={l+1.4746*cr,l-.1645531268436578*cb-.5713531268436578*cr,l+1.8814*cb};
+ if(hlg){for(auto& c:signal)c=hdrRoundTrip::hlgDecode(c);double gain=1000*std::pow(.2627*signal[0]+.678*signal[1]+.0593*signal[2],.2);for(auto& c:signal)c*=gain;}
+ else for(auto& c:signal)c=hdrRoundTrip::nits(c);
+ linear[i]={1.660491*signal[0]-.587641*signal[1]-.072850*signal[2],-.124550*signal[0]+1.132900*signal[1]-.008349*signal[2],-.018151*signal[0]-.100579*signal[1]+1.118730*signal[2]};
+ }
+ pipeline::EnhanceGraph graph(ctx,ring);pipeline::EnhanceGraphDesc gd;gd.sourceWidth=gd.workWidth=width;gd.sourceHeight=gd.workHeight=height;gd.hdrInput=true;gd.enableNr=gd.enableSr=gd.enableFg=false;gd.noFeatures=true;
+ pipeline::ColorDescription color;color.hdrMaxCllNits=float(declared);
+ pipeline::EnhanceGraph::FrameOutputs out;std::vector<float> actual;
+ bool ok=graph.initialize(gd)&&graph.createViews()&&graph.process(f,0,true,out,1,&color)&&captureReadFp16(ctx,ring,graph.diagnosticLinearInput(),actual);
+ double yError=0,hueError=0,last=-1;bool bounded=true,monotone=true,neutral=true;
+ if(ok)for(unsigned i=0;i<count;++i){
+ const auto* p=actual.data()+(i*4+2)*4;const auto& c=linear[i];const double sourceY=.212639*c[0]+.715169*c[1]+.072192*c[2];
+ const double expected=luminance(sourceY,peak),y=.212639*p[0]+.715169*p[1]+.072192*p[2];yError=std::max(yError,std::abs(y-expected));
+ for(unsigned k=0;k<3;++k)bounded&=std::isfinite(p[k])&&p[k]>=-1e-5&&p[k]<=1.0001;
+ if(i<104){monotone&=y+1e-5>=last;last=y;neutral&=std::max({p[0],p[1],p[2]})-std::min({p[0],p[1],p[2]})<.001;}
+ else if(sourceY>1e-6&&expected>.001&&expected<.99){
+ // Common chroma scaling must preserve the linear RGB hue ray.
+ std::array<double,3> a={c[0]/sourceY-1,c[1]/sourceY-1,c[2]/sourceY-1},b={p[0]-y,p[1]-y,p[2]-y};
+ const double norm=std::sqrt(a[0]*a[0]+a[1]*a[1]+a[2]*a[2]);
+ if(norm>.001)for(unsigned k=0;k<3;++k)hueError=std::max(hueError,std::abs(a[k]*b[(k+1)%3]-a[(k+1)%3]*b[k])/norm);
+ }
+ }
+ ok=ok&&bounded&&monotone&&neutral&&yError<.0015&&hueError<.001;
+ std::cout<<"HDR_TONE_GPU hlg="<<hlg<<" declaredPeak="<<declared<<" full="<<full<<" luminanceError="<<yError<<" hueRayError="<<hueError<<" bounded="<<bounded<<" monotone="<<monotone<<" neutral="<<neutral<<" pass="<<ok<<std::endl;
+ if(ok&&!hlg&&!full&&declared==1000){
+ // Static metadata must not pump the picture across seeks/cuts in
+ // the same graph. A new source gets a fresh graph and selection.
+ out={};color.hdrMaxCllNits=4000;std::vector<float> second;
+ const bool stable=graph.process(f,33.333,true,out,2,&color)&&captureReadFp16(ctx,ring,graph.diagnosticLinearInput(),second)&&actual==second;
+ std::cout<<"HDR_TONE_STATIC_RESET pass="<<stable<<std::endl;ok&=stable;
+ }
+ failures+=!ok;out={};ring.drainQueue();graph.shutdown();av_frame_free(&f);
+ }
+ return failures;
+}
+}
diff --git a/tools/media_probe/main.cpp b/tools/media_probe/main.cpp
index 02bdf0d2..7c68fc8e 100644
--- a/tools/media_probe/main.cpp
+++ b/tools/media_probe/main.cpp
@@ -77,7 +77,7 @@ bool createYuvToRgbPipeline(veyra::gfx::D3D12DeviceContext& context, uint32_t wi
return false;
}
- // Root signature: b0 (8 constants) + SRV table (3) + UAV table (1).
+ // Root signature: b0 (12 constants) + SRV table (3) + UAV table (1).
D3D12_DESCRIPTOR_RANGE1 srvRange{};
srvRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
srvRange.NumDescriptors = 3;
@@ -97,7 +97,7 @@ bool createYuvToRgbPipeline(veyra::gfx::D3D12DeviceContext& context, uint32_t wi
rootParams[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
rootParams[0].Constants.ShaderRegister = 0;
rootParams[0].Constants.RegisterSpace = 0;
- rootParams[0].Constants.Num32BitValues = 8;
+ rootParams[0].Constants.Num32BitValues = 12;
rootParams[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
rootParams[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
rootParams[1].DescriptorTable.NumDescriptorRanges = 1;
@@ -253,9 +253,9 @@ bool dispatchYuvToRgb(veyra::gfx::D3D12DeviceContext& context,
// colorParams: limitedRange=1, matrix709=1, transferSRGB=1, padding
const float colorParams[4] = { 1.0f, 1.0f, 1.0f, 0.0f };
const uint32_t dims[4] = { pipeline.width, pipeline.height, 0, 0 };
- const float constants[8] = { colorParams[0], colorParams[1], colorParams[2], colorParams[3],
- static_cast<float>(dims[0]), static_cast<float>(dims[1]), 0.0f, 0.0f };
- list->SetComputeRoot32BitConstants(0, 8, constants, 0);
+ const float constants[12] = { colorParams[0], colorParams[1], colorParams[2], colorParams[3],
+ static_cast<float>(dims[0]), static_cast<float>(dims[1]), 0.0f, 0.0f, 1000.0f, 203.0f, 0.0f, 0.0f };
+ list->SetComputeRoot32BitConstants(0, 12, constants, 0);
list->SetComputeRootDescriptorTable(1, pipeline.srvHeap->GetGPUDescriptorHandleForHeapStart());
// UAV table at slot 2 in the same heap.
D3D12_GPU_DESCRIPTOR_HANDLE uavGpu = { pipeline.srvHeap->GetGPUDescriptorHandleForHeapStart().ptr + 2ull * pipeline.srvIncrement };