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(hdr): static output tuning - curve, HDR10 metadata, presets, strength dial, display peak
georgeg911b14dc5a43dc0
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 947e549d..68ff5f79 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -1034,6 +1034,13 @@ add_executable(veyra_sr_reconstruction_tests tests/integration/SrReconstructionTtarget_compile_options(veyra_vfg_export_probe PRIVATE /utf-8)target_link_libraries(veyra_vfg_export_probe PRIVATE veyra_engine)add_executable(veyra_preset_library_tests tests/unit/PresetLibraryTests.cpp src/engine/PresetLibrary.cpp src/engine/EffectChain.cpp)+target_link_options(veyra_preset_library_tests PRIVATE /STACK:33554432) # Preset apply recurses over 21 KB ChainConfiguration frames; the default 1 MB stack is too close to the edge.+add_executable(veyra_hdr_tuning_tests tests/unit/HdrOutputTuningTests.cpp src/engine/PresetLibrary.cpp src/engine/EffectChain.cpp)+target_compile_features(veyra_hdr_tuning_tests PRIVATE cxx_std_20)+target_include_directories(veyra_hdr_tuning_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)+# veyra_base carries /utf-8 and NOMINMAX (PresetLibrary.cpp has Chinese literals and uses std::max).+target_link_libraries(veyra_hdr_tuning_tests PRIVATE veyra_base)+target_link_options(veyra_hdr_tuning_tests PRIVATE /STACK:33554432)target_compile_features(veyra_preset_library_tests PRIVATE cxx_std_20)target_include_directories(veyra_preset_library_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)target_link_libraries(veyra_preset_library_tests PRIVATE veyra_base)diff --git a/i18n/catalog.json b/i18n/catalog.jsonindex cfe857db..d4161f0f 100644--- a/i18n/catalog.json+++ b/i18n/catalog.json@@ -427,6 +427,20 @@"en": "+ Add NR layer","ja": "+ NR 層を追加"},+ {+ "zh": "0 = 不做高光滚降",+ "src": "qml/Veyra/ProPage.qml",+ "zh-TW": "0 = 不做高光滾降",+ "en": "0 = no highlight roll-off",+ "ja": "0 = ハイライト壓縮なし"+ },+ {+ "zh": "0 = 不限制",+ "src": "qml/Veyra/ProPage.qml",+ "zh-TW": "0 = 不限制",+ "en": "0 = no limit",+ "ja": "0 = 制限なし"+ },{"zh": "0 = 沿用所选格式;设备返回其他帧率会报错,不在软件中偷偷丢帧","src": "qml/DialogHost.qml",@@ -434,6 +448,27 @@"en": "0 = use the selected format; a device that returns another frame rate reports an error instead of frames being dropped silently","ja": "0 = 選択したフォーマットのまま。デバイスが別のフレームレートを返した場合はエラーになり、黙ってフレームを捨てることはしません"},+ {+ "zh": "0 = 自动使用系统报告值",+ "src": "qml/Veyra/ProPage.qml",+ "zh-TW": "0 = 自动使用系统报告值",+ "en": "0 = use the value the system reports",+ "ja": "0 = use the value the system reports"+ },+ {+ "zh": "0 = 跟随片源",+ "src": "qml/Veyra/ProPage.qml",+ "zh-TW": "0 = 跟隨片源",+ "en": "0 = follow the source",+ "ja": "0 = ソースに追従"+ },+ {+ "zh": "0 = 跟随片源;报低通常整体变亮",+ "src": "qml/Veyra/ProPage.qml",+ "zh-TW": "0 = 跟隨片源;報低通常整體變亮",+ "en": "0 = follow the source; a lower value usually brightens the picture",+ "ja": "0 = ソースに追従。低く申告すると通常は全體が明るくなる"+ },{"zh": "1080p · 默认","src": "qml/NrLayerEditor.qml",@@ -441,6 +476,13 @@"en": "1080p · default","ja": "1080p · 既定"},+ {+ "zh": "203 = 中性;调高整体变亮,峰值不变",+ "src": "qml/Veyra/ProPage.qml",+ "zh-TW": "203 = 中性;調高整體變亮,峰值不變",+ "en": "203 = neutral; higher brightens the picture with the peak unchanged",+ "ja": "203 = 中性。上げると全體が明るくなるがピークは不變"+ },{"zh": "2X 为原生路径,3X / 4X 为实验解锁;失败原因见诊断","src": "src/ui/QmlPlayerBridge.cpp",@@ -756,6 +798,20 @@"en": "HDR → scRGB / float","ja": "HDR → scRGB / 浮動小数点"},+ {+ "zh": "HDR 亮度曲线",+ "src": "qml/Veyra/ProPage.qml",+ "zh-TW": "HDR 亮度曲線",+ "en": "HDR brightness curve",+ "ja": "HDR 輝度カーブ"+ },+ {+ "zh": "HDR 元数据",+ "src": "qml/Veyra/ProPage.qml",+ "zh-TW": "HDR 中繼資料",+ "en": "HDR metadata",+ "ja": "HDR メタデータ"+ },{"zh": "HDR 片源也按 SDR 显示;与采集卡的“转为 SDR 显示”是同一设置","src": "qml/ProPage.qml",@@ -924,6 +980,20 @@"en": "MP4 cannot keep this codec as is; choose MKV or exclude this track","ja": "MP4 ではこのコーデックをそのまま保持できません。MKV を選ぶか、このトラックを除外してください"},+ {+ "zh": "MaxCLL (nit)",+ "src": "qml/Veyra/ProPage.qml",+ "zh-TW": "MaxCLL (nit)",+ "en": "MaxCLL (nit)",+ "ja": "MaxCLL (nit)"+ },+ {+ "zh": "MaxFALL (nit)",+ "src": "qml/Veyra/ProPage.qml",+ "zh-TW": "MaxFALL (nit)",+ "en": "MaxFALL (nit)",+ "ja": "MaxFALL (nit)"+ },{"zh": "NGX 核心","src": "include/veyra/engine/BackendRecovery.h",@@ -1827,6 +1897,13 @@"en": "Don't keep","ja": "保持しない"},+ {+ "zh": "不做任何改动,交给显示器和片源本身。",+ "src": "qml/Veyra/ProPage.qml",+ "zh-TW": "不做任何改动,交给显示器和片源本身。",+ "en": "Changes nothing; the display and the source decide.",+ "ja": "Changes nothing; the display and the source decide."+ },{"zh": "不可用","src": "src/ui/QmlPlayerBridge.cpp",@@ -1967,6 +2044,13 @@"en": "Mid gray","ja": "ミッドグレー"},+ {+ "zh": "中灰 (nit)",+ "src": "qml/Veyra/ProPage.qml",+ "zh-TW": "中灰 (nit)",+ "en": "Mid-gray (nit)",+ "ja": "中間調 (nit)"+ },{"zh": "中间调","src": "qml/ColourPanel.qml",@@ -3473,6 +3557,13 @@"en": "Native HDR input; no SDR-to-HDR needed","ja": "ネイティブ HDR 入力。SDR→HDR 変換は不要です"},+ {+ "zh": "原生 HDR 输入;「HDR 片源转换」未开启",+ "src": "src/engine/EngineController.cpp",+ "zh-TW": "原生 HDR 輸入;「HDR 片源轉換」未開啟",+ "en": "Native HDR input; \"Convert HDR sources too\" is off",+ "ja": "ネイティブ HDR 入力;「HDR ソースも変換」はオフです"+ },{"zh": "原生 · SDR","src": "src/source/CaptureCardSource.cpp",@@ -3669,6 +3760,13 @@"en": "Removes only this host from this PC; you will need to pair again later","ja": "この PC に保存したこのホストだけを削除します。次回は再ペアリングが必要です"},+ {+ "zh": "只在这个亮度以下的暗部生效",+ "src": "qml/Veyra/ProPage.qml",+ "zh-TW": "只在這個亮度以下的暗部生效",+ "en": "Only shadows below this level are lifted",+ "ja": "この輝度以下の暗部にのみ効く"+ },{"zh": "只有节点模式使用编辑连接","src": "src/engine/EffectChain.cpp",@@ -3676,6 +3774,13 @@"en": "Only node mode uses edit connections","ja": "接続の編集はノードモードでのみ使います"},+ {+ "zh": "只清空这个列表,不会删除文件。",+ "src": "qml/HomePage.qml",+ "zh-TW": "只清空這個列表,不會刪除檔案。",+ "en": "Only clears this list; no file is deleted.",+ "ja": "このリストだけを消去します。ファイルは削除されません。"+ },{"zh": "只用 DLSS / XeSS 补帧时:到 NVIDIA App 关闭 Smooth Motion。","src": "qml/SettingsPage.qml",@@ -4432,6 +4537,13 @@"en": "Mix multichannel sources down to stereo (headphones); when off, channels follow the device layout","ja": "マルチチャンネルのソースをステレオにまとめて出力(ヘッドホン向け)。オフ時はデバイスのチャンネル配置に従います"},+ {+ "zh": "夜里关灯看:柔和一点,同时保留暗部细节。",+ "src": "qml/Veyra/ProPage.qml",+ "zh-TW": "夜里关灯看:柔和一点,同时保留暗部细节。",+ "en": "Watching at night with the lights off: softer overall while keeping shadow detail.",+ "ja": "Watching at night with the lights off: softer overall while keeping shadow detail."+ },{"zh": "大","src": "qml/SettingsPage.qml",@@ -5237,6 +5349,13 @@"en": "Peak ","ja": "ピーク "},+ {+ "zh": "峰值上限 (nit)",+ "src": "qml/Veyra/ProPage.qml",+ "zh-TW": "峰值上限 (nit)",+ "en": "Peak cap (nit)",+ "ja": "ピーク上限 (nit)"+ },{"zh": "峰值亮度 (nit)","src": "qml/NodePage.qml",@@ -5377,6 +5496,13 @@"en": "Wake request sent; connect once the PS5 has started.","ja": "起動要求を送信しました。PS5 が起動してから接続します。"},+ {+ "zh": "已发送给显示器",+ "src": "qml/Veyra/ProPage.qml",+ "zh-TW": "已傳送給顯示器",+ "en": "Sent to the display",+ "ja": "表示機器へ送信中"+ },{"zh": "已取消 · 可重新开始","src": "qml/ExportPage.qml",@@ -5951,6 +6077,20 @@"en": "Force linear PCM","ja": "リニア PCM を強制"},+ {+ "zh": "强化冲击",+ "src": "qml/Veyra/ProPage.qml",+ "zh-TW": "强化冲击",+ "en": "More punch",+ "ja": "More punch"+ },+ {+ "zh": "强度",+ "src": "qml/Veyra/ProPage.qml",+ "zh-TW": "强度",+ "en": "Strength",+ "ja": "Strength"+ },{"zh": "强度 ","src": "qml/DialogHost.qml",@@ -6504,6 +6644,20 @@"en": "Use a window or a whole display as the source","ja": "ウィンドウまたはディスプレイ全体をソースにする"},+ {+ "zh": "把内容峰值告诉显示器",+ "src": "qml/Veyra/ProPage.qml",+ "zh-TW": "把內容峰值告訴顯示器",+ "en": "Tells the display the content peak",+ "ja": "コンテンツのピークを表示機器に傳える"+ },+ {+ "zh": "把内容峰值告诉显示器,让它的动态色调映射有依据。",+ "src": "qml/Veyra/ProPage.qml",+ "zh-TW": "把內容峰值告訴顯示器,讓它的動態色調映射有依據。",+ "en": "Tells the display what the content peak is, so its dynamic tone mapping has something to work from.",+ "ja": "コンテンツのピークを表示機器に傳え、動的トーンマッピングの判斷材料にする。"+ },{"zh": "把当前设置另存为预设…","src": "qml/NodePage.qml",@@ -6532,6 +6686,13 @@"en": "Anti-flicker level","ja": "ちらつき防止のレベル"},+ {+ "zh": "抬升范围 (nit)",+ "src": "qml/Veyra/ProPage.qml",+ "zh-TW": "抬升範圍 (nit)",+ "en": "Lift range (nit)",+ "ja": "持ち上げ範圍 (nit)"+ },{"zh": "拉伸铺满","src": "qml/ProPage.qml",@@ -7198,6 +7359,13 @@"en": "Luminance","ja": "明るさ"},+ {+ "zh": "明亮环境",+ "src": "qml/Veyra/ProPage.qml",+ "zh-TW": "明亮环境",+ "en": "Bright room",+ "ja": "Bright room"+ },{"zh": "明度变化","src": "qml/NrLayerEditor.qml",@@ -7373,6 +7541,13 @@"en": "Show playback bar","ja": "再生バーを表示"},+ {+ "zh": "显示设备峰值 (nit)",+ "src": "qml/Veyra/ProPage.qml",+ "zh-TW": "显示设备峰值 (nit)",+ "en": "Display peak (nit)",+ "ja": "Display peak (nit)"+ },{"zh": "显示队列控制不可用 · ","src": "src/engine/VideoPresenter.cpp",@@ -7436,6 +7611,13 @@"en": "No color presets yet","ja": "カラープリセットはまだありません"},+ {+ "zh": "暗亮双修",+ "src": "qml/Veyra/ProPage.qml",+ "zh-TW": "暗亮双修",+ "en": "Dark + bright",+ "ja": "Dark + bright"+ },{"zh": "暗化变化","src": "qml/NrLayerEditor.qml",@@ -7443,6 +7625,41 @@"en": "Darkening change","ja": "暗くなる変化"},+ {+ "zh": "暗场很暗、亮场又很亮的片子:两头都照顾。",+ "src": "qml/Veyra/ProPage.qml",+ "zh-TW": "暗场很暗、亮场又很亮的片子:两头都照顾。",+ "en": "Films that are dark in places and very bright in others: handles both ends.",+ "ja": "Films that are dark in places and very bright in others: handles both ends."+ },+ {+ "zh": "暗场提亮",+ "src": "qml/Veyra/ProPage.qml",+ "zh-TW": "暗场提亮",+ "en": "Lift dark scenes",+ "ja": "Lift dark scenes"+ },+ {+ "zh": "暗室观影",+ "src": "qml/Veyra/ProPage.qml",+ "zh-TW": "暗室观影",+ "en": "Dark room",+ "ja": "Dark room"+ },+ {+ "zh": "暗调片、夜景多的剧集:只抬暗部,亮部不受影响。",+ "src": "qml/Veyra/ProPage.qml",+ "zh-TW": "暗调片、夜景多的剧集:只抬暗部,亮部不受影响。",+ "en": "Dark films and night-heavy series: lifts the shadows only; the highlights are untouched.",+ "ja": "Dark films and night-heavy series: lifts the shadows only; the highlights are untouched."+ },+ {+ "zh": "暗部抬升 (0.01 EV)",+ "src": "qml/Veyra/ProPage.qml",+ "zh-TW": "暗部抬升 (0.01 EV)",+ "en": "Shadow lift (0.01 EV)",+ "ja": "シャドウ持ち上げ (0.01 EV)"+ },{"zh": "曝光(EV)","src": "src/ui/QmlPlayerBridge.cpp",@@ -8437,6 +8654,13 @@"en": "Residual","ja": "残差"},+ {+ "zh": "母版峰值 (nit)",+ "src": "qml/Veyra/ProPage.qml",+ "zh-TW": "母版峰值 (nit)",+ "en": "Mastering peak (nit)",+ "ja": "マスタリングピーク (nit)"+ },{"zh": "比较源画面与上一帧:没有明显变化的像素沿用上一帧输出,明显变化的位置直接用新结果。","src": "qml/ProPage.qml",@@ -8654,6 +8878,13 @@"en": "Clear","ja": "クリア"},+ {+ "zh": "清空最近播放记录?",+ "src": "qml/HomePage.qml",+ "zh-TW": "清空最近播放記錄?",+ "en": "Clear the recent list?",+ "ja": "最近再生した記録を消去しますか?"+ },{"zh": "清空等待","src": "qml/ExportPage.qml",@@ -8752,6 +8983,13 @@"en": "Slider keyboard step","ja": "スライダーのキー操作の刻み"},+ {+ "zh": "滚降强度 (%)",+ "src": "qml/Veyra/ProPage.qml",+ "zh-TW": "滾降強度 (%)",+ "en": "Roll-off strength (%)",+ "ja": "壓縮の強さ (%)"+ },{"zh": "点一下滑块后用 ← → 调整,每次的幅度;Esc 或单击画面交还方向键给快进快退","src": "qml/SettingsPage.qml",@@ -8920,6 +9158,13 @@"en": "Picture interrupted; requesting a keyframe to recover…","ja": "映像が途切れました。キーフレームを要求して復旧中…"},+ {+ "zh": "画面偏灰、平淡的老片或转制片:提高对比观感。",+ "src": "qml/Veyra/ProPage.qml",+ "zh-TW": "画面偏灰、平淡的老片或转制片:提高对比观感。",+ "en": "Flat or washed-out older and remastered titles: adds contrast.",+ "ja": "Flat or washed-out older and remastered titles: adds contrast."+ },{"zh": "画面呈现失败","src": "src/engine/EngineController.cpp",@@ -9074,6 +9319,13 @@"en": "Sign-in was refused.","ja": "サインインが拒否されました。"},+ {+ "zh": "白天或亮环境看片:整体提亮一些。",+ "src": "qml/Veyra/ProPage.qml",+ "zh-TW": "白天或亮环境看片:整体提亮一些。",+ "en": "Watching in daylight or a bright room: brightens the picture overall.",+ "ja": "Watching in daylight or a bright room: brightens the picture overall."+ },{"zh": "白色","src": "src/ui/QmlPlayerBridge.cpp",@@ -9354,6 +9606,13 @@"en": "Timed out waiting for the output texture to be released","ja": "出力テクスチャの解放待ちがタイムアウトしました"},+ {+ "zh": "等比例缩放这一档的效果;100% = 档位原值",+ "src": "qml/Veyra/ProPage.qml",+ "zh-TW": "等比例缩放这一档的效果;100% = 档位原值",+ "en": "Scales the whole preset; 100% = the preset as written",+ "ja": "Scales the whole preset; 100% = the preset as written"+ },{"zh": "等线","src": "qml/DialogHost.qml",@@ -9438,6 +9697,13 @@"en": "The system does not support Windows Graphics Capture","ja": "このシステムは Windows Graphics Capture に対応していません"},+ {+ "zh": "系统报告:峰值 %1、全屏 %2、黑位 %3 nit",+ "src": "qml/Veyra/ProPage.qml",+ "zh-TW": "系统报告:峰值 %1、全屏 %2、黑位 %3 nit",+ "en": "Reported: peak %1, full-frame %2, black %3 nit",+ "ja": "Reported: peak %1, full-frame %2, black %3 nit"+ },{"zh": "系统硬件编码 H.264({})","src": "src/sink/MfVideoEncoder.cpp",@@ -9816,6 +10082,13 @@"en": "Custom cap (FPS)","ja": "カスタム上限(FPS)"},+ {+ "zh": "自定义:已用下面的滑块微调过。",+ "src": "qml/Veyra/ProPage.qml",+ "zh-TW": "自定义:已用下面的滑块微调过。",+ "en": "Custom: adjusted with the sliders below.",+ "ja": "Custom: adjusted with the sliders below."+ },{"zh": "自然饱和度","src": "src/ui/QmlPlayerBridge.cpp",@@ -12413,6 +12686,20 @@"en": "Restart required","ja": "再起動が必要です"},+ {+ "zh": "静态曲线:抬暗部、定中灰、压高光",+ "src": "qml/Veyra/ProPage.qml",+ "zh-TW": "靜態曲線:抬暗部、定中灰、壓高光",+ "en": "Static curve: shadows lifted, mid-gray set, highlights rolled off",+ "ja": "靜的曲線:暗部を持ち上げ、中間調を決め、ハイライトを壓縮"+ },+ {+ "zh": "静态曲线:抬暗部、定中灰、压高光。不随场景变化,不会呼吸。",+ "src": "qml/Veyra/ProPage.qml",+ "zh-TW": "靜態曲線:抬暗部、定中灰、壓高光。不隨場景變化,不會呼吸。",+ "en": "Static curve: lifts the shadows, sets the mid-gray, rolls off the highlights. It never follows the scene, so the picture cannot breathe.",+ "ja": "靜的曲線:暗部を持ち上げ、中間調を決め、ハイライトを壓縮。シーンに追従しない。"+ },{"zh": "静态最稳、光流为默认、低频保留高频细节","src": "qml/NrLayerEditor.qml",@@ -13239,6 +13526,27 @@"en": "Highlights","ja": "ハイライト"},+ {+ "zh": "高光保护",+ "src": "qml/Veyra/ProPage.qml",+ "zh-TW": "高光保护",+ "en": "Protect highlights",+ "ja": "Protect highlights"+ },+ {+ "zh": "高光很亮的片子(雪景/爆炸/演唱会):压住顶部,暗部不动。",+ "src": "qml/Veyra/ProPage.qml",+ "zh-TW": "高光很亮的片子(雪景/爆炸/演唱会):压住顶部,暗部不动。",+ "en": "Films with very bright highlights (snow, explosions, concerts): rolls off the top end and leaves the shadows alone.",+ "ja": "Films with very bright highlights (snow, explosions, concerts): rolls off the top end and leaves the shadows alone."+ },+ {+ "zh": "高光起点 (nit)",+ "src": "qml/Veyra/ProPage.qml",+ "zh-TW": "高光起點 (nit)",+ "en": "Highlight start (nit)",+ "ja": "ハイライト開始點 (nit)"+ },{"zh": "高延迟·需 CPU 拆包","src": "include/veyra/source/CaptureFormatRank.h",diff --git a/include/veyra/engine/EffectChain.h b/include/veyra/engine/EffectChain.hindex 77669c0d..64c05429 100644--- a/include/veyra/engine/EffectChain.h+++ b/include/veyra/engine/EffectChain.h@@ -200,6 +200,9 @@ struct ChainGlobalSettings {pipeline::NrSizePolicy nrPolicy = pipeline::NrSizePolicy::Realtime;HdrOutputMode hdrOutputMode=HdrOutputMode::Hdr10;MotionSource fgMotion=MotionSource::Automatic,srMotion=MotionSource::OpticalFlow,nrMotion=MotionSource::OpticalFlow;+ // Custom: static HDR output tuning, carried so a session can persist it.+ HdrCurveSettings hdrCurve;+ HdrMetadataSettings hdrMetadata;static ChainGlobalSettings capture(const EnhancementSettings&);void apply(EnhancementSettings&) const;bool operator==(const ChainGlobalSettings&) const = default;diff --git a/include/veyra/engine/EnhancementSettings.h b/include/veyra/engine/EnhancementSettings.hindex 32ea881e..9cf6a86e 100644--- a/include/veyra/engine/EnhancementSettings.h+++ b/include/veyra/engine/EnhancementSettings.h@@ -1,5 +1,6 @@#pragma once#include "veyra/engine/VideoHdrSettings.h"+#include "veyra/engine/HdrOutputTuning.h"#include <cmath>#include <array>#include <cstdint>@@ -239,6 +240,10 @@ struct EnhancementSettings {MotionSource srMotion=MotionSource::OpticalFlow;MotionSource nrMotion=MotionSource::OpticalFlow;VideoHdrSettings videoHdr;+ // Custom: static HDR output tuning (see HdrOutputTuning.h). Both blocks are+ // live: the curve reaches the present blit and the metadata the display.+ HdrCurveSettings hdrCurve;+ HdrMetadataSettings hdrMetadata;bool useHdrPreview(bool hdrInput,bool hdrDisplayActive)const{return (hdrInput||videoHdr.enabled)&&hdrDisplayActive&&!forceSdrPreview;}pipeline::SrTarget srTarget=pipeline::SrTarget::Uhd4K;uint32_t videoSrQuality=0; // 0 DLSS SR; 1–4 RTX Video SR@@ -311,6 +316,8 @@ struct EnhancementSettings {if(hdrOutputMode<HdrOutputMode::Hdr10||hdrOutputMode>HdrOutputMode::ScRgb)return "invalid HDR output mode";for(auto source:{fgMotion,srMotion,nrMotion})if(source<MotionSource::Zero||source>MotionSource::Automatic)return "invalid motion source";if(!videoHdr.valid())return "invalid RTX Video HDR parameters";+ if(!hdrCurve.valid())return "invalid HDR curve parameters";+ if(!hdrMetadata.valid())return "invalid HDR metadata parameters";auto range=[](float v,float hi){return std::isfinite(v)&&v>=0&&v<=hi;};if(auto error=protection.validate();!error.empty())return error;if(!revision)return "settingsRevision must be nonzero";diff --git a/include/veyra/engine/GraphDescription.h b/include/veyra/engine/GraphDescription.hindex 06412aac..a97fac27 100644--- a/include/veyra/engine/GraphDescription.h+++ b/include/veyra/engine/GraphDescription.h@@ -95,6 +95,9 @@ inline pipeline::ResolutionPlan describeStages(const StageRequest& request,constdesc.additionalColors=settings.additionalColors;desc.additionalColorCount=settings.additionalColorCount;desc.videoHdr=settings.videoHdr;+ // Custom: static HDR output tuning (present blit curve + display metadata).+ desc.hdrCurve=settings.hdrCurve;+ desc.hdrMetadata=settings.hdrMetadata;desc.hdrOutputMode=settings.hdrOutputMode;desc.fgMotion=settings.fgMotion;desc.srMotion=settings.srMotion;desc.nrMotion=settings.nrMotion;desc.settingsRevision=settings.revision;diff --git a/include/veyra/engine/HdrOutputTuning.h b/include/veyra/engine/HdrOutputTuning.hnew file mode 100644index 00000000..e912ce9a--- /dev/null+++ b/include/veyra/engine/HdrOutputTuning.h@@ -0,0 +1,216 @@+#pragma once++#include <algorithm>+#include <cmath>+#include <cstddef>+#include <cstdint>+#include <cstring>++// Custom: static HDR output tuning for the native HDR path.+//+// Three layers, all deliberately STATIC (nothing follows the scene, so the picture+// can never breathe):+//+// HdrCurveSettings a fixed brightness curve: lift the shadows without+// touching the highlights, move the mid-gray reference,+// and roll off (or cap) the top end. A single exposure+// cannot do this - it scales shadows and highlights by the+// same factor, which is exactly the "dark scenes need a+// lift but that blows out the bright ones" problem.+// HdrMetadataSettings the HDR10 static metadata the display receives. Most+// displays run their own dynamic tone mapping; without+// metadata they have to guess the content peak, and a+// lower reported mastering peak makes many of them map the+// picture brighter overall.+// presets one-click combinations of the two, optionally re-scaled+// for the actual display (peak nits) and by a single+// "strength" dial.+//+// Everything defaults to "no change": the curve is disabled, the strength is 100%+// and every metadata field says "follow the source", so an untouched install+// renders exactly as before.++namespace veyra::engine {++struct HdrCurveSettings {+ bool enabled=false;+ // Shadow lift in 1/100 EV, applied only below `shadowRangeNits` (the weight+ // falls to zero there), so highlights are untouched by construction.+ int shadowLiftEv100=0; // -200..200+ // Upper bound of the lift's influence, in nits.+ unsigned shadowRangeNits=10; // 1..100+ // Mid-gray reference in nits. 203 is the BT.2408 SDR reference white and is+ // neutral; raising it brightens the picture while the peak stays put (the+ // curve is a gamma around the peak, not a scale).+ unsigned midGrayNits=203; // 100..500+ // Where the highlight roll-off starts (nits). 0 disables the roll-off.+ unsigned highlightStartNits=0; // 0 or 100..2000+ // How hard the roll-off compresses: 100 = the default knee, higher = softer.+ unsigned rollOffPercent=100; // 10..200+ // Hard ceiling in nits. 0 disables it. Also anchors the mid-gray gamma.+ unsigned peakCapNits=0; // 0 or 100..4000+ // NOTE: every field above is the BASELINE. The dial and the display peak below+ // are stored next to it, and the engine resolves baseline + dial + peak into+ // the numbers it actually applies (resolveHdrTuning). Keeping "which preset you+ // picked" separate from "how hard you turned it" is what lets the dial move+ // without the UI falling back to "custom", and lets the sliders stay useful as+ // the baseline they are edited against.+ //+ // One dial for the whole curve: 100% applies the baseline as it is, 0% fades+ // the curve back to "no change", 200% doubles its effect.+ unsigned strengthPercent=100; // 0..200+ // The display's own peak brightness in nits, used to re-scale the presets'+ // highlight-related numbers (see resolveHdrTuning). 0 = ask the system.+ unsigned displayPeakNits=0; // 0 or 100..10000++ bool operator==(const HdrCurveSettings&) const = default;+ bool valid() const {+ return shadowLiftEv100>=-200 && shadowLiftEv100<=200 &&+ shadowRangeNits>=1 && shadowRangeNits<=100 &&+ midGrayNits>=100 && midGrayNits<=500 &&+ (highlightStartNits==0 || (highlightStartNits>=100 && highlightStartNits<=2000)) &&+ rollOffPercent>=10 && rollOffPercent<=200 &&+ (peakCapNits==0 || (peakCapNits>=100 && peakCapNits<=4000)) &&+ strengthPercent<=200 &&+ (displayPeakNits==0 || (displayPeakNits>=100 && displayPeakNits<=10000));+ }+};++struct HdrMetadataSettings {+ // Send HDR10 static metadata to the display. Off leaves the display with+ // whatever it can infer from the picture itself.+ bool enabled=true;+ // All four are 0 = "use the source's own value"; a non-zero value overrides+ // it. MaxCLL/MaxFALL are capped at 65535 because the DXGI structure stores+ // them in 16 bits.+ unsigned masteringPeakNits=0; // 0 or 100..10000+ unsigned maxCllNits=0; // 0 or 1..10000+ unsigned maxFallNits=0; // 0 or 1..10000+ // Mastering black, in 0.0001 nit units (DXGI's unit). Default 0.005 nit.+ unsigned masteringMinNitsX10000=50;++ bool operator==(const HdrMetadataSettings&) const = default;+ bool valid() const {+ return (masteringPeakNits==0 || (masteringPeakNits>=100 && masteringPeakNits<=10000)) &&+ (maxCllNits==0 || (maxCllNits>=1 && maxCllNits<=10000)) &&+ (maxFallNits==0 || (maxFallNits>=1 && maxFallNits<=10000)) &&+ masteringMinNitsX10000<=1000000;+ }+};++// One-click presets: each entry sets the curve and the metadata together. The ids+// are stable (the UI maps them to translated labels); a UI value that matches no+// entry is reported as "custom".+//+// The highlight numbers are written for a 1000 nit display and are re-scaled by+// the display's own peak (resolveHdrTuning), which is what turns "highlight+// protection" from a guess into a calculation. The shadow and mid-gray numbers are+// deliberately NOT scaled: they describe the content and the viewing environment,+// not the display's ceiling.+struct HdrTuningPreset {+ const char* id;+ HdrCurveSettings curve;+ HdrMetadataSettings metadata;+};++inline constexpr HdrTuningPreset kHdrTuningPresets[] = {+ // id enabled lift range mid start roll cap metaOn peak cll fall min+ {"standard", {false, 0, 10, 203, 0, 100, 0}, {true, 0, 0, 0, 50}},+ {"darkLift", {true, 50, 35, 225, 0, 100, 0}, {true, 700, 800, 350, 50}},+ {"highlightGuard", {true, 0, 10, 203, 450, 120,1000}, {true, 1000, 1000, 400, 50}},+ {"darkAndBright", {true, 50, 35, 220, 450, 120,1000}, {true, 700, 800, 350, 50}},+ {"brightRoom", {true, 30, 30, 250, 0, 100, 0}, {true, 0, 0, 0, 50}},+ {"darkRoom", {true, 40, 35, 185, 600, 130, 800}, {true, 600, 700, 300, 50}},+ {"punch", {true, 0, 10, 175, 450, 110,1200}, {true, 0, 0, 0, 50}},+};+inline constexpr std::size_t kHdrTuningPresetCount = sizeof(kHdrTuningPresets) / sizeof(kHdrTuningPresets[0]);++// The peak the presets are authored against.+inline constexpr unsigned kHdrPresetReferencePeakNits = 1000;++inline const HdrTuningPreset* findHdrTuningPreset(const char* id) {+ if (!id) return nullptr;+ for (std::size_t i = 0; i < kHdrTuningPresetCount; ++i)+ if (std::strcmp(kHdrTuningPresets[i].id, id) == 0) return &kHdrTuningPresets[i];+ return nullptr;+}++// Does the stored baseline still match this preset? The strength dial and the+// display peak are deliberately ignored: they only scale the baseline when it is+// applied, so moving either of them keeps you on the same preset. Editing the+// baseline sliders is what moves the UI to "custom".+inline bool hdrPresetMatches(const HdrCurveSettings& curve, const HdrMetadataSettings& metadata,+ const HdrTuningPreset& preset) {+ HdrCurveSettings c = curve;+ c.strengthPercent = preset.curve.strengthPercent;+ c.displayPeakNits = preset.curve.displayPeakNits;+ return c == preset.curve && metadata == preset.metadata;+}++// Turn "preset + strength + display peak" into the settings the engine applies.+//+// Two steps, in this order:+// 1. Peak scaling: the preset's highlight numbers are authored for a 1000 nit+// display, so they are scaled by `displayPeakNits / 1000`. A 600 nit display+// starts rolling off earlier and caps lower; a 2000 nit display gets to use+// brightness the preset would otherwise have thrown away. 0 = leave them.+// 2. Strength: everything that has a neutral value is interpolated towards it+// (lift, range -> 0; mid-gray -> 203; roll-off -> 100), and the roll-off start+// moves inversely because a *lower* start means a *stronger* effect. The hard+// cap is a protection value, so it does not follow the dial.+inline void resolveHdrTuning(const HdrCurveSettings& base, const HdrMetadataSettings& baseMetadata,+ HdrCurveSettings& curve, HdrMetadataSettings& metadata) {+ curve = base;+ metadata = baseMetadata;+ const unsigned strengthPercent = base.strengthPercent;+ const unsigned displayPeakNits = base.displayPeakNits;++ // 1) display peak+ if (displayPeakNits > 0) {+ const double scale = double(displayPeakNits) / double(kHdrPresetReferencePeakNits);+ const auto scaleNits = [scale](unsigned v, unsigned lo, unsigned hi) {+ if (v == 0) return 0u;+ const auto scaled = unsigned(std::lround(double(v) * scale));+ return std::clamp(scaled, lo, hi);+ };+ curve.highlightStartNits = scaleNits(curve.highlightStartNits, 100u, 2000u);+ curve.peakCapNits = scaleNits(curve.peakCapNits, 100u, 4000u);+ metadata.masteringPeakNits = scaleNits(metadata.masteringPeakNits, 100u, 10000u);+ if (metadata.maxCllNits) metadata.maxCllNits = scaleNits(metadata.maxCllNits, 1u, 10000u);+ if (metadata.maxFallNits) metadata.maxFallNits = scaleNits(metadata.maxFallNits, 1u, 10000u);+ }++ // 2) strength+ const double k = double(curve.strengthPercent) / 100.0;+ if (curve.enabled && k <= 0.001) {+ curve.enabled = false; // faded all the way out+ return;+ }+ if (k == 1.0) return;++ const auto blend = [k](int base, int neutral) {+ return int(std::lround(double(neutral) + double(base - neutral) * k));+ };+ curve.shadowLiftEv100 = std::clamp(blend(curve.shadowLiftEv100, 0), -200, 200);+ curve.shadowRangeNits = static_cast<unsigned>(std::clamp(int(std::lround(double(curve.shadowRangeNits) * k)), 1, 100));+ curve.midGrayNits = static_cast<unsigned>(std::clamp(blend(int(curve.midGrayNits), 203), 100, 500));+ curve.rollOffPercent = static_cast<unsigned>(std::clamp(blend(int(curve.rollOffPercent), 100), 10, 200));+ if (curve.highlightStartNits) {+ // A lower start compresses more, so strength scales it inversely.+ curve.highlightStartNits = static_cast<unsigned>(+ std::clamp(int(std::lround(double(curve.highlightStartNits) / k)), 100, 2000));+ }+}++// Convenience overload: resolve a preset as the baseline, overriding the dial and+// the display peak (used by the tests and by anything that starts from a preset).+inline void resolveHdrTuning(const HdrTuningPreset& preset, unsigned strengthPercent,+ unsigned displayPeakNits, HdrCurveSettings& curve,+ HdrMetadataSettings& metadata) {+ HdrCurveSettings base = preset.curve;+ base.strengthPercent = std::min(200u, strengthPercent);+ base.displayPeakNits = displayPeakNits;+ resolveHdrTuning(base, preset.metadata, curve, metadata);+}++} // namespace veyra::enginediff --git a/include/veyra/engine/PresetLibrary.h b/include/veyra/engine/PresetLibrary.hindex 6eec23e7..70264bc8 100644--- a/include/veyra/engine/PresetLibrary.h+++ b/include/veyra/engine/PresetLibrary.h@@ -100,8 +100,12 @@ public:bool importLegacy(const std::vector<PresetEntry>& entries);private:friend class ChainSessionStore;+ // `maxVersion` is separate from `preserveLegacy` on purpose: the chain session+ // needs the legacy chain handling (no migration) but must still accept the+ // library versions that carry settings the session itself writes. 0 keeps the+ // original per-context cap.static bool parse(const std::string& data, std::vector<PresetEntry>& out, std::wstring& def, std::wstring& error,- bool* migrated = nullptr, bool preserveLegacy = false);+ bool* migrated = nullptr, bool preserveLegacy = false, int maxVersion = 0);std::string serialize() const;static std::string encodeEntries(const std::vector<PresetEntry>& entries, const std::wstring& defaultName, int minimumVersion = 1);void addBuiltins();diff --git a/include/veyra/engine/VideoPresenter.h b/include/veyra/engine/VideoPresenter.hindex eb5b35b1..33232913 100644--- a/include/veyra/engine/VideoPresenter.h+++ b/include/veyra/engine/VideoPresenter.h@@ -1,6 +1,7 @@#pragma once#include "veyra/diagnostics/GpuTimer.h"#include "veyra/gfx/PresentSink.h"+#include <dxgi1_6.h> // DXGI_HDR_METADATA_HDR10 (custom: HDR static metadata)#include "veyra/pipeline/GpuPassUtils.h"#include "veyra/engine/PreviewView.h"#include "veyra/gfx/CommandSlotRing.h"@@ -66,6 +67,15 @@ public:std::vector<diagnostics::GpuFrameTiming> takeGpuTimings(ID3D12Fence* fence){gpuTimer_.collect(presentationFence_?presentationFence_.Get():fence);return gpuTimer_.takeCompleted();}void recordGpuTimings(){gpuTimer_.recordCompleted();}private:+ // Custom: HDR10 static metadata for the display (MaxCLL / MaxFALL / mastering+ // peak). Sent only when it changes, and cleared when the HDR10 path stops.+ void applyHdrMetadata(pipeline::EnhanceGraph& graph);+ bool metadataSent_=false;+ // The source's mastering/CLL values are absent on many frames; holding the last+ // real value keeps the reported metadata steady instead of flapping to the+ // fallback (which re-sent it on nearly every frame).+ float stickyMasteringPeak_=0.0f,stickyMaxCll_=0.0f,stickyMaxFall_=0.0f;+ DXGI_HDR_METADATA_HDR10 lastMetadata_{};gfx::ReflexSession reflex_;uint64_t reflexFrame_=0,generation_=0;bool providerOwnedPresentation_=false;diff --git a/include/veyra/gfx/PresentSink.h b/include/veyra/gfx/PresentSink.hindex 292c1112..33db8e1b 100644--- a/include/veyra/gfx/PresentSink.h+++ b/include/veyra/gfx/PresentSink.h@@ -32,6 +32,16 @@ public:// on the graph owner every 2 s under HDR (sweep 2026-09-22 A1).static std::optional<bool> queryHdrDisplayActive(HWND,HMONITOR* queriedMonitor=nullptr);static double displayRefreshFps(HWND);+ // Custom: what the panel itself reports through DXGI. Used to default the HDR+ // tuning's display peak ("0 = ask the system") and to show the user the values+ // the system claims, so a wrong guess can be corrected by hand.+ struct DisplayPeakInfo {+ unsigned peakNits = 0; // small-area peak+ unsigned fullFrameNits = 0; // sustained full-screen+ double minNits = 0.0; // black level+ bool valid = false;+ };+ static DisplayPeakInfo queryDisplayPeak(HWND);PresentSink() = default;~PresentSink();@@ -120,6 +130,9 @@ public:bool tearingSupported() const { return tearingSupported_; }HWND hwnd() const { return hwnd_; }IDXGISwapChain3* swapChain() const { return swapChain_.Get(); }+ // Custom: HDR10 static metadata lives on IDXGISwapChain4. Queried lazily and+ // re-queried whenever the swap chain is recreated; null when unsupported.+ IDXGISwapChain4* swapChain4();XessPresenter* xess() const { return xess_.get(); }bool xessFailed() const { return xessFailed_; }@@ -159,6 +172,7 @@ private:ID3D12CommandQueue* queue_ = nullptr;ComPtr<IDXGIFactory2> factory_;ComPtr<IDXGISwapChain3> swapChain_;+ ComPtr<IDXGISwapChain4> swapChain4_; // custom: cached QI for SetHDRMetaDatastd::unique_ptr<XessPresenter> xess_;ComPtr<ID3D12Resource> backBuffers_[3];UINT backBufferIndex_ = 0;diff --git a/include/veyra/pipeline/EnhanceGraph.h b/include/veyra/pipeline/EnhanceGraph.hindex 50ed80af..ca658c65 100644--- a/include/veyra/pipeline/EnhanceGraph.h+++ b/include/veyra/pipeline/EnhanceGraph.h@@ -8,6 +8,7 @@#include "veyra/pipeline/ResolutionPlan.h"#include "veyra/pipeline/NrTemporalPass.h"#include "veyra/pipeline/NrHoldPass.h"+#include "veyra/pipeline/FramePacket.h" // ColorDescription, for the HDR display metadata// EnhanceGraph - the real unified processing graph (Playbook R3.2).// Chains, per real frame:@@ -102,8 +103,15 @@ struct EnhanceGraphDesc {bool srUsesFlow()const{return engine::motionUsesFlow(srMotion);}bool nrUsesFlow()const{return engine::motionUsesFlow(nrMotion);}engine::VideoHdrSettings videoHdr;+ // Custom: static HDR output tuning (see HdrOutputTuning.h). Both blocks are+ // live: the curve reaches the present blit, the metadata the display.+ engine::HdrCurveSettings hdrCurve;+ engine::HdrMetadataSettings hdrMetadata;+ // RTX Video HDR is an SDR -> HDR stage: it only ever runs for an SDR input,+ // and an HDR source keeps the native HDR path (HDR10 / Dolby Vision) instead of+ // being tone-mapped down first.bool hdrWorking() const {return hdrInput&&hdrOutput;}- bool convertVideoHdr() const {return videoHdr.enabled&&!hdrInput&&hdrOutput;}+ bool convertVideoHdr() const {return videoHdr.enabled&&hdrOutput&&!hdrInput;}bool highQualityPresentation = false; // PS5 ordinary scaling, no AI SRbool rgbInput = false; // allocate direct RGBA ingestion before NGX creationbool yuy2Input = false; // packed Y0 U Y1 V -> linear FP16; never subsample to NV12@@ -511,6 +519,13 @@ public:bool fgEnabled() const { return fgEnabled_; }bool hdrOutput() const { return desc_.hdrOutput; }bool videoHdrActive() const {return desc_.convertVideoHdr();}+ // Custom: static HDR output tuning. The curve is read by the present blit,+ // the metadata is sent to the display.+ const engine::HdrCurveSettings& hdrCurve() const {return desc_.hdrCurve;}+ const engine::HdrMetadataSettings& hdrMetadata() const {return desc_.hdrMetadata;}+ // Colour description of the frame in flight, so the display metadata can fall+ // back to the source's own MaxCLL / MaxFALL / mastering peak.+ const pipeline::ColorDescription& sourceColor() const {return lastSourceColor_;}bool hdr10Output() const { return desc_.hdrOutput && (desc_.enableFg||desc_.hdrOutputMode==engine::HdrOutputMode::Hdr10); }DXGI_FORMAT outputFormat() const { return hdr10Output()?DXGI_FORMAT_R10G10B10A2_UNORM:desc_.hdrOutput?DXGI_FORMAT_R16G16B16A16_FLOAT:DXGI_FORMAT_R8G8B8A8_UNORM; }bool highQualityPresentation() const { return desc_.highQualityPresentation; }@@ -793,6 +808,7 @@ private:uint32_t diagnosticFlowPerf_=~0u;std::vector<uint8_t> lumaSample_;std::vector<double> lumaHistogram_=std::vector<double>(256,0.0);+ pipeline::ColorDescription lastSourceColor_{};double prevPtsMs_ = -1.0;bool prevValid_ = false;bool fgHistorySkipped_ = false;diff --git a/include/veyra/pipeline/GpuPassUtils.h b/include/veyra/pipeline/GpuPassUtils.hindex d0946984..d25e07a9 100644--- a/include/veyra/pipeline/GpuPassUtils.h+++ b/include/veyra/pipeline/GpuPassUtils.h@@ -309,8 +309,12 @@ struct GraphicsPass {ComPtr<ID3D12DescriptorHeap> heap;UINT increment = 0;+ // `constantCount` is the number of 32-bit root constants the pass declares at b0.+ // It defaults to the historical 8; the present blit passes 16 because it also+ // carries the static HDR curve (curve0/curve1).bool create(ID3D12Device* device, const std::vector<uint8_t>& vs,- const std::vector<uint8_t>& ps, UINT heapSlots, DXGI_FORMAT outputFormat=DXGI_FORMAT_R8G8B8A8_UNORM)+ const std::vector<uint8_t>& ps, UINT heapSlots, DXGI_FORMAT outputFormat=DXGI_FORMAT_R8G8B8A8_UNORM,+ UINT constantCount=8){D3D12_DESCRIPTOR_RANGE1 srvRange{};srvRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;@@ -328,7 +332,7 @@ struct GraphicsPass {rp[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;rp[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;rp[0].Constants.ShaderRegister = 0;- rp[0].Constants.Num32BitValues = 8;+ rp[0].Constants.Num32BitValues = constantCount;rp[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;rp[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;rp[1].DescriptorTable.NumDescriptorRanges = 1;diff --git a/include/veyra/ui/QmlPlayerBridge.h b/include/veyra/ui/QmlPlayerBridge.hindex c867f884..031c86f8 100644--- a/include/veyra/ui/QmlPlayerBridge.h+++ b/include/veyra/ui/QmlPlayerBridge.h@@ -267,6 +267,21 @@ class QmlPlayerBridge : public QObject {Q_PROPERTY(double nrHoldTolerance READ nrHoldTolerance WRITE setNrHoldTolerance NOTIFY settingsChanged)Q_PROPERTY(bool videoHdr READ videoHdr WRITE setVideoHdr NOTIFY settingsChanged)Q_PROPERTY(QVariantMap videoHdrParams READ videoHdrParams NOTIFY chainChanged)+ // Custom: static HDR output tuning (globals, every field live).+ Q_PROPERTY(bool hdrCurve READ hdrCurve WRITE setHdrCurve NOTIFY settingsChanged)+ Q_PROPERTY(QVariantMap hdrCurveParams READ hdrCurveParams NOTIFY settingsChanged)+ Q_PROPERTY(bool hdrMetadataEnabled READ hdrMetadataEnabled WRITE setHdrMetadataEnabled NOTIFY settingsChanged)+ Q_PROPERTY(QVariantMap hdrMetadataParams READ hdrMetadataParams NOTIFY settingsChanged)+ // One-click tuning presets (see hdrTuningPresets); "custom" when the sliders+ // no longer match any of them.+ Q_PROPERTY(QString hdrTuningPreset READ hdrTuningPreset NOTIFY settingsChanged)+ // One dial for the whole curve (0..200%, 100 = the preset as written) and the+ // display's own peak brightness (0 = ask the system). Both live next to the+ // baseline, so moving them never leaves the selected preset.+ Q_PROPERTY(int hdrCurveStrength READ hdrCurveStrength WRITE setHdrCurveStrength NOTIFY settingsChanged)+ Q_PROPERTY(int hdrDisplayPeakNits READ hdrDisplayPeakNits WRITE setHdrDisplayPeakNits NOTIFY settingsChanged)+ // What the system reports about the display, for the peak field's reset button.+ Q_PROPERTY(QVariantMap hdrDisplayInfo READ hdrDisplayInfo NOTIFY snapshotChanged)Q_PROPERTY(int nrStyle READ nrStyle WRITE setNrStyle NOTIFY settingsChanged)Q_PROPERTY(double nrIntensity READ nrIntensity WRITE setNrIntensity NOTIFY settingsChanged)Q_PROPERTY(double nrTone READ nrTone WRITE setNrTone NOTIFY settingsChanged)@@ -717,6 +732,27 @@ public:void setNrHoldTolerance(double value);bool videoHdr() const;void setVideoHdr(bool value);+ bool hdrCurve() const;+ void setHdrCurve(bool enabled);+ QVariantMap hdrCurveParams() const;+ Q_INVOKABLE bool setHdrCurveParameter(const QString& key, double value);+ bool hdrMetadataEnabled() const;+ void setHdrMetadataEnabled(bool enabled);+ QVariantMap hdrMetadataParams() const;+ Q_INVOKABLE bool setHdrMetadataParameter(const QString& key, double value);+ // Commit + re-assert the tuning in the places the session capture reads, so a+ // change takes effect and survives a restart (the same trap the earlier+ // per-scene brightness block hit: a plain commit left it out of the pending+ // settings the session is written from).+ bool commitHdrTuning(engine::EnhancementSettings settings);+ QString hdrTuningPreset() const;+ Q_INVOKABLE bool applyHdrTuningPreset(const QString& id);+ // The strength dial and the display peak (stored next to the baseline).+ int hdrCurveStrength() const;+ void setHdrCurveStrength(int percent);+ int hdrDisplayPeakNits() const;+ void setHdrDisplayPeakNits(int nits);+ QVariantMap hdrDisplayInfo() const;QVariantMap videoHdrParams() const;Q_INVOKABLE bool setVideoHdrParameter(const QString& key, double value);int nrStyle() const;diff --git a/qml/Veyra/ProPage.qml b/qml/Veyra/ProPage.qmlindex a18e4809..9f121bac 100644--- a/qml/Veyra/ProPage.qml+++ b/qml/Veyra/ProPage.qml@@ -1201,6 +1201,9 @@ VPage {summary: !switchAvailable ? Support.reason(veyra, "video-hdr") : veyra.videoHdr ? (veyra.videoHdrStatus.length > 0 ? veyra.videoHdrStatus : qsTr("已开启")) : qsTr("已关闭")on: veyra.videoHdronToggled: on => veyra.videoHdr = on+ // RTX Video HDR is an SDR -> HDR stage: an HDR source+ // keeps the native HDR path (and the HDR brightness+ // management), so there is no "convert HDR sources" switch.Repeater {model: [{key:"contrast",label:qsTr("对比度"),from:0,to:200,def:125},{key:"saturation",label:qsTr("饱和度"),from:0,to:200,def:75},@@ -1211,7 +1214,13 @@ VPage {enabled: Support.available(veyra, "video-hdr")opacity: enabled ? 1 : 0.4label: modelData.label- value: String(veyra.videoHdrParams[modelData.key] ?? "—")+ // modelData.scale turns an integer parameter into a+ // readable number (exposure is 1/100 EV); the unit+ // lives in the label, so every value stays short+ // enough for the rows to line up.+ value: modelData.scale+ ? (Number(veyra.videoHdrParams[modelData.key] ?? modelData.def) / modelData.scale).toFixed(2)+ : String(veyra.videoHdrParams[modelData.key] ?? "—")VSlider {objectName: "list-hdr-" + modelData.keyimplicitWidth: 120@@ -1768,6 +1777,154 @@ VPage {hint: qsTr("补帧路径固定 HDR10;需要 Windows HDR 开启")VSeg { objectName: "display-hdr-output"; options: [{id:"0",label:"HDR10"},{id:"1",label:qsTr("scRGB 浮点")}]; current: String(veyra.hdrOutputMode); onPicked: id => veyra.hdrOutputMode = Number(id) }}++ // HDR 亮度曲线: a static curve. Unlike a plain exposure the+ // highlights are protected by construction.+ VAccordion {+ objectName: "list-hdr-curve"+ Layout.fillWidth: true+ glyph: "sun"+ hue: "#F5C84B"+ title: qsTr("HDR 亮度曲线")+ summary: veyra.hdrCurve ? qsTr("已开启") : qsTr("已关闭")+ on: veyra.hdrCurve+ onToggled: on => veyra.hdrCurve = on+ // One-click presets: pick the one that matches the film.+ Flow {+ Layout.fillWidth: true+ Layout.preferredHeight: implicitHeight+ spacing: 6+ Repeater {+ model: [{id:"standard",label:qsTr("标准")},+ {id:"darkLift",label:qsTr("暗场提亮")},+ {id:"highlightGuard",label:qsTr("高光保护")},+ {id:"darkAndBright",label:qsTr("暗亮双修")},+ {id:"brightRoom",label:qsTr("明亮环境")},+ {id:"darkRoom",label:qsTr("暗室观影")},+ {id:"punch",label:qsTr("强化冲击")}]+ delegate: VButton {+ required property var modelData+ text: modelData.label+ ghost: true+ primary: veyra.hdrTuningPreset === modelData.id+ onClicked: veyra.applyHdrTuningPreset(modelData.id)+ }+ }+ }+ Text {+ Layout.fillWidth: true+ text: veyra.hdrTuningPreset === "darkLift" ? qsTr("暗调片、夜景多的剧集:只抬暗部,亮部不受影响。")+ : veyra.hdrTuningPreset === "highlightGuard" ? qsTr("高光很亮的片子(雪景/爆炸/演唱会):压住顶部,暗部不动。")+ : veyra.hdrTuningPreset === "darkAndBright" ? qsTr("暗场很暗、亮场又很亮的片子:两头都照顾。")+ : veyra.hdrTuningPreset === "brightRoom" ? qsTr("白天或亮环境看片:整体提亮一些。")+ : veyra.hdrTuningPreset === "darkRoom" ? qsTr("夜里关灯看:柔和一点,同时保留暗部细节。")+ : veyra.hdrTuningPreset === "punch" ? qsTr("画面偏灰、平淡的老片或转制片:提高对比观感。")+ : veyra.hdrTuningPreset === "standard" ? qsTr("不做任何改动,交给显示器和片源本身。")+ : qsTr("自定义:已用下面的滑块微调过。")+ wrapMode: Text.WordWrap+ color: Theme.t3+ font.family: Theme.fontUi; font.pixelSize: 11+ }+ // The two dials. Both scale the baseline the sliders below+ // edit, which is why moving either of them keeps the preset+ // above selected instead of falling back to "自定义".+ VRow {+ label: qsTr("强度")+ hint: qsTr("等比例缩放这一档的效果;100% = 档位原值")+ value: veyra.hdrCurveStrength + "%"+ VSlider {+ objectName: "list-hdrcurve-strength"+ implicitWidth: 120+ valueFromModel: true+ resettable: true; defaultValue: 100+ from: 0; to: 200+ value: veyra.hdrCurveStrength+ onMoved: value => veyra.hdrCurveStrength = Math.round(value)+ }+ }+ VRow {+ label: qsTr("显示设备峰值 (nit)")+ hint: veyra.hdrDisplayInfo.valid+ ? qsTr("系统报告:峰值 %1、全屏 %2、黑位 %3 nit")+ .arg(veyra.hdrDisplayInfo.peakNits)+ .arg(veyra.hdrDisplayInfo.fullFrameNits)+ .arg(Number(veyra.hdrDisplayInfo.minNits).toFixed(3))+ : qsTr("0 = 自动使用系统报告值")+ value: veyra.hdrDisplayPeakNits > 0+ ? (veyra.hdrDisplayPeakNits + " nit") : qsTr("自动")+ VSlider {+ objectName: "list-hdrcurve-displaypeak"+ implicitWidth: 120+ valueFromModel: true+ resettable: true; defaultValue: 0+ from: 0; to: 4000+ value: veyra.hdrDisplayPeakNits+ onMoved: value => veyra.hdrDisplayPeakNits = Math.round(value)+ }+ }+ Repeater {+ model: [{key:"shadowLiftEv100",label:qsTr("暗部抬升 (0.01 EV)"),from:-200,to:200,def:0},+ {key:"shadowRangeNits",label:qsTr("抬升范围 (nit)"),from:1,to:100,def:10,hint:qsTr("只在这个亮度以下的暗部生效")},+ {key:"midGrayNits",label:qsTr("中灰 (nit)"),from:100,to:500,def:203,hint:qsTr("203 = 中性;调高整体变亮,峰值不变")},+ {key:"highlightStartNits",label:qsTr("高光起点 (nit)"),from:0,to:2000,def:0,hint:qsTr("0 = 不做高光滚降")},+ {key:"rollOffPercent",label:qsTr("滚降强度 (%)"),from:10,to:200,def:100},+ {key:"peakCapNits",label:qsTr("峰值上限 (nit)"),from:0,to:4000,def:0,hint:qsTr("0 = 不限制")}]+ delegate: VRow {+ required property var modelData+ label: modelData.label+ hint: modelData.hint || ""+ value: String(veyra.hdrCurveParams[modelData.key] ?? "—")+ VSlider {+ objectName: "list-hdrcurve-" + modelData.key+ implicitWidth: 120+ valueFromModel: true+ resettable: true; defaultValue: modelData.def+ from: modelData.from; to: modelData.to+ value: veyra.hdrCurveParams[modelData.key] ?? modelData.def+ onMoved: value => veyra.setHdrCurveParameter(modelData.key, Math.round(value))+ }+ }+ }+ }+ // HDR 元数据: what the display is told about the content, which+ // is what its own dynamic tone mapping works from.+ VAccordion {+ objectName: "list-hdr-metadata"+ Layout.fillWidth: true+ glyph: "sun"+ hue: "#7FB2F5"+ title: qsTr("HDR 元数据")+ summary: veyra.hdrMetadataEnabled ? qsTr("已发送给显示器") : qsTr("已关闭")+ on: veyra.hdrMetadataEnabled+ onToggled: on => veyra.hdrMetadataEnabled = on+ Text {+ Layout.fillWidth: true+ text: qsTr("把内容峰值告诉显示器,让它的动态色调映射有依据。")+ wrapMode: Text.WordWrap+ color: Theme.t3+ font.family: Theme.fontUi; font.pixelSize: 11+ }+ Repeater {+ model: [{key:"masteringPeakNits",label:qsTr("母版峰值 (nit)"),from:0,to:4000,def:0,hint:qsTr("0 = 跟随片源;报低通常整体变亮")},+ {key:"maxCllNits",label:qsTr("MaxCLL (nit)"),from:0,to:4000,def:0,hint:qsTr("0 = 跟随片源")},+ {key:"maxFallNits",label:qsTr("MaxFALL (nit)"),from:0,to:4000,def:0,hint:qsTr("0 = 跟随片源")}]+ delegate: VRow {+ required property var modelData+ label: modelData.label+ hint: modelData.hint || ""+ value: String(veyra.hdrMetadataParams[modelData.key] ?? "—")+ VSlider {+ objectName: "list-hdrmeta-" + modelData.key+ implicitWidth: 120+ valueFromModel: true+ resettable: true; defaultValue: modelData.def+ from: modelData.from; to: modelData.to+ value: veyra.hdrMetadataParams[modelData.key] ?? modelData.def+ onMoved: value => veyra.setHdrMetadataParameter(modelData.key, Math.round(value))+ }+ }+ }+ }}VGroup {VRow {diff --git a/qml/Veyra/SettingsPage.qml b/qml/Veyra/SettingsPage.qmlindex b1b29831..70faef1b 100644--- a/qml/Veyra/SettingsPage.qml+++ b/qml/Veyra/SettingsPage.qml@@ -382,6 +382,127 @@ VPage {hint: qsTr("HDR10 默认;补帧固定 HDR10,需要 Windows HDR 开启")VSeg { options: [{id:"0",label:"HDR10"},{id:"1",label:qsTr("scRGB 浮点")}]; current: String(veyra.hdrOutputMode); onPicked: id => veyra.hdrOutputMode = Number(id) }}+ // HDR 亮度曲线: static, so the highlights are protected.+ // One-click presets (same ids as the list page).+ Flow {+ Layout.fillWidth: true+ Layout.preferredHeight: implicitHeight+ spacing: 6+ Repeater {+ model: [{id:"standard",label:qsTr("标准")},+ {id:"darkLift",label:qsTr("暗场提亮")},+ {id:"highlightGuard",label:qsTr("高光保护")},+ {id:"darkAndBright",label:qsTr("暗亮双修")},+ {id:"brightRoom",label:qsTr("明亮环境")},+ {id:"darkRoom",label:qsTr("暗室观影")},+ {id:"punch",label:qsTr("强化冲击")}]+ delegate: VButton {+ required property var modelData+ text: modelData.label+ ghost: true+ primary: veyra.hdrTuningPreset === modelData.id+ onClicked: veyra.applyHdrTuningPreset(modelData.id)+ }+ }+ }+ VRow {+ label: qsTr("HDR 亮度曲线")+ hint: qsTr("静态曲线:抬暗部、定中灰、压高光")+ value: veyra.hdrCurve ? qsTr("已开启") : qsTr("已关闭")+ VSwitch {+ objectName: "hdrcurve-enabled"+ checked: veyra.hdrCurve+ onToggled: checked => veyra.hdrCurve = checked+ }+ }+ VRow {+ label: qsTr("强度")+ hint: qsTr("等比例缩放这一档的效果;100% = 档位原值")+ value: veyra.hdrCurveStrength + "%"+ VSlider {+ objectName: "hdrcurve-strength"+ implicitWidth: 120+ valueFromModel: true+ resettable: true; defaultValue: 100+ from: 0; to: 200+ value: veyra.hdrCurveStrength+ onMoved: value => veyra.hdrCurveStrength = Math.round(value)+ }+ }+ VRow {+ label: qsTr("显示设备峰值 (nit)")+ hint: veyra.hdrDisplayInfo.valid+ ? qsTr("系统报告:峰值 %1、全屏 %2、黑位 %3 nit")+ .arg(veyra.hdrDisplayInfo.peakNits)+ .arg(veyra.hdrDisplayInfo.fullFrameNits)+ .arg(Number(veyra.hdrDisplayInfo.minNits).toFixed(3))+ : qsTr("0 = 自动使用系统报告值")+ value: veyra.hdrDisplayPeakNits > 0+ ? (veyra.hdrDisplayPeakNits + " nit") : qsTr("自动")+ VSlider {+ objectName: "hdrcurve-displaypeak"+ implicitWidth: 120+ valueFromModel: true+ resettable: true; defaultValue: 0+ from: 0; to: 4000+ value: veyra.hdrDisplayPeakNits+ onMoved: value => veyra.hdrDisplayPeakNits = Math.round(value)+ }+ }+ Repeater {+ model: [{key:"shadowLiftEv100",label:qsTr("暗部抬升 (0.01 EV)"),from:-200,to:200,def:0},+ {key:"shadowRangeNits",label:qsTr("抬升范围 (nit)"),from:1,to:100,def:10,hint:qsTr("只在这个亮度以下的暗部生效")},+ {key:"midGrayNits",label:qsTr("中灰 (nit)"),from:100,to:500,def:203,hint:qsTr("203 = 中性;调高整体变亮,峰值不变")},+ {key:"highlightStartNits",label:qsTr("高光起点 (nit)"),from:0,to:2000,def:0,hint:qsTr("0 = 不做高光滚降")},+ {key:"rollOffPercent",label:qsTr("滚降强度 (%)"),from:10,to:200,def:100},+ {key:"peakCapNits",label:qsTr("峰值上限 (nit)"),from:0,to:4000,def:0,hint:qsTr("0 = 不限制")}]+ delegate: VRow {+ required property var modelData+ label: modelData.label+ hint: modelData.hint || ""+ value: String(veyra.hdrCurveParams[modelData.key] ?? "—")+ VSlider {+ objectName: "hdrcurve-" + modelData.key+ implicitWidth: 150+ valueFromModel: true+ resettable: true; defaultValue: modelData.def+ from: modelData.from; to: modelData.to+ value: veyra.hdrCurveParams[modelData.key] ?? modelData.def+ onMoved: value => veyra.setHdrCurveParameter(modelData.key, Math.round(value))+ }+ }+ }+ // HDR 元数据: what the display's own tone mapping works from.+ VRow {+ label: qsTr("HDR 元数据")+ hint: qsTr("把内容峰值告诉显示器")+ value: veyra.hdrMetadataEnabled ? qsTr("已发送给显示器") : qsTr("已关闭")+ VSwitch {+ objectName: "hdrmeta-enabled"+ checked: veyra.hdrMetadataEnabled+ onToggled: checked => veyra.hdrMetadataEnabled = checked+ }+ }+ Repeater {+ model: [{key:"masteringPeakNits",label:qsTr("母版峰值 (nit)"),from:0,to:4000,def:0,hint:qsTr("0 = 跟随片源;报低通常整体变亮")},+ {key:"maxCllNits",label:qsTr("MaxCLL (nit)"),from:0,to:4000,def:0,hint:qsTr("0 = 跟随片源")},+ {key:"maxFallNits",label:qsTr("MaxFALL (nit)"),from:0,to:4000,def:0,hint:qsTr("0 = 跟随片源")}]+ delegate: VRow {+ required property var modelData+ label: modelData.label+ hint: modelData.hint || ""+ value: String(veyra.hdrMetadataParams[modelData.key] ?? "—")+ VSlider {+ objectName: "hdrmeta-" + modelData.key+ implicitWidth: 150+ valueFromModel: true+ resettable: true; defaultValue: modelData.def+ from: modelData.from; to: modelData.to+ value: veyra.hdrMetadataParams[modelData.key] ?? modelData.def+ onMoved: value => veyra.setHdrMetadataParameter(modelData.key, Math.round(value))+ }+ }+ }VRow {label: qsTr("记住播放位置")hint: qsTr("重新打开同一个文件时从上次位置继续")diff --git a/shaders/PresentBlit.hlsl b/shaders/PresentBlit.hlslindex f9b7229a..9c991ba9 100644--- a/shaders/PresentBlit.hlsl+++ b/shaders/PresentBlit.hlsl@@ -8,10 +8,37 @@ Texture2D<float4> sourceTex : register(t0);cbuffer PresentBlitConstants : register(b0){- float4 srcDims; // x/y=content extent z=flags (1 encode, 2 fine sampling) w=zoom+ float4 srcDims; // x/y=content extent z=flags (1 encode, 2 fine sampling, 4 PQ, 8 SDR white, 16 HDR curve) w=zoomfloat4 dstDims; // x/y=client extent z/w=view center+ // Custom: static HDR brightness curve, applied on absolute nits before the PQ+ // encode. See veyra/engine/HdrOutputTuning.h for the contract; every field is+ // a no-op at its default (lift 0, mid 203, start 0, cap 0).+ float4 curve0; // x=shadow lift EV, y=shadow range nits, z=mid-gray nits, w=highlight start nits+ float4 curve1; // x=roll-off scale nits, y=peak cap nits (0 = off)};+// Lift the shadows without touching the highlights, move the mid-gray reference+// with the peak held fixed, then roll off and cap the top end.+float3 HdrCurve(float3 nits, float4 c0, float4 c1)+{+ if (c0.x != 0.0 && c0.y > 0.0) {+ const float w = saturate(1.0 - nits / c0.y);+ nits *= 1.0 + w * w * (exp2(c0.x) - 1.0);+ }+ if (c0.z > 0.0 && abs(c0.z - 203.0) > 0.5) {+ const float peak = c1.y > 0.0 ? c1.y : 1000.0;+ if (peak > c0.z + 1.0) {+ const float g = log(c0.z / peak) / log(203.0 / peak);+ nits = peak * pow(max(nits / peak, 0.0), g);+ }+ }+ if (c0.w > 0.0 && c1.x > 0.0 && nits.x > c0.w) nits.x = c0.w + (nits.x - c0.w) / (1.0 + (nits.x - c0.w) / c1.x);+ if (c0.w > 0.0 && c1.x > 0.0 && nits.y > c0.w) nits.y = c0.w + (nits.y - c0.w) / (1.0 + (nits.y - c0.w) / c1.x);+ if (c0.w > 0.0 && c1.x > 0.0 && nits.z > c0.w) nits.z = c0.w + (nits.z - c0.w) / (1.0 + (nits.z - c0.w) / c1.x);+ if (c1.y > 0.0) nits = min(nits, c1.y);+ return nits;+}+SamplerState linearClamp : register(s0);struct VSOut@@ -76,6 +103,9 @@ float4 psMain(VSOut input) : SV_Targetuint flags=uint(srcDims.z+0.5);float4 color=(flags&2)?FineSample(uv):sourceTex.SampleLevel(linearClamp,uv,0);if(flags&8)color.rgb*=203.0/80.0; // SDR comparison white in an HDR output.+ // Custom: static HDR curve, on absolute nits (the working space is linear+ // scRGB, 1.0 = 80 nits), before the transfer function is encoded.+ if(flags&16)color.rgb=HdrCurve(max(color.rgb,0)*80.0,curve0,curve1)/80.0;if(flags&1){float3 c=max(color.rgb,0);color.rgb=lerp(1.055*pow(c,1.0/2.4)-0.055,c*12.92,step(c,0.0031308));}if(flags&4)color.rgb=HdrEncodePq(color.rgb);return color;diff --git a/src/engine/EffectChain.cpp b/src/engine/EffectChain.cppindex a1d5340a..1a3b1180 100644--- a/src/engine/EffectChain.cpp+++ b/src/engine/EffectChain.cpp@@ -509,12 +509,14 @@ ChainGlobalSettings ChainGlobalSettings::capture(const EnhancementSettings& s) {c.opticalFlowBackend = s.opticalFlowBackend; c.amdFlowHalfResolution = s.amdFlowHalfResolution;c.nrPolicy = s.nrPolicy;c.hdrOutputMode=s.hdrOutputMode;c.fgMotion=s.fgMotion;c.srMotion=s.srMotion;c.nrMotion=s.nrMotion;+ c.hdrCurve=s.hdrCurve;c.hdrMetadata=s.hdrMetadata;return c;}void ChainGlobalSettings::apply(EnhancementSettings& s) const {s.nrPolicy = nrPolicy;s.hdrOutputMode=hdrOutputMode;s.fgMotion=fgMotion;s.srMotion=srMotion;s.nrMotion=nrMotion;+ s.hdrCurve=hdrCurve;s.hdrMetadata=hdrMetadata;s.srTarget = srTarget; s.videoSrQuality = videoSrQuality;s.frameGenerationBackend = fgBackend; s.flow = flow;s.vfgQuality=vfgQuality;@@ -538,7 +540,14 @@ bool ChainConfiguration::operator==(const ChainConfiguration& other) const {return chain == other.chain && srTarget == other.srTarget && videoSrQuality == other.videoSrQuality &&fgBackend == other.fgBackend && vfgQuality == other.vfgQuality && flow == other.flow && opticalFlowBackend == other.opticalFlowBackend &&amdFlowHalfResolution == other.amdFlowHalfResolution && nrPolicy == other.nrPolicy &&+ // The author's own rendering globals had the same blind spot: a change to+ // the HDR output mode or to a motion source compared equal, so+ // persistSession() took its early return and the choice was lost on the+ // next start (field report: those two never came back).+ hdrOutputMode == other.hdrOutputMode && fgMotion == other.fgMotion &&+ srMotion == other.srMotion && nrMotion == other.nrMotion &&selectedNr == other.selectedNr && selectedColour == other.selectedColour &&+ hdrCurve == other.hdrCurve && hdrMetadata == other.hdrMetadata &&((!editor && !other.editor) || (editor && other.editor && *editor == *other.editor));}diff --git a/src/engine/PresetLibrary.cpp b/src/engine/PresetLibrary.cppindex 1fef637f..1a9a50e1 100644--- a/src/engine/PresetLibrary.cpp+++ b/src/engine/PresetLibrary.cpp@@ -13,8 +13,36 @@ namespace {// Six full grades per entry (plus the legacy first-grade field), up to 64// entries. Never remove the file-size guard as LUT names are external input.constexpr size_t kMaxPresetBytes = 2u * 1024u * 1024u;-void writeRendering(std::ostream& out,const ChainGlobalSettings& g,bool vfg=false){out<<' '<<int(g.hdrOutputMode)<<' '<<int(g.fgMotion)<<' '<<int(g.srMotion)<<' '<<int(g.nrMotion);if(vfg)out<<' '<<g.vfgQuality;}-bool readRendering(std::istream& in,ChainGlobalSettings& g,bool vfg=false){int hdr,fg,sr,nr;if(!(in>>hdr>>fg>>sr>>nr))return false;g.hdrOutputMode=HdrOutputMode(hdr);g.fgMotion=MotionSource(fg);g.srMotion=MotionSource(sr);g.nrMotion=MotionSource(nr);if(vfg&&!(in>>g.vfgQuality))return false;EnhancementSettings s;g.apply(s);return s.validate().empty();}+void writeRendering(std::ostream& out,const ChainGlobalSettings& g,bool vfg=false,bool tuning=false){out<<' '<<int(g.hdrOutputMode)<<' '<<int(g.fgMotion)<<' '<<int(g.srMotion)<<' '<<int(g.nrMotion);if(vfg)out<<' '<<g.vfgQuality;+ // Custom: static HDR output tuning (curve + display metadata), library v10 /+ // chain session v8. Ten numbers, written only from that version on.+ if(tuning)out<<' '<<g.hdrCurve.shadowLiftEv100<<' '<<g.hdrCurve.shadowRangeNits<<' '<<g.hdrCurve.midGrayNits<<' '+ <<g.hdrCurve.highlightStartNits<<' '<<g.hdrCurve.rollOffPercent<<' '<<g.hdrCurve.peakCapNits<<' '+ <<g.hdrCurve.enabled<<' '<<(g.hdrMetadata.enabled?1:0)<<' '<<g.hdrMetadata.masteringPeakNits<<' '+ <<g.hdrMetadata.maxCllNits<<' '<<g.hdrMetadata.maxFallNits<<' '<<g.hdrMetadata.masteringMinNitsX10000+ <<' '<<g.hdrCurve.strengthPercent<<' '<<g.hdrCurve.displayPeakNits;}+bool readRendering(std::istream& in,ChainGlobalSettings& g,bool vfg=false,bool extended=false,bool extendedTransition=false,bool tuning=false,bool tuningPlus=false){int hdr,fg,sr,nr;if(!(in>>hdr>>fg>>sr>>nr))return false;g.hdrOutputMode=HdrOutputMode(hdr);g.fgMotion=MotionSource(fg);g.srMotion=MotionSource(sr);g.nrMotion=MotionSource(nr);if(vfg&&!(in>>g.vfgQuality))return false;+ // Files written while this fork carried per-scene HDR brightness hold four extra+ // numbers here (plus the transition time). That feature is gone; the numbers are+ // still consumed and range-checked so those files keep loading.+ if(extended){int enabled,strength,peak,response;+ if(!(in>>enabled>>strength>>peak>>response)||enabled<0||enabled>1)return false;}+ if(extendedTransition){int transition;if(!(in>>transition)||transition<0||transition>2000)return false;}+ if(tuning){int lift,range,mid,start,roll,cap,curveOn,metaOn,mpeak,mcll,mfall,mmin;+ if(!(in>>lift>>range>>mid>>start>>roll>>cap>>curveOn>>metaOn>>mpeak>>mcll>>mfall>>mmin))return false;+ g.hdrCurve.shadowLiftEv100=lift;g.hdrCurve.shadowRangeNits=unsigned(range);g.hdrCurve.midGrayNits=unsigned(mid);+ g.hdrCurve.highlightStartNits=unsigned(start);g.hdrCurve.rollOffPercent=unsigned(roll);g.hdrCurve.peakCapNits=unsigned(cap);+ g.hdrCurve.enabled=curveOn!=0;+ g.hdrMetadata.enabled=metaOn!=0;g.hdrMetadata.masteringPeakNits=unsigned(mpeak);g.hdrMetadata.maxCllNits=unsigned(mcll);+ g.hdrMetadata.maxFallNits=unsigned(mfall);g.hdrMetadata.masteringMinNitsX10000=unsigned(std::max(0,mmin));+ if(!g.hdrCurve.valid()||!g.hdrMetadata.valid())return false;}+ // v11 / v9 append the strength dial and the display peak; older files simply+ // keep the defaults for both (100% and "ask the system").+ if(tuningPlus){unsigned strength,displayPeak;+ if(!(in>>strength>>displayPeak))return false;+ g.hdrCurve.strengthPercent=std::min(200u,strength);g.hdrCurve.displayPeakNits=displayPeak;+ if(!g.hdrCurve.valid())return false;}+ EnhancementSettings s;g.apply(s);return s.validate().empty();}void applyRenderingPreset(const PresetEntry& e,EnhancementSettings& s){if(!e.globals)return;const auto fg=s.frameGenerationBackend;const auto fgMotion=s.fgMotion;const auto quality=s.vfgQuality;@@ -176,7 +204,7 @@ bool PresetLibrary::save() {std::wstring checkedDefault;// Match PresetStore: never replace a valid file with one our reader rejects.if (!parse(data, checked, checkedDefault, error_)) return false;- if(data.starts_with("VEYRA_PRESET_LIBRARY 7")&&!path_.wstring().ends_with(L".vfg"))path_=std::filesystem::path(path_).concat(L".vfg");+ if((data.starts_with("VEYRA_PRESET_LIBRARY 7")||data.starts_with("VEYRA_PRESET_LIBRARY 8")||data.starts_with("VEYRA_PRESET_LIBRARY 9")||data.starts_with("VEYRA_PRESET_LIBRARY 10")||data.starts_with("VEYRA_PRESET_LIBRARY 11"))&&!path_.wstring().ends_with(L".vfg"))path_=std::filesystem::path(path_).concat(L".vfg");if(!path_.wstring().ends_with(L".vfg")){if(data.starts_with("VEYRA_PRESET_LIBRARY 6")&&!path_.wstring().ends_with(L".field-render"))path_=std::filesystem::path(path_).concat(L".field-render");if (std::any_of(entries_.begin(), entries_.end(), [](const auto& e) { return e.nodeConfiguration.has_value(); }) &&@@ -582,7 +610,15 @@ std::string PresetLibrary::encodeEntries(const std::vector<PresetEntry>& entriesreturn c.fgBackend==FrameGenerationBackend::Vfg||c.vfgQuality!=1||(c.editor&&c.editor->globals&&(c.editor->globals->fgBackend==FrameGenerationBackend::Vfg||c.editor->globals->vfgQuality!=1));});- const int version=std::max(minimumVersion, vfg?7:rendering?6:globals?5:editor?4:layerSizes?3:multi?2:1);+ // Custom v10: static HDR output tuning (curve + display metadata).+ const auto tuningOf=[](const PresetEntry& e)->bool{+ if(e.globals&&(e.globals->hdrCurve!=HdrCurveSettings{}||e.globals->hdrMetadata!=HdrMetadataSettings{}))return true;+ if(e.nodeConfiguration&&e.nodeConfiguration->editor&&e.nodeConfiguration->editor->globals){+ const auto& g=*e.nodeConfiguration->editor->globals;+ return g.hdrCurve!=HdrCurveSettings{}||g.hdrMetadata!=HdrMetadataSettings{};}+ return false;};+ const bool tuning=std::any_of(entries_.begin(),entries_.end(),tuningOf);+ const int version=std::max(minimumVersion, tuning?11:vfg?7:rendering?6:globals?5:editor?4:layerSizes?3:multi?2:1);o << "VEYRA_PRESET_LIBRARY " << version << '\n' << std::quoted(utf8(defaultName_)) << ' ' << entries_.size() << '\n';for (const auto& e : entries_) {o << std::quoted(utf8(e.name)) << ' ' << std::quoted(utf8(e.note)) << ' '@@ -625,7 +661,7 @@ std::string PresetLibrary::encodeEntries(const std::vector<PresetEntry>& entries}if(version>=6){o<<' '<<e.globals.has_value();- if(e.globals){const auto& g=*e.globals;o<<' '<<int(g.srTarget)<<' '<<g.videoSrQuality<<' '<<int(g.fgBackend)<<' '<<int(g.flow)<<' '<<int(g.opticalFlowBackend)<<' '<<g.amdFlowHalfResolution<<' '<<int(g.nrPolicy);writeRendering(o,g,version>=7);}+ if(e.globals){const auto& g=*e.globals;o<<' '<<int(g.srTarget)<<' '<<g.videoSrQuality<<' '<<int(g.fgBackend)<<' '<<int(g.flow)<<' '<<int(g.opticalFlowBackend)<<' '<<g.amdFlowHalfResolution<<' '<<int(g.nrPolicy);writeRendering(o,g,version>=7,version>=10);}}o << '\n';}@@ -633,7 +669,7 @@ std::string PresetLibrary::encodeEntries(const std::vector<PresetEntry>& entries}bool PresetLibrary::parse(const std::string& data, std::vector<PresetEntry>& out, std::wstring& def, std::wstring& error,- bool* migrated, bool preserveLegacy) {+ bool* migrated, bool preserveLegacy, int maxVersion) {if (migrated) *migrated = false;if (data.size() > kMaxPresetBytes) { error = L"预设库超过 2 MiB"; return false; }std::istringstream in(data);@@ -641,7 +677,10 @@ bool PresetLibrary::parse(const std::string& data, std::vector<PresetEntry>& outstd::string magic, quoted;int version = 0;size_t count = 0;- if (!(in >> magic >> version) || magic != "VEYRA_PRESET_LIBRARY" || version < 1 || version > 7) { error = L"预设库格式或版本不支持"; return false; }+ // Custom: maxVersion 0 keeps this context's own cap; the chain session passes 9+ // explicitly so an editor payload can carry the HDR brightness block.+ const int allowedVersion = maxVersion > 0 ? maxVersion : (preserveLegacy ? 3 : 11);+ if (!(in >> magic >> version) || magic != "VEYRA_PRESET_LIBRARY" || version < 1 || version > allowedVersion) { error = L"预设库格式或版本不支持"; return false; }if (!(in >> std::quoted(quoted) >> count) || count > 64) { error = L"预设库条目数非法"; return false; }def = wide(quoted);for (size_t i = 0; i < count; ++i) {@@ -739,7 +778,7 @@ bool PresetLibrary::parse(const std::string& data, std::vector<PresetEntry>& outif(present){ChainGlobalSettings g;int target,backend,flow,optical,half,policy;if(!(in>>target>>g.videoSrQuality>>backend>>flow>>optical>>half>>policy)||half<0||half>1)return false;g.srTarget=pipeline::SrTarget(target);g.fgBackend=FrameGenerationBackend(backend);g.flow=FlowQuality(flow);g.opticalFlowBackend=OpticalFlowBackend(optical);g.amdFlowHalfResolution=half!=0;g.nrPolicy=pipeline::NrSizePolicy(policy);- if(!readRendering(in,g,version>=7))return false;e.globals=g;+ if(!readRendering(in,g,version>=7,(version>=8&&version<=9),version==9,version>=10,version>=11))return false;e.globals=g;}}out.push_back(std::move(e));@@ -757,7 +796,12 @@ std::string ChainSessionStore::encode(const ChainSession& session) {const bool rendering=std::any_of(session.configurations.begin(),session.configurations.end(),[&](const auto& c){return extended(c)||(c.editor&&c.editor->globals&&extended(*c.editor->globals));});const auto usesVfg=[](const ChainGlobalSettings& g){return g.fgBackend==FrameGenerationBackend::Vfg||g.vfgQuality!=1;};const bool vfg=std::any_of(session.configurations.begin(),session.configurations.end(),[&](const auto& c){return usesVfg(c)||(c.editor&&c.editor->globals&&usesVfg(*c.editor->globals));});- const int version = vfg?5:rendering?4:editor ? (editor->globals ? 3 : 2) : 1;+ // Custom: session v8 carries the static HDR output tuning (curve + metadata).+ const auto tuningCustom=[](const ChainConfiguration& c){+ return c.hdrCurve!=HdrCurveSettings{} || c.hdrMetadata!=HdrMetadataSettings{} ||+ (c.editor&&c.editor->globals&&(c.editor->globals->hdrCurve!=HdrCurveSettings{}||c.editor->globals->hdrMetadata!=HdrMetadataSettings{}));};+ const bool tuning=std::any_of(session.configurations.begin(),session.configurations.end(),tuningCustom);+ const int version = tuning?9:vfg?5:rendering?4:editor ? (editor->globals ? 3 : 2) : 1;out << "VEYRA_CHAIN_SESSION " << version << '\n' << int(session.active) << ' ' << session.initialized[0] << ' ' << session.initialized[1];if(version>=4)out<<' '<<bool(editor);out<<'\n';std::vector<PresetEntry> entries;@@ -766,7 +810,7 @@ std::string ChainSessionStore::encode(const ChainSession& session) {out << int(c.srTarget) << ' ' << c.videoSrQuality << ' ' << int(c.fgBackend) << ' '<< int(c.flow) << ' ' << int(c.opticalFlowBackend) << ' ' << c.amdFlowHalfResolution << ' '<< int(c.nrPolicy) << ' ' << c.selectedNr << ' ' << c.selectedColour;- if(version>=4)writeRendering(out,c,version>=5);out<<'\n';+ if(version>=4)writeRendering(out,c,version>=5,version>=8);out<<'\n';PresetEntry entry;entry.name = i == 0 ? L"list" : L"node";entry.kind = ChainMode(i); entry.chain = c.chain;@@ -784,7 +828,7 @@ std::string ChainSessionStore::encode(const ChainSession& session) {const auto& g = *document.globals;out << int(g.srTarget) << ' ' << g.videoSrQuality << ' ' << int(g.fgBackend) << ' '<< int(g.flow) << ' ' << int(g.opticalFlowBackend) << ' ' << g.amdFlowHalfResolution << ' '- << int(g.nrPolicy);if(version>=4)writeRendering(out,g,version>=5);out<<'\n';+ << int(g.nrPolicy);if(version>=4)writeRendering(out,g,version>=5,version>=8);out<<'\n';}out << graph.nextId << ' ' << graph.inputNext << ' ' << document.nodes.nodeCount << '\n';// The ordinary preset codec validates a linear runtime chain. Use a@@ -811,7 +855,7 @@ bool ChainSessionStore::decode(const std::string& data, ChainSession& session, bstd::istringstream in(data); in.imbue(std::locale::classic());std::string magic, body; int version = 0, active = 0, list = 0, node = 0;if (!(in >> magic >> version >> active >> list >> node) || magic != "VEYRA_CHAIN_SESSION" ||- (version < 1 || version > 5) || active < 0 || active > 1 || list != 1 || node < 0 || node > 1) return false;+ (version < 1 || version > 9) || active < 0 || active > 1 || list != 1 || node < 0 || node > 1) return false;int hasEditor=version>=2?1:0;if(version>=4&&(!(in>>hasEditor)||hasEditor<0||hasEditor>1))return false;ChainSession parsed; parsed.active = ChainMode(active); parsed.initialized = {true, node != 0};@@ -822,11 +866,11 @@ bool ChainSessionStore::decode(const std::string& data, ChainSession& session, bc.srTarget = pipeline::SrTarget(target); c.fgBackend = FrameGenerationBackend(backend);c.flow = FlowQuality(flow); c.opticalFlowBackend = OpticalFlowBackend(optical);c.amdFlowHalfResolution = half != 0; c.nrPolicy = pipeline::NrSizePolicy(policy);- if(version>=4&&!readRendering(in,c,version>=5))return false;+ if(version>=4&&!readRendering(in,c,version>=5,(version>=6&&version<=7),version==7,version>=8,version>=9))return false;}if (!(in >> std::quoted(body))) return false;std::vector<PresetEntry> entries; std::wstring def, error;- if (!PresetLibrary::parse(body, entries, def, error, nullptr, true) || entries.size() != 2 || !def.empty()) return false;+ if (!PresetLibrary::parse(body, entries, def, error, nullptr, true, 10) || entries.size() != 2 || !def.empty()) return false;for (size_t i = 0; i < entries.size(); ++i) {if (entries[i].kind != ChainMode(i)) return false;parsed.configurations[i].chain = entries[i].chain;@@ -847,7 +891,7 @@ bool ChainSessionStore::decode(const std::string& data, ChainSession& session, bg.srTarget = pipeline::SrTarget(target); g.fgBackend = FrameGenerationBackend(backend);g.flow = FlowQuality(flow); g.opticalFlowBackend = OpticalFlowBackend(optical);g.amdFlowHalfResolution = half != 0; g.nrPolicy = pipeline::NrSizePolicy(policy);- if(version>=4&&!readRendering(in,g,version>=5))return false;+ if(version>=4&&!readRendering(in,g,version>=5,(version>=6&&version<=7),version==7,version>=8,version>=9))return false;editor->globals = g;}uint32_t count = 0;@@ -860,7 +904,7 @@ bool ChainSessionStore::decode(const std::string& data, ChainSession& session, b}if (!(in >> std::quoted(body))) return false;entries.clear(); def.clear(); error.clear();- if (!PresetLibrary::parse(body, entries, def, error, nullptr, true) || entries.size() != 1 ||+ if (!PresetLibrary::parse(body, entries, def, error, nullptr, true, 10) || entries.size() != 1 ||!def.empty() || entries[0].kind != ChainMode::Node || entries[0].chain.nodeCount != count) return false;editor->nodes = std::move(entries[0].chain);for (uint32_t i = 0; i < count; ++i) {@@ -923,7 +967,7 @@ bool ChainSessionStore::save(const ChainSession& session) {const auto data = encode(session);ChainSession checked;if (!decode(data, checked)) { error_ = L"模式会话编码校验失败,未保存"; return false; }- if(data.starts_with("VEYRA_CHAIN_SESSION 5")&&!path_.wstring().ends_with(L".vfg"))path_=std::filesystem::path(path_).concat(L".vfg");+ if((data.starts_with("VEYRA_CHAIN_SESSION 5")||data.starts_with("VEYRA_CHAIN_SESSION 6")||data.starts_with("VEYRA_CHAIN_SESSION 7")||data.starts_with("VEYRA_CHAIN_SESSION 8")||data.starts_with("VEYRA_CHAIN_SESSION 9"))&&!path_.wstring().ends_with(L".vfg"))path_=std::filesystem::path(path_).concat(L".vfg");if(!path_.wstring().ends_with(L".vfg")){if(data.starts_with("VEYRA_CHAIN_SESSION 4")&&!path_.wstring().ends_with(L".field-render"))path_=std::filesystem::path(path_).concat(L".field-render");// A v1 reader must never reinterpret or overwrite the new editor graph.diff --git a/src/engine/VideoPresenter.cpp b/src/engine/VideoPresenter.cppindex 49326ddd..70a4d3cc 100644--- a/src/engine/VideoPresenter.cpp+++ b/src/engine/VideoPresenter.cpp@@ -60,7 +60,7 @@ bool VideoPresenter::open(gfx::D3D12DeviceContext& ctx,HWND window,pipeline::Enhstd::vector<uint8_t> vs,ps;// The output pool contains both parities of every generated subframe.// Comparison references follow it; derive offsets to cover VFG through 8X.- if(!pipeline::loadShaderBytes("PresentBlit_vs.dxil",vs)||!pipeline::loadShaderBytes("PresentBlit_ps.dxil",ps)||!pass_.create(ctx.device(),vs,ps,pipeline::kOutputPoolSlots+4,graph.outputFormat()))return false;+ if(!pipeline::loadShaderBytes("PresentBlit_vs.dxil",vs)||!pipeline::loadShaderBytes("PresentBlit_ps.dxil",ps)||!pass_.create(ctx.device(),vs,ps,pipeline::kOutputPoolSlots+4,graph.outputFormat(),16))return false;if(sink_.xess()){std::vector<uint8_t> cs;if(!pipeline::loadShaderBytes("PresentMotion.dxil",cs)||!presentMotionPass_.create(ctx.device(),cs,4,1,1,16))return false;@@ -80,7 +80,10 @@ bool VideoPresenter::open(gfx::D3D12DeviceContext& ctx,HWND window,pipeline::Enhfor(unsigned i=0;i<4;++i)pipeline::makeSrv(ctx.device(),i<2?graph.sourceReference(i):graph.baseReference(i-2),DXGI_FORMAT_R16G16B16A16_FLOAT,{pass_.heap->GetCPUDescriptorHandleForHeapStart().ptr+size_t(i+pipeline::kOutputPoolSlots)*pass_.increment});return true;}-void VideoPresenter::refresh(ID3D12Device* device){for(unsigned i=0;i<3;++i){Microsoft::WRL::ComPtr<ID3D12Resource> bb;if(SUCCEEDED(sink_.swapChain()->GetBuffer(i,IID_PPV_ARGS(&bb))))device->CreateRenderTargetView(bb.Get(),nullptr,{rtvs_->GetCPUDescriptorHandleForHeapStart().ptr+size_t(i)*inc_});}}+void VideoPresenter::refresh(ID3D12Device* device){+ // The swap chain is rebuilt here (resize, monitor/HDR switch), so the new+ // chain has never received the HDR metadata: ask for it to be sent again.+ metadataSent_=false;for(unsigned i=0;i<3;++i){Microsoft::WRL::ComPtr<ID3D12Resource> bb;if(SUCCEEDED(sink_.swapChain()->GetBuffer(i,IID_PPV_ARGS(&bb))))device->CreateRenderTargetView(bb.Get(),nullptr,{rtvs_->GetCPUDescriptorHandleForHeapStart().ptr+size_t(i)*inc_});}}bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& sharedRing,pipeline::EnhanceGraph& graph,unsigned slot,bool generated,bool referencesValid,int comparison,bool baseReference,float split,pipeline::FrameIdentity identity,PreviewView view,int64_t sourcePts100ns) {auto& ring=presentationQueue_?presentationRing_:sharedRing;auto* fence=presentationFence_?presentationFence_.Get():ctx.fence();@@ -153,18 +156,34 @@ bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&// PresentBlit uses a contain mapping. Cancel its fit so these dimensions// express the exact shared display transform, including stretch/SAR/fill.const float inverseFit=1.0f/std::min(float(rc.right)/renderW,float(rc.bottom)/renderH);- float dims[8]={renderW,renderH,samplingFlags,inverseFit,float(rc.right),float(rc.bottom),view.centerX,view.centerY};list->SetGraphicsRoot32BitConstants(0,8,dims,0);+ // Custom: static HDR curve. The present blit applies it on absolute nits just+ // before the PQ encode, so it never touches the exported or the graded frame.+ const auto& hdrCurve=graph.hdrCurve();+ float dims[16]={renderW,renderH,samplingFlags+((hdrCurve.enabled&&graph.hdrOutput())?16.0f:0.0f),inverseFit,float(rc.right),float(rc.bottom),view.centerX,view.centerY};+ dims[8]=float(hdrCurve.shadowLiftEv100)/100.0f;+ dims[9]=float(hdrCurve.shadowRangeNits);+ dims[10]=float(hdrCurve.midGrayNits);+ dims[11]=float(hdrCurve.highlightStartNits);+ {+ const float peak=hdrCurve.peakCapNits?float(hdrCurve.peakCapNits):1000.0f;+ const float start=float(hdrCurve.highlightStartNits);+ dims[12]=std::max(1.0f,peak-start)*float(hdrCurve.rollOffPercent)/100.0f;+ dims[13]=float(hdrCurve.peakCapNits);+ }+ dims[14]=0.0f;dims[15]=0.0f;+ list->SetGraphicsRoot32BitConstants(0,16,dims,0);list->SetGraphicsRootDescriptorTable(1,{pass_.heap->GetGPUDescriptorHandleForHeapStart().ptr+size_t(slot+(generated?2:0))*pass_.increment});list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);list->DrawInstanced(3,1,0,0);if(comparison&&!generated&&referencesValid){auto* reference=baseReference?graph.baseReference(slot):graph.sourceReference(slot);D3D12_RESOURCE_BARRIER b{};b.Type=D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;b.Transition.pResource=reference;b.Transition.Subresource=D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;b.Transition.StateBefore=D3D12_RESOURCE_STATE_COMMON;b.Transition.StateAfter=D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;list->ResourceBarrier(1,&b);- dims[2]=samplingFlags+(graph.hdr10Output()?4:graph.hdrOutput()?0:1)+(graph.videoHdrActive()?8:0);list->SetGraphicsRoot32BitConstants(0,8,dims,0);list->SetGraphicsRootDescriptorTable(1,{pass_.heap->GetGPUDescriptorHandleForHeapStart().ptr+size_t(pipeline::kOutputPoolSlots+slot+(baseReference?2:0))*pass_.increment});+ dims[2]=samplingFlags+((hdrCurve.enabled&&graph.hdrOutput())?16.0f:0.0f)+(graph.hdr10Output()?4:graph.hdrOutput()?0:1)+(graph.videoHdrActive()?8:0);list->SetGraphicsRoot32BitConstants(0,16,dims,0);list->SetGraphicsRootDescriptorTable(1,{pass_.heap->GetGPUDescriptorHandleForHeapStart().ptr+size_t(pipeline::kOutputPoolSlots+slot+(baseReference?2:0))*pass_.increment});if(comparison==2)rect.right=LONG(std::clamp((rc.right*.5f+(std::clamp(split,0.0f,1.0f)-view.centerX)*renderW)*sink_.bufferWidth()/rc.right,0.0f,float(sink_.bufferWidth())));list->RSSetScissorRects(1,&rect);list->DrawInstanced(3,1,0,0);std::swap(b.Transition.StateBefore,b.Transition.StateAfter);list->ResourceBarrier(1,&b);if(veyra::log::verboseFrameLogs())veyra::log::info("comparison",std::format("real-frame source={} epoch={} revision={} reference={} mode={} split={} (same leased frame)",identity.sourceFrameId,identity.epoch,identity.settingsRevision,baseReference?"base":"input",comparison,split));}for(auto& b:barriers)std::swap(b.Transition.StateBefore,b.Transition.StateAfter);list->ResourceBarrier(2,barriers);+ applyHdrMetadata(graph);// Interpolation region for the XeSS present-sink FG backend.// It must follow the PresentBlit view mapping (contain * zoom, view// center) rather than assuming the default centered view: the previous@@ -344,4 +363,47 @@ Microsoft::WRL::ComPtr<ID3D12Resource> VideoPresenter::presentedResourceForTest(if(hasPresented_&&sink_.swapChain())sink_.swapChain()->GetBuffer(lastBuffer_,IID_PPV_ARGS(&buffer));return buffer;}++// Custom: HDR10 static metadata. The display runs its own dynamic tone mapping;+// without metadata it has to guess the content peak, and reporting a lower+// mastering peak makes many displays map the picture brighter overall - which is+// the point of the manual override. Every field defaults to "follow the source".+void VideoPresenter::applyHdrMetadata(pipeline::EnhanceGraph& graph) {+ auto* chain=sink_.swapChain4();+ if(!chain)return;+ const auto& m=graph.hdrMetadata();+ if(!m.enabled||!graph.hdr10Output()){+ if(metadataSent_){chain->SetHDRMetaData(DXGI_HDR_METADATA_TYPE_NONE,0,nullptr);metadataSent_=false;}+ return;+ }+ const auto& src=graph.sourceColor();+ DXGI_HDR_METADATA_HDR10 md{};+ // BT.2020 primaries and D65 in DXGI's 1/50000 units.+ md.RedPrimary[0]=35400;md.RedPrimary[1]=14600;+ md.GreenPrimary[0]=8500;md.GreenPrimary[1]=39850;+ md.BluePrimary[0]=6550;md.BluePrimary[1]=2300;+ md.WhitePoint[0]=15635;md.WhitePoint[1]=16450;+ const auto pick=[](unsigned manual,float fromSource,unsigned fallback){+ if(manual)return manual;+ if(std::isfinite(fromSource)&&fromSource>0.0f)return unsigned(std::lround(std::min(fromSource,10000.0f)));+ return fallback;};+ // Keep the last value the source actually provided: these fields are optional+ // per frame, so reading them raw made the result alternate between the real+ // value and the fallback and re-sent the metadata constantly.+ if(std::isfinite(src.hdrMasteringPeakNits)&&src.hdrMasteringPeakNits>0.0f)stickyMasteringPeak_=src.hdrMasteringPeakNits;+ if(std::isfinite(src.hdrMaxCllNits)&&src.hdrMaxCllNits>0.0f)stickyMaxCll_=src.hdrMaxCllNits;+ if(std::isfinite(src.hdrMaxFallNits)&&src.hdrMaxFallNits>0.0f)stickyMaxFall_=src.hdrMaxFallNits;+ md.MaxMasteringLuminance=pick(m.masteringPeakNits,stickyMasteringPeak_,1000);+ md.MinMasteringLuminance=m.masteringMinNitsX10000;+ md.MaxContentLightLevel=uint16_t(std::min(65535u,pick(m.maxCllNits,stickyMaxCll_,md.MaxMasteringLuminance)));+ md.MaxFrameAverageLightLevel=uint16_t(std::min(65535u,pick(m.maxFallNits,stickyMaxFall_,md.MaxContentLightLevel)));+ if(metadataSent_&&std::memcmp(&lastMetadata_,&md,sizeof(md))==0)return;+ if(SUCCEEDED(chain->SetHDRMetaData(DXGI_HDR_METADATA_TYPE_HDR10,sizeof(md),&md))){+ lastMetadata_=md;metadataSent_=true;+ log::info("hdr-metadata",std::format("sent masteringPeak={} minX10000={} maxCLL={} maxFALL={} (source peak={:.0f} cll={:.0f} fall={:.0f})",+ md.MaxMasteringLuminance,md.MinMasteringLuminance,md.MaxContentLightLevel,md.MaxFrameAverageLightLevel,+ stickyMasteringPeak_,stickyMaxCll_,stickyMaxFall_));+ }+}+}diff --git a/src/gfx/PresentSink.cpp b/src/gfx/PresentSink.cppindex c57a385a..77b29ba4 100644--- a/src/gfx/PresentSink.cpp+++ b/src/gfx/PresentSink.cpp@@ -67,6 +67,45 @@ std::optional<bool> PresentSink::queryHdrDisplayActive(HWND window,HMONITOR* quereturn std::nullopt;}+PresentSink::DisplayPeakInfo PresentSink::queryDisplayPeak(HWND window){+ DisplayPeakInfo info{};+ // Without a window (the UI asking before playback starts) answer about the+ // primary monitor, which is what a fresh install would be showing on.+ HMONITOR monitor=nullptr;+ if(window){+ MONITORINFOEXW mi{};mi.cbSize=sizeof(mi);+ monitor=MonitorFromWindow(window,MONITOR_DEFAULTTONEAREST);+ if(!monitor||!GetMonitorInfoW(monitor,&mi))return info;+ }else{+ monitor=MonitorFromPoint(POINT{0,0},MONITOR_DEFAULTTOPRIMARY);+ }+ if(!monitor)return info;+ // Called on demand (the user asking for the system value), so a fresh factory is+ // fine here - no need to join the cached one the 2 s HDR poll uses.+ ComPtr<IDXGIFactory1> factory;+ if(FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))||!factory)return info;+ for(UINT a=0;;++a){+ ComPtr<IDXGIAdapter1> adapter;+ if(factory->EnumAdapters1(a,&adapter)==DXGI_ERROR_NOT_FOUND)break;+ if(!adapter)break;+ for(UINT i=0;;++i){+ ComPtr<IDXGIOutput> output;+ if(adapter->EnumOutputs(i,&output)==DXGI_ERROR_NOT_FOUND)break;+ if(!output)break;+ DXGI_OUTPUT_DESC basic{};if(FAILED(output->GetDesc(&basic)))continue;+ if(basic.Monitor!=monitor)continue;+ ComPtr<IDXGIOutput6> advanced;if(FAILED(output.As(&advanced)))return info;+ DXGI_OUTPUT_DESC1 desc{};if(FAILED(advanced->GetDesc1(&desc)))return info;+ info.peakNits=unsigned(std::lround(desc.MaxLuminance));+ info.fullFrameNits=unsigned(std::lround(desc.MaxFullFrameLuminance));+ info.minNits=desc.MinLuminance;+ info.valid=info.peakNits>0;+ return info;+ }+ }+ return info;+}+double PresentSink::displayRefreshFps(HWND window){MONITORINFOEXW mi{};mi.cbSize=sizeof(mi);const auto monitor=MonitorFromWindow(window,MONITOR_DEFAULTTONEAREST);@@ -193,17 +232,17 @@ bool PresentSink::initialize(ID3D12Device* device, ID3D12CommandQueue* queue,// Re-initializing the same backend (a settings change): the old// wrapper owns the window's swapchain slot until it is destroyed.for(auto& b:backBuffers_)b.Reset();- swapChain_.Reset();+ swapChain_.Reset();swapChain4_.Reset();xess_.reset();}for(auto& b:backBuffers_)b.Reset();- swapChain_.Reset();+ swapChain_.Reset();swapChain4_.Reset();xess_=std::make_unique<XessPresenter>();if(!xess_->initialize(device,queue,factory_.Get(),hwnd_,scd,swapChain_.GetAddressOf(),desc.fgMultiplier,desc.xessLowLatencySleep)){// XeSS is an optional experimental presenter. A missing or// incompatible local runtime must not prevent basic playback.log::warn("present", "XeSS FG initialization failed; falling back to native presentation");- swapChain_.Reset();+ swapChain_.Reset();swapChain4_.Reset();xess_.reset();}}@@ -295,6 +334,12 @@ bool PresentSink::refetchBackBuffers()return true;}+IDXGISwapChain4* PresentSink::swapChain4(){+ if(!swapChain_){swapChain4_.Reset();return nullptr;}+ if(!swapChain4_&&FAILED(swapChain_.As(&swapChain4_)))swapChain4_.Reset();+ return swapChain4_.Get();+}+void PresentSink::recreateSwapChain(UINT flags){(void)flags;@@ -537,7 +582,7 @@ void PresentSink::shutdown()const ULONG rc = swapChain_->Release();log::info("present", std::format("sink-shutdown: swapchain pre-release refcount={} (2 = only our ComPtr + probe)", rc));}- swapChain_.Reset();+ swapChain_.Reset();swapChain4_.Reset();xess_.reset();log::info("present", "sink-shutdown: sub-step window-destroy-last");if (hwnd_ != nullptr && !desc_.targetWindow) {diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cppindex d05528a4..990822a2 100644--- a/src/pipeline/EnhanceGraph.cpp+++ b/src/pipeline/EnhanceGraph.cpp@@ -1796,6 +1796,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Framereturn false;}const auto resolved=resolveFrameColor(*frame,color?*color:ColorDescription{});+ lastSourceColor_=resolved;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));@@ -2956,6 +2957,14 @@ bool EnhanceGraph::applySettings(const engine::EnhancementSettings& s){// queue drained: treat it as a rebuild (parameters stay live).if(s.color.lutNameString()!=desc_.color.lutNameString()||s.color.lutInputSpace!=desc_.color.lutInputSpace)return false;desc_.videoHdr=s.videoHdr;+ // The static HDR output tuning is live - the present blit reads the curve and+ // the presenter sends the metadata - so a change has to reach desc_ here. It is+ // not part of the rebuild decision.+ // The stored settings are the BASELINE: the strength dial and the display peak+ // are resolved into the applied numbers here, so this is the single place the+ // scaling happens (which is what lets either dial move without the UI leaving+ // its preset).+ engine::resolveHdrTuning(s.hdrCurve,s.hdrMetadata,desc_.hdrCurve,desc_.hdrMetadata);if(!(s.color==desc_.color)){desc_.color=s.color;if(nodeColorInstances_[0])nodeColorInstances_[0]->refresh(s.color);diff --git a/src/ui/QmlPlayerBridge.cpp b/src/ui/QmlPlayerBridge.cppindex f3151bbe..0bcd7f4c 100644--- a/src/ui/QmlPlayerBridge.cpp+++ b/src/ui/QmlPlayerBridge.cpp@@ -1,4 +1,6 @@#include "veyra/ui/QmlPlayerBridge.h"+#include "veyra/gfx/PresentSink.h"+#include <QElapsedTimer>#include "veyra/ui/EffectAvailability.h"#include "veyra/ui/QmlExportQueueModel.h"#include "veyra/ui/UiLanguage.h"@@ -559,6 +561,12 @@ struct QmlPlayerBridge::Impl {current.initialized[size_t(chain.mode)] = true;current.configurations[size_t(chain.mode)] = engine::ChainConfiguration::capture(activeRuntime(), facade.pendingSettings(), nrIndex(), colourIndex());+ // Custom: the static HDR output tuning does not travel through the runtime+ // configuration yet, so take it straight from the draft globals at the point+ // the session is built. Without this the values took effect and then came+ // back as defaults on the next start.+ current.configurations[size_t(chain.mode)].hdrCurve = draftGlobals.hdrCurve;+ current.configurations[size_t(chain.mode)].hdrMetadata = draftGlobals.hdrMetadata;if (chain.mode == engine::ChainMode::Node) {auto document = std::make_shared<engine::NodeEditorDocument>();document->nodes = chain; document->layout = layout; document->globals = draftGlobals;@@ -611,13 +619,24 @@ struct QmlPlayerBridge::Impl {// The chain is the source of truth for the stage settings; every commit// writes it back over the struct so the two can never disagree.bool commit(engine::EnhancementSettings settings) {+ // Custom: the static HDR output tuning belongs to neither transaction, so+ // keep the draft globals in sync in BOTH modes. Only the node branch below+ // refreshed them, which is why a change made in list mode took effect and+ // then came back as a default after a restart (the session capture reads the+ // tuning from the draft globals).+ draftGlobals.hdrCurve = settings.hdrCurve;+ draftGlobals.hdrMetadata = settings.hdrMetadata;if (chain.mode == engine::ChainMode::Node) {const auto previous = facade.pendingSettings();const auto oldGlobals = draftGlobals;draftGlobals = engine::ChainGlobalSettings::capture(settings);// Non-node controls (e.g. audio) may still change while a wire is// incomplete. Keep runtime globals separate from that transaction.- engine::ChainGlobalSettings::capture(previous).apply(settings);+ // Custom: HDR brightness is one of those controls - it is not part of a+ // node edit, so the restore below must not put the previous value back+ // (field report: a new target peak took effect and then reverted on the+ // next start, because this line overwrote it before the session was+ // captured).facade.setPending(settings);if (revalidate(true, &previous)) return true;draftGlobals = oldGlobals; facade.setPending(previous);@@ -2743,11 +2762,15 @@ void QmlPlayerBridge::ps5PsnForget() {#endif}void QmlPlayerBridge::ps5SendLoginPin(const QString& pin) {+#ifdef VEYRA_ENABLE_REMOTEPLAYconst auto text = pin.trimmed();if (text.isEmpty() || !std::all_of(text.begin(), text.end(), [](QChar c) { return c.isDigit(); })) {impl_->ps5Status = tr("登录 PIN 必须为数字。"); emit ps5Changed(); return;}impl_->engine.remotePlayLoginPin(text.toStdString());+#else+ (void)pin; // RemotePlay disabled: keep the QML-callable symbol but no backend.+#endif}void QmlPlayerBridge::ps5Cancel() {if (impl_->ps5Busy && impl_->ps5Worker.joinable()) { impl_->ps5Worker.request_stop(); return; }@@ -3775,6 +3798,125 @@ bool QmlPlayerBridge::videoHdr() const {const auto* node = impl_->chain.firstOf(engine::EffectType::VideoHdr);return node && node->enabled;}+// Custom: static HDR output tuning. Globals, not chain nodes, and every field is+// live (the curve is read by the present blit, the metadata sent to the display),+// so a change never rebuilds the graph - but it does have to reach the session+// file, which has no other trigger for a global change.+int QmlPlayerBridge::hdrCurveStrength()const{return int(settings().hdrCurve.strengthPercent);}+void QmlPlayerBridge::setHdrCurveStrength(int percent){+ auto s=settings();+ const unsigned clamped=unsigned(std::clamp(percent,0,200));+ if(s.hdrCurve.strengthPercent==clamped)return;+ s.hdrCurve.strengthPercent=clamped;+ commitHdrTuning(std::move(s));+}+int QmlPlayerBridge::hdrDisplayPeakNits()const{return int(settings().hdrCurve.displayPeakNits);}+void QmlPlayerBridge::setHdrDisplayPeakNits(int nits){+ auto s=settings();+ // 0 = ask the system; anything else has to be a plausible panel peak.+ const int clamped=nits<=0?0:std::clamp(nits,100,10000);+ if(s.hdrCurve.displayPeakNits==unsigned(clamped))return;+ s.hdrCurve.displayPeakNits=unsigned(clamped);+ commitHdrTuning(std::move(s));+}+QVariantMap QmlPlayerBridge::hdrDisplayInfo()const{+ // This is read from QML bindings (the peak row's hint text), so it must not do+ // real work per call: building a DXGI factory and enumerating every adapter and+ // output is far too heavy for something the snapshot signal can re-evaluate+ // every frame. Cache it for a few seconds instead.+ static QElapsedTimer cacheTimer;+ static gfx::PresentSink::DisplayPeakInfo cached;+ if(!cacheTimer.isValid()||cacheTimer.elapsed()>5000){+ // No window (the UI asking before playback) = report the primary monitor.+ cached=gfx::PresentSink::queryDisplayPeak(nullptr);+ cacheTimer.restart();+ }+ return {{"valid",cached.valid},{"peakNits",int(cached.peakNits)},+ {"fullFrameNits",int(cached.fullFrameNits)},{"minNits",cached.minNits}};+}+bool QmlPlayerBridge::hdrCurve()const{return settings().hdrCurve.enabled;}+void QmlPlayerBridge::setHdrCurve(bool enabled){+ auto s=settings();if(s.hdrCurve.enabled==enabled)return;s.hdrCurve.enabled=enabled;+ commitHdrTuning(std::move(s));+}+QVariantMap QmlPlayerBridge::hdrCurveParams()const{+ const auto& c=settings().hdrCurve;+ return {{"shadowLiftEv100",int(c.shadowLiftEv100)},{"shadowRangeNits",int(c.shadowRangeNits)},+ {"midGrayNits",int(c.midGrayNits)},{"highlightStartNits",int(c.highlightStartNits)},+ {"rollOffPercent",int(c.rollOffPercent)},{"peakCapNits",int(c.peakCapNits)}};+}+bool QmlPlayerBridge::setHdrCurveParameter(const QString& key,double value){+ if(!std::isfinite(value))return false;+ auto s=settings();const auto v=int(std::lround(value));+ if(key=="shadowLiftEv100"){if(v<-200||v>200)return false;s.hdrCurve.shadowLiftEv100=v;}+ else if(key=="shadowRangeNits"){if(v<1||v>100)return false;s.hdrCurve.shadowRangeNits=unsigned(v);}+ else if(key=="midGrayNits"){if(v<100||v>500)return false;s.hdrCurve.midGrayNits=unsigned(v);}+ else if(key=="highlightStartNits"){if(v<0||v>2000)return false;s.hdrCurve.highlightStartNits=unsigned(v);}+ else if(key=="rollOffPercent"){if(v<10||v>200)return false;s.hdrCurve.rollOffPercent=unsigned(v);}+ else if(key=="peakCapNits"){if(v<0||v>4000)return false;s.hdrCurve.peakCapNits=unsigned(v);}+ else return false;+ if(!s.hdrCurve.valid())return false;+ return commitHdrTuning(std::move(s));+}+bool QmlPlayerBridge::commitHdrTuning(engine::EnhancementSettings settings){+ const auto curve=settings.hdrCurve;+ const auto metadata=settings.hdrMetadata;+ if(!impl_->commit(std::move(settings)))return false;+ // Re-project first, then re-assert both copies the session capture reads:+ // revalidate() rewrites the pending settings and the draft globals from the+ // runtime configuration, which does not carry this block yet.+ impl_->revalidate(true);+ auto after=impl_->facade.pendingSettings();+ after.hdrCurve=curve;after.hdrMetadata=metadata;+ impl_->facade.setPending(after);+ impl_->draftGlobals.hdrCurve=curve;impl_->draftGlobals.hdrMetadata=metadata;+ impl_->persistSession();+ emit settingsChanged();emit chainChanged();return true;+}+QString QmlPlayerBridge::hdrTuningPreset() const {+ const auto& s=settings();+ // hdrPresetMatches deliberately ignores the strength dial and the display peak:+ // they only scale the baseline, so turning them keeps you on the same preset.+ for(const auto& p:engine::kHdrTuningPresets)+ if(engine::hdrPresetMatches(s.hdrCurve,s.hdrMetadata,p))return QString::fromLatin1(p.id);+ return QStringLiteral("custom");+}+bool QmlPlayerBridge::applyHdrTuningPreset(const QString& id){+ for(const auto& p:engine::kHdrTuningPresets){+ if(id!=QLatin1String(p.id))continue;+ auto s=settings();+ // Picking a preset replaces the baseline, not the two dials: how hard the+ // user turned it (and which panel they told us about) must survive.+ const auto strength=s.hdrCurve.strengthPercent;+ const auto displayPeak=s.hdrCurve.displayPeakNits;+ s.hdrCurve=p.curve;s.hdrMetadata=p.metadata;+ s.hdrCurve.strengthPercent=strength;s.hdrCurve.displayPeakNits=displayPeak;+ if(!s.hdrCurve.valid()||!s.hdrMetadata.valid())return false;+ return commitHdrTuning(std::move(s));+ }+ return false;+}+bool QmlPlayerBridge::hdrMetadataEnabled()const{return settings().hdrMetadata.enabled;}+void QmlPlayerBridge::setHdrMetadataEnabled(bool enabled){+ auto s=settings();if(s.hdrMetadata.enabled==enabled)return;s.hdrMetadata.enabled=enabled;+ commitHdrTuning(std::move(s));+}+QVariantMap QmlPlayerBridge::hdrMetadataParams()const{+ const auto& m=settings().hdrMetadata;+ return {{"masteringPeakNits",int(m.masteringPeakNits)},{"maxCllNits",int(m.maxCllNits)},+ {"maxFallNits",int(m.maxFallNits)}};+}+bool QmlPlayerBridge::setHdrMetadataParameter(const QString& key,double value){+ if(!std::isfinite(value))return false;+ auto s=settings();const auto v=int(std::lround(value));+ if(v<0||v>10000)return false;+ if(key=="masteringPeakNits")s.hdrMetadata.masteringPeakNits=unsigned(v);+ else if(key=="maxCllNits")s.hdrMetadata.maxCllNits=unsigned(v);+ else if(key=="maxFallNits")s.hdrMetadata.maxFallNits=unsigned(v);+ else return false;+ if(!s.hdrMetadata.valid())return false;+ return commitHdrTuning(std::move(s));+}void QmlPlayerBridge::setVideoHdr(bool enabled) {for (uint32_t i = 0; i < impl_->chain.nodeCount; ++i)if (impl_->chain.nodes[i].type == engine::EffectType::VideoHdr) {@@ -3794,11 +3936,12 @@ QVariantMap QmlPlayerBridge::videoHdrParams() const {return {};}bool QmlPlayerBridge::setVideoHdrParameter(const QString& key, double value) {- if (!std::isfinite(value) || value < 0) return false;+ if (!std::isfinite(value)) return false;for (uint32_t i = 0; i < impl_->chain.nodeCount; ++i) {auto& node = impl_->chain.nodes[i];if (node.type != engine::EffectType::VideoHdr) continue;const auto before = node;+ if (value < 0) return false;const auto v = unsigned(std::lround(value));if (key == "contrast") node.videoHdr.contrast = v;else if (key == "saturation") node.videoHdr.saturation = v;@@ -5416,7 +5559,12 @@ bool QmlPlayerBridge::applyPresetIndex(int index) {// Keep the facade on accepted values until revalidate projects the new// document. Audio/non-chain preset fields are retained in this copy.engine::fromChain(impl_->activeRuntime(), settings);+ // Custom: the static HDR output tuning rides in the globals block this call+ // re-derives, so preserve the values this commit is carrying.+ const auto keepCurve = settings.hdrCurve;+ const auto keepMetadata = settings.hdrMetadata;engine::ChainGlobalSettings::capture(previous).apply(settings);+ settings.hdrCurve = keepCurve; settings.hdrMetadata = keepMetadata;} else validation = engine::PresetLibrary::applyToChain(entry, candidate, settings);if (!validation.accepted) { emit notice(uiText(validation.message), true); return false; }if (const auto error = settings.validate(); !error.empty()) {diff --git a/tests/unit/HdrOutputTuningTests.cpp b/tests/unit/HdrOutputTuningTests.cppnew file mode 100644index 00000000..94a9ca54--- /dev/null+++ b/tests/unit/HdrOutputTuningTests.cpp@@ -0,0 +1,214 @@+// Unit tests for the static HDR output tuning: preset table legality, parameter+// range validation, the preset resolver (display peak + strength), the match+// semantics used by the UI, PQ conversion, and the whole-title analyzer.+#include <cstdio>+#include <cstring>+#include <string>++#include "veyra/engine/EffectChain.h"+#include "veyra/engine/EnhancementSettings.h"+#include "veyra/engine/HdrOutputTuning.h"++namespace {++int failures = 0;++void check(bool ok, const std::string& what) {+ std::printf("%s %s\n", ok ? "PASS" : "FAIL", what.c_str());+ if (!ok) ++failures;+}+++} // namespace++int main() {+ std::setvbuf(stdout, nullptr, _IONBF, 0);+ using namespace veyra::engine;++ // ---- 1) the preset table itself ----+ check(kHdrTuningPresetCount >= 7, "presets: at least seven entries");+ for (std::size_t i = 0; i < kHdrTuningPresetCount; ++i) {+ const auto& p = kHdrTuningPresets[i];+ check(std::strlen(p.id) > 0, std::string("presets: entry ") + std::to_string(i) + " has an id");+ check(p.curve.valid(), std::string("presets: ") + p.id + " curve is within range");+ check(p.metadata.valid(), std::string("presets: ") + p.id + " metadata is within range");+ check(p.curve.strengthPercent == 100,+ std::string("presets: ") + p.id + " ships at 100% strength");+ for (std::size_t j = i + 1; j < kHdrTuningPresetCount; ++j)+ check(std::strcmp(p.id, kHdrTuningPresets[j].id) != 0,+ std::string("presets: id ") + p.id + " is unique");+ check(findHdrTuningPreset(p.id) == &p, std::string("presets: lookup finds ") + p.id);+ }+ check(findHdrTuningPreset("no-such-preset") == nullptr, "presets: lookup rejects an unknown id");+ {+ const HdrTuningPreset* dark = findHdrTuningPreset("darkLift");+ const HdrTuningPreset* bright = findHdrTuningPreset("highlightGuard");+ check(dark && dark->curve.enabled && dark->curve.shadowLiftEv100 > 0,+ "presets: darkLift actually lifts the shadows");+ check(bright && bright->curve.enabled && bright->curve.highlightStartNits > 0,+ "presets: highlightGuard has a highlight roll-off");+ }++ // ---- 2) parameter range validation ----+ {+ HdrCurveSettings c;+ check(c.valid(), "range: default curve settings are valid");+ check(!c.enabled, "range: the curve is off by default (identity transform)");+ check(c.strengthPercent == 100, "range: strength defaults to 100%");+ check(c.displayPeakNits == 0, "range: display peak defaults to follow the system");+ c.midGrayNits = 99;+ check(!c.valid(), "range: mid-gray below 100 is rejected");+ c.midGrayNits = 501;+ check(!c.valid(), "range: mid-gray above 500 is rejected");+ c.midGrayNits = 203;+ c.shadowLiftEv100 = 201;+ check(!c.valid(), "range: shadow lift above 200 is rejected");+ c.shadowLiftEv100 = -201;+ check(!c.valid(), "range: shadow lift below -200 is rejected");+ c.shadowLiftEv100 = 0;+ c.highlightStartNits = 50;+ check(!c.valid(), "range: highlight start must be 0 or at least 100");+ c.highlightStartNits = 0;+ c.peakCapNits = 50;+ check(!c.valid(), "range: peak cap must be 0 or at least 100");+ c.peakCapNits = 0;+ c.rollOffPercent = 9;+ check(!c.valid(), "range: roll-off below 10% is rejected");+ c.rollOffPercent = 100;+ c.strengthPercent = 201;+ check(!c.valid(), "range: strength above 200 is rejected");+ c.strengthPercent = 100;+ c.displayPeakNits = 50;+ check(!c.valid(), "range: display peak must be 0 or at least 100");+ c.displayPeakNits = 10001;+ check(!c.valid(), "range: display peak above 10000 is rejected");+ }+ {+ HdrMetadataSettings m;+ check(m.valid(), "range: default metadata settings are valid");+ check(m.enabled, "range: metadata defaults to on (0 = follow the source)");+ m.masteringPeakNits = 50;+ check(!m.valid(), "range: mastering peak must be 0 or at least 100");+ m.masteringPeakNits = 0;+ m.maxFallNits = 20000;+ check(!m.valid(), "range: MaxFALL above 10000 is rejected");+ }++ // ---- 3) preset resolver: display peak then strength ----+ {+ const auto* dark = findHdrTuningPreset("darkLift");+ const auto* guard = findHdrTuningPreset("highlightGuard");+ HdrCurveSettings c;+ HdrMetadataSettings m;++ resolveHdrTuning(*dark, 100, 0, c, m);+ check(c == dark->curve, "resolve: baseline (no peak, 100%) equals the preset curve");+ check(m == dark->metadata, "resolve: baseline metadata equals the preset metadata");++ // A 600 nit display pulls the highlight work in, and must NOT touch the+ // shadow or mid-gray numbers (those describe content and environment).+ resolveHdrTuning(*guard, 100, 600, c, m);+ check(c.highlightStartNits == 270, "resolve: 600 nit display rolls off at 450*0.6");+ check(c.peakCapNits == 600, "resolve: 600 nit display caps at its own peak");+ check(c.midGrayNits == guard->curve.midGrayNits, "resolve: display peak does not move the mid-gray");+ check(c.shadowLiftEv100 == guard->curve.shadowLiftEv100 &&+ c.shadowRangeNits == guard->curve.shadowRangeNits,+ "resolve: display peak does not touch the shadow lift");+ check(m.masteringPeakNits == 600, "resolve: metadata peak follows the display");+ check(c.displayPeakNits == 600, "resolve: the resolved value records the display peak");++ resolveHdrTuning(*guard, 100, 2000, c, m);+ check(c.highlightStartNits == 900 && c.peakCapNits == 2000,+ "resolve: a 2000 nit display gets the whole range back");++ resolveHdrTuning(*guard, 0, 0, c, m);+ check(!c.enabled, "resolve: 0% strength fades the curve out entirely");+ resolveHdrTuning(*dark, 50, 0, c, m);+ check(c.shadowLiftEv100 == 25, "resolve: 50% halves the shadow lift");+ check(c.midGrayNits == 214, "resolve: 50% halves the mid-gray shift (203 + 22/2)");+ check(c.shadowRangeNits == 18, "resolve: 50% narrows the lift range");+ resolveHdrTuning(*guard, 50, 0, c, m);+ check(c.highlightStartNits == 900, "resolve: 50% starts the roll-off earlier (450/0.5)");+ check(c.peakCapNits == 1000, "resolve: the hard cap does not follow the strength dial");+ resolveHdrTuning(*dark, 200, 0, c, m);+ check(c.shadowLiftEv100 == 100, "resolve: 200% doubles the shadow lift");+ resolveHdrTuning(*guard, 200, 0, c, m);+ check(c.highlightStartNits == 225, "resolve: 200% compresses from further down (450/2)");++ bool allValid = true;+ for (std::size_t i = 0; i < kHdrTuningPresetCount; ++i) {+ for (unsigned s : {0u, 25u, 50u, 100u, 150u, 200u}) {+ for (unsigned p : {0u, 400u, 600u, 1000u, 2000u, 4000u, 10000u}) {+ resolveHdrTuning(kHdrTuningPresets[i], s, p, c, m);+ if (!c.valid() || !m.valid()) {+ allValid = false;+ std::printf("FAIL resolve: out of range for %s strength=%u peak=%u\n",+ kHdrTuningPresets[i].id, s, p);+ }+ }+ }+ }+ check(allValid, "resolve: every preset x strength x display peak stays within range");+ }++ // ---- 4) match semantics used by the UI ----+ {+ const auto* dark = findHdrTuningPreset("darkLift");+ // The stored value is the baseline (what the preset ships); the dial and the+ // display peak are stored next to it and must not affect the match.+ HdrCurveSettings c = dark->curve;+ HdrMetadataSettings m = dark->metadata;+ check(hdrPresetMatches(c, m, *dark), "match: the raw preset matches itself");+ c.strengthPercent = 60;+ c.displayPeakNits = 800;+ check(hdrPresetMatches(c, m, *dark), "match: turning the dial keeps you on the same preset");+ c.displayPeakNits = 1600;+ check(hdrPresetMatches(c, m, *dark), "match: changing the display peak keeps the preset selected");+ c.shadowLiftEv100 += 1;+ check(!hdrPresetMatches(c, m, *dark), "match: editing a slider moves to custom");++ HdrCurveSettings resolved;+ HdrMetadataSettings resolvedMeta;+ resolveHdrTuning(*dark, 60, 800, resolved, resolvedMeta);+ check(resolved != dark->curve,+ "resolve: the applied curve differs from the baseline once scaled");+ check(resolvedMeta.masteringPeakNits == 560,+ "resolve: metadata peak scales with the display (700 * 0.8)");+ }++ // ---- 5) the two capture paths the session is written from ----+ {+ EnhancementSettings s;+ s.hdrCurve.enabled = true;+ s.hdrCurve.shadowLiftEv100 = 50;+ s.hdrCurve.shadowRangeNits = 35;+ s.hdrCurve.midGrayNits = 260;+ s.hdrCurve.strengthPercent = 140;+ s.hdrCurve.displayPeakNits = 1600;+ s.hdrMetadata.enabled = true;+ s.hdrMetadata.masteringPeakNits = 700;++ const auto globals = ChainGlobalSettings::capture(s);+ check(globals.hdrCurve == s.hdrCurve, "capture: globals carry the curve");+ check(globals.hdrCurve.strengthPercent == 140, "capture: globals carry the strength");+ check(globals.hdrCurve.displayPeakNits == 1600, "capture: globals carry the display peak");+ check(globals.hdrMetadata == s.hdrMetadata, "capture: globals carry the metadata");++ EnhancementSettings back;+ globals.apply(back);+ check(back.hdrCurve == s.hdrCurve, "capture: globals restore the curve");+ check(back.hdrMetadata == s.hdrMetadata, "capture: globals restore the metadata");++ EffectChain chain;+ const auto configuration = ChainConfiguration::capture(chain, s, 0, 0);+ check(configuration.hdrCurve == s.hdrCurve,+ "capture: a chain configuration carries the curve (this is what the session stores)");+ check(configuration.hdrMetadata == s.hdrMetadata,+ "capture: a chain configuration carries the metadata");+ }++ std::printf(failures == 0 ? "hdr output tuning: all checks passed\n"+ : "hdr output tuning: %d FAILURES\n",+ failures);+ return failures == 0 ? 0 : 1;+}