Data/RefreshGpuReference.ps1

#requires -Version 5.1

param(
    [Parameter(Mandatory)][object[]]$BundledRows,
    [Parameter(Mandatory)][type]$FlagType
)

$ErrorActionPreference = 'Stop'
$covered = @{}
foreach ($row in $BundledRows) {
    foreach ($id in $row.DeviceID -split ' ') {
        $covered["$($row.Vendor)/$id"] = $true
    }
}

function Read-VendorText([string]$Uri) {
    $response = Invoke-WebRequest -Uri $Uri -UseBasicParsing -TimeoutSec 25 -ErrorAction Stop
    $response.RawContentStream.Position = 0
    $reader = [IO.StreamReader]::new($response.RawContentStream, [Text.Encoding]::UTF8, $true)
    try { $reader.ReadToEnd() }
    finally { $reader.Dispose() }
}

function Read-GpuHtmlCells([string]$Html, [string]$Tag) {
    foreach ($cell in [regex]::Matches($Html, "(?is)<$Tag\b[^>]*>(.*?)</$Tag\s*>")) {
        $text = [Net.WebUtility]::HtmlDecode(($cell.Groups[1].Value -replace '<[^>]*>', ' '))
        ($text -replace '\s+', ' ').Trim()
    }
}

function Get-NvidiaNameKey([string]$Name) {
    return ($Name -replace '^(?:NVIDIA\s+)?(?:GeForce\s+)?' -replace '\s+GPU$' -replace '[^0-9a-zA-Z]').ToLowerInvariant()
}

function Get-CodecFlag([string]$Name) {
    return [int][enum]::Parse($FlagType, $Name)
}

function Add-NvidiaProfile([hashtable]$Index, [string[]]$Row, [int]$Mask) {
    $key = Get-NvidiaNameKey $Row[0]
    if (!$key -or !$Row[1]) { return }
    if (!$Index.ContainsKey($key)) {
        $Index[$key] = @{ Family = $Row[1]; Mask = $Mask }
        return
    }
    $profile = $Index[$key]
    $profile.Mask = $profile.Mask -band $Mask
    if ($profile.Family -ne $Row[1]) { $profile.Family = '' }
}

