348 lines
10 KiB
TypeScript
348 lines
10 KiB
TypeScript
import type { GpuRenderMode } from './config'
|
|
|
|
export const VRAM_LOW_THRESHOLD_MIB = 2048
|
|
export const VRAM_RECOVER_THRESHOLD_MIB = 3584
|
|
export const VRAM_MONITOR_INTERVAL_MS = 5_000
|
|
export const VRAM_SWITCH_CONSECUTIVE_REQUIRED = 2
|
|
export const LOW_FPS_THRESHOLD = 20
|
|
export const LOW_FPS_SUSTAINED_MS = 5_000
|
|
export const FPS_STARTUP_WARMUP_MS = 6_000
|
|
export const FPS_REPORT_COOLDOWN_MS = 15_000
|
|
export const AUTO_SWITCH_COOLDOWN_MS = 45_000
|
|
|
|
export interface ChromiumSwitch {
|
|
name: string
|
|
value?: string
|
|
}
|
|
|
|
export type ResolvedGpuTarget = 'default' | 'high-performance' | 'low-power' | 'software'
|
|
|
|
export interface DiscreteVramSample {
|
|
gpuName: string
|
|
usedMiB: number
|
|
freeMiB: number
|
|
totalMiB: number
|
|
}
|
|
|
|
export type StartupGpuDecisionReason =
|
|
| 'headless-smoke'
|
|
| 'gpu-handoff'
|
|
| 'user-software'
|
|
| 'user-low-power'
|
|
| 'user-high-performance'
|
|
| 'low-vram-igpu'
|
|
| 'low-vram-software'
|
|
| 'normal-gpu'
|
|
|
|
export interface StartupGpuDecision {
|
|
target: ResolvedGpuTarget
|
|
requestedMode: GpuRenderMode
|
|
reason: StartupGpuDecisionReason
|
|
vramSample: DiscreteVramSample | null
|
|
hasIntegratedGpu: boolean
|
|
}
|
|
|
|
export interface VramMonitorAction {
|
|
kind: 'switch-to-discrete' | 'switch-to-low-power' | 'switch-to-software'
|
|
sample: DiscreteVramSample
|
|
}
|
|
|
|
export interface GpuPolicyInput {
|
|
platform: NodeJS.Platform
|
|
headlessSmoke: boolean
|
|
softwareGl?: boolean
|
|
target?: ResolvedGpuTarget
|
|
}
|
|
|
|
const VIRTUAL_DISPLAY_ADAPTER_RE = /microsoft basic|remote display|parsec|virtual|indirect|mirage/i
|
|
const INTEL_ADAPTER_RE = /\bintel\b/i
|
|
const INTEL_DISCRETE_ARC_RE = /\barc\b.*\b[ab]\d{3}\b/i
|
|
const AMD_INTEGRATED_RE = /\bamd\s+radeon(?:\(tm\))?\s+(?:graphics|\d+m\b|vega\s+\d+\s+graphics)/i
|
|
|
|
function parseMiBField(raw: string | undefined): number | null {
|
|
if (!raw) return null
|
|
const trimmed = raw.trim()
|
|
if (!trimmed || /n\/a/i.test(trimmed)) return null
|
|
const cleaned = trimmed.replace(/\s*mib$/i, '')
|
|
if (!/^\d+(?:\.\d+)?$/.test(cleaned)) return null
|
|
const num = Number(cleaned)
|
|
return Number.isFinite(num) ? num : null
|
|
}
|
|
|
|
export function parseNvidiaSmiCsv(stdout: string): DiscreteVramSample | null {
|
|
if (!stdout) return null
|
|
for (const rawLine of stdout.split(/\r?\n/)) {
|
|
const line = rawLine.trim()
|
|
if (!line) continue
|
|
const parts = line.split(',')
|
|
if (parts.length < 4) continue
|
|
const gpuName = parts.slice(0, -3).join(',').trim()
|
|
const usedMiB = parseMiBField(parts[parts.length - 3])
|
|
const freeMiB = parseMiBField(parts[parts.length - 2])
|
|
const totalMiB = parseMiBField(parts[parts.length - 1])
|
|
if (
|
|
!gpuName ||
|
|
usedMiB === null ||
|
|
freeMiB === null ||
|
|
totalMiB === null ||
|
|
usedMiB < 0 ||
|
|
freeMiB < 0 ||
|
|
totalMiB <= 0
|
|
) {
|
|
continue
|
|
}
|
|
return { gpuName, usedMiB, freeMiB, totalMiB }
|
|
}
|
|
return null
|
|
}
|
|
|
|
export function detectIntegratedGpuFromRegistryOutput(stdout: string): boolean {
|
|
if (!stdout) return false
|
|
for (const rawLine of stdout.split(/\r?\n/)) {
|
|
const match = /^\s*DriverDesc\s+REG_SZ\s+(.+?)\s*$/i.exec(rawLine)
|
|
if (!match) continue
|
|
const desc = match[1].trim()
|
|
if (!desc || VIRTUAL_DISPLAY_ADAPTER_RE.test(desc)) continue
|
|
if (INTEL_ADAPTER_RE.test(desc) && !INTEL_DISCRETE_ARC_RE.test(desc)) {
|
|
return true
|
|
}
|
|
if (AMD_INTEGRATED_RE.test(desc)) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
export function chooseStartupGpuTarget(input: {
|
|
platform: NodeJS.Platform
|
|
headlessSmoke: boolean
|
|
requestedMode: GpuRenderMode
|
|
handoffTarget?: ResolvedGpuTarget
|
|
vramSample: DiscreteVramSample | null
|
|
hasIntegratedGpu: boolean
|
|
}): StartupGpuDecision {
|
|
const base = {
|
|
requestedMode: input.requestedMode,
|
|
vramSample: input.vramSample,
|
|
hasIntegratedGpu: input.hasIntegratedGpu,
|
|
}
|
|
|
|
if (input.headlessSmoke) {
|
|
return { ...base, target: 'software', reason: 'headless-smoke' }
|
|
}
|
|
if (input.requestedMode === 'software') {
|
|
return { ...base, target: 'software', reason: 'user-software' }
|
|
}
|
|
if (input.requestedMode === 'low-power') {
|
|
return { ...base, target: 'low-power', reason: 'user-low-power' }
|
|
}
|
|
if (input.requestedMode === 'high-performance') {
|
|
return { ...base, target: 'high-performance', reason: 'user-high-performance' }
|
|
}
|
|
if (input.handoffTarget) {
|
|
return { ...base, target: input.handoffTarget, reason: 'gpu-handoff' }
|
|
}
|
|
|
|
if (
|
|
input.platform === 'win32' &&
|
|
input.vramSample &&
|
|
input.vramSample.freeMiB < VRAM_LOW_THRESHOLD_MIB
|
|
) {
|
|
return input.hasIntegratedGpu
|
|
? { ...base, target: 'low-power', reason: 'low-vram-igpu' }
|
|
: { ...base, target: 'software', reason: 'low-vram-software' }
|
|
}
|
|
|
|
return { ...base, target: 'default', reason: 'normal-gpu' }
|
|
}
|
|
|
|
export function resolveChromiumGpuSwitches(input: GpuPolicyInput): ChromiumSwitch[] {
|
|
const effectiveTarget: ResolvedGpuTarget =
|
|
input.headlessSmoke || input.softwareGl || input.target === 'software'
|
|
? 'software'
|
|
: (input.target ?? 'default')
|
|
|
|
if (effectiveTarget === 'software') {
|
|
return [
|
|
{ name: 'disable-gpu' },
|
|
{ name: 'use-gl', value: 'angle' },
|
|
{ name: 'use-angle', value: 'swiftshader' },
|
|
{ name: 'enable-unsafe-swiftshader' },
|
|
]
|
|
}
|
|
|
|
// Avoid forcing enable-zero-copy / enable-gpu-rasterization:
|
|
// on Windows dual-GPU setups with high baseline VRAM usage they can provoke driver TDRs.
|
|
const switches: ChromiumSwitch[] = []
|
|
if (effectiveTarget === 'low-power') {
|
|
switches.push({ name: 'force_low_power_gpu' })
|
|
} else if (effectiveTarget === 'high-performance') {
|
|
switches.push({ name: 'force_high_performance_gpu' })
|
|
}
|
|
switches.push({ name: 'disable-renderer-backgrounding' })
|
|
if (input.platform === 'linux') {
|
|
switches.push({ name: 'ozone-platform-hint', value: 'auto' })
|
|
}
|
|
return switches
|
|
}
|
|
|
|
export function createVramHysteresisTracker(options: {
|
|
activeTarget: ResolvedGpuTarget
|
|
hasIntegratedGpu: boolean
|
|
lowThresholdMiB?: number
|
|
recoverThresholdMiB?: number
|
|
requiredConsecutive?: number
|
|
}) {
|
|
const lowThresholdMiB = options.lowThresholdMiB ?? VRAM_LOW_THRESHOLD_MIB
|
|
const recoverThresholdMiB = options.recoverThresholdMiB ?? VRAM_RECOVER_THRESHOLD_MIB
|
|
const requiredConsecutive = Math.max(1, options.requiredConsecutive ?? VRAM_SWITCH_CONSECUTIVE_REQUIRED)
|
|
let streak = 0
|
|
|
|
return {
|
|
observe(sample: DiscreteVramSample | null): VramMonitorAction | null {
|
|
if (!sample) {
|
|
streak = 0
|
|
return null
|
|
}
|
|
|
|
if (options.activeTarget === 'low-power' || options.activeTarget === 'software') {
|
|
if (sample.freeMiB >= recoverThresholdMiB) {
|
|
streak += 1
|
|
if (streak >= requiredConsecutive) {
|
|
return { kind: 'switch-to-discrete', sample }
|
|
}
|
|
} else {
|
|
streak = 0
|
|
}
|
|
return null
|
|
}
|
|
|
|
if (sample.freeMiB < lowThresholdMiB) {
|
|
streak += 1
|
|
if (streak >= requiredConsecutive) {
|
|
return {
|
|
kind: options.hasIntegratedGpu ? 'switch-to-low-power' : 'switch-to-software',
|
|
sample,
|
|
}
|
|
}
|
|
} else {
|
|
streak = 0
|
|
}
|
|
return null
|
|
},
|
|
reset(): void {
|
|
streak = 0
|
|
},
|
|
}
|
|
}
|
|
|
|
export function createSustainedLowFpsTracker(
|
|
options: {
|
|
thresholdFps?: number
|
|
sustainedMs?: number
|
|
sampleWindowMs?: number
|
|
reportCooldownMs?: number
|
|
} = {},
|
|
) {
|
|
const thresholdFps = options.thresholdFps ?? LOW_FPS_THRESHOLD
|
|
const sustainedMs = options.sustainedMs ?? LOW_FPS_SUSTAINED_MS
|
|
const sampleWindowMs = options.sampleWindowMs ?? 1000
|
|
const reportCooldownMs = options.reportCooldownMs ?? FPS_REPORT_COOLDOWN_MS
|
|
|
|
let bucketStartMs: number | null = null
|
|
let bucketFrames = 0
|
|
let lowDurationMs = 0
|
|
let lowFrames = 0
|
|
let lastReportedAt = -Infinity
|
|
|
|
return {
|
|
onFrame(nowMs: number): { avgFps: number; sustainedMs: number } | null {
|
|
if (!Number.isFinite(nowMs)) return null
|
|
if (bucketStartMs === null) {
|
|
bucketStartMs = nowMs
|
|
bucketFrames = 0
|
|
return null
|
|
}
|
|
bucketFrames += 1
|
|
const elapsedMs = nowMs - bucketStartMs
|
|
if (elapsedMs < sampleWindowMs) {
|
|
return null
|
|
}
|
|
|
|
const fps = (bucketFrames * 1000) / elapsedMs
|
|
bucketStartMs = nowMs
|
|
|
|
if (fps < thresholdFps) {
|
|
lowDurationMs += elapsedMs
|
|
lowFrames += bucketFrames
|
|
bucketFrames = 0
|
|
if (lowDurationMs >= sustainedMs && nowMs - lastReportedAt >= reportCooldownMs) {
|
|
const avgFps = Math.round(((lowFrames * 1000) / lowDurationMs) * 10) / 10
|
|
const reportedDuration = Math.round(lowDurationMs)
|
|
lastReportedAt = nowMs
|
|
lowDurationMs = 0
|
|
lowFrames = 0
|
|
return { avgFps, sustainedMs: reportedDuration }
|
|
}
|
|
return null
|
|
}
|
|
|
|
bucketFrames = 0
|
|
lowDurationMs = 0
|
|
lowFrames = 0
|
|
return null
|
|
},
|
|
reset(): void {
|
|
bucketStartMs = null
|
|
bucketFrames = 0
|
|
lowDurationMs = 0
|
|
lowFrames = 0
|
|
},
|
|
}
|
|
}
|
|
|
|
export function canAutoSwitchGpu(
|
|
lastSwitchAt: number | null | undefined,
|
|
nowMs: number,
|
|
cooldownMs = AUTO_SWITCH_COOLDOWN_MS,
|
|
): boolean {
|
|
return !lastSwitchAt || !Number.isFinite(lastSwitchAt) || nowMs - lastSwitchAt >= cooldownMs
|
|
}
|
|
|
|
export function stripGpuOverrideArgs(argv: string[]): string[] {
|
|
const stripped: string[] = []
|
|
for (let i = 0; i < argv.length; i += 1) {
|
|
const arg = argv[i]
|
|
if (
|
|
arg === '--software-gl' ||
|
|
arg === '--low-power-gpu' ||
|
|
arg === '--high-performance-gpu' ||
|
|
arg === '--gpu-handoff' ||
|
|
arg.startsWith('--gpu-mode=') ||
|
|
arg.startsWith('--gpu-handoff-target=')
|
|
) {
|
|
continue
|
|
}
|
|
if (arg === '--gpu-mode' || arg === '--gpu-handoff-target') {
|
|
i += 1
|
|
continue
|
|
}
|
|
stripped.push(arg)
|
|
}
|
|
return stripped
|
|
}
|
|
|
|
export function buildGpuHandoffArgs(argv: string[], target?: ResolvedGpuTarget): string[] {
|
|
return [
|
|
...stripGpuOverrideArgs(argv),
|
|
'--gpu-handoff',
|
|
...(target ? [`--gpu-handoff-target=${target}`] : []),
|
|
]
|
|
}
|
|
|
|
export function isGpuProcessCrash(
|
|
details: { type?: string; reason?: string } | null | undefined,
|
|
): boolean {
|
|
return Boolean(details && details.type === 'GPU' && details.reason !== 'clean-exit')
|
|
}
|