@echo off
cd %~dp0
if "%~f1" == "" goto fail
echo Preparing to recode "%~f1"...
setlocal enabledelayedexpansion
set tmpname=%Time%
set tmpname=%tmpname::=%
set tmpname=%tmpname:.=%
set tmpname=%tmpname:,=%
set tmpname=%tmpname: =%
for /l %%a in (0,1,1) do set tmpname=!tmpname!!random!
endlocal & set tmpfile=%tmpname%
if not exist tmp mkdir tmp
del /q tmp\*.*
echo Building Avisynth script...
echo LoadPlugin("%~dp0bin\plugins\ffms2.dll") > tmp\%tmpfile%.avs
echo LoadPlugin("%~dp0bin\plugins\vsfilter.dll") >> tmp\%tmpfile%.avs
echo LoadPlugin("%~dp0bin\plugins\LoadFont.dll") >> tmp\%tmpfile%.avs
echo Import("%~dp0bin\plugins\ResizeKAR.avsi") >> tmp\%tmpfile%.avs
echo FFIndex("%~f1",cachefile="%~dp0tmp\%tmpfile%.index") >> tmp\%tmpfile%.avs
echo v=FFVideoSource("%~f1",cachefile="%~dp0tmp\%tmpfile%.index").ChangeFPS(23.976) >> tmp\%tmpfile%.avs
echo a=FFAudioSource("%~f1",cachefile="%~dp0tmp\%tmpfile%.index") >> tmp\%tmpfile%.avs
echo AudioDub(v,a) >> tmp\%tmpfile%.avs
if not exist "%~dpn1.ass" goto srt
echo Detected external ASS subtitles...
echo TextSub("%~dpn1.ass") >> tmp\%tmpfile%.avs
goto endsub
:srt
if not exist "%~dpn1.srt" goto internal
echo Detected external SRT subtitles...
echo TextSub("%~dpn1.srt") >> tmp\%tmpfile%.avs
goto endsub
:internal
if /i "%~x1" NEQ ".mkv" goto endsub
echo Detected MKV container. Trying to parse...
set subnum == ""
bin\mkvmerge -i "%~f1" >> tmp\%tmpfile%.info
findstr subtitles tmp\%tmpfile%.info >> tmp\%tmpfile%.subsinfo
for /f "tokens=3 delims=: " %%a in (tmp\%tmpfile%.subsinfo) do set subnum=%%a
if %subnum% == "" goto endsub
echo Detected internal subtitles. Extracting...
findstr truetype tmp\%tmpfile%.info >> tmp\%tmpfile%.fontsinfo
for /f "tokens=1,5 delims=:'" %%i in (tmp\%tmpfile%.fontsinfo) do for /f "tokens=3" %%k in ("%%i") do (
bin\mkvextract attachments "%~f1" %%k:"tmp\%%j" > nul
echo LoadFont^("%~dp0tmp\%%j"^) >> tmp\%tmpfile%.avs
)
bin\mkvextract tracks "%~f1" %subnum%:"tmp\%tmpfile%.ass" > nul
echo TextSub("%~dp0tmp\%tmpfile%.ass") >> tmp\%tmpfile%.avs
:endsub
echo ResizeKAR(640,360) >> tmp\%tmpfile%.avs
rem echo Trim(0,300) >> tmp\%tmpfile%.avs
echo Avisynth script is ready.
echo Encoding video. Pass 1...
bin\xvid_encraw -i tmp\%tmpfile%.avs -o nul -pass1 tmp\%tmpfile%.stats -w 640 -h 360 -framerate 23.976 -bitrate 550 -max_bframes 0 -progress
echo Encoding video. Pass 2...
bin\xvid_encraw -i tmp\%tmpfile%.avs -avi tmp\%tmpfile%.avi -pass2 tmp\%tmpfile%.stats -w 640 -h 360 -framerate 23.976 -bitrate 550 -max_bframes 0 -progress
echo Encoding audio...
bin\ffmpeg -i tmp\%tmpfile%.avs -vn -acodec pcm_s16le -f wav -y tmp\%tmpfile%.wav
bin\neroaacenc -br 96000 -lc -2pass -if tmp\%tmpfile%.wav -of tmp\%tmpfile%.m4a
echo Muxing...
if exist "%~dpn1.phone.mp4" del "%~dpn1.phone.mp4"
bin\mp4box -add tmp\%tmpfile%.avi -add tmp\%tmpfile%.m4a "%~dpn1.phone.mp4"
echo Removing temporary files...
del /q tmp\%tmpfile%.*
del /q tmp\*.?tf
echo Recode is completed.
goto done
:fail
echo FAIL
:done
pause