function Get-NvidiaRows {
    Write-Verbose 'Reading the live NVIDIA Video Codec matrix and driver PCI list.'
    $matrix = Read-VendorText 'https://developer.nvidia.com/video-encode-decode-support-matrix'
    $encode = @{}
    $decode = @{}
    $encodeHeaders = @(
        'H.264 (AVC) YUV 4:2:0', 'H.264 (AVC) YUV 4:2:2', 'H.264 (AVC) YUV 4:4:4', 'H.264 (AVC) Lossless',
        'H.265 (HEVC) 4K YUV 4:2:0', 'H.265 (HEVC) YUV 4:2:2', 'H.265 (HEVC) 4K YUV 4:4:4',
        'H.265 (HEVC) 4K Lossless', 'H.265 (HEVC) 8K', 'HEVC 10-bit support', 'HEVC B Frame support', 'AV1 YUV 4:2:0'
    )
    $decodeHeaders = @(
        'MPEG-1', 'MPEG-2', 'MPEG-4', 'VC-1', 'VP8', 'VP9 4:2:0 8 Bit 10 Bit 12 Bit',
        'H.264 (AVC) 4:2:0 8 Bit 10 Bit', 'H.264 (AVC) 4:2:2 8 Bit 10 Bit',
        'H.265 (HEVC) 4:2:0 8 Bit 10 Bit 12 Bit', 'H.265 (HEVC) 4:2:2 8 Bit 10 Bit 12 Bit',
        'H.265 (HEVC) 4:4:4 8 Bit 10 Bit 12 Bit', 'AV1 8 Bit 10 Bit'
    )
    $encodeFlags = @{ 7='h264_AVC_HD'; 11='h265_HEVC_420_8bit'; 12='h265_HEVC_422_8bit'; 13='h265_HEVC_444_8bit' }
    $decodeFlags = @{
        6='MPEG1'; 7='MPEG2'; 9='VC1'; 10='VP8'; 11='VP9_8bit'; 12='VP9_10bit'; 13='VP9_12bit'
        14='h264_AVC_HD'; 15='h264_AVC_10bit'; 18='h265_HEVC_420_8bit'; 19='h265_HEVC_420_10bit'
        20='h265_HEVC_420_12bit'; 21='h265_HEVC_422_8bit'; 22='h265_HEVC_422_10bit'; 23='h265_HEVC_422_12bit'
        24='h265_HEVC_444_8bit'; 25='h265_HEVC_444_10bit'; 26='h265_HEVC_444_12bit'; 27='AV1_8bit'; 28='AV1_10bit'
    }

    foreach ($table in [regex]::Matches($matrix, '(?is)<table\b[^>]*>(.*?)</table\s*>')) {
        $html = $table.Groups[1].Value
        $header = @(Read-GpuHtmlCells $html 'th')
        if ($header[0] -ne 'BOARD' -or $header[1] -ne 'FAMILY') { continue }
        $isEncode = $header.Count -eq 19 -and $header[2] -eq 'NVENC Generation' -and
            ($header[7..18] -join '|') -eq ($encodeHeaders -join '|')
        $isDecode = $header.Count -eq 18 -and $header[2] -eq 'NVDEC Generation' -and
            ($header[6..17] -join '|') -eq ($decodeHeaders -join '|')
        if (!$isEncode -and !$isDecode) { continue }
        $flags = if ($isEncode) { $encodeFlags } else { $decodeFlags }
        $expected = if ($isEncode) { 19 } else { 29 }
        $first = if ($isEncode) { 7 } else { 6 }
        $index = if ($isEncode) { $encode } else { $decode }
        foreach ($match in [regex]::Matches($html, '(?is)<tr\b[^>]*>(.*?)</tr\s*>')) {
            $row = @(Read-GpuHtmlCells $match.Groups[1].Value 'td')
            if ($row.Count -ne $expected -or ($row[$first..($expected - 1)] -notmatch '^(?:YES|NO)$')) { continue }
            $mask = 0
            foreach ($column in $flags.Keys) {
                if ($row[$column] -eq 'YES') { $mask = $mask -bor (Get-CodecFlag $flags[$column]) }
            }
            if ($isEncode) {
                if ($row[16] -eq 'YES' -and $row[11] -eq 'YES') { $mask = $mask -bor (Get-CodecFlag 'h265_HEVC_420_10bit') }
                if ($row[18] -eq 'YES') { $mask = $mask -bor (Get-CodecFlag 'AV1_8bit') -bor (Get-CodecFlag 'AV1_10bit') }
                # The SDK lists these additional profiles for ninth-generation Blackwell NVENC.
                if ($row[1] -eq 'Blackwell' -and $row[2] -eq '9th Gen') {
                    if ($row[7] -eq 'YES') { $mask = $mask -bor (Get-CodecFlag 'h264_AVC_10bit') }
                    if ($row[12] -eq 'YES' -and $row[16] -eq 'YES') { $mask = $mask -bor (Get-CodecFlag 'h265_HEVC_422_10bit') }
                    if ($row[13] -eq 'YES' -and $row[16] -eq 'YES') { $mask = $mask -bor (Get-CodecFlag 'h265_HEVC_444_10bit') }
                }
            }
            Add-NvidiaProfile $index $row $mask
        }
    }
    if ($encode.Count -lt 10 -or $decode.Count -lt 10) { throw 'The NVIDIA codec matrices have an unexpected layout.' }

    $driverRoot = 'https://download.nvidia.com/XFree86/Linux-x86_64'
    $latest = Read-VendorText "$driverRoot/latest.txt"
    $driver = [regex]::Match($latest, '^\s*(\d+\.\d+(?:\.\d+)?)(?=\s|$)')
    if (!$driver.Success) { throw 'The NVIDIA driver version could not be identified.' }
    $version = $driver.Groups[1].Value
    $identities = Read-VendorText "$driverRoot/$version/README/supportedchips.html"
    $listed = $false
    foreach ($line in [regex]::Matches($identities, '(?is)<tr\b[^>]*\bid="devid[^"]*"[^>]*>(.*?)</tr\s*>')) {
        $row = @(Read-GpuHtmlCells $line.Groups[1].Value 'td')
        if ($row.Count -lt 2 -or $row[1] -notmatch '^([a-f0-9]{4})(?: [a-f0-9]{4} [a-f0-9]{4})?$') { continue }
        $deviceId = $Matches[1].ToLowerInvariant()
        $listed = $true
        if ($row[1].Length -ne 4) { continue }
        if ($covered.ContainsKey("NVidia/$deviceId")) { continue }
        $key = Get-NvidiaNameKey $row[0]
        $enc = $encode[$key]
        $dec = $decode[$key]
        if (!$enc -or !$dec -or !$enc.Family -or $enc.Family -ne $dec.Family) { continue }
        [pscustomobject]@{
            Vendor = 'NVidia'; Name = $row[0]; Family = $enc.Family
            DeviceID = $deviceId; SubsystemID = ''; HWEncoding = $enc.Mask; HWDecoding = $dec.Mask
            CapabilitySource = "NVIDIA live PCI reference ($version)"
        }
    }
    if (!$listed) { throw 'The NVIDIA driver PCI list has an unexpected layout.' }
}

