okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-028-monitor: the Monitor keeps the app's own GPU readings where the engine has none (AMD on Windows), reads Windows AMD temperature, and drops non-GPU display chips on Linux (#3727)1bf946eaf

main
7.3 KiB104 linesraw
1/**
2 * Windows graphics cards that nvidia-smi does not cover (AMD, Intel): their size and their load.
3 *  - size: the DirectX adapter list in the registry (HKLM\SOFTWARE\Microsoft\DirectX) has a 64-bit DedicatedVideoMemory and the adapter
4 *    LUID. Win32_VideoController.AdapterRAM is 32 bits and reads 0 or 4 GB for a 16 GB card (#3727, #3836).
5 *  - load and memory in use: the Windows GPU performance counters (the ones Task Manager shows), read by one long-lived PowerShell and
6 *    matched to the card by LUID.
7 *  - temperature: the display driver's own D3DKMT adapter performance data (gdi32.dll, no vendor library, no administrator), asked for the
8 *    same LUID. An AMD 7900 XTX gave the same value as ADLX at idle and under load (noctrex, #3727); the card answers in tenths of a degree.
9 *    A driver that does not answer leaves the temperature "not available". Power, fan and the PCIe link stay "not available": D3DKMT gave
10 *    0 for power and for the PCIe rate on that card.
11 */
12import { createPowerShellLoop, endWithHost } from './windows-poll.mjs';
13import { utf8Script } from './powershell-utf8.mjs';
14
15export const DX_ADAPTERS_SCRIPT = utf8Script(
16  "Get-ChildItem HKLM:\\SOFTWARE\\Microsoft\\DirectX | ForEach-Object { $p = Get-ItemProperty $_.PSPath; " +
17  "if ($p.Description -and $null -ne $p.AdapterLuid) { [pscustomobject]@{ Description = [string]$p.Description; VendorId = [string]$p.VendorId; " +
18  "Luid = [string]$p.AdapterLuid; Dedicated = [string]$p.DedicatedVideoMemory; Software = [string]$p.SoftwareAdapter } } } | ConvertTo-Json -Compress");
19
20/** luid_0x<high>_0x<low> in the spelling of the performance counters, from the registry's 64-bit number. */
21export function luidName(value) {
22  try {
23    const n = BigInt.asUintN(64, BigInt(String(value)));
24    const hex = v => '0x' + v.toString(16).padStart(8, '0');
25    return `luid_${hex(n >> 32n)}_${hex(n & 0xffffffffn)}`;
26  } catch { return null; }
27}
28
29/** The adapters the DirectX registry lists: [{ description, vendorId, luid, bytes, software }]. Never throws. */
30export function parseDxAdapters(raw) {
31  try {
32    const parsed = JSON.parse(raw), rows = Array.isArray(parsed) ? parsed : [parsed];
33    return rows.filter(r => r?.Description).map(r => ({
34      description: String(r.Description), vendorId: Number(r.VendorId) || 0, luid: luidName(r.Luid),
35      bytes: Number(r.Dedicated) || 0, software: String(r.Software) === '1' || String(r.Software).toLowerCase() === 'true',
36    }));
37  } catch { return []; }
38}
39
40const norm = text => String(text ?? '').toLowerCase().replace(/[^a-z0-9]/g, '');
41const VIRTUAL = /virtual|remote|indirect|mirror|basic render|meta |parsec|displaylink|idd/i;
42
43/**
44 * Win32_VideoController rows + the DirectX adapter list -> the cards this app can show. A card keeps the size from the registry;
45 * a display driver for a virtual monitor (no size, no known maker) is not a graphics card and is dropped.
46 */
47export function windowsOtherGpus(videoRows, dx) {
48  const used = new Set();
49  const out = [];
50  for (const row of videoRows) {
51    if (!row?.Name) continue;
52    const match = dx.find((a, i) => !used.has(i) && !a.software && norm(a.description) === norm(row.Name));
53    if (match) used.add(dx.indexOf(match));
54    const vendor = /amd|radeon/i.test(row.Name) ? 'amd' : /intel/i.test(row.Name) ? 'intel' : 'unknown';
55    const vramGb = match?.bytes ? Math.round(match.bytes / 1024 ** 3 * 10) / 10 : 0;
56    if (vendor === 'unknown' && (!vramGb || VIRTUAL.test(row.Name))) continue;
57    out.push({ id: String(row.PNPDeviceID), vendor, name: row.Name, vramGb, luid: match?.luid ?? null });
58  }
59  return out;
60}
61
62/** The temperature D3DKMT reports in tenths of a degree -> whole degrees, or null when the driver gave nothing believable. */
63export function d3dkmtTemperatureC(deci) {
64  const c = Number(deci) / 10;
65  return Number.isFinite(c) && c > 0 && c <= 150 ? Math.round(c) : null;
66}
67
68/** One counter line: "G <luid> <load percent> <dedicated bytes in use> [<temperature in tenths of a degree>]". */
69export function parseGpuCounterLine(line) {
70  const m = /^G\s+(luid_0x[0-9a-f]+_0x[0-9a-f]+)\s+(\d+(?:\.\d+)?)\s+(\d+)(?:\s+(-?\d+))?\s*$/i.exec(String(line));
71  return m ? { luid: m[1].toLowerCase(), utilizationPct: Math.max(0, Math.min(100, Number(m[2]))), memoryUsedGb: Number(m[3]) / 1024 ** 3, temperatureC: d3dkmtTemperatureC(m[4]) } : null;
72}
73
74/** The C# that asks D3DKMT (KMTQAITYPE_ADAPTERPERFDATA = 62, 64-byte D3DKMT_ADAPTER_PERFDATA, Temperature at byte 56) for one LUID; -1 = no answer. */
75export const GPU_TEMP_CSHARP = 'using System;using System.Runtime.InteropServices;public static class StrataGpuTemp{[StructLayout(LayoutKind.Sequential)]struct Q{public uint L;public int H;public uint A;}[StructLayout(LayoutKind.Sequential)]struct Info{public uint A;public int T;public IntPtr P;public uint S;}[DllImport("gdi32.dll")]static extern int D3DKMTOpenAdapterFromLuid(ref Q q);[DllImport("gdi32.dll")]static extern int D3DKMTCloseAdapter(ref uint a);[DllImport("gdi32.dll")]static extern int D3DKMTQueryAdapterInfo(ref Info i);public static int Read(int high,uint low){Q q=new Q();q.L=low;q.H=high;if(D3DKMTOpenAdapterFromLuid(ref q)!=0)return -1;IntPtr buf=Marshal.AllocHGlobal(64);try{for(int k=0;k<64;k++)Marshal.WriteByte(buf,k,0);Info i=new Info();i.A=q.A;i.T=62;i.P=buf;i.S=64;if(D3DKMTQueryAdapterInfo(ref i)!=0)return -1;return Marshal.ReadInt32(buf,56);}finally{Marshal.FreeHGlobal(buf);uint a=q.A;D3DKMTCloseAdapter(ref a);}}}';
76
77export function createWindowsGpuReader({ spawnFn, intervalSec = 4, maxStarts = 3, now = Date.now } = {}) {
78  const readings = new Map();
79  const script = utf8Script(
80    `$t=$false;try{Add-Type -TypeDefinition '${GPU_TEMP_CSHARP}';$t=$true}catch{};` +
81    `while($true){` +
82    `$e=@(Get-CimInstance Win32_PerfFormattedData_GPUPerformanceCounters_GPUEngine);$m=@(Get-CimInstance Win32_PerfFormattedData_GPUPerformanceCounters_GPUAdapterMemory);` +
83    `$u=@{};foreach($r in $e){if($r.Name -match '(luid_0x[0-9A-Fa-f]+_0x[0-9A-Fa-f]+)_phys_\\d+_eng_\\d+_engtype_(\\w+)'){$k=$matches[1].ToLower()+'|'+$matches[2];$u[$k]=[double]$u[$k]+[double]$r.UtilizationPercentage}};` +
84    `$b=@{};foreach($k in $u.Keys){$l=$k.Split('|')[0];if(-not $b.ContainsKey($l) -or $u[$k] -gt $b[$l]){$b[$l]=$u[$k]}};` +
85    `foreach($r in $m){if($r.Name -match '(luid_0x[0-9A-Fa-f]+_0x[0-9A-Fa-f]+)'){$l=$matches[1].ToLower();$d=-1;if($t){try{$p=$l.Split('_');$d=[StrataGpuTemp]::Read([Convert]::ToInt32($p[1].Substring(2),16),[Convert]::ToUInt32($p[2].Substring(2),16))}catch{}};[Console]::Out.WriteLine('G '+$l+' '+[math]::Round([double]$b[$l],0)+' '+$r.DedicatedUsage+' '+$d)}};` +
86    `[Console]::Out.Flush();Start-Sleep -Seconds ${intervalSec}}`);
87  const loop = createPowerShellLoop({ script, spawnFn, maxStarts, onLine: line => {
88    const parsed = parseGpuCounterLine(line);
89    if (parsed) readings.set(parsed.luid, { ...parsed, at: now() });
90    return !!parsed;
91  } });
92  return {
93    read(luid) { loop.start(); const r = readings.get(String(luid ?? '').toLowerCase()); return r && now() - r.at < 6 * intervalSec * 1000 ? r : null; },
94    stop() { loop.stop(); },
95  };
96}
97
98let shared = null;
99/** The card's load and memory in use from the Windows counters; null when there is no reading. */
100export function windowsGpuReading(luid) {
101  if (process.platform !== 'win32' || !luid) return null;
102  shared ??= endWithHost(createWindowsGpuReader());
103  return shared.read(luid);
104}