Read-FFmpegCapabilities.ps1

[CmdletBinding()]
param (
    [Parameter(Mandatory)][string]$Executable,
    [string]$Key,
    [string[]]$Vendors,
    [string]$CachePath,
    [string]$GPUControllerQuery,
    [string]$QuickSyncArguments,
    [int]$CudaIndex = -1,
    [int]$Direct3DIndex = -1
)

function Get-EncoderProbeRoute([string]$Encoder) {
    return @{
        Prefix = $(if ($Encoder -like '*_qsv') { $QuickSyncArguments })
        Suffix = $(if ($Encoder -like '*_nvenc' -and $CudaIndex -ge 0) { '-gpu ' + $CudaIndex })
    }
}

function Invoke-CapabilityProbe([string]$Arguments, [string]$Tool = $Executable, [switch]$ProbeTool) {
    $process = [Diagnostics.Process]::new()
    try {
        $process.StartInfo.FileName = $Tool
        $process.StartInfo.Arguments = $(if ($ProbeTool) { '-v error ' } else { '-nostdin -hide_banner ' }) + $Arguments
        $process.StartInfo.UseShellExecute = $false
        $process.StartInfo.CreateNoWindow = $true
        $process.StartInfo.RedirectStandardOutput = $true
        $process.StartInfo.RedirectStandardError = $true
        $null = $process.Start()
        $output = $process.StandardOutput.ReadToEndAsync()
        $errors = $process.StandardError.ReadToEndAsync()
        if (!$process.WaitForExit(6000)) {
            $process.Kill()
            $null = $process.WaitForExit(1000)
            return @{ Success = $false; Transient = $true; Error = 'FFmpeg capability probe timed out.' }
        }
        return @{ Success = ($process.ExitCode -eq 0); Output = $output.Result; Error = $errors.Result }
    }
    catch { return @{ Success = $false; Transient = $true; Error = $_.Exception.Message } }
    finally { $process.Dispose() }
}

function Test-EncodedCapability([string]$Encoder, [string]$Format, [int]$Depth) {
    if (!$probeExecutable -or ![IO.File]::Exists($probeExecutable)) {
        return @{ Success = $false; Transient = $true; Error = 'The sibling FFprobe executable is missing; output depth cannot be verified.' }
    }
    $file = [IO.Path]::Combine([IO.Path]::GetTempPath(), ('VideoTools-depth-' + [guid]::NewGuid().ToString('N') + '.mkv'))
    try {
        $options = switch ($Encoder) {
            'libx264' { '-preset ultrafast' }
            'libx265' { '-preset ultrafast -x265-params pools=1:frame-threads=1' }
            'libsvtav1' { '-preset 12 -svtav1-params lp=2' }
            'libvpx' { '-deadline realtime -cpu-used 8' }
            'libvpx-vp9' { '-deadline realtime -cpu-used 8' }
            default { '' }
        }
        # An accepted input pixel format is not proof of the encoded depth.
        # NVENC can accept p012le while producing a 10-bit compressed stream.
        $route = Get-EncoderProbeRoute $Encoder
        $encoded = Invoke-CapabilityProbe "-loglevel error -n $($route.Prefix) -f lavfi -i color=size=1280x720:rate=30 -vf format=$Format -frames:v 2 -an -threads 2 -c:v $Encoder $($route.Suffix) -pix_fmt $Format -b:v 2M $options `"$file`""
        if (!$encoded.Success) { return $encoded }
        $metadata = Invoke-CapabilityProbe "-select_streams v:0 -show_entries stream=codec_name,pix_fmt,bits_per_raw_sample -of json `"$file`"" -Tool $probeExecutable -ProbeTool
        if (!$metadata.Success) {
            return @{ Success = $false; Transient = $true; Error = 'FFprobe could not verify encoded output: ' + $metadata.Error }
        }
        $streams = @((ConvertFrom-Json $metadata.Output -ErrorAction Stop).streams)
        if ($streams.Count -ne 1) { throw 'Expected one encoded video stream.' }
        $stream = $streams[0]
        $actualDepth = 0
        if ($stream.pix_fmt -match '(9|10|12|14|16)(?:le|be)$') { $actualDepth = [int]$Matches[1] }
        elseif ($stream.pix_fmt -match '^(?:yuvj?420p|nv12|nv21)$') { $actualDepth = 8 }
        else { throw ('Unrecognized encoded pixel format: ' + $stream.pix_fmt) }
        $expectedCodec = switch ($Encoder) {
            'libx264' { 'h264' }
            'libx265' { 'hevc' }
            'libsvtav1' { 'av1' }
            'libvpx' { 'vp8' }
            'libvpx-vp9' { 'vp9' }
            'mpeg2_qsv' { 'mpeg2video' }
            default { $Encoder -replace '_(?:qsv|nvenc)$', '' }
        }
        if ($actualDepth -ne $Depth -or $stream.codec_name -ne $expectedCodec) {
            return @{ Success = $false; Mismatch = $true; Error = ('Requested {0} {1}-bit; encoded {2} {3}. This depth will not be offered.' -f $expectedCodec, $Depth, $stream.codec_name, $stream.pix_fmt) }
        }
        return @{ Success = $true }
    }
    catch { return @{ Success = $false; Transient = $true; Error = $_.Exception.Message } }
    finally {
        # Delete only this probe's uniquely named file, including partial output.
        try { if ([IO.File]::Exists($file)) { [IO.File]::Delete($file) } } catch { }
    }
}
$probeExecutable = [IO.Path]::Combine([IO.Path]::GetDirectoryName($Executable), 'ffprobe.exe')

