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++
diagnostics: add NVIDIA VRAM field collection package
Veyra Goal Agenta210ec18a4af
diff --git a/docs/NV_VRAM_FIELD_PLAN_2026-10-08.md b/docs/NV_VRAM_FIELD_PLAN_2026-10-08.mdnew file mode 100644index 00000000..d99f8344--- /dev/null+++ b/docs/NV_VRAM_FIELD_PLAN_2026-10-08.md@@ -0,0 +1,11 @@+# NVIDIA 显存现场诊断包++用户要求给发生显存持续增长的用户一个可直接运行的诊断包。根因未确认;本轮不尝试 Shutdown、缓存清理、驱动设置或算法修复,不合并 main、不推送或发布。++从 main dbfceabee804cd81bac4a4781f0b7b4cf272902e 在独立 codex/nv-vram-field-20261008 施工;产品基底为已测 71723e0。产物统一 E:/项目/Veyra/{reports,tests,logs,tmp,test-packages}/nv-vram-field-20261008。36 个原工作树、495 份未提交文件以 reports 下不可变 pre-document-state.json 保护,不修改旧 guard。++交付一份诊断 EXE 与启动脚本,放入现有 2.0.6 NVIDIA 包使用,不覆盖原 EXE、运行库或用户配置。私有 profile 只复制普通设置白名单,不复制串流凭据;用户可在诊断进程中按需登录。默认连续记录同 PID,关闭诊断播放器后自动封装证据。记录键用于注明全屏、NR、停止播放阶段;不自动切换设置或重建图。显存增长明显时停止播放并等待约 30 秒再退出,不人为耗尽显存。++证据包括:每 2 秒的进程 LOCAL/NON_LOCAL DXGI 使用量/预算/原始 HRESULT、LUID、设备代次与完成 fence;图及 NR 层创建/关闭边界;仅本轮覆盖调用点的自有纹理/上传缓冲区最终 COM 销毁计数与分配大小估计;外部每 5 秒 WDDM 分实例 Dedicated/Shared/Committed、进程内存/句柄、实际已加载模块路径与 SHA256。跟踪 token 使用 SetPrivateDataInterface,不持有纹理/设备,不 hook SDK/vtable,不做像素回读或 GPU 等待。未覆盖 decoder/Qt/SDK 内部分配,计数不得冒充全进程实际驻留或直接相减判驱动泄漏。++构建通过现有缓存对象加诊断覆盖对象重链接,原构建、候选包全部 SHA 保持。只用一个共享运行目录、独立 profile/log/tmp;每个本机测试不超过 300 秒、串行正常播放,不造压。验收必须包括真实 RTX NR/NVOF 播放、关闭 NR及停止后同 PID 采样、资源 token 可回收、Windows PowerShell 5.1 启动及 ZIP 隐私白名单、计数不可用的明确记录、包 CRC/哈希/源码对应关系。实际结果写报告和 WORKLOG;受影响 GPU 长稳仍待现场。diff --git a/docs/NV_VRAM_FIELD_REPORT_2026-10-08.md b/docs/NV_VRAM_FIELD_REPORT_2026-10-08.mdnew file mode 100644index 00000000..efec26f8--- /dev/null+++ b/docs/NV_VRAM_FIELD_REPORT_2026-10-08.md@@ -0,0 +1,37 @@+# NVIDIA 显存现场诊断包交付++用户要求给真实显存增长用户使用的诊断包。本轮已完成工具和本机验证,**没有定位或修复现场泄漏根因**。不合并 main、不 push、不发布 Release、不代发文件、不关机,不修改运行库/模型/驱动或原配置。++工作树 E:/项目/Veyra/worktrees/nv-vram-field-20261008,分支 codex/nv-vram-field-20261008,起点 dbfceabee804cd81bac4a4781f0b7b4cf272902e;原产品缓存 71723e0。reports/nv-vram-field-20261008/pre-document-state.json 独立保护 36 原工作树/495 脏文件,audit-state.py check 通过。没有修改旧 guard/start。产品 src/include/QML/shader/CMake 文件无差异,诊断只在构建生成的 3 个覆盖对象加入观察。++## 交付文件++`E:/项目/Veyra/test-packages/nv-vram-field-20261008/Veyra-2.0.6-NVIDIA-VRAM-diagnostic.zip`++78,606,236 bytes;SHA256 `92a2a807202489a023a884c9fab998bd1f6d177e056e3b0ae7c04c06d832775d`。17 个条目,ZIP CRC 与逐文件 SHA 全通过。诊断 EXE SHA256 `7519d7e864cfcf7cff9ef27ecff2a584d2a685175bc3cc5c6a18ea68e0c9f04b`。包含 6 个运行文件(EXE/启动两件/摘要/恢复打包两件)、使用说明、manifest、许可证/notice、原产品对应源码 ZIP 与诊断补充源码。不含 DLL、模型、SDK、PDB、测试媒体、配置或日志,使用用户现有解压后的 2.0.6 NVIDIA 运行目录。原对应源码 ZIP SHA256 `44d51be86fa6b7ffd2083663c23a77bbe74fbc9d048fe7932600425e23db23fa`,内层 CRC 与禁止二进制后缀扫描通过。++启动脚本创建独立配置副本及日志目录,只复制普通设置白名单,不复制凭据。默认持续同 PID 采集直到用户正常退出;不会每 280 秒重启、不会自动开关效果/清缓存/加压。Windows PowerShell 5.1 可用,不需要管理员。退出后只封装明确命名的 14 类诊断文件;private-profile/tmp/视频/截图/dmp 不递归加入 ZIP。日志仍可能含路径/设备标识,不能声称完全匿名。另提供重新打包已有记录入口,原记录不覆盖。++## 观察范围++- 每 2 秒在播放器进程内部查询 node0 LOCAL/NON_LOCAL,原字节/预算/预约量/HRESULT、LUID、context 代次、完成 fence。context 关闭前清除 sampler 的 fence 裸指针,采样锁与注销互斥;不持有设备/资源引用、不等待 GPU,只保留 DXGI adapter 引用以继续停止后的进程统计。多个 context 的 DXGI 结果仍是该适配器上进程统计,不能相加当成独立设备私有资源。+- 只将 EnhanceGraph.cpp 的 makeTexture/makeUploadBuffer 调用和 NrInstance.cpp 的 makeTexture 调用替换为原 helper 加观察 token。原分配/状态/返回结果不变;SetPrivateDataInterface 下的 IUnknown token 在资源最终 COM Release 时退出计数。观察器不 AddRef 纹理/设备,不替换 SDK/vtable,不做逐帧像素回读。借用和重复资源不重复计数;分配大小是 GetResourceAllocationInfo 估计,未知/附加失败有计数,不能冒充总物理驻留。+- 创建、最终销毁、图/NR close 入口、存活资源 ID/年龄记录;释放事件队列最多4096项,溢出计数进入存活快照。窗口几何、DPI、显示器像素/刷新率只读记录,不读窗口标题。coversMonitor 不证明独立翻转/MPO。+- 每 5 秒外部 WDDM GPUProcessMemory 保留每实例 Dedicated/Shared/Committed、进程 Private/工作集/句柄、全部当前模块;首次出现记录路径/版本/大小/磁盘 SHA,最后复核文件是否改变。模块加载不等于启用,磁盘 SHA 不等于内存映像校验。按 PID/EXE/启动时间验证身份,失败/缺项不伪填0。+- 原引擎日志提供实际选项/图重建/NR/NVOF/Core 生命周期/错误。已有显存看门狗保持;若触发自动恢复必须分段,不能掩去。摘要保留样本数/跨度/峰值/净增及连续标记段;首尾包含转换,不能报稳态泄漏率。++Qt、decoder、采集源、其它 passes、SDK 内部分配没有完整覆盖。不通过减去已知纹理估计来命名驱动泄漏,也不把这次本机资源销毁当成所有受影响显卡已修好。没有引入 ETW 或提升权限。++## 实际验证++1. `py -3.11 -B scripts/diagnostics/vram-field/build-diagnostic.py`:MSVC 编译 D3D12DeviceContext / EnhanceGraph / NrInstance 三份诊断对象、重链接 GUI,均 exit0。原缓存对象/静态库/EXE 和源产品三文件前后 SHA 不变,完整命令和收据在 logs/nv-vram-field-20261008/build。不是重新构建全部产品。编译没有开启调试层/GBV,也没有修改产品优先级。+2. `py -3.11 -B E:/项目/Veyra/reports/nv-vram-field-20261008/run-field.py final-exe-nr-stop-powershell51`:唯一共享 app 目录使用 1614 文件母包的只读硬链接,独立 profile/log/tmp,不为每轮复制 DLL。RTX5070 / 616.56,GTA 4K 原视频、NVIDIA 原版 NR 内部1080、NVOF、普通优先级。测试脚本在自有 Main.qml 副本定时关闭 FG、启用 NR+flow、全屏、关闭 NR、停止播放,最后恢复 QML;产品母包完整 manifest 前后通过。+3. 最终用例整个 runner 97.875 秒 exit0,玩家定时90秒退出;实际 DXGI 90.1秒/92条(两段各46样本),0 query失败,27有效 WDDM 样本,同 PID7012。停止后 contextActive=0 仍有36条样本(两 segment),不是退出进程后强制释放的假回收。135 创建/135最终销毁,资源ID一一配对,存活0、attachFailures0、unknownSizes0。55窗口记录,34几何全屏记录,DPI96(本机100%);实际日志有 NR original、1920×1080、NVOF init status0、nr=1 fg=0 nvof=1;无 ERROR/FATAL/QML错误。工具有效,**没有复现持续泄漏,也没有进行长期或4K225%/5060Ti验收**。性能开销尚未做匹配 A/B 量化,不能宣称零开销。+4. 末次 LOCAL87.719MiB、WDDM Dedicated1157.738MiB,两个口径不同且采样时刻不同;不相减判归属。停止后较长平台 LOCAL638.324MiB,关窗退出前又下降,已原样保留;不能把135个已覆盖对象销毁等同全进程显存立即归零。+5. 真实 Windows PowerShell5.1 启动、EXE exit0、moduleFilesChanged空、原配置 SHA 不变、自动证据ZIP14条目CRC通过。专设凭据哨兵文件不被复制或打包;ZIP无路径子目录、媒体/dmp/bin,没有伪“无GPU=0”。+6. `py -3.11 -B .../check-tools.py`:PS5.1四份脚本解析、查询失败留空、GPU不可用样本排除、重复 nr-on 标记段不合并、恢复打包和隐私白名单均通过。无管理员、无压力/竞争负载、所有 GPU 用例串行且每次<300秒。+7. `py -3.11 -B .../package.py`:最终交付ZIP、内层源码ZIP、manifest每文件SHA/禁止运行库扫描通过。`git diff --check` 通过。全产物在 E盘;没有删除或重试以往被拒缓存清理。++失败和纠正:第一次 PS5.1 启动继承PS7的模块搜索路径,Get-FileHash 未找到,尚未启动播放器,保留失败目录;改为显式加载执行宿主自带 Utility/Management/Cim/Archive 模块后两轮正常。初版验证器只匹配 `[nvof]` 而实际为 `[nvof-session]`,造成观察标记 false(用例实际 NVOF 已成功);最终用例改为检验 nvOFInit status0 与 graph nvof=1。初轮观察头只记销毁总数,后来补最终销毁事件、存活年龄、DPI/窗口记录后重编并重跑最终EXE;初轮结果不冒充最终EXE通过。未隐藏这些尝试。++下一步仅需受影响用户用原复现条件返回 ZIP,按实际 revision/图代次/窗口阶段分析持续增长与停止回收,再决定是否需要更深入分配追踪。不能保证每个现场只靠这个包就能直接锁定所有者。diff --git a/docs/WORKLOG.md b/docs/WORKLOG.mdindex f6372f25..93f5038b 100644--- a/docs/WORKLOG.md+++ b/docs/WORKLOG.md@@ -8779,3 +8779,10 @@ post-cleanup-smoke.py 从现有完整候选直接启动,独立profile/log/cach## 2026-10-08 桌面项目追加清理用户要求清理桌面 Veyra 项目。独立 start/dirty 备份及 scan before→prepare→PowerShell 预检/-Execute→verify→scan after;8 旧构建 + 旧 1.2.0 解压目录、14,841 历史 logs 先 lossless 去重归档 E 盘,合计移除 17,395 文件路径/9 目录,零失败。C 卷实际增加 7.328 GiB,E 归档/扫描等约成本 2.105 GiB,两卷整轮净增约 5.046 GiB;桌面项目 19.631→12.267 GiB。35 工作树/495 脏文件、66,680 保留文件 SHA/ID/mtime、57 归档/二进制、587 编译输入及上轮 658 donor 通过,当前 VFG Ninja -n exit0;没有重编译或新 GPU 性能/播放测试。旧 ZIP 新增启动日志导致第一次准备停下,无删除;另行 lossless 保存后核对。新产物 E:/项目/Veyra/{archives,reports,logs}/desktop-cleanup-20261008,报告 docs/DESKTOP_STORAGE_CLEANUP_2026-10-08.md。不改产品或其它桌面文件,不 push/Release/关机,未重试上轮被拒绝的 E temp 删除。+# 2026-10-08 NVIDIA 显存现场诊断包++用户要求给显存泄漏用户使用的诊断包。独立 codex/nv-vram-field-20261008 / dbfceab,产品原文件不改;诊断头+构建生成3个覆盖对象,在同2.0.6/VFG基底查询 LOCAL/NON_LOCAL、部分图/NR纹理和上传缓冲最终COM生命周期、窗口/DPI及外部WDDM/进程/实际模块身份。每2/5秒低频,不回读像素、不加压、不改SDK/驱动、不推测driver归属。启动器白名单私有配置、同PID直到用户退出、自动摘要和证据ZIP,异常可恢复打包;凭据/媒体/profile/tmp/dmp不进入返回ZIP。根因未找到/未修复,Qt/decoder/SDK内部未完整覆盖,原显存看门狗保持。++实际命令:build-diagnostic.py 编译三对象+GUI重链接 exit0,原缓存和产品输入SHA不变;run-field.py final-exe-nr-stop-powershell51 97.875秒exit0,RTX5070原版NR1080/NVOF/窗口→全屏→关NR→停止;DXGI92条0失败、27有效WDDM、同PID7012、停止后36条segment记录,135资源创建/135最终销毁ID配对、存活0;原配置和1614母包文件SHA不变,凭据哨兵未复制/入ZIP。只是短测,没有复现长稳泄漏或量化性能开销。check-tools.py PS5.1解析/缺数据/连续标记段/恢复打包/隐私通过;package.py ZIP与内层源码CRC/每文件SHA通过;git diff --check和audit-state.py check保护36原工作树/495脏文件通过。失败:首轮继承PS7模块路径导致PS5.1 Get-FileHash不可用,启动前失败后显式加载宿主模块;初版NVOF验证器频道误匹配修正;补最终释放/DPI采样后重编重测最终EXE,原失败证据保留。++产物 E:/项目/Veyra/{reports,tests,logs,tmp,test-packages}/nv-vram-field-20261008,只保留一共享硬链接app、独立profile和必要证据;未重试旧被拒清理。交付ZIP Veyra-2.0.6-NVIDIA-VRAM-diagnostic.zip 78,606,236字节、SHA92a2a807202489a023a884c9fab998bd1f6d177e056e3b0ae7c04c06d832775d,EXE7519d7e864cfcf7cff9ef27ecff2a584d2a685175bc3cc5c6a18ea68e0c9f04b;包内有对应源码和补充诊断代码,无DLL/模型/SDK。详见docs/NV_VRAM_FIELD_REPORT_2026-10-08.md。不合并main、不push/Release、不代发文件、不关机。下一步受影响用户实际复现后返回同PID原始CSV/JSONL/日志,不能承诺一轮诊断包必然确定所有者。diff --git a/scripts/diagnostics/Pack-VRAM-Diagnostic.cmd b/scripts/diagnostics/Pack-VRAM-Diagnostic.cmdnew file mode 100644index 00000000..e44b3d83--- /dev/null+++ b/scripts/diagnostics/Pack-VRAM-Diagnostic.cmd@@ -0,0 +1,3 @@+@echo off+powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0Pack-VRAM-Diagnostic.ps1"+pausediff --git a/scripts/diagnostics/Pack-VRAM-Diagnostic.ps1 b/scripts/diagnostics/Pack-VRAM-Diagnostic.ps1new file mode 100644index 00000000..2e2cf078--- /dev/null+++ b/scripts/diagnostics/Pack-VRAM-Diagnostic.ps1@@ -0,0 +1,20 @@+param([string]$EvidenceDirectory='')+$ErrorActionPreference='Stop'+foreach($module in @('Microsoft.PowerShell.Utility','Microsoft.PowerShell.Management','Microsoft.PowerShell.Archive')) {+ Import-Module (Join-Path $PSHOME ('Modules/'+$module+'/'+$module+'.psd1')) -Force+}+if(@(Get-Process -Name 'veyra-vram-diagnostic' -ErrorAction SilentlyContinue).Count){throw '请先正常退出显存诊断播放器,再打包已有记录。'}+if(-not $EvidenceDirectory){+ $latest=Get-ChildItem -LiteralPath (Join-Path $PSScriptRoot 'logs') -Directory -Filter 'vram-diagnostic-*' |+ Sort-Object CreationTimeUtc -Descending | Select-Object -First 1+ if(-not $latest){throw '未找到诊断记录目录。'}+ $EvidenceDirectory=$latest.FullName+}+$root=[IO.Path]::GetFullPath($EvidenceDirectory)+if(-not(Test-Path -LiteralPath (Join-Path $root 'machine.json') -PathType Leaf)){throw '该目录不是诊断记录目录。'}+& (Join-Path $PSScriptRoot 'Summarize-VRAM-Diagnostic.ps1') -EvidenceDirectory $root+$allow=@('machine.json','process-memory.jsonl','modules.jsonl','markers.jsonl','dxgi-memory.csv','resource-events.csv','tracked-live-resources.csv','windows.csv','engine.log','console.log','stderr.log','receipt.json','summary.txt','summary.json','summary-failed.txt')+$files=@($allow | ForEach-Object {Join-Path $root $_} | Where-Object {Test-Path -LiteralPath $_ -PathType Leaf})+$zip=$root+'-repacked-'+(Get-Date -Format 'yyyyMMdd-HHmmss-fff')+'.zip'+Compress-Archive -LiteralPath $files -DestinationPath $zip -CompressionLevel Optimal+Write-Host ('只需要发回这个文件:'+$zip)diff --git a/scripts/diagnostics/Start-VRAM-Diagnostic.cmd b/scripts/diagnostics/Start-VRAM-Diagnostic.cmdnew file mode 100644index 00000000..f1734f8c--- /dev/null+++ b/scripts/diagnostics/Start-VRAM-Diagnostic.cmd@@ -0,0 +1,3 @@+@echo off+powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0Start-VRAM-Diagnostic.ps1"+pausediff --git a/scripts/diagnostics/Start-VRAM-Diagnostic.ps1 b/scripts/diagnostics/Start-VRAM-Diagnostic.ps1new file mode 100644index 00000000..59748121--- /dev/null+++ b/scripts/diagnostics/Start-VRAM-Diagnostic.ps1@@ -0,0 +1,152 @@+param(+ [string]$AppDirectory=$PSScriptRoot,+ [string]$ProfileSource='',+ [string]$OutputDirectory='',+ [string]$Source='',+ [ValidateRange(0,280)][int]$MaxSeconds=0,+ [ValidateRange(1,30)][int]$SampleSeconds=5+)+$ErrorActionPreference='Stop'+# A PowerShell 7 caller can pass module paths that exclude Windows PS 5.1's+# modules. Resolve the actual executing host's modules explicitly.+foreach($module in @('Microsoft.PowerShell.Utility','Microsoft.PowerShell.Management','CimCmdlets','Microsoft.PowerShell.Archive')) {+ Import-Module (Join-Path $PSHOME ('Modules/'+$module+'/'+$module+'.psd1')) -Force+}+$encoding=New-Object System.Text.UTF8Encoding($false)+function Write-JsonFile($Path,$Value) { [IO.File]::WriteAllText($Path,($Value | ConvertTo-Json -Depth 12),$encoding) }+function Open-Evidence($Path) {+ $file=[IO.File]::Open($Path,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::Read)+ return New-Object System.IO.StreamWriter($file,$encoding)+}+function Add-Evidence($Stream,$Value) { $Stream.WriteLine(($Value | ConvertTo-Json -Depth 10 -Compress));$Stream.Flush() }+$app=[IO.Path]::GetFullPath($AppDirectory)+$exe=Join-Path $app 'veyra-vram-diagnostic.exe'+foreach($file in @($exe,(Join-Path $app 'Qt6Core.dll'),(Join-Path $app 'qt.conf'),(Join-Path $app 'qml/Veyra/Main.qml'))) {+ if(-not(Test-Path -LiteralPath $file -PathType Leaf)){throw '请将诊断 EXE 和启动文件放到解压后的 Veyra 2.0.6 NVIDIA 主程序旁边。'}+}+if(@(Get-Process -Name 'veyra_qml_ui','veyra-vram-diagnostic','veyra-flash-diagnostic' -ErrorAction SilentlyContinue).Count -gt 0){throw '请先退出其他 Veyra 播放器,再启动诊断。'}+if(-not $ProfileSource){$ProfileSource=Join-Path $app 'runtime_local/user-data-2.0.0'}+if(-not $OutputDirectory){$OutputDirectory=Join-Path $app ('logs/vram-diagnostic-'+(Get-Date -Format 'yyyyMMdd-HHmmss-fff'))}+$output=[IO.Path]::GetFullPath($OutputDirectory)+if(Test-Path -LiteralPath $output){throw '输出目录已存在,拒绝覆盖已有诊断证据。'}+$null=New-Item -ItemType Directory -Path $output+$profile=Join-Path $output 'private-profile';$tmp=Join-Path $output 'tmp'+$null=New-Item -ItemType Directory -Path $profile,$tmp+$copied=@()+foreach($name in @('chain-session.v1','chain-session.v1.vfg','qml-preferences.v1.json','ui-session.v1','presets.v1','node-anchors.json')) {+ $from=Join-Path $ProfileSource $name+ if(Test-Path -LiteralPath $from -PathType Leaf){+ $copied+=@{path=$from;sha256=(Get-FileHash -LiteralPath $from -Algorithm SHA256).Hash}+ Copy-Item -LiteralPath $from -Destination (Join-Path $profile $name)+ }+}+$machine=@{utc=[DateTime]::UtcNow.ToString('o');powershell=$PSVersionTable.PSVersion.ToString();+ os=[Environment]::OSVersion.VersionString;is64BitProcess=[Environment]::Is64BitProcess;+ diagnosticSha256=(Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash;+ executable=$exe;sampleSeconds=$SampleSeconds;dxgiSampleSeconds=2;maxSeconds=$MaxSeconds;+ scope='Process WDDM/DXGI accounting and partial application resource lifetime; not physical residency or complete allocation ownership.'}+try{$machine.videoControllers=@(Get-CimInstance Win32_VideoController -OperationTimeoutSec 5 | Select-Object Name,PNPDeviceID,DriverVersion,AdapterRAM)}catch{$machine.videoControllersUnavailable=$_.Exception.Message}+try{$machine.windows=@(Get-CimInstance Win32_OperatingSystem -OperationTimeoutSec 5 | Select-Object Caption,Version,BuildNumber)}catch{$machine.windowsUnavailable=$_.Exception.Message}+Write-JsonFile (Join-Path $output 'machine.json') $machine+$records=Open-Evidence (Join-Path $output 'process-memory.jsonl')+$modules=Open-Evidence (Join-Path $output 'modules.jsonl')+$markers=Open-Evidence (Join-Path $output 'markers.jsonl')+$names=@('TEMP','TMP','CUDA_CACHE_PATH','VEYRA_LOG_FILE','VEYRA_VRAM_DIAGNOSTIC_DIR')+$saved=@{};foreach($name in $names){$saved[$name]=[Environment]::GetEnvironmentVariable($name,'Process')}+$known=@{};$process=$null;$result=1;$forcedStop=$false;$failure=$null;$reason='player-exited'+$clock=[Diagnostics.Stopwatch]::StartNew()+try{+ $env:TEMP=$tmp;$env:TMP=$tmp;$env:CUDA_CACHE_PATH=Join-Path $tmp 'cuda-cache'+ $env:VEYRA_LOG_FILE=Join-Path $output 'engine.log';$env:VEYRA_VRAM_DIAGNOSTIC_DIR=$output+ # Only child-process environment is changed; no registry or global driver setting.+ $arguments=@('--data-dir',$profile,'--page','pro')+ if($MaxSeconds -gt 0){$arguments+=@('--exit-after',($MaxSeconds*1000).ToString())}+ if($Source){$arguments+=$Source}+ if(@($arguments | Where-Object {$_.Contains('"') -or $_.EndsWith('\')}).Count){throw 'Unsupported argument quoting.'}+ $quoted=@($arguments | ForEach-Object {'"'+$_+'"'})+ $process=Start-Process -FilePath $exe -ArgumentList $quoted -WorkingDirectory $app -PassThru -WindowStyle Normal `+ -RedirectStandardOutput (Join-Path $output 'console.log') -RedirectStandardError (Join-Path $output 'stderr.log')+ $null=$process.Handle+ $start=$process.StartTime.ToUniversalTime()+ Add-Evidence $records @{type='process';pid=$process.Id;startUtc=$start.ToString('o');executable=$exe;utc=[DateTime]::UtcNow.ToString('o');elapsedMs=$clock.ElapsedMilliseconds}+ Write-Host '显存诊断已启动。按平时的方法复现;先保持设置不变,不要反复重启播放器。'+ Write-Host '显存持续涨或明显卡顿时:停止播放,保持播放器打开约 30 秒,再正常退出。'+ Write-Host '可选:切回此窗口按数字打标记(只记录,不替你改设置):'+ Write-Host '1 窗口播放 2 全屏播放 3 已关闭 NR 4 已开启 NR 5 已停止播放 6 已看到显存增长'+ Write-Host ('退出诊断播放器后自动打包。输出:'+$output)+ $nextSample=0L;$lastGpu=$null;$phase='unmarked'+ while(-not $process.HasExited){+ try{+ while(-not [Console]::IsInputRedirected -and [Console]::KeyAvailable){+ $key=[Console]::ReadKey($true).KeyChar.ToString()+ $labels=@{'1'='windowed';'2'='fullscreen';'3'='nr-off';'4'='nr-on';'5'='playback-stopped';'6'='growth-observed'}+ if($labels.ContainsKey($key)){+ $phase=$labels[$key]+ Add-Evidence $markers @{type='user-marker';utc=[DateTime]::UtcNow.ToString('o');elapsedMs=$clock.ElapsedMilliseconds;pid=$process.Id;phase=$phase;meaning='User annotation, not automatic proof of actual state'}+ Write-Host ('已记录:'+$phase)+ }+ }+ }catch{} # noninteractive consoles still collect evidence+ if($clock.ElapsedMilliseconds -ge $nextSample){+ $current=Get-Process -Id $process.Id -ErrorAction SilentlyContinue+ if(-not $current){break}+ if($current.Path -ne $exe -or $current.StartTime.ToUniversalTime() -ne $start){throw 'PID/executable identity changed; refusing to mix sessions.'}+ $record=@{type='sample';utc=[DateTime]::UtcNow.ToString('o');elapsedMs=$clock.ElapsedMilliseconds;pid=$process.Id;phase=$phase}+ try{+ $record.gpu=@(Get-CimInstance Win32_PerfFormattedData_GPUPerformanceCounters_GPUProcessMemory -Filter "Name LIKE 'pid_$($process.Id)_%'" -OperationTimeoutSec 5 |+ Where-Object {$_.Name.StartsWith('pid_'+$process.Id+'_')} | Select-Object Name,DedicatedUsage,SharedUsage,TotalCommitted)+ $record.gpuAvailable=$record.gpu.Count -gt 0+ if($record.gpuAvailable){$lastGpu=($record.gpu | Measure-Object DedicatedUsage -Sum).Sum}+ }catch{$record.gpuAvailable=$false;$record.gpuUnavailable=$_.Exception.Message}+ try{+ $current.Refresh();$record.privateBytes=$current.PrivateMemorySize64;$record.workingSetBytes=$current.WorkingSet64;$record.handles=$current.HandleCount+ $record.modules=@($current.Modules | Select-Object ModuleName,FileName)+ foreach($module in $record.modules){+ $path=$module.FileName+ if(-not $known.ContainsKey($path)){+ $identity=@{type='module';utc=[DateTime]::UtcNow.ToString('o');elapsedMs=$clock.ElapsedMilliseconds;name=$module.ModuleName;path=$path}+ try{$item=Get-Item -LiteralPath $path;$identity.bytes=$item.Length;$identity.modifiedUtc=$item.LastWriteTimeUtc.ToString('o');+ $identity.version=$item.VersionInfo.FileVersion;$identity.sha256=(Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash+ }catch{$identity.identityUnavailable=$_.Exception.Message}+ Add-Evidence $modules $identity;$known[$path]=$identity+ }+ }+ }catch{$record.processOrModulesUnavailable=$_.Exception.Message}+ Add-Evidence $records $record+ if($record.gpuAvailable){Write-Host ('[{0:hh\:mm\:ss}] 专用进程计数 {1:N0} MiB,共享 {2:N0} MiB,标记 {3}' -f $clock.Elapsed,($lastGpu/1MB),((($record.gpu | Measure-Object SharedUsage -Sum).Sum)/1MB),$phase)}+ else{Write-Host 'GPU 计数暂不可用,已明确记录;没有用 0 代替。'}+ $nextSample=$clock.ElapsedMilliseconds+$SampleSeconds*1000+ }+ if($MaxSeconds -gt 0 -and $clock.Elapsed.TotalSeconds -gt $MaxSeconds+45){+ $forcedStop=$true;$reason='bounded-test-timeout';Stop-Process -Id $process.Id -Force;$process.WaitForExit();break+ }+ Start-Sleep -Milliseconds 200+ }+ $process.WaitForExit();$process.Refresh();$result=$process.ExitCode+ if($null -eq $result){$result=125};if($forcedStop){$result=124}+}catch{+ $failure=$_.Exception.Message;$reason='collector-error';$result=1+ Write-Host ('采集失败,已有数据会保留:'+$failure)+}finally{+ foreach($name in $names){[Environment]::SetEnvironmentVariable($name,$saved[$name],'Process')}+ $records.Dispose();$modules.Dispose();$markers.Dispose()+}+$unchanged=$true+foreach($item in $copied){if(-not(Test-Path -LiteralPath $item.path -PathType Leaf) -or (Get-FileHash -LiteralPath $item.path -Algorithm SHA256).Hash -ne $item.sha256){$unchanged=$false}}+$moduleChanged=@()+foreach($path in $known.Keys){+ try{+ $file=Get-Item -LiteralPath $path;$prior=$known[$path]+ if($prior.ContainsKey('sha256') -and ((Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash -ne $prior.sha256)){$moduleChanged+=$path}+ }catch{$moduleChanged+=($path+' [unavailable at end]')}+}+Write-JsonFile (Join-Path $output 'receipt.json') @{exit=$result;forcedStop=$forcedStop;reason=$reason;collectorFailure=$failure;elapsedSeconds=$clock.Elapsed.TotalSeconds;+ pid=$(if($process){$process.Id}else{$null});originalSettingsUnchanged=$unchanged;moduleFilesChanged=$moduleChanged;+ privacy='Evidence includes paths/device/module identities and application logs; excludes profile, credentials, media and crash dumps.'}+try{& (Join-Path $PSScriptRoot 'Summarize-VRAM-Diagnostic.ps1') -EvidenceDirectory $output}catch{[IO.File]::WriteAllText((Join-Path $output 'summary-failed.txt'),$_.Exception.ToString(),$encoding)}+# Strict, named whitelist. Never recursively archive the private profile/tmp.+$allow=@('machine.json','process-memory.jsonl','modules.jsonl','markers.jsonl','dxgi-memory.csv','resource-events.csv','tracked-live-resources.csv','windows.csv','engine.log','console.log','stderr.log','receipt.json','summary.txt','summary.json','summary-failed.txt')+$evidence=@($allow | ForEach-Object {Join-Path $output $_} | Where-Object {Test-Path -LiteralPath $_ -PathType Leaf})+Compress-Archive -LiteralPath $evidence -DestinationPath ($output+'.zip') -CompressionLevel Optimal+Write-Host ('完成。只需要发回这个文件:'+$output+'.zip')+exit $resultdiff --git a/scripts/diagnostics/Summarize-VRAM-Diagnostic.ps1 b/scripts/diagnostics/Summarize-VRAM-Diagnostic.ps1new file mode 100644index 00000000..93326975--- /dev/null+++ b/scripts/diagnostics/Summarize-VRAM-Diagnostic.ps1@@ -0,0 +1,59 @@+param([Parameter(Mandatory)][string]$EvidenceDirectory)+$ErrorActionPreference='Stop'+Import-Module (Join-Path $PSHOME 'Modules/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1') -Force+$encoding=New-Object System.Text.UTF8Encoding($false)+$root=[IO.Path]::GetFullPath($EvidenceDirectory)+$summary=@{units='MiB = 1048576 bytes';allocationOwner='unconfirmed';notes=@(+ 'DXGI and WDDM are separate process accounting sources. They do not equal physical board residency.',+ 'Tracked resources cover selected graph/NR textures and graph uploads only; not Qt/decoder/SDK internal allocations.',+ 'User markers annotate phases; use engine logs to verify actual changes. Whole-session endpoints mix stages and are not a steady-state leak rate.')}+$lines=New-Object 'System.Collections.Generic.List[string]'+$lines.Add('Veyra 显存诊断摘要(根因未确认,不能据此单独判定驱动泄漏)')+function Add-Range($Rows,$TimeColumn,$ValueColumn,$Label){+ if($Rows.Count -lt 2){$lines.Add($Label+':有效样本不足');return $null}+ $first=$Rows[0];$last=$Rows[-1];$seconds=([double]$last.$TimeColumn-[double]$first.$TimeColumn)/1000+ if($seconds -le 0){$lines.Add($Label+':时间跨度不足');return $null}+ $begin=[double]$first.$ValueColumn/1MB;$end=[double]$last.$ValueColumn/1MB+ $peak=($Rows | ForEach-Object {[double]$_.$ValueColumn/1MB} | Measure-Object -Maximum).Maximum+ $result=@{samples=$Rows.Count;seconds=$seconds;firstMiB=$begin;lastMiB=$end;peakMiB=$peak;netMiB=$end-$begin;endpointMiBPerMinute=($end-$begin)*60/$seconds}+ $lines.Add(('{0}:{1:N1} → {2:N1} MiB,峰值 {3:N1},净变化 {4:N1};{5:N1} 秒 / {6} 样本' -f $Label,$begin,$end,$peak,($end-$begin),$seconds,$Rows.Count))+ return $result+}+$dxgiFile=Join-Path $root 'dxgi-memory.csv'+if(Test-Path -LiteralPath $dxgiFile){+ $rows=@(Import-Csv -LiteralPath $dxgiFile)+ $summary.dxgi=@()+ foreach($group in @($rows | Group-Object luid,generation,segment)){+ $valid=@($group.Group | Where-Object {$_.queryHr -eq '0' -and $_.usageBytes -ne ''})+ $range=Add-Range $valid 'tickMs' 'usageBytes' ('DXGI '+$group.Name)+ $summary.dxgi+=@{identity=$group.Name;failedSamples=@($group.Group | Where-Object {$_.queryHr -ne '0'}).Count;range=$range}+ }+ if($rows.Count){+ $last=$rows[-1];$summary.trackedAtLastSample=@{created=$last.trackedCreated;destroyed=$last.trackedDestroyed;live=$last.trackedLive;bytesEstimate=$last.trackedBytesEstimate;attachFailures=$last.attachFailures;unknownSizes=$last.unknownSizes}+ $lines.Add(('末次已覆盖资源:创建 {0},销毁 {1},存活 {2},分配大小估计 {3:N1} MiB(不是总显存)' -f $last.trackedCreated,$last.trackedDestroyed,$last.trackedLive,([double]$last.trackedBytesEstimate/1MB)))+ }+}else{$lines.Add('DXGI:无文件;可能尚未打开任何视频或设备创建失败。')}+$processFile=Join-Path $root 'process-memory.jsonl'+if(Test-Path -LiteralPath $processFile){+ $samples=@(Get-Content -LiteralPath $processFile -Encoding UTF8 | ForEach-Object {$_ | ConvertFrom-Json} | Where-Object {$_.type -eq 'sample'})+ $wddm=@($samples | Where-Object {$_.gpuAvailable} | ForEach-Object {+ [pscustomobject]@{elapsedMs=$_.elapsedMs;dedicated=($_.gpu | Measure-Object DedicatedUsage -Sum).Sum;shared=($_.gpu | Measure-Object SharedUsage -Sum).Sum;phase=$_.phase}+ })+ $summary.wddmDedicated=Add-Range $wddm 'elapsedMs' 'dedicated' 'WDDM Dedicated(所有实例合计)'+ $summary.wddmShared=Add-Range $wddm 'elapsedMs' 'shared' 'WDDM Shared(所有实例合计)'+ $summary.gpuUnavailableSamples=@($samples | Where-Object {-not $_.gpuAvailable}).Count+ $summary.markedPhases=@()+ # Each contiguous phase is kept separate; repeated phase names are never merged.+ $phaseRows=@();$phaseName=$null;$ordinal=0+ foreach($row in $wddm+@([pscustomobject]@{phase='__end__'})){+ if($row.phase -ne $phaseName -and $phaseRows.Count){+ $ordinal++;$range=Add-Range $phaseRows 'elapsedMs' 'dedicated' ('标记段 '+$ordinal+' '+$phaseName)+ $summary.markedPhases+=@{ordinal=$ordinal;phase=$phaseName;wddmDedicated=$range};$phaseRows=@()+ }+ $phaseName=$row.phase;if($row.phase -ne '__end__'){$phaseRows+=,$row}+ }+}+$lines.Add('出现持续增长时:保持同 PID,记录关闭 NR / 停止播放后的回收;不必等到显存耗尽。')+$lines.Add('返回 evidence ZIP 即可;原始 JSONL/CSV 和引擎日志比摘要更重要。')+[IO.File]::WriteAllText((Join-Path $root 'summary.txt'),($lines -join [Environment]::NewLine),$encoding)+[IO.File]::WriteAllText((Join-Path $root 'summary.json'),($summary | ConvertTo-Json -Depth 14),$encoding)diff --git a/scripts/diagnostics/vram-field/README.md b/scripts/diagnostics/vram-field/README.mdnew file mode 100644index 00000000..a7826735--- /dev/null+++ b/scripts/diagnostics/vram-field/README.md@@ -0,0 +1,33 @@+# Veyra 2.0.6 NVIDIA 显存诊断包++这是收集证据的程序,**不是已经修复显存增长的新版本**。基于当前 2.0.6 / VFG 优化后的产品代码,增加低频内存与资源生命周期记录,没有像素回读、显存压力负载、SDK/vtable hook、驱动修改或自动清缓存。原运行库不变。++## 给测试用户++1. 先退出 Veyra。将本包的 `veyra-vram-diagnostic.exe`、`Start-VRAM-Diagnostic.cmd`、`Start-VRAM-Diagnostic.ps1`、`Summarize-VRAM-Diagnostic.ps1`、`Pack-VRAM-Diagnostic.cmd`、`Pack-VRAM-Diagnostic.ps1` **放到已解压的 Veyra 2.0.6 NVIDIA 目录内,与原主程序并排**。不用覆盖或重命名原主程序,也不用管理员权限。不能直接在 ZIP 内运行。+2. 双击 `Start-VRAM-Diagnostic.cmd`,在弹出的诊断播放器里,用原来会出问题的输入、NR 版本和设置正常播放。先保持条件不变;如果以前要几分钟才涨,就继续观察,不要每几分钟重启程序。控制台可以最小化,**不要关掉**。诊断没有默认倒计时,也不会替你开关效果。+3. 一旦确认显存持续涨或明显卡顿,不必等到爆显存。可以先关闭 NR 观察约 20 秒,再**停止播放、保持播放器打开约 30 秒**,最后正常退出播放器。若情况已经很卡,直接停止播放即可。关闭播放器后,控制台会生成 `logs/vram-diagnostic-日期时间.zip`;把这个 ZIP 发回来。++需要辅助标记时,切回控制台按数字:`1` 窗口、`2` 全屏、`3` 已关 NR、`4` 已开 NR、`5` 已停止播放、`6` 已看到增长。这些按键只记录你已完成的操作,不会操作播放器。主日志也会记录实际处理图/设置变化。尽量用原来正常播放条件复现,先不要同时改驱动、NR 包、画面尺寸和补帧。++如果控制台被误关或播放器崩溃,先退出诊断播放器,再双击 `Pack-VRAM-Diagnostic.cmd`,它会重新打包最近一轮已有记录。异常退出不会补出缺失的退出前采样。++诊断使用独立配置副本,不写回原来的配置。只复制普通设置白名单;串流账号/密钥不复制,需要时在诊断播放器中重新登录。返回 ZIP 不包含配置目录、视频、截图、崩溃内存转储或凭据文件;**日志仍可能包含媒体路径、Windows 用户目录、设备标识和模块路径**。没有网络上传,文件由你自行发送。退出后不需要长期使用诊断 EXE。++## 这次多了什么证据++- `dxgi-memory.csv`:每 2 秒采进程在设备适配器 node0 的 LOCAL/NON_LOCAL Usage/Budget/Reservation,保留字节、LUID、设备代次、原始 HRESULT 和完成 fence。查询失败留空,不伪填 0;contextActive=0 表示引擎 context 已关闭,不表示整个进程已退出。+- `resource-events.csv` / `tracked-live-resources.csv`:选定调用点的处理图纹理、NR 层纹理、处理图上传缓冲的创建/最终 COM 销毁,存活资源 ID、年龄和大小估计。group 0/1/2 分别是 graph texture / NR texture / graph upload。通过资源私有数据中的观察 token 跟踪,观察器不持有资源或设备引用。释放事件队列最多 4096 项,溢出次数明确记录;没有无界历史缓存。+- `windows.csv`:每 2 秒记录本进程可见顶层窗口几何、所在显示器分辨率/刷新率、窗口 DPI 和前台状态,不记录窗口标题。coversMonitor 仅表示几何覆盖显示器,不等于独立翻转或 MPO;DPI=0/空显示模式表示 API 数据不可用。+- `process-memory.jsonl`:每 5 秒的 WDDM GPU 进程计数,保留每个 LUID/phys 实例,以及 PrivateBytes、工作集、句柄和当时已加载模块列表。字段不可用明确记录。按 EXE/PID/启动时刻验证身份,不混入 PID 复用后的进程。+- `modules.jsonl`:模块首次出现时的磁盘路径、版本、大小、修改时间和 SHA256;退出时复核已观察文件是否变化。模块加载不等于功能启用,磁盘 SHA 不等于内存映像校验。+- `engine.log`:实际 NR/光流/补帧选择、分辨率、设置 revision、处理图和 NGX/NVOF 创建/关闭及错误。已有产品显存看门狗保持原行为,若触发重建或退出全屏,必须按此日志分段分析。+- `summary.txt/json`:有效样本数量、观察时长、峰值/净增、各用户标记段。全程可能包含开关效果/停止,首尾变化率不能冒充稳态泄漏率。++三种口径不能互换:DXGI Usage、WDDM Dedicated/Shared、已跟踪资源的分配大小估计。**不能相减后把余数叫“驱动泄漏”**。此轮没有覆盖 Qt/decoder/采集源/其它 passes/SDK 的所有内部资源,尚不能直接给出完整分配所有者;D3D12 对象销毁也不保证 WDDM 立刻回收板载驻留。这些是诊断包的边界。++## 对应源码与构建++本包包含原产品对应源码 ZIP 和诊断补充源码(VramField.h、3 份生成的覆盖 cpp、构建脚本与收据)。产品实现未修改;构建脚本从 source/src 生成只加诊断的对象,将它们置于原静态库前重链接 GUI。现有缓存对象要求与收据一致;若更换源码必须用完整开发环境重新构建。没有把 NVIDIA/FFmpeg/Qt 开发 SDK 或运行 DLL 放入补充源码。++本机 RTX5070 短测只验证工具工作与本机回收,并不能代替受影响显卡的真实复现。根因仍待现场证据。diff --git a/scripts/diagnostics/vram-field/VramField.h b/scripts/diagnostics/vram-field/VramField.hnew file mode 100644index 00000000..0dd25c4c--- /dev/null+++ b/scripts/diagnostics/vram-field/VramField.h@@ -0,0 +1,175 @@+#pragma once+// Diagnostic-only instrumentation. No SDK hooks, resource references, GPU work+// or waits. Only resources created at the explicitly replaced call sites count.+#include "veyra/pipeline/GpuPassUtils.h"+#include <dxgi1_6.h>+#include <atomic>+#include <condition_variable>+#include <filesystem>+#include <fstream>+#include <map>+#include <memory>+#include <mutex>+#include <thread>++namespace vramField {+inline uint64_t tick() { return GetTickCount64(); }+inline uint64_t utcMs() {+ FILETIME ft{}; GetSystemTimeAsFileTime(&ft);+ return ((uint64_t(ft.dwHighDateTime)<<32)|ft.dwLowDateTime)/10000-11644473600000ull;+}+struct Item { uint64_t id,bytes,born; unsigned group; };+struct Retired { Item item; uint64_t utc,time; };+struct Ledger {+ std::mutex mutex;+ std::map<uint64_t,Item> live;+ uint64_t next=0,created=0,destroyed=0,liveBytes=0,peakBytes=0,attachFailures=0,unknownSizes=0;+ uint64_t createdBy[3]{},destroyedBy[3]{},bytesBy[3]{};+ std::vector<Retired> retired;+ uint64_t droppedReleaseEvents=0;+};+struct Adapter {+ Microsoft::WRL::ComPtr<IDXGIAdapter3> adapter;+ ID3D12Fence* fence=nullptr; // protected by State::mutex; unregister before owner release+ uint64_t luid=0,generation=0;+ bool active=false;+};+struct State {+ std::shared_ptr<Ledger> ledger=std::make_shared<Ledger>();+ std::mutex mutex;+ std::condition_variable cv;+ std::map<const void*,Adapter> adapters;+ std::ofstream samples,events,windows,live;+ uint64_t generation=0;+ bool enabled=false,quit=false;+ std::thread worker;+ State() {+ wchar_t dir[32768]{};+ const auto n=GetEnvironmentVariableW(L"VEYRA_VRAM_DIAGNOSTIC_DIR",dir,32768);+ if(!n||n>=32768)return;+ const std::filesystem::path path(dir);+ samples.open(path/L"dxgi-memory.csv",std::ios::binary);+ events.open(path/L"resource-events.csv",std::ios::binary);+ windows.open(path/L"windows.csv",std::ios::binary);+ live.open(path/L"tracked-live-resources.csv",std::ios::binary);+ enabled=bool(samples)&&bool(events)&&bool(windows)&&bool(live);+ if(!enabled)return;+ samples<<"utcMs,tickMs,pid,luid,generation,contextActive,segment,queryHr,usageBytes,budgetBytes,reservationBytes,availableReservationBytes,fenceAvailable,fenceCompleted,trackedCreated,trackedDestroyed,trackedLive,trackedBytesEstimate,trackedPeakBytesEstimate,attachFailures,unknownSizes,graphLive,nrLive,uploadLive\n";+ events<<"utcMs,tickMs,event,owner,resourceId,group,allocationBytesEstimate,detail\n";+ windows<<"utcMs,tickMs,hwnd,foreground,visible,dpi,left,top,width,height,monitorWidth,monitorHeight,displayWidth,displayHeight,refreshHz,coversMonitor\n";+ live<<"utcMs,tickMs,resourceId,group,allocationBytesEstimate,ageMs,droppedReleaseEvents\n";+ events.flush();samples.flush();+ worker=std::thread([this]{run();});+ }+ ~State() {+ {std::lock_guard lock(mutex);quit=true;}+ cv.notify_all();if(worker.joinable())worker.join();+ if(enabled){std::lock_guard lock(ledger->mutex);flushRetired();}+ }+ void flushRetired(){ // caller holds ledger->mutex and sampler owns the stream+ for(const auto& r:ledger->retired)events<<r.utc<<','<<r.time<<",resource-final-release,0,"<<r.item.id<<','<<r.item.group<<','<<r.item.bytes<<",0\n";+ ledger->retired.clear();events.flush();+ }+ static BOOL CALLBACK window(HWND hwnd,LPARAM parameter){+ DWORD pid=0;GetWindowThreadProcessId(hwnd,&pid);+ if(pid!=GetCurrentProcessId()||!IsWindowVisible(hwnd))return TRUE;+ auto& s=*reinterpret_cast<State*>(parameter);RECT r{};if(!GetWindowRect(hwnd,&r))return TRUE;+ MONITORINFOEXW monitor{};monitor.cbSize=sizeof(monitor);+ if(!GetMonitorInfoW(MonitorFromWindow(hwnd,MONITOR_DEFAULTTONEAREST),&monitor))return TRUE;+ DEVMODEW mode{};mode.dmSize=sizeof(mode);const auto available=EnumDisplaySettingsW(monitor.szDevice,ENUM_CURRENT_SETTINGS,&mode);+ const auto& m=monitor.rcMonitor;+ s.windows<<utcMs()<<','<<tick()<<','<<uint64_t(reinterpret_cast<uintptr_t>(hwnd))<<','<<(GetForegroundWindow()==hwnd)<<",1,"<<GetDpiForWindow(hwnd)<<','<<r.left<<','<<r.top<<','<<r.right-r.left<<','<<r.bottom-r.top<<','<<m.right-m.left<<','<<m.bottom-m.top<<',';+ if(available)s.windows<<mode.dmPelsWidth<<','<<mode.dmPelsHeight<<','<<mode.dmDisplayFrequency;+ else s.windows<<",,";+ s.windows<<','<<(r.left<=m.left&&r.top<=m.top&&r.right>=m.right&&r.bottom>=m.bottom)<<'\n';+ return TRUE;+ }+ void run() {+ std::unique_lock lock(mutex);+ unsigned cycle=0;+ while(!quit) {+ EnumWindows(window,reinterpret_cast<LPARAM>(this));windows.flush();+ for(auto& [owner,a]:adapters) {+ for(unsigned segment=0;segment<2;++segment) {+ DXGI_QUERY_VIDEO_MEMORY_INFO info{};+ const HRESULT hr=a.adapter?a.adapter->QueryVideoMemoryInfo(0,DXGI_MEMORY_SEGMENT_GROUP(segment),&info):E_NOINTERFACE;+ samples<<utcMs()<<','<<tick()<<','<<GetCurrentProcessId()<<','<<a.luid<<','<<a.generation<<','<<a.active<<','<<(segment?"nonlocal":"local")<<','<<uint32_t(hr)<<',';+ if(SUCCEEDED(hr))samples<<info.CurrentUsage<<','<<info.Budget<<','<<info.CurrentReservation<<','<<info.AvailableForReservation;+ else samples<<",,,"; // unavailable, never a fake zero+ samples<<','<<(a.fence!=nullptr)<<',';+ if(a.fence)samples<<a.fence->GetCompletedValue();+ std::lock_guard counters(ledger->mutex);+ samples<<','<<ledger->created<<','<<ledger->destroyed<<','<<ledger->live.size()<<','<<ledger->liveBytes<<','<<ledger->peakBytes<<','<<ledger->attachFailures<<','<<ledger->unknownSizes;+ for(unsigned group=0;group<3;++group)samples<<','<<ledger->createdBy[group]-ledger->destroyedBy[group];+ samples<<'\n';+ }+ }+ {std::lock_guard counters(ledger->mutex);flushRetired();+ if(cycle++%5==0){for(const auto& [id,item]:ledger->live)+ live<<utcMs()<<','<<tick()<<','<<id<<','<<item.group<<','<<item.bytes<<','<<tick()-item.born<<','<<ledger->droppedReleaseEvents<<'\n';+ live.flush();}}+ samples.flush();+ cv.wait_for(lock,std::chrono::seconds(2),[this]{return quit;});+ }+ }+ void event(const char* name,const void* owner,uint64_t id=0,unsigned group=0,uint64_t bytes=0,uint64_t detail=0) {+ if(!enabled)return;+ std::lock_guard lock(mutex);+ events<<utcMs()<<','<<tick()<<','<<name<<','<<uint64_t(reinterpret_cast<uintptr_t>(owner))<<','<<id<<','<<group<<','<<bytes<<','<<detail<<'\n';+ events.flush();+ }+};+inline State& state(){static State s;return s;}+inline void event(const char* name,const void* owner,uint64_t detail=0){state().event(name,owner,0,0,0,detail);}+inline void contextOpened(const void* owner,IDXGIAdapter1* adapter,ID3D12Fence* fence,uint64_t luid){+ auto& s=state();if(!s.enabled)return;+ {std::lock_guard lock(s.mutex);auto& a=s.adapters[owner];+ if(adapter)adapter->QueryInterface(IID_PPV_ARGS(&a.adapter));+ a.fence=fence;a.luid=luid;a.active=true;a.generation=++s.generation;}+ s.event("context-open",owner);s.cv.notify_all();+}+inline void contextClosing(const void* owner){+ auto& s=state();if(!s.enabled)return;+ s.event("context-close",owner);+ std::lock_guard lock(s.mutex);const auto it=s.adapters.find(owner);+ if(it!=s.adapters.end()){it->second.fence=nullptr;it->second.active=false;}+}+// A resource owns its token; the token owns no COM object. Final Release of+// the resource releases the token, exposing SDK-retained application textures.+inline constexpr GUID tokenGuid{0x868b6eea,0x2e39,0x41da,{0xb1,0x83,0xca,0x32,0xc3,0xb5,0xd2,0x60}};+class Token final:public IUnknown {+ std::atomic<ULONG> refs{1};+ std::shared_ptr<Ledger> ledger;+ Item item;+public:+ bool registered=false;+ Token(std::shared_ptr<Ledger> l,Item i):ledger(std::move(l)),item(i){}+ ~Token(){if(registered){std::lock_guard lock(ledger->mutex);ledger->live.erase(item.id);+ ++ledger->destroyed;++ledger->destroyedBy[item.group];ledger->liveBytes-=item.bytes;ledger->bytesBy[item.group]-=item.bytes;+ if(ledger->retired.size()<4096)ledger->retired.push_back({item,utcMs(),tick()});else ++ledger->droppedReleaseEvents;}}+ HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid,void** out)override{+ if(!out)return E_POINTER;*out=nullptr;if(iid!=IID_IUnknown)return E_NOINTERFACE;*out=this;AddRef();return S_OK;}+ ULONG STDMETHODCALLTYPE AddRef()override{return ++refs;}+ ULONG STDMETHODCALLTYPE Release()override{auto n=--refs;if(!n)delete this;return n;}+};+inline void track(ID3D12Device* device,ID3D12Resource* resource,unsigned group){+ auto& s=state();if(!s.enabled||!device||!resource)return;+ // Do not replace an existing token or double-count aliased resources.+ IUnknown* existing=nullptr;UINT size=sizeof(existing);+ if(SUCCEEDED(resource->GetPrivateData(tokenGuid,&size,&existing))&&existing){existing->Release();return;}+ const auto desc=resource->GetDesc();const auto allocation=device->GetResourceAllocationInfo(0,1,&desc);+ const bool known=allocation.SizeInBytes!=UINT64_MAX;+ auto ledger=s.ledger;Item item{};+ {std::lock_guard lock(ledger->mutex);item={++ledger->next,known?allocation.SizeInBytes:0,tick(),group};}+ auto* token=new Token(ledger,item);+ const auto hr=resource->SetPrivateDataInterface(tokenGuid,token);+ {std::lock_guard lock(ledger->mutex);+ if(SUCCEEDED(hr)){token->registered=true;ledger->live.emplace(item.id,item);++ledger->created;++ledger->createdBy[group];+ ledger->liveBytes+=item.bytes;ledger->bytesBy[group]+=item.bytes;ledger->peakBytes=std::max(ledger->peakBytes,ledger->liveBytes);ledger->unknownSizes+=!known;}+ else ++ledger->attachFailures;}+ token->Release();s.event(SUCCEEDED(hr)?"resource-create":"resource-track-failed",resource,item.id,group,item.bytes,uint32_t(hr));+}+inline auto graphTexture(ID3D12Device* d,uint32_t w,uint32_t h,DXGI_FORMAT f,bool u){auto r=veyra::pipeline::makeTexture(d,w,h,f,u);track(d,r.Get(),0);return r;}+inline auto nrTexture(ID3D12Device* d,uint32_t w,uint32_t h,DXGI_FORMAT f,bool u){auto r=veyra::pipeline::makeTexture(d,w,h,f,u);track(d,r.Get(),1);return r;}+inline auto graphUpload(ID3D12Device* d,uint64_t bytes){auto r=veyra::pipeline::makeUploadBuffer(d,bytes);track(d,r.Get(),2);return r;}+}diff --git a/scripts/diagnostics/vram-field/build-diagnostic.py b/scripts/diagnostics/vram-field/build-diagnostic.pynew file mode 100644index 00000000..07e5cc57--- /dev/null+++ b/scripts/diagnostics/vram-field/build-diagnostic.py@@ -0,0 +1,94 @@+"""Relink diagnostic-only overrides; never write into the cached product build."""+from pathlib import Path+import ctypes, hashlib, json, os, re, shutil, subprocess++TASK='nv-vram-field-20261008'+BASE=Path('E:/项目/Veyra')+HERE=Path(__file__).parent+SOURCE=HERE.parents[2]+BUILD=BASE/'build/vfg-next-20261007'+OUT=BASE/'tests'/TASK/'compiled'+LOG=BASE/'logs'/TASK/'build'+TMP=BASE/'tmp'/TASK/'build'+for path in (OUT,LOG,TMP):path.mkdir(parents=True,exist_ok=True)+def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()+shell=ctypes.WinDLL('shell32',use_last_error=True)+shell.CommandLineToArgvW.argtypes=[ctypes.c_wchar_p,ctypes.POINTER(ctypes.c_int)]+shell.CommandLineToArgvW.restype=ctypes.POINTER(ctypes.c_wchar_p)+ctypes.windll.kernel32.LocalFree.argtypes=[ctypes.c_void_p]+def args(s):+ n=ctypes.c_int();p=shell.CommandLineToArgvW(s,ctypes.byref(n))+ result=[p[i] for i in range(n.value)];ctypes.windll.kernel32.LocalFree(p);return result+NINJA=r'C:/PROGRA~2/MICROS~3/2022/BUILDT~1/Common7/IDE/COMMON~1/MICROS~1/CMake/Ninja/ninja.exe'+commands=subprocess.check_output([NINJA,'-t','commands','veyra_fg_presentation_tests'],cwd=BUILD).decode('utf-8')+compile_line=next(x for x in commands.splitlines() if ' -c ' in x and x.endswith('FgPresentationTests.cpp'))+compile_args=args(compile_line)+(LOG/'compile-template.json').write_text(json.dumps(compile_args,ensure_ascii=False,indent=2),encoding='utf-8')+env=dict(os.environ);env.update(TEMP=str(TMP),TMP=str(TMP))+vcvars=r'C:\PROGRA~2\MICROS~3\2022\BUILDT~1\VC\Auxiliary\Build\vcvars64.bat'+setup=subprocess.run(['cmd.exe','/u','/d','/c','call '+vcvars+' >nul && set'],capture_output=True,text=True,encoding='utf-16-le',check=True,env=env)+for line in setup.stdout.splitlines():+ if '=' in line:+ k,v=line.split('=',1)+ if k and not k.startswith('='):env[k]=v+env.update(TEMP=str(TMP),TMP=str(TMP))++inputs={};objects=[];build_commands=[];changes={}+for name in ('gfx/D3D12DeviceContext.cpp','pipeline/EnhanceGraph.cpp','pipeline/NrInstance.cpp'):+ product=SOURCE/'src'/name;text=product.read_text(encoding='utf-8');inputs[str(product)]=sha(product)+ def replace(old,new):+ global text+ assert text.count(old)==1,(name,old,text.count(old))+ text=text.replace(old,new)+ if name.startswith('gfx'):+ replace(' initialized_ = true;', ' initialized_ = true;\n vramField::contextOpened(this,adapter_.Get(),fence_.Get(),adapterInfo_.luid);')+ replace(' // Slot work is drained', ' vramField::contextClosing(this);\n // Slot work is drained')+ elif name.endswith('EnhanceGraph.cpp'):+ text=text.replace('makeTexture(', 'vramField::graphTexture(').replace('makeUploadBuffer(', 'vramField::graphUpload(')+ replace('bool EnhanceGraph::initialize(const EnhanceGraphDesc& desc)\n{',+ 'bool EnhanceGraph::initialize(const EnhanceGraphDesc& desc)\n{\n vramField::event("graph-initialize",this);')+ # The event marks entry, not successful construction or final GPU retirement.+ replace('void EnhanceGraph::shutdown()\n{', 'void EnhanceGraph::shutdown()\n{\n vramField::event("graph-shutdown-entry",this);')+ else:+ text=text.replace('makeTexture(', 'vramField::nrTexture(')+ replace(' historyValid = false;\n return true;', ' historyValid = false;\n vramField::event("nr-layer-created",this);\n return true;')+ replace('void NrInstance::close() {', 'void NrInstance::close() {\n if(created())vramField::event("nr-layer-close-entry",this);')+ text='#include "VramField.h"\n'+text+ output=OUT/(Path(name).stem+'.diagnostic.cpp');output.write_text(text,encoding='utf-8')+ obj=OUT/(Path(name).stem+'.obj')+ command=[x for x in compile_args if not x.startswith(('/Fo','/Fd')) and x!='/showIncludes' and not x.endswith('FgPresentationTests.cpp')]+ command+=['/I'+str(HERE),'/Fo'+str(obj),'/Fd'+str(OUT/'diagnostic.pdb'),str(output)]+ with (LOG/(obj.stem+'-compile.log')).open('w',encoding='utf-8') as stream:+ r=subprocess.run(command,cwd=BUILD,env=env,stdout=stream,stderr=subprocess.STDOUT,timeout=300)+ print(obj.stem,'compile',r.returncode,flush=True)+ if r.returncode:raise SystemExit(r.returncode)+ build_commands.append(command);objects.append(obj);changes[str(output)]=sha(output)++ninja=(BUILD/'build.ninja').read_text(encoding='utf-8')+match=re.search(r'^build veyra_qml_ui.exe: .*?(?=\n\n)',ninja,re.M|re.S);assert match+lines=match.group().splitlines()+def unescape(s):return s.replace('$ ',' ').replace('$:',':').replace('$$','$')+original_objects=[BUILD/unescape(x) for x in lines[0].split('Release ',1)[1].split(' | ',1)[0].split(' ')]+v=dict(re.match(r' ([A-Z_]+) = (.*)',x).groups() for x in lines[1:] if re.match(r' ([A-Z_]+) = (.*)',x))+libraries=args(unescape(v['LINK_LIBRARIES']))+for item in list(map(str,original_objects))+libraries+['veyra_qml_ui.exe','veyra-qml.manifest']:+ p=Path(item);p=p if p.is_absolute() else BUILD/p+ if p.is_file():inputs[str(p)]=sha(p)+rsp=OUT/'diagnostic-link.rsp'+rsp.write_text('\n'.join(subprocess.list2cmdline([str(p)]) for p in objects+original_objects)+'\n'+unescape(v.get('LINK_PATH',''))+'\n'+unescape(v['LINK_LIBRARIES']),encoding='utf-8')+exe=OUT/'veyra-vram-diagnostic.exe'+link=r'C:\PROGRA~2\MICROS~3\2022\BUILDT~1\VC\Tools\MSVC\1444~1.352\bin\Hostx64\x64\link.exe'+cmake=r'C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe'+flags=[('/MANIFESTINPUT:'+str(BUILD/'veyra-qml.manifest')) if x.startswith('/MANIFESTINPUT:') else x for x in args(unescape(v['LINK_FLAGS']))]+(OUT/'manifest').mkdir(exist_ok=True)+command=[cmake,'-E','vs_link_exe','--msvc-ver=1944','--intdir='+str(OUT/'manifest'),+ r'--rc=C:\PROGRA~2\WI3CF2~1\10\bin\100261~1.0\x64\rc.exe',r'--mt=C:\PROGRA~2\WI3CF2~1\10\bin\100261~1.0\x64\mt.exe','--manifests','--',link,'/nologo','@'+str(rsp),+ '/out:'+str(exe),'/implib:'+str(OUT/'diagnostic.lib'),'/pdb:'+str(OUT/'diagnostic-link.pdb'),'/version:0.0']+flags+with (LOG/'link.log').open('w',encoding='utf-8') as stream:+ r=subprocess.run(command,cwd=BUILD,env=env,stdout=stream,stderr=subprocess.STDOUT,timeout=300)+print('GUI link',r.returncode,flush=True);build_commands.append(command)+for name,digest in inputs.items():assert sha(Path(name))==digest,name+receipt={'exit':r.returncode,'baseProduct':'71723e0249a17764696796fd204a6eb69d6da276','inputsUnchanged':inputs,'generatedSources':changes,'commands':build_commands}+if exe.exists():receipt.update(exeSha256=sha(exe),exeBytes=exe.stat().st_size)+(LOG/'receipt.json').write_text(json.dumps(receipt,ensure_ascii=False,indent=2),encoding='utf-8')+raise SystemExit(r.returncode)