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

From SDA Knowledge Base

Jump to: navigation, search
(did some minor debugging of dvd ripping stuff, too tired to go on tonight though ... wonder if i'll have time to make the new dfnd system tomorrow)
(out of time for today. dvd indexing, new dfnd system are in and working.)
Line 60: Line 60:
 
#name of the directory containing dgindex.exe under anri's program directory and of the executable itself
 
#name of the directory containing dgindex.exe under anri's program directory and of the executable itself
 
$dgmpgdec_dir = "${anri_dir}/dgmpgdec152";
 
$dgmpgdec_dir = "${anri_dir}/dgmpgdec152";
$dgmpgdec = 'dgmpgdec.exe';
+
$dgindex = 'dgindex.exe';
 
 
 
#name of the directory containing virtualdub.exe under anri's program directory and of the executables both gui and cli
 
#name of the directory containing virtualdub.exe under anri's program directory and of the executables both gui and cli
Line 78: Line 78:
 
$pgccount = "pgccount.exe";
 
$pgccount = "pgccount.exe";
 
$mplayer = "mplayer.exe";
 
$mplayer = "mplayer.exe";
 +
$wget = "wget.exe";
  
 
#dunno about this
 
#dunno about this
$dvdripto_parentdir = 'C:\AnriMPEG';
+
$dvdripto_parentdir = "C:\\AnriMPEG";
  
 
#set some keys in the registry to make vdub show only the input video pane (having both the input and output panes open as is default tends to confuse users)
 
#set some keys in the registry to make vdub show only the input video pane (having both the input and output panes open as is default tends to confuse users)
Line 145: Line 146:
 
#main menu
 
#main menu
  
#TODO: using_settings
+
#FIXME: using_settings
  
 
############################################################################
 
############################################################################
Line 153: Line 154:
 
############################################################################
 
############################################################################
  
&out_cls;
+
while (1) {
&out_info("ON HERMESUS LUC ARSUS ESTARIAS AUC ELTRAS LI CELES! Now, let's get to work!");
+
&out_cls;
&out_section("Main");
+
&out_info("ON HERMESUS LUC ARSUS ESTARIAS AUC ELTRAS LI CELES! Now, let's get to work!");
@mainmenu = (
+
&out_section("Main");
['Rip DVD to hard drive (required for DVD material)', '&rip_dvd'],
+
@mainmenu = (
['Start new project', '&project'],
+
['Rip DVD to hard drive (required for DVD material)', '&rip_dvd'],
['Extract sample', '&proc_sample'],
+
['Start new project', '&project'],
['Station ID preview', '&statid_sample'],
+
['Extract sample', '&proc_sample'],
['Exit', 'exit 0'],
+
['Station ID preview', '&statid_sample'],
);
+
['Exit', 'exit 0'],
&out_menu(@mainmenu);
+
);
while (<STDIN>) {
+
chomp;
+
if (m/([1-5])$/) {
+
#execute the contents of this value in the array
+
eval($mainmenu[$1-1][1]);
+
last;
+
}
+
print "Invalid input.\n\n";
+
 
&out_menu(@mainmenu);
 
&out_menu(@mainmenu);
 +
while (<STDIN>) {
 +
chomp;
 +
if (m/([1-5])$/) {
 +
#execute the contents of this value in the array
 +
eval($mainmenu[$1-1][1]);
 +
last;
 +
}
 +
print "Invalid input.\n\n";
 +
&out_menu(@mainmenu);
 +
}
 
}
 
}
  
Line 264: Line 267:
 
while (<STDIN>) {
 
while (<STDIN>) {
 
chomp;
 
chomp;
if (m/^[% ]/) {
+
if (!m/[% ]/) {
 
$projname = $_;
 
$projname = $_;
 
last;
 
last;
Line 271: Line 274:
 
print $prompt;
 
print $prompt;
 
}
 
}
 +
&make_projdir;
 +
&load_plugins;
 
#FIXME settings manager
 
#FIXME settings manager
 
#CALL :find_existing_settings
 
#CALL :find_existing_settings
Line 299: Line 304:
 
&out_info("${dvdripto_parentdir}\\foldername\\ and then answer y to the question below.");
 
&out_info("${dvdripto_parentdir}\\foldername\\ and then answer y to the question below.");
 
&echo("");
 
&echo("");
 +
&q_boo($dvdsource,'DVD/MPEG source [y,n]');
 
#IF NOT "%auto%"=="y" CALL :q_dvdsource
 
#IF NOT "%auto%"=="y" CALL :q_dvdsource
 
if ($dvdsource) {
 
if ($dvdsource) {
Line 333: Line 339:
 
$hqq=19 if not defined($hqq);
 
$hqq=19 if not defined($hqq);
 
$prog=1 if not defined($prog);
 
$prog=1 if not defined($prog);
&proc_gameproperties_p2;
+
#&proc_gameproperties_p2;
 
}
 
}
  
+
$dfnd_set = 0;
if (!$auto) {
+
&q_dfnd if !$auto;
: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=
+
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
+
: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
+
 
+
}
+
 
if (!$dfnd_set) {
 
if (!$dfnd_set) {
#GOTO dfnd_is_set
+
if (!$auto) {
}
+
&echo("");
 
+
&out_info("\"D\" and \"F\" are 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.");
if (!$auto) {
+
&echo("");
&echo("");
+
&out_info("Find D and F for your game at this URL:");
&out_info("\"D\" and \"F\" are 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.");
+
&out_info("http://speeddemosarchive.com/kb/index.php/DF");
&echo("");
+
&echo("");
&out_info("Find D and F for your game at this URL:");
+
&out_info("If you don't see your game listed there, you can use the Extract Sample main menu option 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.");
&out_info("http://speeddemosarchive.com/kb/index.php/DF");
+
&echo("");
&echo("");
+
&echo("Please enter 1 or 4 for D.");
&out_info("If you don't see your game listed there, you can use the Extract Sample main menu option 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.");
+
print $prompt;
&echo("");
+
while (<STDIN>) {
&echo("Please enter 1 or 4 for D.");
+
chomp;
print $prompt;
+
if (m/^[14]$/) {
while (<STDIN>) {
+
$d = $_;
chomp;
+
last;
if (m/^[14]$/) {
+
}
$d = $_;
+
print "Invalid input.\n\n";
last;
+
print $prompt;
 
}
 
}
print "Invalid input.\n\n";
+
&echo("Please enter 1, 2 or 3 for F.");
 
print $prompt;
 
print $prompt;
 +
while (<STDIN>) {
 +
chomp;
 +
if (m/^[123]$/) {
 +
$f = $_;
 +
last;
 +
}
 +
print "Invalid input.\n\n";
 +
print $prompt;
 +
}
 
}
 
}
&echo("Please enter 1, 2 or 3 for F.");
+
if ($f eq 1) {
print $prompt;
+
$twod=0;
while (<STDIN>) {
+
&q_2d if !$auto;
chomp;
+
}
if (m/^[123]$/) {
+
if (!$auto) {
$f = $_;
+
#:q_submit_dfnd
last;
+
&echo("");
}
+
&out_info("You didn't use the SDA games database. Does that mean that it didn't have your game? If so, we'd love it if you posted the \"D\", \"F\" and maybe \"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.");
print "Invalid input.\n\n";
+
&echo("");
print $prompt;
+
system("START http://speeddemosarchive.com/forum/index.php?action=post;topic=6416.0") if &q_boo($throwaway,"Submit this game's data to SDA? [y,n]");
 +
#:dfnd_is_set
 
}
 
}
 
}
 
}
if ($f eq 1) {
 
$twod=0;
 
&q_2d if !$auto;
 
}
 
if (!$auto) {
 
: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=
 
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
 
}
 
#:dfnd_is_set
 
 
$hqq = 17 if $d == 4;
 
$hqq = 17 if $d == 4;
 
$hqq = 19 if $d == 1;
 
$hqq = 19 if $d == 1;
 
  
 
############################################################################
 
############################################################################
Line 745: Line 679:
 
eval("${_[1]} ${projname}.${_[3]}.${nmf}.'.avs' ${projname} ${_[4]} ${_[5]} ${_[6]} ${_[7]} ${_[8]}");
 
eval("${_[1]} ${projname}.${_[3]}.${nmf}.'.avs' ${projname} ${_[4]} ${_[5]} ${_[6]} ${_[7]} ${_[8]}");
 
}
 
}
#}
+
}
  
 
sub nmf {
 
sub nmf {
Line 868: Line 802:
 
sub make_projdir {
 
sub make_projdir {
 
chdir($desktop);
 
chdir($desktop);
mkdir($projname);# if !-e $projname;
+
mkdir($projname) if !-e $projname;
 
chdir($projname);
 
chdir($projname);
 
&cp("${anri_dir}/silence_stereo_48000.wav","${desktop}/${projname}");
 
&cp("${anri_dir}/silence_stereo_48000.wav","${desktop}/${projname}");
Line 1,199: Line 1,133:
 
&out_error($errormsg);
 
&out_error($errormsg);
 
print $prompt;
 
print $prompt;
 +
}
 +
}
 +
 +
############################################################################
 +
# function: q_dfnd
 +
#
 +
# FIXME
 +
############################################################################
 +
sub q_dfnd {
 +
&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. However, you must be connected to the Internet to use it.");
 +
&q_boo($dfnd,"Do you want to use Anri-chan's games database [Y] or enter the data yourself [N]?");
 +
if ($dfnd) {
 +
#:dfnd
 +
&out_info("Anri will now attempt to connect to SDA's games database. This may take a few moments. Once complete, you will see a list of all games in the database.");
 +
&out_info("Press ENTER to continue ...");
 +
<STDIN>;
 +
&echo("");
 +
@dfnddata = ();
 +
$dfpage = "\"${anri_dir}/${wget}\"".' -qO- --user-agent="Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en-US; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14" "http://speeddemosarchive.com/kb/index.php/DF"';
 +
$_ = join("",qx($dfpage));
 +
#must be only one table on that page ... or at least the dfnd data must be in the first one ... but bman assumed this too and it was ok
 +
if (s/.*<table>(.+)<\/table>.*/$1/s) {
 +
@rows = split(/<\/tr>\n<tr>/);
 +
for (@rows) {
 +
chomp;
 +
#we don't want the header row
 +
next if m/<th/;
 +
@data = split(/<\/?t[dr]>+/);
 +
$nes = $gb = $gba = $d = $f = $twod = 0;
 +
for (@data) {
 +
$nes = 1 if m/for [^ ]*NES[^ ]*$/;
 +
if (m/(for [^ ]*GBC?[^ ]*)|(for Game Boy( Color)?)$/) {
 +
$gb = 1;
 +
}
 +
if (m/(for [^ ]*GBA[^ ]*)|(for Game Boy Advance)$/) {
 +
$gba = 1;
 +
}
 +
$d = $1 if m/^D([14])$/;
 +
$f = $1 if m/^F([123])$/;
 +
if (m/^([23])D$/) {
 +
$twod = $1;
 +
$twod =~ tr/23/10/;
 +
}
 +
}
 +
# 0    1  2    3    4    5    6
 +
push(@dfnddata,[$_, $d, $f, $twod, $nes, $gb, $gba]);
 +
}
 +
$titles = '';
 +
for $i ( 0 .. $#dfnddata ) {
 +
$title = $dfnddata[$i][0];
 +
$title =~ s/^<td>([^<]+)<\/td>.+/$1/;
 +
$title =~ s/&amp;/\&/g;
 +
$titles .= "".($i+1).": ${title}\n";
 +
}
 +
print $titles;
 +
#system("echo \"${titles}\" | more");
 +
print $prompt;
 +
while (<STDIN>) {
 +
chomp;
 +
if (m/^$/) {
 +
$errormsg="You must choose a game.";
 +
} elsif (m/[^0-9]/) {
 +
$errormsg="Please enter the number of a game.";
 +
} elsif (($_ gt @dfnddata) or ($_ le 0)) {
 +
$errormsg="Invalid selection.";
 +
} else {
 +
$gamechoice = $_;
 +
last;
 +
}
 +
&out_error($errormsg);
 +
print $prompt;
 +
}
 +
$gamechoice--;
 +
$d = $dfnddata[$gamechoice][1];
 +
$f = $dfnddata[$gamechoice][2];
 +
$twod = $dfnddata[$gamechoice][3];
 +
$nes = $dfnddata[$gamechoice][4];
 +
$gb = $dfnddata[$gamechoice][5];
 +
$gba = $dfnddata[$gamechoice][6];
 +
$dfnd_set = 1;
 +
} else {
 +
&out_error("Could not connect to SDA!");
 +
&q_dfnd if &q_boo($throwaway,"Try again? [y/n]");
 +
}
 
}
 
}
 
}
 
}
Line 1,321: Line 1,339:
 
