@echo off
setlocal EnableExtensions EnableDelayedExpansion

if "%~2"=="" (
    echo Usage: %~nx0 image-file audio-file
    echo        %~nx0 audio-file image-file
    exit /b 1
)

call :classify "%~x1" kind1
call :classify "%~x2" kind2

if /I "!kind1!"=="image" if /I "!kind2!"=="audio" (
    set "image=%~f1"
    set "audio=%~f2"
    set "output=%~dpn2.mp4"
)

if /I "!kind1!"=="audio" if /I "!kind2!"=="image" (
    set "audio=%~f1"
    set "image=%~f2"
    set "output=%~dpn1.mp4"
)

if not defined audio (
    echo Expected one audio file and one image file.
    echo Received: "%~1" and "%~2"
    exit /b 1
)

set "VF=scale=1280:720:force_original_aspect_ratio=decrease,pad=1280:720:(ow-iw)/2:(oh-ih)/2,format=yuv420p"

echo Trying NVIDIA NVENC H.264...
ffmpeg.exe -hide_banner -loglevel error -y -loop 1 -framerate 1 -i "!image!" -i "!audio!" -vf "!VF!" -c:v h264_nvenc -preset p5 -cq 19 -b:v 0 -c:a aac -q:a 2 -shortest -movflags +faststart "!output!"
if not errorlevel 1 call :valid "!output!" && exit /b 0
del "!output!" 2>nul

echo Trying Intel Quick Sync H.264...
ffmpeg.exe -hide_banner -loglevel error -y -loop 1 -framerate 1 -i "!image!" -i "!audio!" -vf "!VF!" -c:v h264_qsv -global_quality 19 -c:a aac -q:a 2 -shortest -movflags +faststart "!output!"
if not errorlevel 1 call :valid "!output!" && exit /b 0
del "!output!" 2>nul

echo Trying AMD AMF H.264...
ffmpeg.exe -hide_banner -loglevel error -y -loop 1 -framerate 1 -i "!image!" -i "!audio!" -vf "!VF!" -c:v h264_amf -quality quality -rc cqp -qp_i 19 -qp_p 19 -qp_b 19 -c:a aac -q:a 2 -shortest -movflags +faststart "!output!"
if not errorlevel 1 call :valid "!output!" && exit /b 0
del "!output!" 2>nul

echo Hardware encoding failed or is unavailable. Falling back to CPU H.264...
ffmpeg.exe -hide_banner -y -loop 1 -framerate 1 -i "!image!" -i "!audio!" -vf "!VF!" -c:v libx264 -crf 18 -preset medium -tune stillimage -c:a aac -q:a 2 -shortest -movflags +faststart "!output!"
if errorlevel 1 exit /b %ERRORLEVEL%
call :valid "!output!"
exit /b %ERRORLEVEL%

:valid
if not exist "%~1" exit /b 1
for %%F in ("%~1") do if %%~zF LEQ 0 exit /b 1
ffprobe.exe -hide_banner -loglevel error "%~1" >nul 2>nul
exit /b %ERRORLEVEL%

:classify
set "%~2="
for %%I in (.jpg .jpeg .png .bmp .gif .webp) do if /I "%~1"=="%%~I" set "%~2=image"
for %%I in (.mp3 .wav .m4a .aac .flac .ogg .opus .wma .aif .aiff) do if /I "%~1"=="%%~I" set "%~2=audio"
exit /b 0
