Difference between revisions of "Anri-chan/Source/anri.bat"

From SDA Knowledge Base

Jump to: navigation, search
(Starting Anri 3.3. Using CRF encoding method with 2nd pass only being performed if first pass exceeds bitrate limit. No more quantizer 19, use crf 17.)
(fixed anri url)
 
Line 7: Line 7:
  
 
REM metroid 2002 speed demos archive anri-chan
 
REM metroid 2002 speed demos archive anri-chan
REM http://www.metroid2002.com/
+
REM http://speeddemosarchive.com/kb/Anri-chan
REM http://speeddemosarchive.com/
+
 
REM nathan jahnke <njahnke@gmail.com>
 
REM nathan jahnke <njahnke@gmail.com>
 
REM Ian Bennett
 
REM Ian Bennett

Latest revision as of 11:21, 13 August 2010

@ECHO OFF

REM ---------------------------------------------------------------------------
REM                                   Credits
REM ---------------------------------------------------------------------------

REM metroid 2002 speed demos archive anri-chan
REM http://speeddemosarchive.com/kb/Anri-chan
REM nathan jahnke <njahnke@gmail.com>
REM Ian Bennett
REM Philip "ballofsnow" Cornell
REM Brett "Psonar" Ables


REM ---------------------------------------------------------------------------
REM             Set Anri-chan to low priority mode. ( & other params)
REM
REM  Environment variables remain even if you call anri-chan on top of itself.
REM  So don't worry about losing information. The loop looks for parameters
REM  that have been sent to anri.bat. Order doesn't matter as you can see. When
REM  setting anri.bat to low priority, you send the parameter "anrilow" so that
REM  anri-chan knows, and doesn't go into an infinite loop.
REM ---------------------------------------------------------------------------

FOR %%G IN (%*) DO (
  IF %%G==anrilow (SET anrilow=y)
  IF %%G==samplemode (SET samplemode=y)
  IF %%G==auto (SET auto=y)
)
IF NOT DEFINED anrilow ( GOTO setanribat )


REM ---------------------------------------------------------------------------
REM                                Initialisation
REM
REM Some obvious stuff in here. todo: describe desktop location
REM ---------------------------------------------------------------------------

(SET anri_ver=3.3)
(SET in_anrichan=y)
REM includes \
SET anri_dir=%~dp0
SET anri_path=%~dp0anri.bat
(SET dgmpgdec_dir=dgmpgdec150)
(SET vdub=virtualdub-1.9.7)

REM ---------------------------------------------------------------------------
REM                              Color Initialization
REM
REM Edit by: Psonar  -  Brett Ables
REM Below is the code necessary to use the CECHO.exe function
REM to add color to anrichan. Run CECHO.exe /? for usage help.
REM CECHO.exe was written by Thomas Polaert.
REM
REM The environment variable CECHO is set to the absolute path
REM of the CECHO.exe program so that %CECHO% may be used 
REM to call the function regardless of the working directory
REM
REM RESET_COLOR is used to reset the default color scheme 
REM after CECHO has been used to output different colors.
REM
REM Color is a DOS function that affects the whole command 
REM window at once.  It is used only once here to initialize the
REM background color of the window. 80 is the same as {black on gray}.
REM 
REM CECHO is used in out_cls, out_info, out_error, and out_section.
REM ---------------------------------------------------------------------------

(SET CECHO="%anri_dir%cecho.exe")
(SET RESET_COLOR=%CECHO% {black on gray})
Color 80

REM ----------------- End Color Initialization ----------------------------

REM log name
(SET log=log_%time%)
(SET log=%log::=%)
(SET log=%log: =%)
(SET log=%log:.=%.txt)

REM get the name of the desktop ... old method for safety...
(SET DESKTOP=%HOMEDRIVE%%HOMEPATH%\desktop)
REM then new method..
FOR /F "skip=4 tokens=2 delims=\" %%G IN ('REG QUERY "hkcu\software\microsoft\windows\currentversion\explorer\user shell folders" /v desktop') DO SET desktop=%HOMEDRIVE%%HOMEPATH%\%%G

REG ADD "HKEY_CURRENT_USER\Software\VirtualDub.org\VirtualDub\Persistence" /v "Update input pane" /t REG_DWORD /d 1 /f > NUL
REG ADD "HKEY_CURRENT_USER\Software\VirtualDub.org\VirtualDub\Persistence" /v "Update output pane" /t REG_DWORD /d 0 /f > NUL

CALL "%anri_dir%ini.bat"
IF NOT DEFINED project_parentdir SET project_parentdir=%DESKTOP%

REM ---------------------------------------------------------------------------
REM                                Main menu
REM 
REM  Anri-chan's home. 
REM ---------------------------------------------------------------------------

:proc_main
CALL :out_cls
IF "%main_anri_updated%"=="y" GOTO die
IF "%using_settings%"=="y" GOTO proc_check_settings
CALL :out_cls
CALL :out_info ON HERMESUS LUC ARSUS ESTARIAS AUC ELTRAS LI CELES! Now, let's get to work!
CALL :out_section Main
rem IF NOT "%auto%"=="y" (CALL :q_projname)

:q_main_options
ECHO  1. Rip DVD to hard drive (required for DVD material)
ECHO  2. Start new project
ECHO  3. Extract sample (for DFnD)
ECHO  4. Station ID preview
ECHO  5. Audio commentary
ECHO  6. Exit
ECHO.
SET s=2
SET /P s=[1,(2),3,4,5,6]: 
CALL :set_var_in mainoption q_main_options 123456

IF %mainoption%==1 CALL :rip_dvd
IF %mainoption%==2 CALL :project
IF %mainoption%==3 CALL :proc_sample
IF %mainoption%==4 CALL :statidpreview
IF %mainoption%==5 CALL :audio_commentary
IF %mainoption%==6 GOTO :DIE

GOTO :proc_main

REM ---------------------------------------------------------------------------
REM                          Sample extraction procedure
REM 
REM  Sample extraction is basically regular mode minus a bunch of questions.
REM  There isn't much documentation about how this works since this was
REM  meant to be short. One thing that's different is that the sample video
REM  will have separated fields. This is to avoid the problem with interlacing
REM  and the Yv12 colorspace.
REM ---------------------------------------------------------------------------

:proc_sample
CALL :out_cls
SETLOCAL ENABLEDELAYEDEXPANSION
CD /D "%project_parentdir%"
(SET no_pause_before_indexing=y)
(SET projname=sample)
CALL :make_projdir
CALL :load_plugins
CALL :out_cls_section Sample extraction
CALL :q_dvdsource
IF "%dvdsource%"=="y" (
  CALL :index_dvd
) ELSE (
  SET maxaudiobitrate=320000
  CALL :q_avi
)
CALL :out_info This sample will be 300 frames long, pick the starting frame of a scene with action.
COPY /B "sample.avs" "sample_trimtemp.avs" 1> NUL
ECHO>> "sample_trimtemp.avs" lanczos4resize^(320,240^)
PAUSE
START "trimming vdub" "%anri_dir%%vdub%\virtualdub.exe" "sample_trimtemp.avs"
CALL :q_trimval
SET /A trim2=!trimval! + 299
ECHO>> sample.avs trim^(!trimval!,!trim2!^)
ECHO>> sample.avs AssumeTFF
ECHO>> sample.avs SeparateFields
ECHO>> sample.avs last.height %% 2 == 1 ? AddBorders^(0,0,0,1^) : NOP
ECHO>> sample.avs converttoyv12
ECHO>> sample.avs AssumeFrameBased
CALL :1pass sample.avs sample 128000 19 1
MOVE /Y sample.mp4 %projname%_finished > NUL 2>&1
ECHO.
ECHO.
%CECHO% "{white on gray}Finished. You will find a sample folder on your desktop. Feel free to rename the video to something more descriptive like nameofgame_sample.mp4.{\n}"
ECHO.
%CECHO% "{red on gray} - READ -{white on gray} You will see that the video has been resized vertically (it's slightly more complicated than that..), {red on gray}THIS IS NORMAL{white on gray} and will make it easier for the techies to help you.{\n}"
%RESET_COLOR%
ECHO.
PAUSE
@ECHO ON
ENDLOCAL ENABLEDELAYEDEXPANSION
EXIT

REM ---------------------------------------------------------------------------
REM                             Station ID preview
REM 
REM Preview the statid in virtualdub.
REM ---------------------------------------------------------------------------

