@echo off
setlocal EnableExtensions EnableDelayedExpansion

if "%~1"=="" (
    echo Usage: file2wav input-file [input-file...]
    exit /b 1
)

set "FFMPEG=%~dp0ffmpeg.exe"
set "FFPROBE=%~dp0ffprobe.exe"
if not exist "%FFMPEG%" set "FFMPEG=ffmpeg.exe"
if not exist "%FFPROBE%" set "FFPROBE=ffprobe.exe"

:next
if "%~1"=="" exit /b 0

set "INPUT=%~1"
set "OUTPUT=%~dpn1.wav"
set "CODEC=pcm_s16le"
set "codec_name="
set "bits_per_sample="
set "bits_per_raw_sample="
set "sample_fmt="
set "PROBEFILE=%TEMP%\file2wav-probe-%RANDOM%-%RANDOM%.txt"

"%FFPROBE%" -v error -select_streams a:0 -show_entries stream=codec_name,bits_per_sample,bits_per_raw_sample,sample_fmt -of default=noprint_wrappers=1 "%INPUT%" > "%PROBEFILE%" 2>nul
for /f "usebackq tokens=1,* delims==" %%A in ("%PROBEFILE%") do (
    set "%%A=%%B"
)
del "%PROBEFILE%" >nul 2>nul

if /I "!codec_name!"=="pcm_s24le" set "CODEC=pcm_s24le"
if /I "!codec_name!"=="pcm_s24be" set "CODEC=pcm_s24le"
if /I "!codec_name!"=="pcm_s32le" set "CODEC=pcm_s32le"
if /I "!codec_name!"=="pcm_s32be" set "CODEC=pcm_s32le"
if /I "!codec_name!"=="pcm_f32le" set "CODEC=pcm_f32le"
if /I "!codec_name!"=="pcm_f32be" set "CODEC=pcm_f32le"
if /I "!codec_name!"=="pcm_f64le" set "CODEC=pcm_f64le"
if /I "!codec_name!"=="pcm_f64be" set "CODEC=pcm_f64le"

if "!bits_per_raw_sample!"=="24" set "CODEC=pcm_s24le"
if "!bits_per_sample!"=="24" set "CODEC=pcm_s24le"
if "!bits_per_raw_sample!"=="32" if /I not "!sample_fmt!"=="flt" if /I not "!sample_fmt!"=="fltp" set "CODEC=pcm_s32le"
if "!bits_per_sample!"=="32" if /I not "!sample_fmt!"=="flt" if /I not "!sample_fmt!"=="fltp" set "CODEC=pcm_s32le"
if /I "!sample_fmt!"=="flt" if /I "!codec_name:~0,5!"=="pcm_f" set "CODEC=pcm_f32le"
if /I "!sample_fmt!"=="dbl" if /I "!codec_name:~0,5!"=="pcm_f" set "CODEC=pcm_f64le"

echo Converting "%INPUT%" to "%OUTPUT%" as !CODEC!
"%FFMPEG%" -hide_banner -i "%INPUT%" -vn -map 0:a:0 -c:a !CODEC! "%OUTPUT%"

shift
goto next