$saved = if ($CachePath) { Get-ItemProperty -LiteralPath $CachePath -ErrorAction SilentlyContinue }
$result = @{ Encoders = @{}; Devices = @{}; Decoders = @{}; Diagnostics = @(); WindowsAdapters = @() }
$result.NvidiaInInventory = 'NVidia' -in $Vendors
try {
    if ($GPUControllerQuery) {
        $result.WindowsAdapters = @(& $GPUControllerQuery -OperationTimeoutSec 4 -ErrorAction Stop | ForEach-Object {
            $device = [regex]::Match([string]$_.PNPDeviceID, 'VEN_[0-9A-F]{4}&DEV_[0-9A-F]{4}(?:&SUBSYS_[0-9A-F]{8})?', 'IgnoreCase').Value
            [ordered]@{ Name = $_.Name; Driver = $_.DriverVersion; Device = $device; Status = $_.ConfigManagerErrorCode }
        })
    }
}
catch { $result.Diagnostics += 'Windows display adapter query failed: ' + $_.Exception.Message }
$nvidiaAdapters = @($result.WindowsAdapters | Where-Object { $_.Device -match '^VEN_10DE' -or $_.Name -match '\bNVIDIA\b' })
$result.NvidiaInWindows = $nvidiaAdapters.Count -gt 0
$result.NvidiaExpected = $result.NvidiaInInventory -or $result.NvidiaInWindows
if ($result.NvidiaInWindows -and !$result.NvidiaInInventory) {
    $identity = ($nvidiaAdapters | ForEach-Object { "$($_.Name)|$($_.Driver)|$($_.Device)" } | Sort-Object) -join ';'
    $Key += '|Windows NVIDIA adapters: ' + $identity
}
$checks = @{
    Encoders = @(
        if ('Intel' -in $Vendors) { 'mpeg2_qsv','vp8_qsv','vp9_qsv','h264_qsv','hevc_qsv','av1_qsv' }
        if ($result.NvidiaExpected) { 'h264_nvenc','hevc_nvenc','av1_nvenc' }
    )
    Devices = @('dxva2','d3d11va','opencl','vulkan'; if ($result.NvidiaExpected) { 'cuda' })
    Decoders = @('h264','hevc','mpeg1','mpeg2','mpeg4','mjpeg','vc1','vp8','vp9','av1' | ForEach-Object {
        if ('Intel' -in $Vendors) { $_ + '_qsv' }
        if ($result.NvidiaExpected) { $_ + '_cuvid' }
    })
}
foreach ($kind in 'Encoders','Devices','Decoders') {
    $name = 'FFmpeg' + $kind + 'V1'
    $cached = $null
    if ($saved.$name) {
        try { $cached = ConvertFrom-Json $saved.$name -ErrorAction Stop }
        catch { $result.Diagnostics += "Ignoring corrupt $name cache." }
    }
    $confirmed = @{}
    $list = $null
    $changed = $false
    foreach ($entry in $checks[$kind]) {
        if ($cached.Key -eq $Key -and $cached.Support.$entry -is [bool]) {
            $result[$kind][$entry] = $confirmed[$entry] = $cached.Support.$entry
            continue
        }
        if ($kind -ne 'Devices') {
            if (!$list) { $list = Invoke-CapabilityProbe ('-' + $kind.ToLowerInvariant()) }
            if (!$list.Success) {
                $result.Diagnostics += ('FFmpeg -{0} failed for {1}: {2}' -f $kind.ToLowerInvariant(), $entry, $list.Error)
                break
            }
            $listed = $list.Output -match ('(?m)^\s*V\S*\s+' + [regex]::Escape($entry) + '\s')
            if (!$listed -or $kind -eq 'Decoders') {
                $result[$kind][$entry] = $confirmed[$entry] = $listed
                $changed = $true
                continue
            }
            $route = Get-EncoderProbeRoute $entry
            $test = Invoke-CapabilityProbe "-loglevel error $($route.Prefix) -f lavfi -i color=size=1280x720:rate=30 -vf format=nv12 -frames:v 2 -c:v $entry $($route.Suffix) -b:v 2M -f null -"
        }
        else {
            $level = if ($entry -eq 'vulkan') { 'debug' } else { 'error' }
            $device = if ($entry -eq 'cuda' -and $CudaIndex -ge 0) {
                'cuda:' + $CudaIndex
            }
            elseif ($entry -eq 'd3d11va' -and $Direct3DIndex -ge 0) {
                'd3d11va:' + $Direct3DIndex
            }
            else { $entry }
            $test = Invoke-CapabilityProbe "-loglevel $level -init_hw_device $device -f lavfi -i color=size=128x128:rate=1 -frames:v 1 -f null -"
        }
        if (!$test.Success) {
            $result.Diagnostics += ('{0} probe failed: {1}' -f $entry, $test.Error)
            continue
        }
        $supported = $entry -ne 'vulkan' -or $test.Error -match '(?:video[ _]decode.*queues:|queue family.*video[ _]decode)'
        $result[$kind][$entry] = $confirmed[$entry] = $supported
        $changed = $true
    }
    if ($changed -and $CachePath) {
        $value = ConvertTo-Json -Compress -InputObject @{ Key = $Key; Support = $confirmed }
        Set-ItemProperty -LiteralPath $CachePath -Name $name -Value $value -ErrorAction SilentlyContinue
    }
}
# Cache format/depth support separately: encoder presence alone does not prove
# that this GPU/driver can encode its advertised 10/12-bit formats.
$result.EncoderFormats = @{}
$depthCache = $null
$knownFormats = @{}
$changed = $false
if ($saved.FFmpegEncoderFormatsV3) {
    try { $depthCache = ConvertFrom-Json $saved.FFmpegEncoderFormatsV3 -ErrorAction Stop } catch { }
}
elseif ($saved.FFmpegEncoderFormatsV2) {
    try { $depthCache = ConvertFrom-Json $saved.FFmpegEncoderFormatsV2 -ErrorAction Stop } catch { }
}
if ($depthCache.Key -eq $Key) {
    foreach ($encoder in $depthCache.Support.PSObject.Properties) {
        $knownFormats[$encoder.Name] = @{}
        foreach ($depth in $encoder.Value.PSObject.Properties) {
            $knownFormats[$encoder.Name][$depth.Name] = [string]$depth.Value
        }
    }
}
$encoderNames = @('libx264','libx265','libsvtav1','libvpx-vp9','libvpx','mpeg2video','mpeg4','wmv2') +
    @($result.Encoders.Keys | Where-Object { $result.Encoders[$_] })