function Get-IntelRows {
    Write-Verbose 'Reading the live Intel media-driver matrix and kernel PCI table.'
    $matrix = Read-VendorText 'https://raw.githubusercontent.com/intel/media-driver/master/README.md'
    $header = Read-VendorText 'https://raw.githubusercontent.com/torvalds/linux/master/include/drm/intel/pciids.h'
    $section = [regex]::Match($matrix, '(?ms)^### Decoding/Encoding Features[ \t]*\r?\n(.*?)(?=^### |\z)')
    $lines = @($section.Groups[1].Value -split '\r?\n' | Where-Object { $_ -match '^\|' })
    if (!$lines.Count -or $lines[0] -notmatch '^\|\s*CODEC\s*\|\s*Build Types\s*\|') { throw 'The Intel media-driver matrix has an unexpected layout.' }
    $columns = @(($lines[0].Trim().Trim('|') -split '\|') | ForEach-Object { $_.Trim() })
    $codecs = @{
        AVC='h264_AVC_HD'; 'MPEG-2'='MPEG2'; 'VC-1'='VC1'; VP8='VP8'
        'HEVC 8bit'='h265_HEVC_420_8bit'; 'HEVC 10bit'='h265_HEVC_420_10bit'; 'HEVC 12bit'='h265_HEVC_420_12bit'
        'HEVC 8bit 422'='h265_HEVC_422_8bit'; 'HEVC 10bit 422'='h265_HEVC_422_10bit'; 'HEVC 12bit 422'='h265_HEVC_422_12bit'
        'HEVC 8bit 444'='h265_HEVC_444_8bit'; 'HEVC 10bit 444'='h265_HEVC_444_10bit'; 'HEVC 12bit 444'='h265_HEVC_444_12bit'
        'VP9 8bit'='VP9_8bit'; 'VP9 10bit'='VP9_10bit'; 'VP9 12bit'='VP9_12bit'
        'AV1 8bit'='AV1_8bit'; 'AV1 10bit'='AV1_10bit'; 'VVC 8bit'='VVC_8bit'; 'VVC 10bit'='VVC_10bit'
    }
    $families = @{ BMG='Battlemage'; PTL='Panther Lake'; LNL='Lunar Lake'; CRI='Crescent Island'; NVL='Nova Lake' }
    $groups = @{ BMG=@('BMG','BMG_G21'); NVL=@('NVLS','NVLP','NVL') }
    $foundPlatform = $false
    for ($i = 2; $i -lt $columns.Count; $i++) {
        $platform = $columns[$i]
        if ($platform -cnotmatch '^[A-Z0-9]{2,8}$') { continue }
        $family = if ($families[$platform]) { $families[$platform] } else { $platform }
        $tokens = if ($groups.ContainsKey($platform)) { $groups[$platform] } else { @($platform) }
        $ids = @(foreach ($token in $tokens) {
            $pattern = '(?ms)^#define\s+INTEL_{0}_IDS\(MACRO__,[^\r\n]+(?<Body>.*?)(?=^\s*$|^#define|\z)' -f $token
            $macro = [regex]::Match($header, $pattern)
            foreach ($match in [regex]::Matches($macro.Groups['Body'].Value, '(?i)\bMACRO__\(0x([a-f0-9]{4}),')) {
                $match.Groups[1].Value.ToLowerInvariant()
            }
        })
        if (!$ids.Count) { continue }
        $enc = $dec = 0
        foreach ($line in $lines) {
            $cells = $line.Trim().Trim('|') -split '\|'
            $codec = $cells[0].Trim()
            if (!$codecs.ContainsKey($codec) -or $cells.Count -ne $columns.Count) { continue }
            $mode = [regex]::Match($cells[$i], '<u>([^<]+)</u>')
            if (!$mode.Success) { continue }
            $flag = Get-CodecFlag $codecs[$codec]
            $operations = $mode.Groups[1].Value -split '/'
            if ('E' -in $operations) { $enc = $enc -bor $flag }
            if ('D' -in $operations) { $dec = $dec -bor $flag }
        }
        if ($dec -eq 0) { continue }
        $foundPlatform = $true
        $newIds = @($ids | Sort-Object -Unique | Where-Object { !$covered.ContainsKey("Intel/$_") })
        if ($newIds.Count) {
            [pscustomobject]@{
                Vendor = 'Intel'; Name = "Intel $family"; Family = $family
                DeviceID = $newIds -join ' '; SubsystemID = ''; HWEncoding = $enc; HWDecoding = $dec
                CapabilitySource = 'Intel live media-driver PCI reference'
            }
        }
    }
    if (!$foundPlatform) { throw 'The Intel media matrix did not match the Intel PCI groups.' }
}

