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(display): HDR state from the display-state service, one refresh on the signal card
Veyra Goal Agentb2eb77dfe7c2
diff --git a/i18n/catalog.json b/i18n/catalog.jsonindex 9428ebf2..a8f93039 100644--- a/i18n/catalog.json+++ b/i18n/catalog.json@@ -2688,6 +2688,13 @@"en": "Don't forward this PC's controller input to the PS5","ja": "この PC のコントローラー入力を PS5 に転送しない"},+ {+ "zh": "不支持",+ "src": "src/ui/QmlPlayerBridge.cpp",+ "zh-TW": "不支援",+ "en": "Not supported",+ "ja": "非対応"+ },{"zh": "不是 8 位配对码","src": "qml/DialogHost.qml",@@ -4572,6 +4579,20 @@"en": "Flush and close the output file","ja": "出力ファイルのフラッシュとクローズ"},+ {+ "zh": "刷新显示器状态",+ "src": "qml/NodePage.qml",+ "zh-TW": "重新整理顯示器狀態",+ "en": "Refresh display state",+ "ja": "ディスプレイの状態を更新"+ },+ {+ "zh": "刷新显示器状态没有完成,请稍后再试",+ "src": "src/ui/QmlPlayerBridge.cpp",+ "zh-TW": "重新整理顯示器狀態未完成,請稍後再試",+ "en": "Refreshing the display state did not finish; try again later",+ "ja": "ディスプレイの状態の更新が完了しませんでした。しばらくしてからもう一度お試しください"+ },{"zh": "刷新设备","src": "qml/DialogHost.qml",@@ -7218,6 +7239,13 @@"en": "Removed.","ja": "削除しました。"},+ {+ "zh": "已刷新显示器状态:系统 HDR %1 · 可变刷新 %2",+ "src": "src/ui/QmlPlayerBridge.cpp",+ "zh-TW": "已重新整理顯示器狀態:系統 HDR %1 · 可變更新 %2",+ "en": "Display state refreshed: Windows HDR %1 · variable refresh %2",+ "ja": "ディスプレイの状態を更新しました:システム HDR %1 · 可変リフレッシュ %2"+ },{"zh": "已加载","src": "qml/SettingsPage.qml",@@ -7617,6 +7645,13 @@"en": "Set as the startup default preset","ja": "起動時の既定プリセットに設定しました"},+ {+ "zh": "已请求",+ "src": "src/ui/QmlPlayerBridge.cpp",+ "zh-TW": "已請求",+ "en": "Requested",+ "ja": "要求済み"+ },{"zh": "已请求主机退出游戏。","src": "src/ui/MoonlightModel.cpp",@@ -7680,13 +7715,6 @@"en": "Keyboard and mouse released (click the picture to capture again)","ja": "キーボードとマウスを解放しました(映像をクリックすると再度キャプチャー)"},- {- "zh": "已重新检测:%1",- "src": "src/ui/QmlPlayerBridge.cpp",- "zh-TW": "已重新偵測:%1",- "en": "Checked again: %1",- "ja": "再検出しました:%1"- },{"zh": "已锁定全屏 · Ctrl+L 解锁,Esc 退出全屏","src": "qml/Main.qml",@@ -7806,6 +7834,13 @@"en": "Distance from bottom","ja": "下端からの距離"},+ {+ "zh": "开",+ "src": "qml/ProPage.qml",+ "zh-TW": "開",+ "en": "On",+ "ja": "オン"+ },{"zh": "开关、进度、选中状态","src": "qml/SettingsPage.qml",@@ -8114,6 +8149,13 @@"en": "Current · settings are kept as they are","ja": "現在 · 設定はそのまま保持"},+ {+ "zh": "当前不可用",+ "src": "src/ui/QmlPlayerBridge.cpp",+ "zh-TW": "目前不可用",+ "en": "Unavailable now",+ "ja": "現在は使用不可"+ },{"zh": "当前为 SDR 预览,HDR 转换未运行","src": "src/engine/EngineController.cpp",@@ -9921,6 +9963,13 @@"en": "Cannot construct the selected capture format. Check resolution, frame rate and driver capabilities.","ja": "選択したキャプチャ形式を作成できません。解像度、レート、ドライバーの対応能力を確認してください。"},+ {+ "zh": "无法检测",+ "src": "src/ui/QmlPlayerBridge.cpp",+ "zh-TW": "無法偵測",+ "en": "Cannot detect",+ "ja": "検出できません"+ },{"zh": "无法检测屏幕是否支持(目前只支持 NVIDIA 显卡)","src": "src/ui/QmlPlayerBridge.cpp",@@ -12343,6 +12392,13 @@"en": "Ambient compensation: add some in a bright room; use none in a dark room","ja": "環境光補正:明るい部屋では補正し、暗い部屋では補正しません"},+ {+ "zh": "生效中",+ "src": "src/ui/QmlPlayerBridge.cpp",+ "zh-TW": "生效中",+ "en": "Active",+ "ja": "有効"+ },{"zh": "生效中:NVIDIA DLSS 帧生成性能模式(测试版)","src": "src/ui/QmlPlayerBridge.cpp",@@ -13141,6 +13197,13 @@"en": "Fine: restores chroma by position and scales up bicubically; not AI super resolution","ja": "精細:位置に合わせて色差を復元し、拡大はバイキュービック。AI 超解像ではありません"},+ {+ "zh": "系统 HDR",+ "src": "qml/ProPage.qml",+ "zh-TW": "系統 HDR",+ "en": "Windows HDR",+ "ja": "システム HDR"+ },{"zh": "系统不支持 Windows Graphics Capture","src": "src/source/ScreenCaptureSource.cpp",@@ -16977,20 +17040,6 @@"en": "Continue from the last position when the same file is reopened","ja": "同じファイルを開き直すと前回の位置から再開"},- {- "zh": "重新检测",- "src": "qml/NodePage.qml",- "zh-TW": "重新偵測",- "en": "Check again",- "ja": "再検出"- },- {- "zh": "重新检测没有完成,请稍后再试",- "src": "src/ui/QmlPlayerBridge.cpp",- "zh-TW": "重新偵測未完成,請稍後再試",- "en": "The check did not finish. Please try again shortly.",- "ja": "再検出が完了しませんでした。しばらくしてから再試行してください。"- },{"zh": "重置本页","src": "qml/ProPage.qml",diff --git a/include/veyra/engine/DisplayStateService.h b/include/veyra/engine/DisplayStateService.hindex ae403398..148ad449 100644--- a/include/veyra/engine/DisplayStateService.h+++ b/include/veyra/engine/DisplayStateService.h@@ -11,21 +11,30 @@#include <vector>namespace veyra::engine {-// Refresh rate and NVIDIA variable-refresh state of one monitor.+// Windows HDR ("Use HDR") and the luminance the panel reports through DXGI.+struct DisplayColorState {+ std::optional<bool> hdr; // none: the output description could not be read+ bool peakValid=false;+ unsigned peakNits=0,fullFrameNits=0;+ double minNits=0;+};+// Refresh rate, NVIDIA variable-refresh and HDR state of one monitor.struct DisplayState {HMONITOR monitor=nullptr;double refreshHz=0;gfx::VrrState vrr{};+ DisplayColorState color{};uint64_t generation=0; // display generation the query ran inuint64_t serial=0; // stored-result counter (all monitors): a holder applies each state once- double refreshMs=0,vrrMs=0; // driver call wall time on the worker thread+ double refreshMs=0,vrrMs=0,colorMs=0; // driver call wall time on the worker thread};-// Display states shared by the presenter and the UI (2026-10-25,-// docs/VRR_EVENT_QUERY_PLAN_2026-10-25.md). Nothing re-reads them on a timer:-// holders may call request() every frame or tick, and a query only runs when-// the monitor has no state of the current display generation. invalidate() (a-// display change, the 可变刷新 switch turned on, 重新检测) makes every state-// stale; force is for the session-start check and the VRR confirmation. One+// Display states shared by the engine, the presenter and the UI (2026-10-25,+// docs/VRR_EVENT_QUERY_PLAN_2026-10-25.md; HDR 2026-10-26). Nothing re-reads them+// on a timer: holders may call request() every frame or tick, and a query only+// runs when the monitor has no state of the current display generation.+// invalidate() (a display change, the 可变刷新 switch turned on, 刷新显示器状态)+// makes every state stale; force is for the session-start check and the VRR+// confirmation. One// query runs at a time on a worker thread and the others wait in a queue.// Reading never waits, except wait(), which only a new presentation chain uses.// A failed query (an NVAPI error, the window closed or moved meanwhile, an@@ -35,7 +44,7 @@ public:using Clock=std::chrono::steady_clock;using Query=std::function<DisplayState(HWND,HMONITOR)>;using MonitorOf=std::function<HMONITOR(HWND)>;- // QueryDisplayConfig refresh + NVAPI VRR of the window's monitor.+ // QueryDisplayConfig refresh + NVAPI VRR + DXGI HDR of the window's monitor.DisplayStateService();// Tests: fake query, monitor lookup and retry delay.DisplayStateService(Query,MonitorOf,std::chrono::milliseconds retryDelay=std::chrono::seconds(2));diff --git a/include/veyra/engine/VideoPresenter.h b/include/veyra/engine/VideoPresenter.hindex 8971c9f6..64a225da 100644--- a/include/veyra/engine/VideoPresenter.h+++ b/include/veyra/engine/VideoPresenter.h@@ -108,9 +108,8 @@ private:// real value keeps the reported metadata steady instead of flapping to the// fallback (which re-sent it on nearly every frame).HdrSourceMetadata sourceMetadata_{};- HMONITOR hdrPeakMonitor_=nullptr;gfx::PresentSink::DisplayPeakInfo hdrPeakInfo_{};- std::chrono::steady_clock::time_point hdrPeakQuery_{},metadataAttempt_{};+ std::chrono::steady_clock::time_point metadataAttempt_{};DXGI_HDR_METADATA_HDR10 lastMetadata_{};gfx::ReflexSession reflex_;uint64_t reflexFrame_=0,generation_=0;diff --git a/include/veyra/gfx/PresentSink.h b/include/veyra/gfx/PresentSink.hindex d5dc6575..03e87288 100644--- a/include/veyra/gfx/PresentSink.h+++ b/include/veyra/gfx/PresentSink.h@@ -27,13 +27,6 @@ using ComPtr = Microsoft::WRL::ComPtr<T>;class PresentSink {public:- static bool hdrDisplayActive(HWND);- // The factory is cached process-wide; DXGI factories detect display- // topology changes (IsCurrent) so a stale one is recreated on demand.- // Creating a factory and enumerating every adapter/output each call ran- // 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.@@ -43,7 +36,14 @@ public:double minNits = 0.0; // black levelbool valid = false;};- static DisplayPeakInfo queryDisplayPeak(HWND);+ static bool hdrDisplayActive(HWND);+ // The factory is cached process-wide; DXGI factories detect display+ // topology changes (IsCurrent) so a stale one is recreated on demand.+ // Creating a factory and enumerating every adapter/output each call ran+ // on the graph owner every 2 s under HDR (sweep 2026-09-22 A1). `peak`+ // receives the same output description's luminance.+ static std::optional<bool> queryHdrDisplayActive(HWND,HMONITOR* queriedMonitor=nullptr,DisplayPeakInfo* peak=nullptr);+ static double displayRefreshFps(HWND);PresentSink() = default;~PresentSink();diff --git a/include/veyra/ui/QmlPlayerBridge.h b/include/veyra/ui/QmlPlayerBridge.hindex 67552863..6bf73fcb 100644--- a/include/veyra/ui/QmlPlayerBridge.h+++ b/include/veyra/ui/QmlPlayerBridge.h@@ -436,10 +436,15 @@ class QmlPlayerBridge : public QObject {Q_PROPERTY(bool variableRefresh READ variableRefresh WRITE setVariableRefresh NOTIFY presentationChanged)Q_PROPERTY(int vrrState READ vrrState NOTIFY perfChanged)Q_PROPERTY(QString vrrHint READ vrrHint NOTIFY perfChanged)- // The level is read on events only (startup, another monitor, a display- // change, the switch turned on); 重新检测 (recheckDisplay) asks the driver- // again, and vrrChecking is true until that answer arrives.- Q_PROPERTY(bool vrrChecking READ vrrChecking NOTIFY perfChanged)+ // Display state of the shown monitor for the 信号 card: Windows HDR (-1+ // unknown, 0 off, 1 on), refresh rate (0 unknown) and a short VRR summary.+ // Everything is read on events only (startup, another monitor, a display+ // change, the switch turned on); 刷新显示器状态 (recheckDisplay) asks the+ // driver again, and displayChecking is true until that answer arrives.+ Q_PROPERTY(int displayHdr READ displayHdr NOTIFY perfChanged)+ Q_PROPERTY(double displayRefreshHz READ displayRefreshHz NOTIFY perfChanged)+ Q_PROPERTY(QString vrrSummary READ vrrSummary NOTIFY perfChanged)+ Q_PROPERTY(bool displayChecking READ displayChecking NOTIFY perfChanged)Q_PROPERTY(int outputRateMode READ outputRateMode WRITE setOutputRateMode NOTIFY presentationChanged)Q_PROPERTY(double outputCustomFps READ outputCustomFps WRITE setOutputCustomFps NOTIFY presentationChanged)Q_PROPERTY(bool presentationOwned READ presentationOwned NOTIFY snapshotChanged)@@ -1067,7 +1072,10 @@ public:void setVariableRefresh(bool value);int vrrState() const;QString vrrHint() const;- bool vrrChecking() const;+ int displayHdr() const;+ double displayRefreshHz() const;+ QString vrrSummary() const;+ bool displayChecking() const;Q_INVOKABLE void recheckDisplay();QString fgDisplayHint() const;Q_INVOKABLE void setPresentationFullscreen(bool value);@@ -1424,6 +1432,7 @@ private:void updateRunStatus();// vrrHint's text for a VRR level (the 重新检测 result notice uses it too).QString vrrHintText(int level) const;+ QString vrrSummaryText(int level) const;void applyPresentation();void applyAspect(bool force);// Live sources started from the start page: switch to 极简 first, show thediff --git a/qml/Veyra/NodePage.qml b/qml/Veyra/NodePage.qmlindex 685b042e..2dfb21cb 100644--- a/qml/Veyra/NodePage.qml+++ b/qml/Veyra/NodePage.qml@@ -832,20 +832,21 @@ VPage {onPicked: id => veyra.displaySync = Number(id)}// 可变刷新 (G-SYNC / FreeSync): the switch greys when the monitor- // cannot do it; 重新检测 stays available (read on events only).+ // cannot do it. The node page has no 信号 card, so the shared+ // 刷新显示器状态 (HDR, refresh rate, VRR; read on events only) sits here.RowLayout {Layout.fillWidth: trueNodeLabel { Layout.fillWidth: true; text: qsTr("可变刷新"); wrapMode: Text.WordWrap }Item {implicitWidth: Theme.ctlHeight; implicitHeight: Theme.ctlHeightVButton {- objectName: "node-vrr-recheck"+ objectName: "node-display-refresh"anchors.fill: parent- visible: !veyra.vrrChecking- icon: true; ghost: true; iconName: "refresh"; tip: qsTr("重新检测")+ visible: !veyra.displayChecking+ icon: true; ghost: true; iconName: "refresh"; tip: qsTr("刷新显示器状态")onClicked: veyra.recheckDisplay()}- VSpinner { anchors.centerIn: parent; visible: veyra.vrrChecking }+ VSpinner { anchors.centerIn: parent; visible: veyra.displayChecking }}VSwitch {objectName: "node-vrr"diff --git a/qml/Veyra/ProPage.qml b/qml/Veyra/ProPage.qmlindex 91ab7058..e92fde46 100644--- a/qml/Veyra/ProPage.qml+++ b/qml/Veyra/ProPage.qml@@ -143,31 +143,17 @@ VPage {}}// 可变刷新 (G-SYNC / FreeSync): the switch greys when the monitor cannot- // do it. The state is read on events only; 重新检测 stays available and- // asks the driver again (its icon becomes a spinner meanwhile).+ // do it. The state is read on events only; 刷新显示器状态 in the 信号+ // card asks the driver again.VRow {label: qsTr("可变刷新")hint: veyra.vrrHint- RowLayout {- spacing: 6- Item {- implicitWidth: Theme.ctlHeight; implicitHeight: Theme.ctlHeight- VButton {- objectName: "presentation-vrr-recheck"- anchors.fill: parent- visible: !veyra.vrrChecking- icon: true; ghost: true; iconName: "refresh"; tip: qsTr("重新检测")- onClicked: veyra.recheckDisplay()- }- VSpinner { anchors.centerIn: parent; visible: veyra.vrrChecking }- }- VSwitch {- objectName: "presentation-vrr"- enabled: veyra.vrrState >= 2- opacity: enabled ? 1 : 0.5- checked: veyra.variableRefresh- onToggled: checked => veyra.variableRefresh = checked- }+ VSwitch {+ objectName: "presentation-vrr"+ enabled: veyra.vrrState >= 2+ opacity: enabled ? 1 : 0.5+ checked: veyra.variableRefresh+ onToggled: checked => veyra.variableRefresh = checked}}VRow {@@ -1016,7 +1002,24 @@ VPage {anchors.fill: parentanchors.margins: 14spacing: 6- VEyebrow { text: qsTr("信号") }+ RowLayout {+ Layout.fillWidth: true+ VEyebrow { Layout.fillWidth: true; text: qsTr("信号") }+ // 刷新显示器状态: Windows HDR, refresh rate and variable refresh are+ // read on events only (startup, a display or monitor change, the+ // 可变刷新 switch turned on); this asks the driver again.+ Item {+ implicitWidth: 22; implicitHeight: 22+ VButton {+ objectName: "pro-display-refresh"+ anchors.fill: parent+ visible: !veyra.displayChecking+ icon: true; ghost: true; iconName: "refresh"; tip: qsTr("刷新显示器状态")+ onClicked: veyra.recheckDisplay()+ }+ VSpinner { anchors.centerIn: parent; visible: veyra.displayChecking }+ }+ }GridLayout {Layout.fillWidth: truecolumns: 2@@ -1053,6 +1056,24 @@ VPage {horizontalAlignment: Text.AlignRightelide: Text.ElideRight}+ // The shown monitor: the video's while playing, otherwise the window's.+ Text { text: qsTr("系统 HDR"); color: Theme.t3; font.family: Theme.fontUi; font.pixelSize: 12 }+ Text {+ objectName: "pro-display-hdr"+ Layout.fillWidth: true+ text: veyra.displayHdr > 0 ? qsTr("开") : veyra.displayHdr === 0 ? qsTr("关") : qsTr("未知")+ color: Theme.t1; font.family: Theme.fontMono; font.pixelSize: 12+ horizontalAlignment: Text.AlignRight+ }+ Text { text: qsTr("可变刷新"); color: Theme.t3; font.family: Theme.fontUi; font.pixelSize: 12 }+ Text {+ objectName: "pro-display-vrr"+ Layout.fillWidth: true+ text: veyra.vrrSummary + (veyra.displayRefreshHz > 0 ? " · " + veyra.displayRefreshHz.toFixed(0) + " Hz" : "")+ color: veyra.vrrState >= 4 ? Theme.ok : Theme.t1; font.family: Theme.fontMono; font.pixelSize: 12+ horizontalAlignment: Text.AlignRight+ elide: Text.ElideRight+ }// Network / server playback (#48): buffer, download speed, reconnects.Text { visible: veyra.networkActive; text: qsTr("网络"); color: Theme.t3; font.family: Theme.fontUi; font.pixelSize: 12 }Text {diff --git a/scripts/acceptance/capture-review-shots.py b/scripts/acceptance/capture-review-shots.pynew file mode 100644index 00000000..ea17f2af--- /dev/null+++ b/scripts/acceptance/capture-review-shots.py@@ -0,0 +1,113 @@+"""Anti-aliasing comparison of the capture-review screenshots (claude-capture-review-20261026).++Decodes each JXR (scRGB half float) with WIC through PowerShell/WPF, then compares+luma in the perceptual domain the anti-aliasing passes use (reference white 203 nits):+the whole picture, edge pixels only, and the edge high-frequency energy that jaggies+add. A still game picture is required; nr-aa-off-repeat measures what NR's+temporal history alone changes between two identical configurations.+Shots are named from the run log ("[capture-review] shot <name> file=<path>"); the+engine swaps the extension to .jxr for HDR output, so files are matched by stem.+nrEnabled switches the selected NR layer only: the user's chain keeps a second NR+layer on, so the "nonr" steps still ran one NR layer, and the node-mode step loaded+node mode's own (empty) chain. Both are reported as such, not as AA-before-NR or+AA-without-NR evidence.+usage: py -3.11 -X utf8 -B -I scripts/acceptance/capture-review-shots.py+"""+from pathlib import Path+import json, re, subprocess+import numpy as np+from PIL import Image++B = Path('E:/项目/Veyra'); T = 'claude-capture-review-20261026'+SHOTS = B/'tests'/T/'shots'; OUT = B/'reports'/T; RAW = B/'tmp'/T/'shots-raw'; LOG = B/'logs'/T/'capture'/'engine.log'+RAW.mkdir(parents=True, exist_ok=True)+DECODE = r'''param([string]$In,[string]$Out)+Add-Type -AssemblyName PresentationCore,WindowsBase+$s=[IO.File]::OpenRead($In)+try{+$d=New-Object System.Windows.Media.Imaging.WmpBitmapDecoder($s,[System.Windows.Media.Imaging.BitmapCreateOptions]::PreservePixelFormat,[System.Windows.Media.Imaging.BitmapCacheOption]::OnLoad)+$f=$d.Frames[0]+$c=New-Object System.Windows.Media.Imaging.FormatConvertedBitmap($f,[System.Windows.Media.PixelFormats]::Rgba128Float,$null,0)+$w=$c.PixelWidth;$h=$c.PixelHeight;$stride=$w*16;$buf=New-Object byte[] ($stride*$h)+$c.CopyPixels($buf,$stride,0);[IO.File]::WriteAllBytes($Out,$buf);Write-Output "$w $h $($f.Format)"+}finally{$s.Close()}+'''+script = RAW/'decode.ps1'; script.write_text(DECODE, 'utf-8-sig')+++def decode(path):+ raw = RAW/(path.stem + '.f32')+ out = subprocess.run(['powershell', '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', str(script), str(path), str(raw)],+ capture_output=True, text=True, timeout=120)+ w, h, fmt = out.stdout.split()[:3]+ rgba = np.fromfile(raw, dtype=np.float32).reshape(int(h), int(w), 4)+ return rgba[..., :3], fmt+++def perceptual_luma(rgb):+ # AntiAlias.hlsli: linear working colour, 1.0 = 80 nits; reference white 203 nits.+ y = np.maximum(rgb @ np.array([0.2126, 0.7152, 0.0722], dtype=np.float32), 0) * (80.0 / 203.0)+ low = np.where(y <= 0.0031308, 12.92 * y, 1.055 * np.power(np.minimum(y, 1.0), 1 / 2.4) - 0.055)+ return np.where(y > 1.0, 1.0 + 0.30469 * np.log2(np.maximum(y, 1e-6)), low)+++def gradient(l):+ gx = np.zeros_like(l); gy = np.zeros_like(l)+ gx[:, 1:-1] = l[:, 2:] - l[:, :-2]; gy[1:-1, :] = l[2:, :] - l[:-2, :]+ return np.hypot(gx, gy)+++def laplacian(l):+ out = np.zeros_like(l)+ out[1:-1, 1:-1] = 4 * l[1:-1, 1:-1] - l[:-2, 1:-1] - l[2:, 1:-1] - l[1:-1, :-2] - l[1:-1, 2:]+ return np.abs(out)+++requested = {}+for line in LOG.read_text('utf8', errors='replace').splitlines():+ if m := re.search(r'\[capture-review\] shot (\S+) file=(\S+) \| (.*)', line): requested[m.group(1)] = (Path(m.group(2)).stem, m.group(3))+files = {p.stem: p for p in SHOTS.iterdir() if p.suffix.lower() in ('.jxr', '.png')}+named = {}+for name, (stem, state) in requested.items():+ path = files[stem]+ rgb, fmt = decode(path) if path.suffix.lower() == '.jxr' else (np.asarray(Image.open(path).convert('RGB'), np.float32) / 255.0, 'png')+ named[name] = dict(path=path, state=state, format=fmt,+ luma=perceptual_luma(rgb) if fmt != 'png' else rgb @ np.array([0.2126, 0.7152, 0.0722], np.float32))+base = named['nr-aa-off']['luma']+edges = gradient(base) > 0.08 # edge pixels of the reference picture+energy = lambda l: float(laplacian(l)[edges].mean())+++def compare(a, b):+ la, lb = named[a]['luma'], named[b]['luma']+ d = np.abs(la - lb)+ return dict(meanAbs=float(d.mean()), edgeMeanAbs=float(d[edges].mean()), flatMeanAbs=float(d[~edges].mean()),+ changedPixels=float((d > 2 / 255).mean()), edgeEnergyA=energy(la), edgeEnergyB=energy(lb))+++pairs = {'NR history noise, two NR layers (same config twice)': ('nr-aa-off', 'nr-aa-off-repeat'),+ 'AA after two NR layers (new placement)': ('nr-aa-off', 'nr-aa-after'),+ 'AA after one NR layer (new placement)': ('nonr-aa-off', 'nonr-aa-on')}+results = {k: compare(*v) for k, v in pairs.items()}+# Visual: the 96x96 window where AA after NR changed edges most, 4x nearest.+d = np.abs(named['nr-aa-off']['luma'] - named['nr-aa-after']['luma']) * edges+k = 96; best = None+for y in range(0, d.shape[0] - k, k // 2):+ for x in range(0, d.shape[1] - k, k // 2):+ s = float(d[y:y + k, x:x + k].sum())+ if best is None or s > best[0]: best = (s, y, x)+_, y, x = best+tiles = []+crop_order = ['nr-aa-off', 'nr-aa-after', 'nr-aa-off-repeat', 'nonr-aa-off', 'nonr-aa-on']+for n in crop_order:+ crop = np.clip(named[n]['luma'][y:y + k, x:x + k], 0, 1.4) / 1.4+ tiles.append(np.kron((crop * 255).astype(np.uint8), np.ones((4, 4), np.uint8)))+strip = np.concatenate([np.pad(t, ((0, 0), (0, 8)), constant_values=255) for t in tiles], axis=1)+Image.fromarray(strip).save(OUT/'aa-crops.png')+report = dict(shots={n: str(v['path']) for n, v in named.items()}, formats={n: v['format'] for n, v in named.items()},+ states={n: v['state'] for n, v in named.items()}, edgeFraction=float(edges.mean()), comparisons=results,+ excluded={'nr-aa-before-node': 'node mode loaded its own chain (plan steps=0 nr=0): no NR, no AA, so not an AA-before-NR picture'},+ note='nrEnabled switches the selected NR layer; the copied chain keeps another NR layer on, so the nonr-* steps ran one NR layer (plan nr=1)',+ crop=dict(x=x, y=y, size=k, order=' | '.join(crop_order), file=str(OUT/'aa-crops.png')))+(OUT/'aa-shots.json').write_text(json.dumps(report, ensure_ascii=False, indent=1), 'utf-8')+print(json.dumps({k: report[k] for k in ['formats', 'edgeFraction', 'comparisons', 'crop']}, ensure_ascii=False, indent=1))diff --git a/scripts/acceptance/capture-review.py b/scripts/acceptance/capture-review.pynew file mode 100644index 00000000..b42505c6--- /dev/null+++ b/scripts/acceptance/capture-review.py@@ -0,0 +1,104 @@+"""One capture-card round with every effect on (claude-capture-review-20261026).++The task build runs in a hard-linked copy of the 2.1.0 NVIDIA runtime base with this+tree's QML/i18n, on a private profile seeded read-only from the user's own+user-data (capture device/format/audio and effect chain); screenshots go to the+task folder. capture-review.qml drives it: 60 s steady state, the 信号 card and+刷新显示器状态, then anti-aliasing screenshots on a paused game.+The user's own player must be closed first (the capture card is exclusive).+usage: py -3.11 -X utf8 -B -I scripts/acceptance/capture-review.py+"""+from pathlib import Path+import hashlib, json, os, re, shutil, subprocess, time++B = Path('E:/项目/Veyra'); T = 'claude-capture-review-20261026'; R = Path(__file__).resolve().parents[2]+D = B/'build/claude-screen-recording-20261022'; A = B/'tests'/T/'app'; P = B/'tests'/T/'profile'+L = B/'logs'/T/'capture'; TMP = B/'tmp'/T/'capture'; OUT = B/'reports'/T; SHOTS = B/'tests'/T/'shots'+USER_DATA = Path('E:/App/Veyra-2.1.0-test-NVIDIA-win64-portable/runtime_local/user-data-2.0.0')+for p in [L, TMP, OUT]: p.mkdir(parents=True, exist_ok=True)+for p in [P, SHOTS]:+ if p.exists(): shutil.rmtree(p)+ p.mkdir(parents=True)+++def sha(p):+ with p.open('rb') as f: return hashlib.file_digest(f, 'sha256').hexdigest()+++def replace(p, data):+ # Unlink first: a hard link to the donor is never written through.+ p.parent.mkdir(parents=True, exist_ok=True)+ if p.exists(): p.unlink()+ p.write_bytes(data)+++running = subprocess.check_output(['tasklist', '/fo', 'csv', '/nh'], text=True, errors='replace')+assert not any(l.lower().startswith('"veyra') for l in running.splitlines()), 'another player is running; the capture card is exclusive'++donor = B/'releases/release-2.1.0-20261019/runtime-base/NVIDIA'+manifest = json.loads((donor/'package-manifest.json').read_text('utf8'))+if not A.exists():+ for e in manifest['files']:+ rel = e['path']+ if rel.startswith('logs/') or any(x.startswith('user-data-') for x in Path(rel).parts): continue+ p = A/rel; p.parent.mkdir(parents=True, exist_ok=True); os.link(donor/rel, p)+ shutil.copyfile(donor/'package-manifest.json', A/'package-manifest.json')+replace(A/'veyra_qml_ui.exe', (D/'veyra_qml_ui.exe').read_bytes())+for folder in ['qml', 'i18n']:+ for p in (R/folder).rglob('*'):+ if p.is_file(): replace(A/folder/p.relative_to(R/folder), p.read_bytes())+for e in manifest['files']:+ if Path(e['path']).suffix.lower() in ['.dll', '.onnx', '.tflite', '.hsaco', '.dxil']: assert sha(A/e['path']) == e['sha256'], e['path']++# The user's capture choice and effect chain, copied (never modified at the source).+seeded = {}+for f in USER_DATA.iterdir():+ if f.is_file(): shutil.copyfile(f, P/f.name); seeded[f.name] = sha(f)+prefs = json.loads((P/'qml-preferences.v1.json').read_text('utf8'))+prefs.update(screenshotDir=str(SHOTS), autoResume=False, prewarmEnhancement=False)+(P/'qml-preferences.v1.json').write_text(json.dumps(prefs, ensure_ascii=False), 'utf8')++env = {k: v for k, v in os.environ.items() if not k.upper().startswith(('VEYRA_', 'QT_', 'QSG_', 'QML_'))}+log_file = L/'engine.log'; console = L/'console.log'+for f in (log_file, console):+ if f.exists(): f.unlink()+env.update(TEMP=str(TMP), TMP=str(TMP), APPDATA=str(P/'AppData'), LOCALAPPDATA=str(P/'LocalAppData'), CUDA_CACHE_PATH=str(TMP/'cuda'),+ QML_DISABLE_DISK_CACHE='1', QT_FORCE_STDERR_LOGGING='1', VEYRA_LOG_FILE=str(log_file))+main = (R/'qml/Veyra/Main.qml').read_text('utf8'); pos = main.rfind('}')+loader = ('\nLoader { anchors.fill: parent; z: 1000; source: ' + json.dumps((R/'scripts/acceptance/capture-review.qml').as_uri()) ++ '; onLoaded: item.shotDir=' + json.dumps(SHOTS.as_posix()) + ' }\n')+replace(A/'qml/Veyra/Main.qml', (main[:pos] + loader + main[pos:]).encode('utf8'))+started = time.time()+try:+ with console.open('wb') as f:+ p = subprocess.run([str(A/'veyra_qml_ui.exe'), '--page', 'pro', '--size', '2400x1300', '--data-dir', str(P), '--exit-after', '280000'],+ cwd=A, env=env, stdout=f, stderr=subprocess.STDOUT, timeout=300)+finally:+ replace(A/'qml/Veyra/Main.qml', (R/'qml/Veyra/Main.qml').read_bytes())+seconds = round(time.time() - started, 1)+log = log_file.read_text('utf8', errors='replace'); text = console.read_text('utf8', errors='replace')+lines = log.splitlines()+marks = [(i, m.group(1)) for i, l in enumerate(lines) if (m := re.search(r'\[capture-review\] (.+)', l))]+mark_at = lambda prefix: next((i for i, t in marks if t.startswith(prefix)), None)+s0, s1 = mark_at('steady-start'), mark_at('steady-end')+steady = lines[s0:s1] if s0 is not None and s1 is not None else []+count = lambda rows, tag: sum(1 for l in rows if tag in l)+def last(rows, tag):+ found = [l for l in rows if tag in l]+ return found[-1].split('] ', 2)[-1] if found else None+users = USER_DATA+untouched = all(sha(users/name) == digest for name, digest in seeded.items())+result = dict(+ exit=p.returncode, seconds=seconds, passed='CR_PASS' in text and 'CR_FAIL' not in text, userDataUntouched=untouched,+ marks=[t for _, t in marks],+ steady=dict(lines=len(steady), displayQueries=count(steady, '[display-query] query '), hdrPolls=count(steady, 'hdr-query-stall'),+ audioSampleWarnings=count(steady, '[WARN ] [capture-audio-samples]'), audioSampleSummaries=count(steady, '[INFO ] [capture-audio-samples]'),+ captureTiming=last(steady, '[capture-timing]'), frameFlow=last(steady, '[frame-flow]'), frameRate=last(steady, '[frame-rate]'),+ engineStalls=count(steady, '[engine-stall]'), errors=[l for l in steady if '[ERROR]' in l][:10]),+ displayQueriesWholeRun=[l.split('] ', 2)[-1] for l in lines if '[display-query]' in l][:40],+ antiAlias=[l.split('] ', 2)[-1] for l in lines if '[anti-alias]' in l or ('[node-dispatch]' in l and 'antialias' in l.lower())][:40],+ plans=[l.split('] ', 2)[-1] for l in lines if 'fixed execution plan accepted' in l][:20],+ qmlErrors=[l for l in text.splitlines() if any(s in l for s in ['ReferenceError:', 'TypeError:', 'Binding loop detected', 'CR_FAIL'])][:10],+ shots=sorted(str(f) for f in SHOTS.iterdir()), exeSha256=sha(A/'veyra_qml_ui.exe'), log=str(log_file))+(OUT/'capture-round.json').write_text(json.dumps(result, ensure_ascii=False, indent=1), 'utf8')+print(json.dumps({k: result[k] for k in ['exit', 'seconds', 'passed', 'userDataUntouched', 'marks', 'steady']}, ensure_ascii=False, indent=1))diff --git a/scripts/acceptance/capture-review.qml b/scripts/acceptance/capture-review.qmlnew file mode 100644index 00000000..5a2e8c47--- /dev/null+++ b/scripts/acceptance/capture-review.qml@@ -0,0 +1,104 @@+// Loaded only into a private staging copy, never the user's running package.+// claude-capture-review-20261026: one capture-card round with the user's own+// capture setup and effect chain (copied read-only into a private profile).+// 1 resume the remembered capture source; anti-aliasing and the colour grade on+// 2 60 s steady state with every effect on (the user keeps playing)+// 3 信号 card: Windows HDR / VRR / refresh, then 刷新显示器状态+// 4 banner: pause the game; anti-aliasing screenshots on a still picture+// (NR on: off / after NR / off again / node order = before NR; NR off: off / on)+// 5 everything back on, banner: carry on playing; quit+import QtQuick+Item {+ id: test+ anchors.fill: parent+ z: 1000+ property string shotDir: ""+ property int phase: 0+ property int ticks: 0+ property int shotIndex: 0+ property var notices: []+ property string banner: ""+ property var steps: [+ {name: "nr-aa-off", nr: true, aa: false, node: 0},+ {name: "nr-aa-after", nr: true, aa: true, node: 0},+ {name: "nr-aa-off-repeat", nr: true, aa: false, node: 0},+ {name: "nr-aa-before-node", nr: true, aa: true, node: 1},+ {name: "nonr-aa-off", nr: false, aa: false, node: 0},+ {name: "nonr-aa-on", nr: false, aa: true, node: 0}+ ]+ function check(ok, why) { if (!ok) throw new Error(why) }+ function log(text) { veyra.logUi("capture-review", text); console.log("CR", text) }+ function state() {+ return "running=" + veyra.running + " applying=" + veyra.applying + " nr=" + veyra.nrEnabled + " aa=" + veyra.antiAliasEnabled+ + " color=" + veyra.colorEnabled + " fg=" + veyra.fgEnabled + " node=" + veyra.nodeMode + " source=" + veyra.sourceSummary+ + " submitFps=" + veyra.submitFps.toFixed(2) + " hdr=" + veyra.displayHdr + " vrr=" + veyra.vrrState + "/" + veyra.vrrSummary+ + " refreshHz=" + veyra.displayRefreshHz.toFixed(1) + " checking=" + veyra.displayChecking+ }+ function next(p, why) { phase = p; ticks = 0; log("phase=" + p + " " + why + " | " + state()) }+ Connections { target: veyra; function onNotice(text, error) { test.notices.push(text); console.log("CR notice", error, text) } }+ Rectangle {+ visible: test.banner.length > 0+ anchors.top: parent.top; anchors.horizontalCenter: parent.horizontalCenter; anchors.topMargin: 40+ width: bannerText.implicitWidth + 60; height: 64; radius: 12+ color: "#E0202020"; border.color: "#FFD54F"; border.width: 2+ Text { id: bannerText; anchors.centerIn: parent; text: test.banner; color: "#FFD54F"; font.pixelSize: 26; font.bold: true }+ }+ Timer {+ interval: 250; repeat: true; running: test.shotDir.length > 0+ onTriggered: { try {+ ++test.ticks+ if (test.phase === 0) {+ if (test.ticks < 8) return+ test.next(1, "resume capture"); veyra.resumeCaptureSession()+ } else if (test.phase === 1) {+ if (!veyra.running || veyra.applying || veyra.submitFps < 1) { check(test.ticks < 160, "capture did not start within 40 s"); return }+ if (test.ticks < 12) return+ if (!veyra.antiAliasEnabled) veyra.antiAliasEnabled = true+ if (!veyra.colorEnabled) veyra.colorEnabled = true+ test.next(2, "all effects on")+ } else if (test.phase === 2) {+ if (test.ticks === 20) test.log("steady-start | " + test.state())+ if (test.ticks < 20 + 240) return // 5 s settle, then 60 s steady+ test.log("steady-end | " + test.state())+ test.notices = []+ test.next(3, "display card")+ check(veyra.displayHdr >= 0 && veyra.displayRefreshHz > 0, "信号 card has Windows HDR and the refresh rate")+ veyra.recheckDisplay()+ check(veyra.displayChecking, "刷新显示器状态 shows the spinner at once")+ } else if (test.phase === 3) {+ if (test.ticks < 24) return+ const answered = test.notices.filter(t => t.indexOf("已刷新显示器状态") === 0)+ check(answered.length === 1 && !veyra.displayChecking, "refresh notice: " + JSON.stringify(test.notices))+ test.log("display-refreshed | " + answered[0] + " | " + test.state())+ test.banner = "请暂停游戏(约 40 秒,画面静止即可)"+ test.next(4, "banner: pause the game")+ } else if (test.phase === 4) {+ if (test.ticks < 40) return // 10 s to pause+ test.shotIndex = 0+ test.next(5, "screenshots")+ } else if (test.phase === 5) {+ const step = test.steps[test.shotIndex]+ if (test.ticks === 1) {+ if (veyra.nodeMode !== step.node) veyra.nodeMode = step.node+ if (veyra.nrEnabled !== step.nr) veyra.nrEnabled = step.nr+ if (veyra.antiAliasEnabled !== step.aa) veyra.antiAliasEnabled = step.aa+ test.log("shot-config " + step.name + " | " + test.state())+ return+ }+ if (veyra.applying || !veyra.running) { check(test.ticks < 80, "configuration " + step.name + " did not apply"); return }+ if (test.ticks < 14) return // settle the NR history on the still picture+ if (test.ticks === 14) { veyra.takeScreenshot(); return }+ if (test.ticks < 22) return+ test.log("shot " + step.name + " file=" + veyra.lastScreenshot + " | " + test.state())+ if (++test.shotIndex < test.steps.length) { test.ticks = 0; return }+ test.banner = "截图完成,可以继续游戏"+ veyra.nodeMode = 0; veyra.nrEnabled = true; veyra.antiAliasEnabled = true+ test.next(6, "restore every effect")+ } else if (test.phase === 6) {+ if (test.ticks < 24 || veyra.applying) return+ test.log("done | " + test.state())+ console.log("CR_PASS"); Qt.quit()+ }+ } catch (e) { console.error("CR_FAIL", test.phase, e.message); test.log("FAIL phase=" + test.phase + " " + e.message); Qt.quit() } }+ }+}diff --git a/scripts/acceptance/vrr-event-query.qml b/scripts/acceptance/vrr-event-query.qmlindex a979adc2..1863654b 100644--- a/scripts/acceptance/vrr-event-query.qml+++ b/scripts/acceptance/vrr-event-query.qml@@ -43,11 +43,11 @@ Item {// Mark first: the presenter may start the query before this handler returns.test.notices=[];next(4,"recheck");veyra.recheckDisplay()// The spinner shows at once; the next 250 ms status update may already clear it.- check(veyra.vrrChecking,"重新检测 shows the spinner at once")+ check(veyra.displayChecking,"刷新显示器状态 shows the spinner at once")}else if(test.phase===4){if(test.ticks<16)return- check(test.notices.some(t=>t.indexOf("已重新检测")===0),"re-check notice: "+JSON.stringify(test.notices))- check(!veyra.vrrChecking,"vrrChecking cleared after the answer")+ check(test.notices.some(t=>t.indexOf("已刷新显示器状态")===0),"re-check notice: "+JSON.stringify(test.notices))+ check(!veyra.displayChecking,"displayChecking cleared after the answer")next(5,"vrr-on");veyra.variableRefresh=true}else if(test.phase===5){// Switch on: one query, plus one VRR confirmation 3 s later when VRR presents.diff --git a/src/engine/DisplayStateService.cpp b/src/engine/DisplayStateService.cppindex 5955c3d9..9359ee4d 100644--- a/src/engine/DisplayStateService.cpp+++ b/src/engine/DisplayStateService.cpp@@ -20,8 +20,13 @@ DisplayState DisplayStateService::queryDisplayState(HWND window,HMONITOR monitorstate.refreshHz=gfx::PresentSink::displayRefreshFps(window);const auto refreshed=Clock::now();state.vrr=gfx::queryVrr(window);+ const auto vrrDone=Clock::now();+ gfx::PresentSink::DisplayPeakInfo peak;+ state.color.hdr=gfx::PresentSink::queryHdrDisplayActive(window,nullptr,&peak);+ state.color.peakValid=peak.valid;state.color.peakNits=peak.peakNits;+ state.color.fullFrameNits=peak.fullFrameNits;state.color.minNits=peak.minNits;const auto finished=Clock::now();- state.refreshMs=Ms(refreshed-began).count();state.vrrMs=Ms(finished-refreshed).count();+ state.refreshMs=Ms(refreshed-began).count();state.vrrMs=Ms(vrrDone-refreshed).count();state.colorMs=Ms(finished-vrrDone).count();if(IsWindow(window)&&MonitorFromWindow(window,MONITOR_DEFAULTTONEAREST)==monitor)state.monitor=monitor;return state;}@@ -100,8 +105,9 @@ void DisplayStateService::collectLocked(){else{state.generation=job.generation;state.serial=++serial_;if(!entry.state||entry.state->generation<=job.generation)entry.state=state;- veyra::log::info("display-query",std::format("result reason={} monitor={} generation={} refreshHz={:.3f} vrrLevel={} status={} refreshMs={:.3f} vrrMs={:.3f} (driver wall time on the worker thread)",- job.reason,monitorName(job.monitor),job.generation,state.refreshHz,gfx::vrrLevel(state.vrr),state.vrr.status,state.refreshMs,state.vrrMs));+ veyra::log::info("display-query",std::format("result reason={} monitor={} generation={} refreshHz={:.3f} vrrLevel={} status={} hdr={} peakNits={} refreshMs={:.3f} vrrMs={:.3f} colorMs={:.3f} (driver wall time on the worker thread)",+ job.reason,monitorName(job.monitor),job.generation,state.refreshHz,gfx::vrrLevel(state.vrr),state.vrr.status,+ state.color.hdr?(*state.color.hdr?"on":"off"):"unknown",state.color.peakValid?int(state.color.peakNits):-1,state.refreshMs,state.vrrMs,state.colorMs));if(state.vrr.status!=0)failedLocked(entry,job,std::format("NVAPI status={}",state.vrr.status));else if(entry.failedGeneration==job.generation)entry.failures=0;}diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cppindex 03306129..7caeef29 100644--- a/src/engine/EngineController.cpp+++ b/src/engine/EngineController.cpp@@ -709,9 +709,20 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sif(!pipeline::Extent{width,height}.valid()){status(L"图像尺寸超出单张GPU纹理能力,需要分块处理",true);break;}HdrDisplayState displayHdrState;bool displayQueryFailed=false;+ uint64_t hdrDisplaySerial=0;+ // Windows HDR comes from the shared display state (the same background+ // query as refresh and VRR, asked again only on a display change, a+ // monitor change or 刷新显示器状态). A new graph waits for a missing or+ // stale answer once, like the synchronous query it replaces.auto displayHdrActive=[&]{- HMONITOR target=nullptr;- const auto queried=gfx::PresentSink::queryHdrDisplayActive(window,&target);+ const HMONITOR target=displayStates_.monitorOf(window);+ auto known=displayStates_.state(target);+ if(!known||known->generation!=displayStates_.generation()){+ displayStates_.request(window,"hdr-output");+ known=displayStates_.wait(target,std::chrono::seconds(1));+ }+ const std::optional<bool> queried=known?known->color.hdr:std::nullopt;+ if(known)hdrDisplaySerial=known->serial;const bool active=displayHdrState.update(reinterpret_cast<std::uintptr_t>(target),queried);if(!queried&&!displayQueryFailed)veyra::log::warn("display-color",std::format("HDR display query unavailable; using target-local hdr={} (unknown target defaults to SDR)",active));if(queried&&displayQueryFailed)veyra::log::info("display-color",std::format("HDR display query recovered hdr={}",active));@@ -1488,11 +1499,18 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,scontinue;}}- if((gd.hdrInput||options.settings.videoHdr.enabled)&&GetTickCount64()-hdrDisplayCheck>2000){- diagnostics::CpuStallTrace hdrTrace("hdr-query-stall",frames);+ // Windows HDR flips with a newer display answer (a display or monitor+ // change, 刷新显示器状态, a session start). Reading it calls no driver; the+ // owner used to enumerate DXGI outputs here every 2 s (0.25-0.64 ms each).+ if((gd.hdrInput||options.settings.videoHdr.enabled)&&GetTickCount64()-hdrDisplayCheck>250){hdrDisplayCheck=GetTickCount64();- const bool native=options.settings.useHdrPreview(gd.hdrInput,displayHdrActive());- if(native!=gd.hdrOutput){std::lock_guard lock(mutex_);if(desired_.revision==options.settings.revision){desired_.revision=++nextRevision_;snapshot_.desired=desired_;snapshot_.applying=true;}}+ const HMONITOR target=displayStates_.monitorOf(window);+ if(const auto known=displayStates_.state(target);known&&known->serial!=hdrDisplaySerial){+ hdrDisplaySerial=known->serial;+ const bool active=displayHdrState.update(reinterpret_cast<std::uintptr_t>(target),known->color.hdr);+ const bool native=options.settings.useHdrPreview(gd.hdrInput,active);+ if(native!=gd.hdrOutput){std::lock_guard lock(mutex_);if(desired_.revision==options.settings.revision){desired_.revision=++nextRevision_;snapshot_.desired=desired_;snapshot_.applying=true;}}+ }}if(audioStarted)publishAudioStatus();if(audioStarted&&injectFileEndpointLoss&&!fileEndpointLossInjected&&frames>=20){audioPipe.requestEndpointLossForTest();fileEndpointLossInjected=true;}diff --git a/src/engine/VideoPresenter.cpp b/src/engine/VideoPresenter.cppindex 61321b2e..7ea1a13e 100644--- a/src/engine/VideoPresenter.cpp+++ b/src/engine/VideoPresenter.cpp@@ -196,12 +196,14 @@ bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&const bool needsDisplayPeak=hdrBaseline.enabled||(metadataBaseline.enabled&&(metadataBaseline.masteringPeakNits||metadataBaseline.maxCllNits||metadataBaseline.maxFallNits));if(graph.hdrOutput()&&needsDisplayPeak&&hdrBaseline.displayPeakNits==0){+ // The panel's own peak from the shared display state: no driver call here+ // (this thread used to build a DXGI factory for it every 2 s).const auto monitor=MonitorFromWindow(window_,MONITOR_DEFAULTTONEAREST);- if(hdrPeakMonitor_!=monitor||now-hdrPeakQuery_>=std::chrono::seconds(2)){- const auto previous=hdrPeakInfo_;- hdrPeakInfo_=gfx::PresentSink::queryDisplayPeak(window_);hdrPeakMonitor_=monitor;hdrPeakQuery_=now;- if(previous.valid!=hdrPeakInfo_.valid||previous.peakNits!=hdrPeakInfo_.peakNits)retainedFrame_.reset();- }+ gfx::PresentSink::DisplayPeakInfo peak{};+ if(displayStates_)if(const auto known=displayStates_->state(monitor))+ peak={known->color.peakNits,known->color.fullFrameNits,known->color.minNits,known->color.peakValid};+ if(peak.valid!=hdrPeakInfo_.valid||peak.peakNits!=hdrPeakInfo_.peakNits)retainedFrame_.reset();+ hdrPeakInfo_=peak;if(hdrPeakInfo_.valid)hdrBaseline.displayPeakNits=std::clamp(hdrPeakInfo_.peakNits,100u,10000u);}HdrCurveSettings hdrCurve;HdrMetadataSettings hdrMetadata;@@ -494,7 +496,7 @@ void VideoPresenter::publishLiveCoverage(const HdrCurveSettings& curve,pipeline:void VideoPresenter::close(){metadataSent_=false;metadataDirty_=false;lastMetadata_={};sourceMetadata_={};metadataAttempt_={};- hdrPeakMonitor_=nullptr;hdrPeakInfo_={};hdrPeakQuery_={};+ hdrPeakInfo_={};refreshMonitor_=nullptr;refreshHz_=0;vrr_={};refreshQueried_=false;vrrSync_=false;displayStateSerial_=0;vrrConfirmAt_.reset();retainedFrame_.reset();xessInputId_=0;xessWork_={};xessWorkPosition_=0;diff --git a/src/gfx/PresentSink.cpp b/src/gfx/PresentSink.cppindex 47bcf64a..16fc5d8b 100644--- a/src/gfx/PresentSink.cpp+++ b/src/gfx/PresentSink.cpp@@ -27,7 +27,20 @@ bool PresentSink::hdrDisplayActive(HWND window){return queryHdrDisplayActive(window).value_or(false);}-std::optional<bool> PresentSink::queryHdrDisplayActive(HWND window,HMONITOR* queriedMonitor){+namespace {+PresentSink::DisplayPeakInfo peakOf(const DXGI_OUTPUT_DESC1& desc){+ PresentSink::DisplayPeakInfo info{};+ if(!std::isfinite(desc.MaxLuminance)||desc.MaxLuminance<100.0f||desc.MaxLuminance>10000.0f)return info;+ info.peakNits=unsigned(std::lround(desc.MaxLuminance));+ info.fullFrameNits=std::isfinite(desc.MaxFullFrameLuminance)&&desc.MaxFullFrameLuminance>0+ ?unsigned(std::lround(std::min(desc.MaxFullFrameLuminance,10000.0f))):0;+ info.minNits=std::isfinite(desc.MinLuminance)&&desc.MinLuminance>=0?desc.MinLuminance:0;+ info.valid=info.peakNits>0;+ return info;+}+}++std::optional<bool> PresentSink::queryHdrDisplayActive(HWND window,HMONITOR* queriedMonitor,DisplayPeakInfo* peak){const auto monitor=MonitorFromWindow(window,MONITOR_DEFAULTTONEAREST);if(queriedMonitor)*queriedMonitor=monitor;if(!monitor)return std::nullopt;@@ -62,53 +75,13 @@ std::optional<bool> PresentSink::queryHdrDisplayActive(HWND window,HMONITOR* queDXGI_OUTPUT_DESC1 desc{};hr=advanced->GetDesc1(&desc);if(FAILED(hr)){log::warn("display-color",std::format("GetDesc1 query failed hr=0x{:X}",unsigned(hr)));return std::nullopt;}if(desc.Monitor!=monitor)return std::nullopt;+ if(peak)*peak=peakOf(desc);return desc.ColorSpace==DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020;}}return 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;- if(!std::isfinite(desc.MaxLuminance)||desc.MaxLuminance<100.0f||desc.MaxLuminance>10000.0f)return info;- info.peakNits=unsigned(std::lround(desc.MaxLuminance));- info.fullFrameNits=std::isfinite(desc.MaxFullFrameLuminance)&&desc.MaxFullFrameLuminance>0- ?unsigned(std::lround(std::min(desc.MaxFullFrameLuminance,10000.0f))):0;- info.minNits=std::isfinite(desc.MinLuminance)&&desc.MinLuminance>=0?desc.MinLuminance:0;- 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);diff --git a/src/ui/QmlPlayerBridge.cpp b/src/ui/QmlPlayerBridge.cppindex 4067ff67..632ff8f0 100644--- a/src/ui/QmlPlayerBridge.cpp+++ b/src/ui/QmlPlayerBridge.cpp@@ -499,11 +499,13 @@ struct QmlPlayerBridge::Impl {// presenting monitor, or of the main window's monitor while idle.QString fgDisplayHint;int vrrState=0;- // 重新检测: the display generation it asked for, until the shown monitor- // answers (vrrChecking also covers any query in flight).- bool vrrChecking=false,vrrRecheckPending=false,displayChanged=false;- uint64_t vrrRecheckGeneration=0;- std::chrono::steady_clock::time_point vrrRecheckSince{};+ // The shown monitor's Windows HDR (-1 unknown) and refresh rate.+ int displayHdr=-1;double displayRefreshHz=0;+ // 刷新显示器状态: the display generation it asked for, until the shown monitor+ // answers (displayChecking also covers any query in flight).+ bool displayChecking=false,displayRecheckPending=false,displayChanged=false;+ uint64_t displayRecheckGeneration=0;+ std::chrono::steady_clock::time_point displayRecheckSince{};DisplayChangeFilter displayChangeFilter;std::atomic<double> gpuUtil{-1.0};// Hardware adapters in Windows' high-performance order (discrete first). The@@ -4941,25 +4943,21 @@ void QmlPlayerBridge::setHdrDisplayPeakNits(int nits){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;- static HMONITOR cachedMonitor=nullptr;+ // Read from QML bindings (the peak row's hint text), so no driver work here:+ // the values come from the shared display state, queried in the background on+ // events and 刷新显示器状态 (this used to build a DXGI factory every 5 s on the+ // UI thread).HWND window=impl_->videoWindow;if(!IsWindow(window)){if(auto* focused=QGuiApplication::focusWindow())window=reinterpret_cast<HWND>(focused->winId());else window=nullptr;}- const auto monitor=window?MonitorFromWindow(window,MONITOR_DEFAULTTONEAREST):MonitorFromPoint(POINT{0,0},MONITOR_DEFAULTTOPRIMARY);- if(!cacheTimer.isValid()||cacheTimer.elapsed()>5000||cachedMonitor!=monitor){- cached=gfx::PresentSink::queryDisplayPeak(window);cachedMonitor=monitor;- cacheTimer.restart();- }- return {{"valid",cached.valid},{"plausible",cached.valid},{"peakNits",int(cached.peakNits)},- {"fullFrameNits",int(cached.fullFrameNits)},{"minNits",cached.minNits}};+ auto& displays=impl_->engine.displayStates();+ std::optional<engine::DisplayState> known;+ if(window){displays.request(window,"ui");known=displays.state(displays.monitorOf(window));}+ const engine::DisplayColorState c=known?known->color:engine::DisplayColorState{};+ return {{"valid",c.peakValid},{"plausible",c.peakValid},{"peakNits",int(c.peakNits)},+ {"fullFrameNits",int(c.fullFrameNits)},{"minNits",c.minNits}};}bool QmlPlayerBridge::hdrCurve()const{return settings().hdrCurve.enabled;}void QmlPlayerBridge::setHdrCurve(bool enabled){@@ -8229,31 +8227,36 @@ void QmlPlayerBridge::updateRunStatus() {const auto sync=i.presentation.display==engine::DisplaySync::Vsync?tr("垂直同步"):tr("自动显示同步");options<<((refresh>0)?tr("%1 · 屏幕 %2 Hz").arg(sync).arg(refresh,0,'f',1):sync);}- // Variable refresh (NVIDIA G-SYNC / G-SYNC Compatible): the presenting- // monitor while playing, otherwise the main window's monitor. Both come- // from the engine's DisplayStateService, queried in the background on- // events only (startup, another monitor, WM_DISPLAYCHANGE, the switch- // turned on, 重新检测), never on a timer. The driver setting is the- // user's; the 可变刷新 switch decides how Veyra presents when it is possible.+ // Variable refresh (NVIDIA G-SYNC / G-SYNC Compatible), Windows HDR and the+ // refresh rate: the presenting monitor while playing, otherwise the main+ // window's monitor. They come from the engine's DisplayStateService,+ // queried in the background on events only (startup, another monitor,+ // WM_DISPLAYCHANGE, the switch turned on, 刷新显示器状态), never on a timer.+ // The driver and Windows settings are the user's; the 可变刷新 switch decides+ // how Veyra presents when it is possible.auto& displays=i.engine.displayStates();if(i.displayChanged){i.displayChanged=false;displays.invalidate("display-change");}HWND host=s.running&&i.videoWindow?i.videoWindow:owner;if(!host)if(auto* window=QGuiApplication::focusWindow())host=reinterpret_cast<HWND>(window->winId());// request() starts a query only when this monitor's state is stale or// missing (the presenter asks for the same monitor while playing).- if(host)displays.request(host,i.vrrRecheckPending?"manual":"ui");+ if(host)displays.request(host,i.displayRecheckPending?"manual":"ui");const auto display=host?displays.state(displays.monitorOf(host)):std::nullopt;const int vrrLevel=s.running?int(s.displayVrr):display?int(gfx::vrrLevel(display->vrr)):0;+ const int hdr=display&&display->color.hdr?int(*display->color.hdr):-1;+ const double refreshHz=display?display->refreshHz:0;QString recheckNotice;bool recheckFailed=false;- if(i.vrrRecheckPending){+ if(i.displayRecheckPending){// Answered once the shown monitor has a state of the re-check's generation.- if(display&&display->generation>=i.vrrRecheckGeneration){- i.vrrRecheckPending=false;recheckNotice=tr("已重新检测:%1").arg(vrrHintText(int(gfx::vrrLevel(display->vrr))));- }else if(std::chrono::steady_clock::now()-i.vrrRecheckSince>std::chrono::seconds(5)){- i.vrrRecheckPending=false;recheckNotice=tr("重新检测没有完成,请稍后再试");recheckFailed=true;+ if(display&&display->generation>=i.displayRecheckGeneration){+ i.displayRecheckPending=false;+ recheckNotice=tr("已刷新显示器状态:系统 HDR %1 · 可变刷新 %2")+ .arg(hdr>0?tr("开"):hdr==0?tr("关"):tr("未知"),vrrSummaryText(int(gfx::vrrLevel(display->vrr))));+ }else if(std::chrono::steady_clock::now()-i.displayRecheckSince>std::chrono::seconds(5)){+ i.displayRecheckPending=false;recheckNotice=tr("刷新显示器状态没有完成,请稍后再试");recheckFailed=true;}}- const bool vrrChecking=i.vrrRecheckPending||displays.busy();+ const bool displayChecking=i.displayRecheckPending||displays.busy();if(i.presentation.variableRefresh){if(vrrLevel>=4)options<<tr("可变刷新 · 生效中");else if(vrrLevel==3)options<<tr("可变刷新 · 等待驱动确认");@@ -8347,9 +8350,11 @@ void QmlPlayerBridge::updateRunStatus() {const double gpu = i.gpuUtil.load();const double target=active&&f.rateWindowReady&&rate.targetFps>0?rate.targetFps:-1;const bool changed = ratioChanged || active || status != i.runStatus || level != i.runLevel || text != i.runDetail || options!=i.runOptions || std::abs(target-i.effectiveOutputFps)>.05 || std::abs(gpu - i.gpuPublished) > 0.05 ||- fgHint != i.fgDisplayHint || vrrLevel != i.vrrState || vrrChecking != i.vrrChecking;+ fgHint != i.fgDisplayHint || vrrLevel != i.vrrState || displayChecking != i.displayChecking ||+ hdr != i.displayHdr || std::abs(refreshHz - i.displayRefreshHz) > .01;i.runStatus = status; i.runLevel = level; i.runDetail = text; i.gpuPublished = gpu;- i.runOptions=options;i.effectiveOutputFps=target;i.fgDisplayHint=fgHint;i.vrrState=vrrLevel;i.vrrChecking=vrrChecking;+ i.runOptions=options;i.effectiveOutputFps=target;i.fgDisplayHint=fgHint;i.vrrState=vrrLevel;i.displayChecking=displayChecking;+ i.displayHdr=hdr;i.displayRefreshHz=refreshHz;if (changed) emit perfChanged();if (!recheckNotice.isEmpty()) emit notice(recheckNotice, recheckFailed);}@@ -8605,17 +8610,30 @@ void QmlPlayerBridge::setVariableRefresh(bool value) {applyPresentation();}int QmlPlayerBridge::vrrState() const { return impl_->vrrState; }-bool QmlPlayerBridge::vrrChecking() const { return impl_->vrrChecking; }+int QmlPlayerBridge::displayHdr() const { return impl_->displayHdr; }+double QmlPlayerBridge::displayRefreshHz() const { return impl_->displayRefreshHz; }+bool QmlPlayerBridge::displayChecking() const { return impl_->displayChecking; }void QmlPlayerBridge::recheckDisplay() {// Every stored display state becomes stale; the next status update (or the// presenter's next loop) queries the shown monitor in the background.auto& i = *impl_;- i.vrrRecheckGeneration = i.engine.displayStates().invalidate("manual");- i.vrrRecheckPending = true;- i.vrrRecheckSince = std::chrono::steady_clock::now();- if (!i.vrrChecking) { i.vrrChecking = true; emit perfChanged(); }+ i.displayRecheckGeneration = i.engine.displayStates().invalidate("manual");+ i.displayRecheckPending = true;+ i.displayRecheckSince = std::chrono::steady_clock::now();+ if (!i.displayChecking) { i.displayChecking = true; emit perfChanged(); }}QString QmlPlayerBridge::vrrHint() const { return vrrHintText(impl_->vrrState); }+QString QmlPlayerBridge::vrrSummary() const { return vrrSummaryText(impl_->vrrState); }+// The 信号 card's short form of vrrHintText.+QString QmlPlayerBridge::vrrSummaryText(int level) const {+ switch (level) {+ case 0: return tr("无法检测");+ case 1: return tr("不支持");+ case 2: return tr("当前不可用");+ case 3: return impl_->presentation.variableRefresh && impl_->snapshot.running ? tr("已请求") : tr("可用");+ default: return tr("生效中");+ }+}QString QmlPlayerBridge::vrrHintText(int level) const {// The 可变刷新 switch is available (not grey) from level 2: the monitor// can do VRR even if the driver setting is still off.diff --git a/tests/integration/AntiAliasGpuTests.cpp b/tests/integration/AntiAliasGpuTests.cppindex da12b9d8..fa375551 100644--- a/tests/integration/AntiAliasGpuTests.cpp+++ b/tests/integration/AntiAliasGpuTests.cpp@@ -14,6 +14,9 @@// NR graphs with anti-aliasing in node slots. tiled-image: the tiled// full-resolution image path (no compiled plan) matches one whole-image graph.// timing-*: GPU milliseconds of the anti-aliasing span per method.+// real-frame: a captured picture (VEYRA_AA_FRAME, binary PPM) through SMAA high+// without NR and with a real NR layer before / after it; the outputs go to+// VEYRA_AA_FRAME_OUT as PPM for comparison. A diagnostic, not part of a sweep.// VEYRA_AA_GPU_DEBUG=1 enables the D3D12 debug layer and fails on its errors.#include "veyra/engine/PreviewGpuSession.h"#include "veyra/engine/GraphDescription.h"@@ -29,7 +32,9 @@#include <cstdio>#include <cstdlib>#include <cstring>+#include <filesystem>#include <format>+#include <fstream>#include <functional>#include <iostream>#include <memory>@@ -492,6 +497,94 @@ engine::ChainNode nrNode() {n.nr.sizePolicy = pipeline::NrSizePolicy::Realtime; n.nr.temporal = false; return n;}+// ---- a captured picture -----------------------------------------------------------------+AVFrame* ppmFrame(const std::filesystem::path& path) {+ std::ifstream in(path, std::ios::binary);+ std::string magic; unsigned w = 0, h = 0, maxValue = 0;+ if (!(in >> magic >> w >> h >> maxValue) || magic != "P6" || maxValue != 255 || !w || !h) return nullptr;+ in.get();+ std::vector<uint8_t> rgb(size_t(w) * h * 3);+ if (!in.read(reinterpret_cast<char*>(rgb.data()), std::streamsize(rgb.size()))) return nullptr;+ AVFrame* f = av_frame_alloc();+ if (!f) return nullptr;+ f->format = AV_PIX_FMT_BGR0; f->width = int(w); f->height = int(h);+ f->color_range = AVCOL_RANGE_UNSPECIFIED; f->color_trc = AVCOL_TRC_IEC61966_2_1; f->colorspace = AVCOL_SPC_RGB;+ if (av_frame_get_buffer(f, 32) < 0) { av_frame_free(&f); return nullptr; }+ for (unsigned y = 0; y < h; ++y)+ for (unsigned x = 0; x < w; ++x) {+ const uint8_t* s = rgb.data() + (size_t(y) * w + x) * 3;+ auto* p = f->data[0] + size_t(y) * f->linesize[0] + size_t(x) * 4;+ p[0] = s[2]; p[1] = s[1]; p[2] = s[0]; p[3] = 255;+ }+ return f;+}+bool savePpm(const std::filesystem::path& path, const sink::RgbaImage& image) {+ std::ofstream out(path, std::ios::binary);+ out << "P6\n" << image.width << ' ' << image.height << "\n255\n";+ for (size_t i = 0; i + 3 < image.pixels.size(); i += 4) out.write(reinterpret_cast<const char*>(&image.pixels[i]), 3);+ return bool(out);+}+// One frame through a real node graph (NGX NR), without output dithering.+bool nodeRender(AVFrame* frame, std::initializer_list<engine::ChainNode> nodes, sink::RgbaImage& image) {+ auto chain = std::make_unique<engine::EffectChain>(); chain->mode = engine::ChainMode::Node;+ bool nr = false;+ for (const auto& n : nodes) { chain->nodes[chain->nodeCount++] = n; nr |= n.type == EffectType::NrEnhance; }+ engine::EnhancementSettings settings; engine::fromChain(*chain, settings);+ settings.multiplier = 1; settings.nrMotion = engine::MotionSource::Zero;+ const auto order = engine::runtimeOrder(*chain);+ engine::StageRequest request; request.width = unsigned(frame->width); request.height = unsigned(frame->height); request.nr = nr; request.nodeOrder = &*order;+ pipeline::EnhanceGraphDesc desc; engine::describeStages(request, settings, desc);+ if (!desc.fixedExecutionPlanError.empty() || !desc.validateFixedExecutionPlan().empty()) return false;+ desc.rgbInput = true; desc.outputDitherStep = 0; desc.runtimeAbsPath = runtime::localRuntimeDirectory().wstring();+ engine::PreviewGpuSession session;+ pipeline::EnhanceGraph::FrameOutputs out;+ bool ok = session.initialize() && session.graph->initialize(desc) && session.graph->createViews() &&+ session.graph->process(frame, 0.0, true, out, 1) && session.ring.waitIdle() &&+ sink::readRgba8(session.context, session.ring, session.graph->videoFrameResource(out.videoSlot), image);+ ok = ok && (!nr || session.graph->metrics().nrEvaluateCount > 0);+ out = {};+ session.ring.drainQueue(); session.graph->shutdown(); session.shutdown();+ return ok;+}+int realFrameCase() {+ const wchar_t* input = _wgetenv(L"VEYRA_AA_FRAME");+ const wchar_t* output = _wgetenv(L"VEYRA_AA_FRAME_OUT");+ if (!input || !output) { std::printf("real-frame: set VEYRA_AA_FRAME (binary PPM) and VEYRA_AA_FRAME_OUT (folder)\n"); return 2; }+ HRESULT com = CoInitializeEx(nullptr, COINIT_MULTITHREADED); (void)com;+ const std::filesystem::path folder(output);+ std::filesystem::create_directories(folder);+ AVFrame* frame = ppmFrame(input);+ check(frame != nullptr, "real-frame: the picture loads");+ if (!frame) return 1;+ const unsigned w = unsigned(frame->width), h = unsigned(frame->height);+ const auto smaa = aa(AntiAliasMethod::Smaa, 2);+ AntiAliasSettings disabled = smaa; disabled.enabled = false;+ sink::RgbaImage plain, aaOnly, nrOnly, nrAgain, aaBefore, aaAfter;+ auto gpu = std::make_unique<Gpu>();+ const bool ok = gpu->start(withAa(disabled), w, h, false) && gpu->render(frame, true, plain) &&+ gpu->start(withAa(smaa), w, h, false) && gpu->render(frame, true, aaOnly);+ gpu.reset();+ check(ok, "real-frame: SMAA high without NR runs");+ const bool nrOk = ok && nodeRender(frame, {nrNode()}, nrOnly) && nodeRender(frame, {nrNode()}, nrAgain) &&+ nodeRender(frame, {aaNode(smaa), nrNode()}, aaBefore) && nodeRender(frame, {nrNode(), aaNode(smaa)}, aaAfter);+ check(nrOk, "real-frame: NR alone (twice), SMAA before NR and SMAA after NR run");+ const auto changed = [](const sink::RgbaImage& a, const sink::RgbaImage& b) {+ size_t n = 0;+ for (size_t i = 0; a.pixels.size() == b.pixels.size() && i + 3 < a.pixels.size(); i += 4)+ n += a.pixels[i] != b.pixels[i] || a.pixels[i + 1] != b.pixels[i + 1] || a.pixels[i + 2] != b.pixels[i + 2];+ return n;+ };+ std::printf("METRIC case=real-frame extent=%ux%u aaChanged=%zu nrRepeatChanged=%zu aaBeforeNrChanged=%zu aaAfterNrChanged=%zu\n", w, h,+ changed(plain, aaOnly), changed(nrOnly, nrAgain), changed(nrOnly, aaBefore), changed(nrOnly, aaAfter));+ const std::pair<const char*, const sink::RgbaImage*> outputs[] = {+ {"plain", &plain}, {"aa", &aaOnly}, {"nr", &nrOnly}, {"nr-again", &nrAgain}, {"aa-before-nr", &aaBefore}, {"aa-after-nr", &aaAfter}};+ bool saved = true;+ for (const auto& [label, image] : outputs) saved = saved && savePpm(folder / (std::string(label) + ".ppm"), *image);+ check(ok && nrOk && saved, "real-frame: every output written");+ av_frame_free(&frame);+ return failures ? 1 : 0;+}+// ---- tiled full-resolution image path -------------------------------------------------// MLAA only uses integer loads, so tiles with a halo past its reach must match a// whole-image graph exactly. SMAA / FXAA search with normalised coordinates;@@ -602,6 +695,7 @@ std::vector<Case> cases() {c.push_back({"node-source-and-tail", [] {return nodeCase("node-source-and-tail", {aaNode(aa(AntiAliasMethod::Smaa, 0)), srNode(), nrNode(), aaNode(aa(AntiAliasMethod::Fxaa, 1))}, 2); }});c.push_back({"tiled-image", [] { return tiledCase(); }});+ c.push_back({"real-frame", [] { return realFrameCase(); }});c.push_back({"timing-1080p", [] { return timingCase(1920, 1080); }});c.push_back({"timing-1440p", [] { return timingCase(2560, 1440); }});c.push_back({"timing-2160p", [] { return timingCase(3840, 2160); }});diff --git a/tests/unit/AsyncDisplayQueryTests.cpp b/tests/unit/AsyncDisplayQueryTests.cppindex d1db434a..fa8eaf56 100644--- a/tests/unit/AsyncDisplayQueryTests.cpp+++ b/tests/unit/AsyncDisplayQueryTests.cpp@@ -69,6 +69,8 @@ int wmain(int argc,wchar_t** argv){if(raise.load())throw std::runtime_error("simulated NVAPI crash");DisplayState state;state.monitor=moved.load()?nullptr:monitor;state.refreshHz=window==windowA?144.0:60.0;state.vrr.known=true;state.vrr.capsKnown=state.vrr.supportsVrr=state.vrr.currentlyCapable=true;state.vrr.status=status.load();+ // Windows HDR on monitor A only; the panel peak comes from the same answer.+ state.color.hdr=window==windowA;state.color.peakValid=true;state.color.peakNits=window==windowA?1000:400;return state;};auto monitorOf=[&](HWND window){return window==windowA?monitorA:window==windowB?monitorB:HMONITOR(nullptr);};@@ -89,6 +91,7 @@ int wmain(int argc,wchar_t** argv){check(service.request(windowA,"test"),"the first request starts one query");auto a=settle(monitorA);check(a&&a->refreshHz==144.0&&a->generation==service.generation()&&calls==1,"the answer is stored for its monitor in the current generation");+ check(a&&a->color.hdr==true&&a->color.peakValid&&a->color.peakNits==1000,"Windows HDR and the panel peak arrive with the same answer");bool quiet=true;for(unsigned i=0;i<1000;++i)quiet&=!service.request(windowA,"test");check(quiet&&calls==1&&!service.busy(),"requests every frame/tick never query a current monitor again");@@ -105,6 +108,7 @@ int wmain(int argc,wchar_t** argv){setGate(true);auto fresh=settle(monitorA);auto b=service.state(monitorB);check(fresh&&fresh->generation==generation&&fresh->serial!=first&&b&&b->refreshHz==60.0&&calls==3,"both monitors answered once each after the release");+ check(b&&b->color.hdr==false&&b->color.peakNits==400,"each monitor keeps its own HDR state");check(service.request(windowA,"vrr-confirm",true)&&!service.request(windowA,"vrr-confirm",true),"a forced check runs once even while current");settle(monitorA);check(calls==4,"the forced check queried exactly once");