:statidpreview
CALL :out_cls_section Station ID preview
SET statid1=
SET statid2=
SET statid3=
SET /P statid1=Station ID Line 1 (normally runner name): 
SET /P statid2=Station ID Line 2 (normally game name, run type and time): 
SET /P statid3=Station ID Line 3 (normally game name, run type and time continued if necessary): 
IF NOT DEFINED statid1 (SET statid1= )
IF NOT DEFINED statid2 (SET statid2= )
IF NOT DEFINED statid3 (SET statid3= )
REM Replace quotes from user
(SET statid1=%statid1:"="+chr(34)+"%)
(SET statid2=%statid2:"="+chr(34)+"%)
(SET statid3=%statid3:"="+chr(34)+"%)
CD /D %project_parentdir%
COPY /Y "%anri_dir%statid.png" > NUL
ECHO> statid_preview.avs import("%anri_dir%sda.avs")
ECHO>> statid_preview.avs blankclip(length=150, width=640, height=480, fps=30, color=$000000)
ECHO>> statid_preview.avs nate_statid(last,"%statid1%\n\n%statid2%\n%statid3%","n","n")
START "Station ID preview" "%anri_dir%%vdub%\virtualdub.exe" "statid_preview.avs"
rem del statid_preview.avs statid.png
SET statid1=
SET statid2=
SET statid3=
ECHO.
PAUSE
GOTO :EOF

REM ---------------------------------------------------------------------------
REM                             Audio commentary
REM 
REM This is not integrated into the main encoding process. The user is expected
REM to have prepared a wav file in sync with the video.
REM ---------------------------------------------------------------------------

:audio_commentary
CALL :out_cls_section Audio Commentary
CALL :out_info Path to audio commentary .wav file
ECHO e.g. c:\path to\commentary.wav
:audio_commentary_audioinput
SET /P audio_commentary_path=: 
CALL :removequotations audio_commentary_path
REM Validate. Precedence is descending, e.g. empty string is first because it is the most serious error
IF NOT DEFINED audio_commentary_path (
  CALL :out_error You must enter a path.
  GOTO :audio_commentary_audioinput
) ELSE (
  IF NOT %audio_commentary_path:~-4%==.wav (
    CALL :out_error Must be a .wav file ^(File menu, Export to WAV in Audacity^), try again.
    GOTO :audio_commentary_audioinput
  ) ELSE (
    IF NOT EXIST "%audio_commentary_path%" (
      CALL :out_error File does not exist, try again.
      GOTO :audio_commentary_audioinput
    ) ELSE (
      CALL :out_info WAV audio loaded successfully!
    )
  )
)

ECHO.
CALL :out_info Path to target video .mp4 files
ECHO e.g. c:\path to\video.mp4   - Type n to quit -
SET video_commentary_path=
:audio_commentary_videoinput
SET videofile=
SET /P videofile=: 
CALL :removequotations videofile
REM Validate. Precedence is descending, e.g. empty string is first because it is the most serious error
IF NOT "%videofile%"=="n" (
  IF NOT DEFINED videofile (
    CALL :out_error You must enter a path, or type n to quit.
    GOTO :audio_commentary_videoinput
  ) ELSE (
    IF NOT %videofile:~-4%==.mp4 (
      CALL :out_error Must be an mp4 file, try again.
      GOTO :audio_commentary_videoinput
    ) ELSE (
      IF NOT EXIST "%videofile%" (
        CALL :out_error File does not exist, try again.
        GOTO :audio_commentary_videoinput
      ) ELSE (
        (SET video_commentary_path=%video_commentary_path%"%videofile%" )
        GOTO :audio_commentary_videoinput
      )
    )
  )
) ELSE (
  IF NOT DEFINED video_commentary_path (
    CALL :out_error You must load at least one mp4 file.
    GOTO :audio_commentary_videoinput
  )
)

REM ENCODE AUDIO TO 32 KBIT AAC MP4
"%anri_dir%neroAacEnc.exe" -br 32000 -lc -if "%audio_commentary_path%" -of "%project_parentdir%\commentary_track3.mp4"
IF NOT %ERRORLEVEL%==0 (
  CALL :out_error Could not read .wav file! Is this a proper .wav file exported from e.g. Audacity?
  PAUSE
  GOTO :EOF
)

SETLOCAL ENABLEDELAYEDEXPANSION
FOR %%G IN (%video_commentary_path%) DO (
  REM Build path info and change to video's directory
  SET video_commentary_video=%%~nxG
  SET video_commentary_video_base=%%~nG
  CD /D %%~dpG
  REM MUX
  "%anri_dir%MP4Box.exe" -single 1 "!video_commentary_video!"
  "%anri_dir%MP4Box.exe" -single 2 "!video_commentary_video!"
  COPY /Y "!video_commentary_video!" "!video_commentary_video_base!.backup.mp4" > NUL
  "%anri_dir%MP4Box.exe" -tmp . -new -add "!video_commentary_video_base!_track1.mp4" -add "!video_commentary_video_base!_track2.mp4" -add "%project_parentdir%\commentary_track3.mp4" -disable 3 "!video_commentary_video!"
  DEL "!video_commentary_video_base!_track1.mp4"
  DEL "!video_commentary_video_base!_track2.mp4"
  ECHO.
  %CECHO% "{white on gray}Finished. Audio commentary has been added to your video. Your original video (without the commentary) has been moved to !video_commentary_video_base!.backup.mp4.{\n}"
  %RESET_COLOR%
  ECHO.
)
DEL "%project_parentdir%\commentary_track3.mp4"
ENDLOCAL ENABLEDELAYEDEXPANSION
PAUSE
GOTO :EOF

REM ---------------------------------------------------------------------------
REM                              Main procedure
REM 
REM  Anri-chan's home.. housing the program flow. This is beginning to end for
REM  encoding the video.
REM 
REM  The first section sets up the project name and folder, or if one already
REM  exists it will find the existing settings and go to the encoding stage.
REM ---------------------------------------------------------------------------

:project
CALL :out_cls
CALL :out_info ON HERMESUS LUC ARSUS ESTARIAS AUC ELTRAS LI CELES! Now, let's get to work!
CALL :out_section PROJECT SETUP
IF NOT "%auto%"=="y" (CALL :q_projname)
CALL :make_projdir
CALL :load_plugins
CALL :find_existing_settings
IF "%using_settings%"=="y" GOTO proc_check_settings

REM ---------------------------------------------------------------------------
REM  Main procedure - Movie source
REM 
REM  It's either DVD or AVI, no exceptions (for now). The current method for
REM  DVD extraction is as follows: Find and validate the DVD folder. Check for
REM  the existence of IFO files (has details on structure of DVD). If they are
REM  found, the IFO is analyzed and ripped with Mplayer. Otherwise it goes
REM  straight to DGindex.
REM
REM  Why Mplayer? It has the ability to rip files per program chain. There is
REM  a problem where indexing multiple program chains can cause audio desync.
REM  Now that we get the data on a per PGC basis, we can index them individually
REM  and join them up later in AviSynth which can properly align video/audio.
REM 
REM  There are two methods for loading AVI files. Either the user enters the
REM  paths to the file individually, or specifies a directory and anri-chan
REM  loads all AVI files alphabetically. There is currently no validation for
REM  AVI files with different video properties.
REM ---------------------------------------------------------------------------

CALL :out_cls_section MOVIE SOURCE
CALL :out_info If you used a capture card with DVD or MPEG settings, place those files in
CALL :out_info %dvdripto_parentdir%\foldername\ and then answer y to the question below.
ECHO.
IF NOT "%auto%"=="y" CALL :q_dvdsource
IF "%dvdsource%"=="y" (
  REM automation changes for q_driveletter are handled within the function b/c 
  REM important code related to ripping and dgindex is found there.
  CALL :index_dvd
) ELSE (
  REM q_avi must be called (even in "auto" mode) for avs files to be set up properly
  SET maxaudiobitrate=320000
  CALL :q_avi
)

REM ---------------------------------------------------------------------------
REM  Main procedure - Movie source verification and properties
REM 
REM Verify that AviSynth can load the source files. Also an opportunity to
REM extract media info.
REM ---------------------------------------------------------------------------

:verifysource
SETLOCAL ENABLEDELAYEDEXPANSION
ECHO.
CALL :out_info Verifying source...
ECHO.
IF EXIST "%projname%_verifysource.log" DEL "%projname%_verifysource.log"
IF EXIST "%projname%_verifysource.avs" DEL "%projname%_verifysource.avs"
REM Pass 1 - test avi pairs
IF DEFINED avifiles (
  SET pass1=
  REM Index the files
  SET count=1
  FOR %%G IN (%avifiles%) DO (
    SET [!count!]=%%G
    SET /A count=!count!+1
  )
  SET /A filetotal=!count!-1
  CALL :aviordirectshow ![1]!
  ECHO>> "%projname%_verifysource.avs" try{trim^(!callresult!,0,-1^)}catch^(err_msg^){WriteFileStart^(blankclip,"%projname%_verifysource.log","err_msg",append=true^)}
  REM Generate pairs
  FOR /L %%G IN (2,1,!filetotal!) DO (
    SET /A previous=%%G-1	
	CALL :aviordirectshow %%[!previous!]%%
    SET previous=!callresult!
	CALL :aviordirectshow ![%%G]!
    SET current=!callresult!	
    ECHO>> "%projname%_verifysource.avs" try{trim^(!previous!++!current!,0,-1^)}catch^(err_msg^){WriteFileStart^(blankclip,"%projname%_verifysource.log","err_msg",append=true^)}
  )
  REM test it...
  "%anri_dir%%vdub%\vdub.exe" /i "%anri_dir%RunNullVideoPass.vcf" "%projname%_verifysource.avs"
  IF NOT !ERRORLEVEL!==0 ECHO>> "%projname%_verifysource.log" vdub NullVideoPass failed
  IF NOT EXIST "%projname%_verifysource.log" SET avipass1=success
)

REM Pass 2 - all files appended (avi/dvd)
ECHO> "%projname%_verifysource.avs" try{import^("%projname%.avs"^)}catch^(err_msg^){WriteFileStart^(blankclip,"%projname%_verifysource.log","err_msg",append=true^)}
REM Grab some properties of the video while we're here..
ECHO>> "%projname%_verifysource.avs" WriteFileStart^("mediainfo.log",   """ "Width:" """,                   "last.Width",                   append=false^)
ECHO>> "%projname%_verifysource.avs" WriteFileStart^("mediainfo.log",   """ "Height:" """,                  "last.Height",                  append=true^)
ECHO>> "%projname%_verifysource.avs" WriteFileStart^("mediainfo.log",   """ "FrameCount:" """,              "last.FrameCount",              append=true^)
ECHO>> "%projname%_verifysource.avs" WriteFileStart^("mediainfo.log",   """ "FrameRate:" """,               "last.FrameRate",               append=true^)
ECHO>> "%projname%_verifysource.avs" WriteFileStart^("mediainfo.log",   """ "FrameRateNumerator:" """,      "last.FrameRateNumerator",      append=true^)
ECHO>> "%projname%_verifysource.avs" WriteFileStart^("mediainfo.log",   """ "FrameRateDenominator:" """,    "last.FrameRateDenominator",    append=true^)
ECHO>> "%projname%_verifysource.avs" WriteFileStart^("mediainfo.log",   """ "AudioRate:" """,               "last.AudioRate",               append=true^)
ECHO>> "%projname%_verifysource.avs" WriteFileStart^("mediainfo.log",   """ "AudioLength:" """,             "last.AudioLength",             append=true^)
ECHO>> "%projname%_verifysource.avs" WriteFileStart^("mediainfo.log",   """ "AudioLengthF:" """,            "last.AudioLengthF",            append=true^)
ECHO>> "%projname%_verifysource.avs" WriteFileStart^("mediainfo.log",   """ "AudioChannels:" """,           "last.AudioChannels",           append=true^)
ECHO>> "%projname%_verifysource.avs" WriteFileStart^("mediainfo.log",   """ "AudioBits:" """,               "last.AudioBits",               append=true^)
ECHO>> "%projname%_verifysource.avs" WriteFileStart^("mediainfo.log",   """ "IsAudioFloat:" """,            "last.IsAudioFloat",            append=true^)
ECHO>> "%projname%_verifysource.avs" WriteFileStart^("mediainfo.log",   """ "IsAudioInt:" """,              "last.IsAudioInt",              append=true^)
ECHO>> "%projname%_verifysource.avs" WriteFileStart^("mediainfo.log",   """ "HasAudio:" """,                "last.HasAudio",                append=true^)
ECHO>> "%projname%_verifysource.avs" WriteFileStart^("mediainfo.log",   """ "HasVideo:" """,                "last.HasVideo",                append=true^)
ECHO>> "%projname%_verifysource.avs" trim^(0,-1^)
REM test it...
"%anri_dir%%vdub%\vdub.exe" /i "%anri_dir%RunNullVideoPass.vcf" "%projname%_verifysource.avs"
IF NOT %ERRORLEVEL%==0 ECHO>> "%projname%_verifysource.log" vdub NullVideoPass failed
IF EXIST "%projname%_verifysource.log" (
  ECHO.
  CALL :out_error There was a problem loading the videos.
  ECHO contents of %projname%_verifysource.log:
  TYPE "%projname%_verifysource.log"
  ECHO.
  IF DEFINED avipass1 (
    CALL :out_info Anri ran two passes on your files. The first pass was successfull while the second pass was not. This indicates you are trying to join together more file than Anri can handle.
	CALL :out_info Anri can work around this by creating a smaller set of lossless files, but this will require extra disk space.
	ECHO.
	SET s=y
    SET /P s=Continue creating the new files? [^(y^),n]: 
	IF NOT "!s!"=="y" GOTO :DIE
	CALL :nmf_avi %avifiles%
	CALL :aviloaded
	CALL :verifysource
  ) ELSE (
    ECHO Possible causes:
    ECHO  - Path to video file no longer valid
    ECHO  - Video codec not installed properly
    ECHO  - The videos do not have the same resolution and/or framerate
    ECHO  - Anri doesn't recognize a character in the filename/path.
    ECHO.
    ECHO Ask for help in the Tech Support forum.
    ECHO Anri will now exit.
    ECHO.
    GOTO :DIE
  )
)
DEL "%projname%_verifysource.avs" > NUL
ENDLOCAL ENABLEDELAYEDEXPANSION & SET avifiles=%avifiles%
FOR /F "tokens=2 delims=:" %%G IN ('FIND "Width" mediainfo.log') DO SET nativewidth=%%G
FOR /F "tokens=2 delims=:" %%G IN ('FIND "Height" mediainfo.log') DO SET nativeheight=%%G


REM ---------------------------------------------------------------------------
REM  Main procedure - Game properties
REM 
REM  The purpose here is to find resolution, framerate and whether there are
REM  flickering effects in the game. An online database is maintained at
REM  http://speeddemosarchive.com/kb/index.php/DF to hold this information since
REM  there isn't really a way to do it programmatically. Probably need C++ for
REM  that... but even then. 
REM  
REM  SDA has decided on minimum quantizers of 17 and 19 for low/high resolution
REM  videos.
REM ---------------------------------------------------------------------------

:proc_gameproperties
CALL :out_cls_section GAME PROPERTIES
IF "%dvdsource%"=="n" (
  IF NOT "%auto%"=="y" (
    CALL :out_info Is this a PC game recorded with screen capture software, or simply a non-console run? If you say no, your video will be treated as NTSC / PAL.
    CALL :q_isPCGAME
  )
)
IF "%isPCGAME%"=="y" (
  IF NOT DEFINED d      (SET d=1)
  IF NOT DEFINED f      (SET f=1)
  IF NOT DEFINED twod   (SET twod=n)
  IF NOT DEFINED prog   (SET prog=y)
  GOTO proc_gameproperties_p2
)

IF NOT "%auto%"=="y" CALL :q_dfnd
IF "%dfnd_set%"=="y" GOTO dfnd_is_set
IF NOT "%auto%"=="y" CALL :q_d
IF NOT "%auto%"=="y" CALL :q_f
IF NOT "%f%"=="1" (SET twod=n) ELSE (
    IF NOT "%auto%"=="y" (
        CALL :q_2d
    )
)
IF NOT "%auto%"=="y" CALL :q_submit_dfnd
:dfnd_is_set

REM ---------------------------------------------------------------------------
REM  Main procedure - Video properties
REM 
REM  Wouldn't it be great if there was no more interlacing and everything was
REM  progressive? As you can see, if the video is progressive you pretty much
REM  skip the entire section. Anyways..
REM 
REM  The method for getting the field order is to open up an instance of vdub 
REM  with the video, the top half of the screen using Top Field First, and the
REM  bottom half using Bottom Field First. The user then plays it to see which
REM  one looks natural and chooses top or bottom accordingly.
REM  
REM  onepixel simply shifts one of the fields up or down by one pixel.
REM  
REM  TO DO: Describe nes, gba, deflicker.
REM ---------------------------------------------------------------------------

CALL :out_cls_section VIDEO PROPERTIES
IF NOT "%auto%"=="y" (
  CALL :out_info Progressive or interlaced? If you don't know, it's most likely interlaced ^(answer "n" to the question^). However, if your video is a PC screen capture ^(made using e.g. FRAPS or Camtasia^) and never touched a VCR or DVD recorder, then it may be progressive.
  CALL :q_prog
)
IF "%prog%"=="y" GOTO proc_gameproperties_p2
IF NOT "%auto%"=="y" CALL :q_fieldorder
IF NOT "%auto%"=="y" CALL :q_vhs
IF "%d%"=="1" GOTO proc_gameproperties_p2
REM Don't need to check pixelshift for F3 since F3 decimation is separatefields + selecteven + decimate plugin
IF NOT "%f%"=="2" IF NOT "%f%"=="3" (
    IF NOT "%auto%"=="y" CALL :q_pixelshift
)
IF NOT "%auto%"=="y" CALL :q_nes
IF "%nes%"=="y" GOTO proc_gameproperties_p2
IF NOT "%auto%"=="y" CALL :q_gba
IF "%gba%"=="y" (
  SET deflicker=y
  SET nativewidth=240
  SET nativeheight=160
  SET DARnum=3
  SET DARden=2
  GOTO proc_gameproperties_p2
)
IF NOT "%auto%"=="y" CALL :q_gameboy
IF "%gameboy%"=="y" (
  SET deflicker=y
  GOTO proc_gameproperties_p2
)
    
REM ---------------------------------------------------------------------------
REM  Main procedure - Content properties
REM 
REM  For trimming, we startup another vdub instance and ask the user to input
REM  frame numbers. The frame numbers will go into a single variable separated
REM  by spaces. There is currently no validation for entering a frame range
REM  like 50 to 30... or negative numbers. Users can enter dummy values and edit
REM  job_project.bat later on and it will still work.
REM 
REM  StatID.. not much to it. Three lines, quotations are allowed. Gets appended
REM  at beginning and end of video.
REM ---------------------------------------------------------------------------

:proc_gameproperties_p2
CALL :out_cls_section CONTENT PROPERTIES
IF NOT "%auto%"=="y" CALL :q_trim
IF "%trim%"=="y" (IF NOT "%auto%"=="y" CALL :q_trimming)
IF NOT "%auto%"=="y" IF NOT "%gba%"=="y" IF NOT "%gameboy%"=="y" IF NOT "%nes%"=="y" CALL :q_widescreen
IF NOT "%auto%"=="y" (CALL :q_statid)
IF "%statid%"=="y" (IF NOT "%auto%"=="y" CALL :q_statid_lines)

REM ---------------------------------------------------------------------------
REM  Main procedure - Check settings
REM 
REM  This is where you get taken when you run job_project.bat. A file compare
REM  is done to check if the user has edited job.bat. If it has been changed,
REM  or if there are missing AviSynth files, the files are rebuilt. So if
REM  someone is tinkering with the AviSynth files, they'd be wise to leave
REM  job.bat alone, else have their work be overwritten.
REM ---------------------------------------------------------------------------

:proc_check_settings
CD /D "%project_parentdir%\%projname%"
SET projdirpath=%CD%
CALL :filecompare "job_%PROJNAME%.bat" "job_%PROJNAME%.bak"
REM Yay batch code...
SET multipleif=false
IF %callresult%==0 IF EXIST "%PROJNAME%_LQ.avs" IF EXIST "%PROJNAME%_LQ_xvid.avs" IF EXIST "%PROJNAME%.avs" IF EXIST "%PROJNAME%_xvid.avs" IF EXIST "%PROJNAME%_HQ.avs" IF EXIST "%PROJNAME%_IQ.avs" IF EXIST "%PROJNAME%_XQ.avs" SET multipleif=true
IF %multipleif%==false (
  CALL :savesettings
  CALL :script_buildfiles
)

REM ---------------------------------------------------------------------------
REM  Main procedure - Check settings (continued)
REM 
REM  All necessary files are ready for the encoding stage. Show the user the
REM  current settings, then ask if they want to encode now. Saying no will reset
REM  some variables and take the user back to Game Properties (DFnD).
REM ---------------------------------------------------------------------------

IF NOT "%auto%"=="y" (
  CALL :check_settings
) ELSE (
  SET settings_good=y
)
IF NOT "%settings_good%"=="y" GOTO proc_check_settings_p2
CALL :out_cls_section READY TO ENCODE
CALL :out_info Your settings for this project have been saved to "job_%PROJNAME%.bat". To resume the project, double-click that file.
IF NOT "%auto%"=="y" (
  CALL :q_encodenow
) ELSE (
  SET start_encode=y
)
IF "%start_encode%"=="y" (GOTO proc_encode) ELSE (GOTO proc_close)
:proc_check_settings_p2
FOR %%A IN (dfnd_set d f twod fieldorder vhs onepixel nes gba gameboy deflicker trimarray) DO (SET %%A=)
SET batch=
DEL "job_%PROJNAME%.bat"
DEL "job_%PROJNAME%.bak"
GOTO proc_gameproperties

REM ---------------------------------------------------------------------------
REM  Main procedure - Encoding options
REM 
REM  Ask for H.264 LQ/MQ/HQ/IQ, and Xvid LQ/MQ.
REM 
REM  IF D1 and the user is encoding HQ/IQ/XQ, he will be asked whether
REM  he wants to encode a New Master File. This is to avoid using the extremely
REM  slow mvbob deinterlacer four times, one for each pass. Instead, it will be
REM  done once and encoded to the lossless Lagarith codec in Yv12 colorspace.
REM  This NMF will then be used to encode HQ/IQ/XQ
REM ---------------------------------------------------------------------------

:proc_encode
CALL :out_cls_section ENCODING OPTIONS
IF NOT "%auto%"=="y" CALL :select_qualities
REM Batch has limited boolean logic. I want an OR between hq/iq/xq.
IF "%d%"=="1" IF "%prog%"=="n" IF "%create_hq%"=="y" (
  CALL :NMF
) ELSE (
  IF "%create_iq%"=="y" (
    CALL :nmf
  ) ELSE (
    IF "%create_xq%"=="y" (
      CALL :nmf
    )
  )
)
REM IF "%not_encoding%"=="y" GOTO proc_close
REM see below comment for more about this
REM CALL :out_cls_info Now encoding.
MD %projname%_finished > NUL 2>&1
CALL :encode_movies

FOR %%G IN (*.bat) DO (
  ECHO>> %projname%_finished\%log% ----------------------------------------
  ECHO>> %projname%_finished\%log%  Contents of %%G
  ECHO>> %projname%_finished\%log% ----------------------------------------
  ECHO.>> %projname%_finished\%log%
  TYPE>> %projname%_finished\%log% "%%G"
  ECHO.>> %projname%_finished\%log%
  ECHO.>> %projname%_finished\%log%
  ECHO.>> %projname%_finished\%log%
)

FOR %%G IN (*.log) DO (
  ECHO>> %projname%_finished\%log% ----------------------------------------
  ECHO>> %projname%_finished\%log%  Contents of %%G
  ECHO>> %projname%_finished\%log% ----------------------------------------
  ECHO.>> %projname%_finished\%log%
  TYPE>> %projname%_finished\%log% "%%G"
  ECHO.>> %projname%_finished\%log%
  ECHO.>> %projname%_finished\%log%
  ECHO.>> %projname%_finished\%log%
)

ECHO>> %projname%_finished\%log% ----------------------------------------
ECHO>> %projname%_finished\%log%  Contents of project folder
ECHO>> %projname%_finished\%log% ----------------------------------------
ECHO.>> %projname%_finished\%log%
DIR >> %projname%_finished\%log%
ECHO.>> %projname%_finished\%log%
ECHO.>> %projname%_finished\%log%

FOR %%G IN (*.avs) DO (
  ECHO>> %projname%_finished\%log% ----------------------------------------
  ECHO>> %projname%_finished\%log%  Contents of %%G
  ECHO>> %projname%_finished\%log% ----------------------------------------
  ECHO.>> %projname%_finished\%log%
  TYPE>> %projname%_finished\%log% "%%G"
  ECHO.>> %projname%_finished\%log%
  ECHO.>> %projname%_finished\%log%
  ECHO.>> %projname%_finished\%log%
)

:proc_close
ECHO.
ECHO.
CALL :out_info All dun.
ECHO.
GOTO die


REM ------- QUESTIONS ABOUT MOVIE SOURCE -------

:q_projname

CALL :out_info Enter a project name. This name will be used as the basename for your encoded videos (e.g. the high quality video will be called projectname_HQ.mp4, etc.).
ECHO.
%CECHO% "{white on gray}All files associated with this project will appear in {navy on gray}%project_parentdir%\(project name)\{\n}"
%RESET_COLOR%
ECHO.
SET s=AC%random%
SET /P s=Project name [user input,(random number)]: 
CALL :set_var_nospace projname q_projname
ECHO %projname%|findStr /c:"%%">nul
IF %ERRORLEVEL%==0 (
  CALL :out_error Invalid value. You cannot have a percent sign.
  GOTO q_projname
)
GOTO :EOF


:q_dfnd
CALL :out_info The next few questions are about the game played in this video. SDA has a database of games we have seen in the past, which can answer some or all of the questions for you.
SET s=n
SET /P s=Do you want to use Anri-chan's games database [y] or enter the data yourself [n]? [y,(n)]: 
CALL :set_var_bool dfnd q_dfnd
IF "%dfnd%"=="y" CALL :dfnd
GOTO :EOF

:q_dvdsource
SET s=y
SET /P s=DVD/MPEG source [(y),n]: 
CALL :set_var_bool dvdsource q_dvdsource
GOTO :EOF


REM ---------------------------------------------------------------------------
REM  function: rip_dvd
REM  
REM  If IFO files are present, rip with Mplayer. Otherwise just a straight copy.
REM ---------------------------------------------------------------------------

:rip_dvd
SETLOCAL ENABLEDELAYEDEXPANSION
CALL :out_cls_section Rip DVD
CALL :q_driveletter
ECHO.
CALL :out_info Anri-chan will extract to the %dvdripto_parentdir% parent directory. Name a folder for your DVD files.
:rip_dvd_dir
SET /P dvdripto=Folder name: 
REM Validate
IF NOT DEFINED dvdripto (
  CALL :out_error You must enter a valid folder name.
  GOTO :rip_dvd_dir
) ELSE (
  MKDIR "%dvdripto_parentdir%\%dvdripto%"
  IF !ERRORLEVEL!==1 (
    CALL :out_error You must enter a valid folder name.
    GOTO :rip_dvd_dir
  )
)
SET dvdripto=%dvdripto_parentdir%\%dvdripto%
ECHO.
CALL :out_info Anri-chan will now extract everything needed from the DVD to %dvdripto%. Make sure you have enough hard drive space (up to 4.3 GB). This may take some time.
ECHO.
PAUSE
PUSHD %dvdripto%

IF EXIST %driveletter%:\VIDEO_TS (
  SET dvdsource=%driveletter%:\VIDEO_TS
  IF EXIST !dvdsource!\*.IFO (
    REM Create pgclist.txt
    SET ifolist=
    FOR %%G IN (!dvdsource!\VTS*.IFO) DO (
      (SET ifolist=!ifolist!%%~fG )
    )    
    "%anri_dir%pgccount.exe" !ifolist!

    IF "%advanced_mode%"=="true" (
      IF NOT "%auto%"=="y" (
        ECHO.
        CALL :out_info -advanced mode- Rip specific title numbers. Separate by spaces, or leave blank to rip all. You can look at pgclist.txt in the DVD file destination directory to see which titles will be ripped by default.
        SET s=
        SET /P s=Title numbers: 
      ) ELSE (
        SET s=%auto_Title_numbers%
      )
      IF DEFINED s (
        REN pgclist.txt pgclist.bak
        FOR %%G IN (!s!) DO (
          TYPE pgclist.bak | FIND "%%G," >> pgclist.txt
        )
      )
    )

    REM Rip the titles with Mplayer using info from pgclist.txt
    FOR /F "tokens=1,2 delims=," %%G IN (pgclist.txt) DO (
      SET str=%%~nH
      SET str=!str:~4,2!
      REM Add leading zeros to avoid sorting problems where 10 comes before 1.
      SET expandpgc=00000000000%%G
      SET expandpgc=!expandpgc:~-3!
      "%anri_dir%mplayer.exe" dvd://%%G -dvd-device !dvdsource! -dumpstream -dumpfile I!str!_!expandpgc!.vob 2>> %log%
    )
  ) ELSE (
    COPY "!dvdsource!\*" "%dvdripto%"
  )
) ELSE (
  IF EXIST %driveletter%:\DVD_RTAV (
    COPY "%driveletter%:\DVD_RTAV\*" "%dvdripto%"
  ) ELSE (
    ECHO Neither VIDEO_TS or DVD_RTAV folder was found on %driveletter%:\. Anri-chan is displeased.
    GOTO :die
  )
)
POPD
CALL :out_info finished ripping
PAUSE
ENDLOCAL ENABLEDELAYEDEXPANSION
GOTO :EOF


REM ---------------------------------------------------------------------------
REM  function: driveletter
REM 
REM  Ask for the drive letter.
REM ---------------------------------------------------------------------------

:q_driveletter
IF NOT "%auto%"=="y" (
  CALL :out_info Tip: If you already have your DVD source files on your hard drive, move them into C:\VIDEO_TS\ and select C as your drive letter.
  SET s=
  SET /P s=DVD Drive Letter: 
  CALL :set_var_letter driveletter q_driveletter
)
GOTO :EOF


REM ---------------------------------------------------------------------------
REM  function: q_avi
REM 
REM  User enters paths to avi files and/or folders containing avi files.
REM  
REM ---------------------------------------------------------------------------

:q_avi
IF "%auto%"=="y" GOTO aviloaded
SETLOCAL ENABLEDELAYEDEXPANSION
CALL :out_cls_section AVI SOURCE
CALL :out_info Enter the path to each avi file or folder. If specifying a folder, anri-chan will load the files in an alphabetical manner. The files must have the same resolution and framerate to be joined together.
%CECHO% "{navy on gray} - Type n to quit -{\n}"
%RESET_COLOR%
ECHO.
SET avifiles=
SET counter=1
:q_avi_p2
SET input=
SET /P input=avi#%counter%: 
REM User enters nothing
IF NOT DEFINED input (
  CALL :out_error You must enter a value, or type n to quit.
  GOTO :q_avi_p2
)
CALL :removequotations input
IF NOT "%input%"=="n" (
  REM User does not enter full path
  IF NOT "%input:~1,2%"==":\" (
    CALL :out_error Must be full path.
    GOTO :q_avi_p2
  )
  REM Remove trailing backslash
  IF "!input:~-1!"=="\" SET input=!input:~0,-1!
  REM Check if folder or file is specified
  DIR "%input%\" > NUL 2>&1
  IF "!ERRORLEVEL!"=="0" (
    REM Folder exists. Make avi file array.
    CALL :out_info folder detected
    FOR %%G IN ("%input%\*.avi") DO (
      (SET avifiles=!avifiles!"%%~fG" )
      ECHO avi#!counter!: %%~fG
	  SET /A counter=!counter! + 1
    )
	GOTO :q_avi_p2
  ) ELSE (
    REM Not a folder
	IF NOT EXIST "%input%" (
      CALL :out_error File does not exist, try again.
      GOTO :q_avi_p2
	)
	REM Not avi or avs
	IF NOT "%input:~-4%"==".avi" IF NOT "%input:~-4%"==".avs" (
      CALL :out_error Must be an avi file, try again.
      GOTO :q_avi_p2
    )
    (SET avifiles=!avifiles!"%input%" )
    SET /A counter=!counter! + 1
	GOTO :q_avi_p2
  )  
) ELSE (
  IF "!counter!"=="1" (
    CALL :out_error You must load at least one file.
    GOTO :q_avi_p2
  )
)
SET avifiles=!avifiles:~0,-1!
ENDLOCAL ENABLEDELAYEDEXPANSION & SET avifiles=%avifiles%
:aviloaded
REM ---------------------------------------------------------------------------
REM AVI files loaded, generate avs source lines.
REM ---------------------------------------------------------------------------
ECHO> "%projname%.avs" import^("%anri_dir%sda.avs"^)
ECHO>> "%projname%.avs" import^("%projdirpath%\plugins.avs"^)
SETLOCAL ENABLEDELAYEDEXPANSION
SET num=1
FOR %%G IN (%avifiles%) DO (
  IF NOT !num!==1 (
    ECHO>> "%projname%.avs" \++\ 
  )
  FOR /F "skip=4 delims=" %%H IN ('CALL "%anri_dir%cfourcc.exe" "%%~G"') DO ECHO>> fourcc.log %%H
  CALL :aviordirectshow %%G
  ECHO>> "%projname%.avs" !callresult!
  SET /A num=!num!+1
)
ENDLOCAL ENABLEDELAYEDEXPANSION
ECHO>> "%projname%.avs" converttorgb32
COPY /Y "%projname%.avs" "%projname%.bak" > NUL
GOTO :EOF


REM ---------------------------------------------------------------------------
REM  function: aviordirectshow
REM 
REM  Check fourcc, return avisource or directshowsource
REM  
REM ---------------------------------------------------------------------------

:aviordirectshow
FOR /F "skip=6 tokens=2 delims=: " %%H IN ('CALL "%anri_dir%cfourcc.exe" "%~1"') DO FIND /I "%%H" "%anri_dir%directshowsource_list.txt" > NUL
IF %ERRORLEVEL%==0 (
  SET callresult=directshowsource^("%~1"^)
) ELSE (
  SET callresult=avisource^("%~1"^)
)
GOTO :EOF

:q_isPCGAME
SET s=y
SET /P s=[(y),n]: 
CALL :set_var_bool isPCGAME q_isPCGAME
GOTO :EOF

:q_d
ECHO.
CALL :out_info "D" and "F" are letters used at SDA to refer to the video dimensions and framerate. D1 is full resolution and D4 is half resolution. F1 is full framerate, F2 is half framerate and F3 is 1/3 framerate.
ECHO.
CALL :out_info   Find D and F for your game at this URL:
CALL :out_info   http://speeddemosarchive.com/kb/index.php/DF
ECHO.
CALL :out_info If you don't see your game listed there, you can use the Extract Sample utility to make a sample video to post in the SDA Tech Support Forum. Someone there will look at the video and let you know what D and F are.
ECHO.
:q_d_p2
SET s=
SET /P s=D [1,4]: 
CALL :set_var_in d q_d_p2 14
GOTO :EOF

:q_f
SET s=
(SET /P s=F [1,2,3]: )
CALL :set_var_in f q_f 12345
GOTO :EOF

:q_prog
SET s=n
SET /P s=Progressive scan source? Answer n if you don't know [y,(n)]: 
CALL :set_var_bool prog q_prog
GOTO :EOF

REM ---------------------------------------------------------------------------
REM  function: q_fieldorder
REM 
REM  There's no fool proof method to detect field order programmatically. The
REM  next best thing is to show the user both, and let him decide which looks
REM  better.
REM  
REM  The script is simple enough, have a split screen with AssumeTFF and
REM  AssumeBFF. Whichever is chosen will be used in all AviSynth script.
REM ---------------------------------------------------------------------------

:q_fieldorder
ECHO.
CALL :out_info Virtualdub will now open with a split screen of your video. Find a scene with movement and use the slider or play button to play through it to see which one has smoother motion. Enter t for top, or b for bottom. If both look good, enter t.
PAUSE
ECHO.
COPY /B "%projname%.bak" "%projname%_fieldordertemp.avs" 1> NUL
ECHO>> "%projname%_fieldordertemp.avs" tff=last.AssumeTFF.SeparateFields.bilinearresize^(320,240^).subtitle^("t"^)
ECHO>> "%projname%_fieldordertemp.avs" bff=last.AssumeBFF.SeparateFields.bilinearresize^(320,240^).subtitle^("b"^)
ECHO>> "%projname%_fieldordertemp.avs" StackVertical^(tff,bff^)
START "determine field order" "%anri_dir%%vdub%\virtualdub.exe" "%projname%_fieldordertemp.avs"
:q_fieldorder_p2
SET s=
SET /P s=[t,b]: 
CALL :set_var_in fieldorder q_fieldorder_p2 tb
CALL :out_info You may now close the VirtualDub window.
DEL "%projname%_fieldordertemp.avs" > NUL
ECHO.
GOTO :EOF

REM ---------------------------------------------------------------------------
REM  function: q_pixelshift
REM  
REM  This displays 1.no change 2.deflicker 3. deflicker alt 4.one pixel bob 5.one pixel bob alt
REM  The user chooses the best one.  
REM ---------------------------------------------------------------------------

:q_pixelshift
SETLOCAL ENABLEDELAYEDEXPANSION
SET s=n
SET /P s=Check for bobbing (picture jumping up and down) [y,(n)]: 
CALL :set_var_bool s q_pixelshift
IF "%s%"=="n" (
  ENDLOCAL ENABLEDELAYEDEXPANSION
  GOTO :EOF
)
ECHO.
CALL :out_info Virtualdub will now open with a split screen of your video. Choose the one that has the least bobbing.
ECHO.
COPY /B "%projname%.bak" "%projname%_pixelshifttemp.avs" 1> NUL
IF "%fieldorder%"=="t" SET assume=AssumeTFF
IF "%fieldorder%"=="b" SET assume=AssumeBFF
ECHO>> "%projname%_pixelshifttemp.avs" %assume%
ECHO>> "%projname%_pixelshifttemp.avs" SeparateFields
ECHO>> "%projname%_pixelshifttemp.avs" method1=last.lanczos4resize^(int((last.height*4)/3),last.height^).subtitle^("1 - no change"^)
ECHO>> "%projname%_pixelshifttemp.avs" method2=last.lanczos4resize^(int((last.height*4)/3),last.height^).nate_retard_bob_2.subtitle^("2 - deflicker"^)
ECHO>> "%projname%_pixelshifttemp.avs" method3=last.lanczos4resize^(int((last.height*4)/3),last.height^).nate_alternate_retard_bob_2.subtitle^("3 - deflicker alternate"^)
ECHO>> "%projname%_pixelshifttemp.avs" method4=last.lanczos4resize^(int((last.height*4)/3),last.height^).nate_1_pixel_bob_fix.subtitle^("4 - one pixel bob fix"^)
ECHO>> "%projname%_pixelshifttemp.avs" method5=last.lanczos4resize^(int((last.height*4)/3),last.height^).nate_alternate_1_pixel_bob_fix.subtitle^("5 - one pixel bob fix alternate"^)
ECHO>> "%projname%_pixelshifttemp.avs" stackvertical^(stackhorizontal^(method1,method2,method3^),stackhorizontal^(blankclip(method1),method4,method5^)^)
START "determine pixel shift" "%anri_dir%%vdub%\virtualdub.exe" "%projname%_pixelshifttemp.avs"
:q_pixelshift_p2
SET s=1
SET /P s=[(1),2,3,4,5]: 
CALL :set_var_in pixelshift q_pixelshift_p2 12345
IF "%pixelshift%"=="2" SET deflicker=y
IF "%pixelshift%"=="3" SET deflickeralt=y
IF "%pixelshift%"=="4" SET onepixel=y
IF "%pixelshift%"=="5" SET onepixelalt=y
CALL :out_info You may now close the VirtualDub window.
DEL "%projname%_pixelshifttemp.avs" > NUL
ECHO.
ENDLOCAL ENABLEDELAYEDEXPANSION & (SET deflicker=%deflicker%) & (SET deflickeralt=%deflickeralt%) & (SET onepixel=%onepixel%) & (SET onepixelalt=%onepixelalt%)
GOTO :EOF

:q_vhs
SET s=n
SET /P s=Originally VHS [y,(n)]: 
CALL :set_var_bool vhs q_vhs
GOTO :EOF

:q_nes
SET s=n
SET /P s=NES [y,(n)]: 
CALL :set_var_bool nes q_nes
GOTO :EOF

:q_gba
SET s=n
SET /P s=Game Boy Advance [y,(n)]: 
CALL :set_var_bool gba q_gba
GOTO :EOF

:q_gameboy
SET s=n
SET /P s=Game Boy [y,(n)]: 
CALL :set_var_bool gameboy q_gameboy
GOTO :EOF

:q_2d
SET s=
SET /P s=2D game [y,n]: 
CALL :set_var_bool twod q_2d
GOTO :EOF

:q_trim
CALL :out_info Trimming lets you cut out frames from the existing movie so you only keep the run itself.
:q_trim_p2
SET s=n
SET /P s=Do you want to trim off unwanted content in this video? [y,(n)]: 
CALL :set_var_bool trim q_trim_p2
GOTO :EOF

:q_widescreen
SETLOCAL ENABLEDELAYEDEXPANSION
ECHO.
CALL :out_info Set the display aspect ratio / widescreen. By default the aspect ratio is set to 4/3 or your PC game's native aspect ratio. You can also enter a custom aspect ratio in fraction format.
:q_widescreen_input
SET s=n
SET /P s=Apply 16/9 widescreen [y, #/#, (n)]: 
FOR /F "tokens=1,2 delims=:/, " %%G IN ("%s%") DO (
  IF "%%G" EQU "y" (
    (SET DARnum=16)
    (SET DARden=9)
  ) ELSE (
    IF "%%G" EQU "n" (
      IF "%isPCGAME%"=="y" (
        (SET DARnum=%nativewidth%)
        (SET DARden=%nativeheight%)
      ) ELSE (
        (SET DARnum=4)
        (SET DARden=3)
      )
    ) ELSE (
      ECHO %%G|findStr "[^0-9]">NUL
      IF NOT !ERRORLEVEL!==0 (
        ECHO %%H|findStr "[^0-9]">NUL
        IF NOT !ERRORLEVEL!==0 (
          (SET DARnum=%%G)
          (SET DARden=%%H)
        ) ELSE (
          CALL :out_error Invalid value.
          GOTO :q_widescreen_input
        )
      ) ELSE (
        CALL :out_error Invalid value.
        GOTO :q_widescreen_input
      )
    )
  )
)
ENDLOCAL ENABLEDELAYEDEXPANSION & (SET DARnum=%DARnum%) & (SET DARden=%DARden%)
GOTO :EOF


REM ---------------------------------------------------------------------------
REM  function: q_trimming
REM 
REM  Create an array of numbers separated by spaces which will be used later on
REM  when writing to the AviSynth scripts.
REM  
REM  There isn't much validation yet. A modulus of 2 is used to make sure there's
REM  an even number of values. No checking to see if the frame ranges are valid
REM  yet. No checking of negative values either.
REM ---------------------------------------------------------------------------

:q_trimming
ECHO.
CALL :out_info VirtualDub will now open with a low quality temporary version of the source video. Use the slider at the bottom of the VirtualDub window to locate the first and last frame numbers of the part of the video you WANT TO KEEP.
ECHO.
CALL :out_info You can specify multiple ranges of frames. - Type n to quit -
PAUSE
ECHO.
COPY /B "%projname%.bak" "%projname%_trimtemp.avs" 1> NUL
ECHO>> "%projname%_trimtemp.avs" Lanczos4Resize^(320,round^(last.height*^(320.000/last.width^)^)^)
ECHO>> "%projname%_trimtemp.avs" last.height %% 2 == 1 ? AddBorders^(0,0,0,1^) : NOP
ECHO>> "%projname%_trimtemp.avs" last
START "trimming vdub" "%anri_dir%%vdub%\virtualdub.exe" "%projname%_trimtemp.avs"
SET trimarray=
SET counterA=0
SET counterB=1
:trimloop
SET /A counterC=%counterA%/2+1
(SET qframe=Range#%counterC%/Frame#%counterB%: )
CALL :q_trimval
IF NOT "%s%"=="n" (
  (SET trimarray=%trimarray%%trimval% )
  SET /A counterA=%counterA%+1
  SET /A counterB=%counterB%+1
  GOTO trimloop
) ELSE (
  IF %counterA%==0 (
    CALL :out_info No values entered, cancelling trim.
    SET trim=n
    PAUSE
  ) ELSE (
    SETLOCAL ENABLEDELAYEDEXPANSION
    SET /A countermodulus="!counterA!%%2"
    IF !countermodulus!==1 (
      CALL :out_error DETECTED ODD NUMBER OF FRAME INPUTS.
      ENDLOCAL ENABLEDELAYEDEXPANSION
      GOTO trimloop
    )
    ENDLOCAL ENABLEDELAYEDEXPANSION
  )
)
DEL "%projname%_trimtemp.avs"
GOTO :EOF

:q_trimval
IF "%qframe%"=="" (SET qframe=Frame#: )
SET s=
SET /P s=%qframe%
IF NOT "%s%"=="n" CALL :set_var_number trimval q_trimval
GOTO :EOF

:q_statid
CALL :out_cls_section Station ID
CALL :out_info Set the info shown on the Station ID (the clip at the start of an SDA movie). Run the Station ID Preview program for a preview.
SET statid1=
SET statid2=
SET statid3=
:q_statid_p2
SET s=n
ECHO Do you want to append an SDA Station ID to the front and end of this video?
SET /P s=[y,(n)]: 
CALL :set_var_bool statid q_statid_p2
GOTO :EOF

:q_statid_lines
ECHO.
CALL :out_info Line 1 is normally the runner's name. Line 2 (and Line 3 if necessary) normally include the game name, the type of run and the time to completion. Tip: type \n to add extra line breaks.
SET /P statid1=Station ID Line 1: 
SET /P statid2=Station ID Line 2: 
SET /P statid3=Station ID Line 3: 
IF NOT DEFINED statid1 (SET statid1= )
IF NOT DEFINED statid2 (SET statid2= )
IF NOT DEFINED statid3 (SET statid3= )
REM Replace quotes from user
SET statid1=%statid1:"="+chr(34)+"%
SET statid2=%statid2:"="+chr(34)+"%
SET statid3=%statid3:"="+chr(34)+"%
ECHO.
CALL :out_info StatID type
:q_statid_lines_commentary
SET s=n
SET /P s=Do you plan on having audio commentary on track 2? [y,(n)]: 
CALL :set_var_bool statid_commentary q_statid_lines_commentary
:q_statid_lines_type
SET s=n
SET /P s=Do you want a blank Station ID with only the text? [y,(n)]: 
CALL :set_var_bool statid_alternative q_statid_lines_type
GOTO :EOF

:q_encodenow
SET s=y
SET /P s="Do you want to start encoding now? [(y),n]: "
CALL :set_var_bool start_encode q_encodenow
GOTO :EOF

:q_nmf
SET s=
SET /P s=Create nmf? [y,n]: 
CALL :set_var_bool create_nmf q_nmf
GOTO :EOF

:q_update_anri
SET s=n
SET /P s="Do you want to update Anri-chan's games database? [y,(n)]: "
CALL :set_var_bool check_now q_update_anri
GOTO :EOF

:q_submit_dfnd
ECHO.
CALL :out_info You didn't use the Anri-chan DFnD database. Does that mean that it didn't have your game? If so, we'd love it if you posted the "D", "F" and "2D Game" info you just entered here, into our DFnD updates topic on SDA, so we can add it to the next version of the database. You don't need to register to do so and it only takes a few seconds.
ECHO.
SET s=n
SET /P s="Submit this game's DFnD data to SDA? [y,(n)]: "
CALL :set_var_bool submit_dfnd q_submit_dfnd
IF "%submit_dfnd%"=="n" GOTO :EOF
START http://speeddemosarchive.com/forum/index.php?action=post;topic=6416.0
CALL :out_info Thanks!
PAUSE
GOTO :EOF


REM ------- DFND SECTION -------

:dfnd
CALL :q_update_anri
IF "%check_now%"=="y" (
IF EXIST "dfnd_data_temp.bat" DEL "dfnd_data_temp.bat"
IF EXIST "dfnd_titles_temp.bat" DEL "dfnd_titles_temp.bat"
"%anri_dir%wget.exe" http://speeddemosarchive.com/anrichan/dfnd_data_temp.bat
"%anri_dir%wget.exe" http://speeddemosarchive.com/anrichan/dfnd_titles_temp.bat
REM can't write to the anri-chan dir in vista...
IF EXIST "dfnd_data_temp.bat" MOVE /Y "dfnd_data_temp.bat" "%appdata%\dfnd_data.bat"
IF EXIST "dfnd_titles_temp.bat" MOVE /Y "dfnd_titles_temp.bat" "%appdata%\dfnd_titles.bat"
CALL :out_info Anri-chan updated.
)

SET nodb=n
IF NOT EXIST "%anri_dir%dfnd_titles.bat" SET nodb=y
IF NOT EXIST "%anri_dir%dfnd_data.bat" SET nodb=y
IF "%nodb%"=="y" (
	CALL :out_error The DFnD database was not found in Anri-chan's data directory.
	GOTO :EOF
)

SET dfnd_titlesfile=dfnd_titles.bat
SET dfnd_titles="%appdata%\%dfnd_titlesfile%"
IF NOT EXIST "%appdata%\%dfnd_titlesfile%" SET dfnd_titles="%anri_dir%%dfnd_titlesfile%"

SET dfnd_datafile=dfnd_data.bat
SET dfnd_data="%appdata%\%dfnd_datafile%"
IF NOT EXIST "%appdata%\%dfnd_datafile%" SET dfnd_data="%anri_dir%%dfnd_datafile%"

CALL :out_info Ignore "The" in a game's title when answering this question: in the case of games from the "The Legend of Zelda" series, enter Z. For .hack games, enter D.
:dfnd_letter
SET s=
SET /P s="Enter the first letter of the game's title: "
CALL :set_var_letter dfnd_letter dfnd_letter
:dfnd_list
CALL %dfnd_titles% | MORE
PAUSE
ECHO.
:dfnd_code
CALL :out_info If your game was not shown, enter L to select another letter or X to enter details manually. Enter R to repeat the list of games.
SET s=
SET /P s="Enter the game's code (shown at the left, not including the colon): "
IF /I "%s%"=="l" GOTO dfnd_letter
IF /I "%s%"=="x" GOTO :EOF
IF /I "%s%"=="r" GOTO dfnd_list
CALL %dfnd_data%
IF NOT "%dfnd_set%"=="y" (
	CALL :out_error A game with code %s% was not found.
	GOTO :dfnd_code
)
CALL :out_info Set data successfully.
PAUSE
GOTO :EOF


REM ------- SUBROUTINES TO VALIDATE/SET VARIABLES -------

:set_var_bool
IF "%s%"=="y" (
	SET %1=y
	GOTO :EOF
)
IF "%s%"=="n" (
	SET %1=n
	GOTO :EOF
)
CALL :out_error Invalid value. Please enter Y (Yes) or N (No).
GOTO :%2

:set_var_letter
ECHO %s%|findStr /i "^[a-z]$">nul
IF %ERRORLEVEL%==0 (
	SET %1=%s%
	GOTO :EOF
) ELSE (
	CALL :out_error Invalid value. Please enter a single letter.
	GOTO :%2
)

:set_var_number
ECHO %s%|findStr "[^0-9]">nul
IF %ERRORLEVEL%==0 (
	CALL :out_error Invalid value. Please enter a number.
	GOTO :%2
)
IF "%3"=="" GOTO :napproved
IF %s% GTR %3% (
	CALL :out_error Invalid value. The maximum value is %3.
	GOTO :%2
)
:napproved
SET %1=%s%
GOTO :EOF

:set_var_nospace
ECHO %s%|findStr /c:" ">nul
IF %ERRORLEVEL%==0 (
	CALL :out_error Invalid value. You cannot have a space.
	GOTO :%2
) ELSE (
	SET %1=%s%
	GOTO :EOF
)

:set_var_notnull
IF NOT DEFINED s (
	CALL :out_error Invalid value. You must enter a value.
	GOTO :%2
) ELSE (
	SET %1=%s%
	GOTO :EOF
)

:set_var_in
ECHO %s%|findStr "^[%3]$">nul
IF %ERRORLEVEL%==0 (
	SET %1=%s%
	GOTO :EOF
) ELSE (
	CALL :out_error Invalid value. Please enter one of the suggested values only.
	GOTO :%2
)

REM ------- FILE HANDLING -------

:make_projdir
CD /D "%project_parentdir%"
IF NOT EXIST "%projname%" MD "%projname%"
CD /D "%projname%"
SET projdirpath=%CD%
SET in_projdir=y
COPY /Y "%anri_dir%%dgmpgdec_dir%\infotemplate.avs" > NUL
COPY /Y "%anri_dir%statid.png" > NUL
COPY /Y "%anri_dir%statid_alternative.png" > NUL
MD %projname%_finished
GOTO :EOF

:wipe_projdir
IF NOT "%in_projdir%"=="y" CALL :make_projdir
IF EXIST "%projname%.avs" DEL *.avs *.d2v *.wav
IF EXIST "job_%PROJNAME%.bat" DEL job_%PROJNAME%.bat
GOTO :EOF

:wipe_avs
IF EXIST "%projname%.avs" DEL *.avs
COPY /B "%projname%.bak" "%projname%.avs" 1> NUL
COPY /B "plugins.bak" "plugins.avs" 1> NUL
GOTO :EOF

REM ---------------------------------------------------------------------------
REM  function: load_plugins
REM
REM  All plugins used by anrichan should be contained in its own directory. Scan
REM  the plugins folder and write plugins.avs which will later be used for all
REM  scripts. We should never have to refer to the avisynth folder.
REM ---------------------------------------------------------------------------

:load_plugins
IF EXIST plugins.avs DEL plugins.avs
FOR %%G IN ("%anri_dir%plugins\*") DO (
  IF %%~xG==.dll ECHO>> "plugins.avs" loadplugin^("%%~fG"^)
  IF %%~xG==.avs ECHO>> "plugins.avs" import^("%%~fG"^)
)
COPY /B "plugins.avs" "plugins.bak" 1> NUL
GOTO :EOF

REM ---------------------------------------------------------------------------
REM  function: index_dvd
REM 
REM  Show a list of ripped DVDs. Cycle through the user's choices, indexing
REM  VOB/VRO files one by one. Run a preview as well to get the dgindex log.
REM  The log gets created in the vob folder, so it needs to be moved to the
REM  project folder. Used to determine maxaudiobitrate. Everything that's been
REM  done so far (ripping and indexing) should be transparent with the rest of
REM  the program. All that matters is creating a valid project.avs.
REM ---------------------------------------------------------------------------

:index_dvd
SETLOCAL ENABLEDELAYEDEXPANSION
CALL :out_cls_info Here is the list of DVD/MPEG files in %dvdripto_parentdir%\. Select one or more by typing in the number, or numbers separated by a space. If you select more than one, the files will be joined in the order you specify.
ECHO.
%CECHO% "{navy on gray}Note that joining different DVD/MPEG files is only recommended if it's of the same game.  The settings you choose later in editing will be applied to the whole project which can cause problems since different games will possibly need different settings.{\n}"
%RESET_COLOR%
ECHO.
SET index=0
PUSHD %dvdripto_parentdir%
FOR /D %%G IN (*) DO (
  SET /a index+=1
  SET dvdfolder!index!=%%G
  IF EXIST %%G\*.v* (
    ECHO  !index!. %%G
  ) ELSE (
    IF EXIST %%G\*.mpg (
      ECHO  !index!. %%G
    ) ELSE (
      IF EXIST %%G\*.mpeg (
        ECHO  !index!. %%G
      ) ELSE (
        ECHO  !index!. %%G - no VOB or VRO files found - empty?
      )
    )
  )
)
POPD
ECHO.
:index_dvd_choice
SET dvdchoice=0
SET /P dvdchoice=[1-%index%]: 
REM Start - Validate
FOR %%G IN (%dvdchoice%) DO (
  IF NOT DEFINED dvdfolder%%G (
    CALL :out_error Folder %%G was not found.
    GOTO :index_dvd_choice
  )
)
REM End - Validate

ECHO.
CALL :out_info Now indexing MPEG-2 ...

REM Start - AVS prep
IF EXIST %projname%.avs DEL %projname%.avs
ECHO> %projname%.avs loadplugin^("%anri_dir%%dgmpgdec_dir%\DGDecode.dll"^)
ECHO>> %projname%.avs import^("%anri_dir%sda.avs"^)
ECHO>> %projname%.avs import^("%projdirpath%\plugins.avs"^)
REM End - AVS prep

SET num=1
SET maxaudiobitrate=0
FOR %%G IN (%dvdchoice%) DO (
  FOR %%H IN ("%dvdripto_parentdir%\!dvdfolder%%G!\*.V*" "%dvdripto_parentdir%\!dvdfolder%%G!\*.MPG" "%dvdripto_parentdir%\!dvdfolder%%G!\*.MPEG" ) DO (
    IF %%~zH GTR 5000 (
      REM Run current vob through dgindex. Set to demux all tracks. Place vid,aud,delay info into temporary avs file.
      "%anri_dir%%dgmpgdec_dir%\dgindex.exe" -IF=[%%H] -OF=[%projname%%%~nH] -PREVIEW -exit
      MOVE /Y "%dvdripto_parentdir%\!dvdfolder%%G!\%%~nH.log" "%projdirpath%\%projname%_!num!_%%~nH.log"
      "%anri_dir%%dgmpgdec_dir%\dgindex.exe" -IF=[%%H] -OM=2 -OF=[%projname%_!num!_%%~nH] -AT=[infotemplate.avs] -exit
      REM If there's more than one file to be joined, they must be appended together.
      IF NOT !num!==1 ECHO>> %projname%.avs \++\
      REM Detect audio type, set vid,aud,delay to parameters a, b and c, generate source line.
      IF EXIST "%projname%_!num!_*.ac3" (
        FOR /F "tokens=1,2,3 delims=," %%A IN ('TYPE "%projname%_!num!_%%~nH.avs"') DO (
          ECHO>> %projname%.avs AC3source^(MPEG2source^("%%A"^,upConv=2^),"%%B"^).converttorgb32.DelayAudio^(%%C^)
        )
      ) ELSE (
        IF EXIST "%projname%_!num!_*.mp*" (
          FOR /F "tokens=1,2,3 delims=," %%A IN ('TYPE "%projname%_!num!_%%~nH.avs"') DO (
            ECHO>> %projname%.avs AudioDub^(MPEG2source^("%%A"^,upConv=2^),mpasource^("%%B"^)^).converttorgb32.DelayAudio^(%%C^)
          )
        ) ELSE (
          IF EXIST "%projname%_!num!_*.wav" (
            FOR /F "tokens=1,2 delims=," %%A IN ('TYPE "%projname%_!num!_%%~nH.avs"') DO (
              ECHO>> %projname%.avs AudioDub^(MPEG2source^("%%A"^,upConv=2^),wavsource^("%%B"^)^).converttorgb32
            )
          )
        )
      )
      REM Find max bitrate, unless PCM which will make it 320000
      FINDSTR /C:PCM "%projname%_!num!_%%~nH.log" > NUL
      IF !ERRORLEVEL!==0 (
        SET maxaudiobitrate=320000
      ) ELSE (
        FOR /F "tokens=*" %%N in ('FINDSTR /C:Audio "%projname%_!num!_%%~nH.log"') DO SET bitrate=%%N
        SET bitrate=!bitrate:~-3!000
        IF !bitrate! GTR !maxaudiobitrate! (
          SET maxaudiobitrate=!bitrate!
        )
      )
      REM Delete infotemplate child
      DEL "%projname%_!num!_%%~nH.avs"
      SET /A num+=1
    )
  )
)
REM Just in case
IF %maxaudiobitrate%==0 SET maxaudiobitrate=320000
ENDLOCAL ENABLEDELAYEDEXPANSION & SET maxaudiobitrate=%maxaudiobitrate%
COPY /Y "%projname%.avs" "%projname%.bak" > NUL
IF %maxaudiobitrate% GTR 320000 SET maxaudiobitrate=320000
GOTO :EOF


REM ---------------------------------------------------------------------------
REM  function: nmf
REM 
REM  
REM ---------------------------------------------------------------------------

:nmf
SETLOCAL ENABLEDELAYEDEXPANSION
CALL :out_cls_section New Master File
CALL :out_info NMF: New Master File refers to an intermediate source video file in the encoding process, usually one saved after deinterlacing (to avoid slow deinterlacing during each pass for each quality of output). 
ECHO.
CALL :out_info You have chosen to encode HQ/IQ/XQ. We can speed up the encoding process by creating a NMF. ^^! BEWARE ^^! The new file can be extremely large, somewhere around 36 to 72 GB per hour. Make sure you have enough hard drive space.
ECHO.
CALL :q_nmf
ECHO.
IF %create_nmf%==n (
  ENDLOCAL ENABLEDELAYEDEXPANSION & SET create_nmf=%create_nmf%
  GOTO :EOF
)
SET counterA=1
SET counterB=0
REM Set lagarith to yv12 temporarily.
IF DEFINED LOCALAPPDATA (
  REM Vista/7
  IF NOT EXIST "%LOCALAPPDATA%\VirtualStore\Windows" MD "%LOCALAPPDATA%\VirtualStore\Windows"
  IF EXIST "%LOCALAPPDATA%\VirtualStore\Windows\lagarith.bak" DEL "%LOCALAPPDATA%\VirtualStore\Windows\lagarith.bak"
  IF EXIST "%LOCALAPPDATA%\VirtualStore\Windows\lagarith.ini" REN "%LOCALAPPDATA%\VirtualStore\Windows\lagarith.ini" lagarith.bak
  ECHO> "%LOCALAPPDATA%\VirtualStore\Windows\lagarith.ini" [settings]
  ECHO>> "%LOCALAPPDATA%\VirtualStore\Windows\lagarith.ini" lossy_option=3
  IF %NUMBER_OF_PROCESSORS% GTR 1 (
    ECHO>> "%LOCALAPPDATA%\VirtualStore\Windows\lagarith.ini" multithreading=1
  ) ELSE (
    ECHO>> "%LOCALAPPDATA%\VirtualStore\Windows\lagarith.ini" multithreading=0
  )
) ELSE (
  IF EXIST "%WINDIR%\lagarith.bak" DEL "%WINDIR%\lagarith.bak"
  IF EXIST "%WINDIR%\lagarith.ini" REN "%WINDIR%\lagarith.ini" lagarith.bak
  ECHO> "%WINDIR%\lagarith.ini" [settings]
  ECHO>> "%WINDIR%\lagarith.ini" lossy_option=3
  IF %NUMBER_OF_PROCESSORS% GTR 1 (
    ECHO>> "%WINDIR%\lagarith.ini" multithreading=1
  ) ELSE (
    ECHO>> "%WINDIR%\lagarith.ini" multithreading=0
  )
)
DEL "%projname%_XQ_nmf.avs" > NUL 2>&1
:nmf_vdubloop
COPY /Y %projname%_XQ.avs %projname%_HQIQXQ_%counterA%.avs > NUL
ECHO>> %projname%_HQIQXQ_%counterA%.avs Trim^(floor^(last.framecount/%NUMBER_OF_PROCESSORS%.000*%counterB%.000^), floor^(last.framecount/%NUMBER_OF_PROCESSORS%.000*%counterA%.000^)-1^)
ECHO>> %projname%_XQ_nmf.avs avisource^("%projname%_HQIQXQ_%counterA%.avi"^)
DEL "%projname%_HQIQXQ_%counterA%.avi" > NUL 2>&1
START /LOW /B "encoding nmf section %counterA%" "%anri_dir%%vdub%\vdub.exe" "%projname%_HQIQXQ_%counterA%.avs" /i "%anri_dir%nmf.vcf" "%projname%_HQIQXQ_%counterA%.avi" > NUL
SET /A counterA=%counterA% + 1
SET /A counterB=%counterB% + 1
IF %counterA% LEQ %NUMBER_OF_PROCESSORS% (
  ECHO>> %projname%_XQ_nmf.avs \++\
  GOTO nmf_vdubloop
)
COPY /Y %projname%_XQ_nmf.avs %projname%_IQ_nmf.avs > NUL
COPY /Y %projname%_XQ_nmf.avs %projname%_HQ_nmf.avs > NUL
REM ### XQ ###
ECHO>> "%projname%_XQ_nmf.avs" converttoyv12
ECHO>> "%projname%_XQ_nmf.avs" changefps(last.framerate)
ECHO>> "%projname%_XQ_nmf.avs" WriteFileStart^("SAR_%projname%_XQ.log","last.width",""" "," """, "last.height",append=false^)
REM ### IQ ###
ECHO>> "%projname%_IQ_nmf.avs" converttorgb32
ECHO>> "%projname%_IQ_nmf.avs" last.height ^> 1000 ? ^(last.width ^> 720 * %DARnum%./%DARden% ? lanczos4resize^(ceil^(720 * %DARnum%./%DARden%^),720^) : lanczos4resize^(last.width,720^)^) : ^(last.width ^> last.height * %DARnum%./%DARden% ? lanczos4resize^(ceil^(last.height * %DARnum%./%DARden%^),last.height^) : NOP^)
ECHO>> "%projname%_IQ_nmf.avs" last.height %% 2 == 1 ? AddBorders^(0,0,0,1^) : NOP
ECHO>> "%projname%_IQ_nmf.avs" last.width %% 4 ^<^> 0 ? AddBorders^(floor^(^(4 - last.width %% 4^) / 2.^), 0, ceil^(^(4 - last.width %% 4^) / 2.^), 0^) : NOP
ECHO>> "%projname%_IQ_nmf.avs" converttoyv12
ECHO>> "%projname%_IQ_nmf.avs" changefps(last.framerate)
ECHO>> "%projname%_IQ_nmf.avs" WriteFileStart^("SAR_%projname%_IQ.log","last.width",""" "," """, "last.height",append=false^)
REM ### HQ ###
ECHO>> "%projname%_HQ_nmf.avs" converttorgb32
ECHO>> "%projname%_HQ_nmf.avs" last.height ^> 700 ? ^(last.width ^> 480 * %DARnum%./%DARden% ? lanczos4resize^(ceil^(480 * %DARnum%./%DARden%^),480^) : lanczos4resize^(last.width,480^)^) : ^(last.width ^> last.height * %DARnum%./%DARden% ? lanczos4resize^(ceil^(last.height * %DARnum%./%DARden%^),last.height^) : NOP^)
ECHO>> "%projname%_HQ_nmf.avs" last.height %% 2 == 1 ? AddBorders^(0,0,0,1^) : NOP
ECHO>> "%projname%_HQ_nmf.avs" last.width %% 4 ^<^> 0 ? AddBorders^(floor^(^(4 - last.width %% 4^) / 2.^), 0, ceil^(^(4 - last.width %% 4^) / 2.^), 0^) : NOP
ECHO>> "%projname%_HQ_nmf.avs" converttoyv12
ECHO>> "%projname%_HQ_nmf.avs" changefps(last.framerate)
ECHO>> "%projname%_HQ_nmf.avs" WriteFileStart^("SAR_%projname%_HQ.log","last.width",""" "," """, "last.height",append=false^)

:nmf_waitingloop
ECHO %time%  Encoding nmf...
"%anri_dir%TIMEOUT" 20 > NUL
"%anri_dir%TASKLIST" | find "vdub.exe" > NUL
IF %ERRORLEVEL%==0 GOTO nmf_waitingloop
ECHO.
CALL :out_info NMF successfully created. Continuing with encoding process in 5 seconds...
ECHO.
"%anri_dir%TIMEOUT" 5 > NUL
IF DEFINED LOCALAPPDATA (
  IF EXIST "%LOCALAPPDATA%\VirtualStore\Windows\lagarith.bak" (
    DEL "%LOCALAPPDATA%\VirtualStore\Windows\lagarith.ini"
	REN "%LOCALAPPDATA%\VirtualStore\Windows\lagarith.bak" lagarith.ini
  )
) ELSE (
  IF EXIST "%WINDIR%\lagarith.bak" (
    DEL "%WINDIR%\lagarith.ini"
	REN "%WINDIR%\lagarith.bak" lagarith.ini
  )
)
ENDLOCAL ENABLEDELAYEDEXPANSION & SET create_nmf=%create_nmf%
GOTO :EOF


REM ---------------------------------------------------------------------------
REM  function: nmf_avi
REM 
REM  
REM ---------------------------------------------------------------------------

:nmf_avi
SETLOCAL ENABLEDELAYEDEXPANSION
REM Set lagarith to yv12 temporarily.
IF DEFINED LOCALAPPDATA (
  REM Vista/7
  IF NOT EXIST "%LOCALAPPDATA%\VirtualStore\Windows" MD "%LOCALAPPDATA%\VirtualStore\Windows"
  IF EXIST "%LOCALAPPDATA%\VirtualStore\Windows\lagarith.bak" DEL "%LOCALAPPDATA%\VirtualStore\Windows\lagarith.bak"
  IF EXIST "%LOCALAPPDATA%\VirtualStore\Windows\lagarith.ini" REN "%LOCALAPPDATA%\VirtualStore\Windows\lagarith.ini" lagarith.bak
  ECHO> "%LOCALAPPDATA%\VirtualStore\Windows\lagarith.ini" [settings]
  ECHO>> "%LOCALAPPDATA%\VirtualStore\Windows\lagarith.ini" lossy_option=3
  IF %NUMBER_OF_PROCESSORS% GTR 1 (
    ECHO>> "%LOCALAPPDATA%\VirtualStore\Windows\lagarith.ini" multithreading=1
  ) ELSE (
    ECHO>> "%LOCALAPPDATA%\VirtualStore\Windows\lagarith.ini" multithreading=0
  )
) ELSE (
  IF EXIST "%WINDIR%\lagarith.bak" DEL "%WINDIR%\lagarith.bak"
  IF EXIST "%WINDIR%\lagarith.ini" REN "%WINDIR%\lagarith.ini" lagarith.bak
  ECHO> "%WINDIR%\lagarith.ini" [settings]
  ECHO>> "%WINDIR%\lagarith.ini" lossy_option=3
  IF %NUMBER_OF_PROCESSORS% GTR 1 (
    ECHO>> "%WINDIR%\lagarith.ini" multithreading=1
  ) ELSE (
    ECHO>> "%WINDIR%\lagarith.ini" multithreading=0
  )
)
DEL %projname%_nmfbatch* > NUL 2>&1
SET counterA=1
SET counterB=1
REM Generate avs batches, up to 20 files being appended.
FOR %%G IN (%*) DO (
  IF !counterB! GTR 20 (
    SET /A counterA=!counterA! + 1
	SET counterB=1
  )
  SET expandcounterA=0000000!counterA!
  SET expandcounterA=!expandcounterA:~-3!
  IF !counterB! GTR 1 ECHO>> %projname%_nmfbatch!expandcounterA!.avs \++\
  CALL :aviordirectshow %%G
  ECHO>> %projname%_nmfbatch!expandcounterA!.avs !callresult!
  SET /A counterB=!counterB! + 1
)
REM Encode them in vdub
SET avifiles=
FOR %%G IN (%projname%_nmfbatch*) DO (
  ECHO Encoding %%~fG...
  START /LOW /B /WAIT "encoding nmf %%G" "%anri_dir%%vdub%\vdub.exe" "%%G" /i "%anri_dir%nmf.vcf" "%%~nG.avi" > NUL
  (SET avifiles=!avifiles!"%%~dpnG.avi" )
)
CALL :out_info NMF successfully created.
ECHO.
IF DEFINED LOCALAPPDATA (
  IF EXIST "%LOCALAPPDATA%\VirtualStore\Windows\lagarith.bak" (
    DEL "%LOCALAPPDATA%\VirtualStore\Windows\lagarith.ini"
	REN "%LOCALAPPDATA%\VirtualStore\Windows\lagarith.bak" lagarith.ini
  )
) ELSE (
  IF EXIST "%WINDIR%\lagarith.bak" (
    DEL "%WINDIR%\lagarith.ini"
	REN "%WINDIR%\lagarith.bak" lagarith.ini
  )
)
ENDLOCAL ENABLEDELAYEDEXPANSION & SET avifiles=%avifiles%
GOTO :EOF


REM ---------------------------------------------------------------------------
REM  function: script_buildfiles
REM 
REM  
REM ---------------------------------------------------------------------------

:script_buildfiles
REM Delete all avs files and restore base avs which has video source lines.
CALL :wipe_avs

IF "%trim%"=="y" (
  SET trimarraycode=
  SETLOCAL ENABLEDELAYEDEXPANSION
  (SET counter=0)
  FOR %%G IN (!trimarray!) DO (
    SET /A counter=!counter!+1
    SET /A countermodulus="!counter!%%2"
    IF !countermodulus!==1 (
      SET trimarraycode=!trimarraycode!trim^(%%G,
    ) ELSE (
      SET trimarraycode=!trimarraycode!%%G^)++
    )
  )
  SET trimarraycode=!trimarraycode:~0,-2!
  ECHO>> "%projname%.avs" !trimarraycode!
  ENDLOCAL ENABLEDELAYEDEXPANSION
)

IF "%fieldorder%"=="t" ECHO>> "%projname%.avs" AssumeTFF
IF "%fieldorder%"=="b" ECHO>> "%projname%.avs" AssumeBFF

REM The base avs file at this point loads plugins, media files, possibly does trimming, possibly declares field order. It's backed up as projname.bak.
REM It also has a conversion to RGB. This is needed since we may deal with resolutions that are temporarily not mod 4 width. (YUY2 is 4x1, YV12 is 4x2)
COPY /B "%projname%.avs" "%projname%_HQ.avs" 1> NUL
COPY /B "%projname%.avs" "%projname%_IQ.avs" 1> NUL
COPY /B "%projname%.avs" "%projname%_XQ.avs" 1> NUL

REM ### XQ ###
IF "%prog%"=="n" (
  IF %d%==1               ECHO>> "%projname%_XQ.avs" converttoyuy2.mvbob.converttorgb32
  IF %d%==4               ECHO>> "%projname%_XQ.avs" separatefields
) ELSE (
  REM                                                [IF1cond...........][IF1true..........................][IF1false [IF2cond.....][IF2true....................................][IF2false.........................]]
  IF %d%==4               ECHO>> "%projname%_XQ.avs" last.height ^> 700 ? lanczos4resize^(last.width,240^) : ^(last.height ^>= 480 ? lanczos4resize^(last.width,last.height/2^) : lanczos4resize^(last.width,240^)^)
)
ECHO>> "%projname%_XQ.avs" last.width ^> last.height * %DARnum%./%DARden% ? lanczos4resize^(ceil^(last.height * %DARnum%./%DARden%^),last.height^) : NOP

REM ### IQ ###
IF "%prog%"=="n" (
  IF %d%==1               ECHO>> "%projname%_IQ.avs" converttoyuy2.mvbob.converttorgb32
  IF %d%==4               ECHO>> "%projname%_IQ.avs" separatefields
) ELSE (
  REM                                                [IF1cond...........][IF1true..........................][IF1false [IF2cond.....][IF2true....................................][IF2false.........................]]
  IF %d%==4               ECHO>> "%projname%_IQ.avs" last.height ^> 700 ? lanczos4resize^(last.width,240^) : ^(last.height ^>= 480 ? lanczos4resize^(last.width,last.height/2^) : lanczos4resize^(last.width,240^)^)
)
REM                        [IF1cond...........][IF1true [IF2cond.........................][IF2true................................................][IF2false..........................]][IF1false [IF3cond................................][IF3true...............................................................][If3false]]
ECHO>> "%projname%_IQ.avs" last.height ^> 768 ? ^(last.width ^> 768 * %DARnum%./%DARden% ? lanczos4resize^(ceil^(768 * %DARnum%./%DARden%^),768^) : lanczos4resize^(last.width,768^)^) : ^(last.width ^> last.height * %DARnum%./%DARden% ? lanczos4resize^(ceil^(last.height * %DARnum%./%DARden%^),last.height^) : NOP^)

REM ### HQ ###
IF "%prog%"=="n" (
  IF %d%==1 IF %f%==1     ECHO>> "%projname%_HQ.avs" converttoyuy2.mvbob.converttorgb32
  IF %d%==1 IF NOT %f%==1 ECHO>> "%projname%_HQ.avs" last.height ^> 1000 ? separatefields.lanczos4resize^(last.width,480^) : converttoyuy2.mvbob.converttorgb32
  IF %d%==4               ECHO>> "%projname%_HQ.avs" separatefields
) ELSE (
  REM                                                [IF1cond...........][IF1true..........................][IF1false [IF2cond.....][IF2true....................................][IF2false.........................]]
  IF %d%==4               ECHO>> "%projname%_HQ.avs" last.height ^> 700 ? lanczos4resize^(last.width,240^) : ^(last.height ^>= 480 ? lanczos4resize^(last.width,last.height/2^) : lanczos4resize^(last.width,240^)^)
)
REM                        [IF1cond...........][IF1true [IF2cond.........................][IF2true................................................][IF2false..........................]][IF1false [IF3cond................................][IF3true...............................................................][If3false]]
ECHO>> "%projname%_HQ.avs" last.height ^> 700 ? ^(last.width ^> 480 * %DARnum%./%DARden% ? lanczos4resize^(ceil^(480 * %DARnum%./%DARden%^),480^) : lanczos4resize^(last.width,480^)^) : ^(last.width ^> last.height * %DARnum%./%DARden% ? lanczos4resize^(ceil^(last.height * %DARnum%./%DARden%^),last.height^) : NOP^)

REM ### MQ ###
IF "%prog%"=="n" (
  ECHO>> "%projname%.avs" last.height ^> 700 ? separatefields.lanczos4resize^(last.width,240^) : separatefields
) ELSE (
  REM                     [IF1cond...........][IF1true..........................][IF1false [IF2cond.....][IF2true....................................][IF2false.........................]]
  ECHO>> "%projname%.avs" last.height ^> 700 ? lanczos4resize^(last.width,240^) : ^(last.height ^>= 480 ? lanczos4resize^(last.width,last.height/2^) : lanczos4resize^(last.width,240^)^)
)
REM                     [IF1cond...........][IF1true [IF2cond.........................][IF2true................................................][IF2false..........................]][IF1false [IF3cond................................][IF3true...............................................................][If3false]]
ECHO>> "%projname%.avs" last.height ^> 700 ? ^(last.width ^> 480 * %DARnum%./%DARden% ? lanczos4resize^(ceil^(480 * %DARnum%./%DARden%^),480^) : lanczos4resize^(last.width,480^)^) : ^(last.width ^> last.height * %DARnum%./%DARden% ? lanczos4resize^(ceil^(last.height * %DARnum%./%DARden%^),last.height^) : NOP^)

REM Fit to mod 4 width and mod 2 height
ECHO>> "%projname%_XQ.avs" last.height %% 2 == 1 ? AddBorders^(0,0,0,1^) : NOP
ECHO>> "%projname%_XQ.avs" last.width %% 4 ^<^> 0 ? AddBorders^(floor^(^(4 - last.width %% 4^) / 2.^), 0, ceil^(^(4 - last.width %% 4^) / 2.^), 0^) : NOP
ECHO>> "%projname%_IQ.avs" last.height %% 2 == 1 ? AddBorders^(0,0,0,1^) : NOP
ECHO>> "%projname%_IQ.avs" last.width %% 4 ^<^> 0 ? AddBorders^(floor^(^(4 - last.width %% 4^) / 2.^), 0, ceil^(^(4 - last.width %% 4^) / 2.^), 0^) : NOP
ECHO>> "%projname%_HQ.avs" last.height %% 2 == 1 ? AddBorders^(0,0,0,1^) : NOP
ECHO>> "%projname%_HQ.avs" last.width %% 4 ^<^> 0 ? AddBorders^(floor^(^(4 - last.width %% 4^) / 2.^), 0, ceil^(^(4 - last.width %% 4^) / 2.^), 0^) : NOP
ECHO>> "%projname%.avs" last.height %% 2 == 1 ? AddBorders^(0,0,0,1^) : NOP
ECHO>> "%projname%.avs" last.width %% 4 ^<^> 0 ? AddBorders^(floor^(^(4 - last.width %% 4^) / 2.^), 0, ceil^(^(4 - last.width %% 4^) / 2.^), 0^) : NOP

IF "%vhs%"=="y" 		 ECHO>> "%projname%_temp.avs" nate_vhs_head_change_erase
IF "%onepixel%"=="y" 	 ECHO>> "%projname%_temp.avs" nate_1_pixel_bob_fix
IF "%onepixelalt%"=="y"  ECHO>> "%projname%_temp.avs" nate_alternate_1_pixel_bob_fix
IF "%deflicker%"=="y" 	 ECHO>> "%projname%_temp.avs" nate_retard_bob_2
IF "%deflickeralt%"=="y" ECHO>> "%projname%_temp.avs" nate_alternate_retard_bob_2
IF "%nes%"=="y" 		 ECHO>> "%projname%_temp.avs" nate_nes
IF "%gba%"=="y" 		 ECHO>> "%projname%_temp.avs" nate_gba
IF "%gameboy%"=="y" 	 ECHO>> "%projname%_temp.avs" nate_gb

IF "%f%"=="3" (
  ECHO>> "%projname%_temp.avs" changefps^(last.framerate/2^)
  ECHO>> "%projname%_temp.avs" converttoyuy2.decimate^(cycle=3^).converttorgb32
) ELSE (
  ECHO>> "%projname%_temp.avs" changefps^(last.framerate/%f%^)
)

ECHO>> "%projname%_temp.avs" statid=nate_statid(last,"%statid1%\n\n%statid2%\n%statid3%","%statid_alternative%","%statid_commentary%")
REM Pre-shrink the statid so it looks normal after setting the display aspect ratio.
ECHO>> "%projname%_temp.avs" statid=statid.AddBorders^(int^(^(statid.width * float(%DARnum%*statid.height)/float(%DARden%*statid.width) - statid.width^) / 2.^), 0, int^(^(statid.width * float(%DARnum%*statid.height)/float(%DARden%*statid.width) - statid.width^) / 2.^), 0^).Lanczos4Resize^(statid.width,statid.height^)
IF "%statid%"=="y" ECHO>> "%projname%_temp.avs" statid++last++statid

ECHO>> "%projname%_temp.avs" changefps(last.framerate)
ECHO>> "%projname%_temp.avs" converttoyv12
TYPE>> "%projname%.avs" "%projname%_temp.avs"
TYPE>> "%projname%_HQ.avs" "%projname%_temp.avs"
TYPE>> "%projname%_IQ.avs" "%projname%_temp.avs"
TYPE>> "%projname%_XQ.avs" "%projname%_temp.avs"
COPY /B "%projname%.avs" "%projname%_LQ.avs" 1> NUL
IF "%twod%"=="y" ECHO>> "%projname%_LQ.avs" ^(last.framerate ^> 31^) ? changefps^(last.framerate/3^) : last
IF "%twod%"=="n" (
  ECHO>> "%projname%.avs" ^(last.framerate ^> 31^) ? changefps^(last.framerate/2^) : last
  ECHO>> "%projname%_LQ.avs" ^(last.framerate ^> 31^) ? changefps^(last.framerate/2^) : last
)
COPY /B "%projname%_LQ.avs" "%projname%_xvid.avs" 1> NUL
COPY /B "%projname%_LQ.avs" "%projname%_LQ_xvid.avs" 1> NUL

REM x264 will weave a field based avisynth script. Set the scripts to frame based.
ECHO>> "%projname%_XQ.avs" AssumeFrameBased
ECHO>> "%projname%_IQ.avs" AssumeFrameBased
ECHO>> "%projname%_HQ.avs" AssumeFrameBased
ECHO>> "%projname%.avs" AssumeFrameBased
ECHO>> "%projname%_LQ.avs" AssumeFrameBased

REM Need final sample aspect ratio for calculation of individual pixel aspect ratio.
ECHO>> "%projname%_XQ.avs" WriteFileStart^("SAR_%projname%_XQ.log","last.width",""" "," """, "last.height",append=false^)
ECHO>> "%projname%_IQ.avs" WriteFileStart^("SAR_%projname%_IQ.log","last.width",""" "," """, "last.height",append=false^)
ECHO>> "%projname%_HQ.avs" WriteFileStart^("SAR_%projname%_HQ.log","last.width",""" "," """, "last.height",append=false^)
ECHO>> "%projname%.avs" WriteFileStart^("SAR_%projname%.log","last.width",""" "," """, "last.height",append=false^)
ECHO>> "%projname%_LQ.avs" WriteFileStart^("SAR_%projname%_LQ.log","last.width",""" "," """, "last.height",append=false^)

DEL "%projname%_temp.avs" "%projname%_trimtemp.avs"
GOTO :EOF


REM ------- SETTINGS MANAGER -------

:find_existing_settings
IF EXIST "%projdirpath%\job_%PROJNAME%.bat" (
	CALL "%projdirpath%\job_%PROJNAME%.bat"
	SET using_settings=y
)
GOTO :EOF

:check_settings
CALL :show_settings
:check_settings_p2
SET s=y
SET /P s=Do you want to encode using these settings? If you choose No you will be prompted to enter them again. [(y),n]: 
CALL :set_var_bool settings_good check_settings_p2
GOTO :EOF

:show_settings
CALL :out_cls_section REVIEW SETTINGS
IF DEFINED this_anriver IF NOT "%this_anriver%"=="%anri_ver%" CALL :out_info NOTICE: Your settings for this project were created in an outdated version of Anri-chan. They may not work properly in this version. It is recommended that you discard these settings and re-enter them.
IF "%dvdsource%"=="y" ( ECHO DVD Source: Yes ) ELSE ( ECHO DVD Source: No )
ECHO Project Name: %projname%
IF DEFINED avifiles ECHO Source Video Files: %avifiles%
IF NOT "%twod%"=="y" (SET twodtemp=3D) ELSE (SET twodtemp=2D)
IF DEFINED d IF DEFINED f ECHO Video Format: D%d% F%f% %twodtemp%
IF "%vhs%"=="y" ( ECHO From VHS Source )
IF "%prog%"=="y" ( ECHO Progressive ) ELSE ( ECHO Interlaced )
IF "%fieldorder%"=="t" ECHO Top field first
IF "%fieldorder%"=="b" ECHO Bottom field first
IF "%onepixel%"=="y" ECHO One-Pixel Bob
IF "%onepixelalt%"=="y" ECHO One-Pixel Bob
IF "%nes%"=="y" ECHO From NES Console
IF "%gba%"=="y" ECHO From Game Boy Advance
IF "%gameboy%"=="y" ECHO From Game Boy
IF "%deflicker%"=="y" ECHO Deflickered
IF "%deflickeralt%"=="y" ECHO Deflickered
IF "%trim%"=="y" ECHO Trim frame ranges %trimarray%
IF DEFINED DARnum IF DEFINED DARden ECHO Display aspect ratio: %DARnum%/%DARden%
IF "%statid%"=="y" ECHO StatID: %statid1:"+chr(34)+"="% / %statid2:"+chr(34)+"="% / %statid3:"+chr(34)+"="%
ECHO.
GOTO :EOF

:savesettings
IF "%DARnum%"=="" SET DARnum=4
IF "%DARden%"=="" SET DARden=3
REM Make sure there are no spaces at the end of each line.
ECHO>  "job_%PROJNAME%.bat" @ECHO OFF
ECHO>> "job_%PROJNAME%.bat" SET proj_anriver=%anri_ver%
ECHO>> "job_%PROJNAME%.bat" SET using_settings=y
ECHO>> "job_%PROJNAME%.bat" SET dvdsource=%dvdsource%
ECHO>> "job_%PROJNAME%.bat" SET avifiles=%avifiles%
ECHO>> "job_%PROJNAME%.bat" SET fieldorder=%fieldorder%
ECHO>> "job_%PROJNAME%.bat" SET d=%d%
ECHO>> "job_%PROJNAME%.bat" SET f=%f%
ECHO>> "job_%PROJNAME%.bat" SET vhs=%vhs%
ECHO>> "job_%PROJNAME%.bat" SET deflicker=%deflicker%
ECHO>> "job_%PROJNAME%.bat" SET deflickeralt=%deflickeralt%
ECHO>> "job_%PROJNAME%.bat" SET onepixel=%onepixel%
ECHO>> "job_%PROJNAME%.bat" SET onepixelalt=%onepixelalt%
ECHO>> "job_%PROJNAME%.bat" SET nes=%nes%
ECHO>> "job_%PROJNAME%.bat" SET twod=%twod%
ECHO>> "job_%PROJNAME%.bat" SET statid=%statid%
ECHO>> "job_%PROJNAME%.bat" SET statid1=%statid1%
ECHO>> "job_%PROJNAME%.bat" SET statid2=%statid2%
ECHO>> "job_%PROJNAME%.bat" SET statid3=%statid3%
ECHO>> "job_%PROJNAME%.bat" SET statid_alternative=%statid_alternative%
ECHO>> "job_%PROJNAME%.bat" SET statid_commentary=%statid_commentary%
ECHO>> "job_%PROJNAME%.bat" SET driveletter=%driveletter%
ECHO>> "job_%PROJNAME%.bat" SET projname=%projname%
ECHO>> "job_%PROJNAME%.bat" SET gba=%gba%
ECHO>> "job_%PROJNAME%.bat" SET gameboy=%gameboy%
ECHO>> "job_%PROJNAME%.bat" SET prog=%prog%
ECHO>> "job_%PROJNAME%.bat" SET trim=%trim%
ECHO>> "job_%PROJNAME%.bat" SET trimarray=%trimarray%
ECHO>> "job_%PROJNAME%.bat" SET maxaudiobitrate=%maxaudiobitrate%
ECHO>> "job_%PROJNAME%.bat" SET isPCGAME=%isPCGAME%
ECHO>> "job_%PROJNAME%.bat" SET nativewidth=%nativewidth%
ECHO>> "job_%PROJNAME%.bat" SET nativeheight=%nativeheight%
ECHO>> "job_%PROJNAME%.bat" SET DARnum=%DARnum%
ECHO>> "job_%PROJNAME%.bat" SET DARden=%DARden%
ECHO>> "job_%PROJNAME%.bat" IF NOT "%%in_anrichan%%"=="y" call "%anri_path%"
COPY /Y "job_%PROJNAME%.bat" "job_%PROJNAME%.bak" > NUL
GOTO :EOF

:createjob
CALL :savesettings
PAUSE
GOTO die


REM ------- QUALITIES SELECTION -------

:selectquality
SET s=%4
SET /P s="Create %1 (%2 Kbps) movie? (%4): "
IF "%s%"=="y" (
	SET create_%3=y
	GOTO :EOF
)
IF "%s%"=="n" (
	SET create_%3=n
	GOTO :EOF
)
CALL :out_error Invalid value. Please enter Y (Yes) or N (No).
GOTO :selectquality %1 %2 %3 %4

:select_qualities
CALL :savesettings
CALL :out_info Required for submission:
CALL :selectquality Low-Quality 192 lq y
CALL :selectquality Normal-Quality 576 mq y
CALL :selectquality High-Quality 2176 hq y
IF "%d%"=="1" IF NOT "%gba%"=="y" IF NOT "%gameboy%"=="y" (
  ECHO.
  CALL :out_info Optional, recommended for videos with high resolution/framerate:
  CALL :selectquality Insane-Quality 5320 iq n
  CALL :selectquality X-TREME-Quality-High-Definition 10320 xq n
) ELSE (
  SET create_iq=n
  SET create_xq=n
)
ECHO.
CALL :out_info Non-submittable to SDA, no longer maintained:
CALL :selectquality XviD-Low-Quality 192 xl n
CALL :selectquality XviD-Normal-Quality 576 xm n
GOTO :EOF

REM ------- ENCODING -------

:encode_movies
CALL :out_section encoding %projname%

REM PAR = DAR / SAR
REM PAR = (DAR numerator * SAR denominator) / (DAR denominator * SAR numerator)
REM  e.g. widescreen 16/9:	(16 * 480) / (9 * 720) = 7680 / 6480
REM The formula results in 1/1 PAR if not changing aspect ratio.
REM  e.g. (4 * 480) / (3 * 640) = 1920 / 1920 = 1 / 1

IF "%create_lq%"=="y" (
  CALL :out_section encoding %projname% LQ MP4
  CALL :2pass %projname%_LQ.avs %projname%_LQ 128 64000 1 1
  MOVE /Y "%projname%_LQ.mp4" %projname%_finished > NUL 2>&1
)

IF "%create_mq%"=="y" (
  CALL :out_section encoding %projname% MQ MP4
  CALL :ipod %projname%.avs %projname% 512 64000 1 1
  MOVE /Y "%projname%.mp4" %projname%_finished > NUL 2>&1
)

IF "%create_hq%"=="y" (
  CALL :out_section encoding %projname% HQ MP4
  IF "%create_nmf%"=="y" (
    CALL :2pass %projname%_HQ_nmf.avs %projname%_HQ 2048 128000 1 1
  ) ELSE (
    CALL :2pass %projname%_HQ.avs %projname%_HQ 2048 128000 1 1
  )
  MOVE /Y "%projname%_HQ.mp4" %projname%_finished > NUL 2>&1
)

IF "%create_iq%"=="y" (
  CALL :out_section encoding %projname% IQ MP4
  IF "%create_nmf%"=="y" (
    CALL :2pass %projname%_IQ_nmf.avs %projname%_IQ 5000 %maxaudiobitrate% 1 1
  ) ELSE (
    CALL :2pass %projname%_IQ.avs %projname%_IQ 5000 %maxaudiobitrate% 1 1
  )
  MOVE /Y "%projname%_IQ.mp4" %projname%_finished > NUL 2>&1
)

IF "%create_xq%"=="y" (
  CALL :out_section encoding %projname% XQ MP4
  IF "%create_nmf%"=="y" (
    CALL :2pass %projname%_XQ_nmf.avs %projname%_XQ 10000 %maxaudiobitrate% 1 1
  ) ELSE (
    CALL :2pass %projname%_XQ.avs %projname%_XQ 10000 %maxaudiobitrate% 1 1
  )
  MOVE /Y "%projname%_XQ.mp4" %projname%_finished > NUL 2>&1
)

IF "%create_xl%"=="y" (
  CALL :out_section encoding %projname% LQ AVI
  CALL :xvid %projname%_LQ_xvid.avs %projname%_LQ 128 64 1 1
  MOVE /Y "%projname%_LQ.avi" %projname%_finished > NUL 2>&1
)
IF "%create_xm%"=="y" (
  CALL :out_section encoding %projname% MQ AVI
  CALL :xvid %projname%_xvid.avs %projname% 512 64 1 1
  MOVE /Y "%projname%.avi" %projname%_finished > NUL 2>&1
)
GOTO :EOF


:2pass
SETLOCAL ENABLEDELAYEDEXPANSION
REM args: 1 = avs script, 2 = file name, 3 = video bitrate in kbps, 4 = audio bitrate in bps, 5 = bool delete states file, 6 = bool delete temp video/audio files
ECHO Beginning x264 first pass...
"%anri_dir%x264.exe" --preset veryslow --crf 17 --pass 1 --slow-firstpass --no-interlaced --b-pyramid 0 --stats "%2.stats" --output "%2_video.mp4" %1 2>&1 | "%anri_dir%tee.exe" x264pass1_stdout.txt
REM Parse x264pass1_stdout.txt and compare average bitrate. If higher, run second pass.
FOR /F "tokens=7 delims=. " %%G IN ('TYPE x264pass1_stdout.txt ^| FIND "encoded"') DO (
  IF %%G GTR %3 (
    ECHO Beginning x264 second pass...
    "%anri_dir%x264.exe" --preset veryslow --bitrate %3 --pass 2 --no-interlaced --b-pyramid 0 --stats "%2.stats" --output "%2_video.mp4" %1
  )
)
ECHO Beginning vdub wav dump...
"%anri_dir%%vdub%\vdub.exe" %1 /i "%anri_dir%audioout.vcf" "%2_temp.wav"
ECHO Beginning nero audio encoding...
"%anri_dir%neroAacEnc.exe" -br %4 -lc -if "%2_temp.wav" -of "%2_audio.mp4"
IF NOT %ERRORLEVEL%==0 (
  ECHO There was an error encoding from the temporary wav file. Attempting bepipe audio encoding.
  "%anri_dir%bepipe.exe" --script "DirectShowSource(^%~f1^)" | "%anri_dir%neroAacEnc.exe" -br %4 -lc -if - -of "%2_audio.mp4"
)
FOR /F "tokens=1,2 delims=," %%P IN (SAR_%2.log) DO (
  SET /A PARnum=%DARnum% * %%Q
  SET /A PARden=%DARden% * %%P
)
CALL :gcd %PARnum% %PARden%
SET /A PARnum=%PARnum% / %callresult%
SET /A PARden=%PARden% / %callresult%
ECHO Beginning mp4box muxing...
"%anri_dir%MP4Box.exe" -tmp . -new -add "%2_video.mp4" -add "%2_audio.mp4" "%2.mp4" -par 1=%PARnum%:%PARden%
IF "%5" == "1" del %2.stats
IF "%6" == "1" del %2_video.mp4 | del %2_temp.wav | del %2_audio.mp4
ENDLOCAL ENABLEDELAYEDEXPANSION
GOTO :EOF

:ipod
SETLOCAL ENABLEDELAYEDEXPANSION
REM args: 1 = avs script, 2 = file name, 3 = video bitrate in kbps, 4 = audio bitrate in bps, 5 = bool delete states file, 6 = bool delete temp video/audio files
ECHO Beginning x264 first pass...
"%anri_dir%x264.exe" --profile baseline --level 1.3 --pass 1 --slow-firstpass --no-interlaced --crf 17 --stats "%2.stats" --no-cabac                           --ref 1  --vbv-bufsize 768   --vbv-maxrate 768   --me umh --partitions p8x8,b8x8,i4x4             --no-8x8dct --trellis 0 --output "%2_video.mp4" %1 2>&1 | "%anri_dir%tee.exe" x264pass1_stdout.txt
REM Parse x264pass1_stdout.txt and compare average bitrate. If higher, run second pass.
FOR /F "tokens=7 delims=. " %%G IN ('TYPE x264pass1_stdout.txt ^| FIND "encoded"') DO (
  IF %%G GTR %3 (
    ECHO Beginning x264 second pass...
    "%anri_dir%x264.exe" --profile baseline --level 1.3 --pass 2 --no-interlaced --bitrate %3 --stats "%2.stats" --no-cabac                           --ref 1  --vbv-bufsize 768   --vbv-maxrate 768   --me umh --partitions p8x8,b8x8,i4x4             --no-8x8dct --trellis 0 --output "%2_video.mp4" %1
  )
)
ECHO Beginning vdub wav dump...
"%anri_dir%%vdub%\vdub.exe" %1 /i "%anri_dir%audioout.vcf" "%2_temp.wav"
ECHO Beginning nero audio encoding...
"%anri_dir%neroAacEnc.exe" -br %4 -lc -if "%2_temp.wav" -of "%2_audio.mp4"
IF NOT %ERRORLEVEL%==0 (
  ECHO There was an error encoding from the temporary wav file. Attempting bepipe audio encoding.
  "%anri_dir%bepipe.exe" --script "DirectShowSource(^%~f1^)" | "%anri_dir%neroAacEnc.exe" -br %4 -lc -if - -of "%2_audio.mp4"
)
FOR /F "tokens=1,2 delims=," %%P IN (SAR_%2.log) DO (
  SET /A PARnum=%DARnum% * %%Q
  SET /A PARden=%DARden% * %%P
)
CALL :gcd %PARnum% %PARden%
SET /A PARnum=%PARnum% / %callresult%
SET /A PARden=%PARden% / %callresult%
ECHO Beginning mp4box muxing...
"%anri_dir%MP4Box.exe" -tmp . -new -add "%2_video.mp4" -add "%2_audio.mp4" "%2.mp4" -par 1=%PARnum%:%PARden%
IF "%5" == "1" del %2.stats
IF "%6" == "1" del %2_video.mp4 | del %2_temp.wav | del %2_audio.mp4
ENDLOCAL ENABLEDELAYEDEXPANSION
GOTO :EOF

:1pass
SETLOCAL ENABLEDELAYEDEXPANSION
REM This is only really used for the sample creator
REM args: 1 = avs script, 2 = file name, 3 = audio bitrate in bps, 4 = video quantizer, 5 = bool delete temp video/audio files
"%anri_dir%x264.exe" --profile high --crf %4 --thread-input --b-adapt 2 --direct auto --me umh --trellis 2 --output "%2_video.mp4" %1 
"%anri_dir%%vdub%\vdub.exe" %1 /i "%anri_dir%audioout.vcf" "%2_temp.wav"
"%anri_dir%neroAacEnc.exe" -br %3 -lc -if "%2_temp.wav" -of "%2_audio.mp4"
"%anri_dir%MP4Box.exe" -tmp . -new -add "%2_video.mp4" -add "%2_audio.mp4" "%2.mp4" -par 1=4:3
IF "%5" == "1" del %2_video.mp4 | del %2_temp.wav | del %2_audio.mp4
ENDLOCAL ENABLEDELAYEDEXPANSION
GOTO :EOF

:xvid
SETLOCAL ENABLEDELAYEDEXPANSION
"%anri_dir%xvid_encraw.exe" -i %1 -bitrate %3 -pass1 "%2.stats"
"%anri_dir%xvid_encraw.exe" -i %1 -bitrate %3 -pass2 "%2.stats" -avi "%2v.avi"
"%anri_dir%ffmpeg.exe" -b %4 -ac 2 -acodec mp3 -y -i "%2v.avi" -vcodec copy -i %1 "%2.avi"
IF "%5" == "1" del "%2.stats"
IF "%6" == "1" del "%2v.avi"
ENDLOCAL ENABLEDELAYEDEXPANSION
GOTO :EOF


REM ------- OUTPUT -------

REM ---------- Colorized Output --------------------
REM By: Brett Ables - Psonar
REM %CECHO% is a call to CECHO.exe which is used for colored output
REM Usage should be self-explanatory. Run CECHO.exe /? for help.
REM Also see comment in Initialization section.
REM Sorry about long lines... lines can be shortened with
REM 2 digit color codes (instead of whole words) if needed.
REM ------------------------------------------------------

:out_cls
CLS
%CECHO% "{gray on black}                                                                               {\n}"
%CECHO% "{blue on black}==============================================================================={\n}"
%CECHO% "{white on black}               metroid 2002 speed demos archive anri-chan %anri_ver%                  {\n}"
%CECHO% "{aqua on black}       http://www.metroid2002.com/     http://speeddemosarchive.com/           {\n}"
%CECHO% "{blue on black}==============================================================================={\n}"
ECHO.
%RESET_COLOR%
Goto :EOF

:out_info
%CECHO% "{white on gray}%*{\n}"
%RESET_COLOR%
REM ECHO.
GOTO :EOF

:out_error
%CECHO% "{maroon on gray}[!]{\n}"
%CECHO% "{maroon on gray}[!] {maroon on silver}%*{\n}"
%CECHO% "{maroon on gray}[!]{\n}"
%RESET_COLOR%
ECHO.
GOTO :EOF

:out_section
TITLE Anri-chan %anri_ver% - %*
%CECHO% "{teal on gray}-------------------------{\n}"
%CECHO% "{navy on gray}%*{\n}
%CECHO% "{teal on gray}-------------------------{\n}"
%RESET_COLOR%
ECHO.
GOTO :EOF

:out_cls_section
CALL :out_cls
CALL :out_section %*
GOTO :EOF

:out_cls_info
CALL :out_cls
CALL :out_info %*
GOTO :EOF


REM ------- OTHER -------

:resetvars
FOR %%A IN (%vars_to_use%) DO (SET %%A=)
GOTO :EOF

:filecompare
REM no differences = 0
FC %1 %2 > NUL 2>&1
SET callresult=%ERRORLEVEL%
GOTO :EOF

:gcd
SETLOCAL ENABLEDELAYEDEXPANSION
REM Euclidian algorithm to find greatest common denominator.
IF %1 GEQ %2 (
  (SET high=%1)
  (SET low=%2)
) ELSE (
  (SET high=%2)
  (SET low=%1)
)
SET /A remainder=%high% %% %low%
IF %remainder% NEQ 0 (
  :gcd_loop
  SET high=!low!
  SET low=!remainder!
  SET /A remainder=!high! %% !low!
  IF !remainder! NEQ 0 GOTO :gcd_loop
)
ENDLOCAL ENABLEDELAYEDEXPANSION & SET callresult=%low%
GOTO :EOF

:removequotations
REM This function expects the variable name only
FOR /F "delims=" %%G IN ('CALL ECHO %%%1%%') DO CALL SET %1=%%~G
GOTO :EOF

:die
CALL :resetvars
(SET in_anrichan=)
CD /D "%DESKTOP%"
TITLE Anri-chan dun ^^_^^
PAUSE
EXIT

REM ---------------------------------------------------------------------------
REM  Function: setanribat
REM
REM  The start command, without a /wait in there gets two instances running at
REM  the same time. What happens is we call anri.bat on top of itself at low
REM  priority. The old instance which is running at normal priority, dies.
REM  The /B keeps the new instance in the same window.
REM ---------------------------------------------------------------------------

:setanribat
CD /D %~dp0
IF NOT "%auto%"=="y" (
START /LOW /B anri.bat anrilow
) ELSE (
REM need to change this to call this filename, whatever that may be
START /LOW /B %anri_auto_bat% anrilow
)
EXIT
Personal tools