foreach ($encoderName in $encoderNames) {
    if (!$knownFormats.ContainsKey($encoderName)) { $knownFormats[$encoderName] = @{} }
    $formats = $knownFormats[$encoderName]
    $missing = @(8,10,12 | Where-Object { !$formats.ContainsKey([string]$_) })
    if (!$missing.Count) { continue }
    $help = Invoke-CapabilityProbe "-h encoder=$encoderName"
    if (!$help.Success -or $help.Output -notmatch 'Supported pixel formats:\s*([^\r\n]+)') { continue }
    $advertised = $Matches[1] -split '\s+'
    $hardwareEncoder = $encoderName -match '_(qsv|nvenc)$'
    foreach ($depth in $missing) {
        $candidates = if ($depth -eq 8) { 'nv12','yuv420p' }
            elseif ($depth -eq 10) { 'p010le','yuv420p10le' }
            else { 'p012le','yuv420p12le' }
        if (!$hardwareEncoder) { [array]::Reverse($candidates) }
        $format = $candidates | Where-Object { $_ -in $advertised } | Select-Object -First 1
        if (!$format) {
            $formats[[string]$depth] = 'NotAdvertised'
        }
        else {
            $probe = Test-EncodedCapability $encoderName $format $depth
            if (!$probe.Success) {
                $result.Diagnostics += ('{0} {1}-bit output verification failed: {2}' -f $encoderName, $depth, $probe.Error)
                if (!$probe.Mismatch) { continue }
                $formats[[string]$depth] = 'Mismatch'
            }
            else { $formats[[string]$depth] = $format }
        }
        $changed = $true
    }
}
foreach ($encoderName in $knownFormats.Keys) {
    $verified = @{}
    foreach ($depth in $knownFormats[$encoderName].Keys) {
        $format = $knownFormats[$encoderName][$depth]
        if ($format -notin 'Mismatch','NotAdvertised') { $verified[$depth] = $format }
    }
    $result.EncoderFormats[$encoderName] = $verified
}
if ($changed -and $CachePath) {
    $value = ConvertTo-Json -Depth 5 -Compress -InputObject @{ Key = $Key; Support = $knownFormats }
    Set-ItemProperty -LiteralPath $CachePath -Name FFmpegEncoderFormatsV3 -Value $value -ErrorAction SilentlyContinue
}
return $result