function Get-AmdRows {
    Write-Verbose 'Reading the live AMD AMF hardware matrix and GPUOpen Device Info table.'
    $matrix = Read-VendorText 'https://github.com/GPUOpen-LibrariesAndSDKs/AMF/wiki/GPU-and-APU-HW-Features-and-Support'
    $deviceInfo = Read-VendorText 'https://raw.githubusercontent.com/GPUOpen-Tools/device_info/master/device_info.cpp'
    $profiles = @{}
    $chips = @{}
    $codecHeadings = '|AVC|HEVC|VP9|AV1|AVC|HEVC|AV1'
    $codecs = @('h264', 'hevc', 'vp9', 'av1', 'h264', 'hevc', 'av1')
    $flags = @{
        h264 = @{ '8'='h264_AVC_HD'; '10'='h264_AVC_10bit' }
        hevc = @{ '8'='h265_HEVC_420_8bit'; '10'='h265_HEVC_420_10bit'; '12'='h265_HEVC_420_12bit' }
        vp9 = @{ '8'='VP9_8bit'; '10'='VP9_10bit'; '12'='VP9_12bit' }
        av1 = @{ '8'='AV1_8bit'; '10'='AV1_10bit' }
    }

    if ($matrix -notmatch 'All codecs are 4:2:0') { throw 'The AMD AMF chroma format is unclear.' }
    foreach ($table in [regex]::Matches($matrix, '(?is)<table\b[^>]*>(.*?)</table\s*>')) {
        $html = $table.Groups[1].Value
        $headings = @(Read-GpuHtmlCells $html 'th') -join '|'
        $isChipTable = $headings -eq 'Name|Code name|VCN version|Number of VCNs|Comments'
        $isCodecTable = $headings -eq 'VCN|Decode||||Encode||'
        if (!$isChipTable -and !$isCodecTable) { continue }
        $checkedCodecHeadings = $false
        foreach ($match in [regex]::Matches($html, '(?is)<tr\b[^>]*>(.*?)</tr\s*>')) {
            $row = @(Read-GpuHtmlCells $match.Groups[1].Value 'td')
            if ($isChipTable -and $row.Count -eq 5 -and $row[1] -and $row[2] -match '^VCN (\d+\.\d+)$') {
                $version = $Matches[1]
                $chip = $row[1] -replace '\s+', ''
                $decodeOnly = $row[4] -match 'decode only'
                if (!$chips.ContainsKey($chip)) {
                    $chips[$chip] = @{ Version = $version; DecodeOnly = $decodeOnly }
                }
                elseif ($chips[$chip].Version -eq $version) {
                    $chips[$chip].DecodeOnly = $chips[$chip].DecodeOnly -or $decodeOnly
                }
                else {
                    $chips[$chip].Version = ''
                }
            }
            elseif ($isCodecTable -and $row.Count -eq 8) {
                if (!$checkedCodecHeadings) {
                    if (($row -join '|') -ne $codecHeadings) { throw 'The AMD AMF codec columns have changed.' }
                    $checkedCodecHeadings = $true
                    continue
                }
                if ($row[0] -notmatch '^\d+\.\d+(?:,\s*\d+\.\d+)*$') { continue }
                $enc = $dec = 0
                for ($column = 1; $column -lt $row.Count; $column++) {
                    if ($row[$column] -eq 'N/A') { continue }
                    if ($row[$column] -notmatch '^(\d+(?:,\s*\d+)*)b\s*:') {
                        throw "An AMD AMF bit-depth entry has an unexpected format: $($row[$column])."
                    }
                    $codecFlags = $flags[$codecs[$column - 1]]
                    foreach ($depth in ($Matches[1] -split ',\s*')) {
                        if (!$codecFlags.ContainsKey($depth)) { continue }
                        $flag = Get-CodecFlag $codecFlags[$depth]
                        if ($column -lt 5) { $dec = $dec -bor $flag }
                        else { $enc = $enc -bor $flag }
                    }
                }
                foreach ($version in ($row[0] -split ',\s*')) {
                    $profiles[$version] = @{ Encode = $enc; Decode = $dec }
                }
            }
        }
    }
    if (!$chips.Count -or !$profiles.Count) { throw 'The AMD AMF tables have an unexpected layout.' }

    # Device Info identifies discrete chips by GFX target. APUs with shared targets need an exact PCI mapping.
    $discrete = @{
        gfx1010='Navi10'; gfx1011='Navi12'; gfx1012='Navi14'; gfx1030='Navi21'; gfx1031='Navi22'
        gfx1032='Navi23'; gfx1034='Navi24'; gfx1100='Navi31'; gfx1101='Navi32'; gfx1102='Navi33'
        gfx1200='Navi44'; gfx1201='Navi48'
    }
    $integrated = @{
        '1638/gfx90c'='Cezanne'; '1681/gfx1035'='Rembrandt'
        '164e/gfx1036'='Raphael'; '15bf/gfx1103'='Phoenix'
    }
    $pattern = '(?mi)^\s*\{kGfx\w+,\s*0x(?<Id>[a-f0-9]{4}),\s*0x[a-f0-9]{2},\s*kGfx\w+,\s*(?<Apu>true|false),\s*"(?<Target>gfx[a-f0-9]+)",\s*"(?<Name>[^"]+)"\s*\}'
    $devices = foreach ($match in [regex]::Matches($deviceInfo, $pattern)) {
        $id = $match.Groups['Id'].Value.ToLowerInvariant()
        $target = $match.Groups['Target'].Value
        $chip = if ($match.Groups['Apu'].Value -eq 'true') { $integrated["$id/$target"] }
            else { $discrete[$target] }
        [pscustomobject]@{ Id = $id; Chip = $chip; Name = $match.Groups['Name'].Value }
    }
    $matchedProfile = $false
    foreach ($device in ($devices | Group-Object Id)) {
        # Each PCI ID can have several hardware revisions and product names. Require agreement on the chip.
        if ($device.Group | Where-Object { !$_.Chip }) { continue }
        $families = @($device.Group.Chip | Select-Object -Unique)
        if ($families.Count -ne 1 -or !$families[0]) { continue }
        $family = $families[0]
        $chip = $chips[$family]
        if (!$chip -or !$chip.Version -or !$profiles.ContainsKey($chip.Version)) { continue }
        $profile = $profiles[$chip.Version]
        if (!$profile.Decode) { continue }
        $matchedProfile = $true
        if ($covered.ContainsKey("AMD/$($device.Name)")) { continue }
        $names = @($device.Group.Name | Where-Object { $_ -match '^AMD ' } | Select-Object -Unique)
        $name = if ($names.Count -eq 1 -and $names[0] -notmatch '^AMD Radeon(?:\(TM\))? Graphics$') { $names[0] }
            else { "AMD Radeon ($family)" }
        [pscustomobject]@{
            Vendor = 'AMD'
            Name = $name
            Family = $family
            DeviceID = $device.Name
            SubsystemID = ''
            HWEncoding = if ($chip.DecodeOnly) { 0 } else { $profile.Encode }
            HWDecoding = $profile.Decode
            CapabilitySource = "AMD live AMF VCN $($chip.Version) PCI reference"
        }
    }
    if (!$matchedProfile) { throw 'The AMD Device Info entries did not match usable AMF profiles.' }
}


Get-NvidiaRows
Get-IntelRows
Get-AmdRows