if (!m/^$/) {
 
if (!m/^$/) {
 
$dvdripto = "${dvdripto_parentdir}/${_}";
 
$dvdripto = "${dvdripto_parentdir}/${_}";
 +
mkdir($dvdripto) if !-e $dvdripto;
 
last;
 
last;
 
} else {
 
} else {
Line 1,386: Line 1,405:
 
sub index_dvd {
 
sub index_dvd {
 
$maxaudiobr = 320000;
 
$maxaudiobr = 320000;
&out_cls_info("Here is the list of folders containing DVD/MPEG files (*.mpg, *.mpeg, *.vob, *.vro, etc.) 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.");
+
&out_cls_info("Here is the list of folders containing DVD/MPEG files (*.mpg, *.mpeg, *.vob, *.vro, etc.) in ${dvdripto_parentdir}\\. Select one or more by typing in the name or names separated by spaces. If you select more than one, the files will be joined in the order you specify.");
 
&echo("");
 
&echo("");
 
&echo("${navy_on_gray}Note that joining different DVD/MPEG files is only recommended if they're of the same game.  The settings you choose later in the editing phase will be applied to the whole project which can cause problems since different games will possibly need different settings.");
 
&echo("${navy_on_gray}Note that joining different DVD/MPEG files is only recommended if they're of the same game.  The settings you choose later in the editing phase will be applied to the whole project which can cause problems since different games will possibly need different settings.");
print $reset_color;
+
system($reset_color);
 
&echo("");
 
&echo("");
print $reset_color;
+
system($reset_color);
 
 
 
$i = 0;
 
$i = 0;
 
#following masks are all lowercase
 
#following masks are all lowercase
 
@dvdfilemasks = ( '*.v*', '*.mpg', '*.mpeg' );
 
@dvdfilemasks = ( '*.v*', '*.mpg', '*.mpeg' );
#now add the uppercase equivalents for case-sensitive filesystems
+
#FIXME os x still usually uses a case-insensitive filesystem
foreach $mask (@dvdfilemasks) {
+
if ($os ne 'windows') {
push(@dvdfilemasks, uc($mask));
+
#now add the uppercase equivalents for case-sensitive filesystems
 +
foreach $mask (@dvdfilemasks) {
 +
push(@dvdfilemasks, uc($mask));
 +
}
 
}
 
}
 
#i took out printing the dir even if no mpeg files are found in there because there's no point in showing it if the user can't do anything with it, also clarified that above in the messages to the user (nate)
 
#i took out printing the dir even if no mpeg files are found in there because there's no point in showing it if the user can't do anything with it, also clarified that above in the messages to the user (nate)
@gooddvddirs = ();
+
%gooddvddirs = ();
foreach $dvddir (glob("${dvdripto_parentdir}/*")) {
+
opendir(DVDRIPTO, $dvdripto_parentdir);
foreach $mask (@dvdfilemasks) {
+
@dvddirs = readdir(DVDRIPTO);
if (glob("${dvddir}/${mask}")) {
+
closedir(DVDRIPTO);
&echo(" ".++$i.". ".$dvddir);
+
foreach $dvddir (@dvddirs) {
push(@gooddvddirs,$dvddir);
+
if ((-d "${dvdripto_parentdir}/${dvddir}") and ($dvddir ne '.') and ($dvddir ne '..')) {
last;
+
opendir((DVDDIR), "${dvdripto_parentdir}/${dvddir}");
 +
@dvddircontents = readdir(DVDDIR);
 +
closedir(DVDDIR);
 +
for (@dvddircontents) {
 +
foreach $themask (@dvdfilemasks) {
 +
if (m/\.${themask}$/) {
 +
$gooddvddirs{$dvddir} = "${dvdripto_parentdir}/${dvddir}";
 +
last;
 +
}
 +
}
 
}
 
}
 +
}
 +
}
 +
if (!keys(%gooddvddirs)) {
 +
&out_error("No folders with DVD files found!");
 +
<STDIN>;
 +
exit 1;
 +
} else {
 +
while (($key, $value) = each(%gooddvddirs)) {
 +
&echo("${key}\n");
 
}
 
}
 
}
 
}
Line 1,419: Line 1,459:
 
@errormsgs = ();
 
@errormsgs = ();
 
#if (!m/^([0-9]+[ ]+[0-9]+)+$/) { #regex for if more than one input is required on a line
 
#if (!m/^([0-9]+[ ]+[0-9]+)+$/) { #regex for if more than one input is required on a line
if (!m/^([0-9]+[ ]?)+$/) {
+
if (m/^$/) {
 
push(@errormsgs,"Invalid input.");
 
push(@errormsgs,"Invalid input.");
 
} else {
 
} else {
 
for (split(" ")) {
 
for (split(" ")) {
if ($_ le @gooddvddirs) {
+
if (defined($gooddvddirs{$_})) {
push(@dvdchoices,$gooddvddirs[$_-1]);
+
push(@dvdchoices,$gooddvddirs{$_});
 
} else {
 
} else {
 
push(@errormsgs,"Invalid selection: ${_}");
 
push(@errormsgs,"Invalid selection: ${_}");
Line 1,447: Line 1,487:
 
$i=0;
 
$i=0;
 
$alignedsplice = '';
 
$alignedsplice = '';
for (@dvdchoices) {
+
foreach $dvdchoice (@dvdchoices) {
 
foreach $mask (@dvdfilemasks) {
 
foreach $mask (@dvdfilemasks) {
for (glob("${_}/$mask")) {
+
foreach $mpegfile (glob("${dvdchoice}/$mask")) {
 
$i++;
 
$i++;
 
&echotofile($alignedsplice,">>","${projname}.avs");
 
&echotofile($alignedsplice,">>","${projname}.avs");
Line 1,458: Line 1,498:
 
#dvdtest_1_I01_001.d2v
 
#dvdtest_1_I01_001.d2v
 
#dvdtest_1_I01_001.log
 
#dvdtest_1_I01_001.log
system("\"${dgmpgdec_dir}/${dgindex}\" -IF=[${_}] -OF=[${projname}_${i}_${1}] -PREVIEW -exit");
+
system("\"${dgmpgdec_dir}/${dgindex}\" -IF=[${mpegfile}] -OF=[${projname}_${i}_${1}] -PREVIEW -exit");
&mv("\"${dvdripto_parentdir}/${_}/${i}.log\"","\"${desktop}/${projname}/${projname}_${i}_${1}.log\"");
+
system("\"${dgmpgdec_dir}/${dgindex}\" -IF=[${mpegfile}] -OM=2 -OF=[${projname}_${i}_${1}] -AT=[infotemplate.avs] -exit");
system("\"${dgmpgdec_dir}/${dgindex}\" -IF=[${_}] -OM=2 -OF=[${projname}_${i}_${1}] -AT=[infotemplate.avs] -exit");
+
$mpegfile =~ s/^(.+)\.[^.]+$/$1/;
 +
$logname = $1;
 +
#cut off the path
 +
$logname =~ s/.*([^\/]+)$/$1/;
 +
&mv("${mpegfile}.log","${desktop}/${projname}/${projname}_${i}_${logname}.log");
 
for (glob("${projname}_${i}_*")) {
 
for (glob("${projname}_${i}_*")) {
&echotofile("ac3source(MPEG2source(\"${1}.d2v\",upconv=1),\"$_\").delayaudio(".($2/1000).")\n",">>","${projname}.avs") if (m/^([^ ]+) .+DELAY (-?[0-9]+)ms.*\.ac3$/);
+
&echotofile("ac3source(MPEG2source(\"${1}.d2v\",upconv=1),\"${_}\").delayaudio(".($2/1000).")\n",">>","${projname}.avs") if (m/^([^ ]+) .+DELAY (-?[0-9]+)ms.*\.ac3$/);
&echotofile("audiodub(MPEG2source(\"${1}.d2v\",upConv=1),mpasource(\"$_\")).delayaudio(".($2/1000).")\n",">>","${projname}.avs") if (m/^([^ ]+) .+DELAY (-?[0-9]+)ms.*\.mp.*$/);
+
&echotofile("audiodub(MPEG2source(\"${1}.d2v\",upConv=1),mpasource(\"${_}\")).delayaudio(".($2/1000).")\n",">>","${projname}.avs") if (m/^([^ ]+) .+DELAY (-?[0-9]+)ms.*\.mp.*$/);
&echotofile("audiodub(MPEG2source(\"${1}.d2v\",wavsource(\"$_\"))\n",">>","${projname}.avs") if (m/^([^ ]+).*\.wav$/);
+
&echotofile("audiodub(MPEG2source(\"${1}.d2v\",wavsource(\"${_}\"))\n",">>","${projname}.avs") if (m/^([^ ]+).*\.wav$/);
 
if (defined($3)) {
 
if (defined($3)) {
 
$maxaudiobr = ($3+1000) if $maxaudiobr lt ($3+1000);
 
$maxaudiobr = ($3+1000) if $maxaudiobr lt ($3+1000);
Line 1,470: Line 1,514:
 
}
 
}
 
# If there's more than one file to be joined, they must be appended together.
 
# If there's more than one file to be joined, they must be appended together.
$alignedsplice = "++\\\n";
+
$alignedsplice = "++\n";
 
}
 
}
 
}
 
}
Line 1,478: Line 1,522:
 
}
 
}
  
 +
#system("\"${anri_dir}/${mplayer}\" dvd://${1} -dvd-device ${dvdsource} -dumpstream -dumpfile ${dvdripto}/I${2}_${expandpgc}.vob");
 
############################################################################
 
############################################################################
 
#                              Encoding
 
#                              Encoding

Revision as of 17:37, 27 August 2008

#!/usr/bin/perl

############################################################################
#                               Credits
#
# nathan jahnke <njahnke@gmail.com>
# Ian Bennett
# Philip "ballofsnow" Cornell
# Brett "Psonar" Ables
#
# Anri is distributed under the terms of the Gnu General Public License 3.0:
# http://www.gnu.org/licenses/gpl-3.0.txt
############################################################################

############################################################################
#                               Initialization
#
# Some obvious stuff in here. Desktop location is set using the win32api
# module under Windows.
############################################################################

use warnings;
use strict 'subs';
package anri;

#version of this software, used in building the path to the executable, so must match the value from the installer
$version = '4a1';

#name of this file
$anripl = 'anri.pl';

#cute prompt for user input
$prompt = 'ANRI> ';

#what os are we running? unix is default since there are so many possible flavors
$os = 'unix';
$os = 'windows' if "$^O" eq "MSWin32";

#no auto mode yet
$auto=0;

#nmf off by default, so filename identifier is null
$nmf='';

if ($os eq 'windows') {
	#the below api calls probably require the win32api module(?) to be installed which will have to be included in the anri installer ...
	
	#get the name of the work directory. this is the desktop by default under windows
	use Win32 qw(CSIDL_DESKTOPDIRECTORY);
	$desktop = Win32::GetFolderPath(CSIDL_DESKTOPDIRECTORY);
	
	#get the path to program files so we can build the anri program directory
	use Win32 qw(CSIDL_PROGRAM_FILES);
	$programfiles = Win32::GetFolderPath(CSIDL_PROGRAM_FILES);
	
	#anri program directory
	$anri_dir = "${programfiles}/anri_${version}";
	
	#name of the directory containing dgindex.exe under anri's program directory and of the executable itself
	$dgmpgdec_dir = "${anri_dir}/dgmpgdec152";
	$dgindex = 'dgindex.exe';
	
	#name of the directory containing virtualdub.exe under anri's program directory and of the executables both gui and cli
	$vdub_dir = "${anri_dir}/VirtualDub-1.8.5";
	$vdubgui = 'virtualdub.exe';
	$vdubcli = 'vdub.exe';
	
	#our encoders
	$x264 = 'x264.exe';
	$naac = 'neroaacenc.exe';
	$mp4box = 'mp4box.exe';
	$xvid = 'xvid_encraw.exe';
	$ffmpeg = 'ffmpeg.exe';
	
	#some anri support files
	$directshowsourcelistfile = 'directshowsource_list.txt';
	$pgccount = "pgccount.exe";
	$mplayer = "mplayer.exe";
	$wget = "wget.exe";

	#dunno about this
	$dvdripto_parentdir = "C:\\AnriMPEG";

	#set some keys in the registry to make vdub show only the input video pane (having both the input and output panes open as is default tends to confuse users)
	&update_registry_key("CUser/Software/Freeware/VirtualDub/Persistence/Update input pane", "0x0001", "REG_DWORD");
	&update_registry_key("CUser/Software/Freeware/VirtualDub/Persistence/Update output pane", "0x0000", "REG_DWORD");

	#os-specific commands
	$clear = "CLS";
	#or, for debugging ...
	$clear = "";
	
	############################################################################
	#                              Color Initialization
	# 
	# Edit by: Psonar  -  Brett Ables
	# Below is the code necessary to use the CECHO.exe function
	# to add color to anrichan. Run CECHO.exe /? for usage help.
	# CECHO.exe was written by Thomas Polaert.
	# 
	# The environment variable CECHO is set to the absolute path
	# of the CECHO.exe program so that %CECHO% may be used 
	# to call the function regardless of the working directory
	# 
	# RESET_COLOR is used to reset the default color scheme 
	# after CECHO has been used to output different colors.
	# 
	# Color is a DOS function that affects the whole command 
	# window at once.  It is used only once here to initialize the
	# background color of the window. 80 is the same as {black on gray}.
	# 
	# CECHO is used in out_cls, out_info, out_error, and out_section.
	############################################################################
	
	$cecho = "${anri_dir}/cecho.exe";
	
	$black_on_gray = '{black on gray}';
	$gray_on_black = '{gray on black}';
	$blue_on_black = '{blue on black}';
	$white_on_black = '{white on black}';
	$aqua_on_black = '{aqua on black}';
	$blue_on_black = '{blue on black}';
	$teal_on_gray = '{teal on gray}';
	$navy_on_gray = '{navy on gray}';
	$maroon_on_gray = '{maroon on gray}';
	$maroon_on_silver = '{maroon on silver}';
	$white_on_gray = '{white on gray}';
	$red_on_gray = '{red on gray}';
	
	$reset_color = "\"${cecho}\" ${black_on_gray}";
	system("Color 80");
} else {
	#FIXME UNIX DESKTOP
	
	#color initialization
	
	#os-specific commands
	$clear = "clear";
}

#FIXME LOGFILE STUFF

#FIXME EXTERNAL CONFIGURATION FILE

#main menu

#FIXME: using_settings

############################################################################
#                               Main menu
#
# Anri's home.
############################################################################

while (1) {
	&out_cls;
	&out_info("ON HERMESUS LUC ARSUS ESTARIAS AUC ELTRAS LI CELES! Now, let's get to work!");
	&out_section("Main");
	@mainmenu = (
	['Rip DVD to hard drive (required for DVD material)', 	'&rip_dvd'],
	['Start new project', 					'&project'],
	['Extract sample', 					'&proc_sample'],
	['Station ID preview', 					'&statid_sample'],
	['Exit', 						'exit 0'],
	);
	&out_menu(@mainmenu);
	while (<STDIN>) {
		chomp;
		if (m/([1-5])$/) {
			#execute the contents of this value in the array
			eval($mainmenu[$1-1][1]);
			last;
		}
		print "Invalid input.\n\n";
		&out_menu(@mainmenu);
	}
}

############################################################################
#                         Sample extraction procedure
# 
# Sample extraction is basically regular mode minus a bunch of questions.
# This procedure gets called when a parameter "sample" has been sent to
# anri.bat. There isn't much documentation about how this works since this
# was meant to be short. One thing that's different is that the sample video
# will have separated fields. This is to avoid the problem with interlacing
# and the Yv12 colorspace. The fields are then weaved back together to
# determine DFnD.
############################################################################

sub proc_sample {
#	&out_cls;
	chdir($desktop);
	#FIXME no_pause_before_indexing?
	$projname = 'anri_sample';
	&make_projdir;
	&load_plugins;
	&out_cls_section("Sample Extraction");
	&q_boo($dvdsource,'DVD/MPEG source [y,n]');
	$dvdsource ? &index_dvd : &q_avi;
	&cp("${projname}.avs","${projname}_trimtemp.avs");
	&echotofile("lanczos4resize(320,240)\n",">>","${projname}_trimtemp.avs");
	&out_info("This sample will be 300 frames long. Pick the starting frame of a scene with");
	&out_info("action.");
	&echo("");
	&out_info("Press ENTER to continue ...");
	<STDIN>;
	if ($os eq 'windows') {
		system("START \"trimming vdub\" \"${vdub_dir}/${vdubgui}\" \"${projname}_trimtemp.avs\"");
	} else {
		#how are we going to do this in unix? your guess is as good as mine
	}
	print $prompt;
	while (<STDIN>) {
		chomp;
		if (m/^[0-9]+$/) {
			$startframe = $_;
			last;
		}
		print "Invalid input.\n\n";
		print $prompt;
	}
	&echotofile("trim(${startframe},".($startframe+299).")\n",">>","${projname}.avs");
	&echotofile("AssumeTFF\nSeparateFields\nconverttoyv12\n",">>","${projname}.avs");
	&onepass("${desktop}/${projname}/${projname}.avs","${desktop}/${projname}/${projname}","128000","19",1);
	&cp("${desktop}/${projname}/${projname}.mp4","${desktop}");
# 	@todel = (
# 		"${projname}*.avs",
# 		"${projname}.bak",
# 		"${projname}*.d2v",
# 		"${projname}VTS*",
# 		"log*.txt",
# 	);
	chdir("${desktop}");
	&rm("${desktop}/${projname}");
	&echo("\n\n${white_on_gray}Finished. You will find a sample.mp4 file on your desktop. Feel free to rename it something more descriptive like nameofgame_sample.mp4.");
	&echo("\n${red_on_gray} - READ -${white_on_gray} You will see that the video has been resized vertically.");
	&echo("${red_on_gray}THIS IS NORMAL${white_on_gray} and will make it easier for the techies to help you.");
	system($reset_color);
	<STDIN>;
	exit 0;
}

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

sub project {
	&out_cls;
	&out_info("ON HERMESUS LUC ARSUS ESTARIAS AUC ELTRAS LI CELES! Now, let's get to work!");
	&out_section("PROJECT SETUP");
	#IF NOT "%auto%"=="y" (CALL :q_projname)
	
	&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.). You may not use spaces or the % character in the name, sorry.");
	&echo("");
	&echo("${white_on_gray}All files associated with this project will appear in ${navy_on_gray}${desktop}\\(project name)\n");
	system($reset_color);
	&echo("");
	print $prompt;
	while (<STDIN>) {
		chomp;
		if (!m/[% ]/) {
			$projname = $_;
			last;
		}
		print "You may not use spaces or the % character in the name, sorry.\n\n";
		print $prompt;
	}
	&make_projdir;
	&load_plugins;
	#FIXME settings manager
	#CALL :find_existing_settings
	#IF "%using_settings%"=="y" GOTO proc_check_settings
	
	############################################################################
	# Main procedure - Movie source
	# 
	# It's either DVD or AVI, no exceptions (for now). The current method for
	# DVD extraction is as follows: Find and validate the DVD folder. Check for
	# the existence of IFO files (has details on structure of DVD). If they are
	# found, the IFO is analyzed and ripped with Mplayer. Otherwise it goes
	# straight to DGindex.
	# 
	# Why Mplayer? It has the ability to rip files per program chain. There is
	# a problem where indexing multiple program chains can cause audio desync.
	# Now that we get the data on a per PGC basis, we can index them individually
	# and join them up later in AviSynth which can properly align video/audio.
	# 
	# There are two methods for loading AVI files. Either the user enters the
	# paths to the file individually, or specifies a directory and anri-chan
	# loads all AVI files alphabetically. There is currently no validation for
	# AVI files with different video properties.
	############################################################################
	
	&out_cls_section("MOVIE SOURCE");
	&out_info("If you used a capture card with DVD or MPEG settings, place those files in");
	&out_info("${dvdripto_parentdir}\\foldername\\ and then answer y to the question below.");
	&echo("");
	&q_boo($dvdsource,'DVD/MPEG source [y,n]');
	#IF NOT "%auto%"=="y" CALL :q_dvdsource
	if ($dvdsource) {
		#automation changes for q_driveletter are handled within the function b/c 
		#important code related to ripping and dgindex is found there.
		&index_dvd;
	} else {
		#q_avi must be called (even in "auto" mode) for avs files to be set up properly
		&q_avi;
	}

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

	#:proc_gameproperties
	&out_cls_section("GAME PROPERTIES");
	if ((!$dvdsource) and (!$auto)) {
		&q_boo($isPCGAME,"Is this a PC game/non-console run recorded with screen capture software? If you say no, your video will be treated as NTSC / PAL.");
	}
	if ($isPCGAME) {
		$d=1 if not defined($d);
		$f=1 if not defined($f);
		$twod=0 if not defined($twod);
		$hqq=19 if not defined($hqq);
		$prog=1 if not defined($prog);
		#&proc_gameproperties_p2;
	}

	$dfnd_set = 0;
	&q_dfnd if !$auto;
	if (!$dfnd_set) {
		if (!$auto) {
			&echo("");
			&out_info("\"D\" and \"F\" are 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("");
			&out_info("Find D and F for your game at this URL:");
			&out_info("http://speeddemosarchive.com/kb/index.php/DF");
			&echo("");
			&out_info("If you don't see your game listed there, you can use the Extract Sample main menu option 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("");
			&echo("Please enter 1 or 4 for D.");
			print $prompt;
			while (<STDIN>) {
				chomp;
				if (m/^[14]$/) {
					$d = $_;
					last;
				}
				print "Invalid input.\n\n";
				print $prompt;
			}
			&echo("Please enter 1, 2 or 3 for F.");
			print $prompt;
			while (<STDIN>) {
				chomp;
				if (m/^[123]$/) {
					$f = $_;
					last;
				}
				print "Invalid input.\n\n";
				print $prompt;
			}
		}
		if ($f eq 1) {
			$twod=0;
			&q_2d if !$auto;
		}
		if (!$auto) {
			#:q_submit_dfnd
			&echo("");
			&out_info("You didn't use the SDA games database. Does that mean that it didn't have your game? If so, we'd love it if you posted the \"D\", \"F\" and maybe \"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("");
			system("START http://speeddemosarchive.com/forum/index.php?action=post;topic=6416.0") if &q_boo($throwaway,"Submit this game's data to SDA? [y,n]");
			#:dfnd_is_set
		}
	}
	$hqq = 17 if $d == 4;
	$hqq = 19 if $d == 1;

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

	&out_cls_section("VIDEO PROPERTIES");
	if (!$auto) {
		&q_boo($prog,"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.");
	}
	#IF "%prog%"=="y" GOTO proc_gameproperties_p2
	
	
	############################################################################
	# function: q_fieldorder
	# 
	# There's no foolproof method to detect field order programmatically. The
	# next best thing is to show the user both, and let them decide which looks
	# better.
	# 
	# The script is simple enough, have a split screen with AssumeTFF and
	# AssumeBFF. Whichever is chosen will be used in all AviSynth scripts.
	############################################################################

	&echo("");
	&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 looks better. Enter t for top, or b for bottom. If both look good, enter t.");
	&out_info("Press ENTER to continue ...");
	<STDIN>;
	&echo("");
	&cp("${projname}.bak","${projname}_fieldordertemp.avs");
	&echotofile("tff=last.AssumeTFF().SeparateFields().bilinearresize(320,240).subtitle(\"t\")\n",">>","${projname}_fieldordertemp.avs");
	&echotofile("bff=last.AssumeBFF().SeparateFields().bilinearresize(320,240).subtitle(\"b\")\n",">>","${projname}_fieldordertemp.avs");
	&echotofile("StackVertical(tff,bff)\n",">>","${projname}_fieldordertemp.avs");
	system("START \"determine field order\" \"${vdub_dir}/${vdubgui}\" \"${projname}_fieldordertemp.avs\"");
	#:q_fieldorder_p2
	print $prompt;
	while (<STDIN>) {
		chomp;
		if (m/^[tb]$/) {
			#t becomes 1 (true), b becomes 0 (false)
			tr/tb/10/;
			$fieldorder = $_;
			last;
		}
		print "Invalid input.\n\n";
		print $prompt;
	}
	&out_info("You may now close the VirtualDub window.");
	&rm("${projname}_fieldordertemp.avs");
	&echo("");

	#q_vhs
	&q_boo($vhs,"Did you use VHS to help capture this run? [y/n]");

	#IF "%d%"=="1" GOTO proc_gameproperties_p2

	&q_boo($onepixel,"1 pixel bob ... answer y if it's jumping up and down, otherwise n.") if !$auto and ($f != 2);

	&q_boo($nes,"NES [y/n]") if !$auto;
	#IF "%nes%"=="y" GOTO proc_gameproperties_p2

	&q_boo($gba,"Game Boy Advance [y/n]") if !$auto;
	$deflicker=1 if $gba;
	#GOTO proc_gameproperties_p2

	&q_boo($gb,"Game Boy [y/n]") if !$auto;
	$deflicker=1 if $gb;

	&q_boo($deflicker,"Deflickered (rereleased old game e.g. Mega Man AC, Sonic Mega Collection, Wii Virtual Console) [y,n]") if !$auto and ($f != 2);

	############################################################################
	# Main procedure - Content properties
	# 
	# For trimming, we startup another vdub instance and ask the user to input
	# frame numbers. The frame numbers will go into a single variable separated
	# by spaces. There is currently no validation for entering a frame range
	# like 50 to 30... or negative numbers. Users can enter dummy values and edit
	# project_job.bat later on and it will still work.
	# 
	# StatID... not much to it. Three lines, quotations are allowed. Gets appended
	# at beginning and end of video.
	############################################################################

	#:proc_gameproperties_p2
	&out_cls_section("CONTENT PROPERTIES");
	if (!$auto) {
		&out_info("Trimming lets you remove the start and end of the existing movie so you only keep the run itself.");
		&q_boo($trim,"Do you want to trim off unwanted content in this video? [y,n]");

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

		if ($trim) {
			&echo("");
			&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("");
			&out_info("You can specify multiple ranges of frames. - Type n to quit -");
			&out_info("Press ENTER to continue ...");
			<STDIN>;
			&echo("");
			&cp("${projname}.bak","${projname}_trimtemp.avs");
			if ($isPCGAME) {
				&echotofile("Lanczos4Resize(320,round(last.height*(320.000/last.width)))",">>","${projname}_trimtemp.avs");
				&echotofile("last.height %% 2 == 1 ? AddBorders(0,0,0,1) : NOP",">>","${projname}_trimtemp.avs");
				&echotofile("last",">>","${projname}_trimtemp.avs");
			} else {
				&echotofile("Lanczos4Resize(320,240)",">>","${projname}_trimtemp.avs");
			}
			system("START \"trimming vdub\" \"${vdub_dir}/${vdubgui}\" \"${projname}_trimtemp.avs\"");
			@trimarr = ();
			print $prompt;
			while (<STDIN>) {
				chomp;
				#error codes' precedence is descending, e.g. empty string is first because it is the most serious error
				if ($_ eq '') {
					$errormsg="You must enter a frame number, or type n to quit.";
				} elsif (m/^n$/i) {
					if (@trimarr < 1) {
						&out_info("No values entered. Canceling trim.");
						$trim=0;
						last;
					} elsif (@trimarr % 2) {
						&out_error("Odd number of frame numbers detected! All trim values erased!");
						@trimarr = ();
					}
				} elsif (!m/^[0-9]+$/i) {
					$errormsg="Invalid input. Must be frame number.";
				} else {
					push(@trimarr,$_);
					&out_info('trim point #'.@trimarr.' loaded successfully!');
					&echo("");
					print $prompt;
					next;
				}
				&out_error($errormsg);
				print $prompt;
			}
			&rm("${projname}_trimtemp.avs");
		}
		
		#statid stuff
		&out_cls_section("Station ID");
		&out_info("Set the info shown on the Station ID (the clip at the start of an SDA video). Run the Station ID Preview program for a preview.");
		&q_boo($statid,"Do you want to append an SDA Station ID to the front and end of this video? [y,n]");
		if ($statid) {
			@statidlines = ();
			&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.");
			for ($i = 1 ; $i <= 3 ; $i++) {
				&out_info("Station ID Line ${i}:");
				print $prompt;
				$statidline = <STDIN>;
				$statidline =~ s/"/"+chr(34)+"/g;
				push(@statidlines,'"'.$statidline.'"');
				&echo("");
			}
		}
	} #end of !$auto

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

	#:proc_check_settings
	&cd("${desktop}/${projname}");
	$ready=1;
	$ready=0 if !&samefiles("${projname}_job.bat","${projname}_job.bak");
	foreach $thefile ("${projname}_LQ.avs","${projname}_LQ_xvid.avs","${projname}.avs","${projname}_xvid.avs","${projname}_HQ.avs","${projname}_IQ.avs") {
		$ready=0 if !-e $thefile;
	}
	if (!$ready) {
		&savesettings;
		&script_buildfiles;
	}

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

	if (!$auto) {
		&check_settings;
	} else {
		$settings_good=1;
	}
	#IF NOT "%settings_good%"=="y" GOTO proc_check_settings_p2
	
	&out_cls_section("READY TO ENCODE");
	&out_info("Your settings for this project have been saved to \"${projname}_job.bat\". To resume the project, double-click that file.");

	if (!$auto) {
		&q_encodenow;
	} else {
		$start_encode=1;
	}

	if ($start_encode) {
		&proc_encode;
	} else {
		&proc_encode;
	}

	#: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=

	&rm("${projname}_job.bat");
	&rm("${projname}_job.bak");
	#GOTO proc_gameproperties

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

	#:proc_encode

	&out_cls_section("ENCODING OPTIONS");
	if (!$auto) {
		&savesettings;

		@encodethese = ();
		#makethisboolean, howtomake, english, id tag, video bitrate in kbaud, audio bitrate in baud, minimum quantizer for x264, delete 2pass stats, delete all other tempfiles
		for (
		#	0		1			2		3	4	5		6	7 8
		[	1,	'&twopass',	"Low quality H.264 MP4",	"_LQ",	128,	64000,		17,	1,1],
		[	1,	'&ipod',	"Medium quality H.264 MP4",	"",	512,	64000,		17,	1,1],
		[	1,	'&twopass',	"High quality H.264 MP4",	"_HQ",	2048,	128000,		$hqq,	1,1],
		[($d&&$f),	'&twopass',	"Insane quality H.264 MP4",	"_IQ",	5000,	$maxaudiobr,	19,	1,1],
		[($d&&$f),	'&twopass',	"X-Treme quality H.264 MP4",	"_XQ",	10000,	$maxaudiobr,	19,	1,1],
		[	1,	'&xvid',	"Low quality XviD AVI",		"",	128,	64000,		"",	1,1],
		[	1,	'&xvid',	"Medium quality XviD AVI",	"_LQ",	512,	64000,		"",	1,1],
		) {
			if ($_[0]) {
				push (@encodethese,@_) if &q_boo($throwaway,"Create ${_[2]} (".($_[4]+($_[5]/1000))." Kbps) video? [y/n]");
			}
		}
		
	}
	
	$_ = $_[3];
	&nmf if (
		(($d&&$f) and ($_[3] eq "_HQ"))
	or
		(m/^(_IQ|_XQ)$/)); #any iq/xq
	
	&out_cls_info("Now encoding ...");
	for (@encodethese) {
		#			0		     1      2     3     4     5     6
		eval("${_[1]} ${projname}.${_[3]}.${nmf}.'.avs' ${projname} ${_[4]} ${_[5]} ${_[6]} ${_[7]} ${_[8]}");
	}
}

sub nmf {
	$nmf = '_nmf';
}

# MD finished > NUL 2>&1
# 
# FOR %%G IN (*.bat) DO (
#   ECHO ---------------------------------------- >> .\finished\%log%
#   ECHO  Contents of %%G >> finished\%log%
#   ECHO ---------------------------------------- >> finished\%log%
#   ECHO. >> finished\%log%
#   TYPE "%%G" >> finished\%log%
#   ECHO. >> finished\%log%
#   ECHO. >> finished\%log%
#   ECHO. >> finished\%log%
# )
# 
# ECHO ---------------------------------------- >> finished\%log%
# ECHO  Contents of project folder >> finished\%log%
# ECHO ---------------------------------------- >> finished\%log%
# ECHO. >> finished\%log%
# DIR >> finished\%log%
# ECHO. >> finished\%log%
# ECHO. >> finished\%log%
# 
# FOR %%G IN (*.avs) DO (
#   ECHO ---------------------------------------- >> finished\%log%
#   ECHO  Contents of %%G >> finished\%log%
#   ECHO ---------------------------------------- >> finished\%log%
#   ECHO. >> finished\%log%
#   TYPE "%%G" >> finished\%log%
#   ECHO. >> finished\%log%
#   ECHO. >> finished\%log%
#   ECHO. >> finished\%log%
# )
# 
# FOR %%G IN (*.log) DO (
#   ECHO ---------------------------------------- >> finished\%log%
#   ECHO  Contents of %%G >> finished\%log%
#   ECHO ---------------------------------------- >> finished\%log%
#   ECHO. >> finished\%log%
#   TYPE "%%G" >> finished\%log%
#   ECHO. >> finished\%log%
#   ECHO. >> finished\%log%
#   ECHO. >> finished\%log%
# )
# COPY finished\%log% finished\%log:~0,-4%.bak > NUL
# ATTRIB +H finished\%log:~0,-4%.bak
# 
# MOVE /Y %PROJNAME%_LQ.avi finished > NUL 2>&1
# MOVE /Y %PROJNAME%.avi    finished > NUL 2>&1
# MOVE /Y %PROJNAME%_LQ.mp4 finished > NUL 2>&1
# MOVE /Y %PROJNAME%.mp4    finished > NUL 2>&1
# MOVE /Y %PROJNAME%_HQ.mp4 finished > NUL 2>&1
# MOVE /Y %PROJNAME%_IQ.mp4 finished > NUL 2>&1
# MOVE /Y %PROJNAME%_XQ.mp4 finished > NUL 2>&1
# 
# 
# :proc_close
# ECHO.
# ECHO.
# IF "%IQskipped%"=="true" (
#   ECHO HQ reached the quality limit imposed by SDA. IQ would reach the same limit, therefore it has been skipped. | "%anri_dir%tee.exe" -a finished\read.txt
#   ECHO. | "%anri_dir%tee.exe" -a finished\read.txt
# )
# IF "%XQskipped%"=="true" (
#   ECHO You chose XQ for high definition video. HQ reached the quality limit imposed by SDA so IQ was encoded with XQ settings and XQ has been skipped. | "%anri_dir%tee.exe" -a finished\read.txt
#   ECHO. | "%anri_dir%tee.exe" -a finished\read.txt
# )
# IF "%XQskipped%"=="notHD" (
#   ECHO You chose XQ for high definition video however Anri-chan determined that it is not truly HD. XQ has been skipped. | "%anri_dir%tee.exe" -a finished\read.txt
#   ECHO. | "%anri_dir%tee.exe" -a finished\read.txt
# )
# CALL :out_info All dun.
# ECHO.
# GOTO die












############################################################################
#                               File Handling
#
# Handle files in project directory.
############################################################################

#string, > or >>, filepath
#not much here yet but may need to modify in the future
#don't forget the \n if you want a newline as this won't do it otherwise
sub echotofile {
	open(OUTFILE, "${_[1]}${_[2]}");
	print OUTFILE $_[0];
	close(OUTFILE);
}

sub samefiles {
	open(FILEONE, $_[0]);
	@fileone=<FILEONE>;
	close(FILEONE);
	open(FILETWO, $_[1]);
	@filetwo=<FILETWO>;
	close(FILETWO);
	#are they the same number of lines?
	return 0 if @fileone != @filetwo;
	#compare each line ... can tell the line on which they differ but currently no use for it in anri
	for ($f = 0 ; $f < @fileone ; $f++) {
		return 0 if $fileone[$f] ne $filetwo[$f];
	}
	return 1;
}

sub make_projdir {
	chdir($desktop);
	mkdir($projname) if !-e $projname;
	chdir($projname);
	&cp("${anri_dir}/silence_stereo_48000.wav","${desktop}/${projname}");
	&cp("${dgmpgdec_dir}/infotemplate.avs","${desktop}/${projname}");
	&cp("${anri_dir}/ntsc_d1.png","${desktop}/${projname}");
}

sub wipe_avs {
	chdir("${desktop}/${projname}");
	&rm("*.avs") if -e "${projname}.avs";
	&cp("${projname}.bak","${projname}.avs");
	&cp("plugins.bak","plugins.avs");
}

#load_plugins makes a file plugins.avs in the project directory that contains the proper loadplugin() or import() declarations for every plugin (defined as a file ending in .dll or .avs) found under $anri_dir/plugins.
sub load_plugins {
	&rm("plugins.avs") if -e "plugins.avs";

	opendir(PLUGINS, "${anri_dir}/plugins");
	@plugins = readdir(PLUGINS);
	closedir(PLUGINS);
	for (@plugins) {
		if (m/.*\.([dll]+)$/i) {
			&echotofile("loadplugin(\"${anri_dir}/plugins/${_}\")\n",">>","plugins.avs");
		} elsif (m/.*\.([avs]+)$/i) {
			&echotofile("import(\"${anri_dir}/plugins/${_}\")\n",">>","plugins.avs");
		}
	}
	&cp("plugins.avs","plugins.bak");
}

############################################################################
#                               Windows
#
# These subroutines make use of the win32api module.
############################################################################

#fullpathtokey, data, type
sub update_registry_key {
	use Win32::TieRegistry(Delimiter=>"/",ArrayValues=>0);
	$Registry->{$_[0]} = [ $_[1], $_[2] ];
}

############################################################################
#                               System
#
# These subroutines send OS-dependent shell commands.
############################################################################

#path
#/D means change even if cwd is on a different drive letter
# sub cd {
# 	$flags = '';
# 	$flags = ' /D' if $os eq 'windows';
# 	
# 	#for debugging
# 	$command = "cd${flags} \"${_[0]}\"";
# 	print "$command\n";
# 	system($command);
# }

#path, newpath (both can be relative)
#/Y means overwrite (i.e. automatically say Yes to the overwrite question)
#/B means force binary copy (do not attempt to translate line endings)
#-R means recursive (copy directories and the files in them as well as just files)
sub cp {
	if ($os eq 'windows') {
		for (@_) {
			#COPY gives me errors unless the path delimiter is \ under doze
			s,/,\\,g if m,/,;
		}
	}
	
	$command = 'cp';
	$command = 'COPY' if $os eq 'windows';
	
	$flags = ' -R';
	$flags = ' /Y /B' if $os eq 'windows';
	
	$redirect = '';
	$redirect = ' > NUL' if $os eq 'windows';
	
	$command = "${command}${flags} \"${_[0]}\" \"${_[1]}\"${redirect}";
	#for debugging
#	print $command."\n";
	system($command);
}

#path, newpath (both can be relative)
#/Y means overwrite (i.e. automatically say Yes to the overwrite question)
#-R means recursive (copy directories and the files in them as well as just files)
sub mv {
	if ($os eq 'windows') {
		for (@_) {
			#MOVE gives me errors unless the path delimiter is \ under doze
			s,/,\\,g if m,/,;
		}
	}
	
	$command = 'mv';
	$command = 'MOVE' if $os eq 'windows';
	
	$flags = ' -R';
	$flags = ' /Y' if $os eq 'windows';
	
	$redirect = '';
	$redirect = ' > NUL' if $os eq 'windows';
	
	$command = "${command}${flags} \"${_[0]}\" \"${_[1]}\"${redirect}";
	#for debugging
#	print $command."\n";
	system($command);
}

#path
#-r means recursive (delete directories and the files in them as well as just files)
#-f means force (don't ask for confirmation, just do it - may be necessary on some red hat linux installs)
#/Q means don't ask for confirmation
#/S means recursive (delete directories and the files in them as well as just files)
sub rm {
	if ($os eq 'windows') {
		for (@_) {
			#COPY gives me errors unless the path delimiter is \ under doze
			s,/,\\,g if m,/,;
		}
	}

	$command = 'rm';
	$command = 'DEL' if $os eq 'windows';
	
	$flags = ' -rf';
	$flags = ' /Q /F' if $os eq 'windows';
	
	for (@_) {
		#is this a directory?
		if (-d "$_") {
			$command = 'RD' if $os eq 'windows';
			$flags = ' /Q /S' if $os eq 'windows';
		}
		
		system("${command}${flags} \"${_}\"");
	}
}

#lol it says subtitle - set the console's title
sub title {
	if ($os eq 'windows') {
		system('TITLE '.$_[0]);
	} else {
		system('declare -x PROMPT_COMMAND=\'printf "\e]0;'.$_[0].'\a"\'');
	}
}

############################################################################
#                               Input
#
# These subroutines get data from the user.
############################################################################

# function: q_boo
# sets boolean variable (0 or 1)
#variable to set, out_info text
sub q_boo {
	&out_info($_[1]);
	print $prompt;
	while (<STDIN>) {
		chomp;
		if (m/^[yn]$/) {
			#t becomes 1 (true), b becomes 0 (false)
			tr/yn/10/;
			$_[0] = $_;
			last;
		}
		print "Invalid input.\n\n";
		print $prompt;
	}
	return $_[0];
}

############################################################################
# function: q_avi
# 
# Ask the user if he wants to do manual input of file paths, or automatically
# by loading the files in a specified directory alphabetically.
############################################################################
sub q_avi {
	$maxaudiobr = 320000;
	&out_cls_section("AVI SOURCE");
	&out_info("Enter the path to each avi file [i]ndividually or [a]utomatically. Note that if you choose automatic, Anri will load the files in an alphabetical manner. The files must have the same resolution and framerate to be joined together.");
	&echo("");
	print $prompt;
	while (<STDIN>) {
		chomp;
		if (m/([ia])$/) {
			#i becomes 1 (true), a becomes 0 (false)
			tr/ia/10/;
			$_ ? &q_avi_i : &q_avi_a;
			last;
		}
		print "Invalid input.\n\n";
		print $prompt;
	}

	#IF "%auto%"=="y" GOTO avimethod_skip
	#:avimethod_skip
	#AVI files loaded, generate avs source lines.
	&echotofile("import(\"${anri_dir}/sda.avs\")\n",">>","${projname}.avs");
	&echotofile("import(\"${desktop}/${projname}/plugins.avs\")\n",">>","${projname}.avs");
	$alignedsplice = '';
	for $avifile (@avifiles) {
		&echotofile($alignedsplice,">>","${projname}.avs");
		if ($os eq 'windows') {
			@fourccstuff = qx("\"${anri_dir}/cfourcc.exe\" \"${avifile}\"");
			$fourcc = join('',@fourccstuff);
			#"${anri_dir}/cfourcc.exe" "%avifolder%%%~G" >> running_log.txt
			$fourcc =~ s/.*Use : (....).*/$1/s;
			open(DSHOW, "${anri_dir}/${directshowsourcelistfile}");
			@directshowsourcelist=<DSHOW>;
			close(DSHOW);
			for (@directshowsourcelist) {
				chomp;
				$use_dshow{lc($_)} = 1;
			}
			$sourcedecverb = 'avisource';
			$sourcedecverb = 'directshowsource' if $use_dshow{lc($fourcc)};
			&echotofile("${sourcedecverb}(\"${avifile}\")",">>","${projname}.avs");
			$alignedsplice = "++\\\n";
		} else {
			#unix avi source declaration stuff goes here?
		}
	}
	#newline needed
	&echotofile("\nconverttoyuy2()\n",">>","${projname}.avs");
	&cp("${projname}.avs","${projname}.bak");
}

############################################################################
# function: q_avi_i
# 
# Manually add each file path to @avifiles. Do some validation; no 
# resolution check yet.
############################################################################
sub q_avi_i {
	&echo("");
	&out_info('Path to source video file e.g. c:\path to\video.avi without quotes.');
	&out_info("  - Type n to quit -");
	&echo("");
	#:q_avi_i_p2
	print $prompt;
	while (<STDIN>) {
		chomp;
		#error codes' precedence is descending, e.g. empty string is first because it is the most serious error
		if ($_ eq '') {
			$errormsg="You must enter a path, or type n to quit.";
		} elsif (m/^n$/i) {
			if (@avifiles < 1) {
				$errormsg="You must load at least one avi file.";
			} else {
				last;
			}
		} elsif (!m/.*\.av[si]$/i) {
			$errormsg="Must be an avi file, try again.";
		} elsif (! -e $_) {
			$errormsg="File does not exist, try again.";
		} else {
			push(@avifiles,$_);
			&out_info('avi #'.@avifiles.' loaded successfully!');
			&echo("");
			print $prompt;
			next;
		}
		&out_error($errormsg);
		print $prompt;
	}
}

############################################################################
# function: q_avi_a
# 
# Automatic file loading. User just has to specify a directory and it will
# load the files alphabetically.
############################################################################
sub q_avi_a {
	&echo("");
	#saved this string in a variable for use later on down
	$enterhelp = 'Enter the path to the avi folder e.g. c:\my video folder\ without quotes.';
	&out_info($enterhelp);
	print $prompt;
	#Validate avifolder. Check for blank, then :\ for full path if windows, then see whether it exists.
	while (<STDIN>) {
		@avifiles = ();
		chomp;
		if (m/^$/) {
			$errormsg="You must enter a path.";
		} elsif (m/^.[^:][^\\].*/) {
			$errormsg="Must be full path.";
		} elsif (! -e $_) {
			$errormsg="Folder does not exist.";
		} else {
			$avifolder = $_;
			#remove any and all / or \ characters from the end of the path
			$avifolder =~ s/[\/]*$//;
			
			#build list
			for (<$avifolder/*.avi>) {
				push(@avifiles,$_);
				print $_."\n";
			}
			
			#user can accept if files were found
			if (@avifiles == 0) {
				$errormsg = 'No avi files found in that folder!';
			} else {
				#Ask user if the list is good.
				&echo('Continue [y] or rescan [n]?');
				print $prompt;
				while (<STDIN>) {
					chomp;
					last if (m/^[yn]$/);
					
					print "Invalid input.\n\n";
					print $prompt;
				}
				
				#do we need to do this whole thing again?
				last if $_ eq 'y';
				$errormsg = $enterhelp;
			}
		}
		&out_error($errormsg);
		print $prompt;
	}
}

############################################################################
# function: q_dfnd
# 
# FIXME
############################################################################
sub q_dfnd {
	&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. However, you must be connected to the Internet to use it.");
	&q_boo($dfnd,"Do you want to use Anri-chan's games database [Y] or enter the data yourself [N]?");
	if ($dfnd) {
		#:dfnd
		&out_info("Anri will now attempt to connect to SDA's games database. This may take a few moments. Once complete, you will see a list of all games in the database.");
		&out_info("Press ENTER to continue ...");
		<STDIN>;
		&echo("");
		@dfnddata = ();
		$dfpage = "\"${anri_dir}/${wget}\"".' -qO- --user-agent="Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en-US; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14" "http://speeddemosarchive.com/kb/index.php/DF"';
		$_ = join("",qx($dfpage));
		#must be only one table on that page ... or at least the dfnd data must be in the first one ... but bman assumed this too and it was ok
		if (s/.*<table>(.+)<\/table>.*/$1/s) {
			@rows = split(/<\/tr>\n<tr>/);
			for (@rows) {
				chomp;
				#we don't want the header row
				next if m/<th/;
				@data = split(/<\/?t[dr]>+/);
				$nes = $gb = $gba = $d = $f = $twod = 0;
				for (@data) {
					$nes = 1 if m/for [^ ]*NES[^ ]*$/;
					if (m/(for [^ ]*GBC?[^ ]*)|(for Game Boy( Color)?)$/) {
						$gb = 1;
					}
					if (m/(for [^ ]*GBA[^ ]*)|(for Game Boy Advance)$/) {
						$gba = 1;
					}
					$d = $1 if m/^D([14])$/;
					$f = $1 if m/^F([123])$/;
					if (m/^([23])D$/) {
						$twod = $1;
						$twod =~ tr/23/10/;
					}
				}
#			 			0    1   2    3     4     5     6
				push(@dfnddata,[$_, $d, $f, $twod, $nes, $gb, $gba]);
			}
			$titles = '';
			for $i ( 0 .. $#dfnddata ) {
				$title = $dfnddata[$i][0];
				$title =~ s/^<td>([^<]+)<\/td>.+/$1/;
				$title =~ s/&/\&/g;
				$titles .= "".($i+1).": ${title}\n";
			}
			print $titles;
			#system("echo \"${titles}\" | more");
			print $prompt;
			while (<STDIN>) {
				chomp;
				if (m/^$/) {
					$errormsg="You must choose a game.";
				} elsif (m/[^0-9]/) {
					$errormsg="Please enter the number of a game.";
				} elsif (($_ gt @dfnddata) or ($_ le 0)) {
					$errormsg="Invalid selection.";
				} else {
					$gamechoice = $_;
					last;
				}
				&out_error($errormsg);
				print $prompt;
			}
			$gamechoice--;
			$d = $dfnddata[$gamechoice][1];
			$f = $dfnddata[$gamechoice][2];
			$twod = $dfnddata[$gamechoice][3];
			$nes = $dfnddata[$gamechoice][4];
			$gb = $dfnddata[$gamechoice][5];
			$gba = $dfnddata[$gamechoice][6];
			$dfnd_set = 1;
		} else {
			&out_error("Could not connect to SDA!");
			&q_dfnd if &q_boo($throwaway,"Try again? [y/n]");
		}
	}
}

############################################################################
#                               Output
#
# These subroutines send data to the console.
############################################################################

sub echo {
	$_[0] = '' if not defined $_[0];
	if ($os eq 'windows') {
		system("\"${cecho}\" ".$_[0].'{\n}');
	} else {
		print $_[0]."\n";
	}
}

sub out_cls {
	system($clear);
	&echo("${gray_on_black}                                                                               ");
	&echo("${blue_on_black}===============================================================================");
	&echo("${white_on_black}                        Speed Demos Archive Anri ${version}");
	&echo("${aqua_on_black}       http://speeddemosarchive.com/     http://www.metroid2002.com/           ");
	&echo("${blue_on_black}===============================================================================");
	&echo("");
	system($reset_color);
}

sub out_info {
	$_[0] = '' if not defined $_[0];
	&echo("${white_on_gray}$_[0]");
	system($reset_color);
}

sub out_error {
	$_[0] = '' if not defined $_[0];
	&echo("${maroon_on_gray}[!]");
	for (@_) {
		&echo("${maroon_on_gray}[!] ${maroon_on_silver}".$_);
	}
	&echo("${maroon_on_gray}[!]");
	system($reset_color);
	&echo("");
}

sub out_section {
	$_[0] = '' if not defined $_[0];
	&title("Anri-chan ${version} - ".$_[0]);
	&echo("${teal_on_gray}-------------------------");
	&echo("${navy_on_gray}".$_[0]."");
	&echo("${teal_on_gray}-------------------------");
	system($reset_color);
	&echo("");
}

sub out_cls_section {
	&out_cls;
	&out_section($_[0]);
}

sub out_cls_info {
	&out_cls;
	&out_info($_[0]);
}

#print the numbered english half of a 2d array consisting of english,command pairs and show the anri prompt at the end
sub out_menu {
	for ($i = 0; $i < @_; $i++) {
		print " ".($i+1).". ".$_[$i][0]."\n";
	}
	print "\n${prompt}";
}

############################################################################
#                               Acquisition
#
# Import video.
############################################################################

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

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

sub rip_dvd {
	&out_cls_section("Rip DVD");
	if (!$auto) {
		&out_info("What is the drive letter of your DVD drive (e.g. D)?");
		&out_info("Tip: If you already have your DVD source files on your hard drive, move them into C:\\VIDEO_TS\\ and enter C as your drive letter.");
		print $prompt;
		while (<STDIN>) {
			chomp;
			if (m/^[a-z]$/i) {
				$driveletter = $_;
				last;
			} else {
				$errormsg="You must enter a drive letter. Enter e.g. D, not D: or D:\\.";
			}
			&out_error($errormsg);
			print $prompt;
		}
	}
	&echo("");
	&out_info("Anri-chan will extract to the ${dvdripto_parentdir} parent directory. Name a folder for your DVD files.");
	print $prompt;
	while (<STDIN>) {
		chomp;
		if (!m/^$/) {
			$dvdripto = "${dvdripto_parentdir}/${_}";
			mkdir($dvdripto) if !-e $dvdripto;
			last;
		} else {
			$errormsg="You must enter a folder name.";
		}
		&out_error($errormsg);
		print $prompt;
	}
	&echo("");
	&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.");
	&out_info("Press ENTER to continue ...");
	&echo("");
	<STDIN>;

	if (-e "${driveletter}:/VIDEO_TS") {
		$dvdsource = "${driveletter}:/VIDEO_TS";
		if (glob("${dvdsource}/VTS*.IFO")) {
			$ifofiles = join(" ",(glob("${dvdsource}/VTS*.IFO")));
			#forward slash as path delimiter confuses pgccount
			#$ifofiles =~ s,/,\\,g;
			$pgccountcommand = "\"${anri_dir}/${pgccount}\" ${ifofiles}";
			@pgclist = split("\n",qx($pgccountcommand));

			if ($advanced_mode) {
		#       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
		#         )
		#       )
		#     )
			}

			#Rip the titles with Mplayer using info from pgclist.txt
			for (@pgclist) {
				m/^([^,]+),.+\/VTS_([0-9][0-9])_.*$/;
				#zero pad to 3 places to avoid sorting problems where 10 comes before 1.
				$expandpgc = sprintf("%03d", $1);
				#FIXME log this
				system("\"${anri_dir}/${mplayer}\" dvd://${1} -dvd-device ${dvdsource} -dumpstream -dumpfile ${dvdripto}/I${2}_${expandpgc}.vob");
			}
		} else {
			&cp("${dvdsource}/*","${dvdripto}");
		}
	} else {
		if (-e "${driveletter}/DVD_RTAV") {
			&cp("${driveletter}/DVD_RTAV/*","${dvdripto}");
		} else {
			&echo("Neither VIDEO_TS or DVD_RTAV folder was found on ${driveletter}:\\. Anri-chan is displeased.");
			#GOTO DIE
		}
	}
	&out_info("Finished ripping. Press ENTER to continue ...");
	<STDIN>;
}

sub index_dvd {
	$maxaudiobr = 320000;
	&out_cls_info("Here is the list of folders containing DVD/MPEG files (*.mpg, *.mpeg, *.vob, *.vro, etc.) in ${dvdripto_parentdir}\\. Select one or more by typing in the name or names separated by spaces. If you select more than one, the files will be joined in the order you specify.");
	&echo("");
	&echo("${navy_on_gray}Note that joining different DVD/MPEG files is only recommended if they're of the same game.  The settings you choose later in the editing phase will be applied to the whole project which can cause problems since different games will possibly need different settings.");
	system($reset_color);
	&echo("");
	system($reset_color);
	
	$i = 0;
	#following masks are all lowercase
	@dvdfilemasks = ( '*.v*', '*.mpg', '*.mpeg' );
	#FIXME os x still usually uses a case-insensitive filesystem
	if ($os ne 'windows') {
		#now add the uppercase equivalents for case-sensitive filesystems
		foreach $mask (@dvdfilemasks) {
			push(@dvdfilemasks, uc($mask));
		}
	}
	#i took out printing the dir even if no mpeg files are found in there because there's no point in showing it if the user can't do anything with it, also clarified that above in the messages to the user (nate)
	%gooddvddirs = ();
	opendir(DVDRIPTO, $dvdripto_parentdir);
	@dvddirs = readdir(DVDRIPTO);
	closedir(DVDRIPTO);
	foreach $dvddir (@dvddirs) {
		if ((-d "${dvdripto_parentdir}/${dvddir}") and ($dvddir ne '.') and ($dvddir ne '..')) {
			opendir((DVDDIR), "${dvdripto_parentdir}/${dvddir}");
			@dvddircontents = readdir(DVDDIR);
			closedir(DVDDIR);
			for (@dvddircontents) {
				foreach $themask (@dvdfilemasks) {
					if (m/\.${themask}$/) {
						$gooddvddirs{$dvddir} = "${dvdripto_parentdir}/${dvddir}";
						last;
					}
				}
			}
		}
	}
	if (!keys(%gooddvddirs)) {
		&out_error("No folders with DVD files found!");
		<STDIN>;
		exit 1;
	} else {
		while (($key, $value) = each(%gooddvddirs)) {
			&echo("${key}\n");
		}
	}

	@dvdchoices = ();
	print $prompt;
	while (<STDIN>) {
		chomp;
		#have to initialize @errormsgs here because we may be pushing to it later
		@errormsgs = ();
		#if (!m/^([0-9]+[ ]+[0-9]+)+$/) { #regex for if more than one input is required on a line
		if (m/^$/) {
			push(@errormsgs,"Invalid input.");
		} else {
			for (split(" ")) {
				if (defined($gooddvddirs{$_})) {
					push(@dvdchoices,$gooddvddirs{$_});
				} else {
					push(@errormsgs,"Invalid selection: ${_}");
				}
			}
			last if @dvdchoices > 0;
		}
		&out_error(@errormsgs);
		print $prompt;
	}

	&echo("");
	
	&out_info("Now indexing MPEG-2 ...");
	#Start - AVS prep
	&rm("${projname}.avs") if -e "${projname}.avs";
	&echotofile("loadplugin(\"${dgmpgdec_dir}/DGDecode.dll\")",">","${projname}.avs");
	&echotofile("import(\"${anri_dir}/sda.avs\")",">>","${projname}.avs");
	&echotofile("import(\"${desktop}/${projname}/plugins.avs\")",">>","${projname}.avs");
	# End - AVS prep
	
	$i=0;
	$alignedsplice = '';
	foreach $dvdchoice (@dvdchoices) {
		foreach $mask (@dvdfilemasks) {
			foreach $mpegfile (glob("${dvdchoice}/$mask")) {
				$i++;
				&echotofile($alignedsplice,">>","${projname}.avs");
				#split into basename and extension
				/^(.+)\.([^.]+)$/;
				# Run current vob through dgindex. Set to demux all tracks. Place vid,aud,delay info into temporary avs file.
				#I01_001.vob
				#dvdtest_1_I01_001.d2v
				#dvdtest_1_I01_001.log
				system("\"${dgmpgdec_dir}/${dgindex}\" -IF=[${mpegfile}] -OF=[${projname}_${i}_${1}] -PREVIEW -exit");
				system("\"${dgmpgdec_dir}/${dgindex}\" -IF=[${mpegfile}] -OM=2 -OF=[${projname}_${i}_${1}] -AT=[infotemplate.avs] -exit");
				$mpegfile =~ s/^(.+)\.[^.]+$/$1/;
				$logname = $1;
				#cut off the path
				$logname =~ s/.*([^\/]+)$/$1/;
				&mv("${mpegfile}.log","${desktop}/${projname}/${projname}_${i}_${logname}.log");
				for (glob("${projname}_${i}_*")) {
					&echotofile("ac3source(MPEG2source(\"${1}.d2v\",upconv=1),\"${_}\").delayaudio(".($2/1000).")\n",">>","${projname}.avs") if (m/^([^ ]+) .+DELAY (-?[0-9]+)ms.*\.ac3$/);
					&echotofile("audiodub(MPEG2source(\"${1}.d2v\",upConv=1),mpasource(\"${_}\")).delayaudio(".($2/1000).")\n",">>","${projname}.avs") if (m/^([^ ]+) .+DELAY (-?[0-9]+)ms.*\.mp.*$/);
					&echotofile("audiodub(MPEG2source(\"${1}.d2v\",wavsource(\"${_}\"))\n",">>","${projname}.avs") if (m/^([^ ]+).*\.wav$/);
					if (defined($3)) {
						$maxaudiobr = ($3+1000) if $maxaudiobr lt ($3+1000);
					}
				}
				# If there's more than one file to be joined, they must be appended together.
				$alignedsplice = "++\n";
			}
		}
	}
	&echotofile("\n",">>","${projname}.avs");
	&cp("${projname}.avs","${projname}.bak");
}

#system("\"${anri_dir}/${mplayer}\" dvd://${1} -dvd-device ${dvdsource} -dumpstream -dumpfile ${dvdripto}/I${2}_${expandpgc}.vob");
############################################################################
#                               Encoding
#
# Encode video in OS-specific ways.
############################################################################

#input filename, output basename, output audio bitrate in baud, x264 minimum quantizer, delete tempfiles boolean
sub onepass {
	system("\"${anri_dir}/${x264}\" --qp ${_[3]} --ref 8 --mixed-refs --no-fast-pskip --bframes 5 --b-rdo --bime --weightb --nf --direct auto --subme 7 --analyse p8x8,b8x8,i4x4,p4x4 --threads auto --thread-input --progress --no-psnr --no-ssim --output \"${_[1]}_video.mp4\" \"${_[0]}\"");
	system("\"${vdub_dir}/${vdubcli}\" \"${_[0]}\" /i \"${anri_dir}/audioout.vcf\" \"${_[1]}_temp.wav\"");
	system("\"${anri_dir}/${naac}\" -br ${_[2]} -lc -if \"${_[1]}_temp.wav\" -of \"${_[1]}_audio.mp4\"");
	system("\"${anri_dir}/${mp4box}\" -tmp . -new -add \"${_[1]}_video.mp4\" -add \"${_[1]}_audio.mp4\" \"${_[1]}.mp4\"");
	if (${_[4]}) {
		@todel = (
			"${_[1]}_video.mp4",
			"${_[1]}_temp.wav",
			"${_[1]}_audio.mp4",
		);
		&rm(@todel);
	}
}

#input filename, output basename, video output bitrate in kbaud, output audio bitrate in baud, x264 minimum quantizer, delete 2pass statsfile boolean, delete all other tempfiles boolean
sub twopass {
	system("\"${anri_dir}/${x264}\" --pass 1 --bitrate ${_[2]} --stats \"${_[1]}.stats\" --level 4.1 --bframes 3 --analyse none --qpmin ${_[4]} --vbv-bufsize 9000 --vbv-maxrate 25000 --threads auto --thread-input --progress --no-psnr --no-ssim --output NUL \"${_[0]}\"");
	system("\"${anri_dir}/${x264}\" --pass 2 --bitrate ${_[2]} --stats \"${_[1]}.stats\" --level 4.1 --ref 3 --mixed-refs --no-fast-pskip --bframes 3 --b-rdo --bime --weightb --direct auto --subme 7 --trellis 2 --partitions p8x8,b8x8,i4x4,i8x8 --8x8dct --qpmin ${_[4]} --vbv-bufsize 9000 --vbv-maxrate 25000 --me umh --threads auto --thread-input --progress --no-psnr --output \"${_[1]}_video.mp4\" \"${_[0]}\"");
	system("\"${vdub_dir}/${vdubcli}\" ${_[0]} /i \"${anri_dir}/audioout.vcf\" \"${_[1]}_temp.wav\"");
	system("\"${anri_dir}/${naac}\" -br ${_[3]} -lc -if \"${_[1]}_temp.wav\" -of \"${_[1]}_audio.mp4\"");
	system("\"${anri_dir}/${mp4box}\" -tmp . -new -add \"${_[1]}_video.mp4\" -add \"${_[1]}_audio.mp4\" \"${_[1]}.mp4\"");
	if (${_[5]}) {
		@todel = (
			"${_[1]}.stats",
		);
		&rm(@todel);
	}
	if (${_[6]}) {
		@todel = (
			"${_[1]}_video.mp4",
			"${_[1]}_temp.wav",
			"${_[1]}_audio.mp4",
		);
		&rm(@todel);
	}
}

#input filename, output basename, video output bitrate in kbaud, output audio bitrate in baud, x264 minimum quantizer, delete 2pass statsfile boolean, delete all other tempfiles boolean
sub ipod {
	system("\"${anri_dir}/${x264}\" --pass 1 --bitrate ${_[2]} --vbv-bufsize 512 --vbv-maxrate 768 --stats \"${_[1]}.stats\" --level 1.3 --no-cabac --analyse none --qpmin ${_[4]} --threads auto --thread-input --progress --no-psnr --no-ssim --output NUL ${_[0]}");
	system("\"${anri_dir}/${x264}\" --pass 2 --bitrate ${_[2]} --vbv-bufsize 512 --vbv-maxrate 768 --stats \"${_[1]}.stats\" --level 1.3 --no-cabac --no-fast-pskip --subme 7 --trellis 2 --analyse all --qpmin ${_[4]} --me umh --threads auto --thread-input --progress --no-psnr --output \"${_[1]}_video.mp4\" \"${_[0]}\"");
	system("\"${vdub_dir}/${vdubcli}\" ${_[0]} /i \"${anri_dir}/audioout.vcf\" \"${_[1]}_temp.wav\"");
	system("\"${anri_dir}/${naac}\" -br ${_[3]} -lc -if \"${_[1]}_temp.wav\" -of \"${_[1]}_audio.mp4\"");
	system("\"${anri_dir}/${mp4box}\" -tmp . -new -add \"${_[1]}_video.mp4\" -add \"${_[1]}_audio.mp4\" \"${_[1]}.mp4\"");
	if (${_[5]}) {
		@todel = (
			"${_[1]}.stats",
		);
		&rm(@todel);
	}
	if (${_[6]}) {
		@todel = (
			"${_[1]}_video.mp4",
			"${_[1]}_temp.wav",
			"${_[1]}_audio.mp4",
		);
		&rm(@todel);
	}
}

#input filename, output basename, video output bitrate in kbaud, output audio bitrate in baud, empty, delete 2pass statsfile boolean, delete all other tempfiles boolean
sub xvid {
	system("\"${anri_dir}/${xvid}\" -i \"${_[0]}\" -bitrate ${_[2]} -pass1 \"${_[1]}.stats\"");
	system("\"${anri_dir}/${xvid}\" -i \"${_[0]}\" -bitrate ${_[2]} -pass2 \"${_[1]}.stats\" -avi \"${_[1]}v.avi\"");
	system("\"${anri_dir}/${ffmpeg}\" -b ".($_[3]/1000)." -ac 2 -acodec mp3 -y -i \"${_[1]}v.avi\" -vcodec copy -i \"${_[0]}\" \"${_[1]}.avi\"");
	if (${_[5]}) {
		@todel = (
			"${_[1]}.stats",
		);
		&rm(@todel);
	}
	if (${_[6]}) {
		@todel = (
			"${_[1]}v.avi",
		);
		&rm(@todel);
	}
}
Personal tools