# encode-smoke-tests.ps1
#
# Hardware H.264 encode smoke test for the LGPL NextNote FFmpeg build.
# The release no longer contains libx264: LiveView requires NVENC, AMF, or
# QSV. This test tries the same preference order as the Windows helpers and
# emits a raw Annex-B sample for decode-smoke-tests.ps1.
#
# Not intended to be run standalone; called by test.ps1.

[CmdletBinding()]
param(
    [Parameter(Mandatory)][string]$FfmpegPath,
    [Parameter(Mandatory)][string]$OutDir
)

$ErrorActionPreference = 'Stop'
Set-StrictMode -Version Latest
Import-Module (Join-Path $PSScriptRoot '..\scripts\BuildCommon.psm1') -Force

$w = 320
$h = 180
$frames = 2
$h264File = Join-Path $OutDir 'encode-smoke.h264'
$attempts = @()
$selectedEncoder = $null

function Get-SmokeArguments {
    param([Parameter(Mandatory)][string]$Encoder)

    $inputArgs = "-f lavfi -i color=black:size=${w}x${h}:rate=30"
    $filterArgs = ''
    $encoderArgs = switch ($Encoder) {
        'h264_nvenc' { '-preset p1 -tune ll -rc vbr -b:v 2M -maxrate 4M -rc-lookahead 0 -profile:v high -level 4.0 -forced-idr 1' }
        'h264_amf'   { '-usage ultralowlatency -quality speed -rc vbr_peak -b:v 2M -maxrate 4M -bufsize 1M -profile:v high -level 4.0 -pix_fmt yuv420p' }
        'h264_qsv'   {
            $inputArgs = "-f gdigrab -framerate 30 -video_size ${w}x${h} -offset_x 0 -offset_y 0 -i desktop"
            $filterArgs = "-vf drawbox=x=0:y=0:w=${w}:h=${h}:color=black:t=fill"
            '-preset veryfast -b:v 2M -profile:v high -level 4.0 -pix_fmt yuv420p'
        }
        default { throw "Unsupported encoder: $Encoder" }
    }

    return ("{0} -vframes {1} {2} -c:v {3} {4} " +
        '-bsf:v "dump_extra=freq=keyframe,filter_units=remove_types=6|12" ' +
        '-bf 0 -an -f h264 pipe:1') -f
        $inputArgs, $frames, $filterArgs, $Encoder, $encoderArgs
}

foreach ($encoder in 'h264_nvenc', 'h264_amf', 'h264_qsv') {
    Remove-Item $h264File -Force -ErrorAction SilentlyContinue
    $encArgs = Get-SmokeArguments -Encoder $encoder
    $result = Invoke-FfmpegProcess -FfmpegPath $FfmpegPath -ArgumentLine $encArgs -StdoutFile $h264File -TimeoutSec 30
    $size = if (Test-Path $h264File) { (Get-Item $h264File).Length } else { 0 }
    $passed = $result.exitCode -eq 0 -and $size -gt 0

    $attempts += [ordered]@{
        encoder = $encoder
        passed = $passed
        args = $encArgs
        exitCode = $result.exitCode
        outBytes = $size
        stderrTail = $result.stderrTail
    }

    Write-Host ("{0,-12} exit={1} bytes={2}  {3}" -f
        $encoder, $result.exitCode, $size, $(if ($passed) { 'PASS' } else { 'unavailable' }))

    if ($passed) {
        $selectedEncoder = $encoder
        break
    }
}

$overallPassed = -not [string]::IsNullOrWhiteSpace($selectedEncoder)
if (-not $overallPassed) {
    $stderrPath = Join-Path $OutDir 'encode-smoke-stderr.log'
    $attempts | ConvertTo-Json -Depth 6 | Set-Content -Path $stderrPath -Encoding UTF8
    Write-Host "No supported hardware H.264 encoder initialised. Attempt details: $stderrPath" -ForegroundColor Red
}

[ordered]@{
    name = 'encode-smoke-tests'
    passed = $overallPassed
    selectedEncoder = $selectedEncoder
    outFile = $h264File
    outBytes = if (Test-Path $h264File) { (Get-Item $h264File).Length } else { 0 }
    attempts = $attempts
}
