@echo off
setlocal EnableExtensions

if "%~1"=="" exit /b 1
if "%~2"=="" exit /b 1

set "IN=%~1"
set "OUT=%~2"

if /I "%~f1"=="%~f2" (
    set "OUT=%~dpn2-remux%~x2"
)

echo Trying stream-copy remux...
ffmpeg.exe -hide_banner -loglevel error -y -i "%IN%" -map 0 -c copy -movflags +faststart "%OUT%"
if not errorlevel 1 call :valid "%OUT%" && exit /b 0

del "%OUT%" 2>nul

echo Remux failed. Trying NVIDIA NVENC H.264...
ffmpeg.exe -hide_banner -loglevel error -y -i "%IN%" -map 0:v? -map 0:a? -sn -dn -c:v h264_nvenc -preset p5 -cq 19 -b:v 0 -pix_fmt yuv420p -c:a aac -q:a 2 -movflags +faststart "%OUT%"
if not errorlevel 1 call :valid "%OUT%" && exit /b 0

del "%OUT%" 2>nul

echo NVENC failed. Trying Intel Quick Sync H.264...
ffmpeg.exe -hide_banner -loglevel error -y -i "%IN%" -map 0:v? -map 0:a? -sn -dn -c:v h264_qsv -global_quality 19 -pix_fmt yuv420p -c:a aac -q:a 2 -movflags +faststart "%OUT%"
if not errorlevel 1 call :valid "%OUT%" && exit /b 0

del "%OUT%" 2>nul

echo Quick Sync failed. Trying AMD AMF H.264...
ffmpeg.exe -hide_banner -loglevel error -y -i "%IN%" -map 0:v? -map 0:a? -sn -dn -c:v h264_amf -quality quality -rc cqp -qp_i 19 -qp_p 19 -qp_b 19 -pix_fmt yuv420p -c:a aac -q:a 2 -movflags +faststart "%OUT%"
if not errorlevel 1 call :valid "%OUT%" && exit /b 0

del "%OUT%" 2>nul

echo Hardware encoding failed or is unavailable. Falling back to CPU H.264...
ffmpeg.exe -hide_banner -y -i "%IN%" -map 0:v? -map 0:a? -sn -dn -c:v libx264 -crf 18 -preset medium -pix_fmt yuv420p -c:a aac -q:a 2 -movflags +faststart "%OUT%"
if errorlevel 1 exit /b %ERRORLEVEL%
call :valid "%OUT%"
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%
