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

From SDA Knowledge Base

Jump to: navigation, search
(this hasn't been debugged so for god's sake don't run it)
(audio commentary etc)
 
(54 intermediate revisions by 6 users not shown)
Line 9: Line 9:
 
# Philip "ballofsnow" Cornell
 
# Philip "ballofsnow" Cornell
 
# Brett "Psonar" Ables
 
# Brett "Psonar" Ables
 +
# Karol "dex" Urbanski
 
#
 
#
 
# Anri is distributed under the terms of the Gnu General Public License 3.0:
 
# Anri is distributed under the terms of the Gnu General Public License 3.0:
Line 24: Line 25:
 
use strict 'subs';
 
use strict 'subs';
 
package anri;
 
package anri;
 +
use Getopt::Long qw(:config bundling);
 +
use File::Find;
 +
use File::Basename;
 +
use File::Spec;
 +
use threads;
 +
use threads::shared;
  
 
#version of this software, used in building the path to the executable, so must match the value from the installer
 
#version of this software, used in building the path to the executable, so must match the value from the installer
Line 38: Line 45:
 
$os = 'windows' if "$^O" eq "MSWin32";
 
$os = 'windows' if "$^O" eq "MSWin32";
  
#no auto mode yet
+
#default
$auto=0;
+
$language = "english";
  
 
#nmf off by default, so filename identifier is null
 
#nmf off by default, so filename identifier is null
Line 46: Line 53:
 
if ($os eq 'windows') {
 
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 ...
 
#the below api calls probably require the win32api module(?) to be installed which will have to be included in the anri installer ...
 +
require Win32;
 
 
 
#get the name of the work directory. this is the desktop by default under windows
 
#get the name of the work directory. this is the desktop by default under windows
use Win32 qw(CSIDL_DESKTOPDIRECTORY);
+
$desktop = Win32::GetFolderPath(Win32::CSIDL_DESKTOPDIRECTORY());
$desktop = Win32::GetFolderPath(CSIDL_DESKTOPDIRECTORY);
+
 
 
 
#get the path to program files so we can build the anri program directory
 
#get the path to program files so we can build the anri program directory
use Win32 qw(CSIDL_PROGRAM_FILES);
+
$programfiles = Win32::GetFolderPath(Win32::CSIDL_PROGRAM_FILES());
$programfiles = Win32::GetFolderPath(CSIDL_PROGRAM_FILES);
+
 
 
 
#anri program directory
 
#anri program directory
Line 60: Line 66:
 
#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 75: Line 81:
 
 
 
#some anri support files
 
#some anri support files
$directshowsourcelistfile = 'directshowsource_list.txt';
+
$mplayer = "mplayer.exe";
 +
$wget = "wget.exe";
 +
 
 +
#dunno about this
 +
$dvdripto_parentdir = "C:\\AnriMPEG";
 +
 +
#goes after a drive letter
 +
$colon = ':';
 +
 +
#black hole
 +
$nul = 'NUL';
 +
 +
#to start programs/open urls
 +
$start = "START";
  
 
#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 112: Line 131:
 
$black_on_gray = '{black on gray}';
 
$black_on_gray = '{black on gray}';
 
$gray_on_black = '{gray on black}';
 
$gray_on_black = '{gray on black}';
$blue_on_black = '{blue on black}';
 
 
$white_on_black = '{white on black}';
 
$white_on_black = '{white on black}';
 
$aqua_on_black = '{aqua on black}';
 
$aqua_on_black = '{aqua on black}';
Line 125: Line 143:
 
$reset_color = "\"${cecho}\" ${black_on_gray}";
 
$reset_color = "\"${cecho}\" ${black_on_gray}";
 
system("Color 80");
 
system("Color 80");
} else {
+
} else { #we're on unix
#FIXME UNIX DESKTOP
+
      $desktop = glob("~/Desktop");
 +
#os-dependent path to verdana stuff
 +
if ("$^O" eq "darwin") {
 +
$path_to_verdana = "/Library/Fonts/Verdana.ttf";
 +
} else {
 +
### FIXME NON-MAC UNIX PATH TO VERDANA
 +
}
 
 
 +
#anri program directory
 +
      $anri_dir = File::Spec->rel2abs(dirname($0));
 +
 +
#our encoders - invocation names only - path will be prepended later ...
 +
$x264 = 'bin/x264';
 +
$afconvert = 'bin/afconvert';
 +
#for mp4box
 +
# print "export DYLD_LIBRARY_PATH=${anri_dir}\n";
 +
$mp4box = 'bin/mp4box';
 +
$ffmpeg = 'bin/ffmpeg';
 +
 +
#some anri support files
 +
$avidemux = $anri_dir.'/avidemux2_qt4.app/Contents/Resources/script'; #gui - for debugging
 +
$avidemux = $anri_dir.'/avidemux2_qt4.app/Contents/Resources/avi_cli';
 +
$mplayer = "bin/mplayer";
 +
$mencoder = "bin/mencoder";
 +
$really_quiet = "-really-quiet"; #for mencoder
 +
$wget = "bin/wget";
 +
 +
#dunno about this
 +
$dvdripto_parentdir = "${anri_dir}/dvdripto"; ### FIXME
 +
 +
#not needed under unix
 +
$colon = '';
 +
 +
#black hole
 +
$nul = '/dev/null';
 +
 +
#to start programs/open urls
 +
$start = "open";
 +
 
#color initialization
 
#color initialization
 +
require Term::ANSIColor;
 +
import Term::ANSIColor qw(color);
 +
$cecho = "echo";
 +
 +
#fewer colors to choose from than under windows if we want to maintain portability ...
 +
$black_on_gray = color("black on_white");
 +
$gray_on_black = color("white on_black");
 +
$white_on_black = color("white on_black");
 +
$aqua_on_black = color("green on_black");
 +
$blue_on_black = color("blue on_black");
 +
$teal_on_gray = color("green on_white");
 +
$navy_on_gray = color("blue on_white");
 +
$maroon_on_gray = color("magenta on_white");
 +
$maroon_on_silver = color("magenta on_white");
 +
$white_on_gray = color("white on_black");
 +
$red_on_gray = color("red on_white");
 +
 +
$reset_color = "\"${cecho}\" ".color("reset");
 
 
 
#os-specific commands
 
#os-specific commands
Line 134: Line 207:
 
}
 
}
  
#FIXME LOGFILE STUFF
+
#make sure we can find anri's libs
 +
push @INC, $anri_dir;
  
#FIXME EXTERNAL CONFIGURATION FILE
+
#progress bar helper stuff
 +
$mplayer_loop_thread=0;
 +
$end_bar=0;
 +
 
 +
#load only if command line arguments are specified
 +
&load_cli if @ARGV;
 +
 
 +
########################################################################################
 +
# CLI and config handling
 +
#
 +
# This subroutine deals with the config/cli loading. Only fired up when command line args
 +
# are specified, since you have to load the config that way.
 +
#
 +
# Not very well tested, so expect changes here.
 +
#
 +
# Things still to do: some error checking, it's not going to be hard to make but I want
 +
# to do that only after extensive testing.
 +
# The qualities arg is glitchy when not lowercase, and lc() craps out. Probably gonna use
 +
# td to deal with that later.
 +
# Some cleanup is in order too.
 +
#
 +
########################################################################################
 +
 
 +
sub load_cli {
 +
#initialising some variables to avoid errors/enforce better behaviour
 +
$nes=0;
 +
$gb=0;
 +
$gba=0;
 +
$prog=0;
 +
$fieldorder=1; #this defaults to the top screen in the user test in manual mode
 +
$vhs=0;
 +
$onepixel=0;
 +
$deflicker=0;
 +
$make_nmf=0;
 +
$statid=0;
 +
$gb_crop='';
 +
$gba_crop='';
 +
$spec='';
 +
$rip_a_dvd='';
 +
$help=0;
 +
#load all args, some as string, some as int, some as boolean
 +
#all variables are temporary in order to enforce cli precedence over config
 +
GetOptions ('config|c=s' => \$config_file ,
 +
'statid1|1=s' => \$statidline1,
 +
'statid2|2=s' => \$statidline2,
 +
'statid3|3=s' => \$statidline3,
 +
'statid_lines|s=s' => \$statid_lines,
 +
'spec|S=s' => \$spec,
 +
'trim|t=s' => \$trim_arg ,
 +
'rip|r=s' => \$rip_a_dvd,
 +
'gb_crop|p=s' => \$gb_crop,
 +
'gba_crop|P=s' => \$gba_crop,
 +
'language|l=s' => \$lang,
 +
'qualities|q=s' => \$qual,
 +
'projectname|n=s' => \$project_name,
 +
'avidir|d=s' => \$avidirectory,
 +
'avifile|f=s' => \@avi_files,
 +
'dvdsource|D=s' => \$dvd_source,
 +
'sample_extraction|x=i' => \$start_frame,
 +
'database' => \$data_dfnd,
 +
'gb|g' => \$gb_source,
 +
'gba|G' => \$gba_source,
 +
'nes|N' => \$nes_source,
 +
'vhs|v' => \$vhs_source,
 +
'deflickered|F' => \$dflckrd,
 +
'progressive|R' => \$progressive_source,
 +
'field_order|L' => \$order_of_fields,
 +
'pixelbob|b' => \$pixel_bobbing,
 +
'nmf|m' => \$create_nmf,
 +
'no_statid|o' => \$nostatid,
 +
'no_trim|i'  => \$notrim,
 +
'maxaudbitrate|a=i' => \$maximal_bitrate,
 +
'pcgame|C' => \$is_pc,
 +
'quietmen|Q' => \$mencoder_quiet,
 +
'help|h' => \$help
 +
);
 +
#language
 +
$language=$lang if $lang;
 +
#if asked for help, print and exit
 +
if($help){
 +
#has to be added to load the help...
 +
require 'lang_english.pl';
 +
require "lang_${language}.pl" if $language ne "english";
 +
#clear print used because the other functions don't recognise \n, something to FIXME
 +
&out_cls;
 +
print $lang{COMMAND_LINE_HELP};
 +
exit 0;
 +
}
 +
#load config if one specified
 +
&load_config($config_file) if $config_file;
 +
#qualities
 +
#can be provided in binary or decimal or as a string:
 +
#string: mq,lq,mqavi etc.
 +
#binary: 0b[7 digit binary number]. First digit corresponds to xq, second to iq, third to hq, fourth to mq,
 +
#        fifth to lq, sixth to mqavi and seventh to lqavi. For instance, 0b1001000 will encode XQ and MQ.
 +
#decimal: [number from 1 to 127]. Add the values of these to get the qualities to encode: xq - 64, iq - 32,
 +
#        hq - 16, mq - 8, lq - 4, mqavi - 2, lqavi - 1. For example, 72 will encode XQ and MQ.
 +
if($qual=~m/0b([10]{7})/){
 +
$qual=unpack("N", pack("B32", substr("0" x 32 . $1, -32)));
 +
}
 +
if($qual=~m/\d+/){
 +
@temp_qual_to_enc = qw(xq iq hq mq lq mqavi lqavi);
 +
$temp_for_qual = 64;
 +
while($qual){
 +
$temp_quality = shift(@temp_qual_to_enc);
 +
if($qual-$temp_for_qual>=0){
 +
push(@encodethese, $temp_quality);
 +
$qual-=$temp_for_qual;
 +
}
 +
$temp_for_qual>>=1;
 +
}
 +
 +
} elsif($qual) {
 +
@encodethese=split (',',$qual);
 +
}
 +
#trim
 +
@trimarr=split(',', $trim_arg) if $trim_arg;
 +
$trim=1 if @trimarr;
 +
$trim=0 if $notrim;
 +
#avis
 +
push(@avifiles,@avi_files);
 +
#statid
 +
@statidlines=split(',',$statid_lines) if $statid_lines;
 +
$statidlines[0] = $statidline1 if $statidline1;
 +
$statidlines[1] = $statidline2 if $statidline2;
 +
$statidlines[2] = $statidline3 if $statidline3;
 +
$statid=1 if @statidlines;
 +
$statid=0 if $nostatid;
 +
#project name
 +
$projname=$project_name if $project_name;
 +
#sample extraction
 +
$startframe=$start_frame if $start_frame;
 +
$isPCGAME=$is_pc if $is_pc;
 +
#avidir
 +
$avidir=$avidirectory if $avidirectory;
 +
#dvd dirs
 +
@dvdchoices=split (',',$dvd_source) if $dvd_source;
 +
$dvdsource=1 if $dvd_source;
 +
#source stuff
 +
$nes=$nes_source if $nes_source;
 +
$deflicker=$dflckrd if $dflckrd;
 +
$prog=$progressive_source if $progressive_source;
 +
$make_nmf=$create_nmf if $create_nmf;
 +
$onepixel=$pixel_bobbing if $pixel_bobbing;
 +
$vhs=$vhs_source if $vhs_source;
 +
$fieldorder=0 if $order_of_fields;
 +
$maxaudiobitrate=$maximal_bitrate if $maximal_bitrate;
 +
#quiet mode
 +
$really_quiet = "-really-quiet" if $mencoder_quiet;
 +
#gb and gba stuff
 +
if($gba_crop=~m/(.+),(.+),(.+),(.+)/){
 +
$gba_crop_left = $1;
 +
$gba_crop_top = $2;
 +
$gba_crop_right = $3;
 +
$gba_crop_bottom = $4;
 +
}
 +
if($gb_crop=~m/(.+),(.+),(.+),(.+)/){
 +
$gb_crop_left = $1;
 +
$gb_crop_top = $2;
 +
$gb_crop_right = $3;
 +
$gb_crop_bottom = $4;
 +
}
 +
$gba=1 if $gba_source || $gba_crop_left;
 +
$gb=1 if $gb_source || $gb_crop_left;
 +
#d, f, dimensions
 +
if($spec=~m/d(.)f(.)(.)d/i){
 +
$d=$1;
 +
$f=$2;
 +
if($3==2){
 +
$twod=1;
 +
} else {
 +
$twod=0;
 +
}
 +
}
 +
if($d && $f){
 +
$dfnd_set=1;
 +
$dfnd=0;
 +
}
 +
$dfnd=$data_dfnd;
 +
#rippin'
 +
if($rip_a_dvd=~m/(.+):(.+)/){
 +
$driveletter=$1;
 +
$dvdripto=$2;
 +
$rip=1;
 +
}
 +
$dvdsource=0 if $avidir || @avifiles;
 +
#auto mode if possible
 +
if( ((@avifiles || $avidir || $dvdsource ) && ($isPCGAME || $dvdsource)) || $rip ) {
 +
$auto = 1;
 +
}
 +
#choosing menu choices automagically
 +
@menuchoices=(2) if @avifiles;
 +
@menuchoices=(2) if $dvdsource;
 +
@menuchoices=(2) if $avidir;
 +
@menuchoices=(3) if $startframe;
 +
@menuchoices=(1) if $rip;
 +
}
 +
###############################################################
 +
#                Config loading
 +
#
 +
# This just loads the config. No rocket science here.
 +
#
 +
###############################################################
 +
sub load_config {
 +
open(CONFIG,$_[0]) if -e $_[0];
 +
while(<CONFIG>){
 +
if (m/^\#/) { next; } #this is a comment line
 +
if (m/^statid(\d)=(.+)/i) { $statidlines[$1-1] = ($2); next; } #statid
 +
if (m/^statid_lines=(.+)/i) { @statidlines=split(',',$1); next; } #statid
 +
if (m/^no_statid=1/i) { $statid=0; next; } #force no statid mode
 +
if (m/^spec=d(.)f(.)(.)d/i) { $d=$1; $f=$2; $3==2 ? $twod=1 : $twod=0; next; } #d,f, dim
 +
if (m/^rip=(.+):(.+)/i) { $driveletter=$1; $dvdripto=$2; $rip=1; next; } #ripping mode
 +
if (m/^quietmen=1/i) { $really_quiet = "-really-quiet"; next; } #quiet mencoder
 +
if (m/^pcgame=1/i) { $isPCGAME = 1; next; } #PC game
 +
if (m/^trim=(.+)/i) { @trimarr=split (',',$1); next; } #trimming
 +
if (m/^no_trim=1/i) { $notrim=1; next; } #force no trimming mode
 +
if (m/^nmf=1/i) { $make_nmf=1; next; } #create nmf
 +
if (m/^progressive=1/i) { $prog=1; next; } #progressive source
 +
if (m/^pixelbob=1/i) { $onepixel=1; next; } #one pixel bob
 +
if (m/^field_order=(\d)/i) { $fieldorder=$1; next; } #field order
 +
if (m/^gba=1/i) { $gba=1; next; } #gba source
 +
if (m/^gb=1/i) { $gb=1; next; } #gb source
 +
if (m/^vhs=1/i) { $vhs=1; next; } #vhs source
 +
if (m/^nes=1/i) { $nes=1; next; } #nes source
 +
if (m/^database=1/i) { $dfnd=1; next; } #use database <useless really>
 +
if (m/^deflickered=1/i) { $deflicker=1; next; } #deflickered source
 +
if (m/^projectname=(.+)/i) { $projname=$1; next; } #name of the project
 +
if (m/^language=(.+)/i) { $language=$1; next; } #language
 +
if (m/^sample_extraction=(\d)/i) { $startframe=$1; next; } #sample extract mode
 +
if (m/gba_crop=(.+),(.+),(.+),(.+)/i){ $gba_crop_left = $1; $gba_crop_top = $2; $gba_crop_right = $3; $gba_crop_bottom = $4; next; } #gba cropping
 +
if (m/gb_crop=(.+),(.+),(.+),(.+)/i){ $gb_crop_left = $1; $gb_crop_top = $2; $gb_crop_right = $3; $gb_crop_bottom = $4; next; } #gb cropping
 +
if (m/dvdsource=(.+)/i) { @dvdchoices=split(',',$1); $dvdsource=1; next; } #dvd source
 +
if (m/avidir=(.+)/i) { $avidir=$1; next; } #avi directory
 +
if (m/avifile=(.+)/i) { push(@avifiles,$1); next; } #avisource(s)
 +
if (m/qualities=(.+)/i) { @encodethese=split (',',$1); } #qualities to encode
 +
}
 +
close CONFIG;
 +
#require $_[0] if -e $_[0];
 +
}
 +
 
 +
 
 +
#load config file
 +
#require 'config.ini' if -e 'config.ini';
 +
 
 +
#localization
 +
require 'lang_english.pl';
 +
#after having loaded english, load preferred language by using $language variable from config file, would be cool if we could set this in the installer
 +
require "lang_${language}.pl" if $language ne "english";
 +
 
 +
#FIXME LOGFILE STUFF
  
 
#main menu
 
#main menu
  
#TODO: using_settings
+
#FIXME: using_settings
  
 
############################################################################
 
############################################################################
Line 149: Line 472:
  
 
&out_cls;
 
&out_cls;
&out_info("ON HERMESUS LUC ARSUS ESTARIAS AUC ELTRAS LI CELES! Now, let's get to work!");
 
&out_section("Main");
 
 
@mainmenu = (
 
@mainmenu = (
['Rip DVD to hard drive (required for DVD material)', '&rip_dvd'],
+
[$lang{MAINMENU_RIPDVD}, '&rip_dvd'],
['Start new project', '&project'],
+
[$lang{MAINMENU_STARTNEWPROJECT}, '&project'],
['Extract sample', '&proc_sample'],
+
[$lang{MAINMENU_EXTRACTSAMPLE}, '&proc_sample'],
['Station ID preview', '&statid_sample'],
+
[$lang{MAINMENU_STATIDPREVIEW}, '&statid_sample'],
['Exit', 'exit 0;'],
+
[$lang{MAINMENU_AUDIOCOMMENTARY}, '&audio_commentary'],
 +
[$lang{MAINMENU_EXIT}, 'exit 0'],
 
);
 
);
&out_menu(@mainmenu);
+
$number_of_menu_choices = scalar @mainmenu;
while (<STDIN>) {
+
while (1) {
chomp;
+
if (@menuchoices) {
if (m/([1-5])$/) {
+
eval($mainmenu[shift(@menuchoices)-1][1]);
#execute the contents of this value in the array
+
} else {
eval($mainmenu[$1-1][1]);
+
&out_cls;
last;
+
&out_info($lang{PROGRAM_START});
 +
&out_section($lang{MAINMENU});
 +
&out_menu(@mainmenu);
 +
while (<STDIN>) {
 +
chomp;
 +
if (m/([1-${number_of_menu_choices}])$/) {
 +
#execute the contents of this value in the array
 +
eval($mainmenu[$1-1][1]);
 +
last;
 +
}
 +
print "$lang{INVALID_INPUT}\n\n";
 +
&out_menu(@mainmenu);
 +
}
 +
}
 +
if($auto){
 +
exit 0;
 
}
 
}
print "Invalid input.\n\n";
 
&out_menu(@mainmenu);
 
 
}
 
}
  
Line 188: Line 523:
 
$projname = 'anri_sample';
 
$projname = 'anri_sample';
 
&make_projdir;
 
&make_projdir;
&load_plugins;
+
&load_plugins if $os eq 'windows';
&out_cls_section("Sample Extraction");
+
&out_cls_section($lang{SECTION_SAMPLE_EXTRACTION});
&q_boo($dvdsource,'DVD/MPEG source [y,n]');
+
q_boo($lang{QUESTION_DVDMPEG_SOURCE}, $dvdsource);
 
$dvdsource ? &index_dvd : &q_avi;
 
$dvdsource ? &index_dvd : &q_avi;
 
&cp("${projname}.avs","${projname}_trimtemp.avs");
 
&cp("${projname}.avs","${projname}_trimtemp.avs");
 
&echotofile("lanczos4resize(320,240)\n",">>","${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");
+
if (! defined $startframe) {
&out_info("action.");
+
&out_info($lang{INFO_SAMPLE_LENGTH});
&echo("");
+
&echo("");
&out_info("Press ENTER to continue ...");
+
&out_info($lang{PRESS_ENTER_TO_CONTINUE});
<STDIN>;
+
<STDIN>;
if ($os eq 'windows') {
+
if ($os eq 'windows') {
system("START \"trimming vdub\" \"${vdub_dir}/${vdubgui}\" \"${projname}_trimtemp.avs\"");
+
system("${start} \"trimming vdub\" \"${vdub_dir}/${vdubgui}\" \"${projname}_trimtemp.avs\"");
} else {
+
} else {
#how are we going to do this in unix? your guess is as good as mine
+
@sources = &pipe_prepare($projname, "sources");
}
+
$avidemuxarg = " --load";
print $prompt;
+
for (@sources) {
while (<STDIN>) {
+
$avidemuxargs .= "${avidemuxarg} \"${desktop}/anri_sample/${_}\"";
chomp;
+
$avidemuxarg = " --append";
if (m/^[0-9]+$/) {
+
}
$startframe = $_;
+
#system("sh \"${avidemux}\" --autoindex ${avidemuxargs} &");
last;
+
 
}
 
}
print "Invalid input.\n\n";
 
 
print $prompt;
 
print $prompt;
 +
while (<STDIN>) {
 +
chomp;
 +
if (m/^[0-9]+$/) {
 +
$startframe = $_;
 +
last;
 +
}
 +
print "$lang{INVALID_INPUT}\n\n";
 +
print $prompt;
 +
}
 +
}
 +
if ($os ne 'windows') {
 +
### remove .idx files
 
}
 
}
 
&echotofile("trim(${startframe},".($startframe+299).")\n",">>","${projname}.avs");
 
&echotofile("trim(${startframe},".($startframe+299).")\n",">>","${projname}.avs");
&echotofile("AssumeTFF\nSeparateFields\nconverttoyv12\n",">>","${projname}.avs");
+
&echotofile("AssumeTFF()\nSeparateFields()\nconverttoyv12\n",">>","${projname}.avs");
&onepass("${desktop}/${projname}/${projname}.avs","${desktop}/${projname}/${projname}","128000","19",1);
+
&onepass("${desktop}/${projname}/${projname}","${desktop}/${projname}/${projname}","128000","19",1);
 
&cp("${desktop}/${projname}/${projname}.mp4","${desktop}");
 
&cp("${desktop}/${projname}/${projname}.mp4","${desktop}");
 
# @todel = (
 
# @todel = (
Line 225: Line 570:
 
# "log*.txt",
 
# "log*.txt",
 
# );
 
# );
chdir("${desktop}");
+
chdir($desktop);
&rm("${desktop}/${projname}");
+
#&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\n${white_on_gray}$lang{SAMPLE_EXTRACTION_DONE}");
&echo("\n${red_on_gray} - READ -${white_on_gray} You will see that the video has been resized vertically.");
+
&echo("\n$lang{SAMPLE_EXTRACTION_README}");
&echo("${red_on_gray}THIS IS NORMAL${white_on_gray} and will make it easier for the techies to help you.");
+
 
system($reset_color);
 
system($reset_color);
 
<STDIN>;
 
<STDIN>;
 
exit 0;
 
exit 0;
 +
}
 +
 +
 +
 +
sub audio_commentary {
 +
&out_cls_section($lang{SECTION_AUDIO_COMMENTARY});
 +
&echo("");
 +
 +
&out_info($lang{COMMENTARY_AUDIO_PATH_TO});
 +
&echo("");
 +
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=$lang{COMMENTARY_BAD_INPUT};
 +
} elsif (!m/.*\.wav$/i) {
 +
$errormsg=$lang{COMMENTARY_NOT_WAV};
 +
} elsif (! -e $_) {
 +
$errormsg=$lang{FILE_NOT_FOUND};
 +
} else {
 +
$audio_commentary_path = $_;
 +
&out_info($lang{COMMENTARY_AUDIO_LOADED_SUCCESSFULLY});
 +
&echo("");
 +
last;
 +
}
 +
&out_error($errormsg);
 +
print $prompt;
 +
}
 +
 +
&out_info($lang{COMMENTARY_VIDEO_PATH_TO});
 +
&echo("");
 +
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=$lang{COMMENTARY_BAD_INPUT};
 +
} elsif (!m/.*\.mp4$/i) {
 +
$errormsg=$lang{COMMENTARY_NOT_MP4};
 +
} elsif (! -e $_) {
 +
$errormsg=$lang{FILE_NOT_FOUND};
 +
} else {
 +
$video_commentary_path = $_;
 +
&out_info($lang{COMMENTARY_VIDEO_LOADED_SUCCESSFULLY});
 +
&echo("");
 +
last;
 +
}
 +
&out_error($errormsg);
 +
print $prompt;
 +
}
 +
 +
#BUILD PATH INFO
 +
@video_commentary_path_arr = split(/\\|\//,$video_commentary_path);
 +
$video_commentary_video = pop @video_commentary_path_arr;
 +
$video_commentary_video_base = $video_commentary_video;
 +
$video_commentary_video_base =~ s/\.mp4$//i;
 +
chdir(join('/',@video_commentary_path_arr)) or warn $!;
 +
 +
#ENCODE AUDIO TO 32 KBIT AAC MP4
 +
if ($os eq 'windows') {
 +
if(system("\"${anri_dir}/${naac}\" -br 32000 -lc -if \"${audio_commentary_path}\" -of \"${video_commentary_video_base}_track3.mp4\"")) {
 +
&out_error($lang{ERROR_COULD_NOT_READ_COMMENTARY_WAV});
 +
system($reset_color);
 +
<STDIN>;
 +
exit 0;
 +
}
 +
} else {
 +
###FIXME UNIX
 +
}
 +
 +
#MUX
 +
if ($os eq 'windows') {
 +
system("\"${anri_dir}/${mp4box}\" -single 1 \"${video_commentary_video}\"");
 +
system("\"${anri_dir}/${mp4box}\" -single 2 \"${video_commentary_video}\"");
 +
&mv("${video_commentary_video}","${video_commentary_video_base}.backup.mp4");
 +
system("\"${anri_dir}/${mp4box}\" -tmp . -new -add \"${video_commentary_video_base}_track1.mp4\" -add \"${video_commentary_video_base}_track2.mp4\" -add \"${video_commentary_video_base}_track3.mp4\" -disable 3 \"${video_commentary_video}\"");
 +
for my $track (1..3) {
 +
&rm("${video_commentary_video_base}_track${track}.mp4");
 +
}
 +
} else {
 +
#FIXME UNIX
 +
#system("export DYLD_LIBRARY_PATH=\"${anri_dir}\";\"${anri_dir}/${mp4box}\" ${mp4boxnewframerate} -tmp . -new -add \"${_[1]}_video.${x264outext}\" -add \"${_[1]}_audio.${audioext}\" \"${_[1]}.mp4\"");
 +
}
 +
 +
 +
 +
 +
&echo("\n\n${white_on_gray}$lang{AUDIO_COMMENTARY_DONE}");
 +
system($reset_color);
 +
<STDIN>;
 +
exit 0;
 +
}
 +
 +
 +
 +
 +
############################################################################
 +
#                        Statid Sample
 +
#
 +
# Statid preview mode shows users how their statid will look without having
 +
# to encode anything.  A slimmed down version of the code from the main
 +
# procedure and script_buildfiles is used.  The same temporary project
 +
# name and directory from sample extraction mode are used and deleted.
 +
# The user is sent back to the main menu but currently will need
 +
# to enter the statid information again during the main script.
 +
############################################################################
 +
 +
sub statid_sample {
 +
chdir($desktop);
 +
$projname = 'anri_sample';
 +
&make_projdir;
 +
&out_cls_section($lang{SECTION_STATID});
 +
&out_info($lang{STATID_ABOUT_EACH_LINE});
 +
if (!@statidlines) {
 +
foreach $i (1 .. 3) {
 +
&out_info($lang{STATID_LINE}." ${i}:");
 +
print $prompt;
 +
$statidline = <STDIN>;
 +
chomp($statidline);
 +
$statidline =~ s/"/"+chr(34)+"/g;
 +
push(@statidlines,$statidline);
 +
&echo("");
 +
}
 +
}
 +
&echotofile("global pal = false\n",">","${projname}.avs");
 +
&echotofile("import(\"${anri_dir}/sda.avs\")\n",">>","${projname}.avs");
 +
$projtemp  = "run = blankclip(width=640, height=480)";
 +
$projtemp .= "statid=nate_statid_d1(run,\"".$statidlines[0]."\",\"".$statidlines[1]."\",\"".$statidlines[2]."\",".($audio_commentary == 1 ? 1 : 0).").ConvertToRGB\n";
 +
$projtemp .= "statid = float(run.width) / run.height >= 4./3 ?\n";
 +
$projtemp .= "\\ statid.Lanczos4Resize(round(run.height*4./3),run.height).AddBorders(floor((run.width-round(run.height*4./3))/2.),0,ceil((run.width-round(run.height*4./3))/2.),0).ConvertToYv12 :\n";
 +
$projtemp .= "\\ statid.Lanczos4Resize(run.width,round(run.width*3./4)).AddBorders(0,floor((run.height-round(run.width*3./4))/2.),0,ceil((run.height-round(run.width*3./4))/2.)).ConvertToYv12\n";
 +
$projtemp .= "statid\n";
 +
&echotofile($projtemp,">>","${projname}.avs");
 +
system("\"${vdub_dir}/${vdubgui}\" \"${projname}.avs\"");
 +
chdir($desktop);
 +
&rm("${desktop}/${projname}");
 
}
 
}
  
Line 238: Line 719:
 
#                            Main procedure
 
#                            Main procedure
 
#  
 
#  
# Anri-chan's home housing the program flow. This is beginning to end for
+
# Anri's home housing the program flow. This is beginning to end for
 
# encoding the video.
 
# encoding the video.
 
#  
 
#  
Line 247: Line 728:
 
sub project {
 
sub project {
 
&out_cls;
 
&out_cls;
&out_info("ON HERMESUS LUC ARSUS ESTARIAS AUC ELTRAS LI CELES! Now, let's get to work!");
+
&out_info($lang{PROGRAM_START});
&out_section("PROJECT SETUP");
+
&out_section($lang{SECTION_PROJECT_SETUP});
#IF NOT "%auto%"=="y" (CALL :q_projname)
+
if (! defined $projname) {
+
&out_info($lang{ENTER_PROJECT_NAME});
&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("");
+
&echo("$lang{PROJECT_FILES_APPEAR_IN} ${navy_on_gray}${desktop}\\($lang{PROJECT_NAME})\n");
&echo("${white_on_gray}All files associated with this project will appear in ${navy_on_gray}%project_parentdir%\(project name)\n");
+
system($reset_color);
system($reset_color);
+
&echo("");
&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;
 
print $prompt;
 +
while (<STDIN>) {
 +
chomp;
 +
if (!m/[% ]/) {
 +
$projname = $_;
 +
last;
 +
}
 +
print "$lang{PROJECT_NAME_ILLEGAL_CHARACTERS}\n\n";
 +
print $prompt;
 +
}
 
}
 
}
 +
&make_projdir;
 +
&load_plugins if $os eq 'windows';
 
#FIXME settings manager
 
#FIXME settings manager
 
#CALL :find_existing_settings
 
#CALL :find_existing_settings
Line 285: Line 768:
 
#  
 
#  
 
# There are two methods for loading AVI files. Either the user enters the
 
# 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
+
# paths to the file individually, or specifies a directory and anri
 
# loads all AVI files alphabetically. There is currently no validation for
 
# loads all AVI files alphabetically. There is currently no validation for
 
# AVI files with different video properties.
 
# AVI files with different video properties.
 
############################################################################
 
############################################################################
 
 
&out_cls_section("MOVIE SOURCE");
+
&out_cls_section($lang{MOVIE_SOURCE});
&out_info("If you used a capture card with DVD or MPEG settings, place those files in");
+
&out_info($lang{MOVIE_SOURCE_MPEG2_HINT});
&out_info("${dvdripto_parentdir}\foldername\ and then answer y to the question below.");
+
 
&echo("");
 
&echo("");
 
#IF NOT "%auto%"=="y" CALL :q_dvdsource
 
#IF NOT "%auto%"=="y" CALL :q_dvdsource
if ($dvdsource) {
+
if (q_boo($lang{MPEG2_SOURCE_QUESTION}, $dvdsource)) {
 
#automation changes for q_driveletter are handled within the function b/c  
 
#automation changes for q_driveletter are handled within the function b/c  
 
#important code related to ripping and dgindex is found there.
 
#important code related to ripping and dgindex is found there.
Line 318: Line 800:
  
 
#:proc_gameproperties
 
#:proc_gameproperties
&out_cls_section("GAME PROPERTIES");
+
&out_cls_section($lang{SECTION_GAME_PROPERTIES});
 
if ((!$dvdsource) and (!$auto)) {
 
if ((!$dvdsource) and (!$auto)) {
&q_boo($isPCGAME,"Is this a PC game recorded with screen capture software (y), or simply a non-console run (n)? If you say no, your video will be treated as NTSC / PAL.");
+
q_boo($lang{PC_GAME_QUESTION}, $isPCGAME);
 
}
 
}
 
if ($isPCGAME) {
 
if ($isPCGAME) {
Line 328: Line 810:
 
$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;
}
+
} else {
 +
&q_dfnd if !$dfnd_set;
 +
if (!$dfnd_set) {
 +
&echo("");
 +
&out_info($lang{DF_EXPLAIN});
 +
&echo("");
 +
&out_info($lang{DF_FIND_AT_THIS_URL});
 +
&out_info($lang{DFND_URL});
 +
&echo("");
 +
&out_info($lang{DF_IF_NOT_FOUND_THEN_WHAT});
 +
&echo("");
 +
if (! defined $d) {
 +
&echo($lang{QUESTION_D});
 +
print $prompt;
 +
while (<STDIN>) {
 +
chomp;
 +
if (m/^[14]$/) {
 +
$d = $_;
 +
last;
 +
}
 +
print "$lang{INVALID_INPUT}\n\n";
 +
print $prompt;
 +
}
 +
}
 +
if (! defined $f) {
 +
&echo($lang{QUESTION_F});
 +
print $prompt;
 +
while (<STDIN>) {
 +
chomp;
 +
if (m/^[1-5]$/) {
 +
$f = $_;
 +
last;
 +
}
 +
print "$lang{INVALID_INPUT}\n\n";
 +
print $prompt;
 +
}
 +
}
 +
q_boo($lang{QUESTION_ND}, $twod) if ($f == 1);
 +
if (!$auto) {
 +
#:q_submit_dfnd
 +
&echo("");
 +
&out_info($lang{QUESTION_SUBMIT_DFND_WHY});
 +
&echo("");
 +
system($start, 'http://speeddemosarchive.com/forum/index.php?action=post;topic=6416.0') if q_boo($lang{QUESTION_SUBMIT_DFND});
 +
#:dfnd_is_set
 +
}
 +
}
 +
$hqq = 17 if $d == 4;
 +
$hqq = 19 if $d == 1;
  
+
############################################################################
&q_dfnd if !$auto;;
+
# Main procedure - Video properties
}
+
#
if (!$dfnd_set) {
+
# Wouldn't it be great if there was no more interlacing and everything was
#GOTO dfnd_is_set
+
# progressive? As you can see, if the video is progressive you pretty much
}
+
# skip the entire section. Anyways..
&q_d if !$auto;
+
#
&q_f if !$auto;
+
# The method for getting the field order is to open up an instance of vdub
if ($f eq 1) {
+
# with the video, the top half of the screen using Top Field First, and the
$twod=0;
+
# bottom half using Bottom Field First. The user then plays it to see which
&q_2d if !$auto;
+
# one looks natural and chooses top or bottom accordingly.
}
+
#
&q_submit_dfnd if !$auto;
+
# onepixel simply shifts one of the fields up or down by one pixel.
#:dfnd_is_set
+
#
$hqq = 17 if $d == 4;
+
# TO DO: Describe nes, gba, deflicker.
$hqq = 19 if $d == 1;
+
############################################################################
  
 
+
&out_cls_section($lang{SECTION_VIDEO_PROPERTIES});
############################################################################
+
q_boo($lang{QUESTION_PROGRESSIVE_INTERLACED}, $prog);
# Main procedure - Video properties
+
#IF "%prog%"=="y" GOTO proc_gameproperties_p2
#
+
if($prog != 1){
# 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
+
# function: q_fieldorder
#  
+
#  
# There's no foolproof method to detect field order programmatically. The
+
# 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
+
# next best thing is to show the user both, and let them decide which looks
# better.
+
# better.
#  
+
#  
# The script is simple enough, have a split screen with AssumeTFF and
+
# The script is simple enough, have a split screen with AssumeTFF and
# AssumeBFF. Whichever is chosen will be used in all AviSynth scripts.
+
# AssumeBFF. Whichever is chosen will be used in all AviSynth scripts.
############################################################################
+
############################################################################
  
&echo("");
+
&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.");
+
if (! defined $fieldorder) {
&out_info("Press ENTER to continue ...");
+
&out_info($lang{FIELDORDER_VDUB_WINDOW_OPENS});
<STDIN>;
+
&out_info($lang{PRESS_ENTER_TO_CONTINUE});
&echo("");
+
<STDIN>;
&cp("${projname}.bak","${projname}_fieldordertemp.avs");
+
&echo("");
&echotofile("tff=last.AssumeTFF().SeparateFields().bilinearresize(320,240).subtitle(\"t\")\n",">>","${projname}_fieldordertemp.avs");
+
&cp("${projname}.bak","${projname}_fieldordertemp.avs");
&echotofile("bff=last.AssumeBFF().SeparateFields().bilinearresize(320,240).subtitle(\"b\")\n",">>","${projname}_fieldordertemp.avs");
+
&echotofile("tff=last.AssumeTFF().SeparateFields().bilinearresize(320,240).subtitle(\"t\")\n",">>","${projname}_fieldordertemp.avs");
&echotofile("StackVertical(tff,bff)\n",">>","${projname}_fieldordertemp.avs");
+
&echotofile("bff=last.AssumeBFF().SeparateFields().bilinearresize(320,240).subtitle(\"b\")\n",">>","${projname}_fieldordertemp.avs");
system("START \"determine field order\" \"${vdub_dir}/${vdubgui}\" \"${projname}_fieldordertemp.avs\"");
+
&echotofile("StackVertical(tff,bff)\n",">>","${projname}_fieldordertemp.avs");
#:q_fieldorder_p2
+
system("${start} \"determine field order\" \"${vdub_dir}/${vdubgui}\" \"${projname}_fieldordertemp.avs\"");
print $prompt;
+
#:q_fieldorder_p2
while (<STDIN>) {
+
print $prompt;
chomp;
+
while (<STDIN>) {
if (m/^[tb]$/) {
+
chomp;
#t becomes 1 (true), b becomes 0 (false)
+
if (m/^[tb]$/) {
tr/tb/10/;
+
#t becomes 1 (true), b becomes 0 (false)
$fieldorder = $_;
+
tr/tb/10/;
last;
+
$fieldorder = $_;
}
+
last;
print "Invalid input.\n\n";
+
}
print $prompt;
+
print "$lang{INVALID_INPUT}\n\n";
}
+
print $prompt;
&out_info("You may now close the VirtualDub window.");
+
}
&rm("${projname}_fieldordertemp.avs");
+
&out_info($lang{VDUB_WINDOW_CAN_CLOSE_NOW});
&echo("");
+
&rm("${projname}_fieldordertemp.avs");
 +
}
 +
&echo("");
  
#q_vhs
+
#q_vhs
&q_boo($vhs,"Did you use VHS to help capture this run? [y/n]");
+
q_boo($lang{QUESTION_VHS}, $vhs);
  
#IF "%d%"=="1" GOTO proc_gameproperties_p2
+
#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($lang{QUESTION_1PIXEL_BOB}, $onepixel) if ($f != 2);
  
&q_boo($nes,"NES [y/n]") if !$auto;
+
q_boo($lang{QUESTION_NES}, $nes);
#IF "%nes%"=="y" GOTO proc_gameproperties_p2
+
#IF "%nes%"=="y" GOTO proc_gameproperties_p2
  
&q_boo($gba,"Game Boy Advance [y/n]") if !$auto;
+
q_boo($lang{QUESTION_GBA}, $gba);
$deflicker=1 if $gba;
+
$deflicker=1 if $gba;
#GOTO proc_gameproperties_p2
+
#GOTO proc_gameproperties_p2
  
&q_boo($gb,"Game Boy [y/n]") if !$auto;
+
q_boo($lang{QUESTION_GB}, $gb);
$deflicker=1 if $gb;
+
$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);
+
  
 +
q_boo($lang{QUESTION_DEFLICKERED}, $deflicker) if ($f != 2);
 +
}
 +
} #end if($prog != 1)
 
############################################################################
 
############################################################################
 
# Main procedure - Content properties
 
# Main procedure - Content properties
Line 435: Line 948:
 
# For trimming, we startup another vdub instance and ask the user to input
 
# 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
 
# frame numbers. The frame numbers will go into a single variable separated
# by spaces. There is currently no validation for entering a frame range
+
# by spaces. If the frame range is like 50 to 30 an error is shown, same if a '-'
# like 50 to 30... or negative numbers. Users can enter dummy values and edit
+
# is inputted.
# project_job.bat later on and it will still work.
+
# 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
 
# StatID... not much to it. Three lines, quotations are allowed. Gets appended
Line 444: Line 958:
  
 
#:proc_gameproperties_p2
 
#:proc_gameproperties_p2
&out_cls_section("CONTENT PROPERTIES");
+
&out_cls_section($lang{SECTION_CONTENT_PROPERTIES});
if (!$auto) {
+
if (! defined $trim) {
&out_info("Trimming lets you remove the start and end of the existing movie so you only keep the run itself.");
+
&out_info($lang{INFO_TRIM});
&q_boo($trim,"Do you want to trim off unwanted content in this video? [y,n]");
+
if (q_boo($lang{QUESTION_TRIM}, $trim)) {
 
+
############################################################################
############################################################################
+
# function: q_trimming
# function: q_trimming
+
#  
#  
+
# Create an array of numbers separated by spaces which will be used later on
# Create an array of numbers separated by spaces which will be used later on
+
# when writing to the AviSynth scripts.
# when writing to the AviSynth scripts.
+
#  
#  
+
# There isn't much validation yet. A modulus of 2 is used to make sure there's
# There isn't much validation yet. A modulus of 2 is used to make sure there's
+
# an even number of values. Implemented basic checking if the frame range is valid.
# 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("");
 
&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.");
+
&out_info($lang{TRIM_VDUB_WINDOW_OPENS});
 
&echo("");
 
&echo("");
&out_info("You can specify multiple ranges of frames. - Type n to quit -");
+
&out_info($lang{TRIM_MULTIPLE_RANGES});
&out_info("Press ENTER to continue ...");
+
&out_info($lang{PRESS_ENTER_TO_CONTINUE});
 
<STDIN>;
 
<STDIN>;
 
&echo("");
 
&echo("");
 
&cp("${projname}.bak","${projname}_trimtemp.avs");
 
&cp("${projname}.bak","${projname}_trimtemp.avs");
 
if ($isPCGAME) {
 
if ($isPCGAME) {
&echotofile("Lanczos4Resize(320,round(last.height*(320.000/last.width)))",">>","${projname}_trimtemp.avs");
+
&echotofile("Lanczos4Resize(320,round(last.height*(320.000/last.width)))\n",">>","${projname}_trimtemp.avs");
&echotofile("last.height %% 2 == 1 ? AddBorders(0,0,0,1) : NOP",">>","${projname}_trimtemp.avs");
+
&echotofile("last.height % 2 == 1 ? AddBorders(0,0,0,1) : NOP\n",">>","${projname}_trimtemp.avs");
&echotofile("last",">>","${projname}_trimtemp.avs");
+
&echotofile("last\n",">>","${projname}_trimtemp.avs");
 
} else {
 
} else {
&echotofile("Lanczos4Resize(320,240)",">>","${projname}_trimtemp.avs");
+
&echotofile("Lanczos4Resize(320,240)\n",">>","${projname}_trimtemp.avs");
 
}
 
}
system("START \"trimming vdub\" \"${vdub_dir}/${vdubgui}\" \"${projname}_trimtemp.avs\"");
+
system("${start} \"trimming vdub\" \"${vdub_dir}/${vdubgui}\" \"${projname}_trimtemp.avs\"");
 
@trimarr = ();
 
@trimarr = ();
 
print $prompt;
 
print $prompt;
Line 483: Line 993:
 
#error codes' precedence is descending, e.g. empty string is first because it is the most serious error
 
#error codes' precedence is descending, e.g. empty string is first because it is the most serious error
 
if ($_ eq '') {
 
if ($_ eq '') {
$errormsg="You must enter a frame number, or type n to quit.";
+
$errormsg=$lang{TRIM_ILLEGAL_VALUE};
 
} elsif (m/^n$/i) {
 
} elsif (m/^n$/i) {
 
if (@trimarr < 1) {
 
if (@trimarr < 1) {
&out_info("No values entered. Canceling trim.");
+
&out_info($lang{TRIM_NO_VALUES_ENTERED});
 
$trim=0;
 
$trim=0;
 
last;
 
last;
 
} elsif (@trimarr % 2) {
 
} elsif (@trimarr % 2) {
&out_error("Odd number of frame numbers detected! All trim values erased!");
+
&out_error($lang{TRIM_ODD_NUMBER_OF_FRAMES});
 
@trimarr = ();
 
@trimarr = ();
 +
} else {
 +
&out_info($lang{TRIM_DONE});
 +
last;
 
}
 
}
 
} elsif (!m/^[0-9]+$/i) {
 
} elsif (!m/^[0-9]+$/i) {
$errormsg="Invalid input. Must be frame number.";
+
$errormsg=$lang{TRIM_INVALID_INPUT_MUST_BE_FRAME_NUMBER};
 +
} elsif ((@trimarr % 2) && ($trimarr[@trimarr-1] > $_)) {
 +
$errormsg=$lang{TRIM_INVALID_RANGE};
 
} else {
 
} else {
 
push(@trimarr,$_);
 
push(@trimarr,$_);
&out_info('trim point #'.@trimarr.' loaded successfully!');
+
&out_info($lang{TRIM_POINT_LOADED_SUCCESSFULLY}.' #'.@trimarr);
 
&echo("");
 
&echo("");
 
print $prompt;
 
print $prompt;
Line 507: Line 1,022:
 
&rm("${projname}_trimtemp.avs");
 
&rm("${projname}_trimtemp.avs");
 
}
 
}
+
}
#statid stuff
+
&out_cls_section("Station ID");
+
if (! defined $statid) {
&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.");
+
&out_cls_section($lang{SECTION_STATID});
&q_boo($statid,"Do you want to append an SDA Station ID to the front and end of this video? [y,n]");
+
&out_info($lang{STATID_INFO});
if ($statid) {
+
if (q_boo($lang{QUESTION_STATID}, $statid)) {
 +
q_boo($lang{QUESTION_AUDIOCOMMENTARY}, $audio_commentary) if ! defined $audio_commentary;
 
@statidlines = ();
 
@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.");
+
&out_info($lang{STATID_ABOUT_EACH_LINE});
for ($i = 1 ; $i <= 3 ; $i++) {
+
for (my $i = 1 ; $i <= 3 ; $i++) {
&out_info("Station ID Line ${i}:");
+
&out_info($lang{STATID_LINE}." ${i}:");
 
print $prompt;
 
print $prompt;
 
$statidline = <STDIN>;
 
$statidline = <STDIN>;
 +
chomp($statidline);
 
$statidline =~ s/"/"+chr(34)+"/g;
 
$statidline =~ s/"/"+chr(34)+"/g;
push(@statidlines,'"'.$statidline.'"');
+
push(@statidlines,$statidline);
 
&echo("");
 
&echo("");
 
}
 
}
 +
} else {
 +
@statidlines = ('','','');
 
}
 
}
} #end of !$auto
+
}
  
 
############################################################################
 
############################################################################
Line 537: Line 1,056:
  
 
#:proc_check_settings
 
#:proc_check_settings
&cd("${desktop}/${projname}");
+
chdir("${desktop}/${projname}");
 
$ready=1;
 
$ready=1;
$ready=0 if !&samefiles("${projname}_job.bat","${projname}_job.bak");
+
#$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") {
 
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;
 
$ready=0 if !-e $thefile;
 
}
 
}
 
if (!$ready) {
 
if (!$ready) {
&savesettings;
+
#&savesettings;
 
&script_buildfiles;
 
&script_buildfiles;
 
}
 
}
Line 556: Line 1,075:
 
############################################################################
 
############################################################################
  
if (!$auto) {
+
# if (!$auto) {
&check_settings;
+
# &check_settings;
} else {
+
# } else {
$settings_good=1;
+
# $settings_good=1;
}
+
# }
 
#IF NOT "%settings_good%"=="y" GOTO proc_check_settings_p2
 
#IF NOT "%settings_good%"=="y" GOTO proc_check_settings_p2
 
 
&out_cls_section("READY TO ENCODE");
+
&out_cls_section($lang{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.");
+
&out_info("$lang{SETTINGS_SAVED_TO_FILE} \"${projname}_job.bat\".");
  
if (!$auto) {
+
# if (!$auto) {
&q_encodenow;
+
# &q_encodenow;
} else {
+
# } else {
$start_encode=1;
+
# $start_encode=1;
}
+
# }
  
if ($start_encode) {
+
if ($auto or q_boo($lang{QUESTION_ENCODE_NOW_OR})) {
&proc_encode;
+
} else {
+
#:proc_check_settings_p2
&proc_encode;
+
}
+
#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/XQ, and Xvid LQ/MQ.
 +
#
 +
# IF D1 and the user is encoding HQ/IQ/XQ, they will be asked whether
 +
# they want 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.
 +
############################################################################
 +
 +
&out_cls_section($lang{SECTION_ENCODING_OPTIONS});
 +
%qualities = (
 +
#makethisboolean, howtomake, english, id tag, video bitrate in kbaud, audio bitrate in baud, minimum quantizer for x264, delete 2pass stats, delete all other tempfiles
 +
# 0 1 2 3 4 5 6 7 8
 +
lq    => [ 1, \&twopass, "Low quality H.264 MP4", "_LQ", 128, 64000, 17, 1,1],
 +
mq    => [ 1, \&ipod, "Medium quality H.264 MP4", "", 512, 64000, 17, 1,1],
 +
hq    => [ 1, \&twopass, "High quality H.264 MP4", "_HQ", 2048, 128000, $hqq, 1,1],
 +
iq    => [  (($d==1) && ($f==1)), \&twopass, "Insane quality H.264 MP4", "_IQ", 5000, $maxaudiobr, 19, 1,1],
 +
xq    => [  (($d==1) && ($f==1)), \&twopass, "X-Treme quality H.264 MP4", "_XQ", 10000, $maxaudiobr, 19, 1,1],
 +
lqavi => [ 1, \&xvid, "Low quality XviD AVI", "_LQ", 128, 64000, "", 1,1],
 +
mqavi => [ 1, \&xvid, "Medium quality XviD AVI", "", 512, 64000, "", 1,1],
 +
);
 +
 +
if (!@encodethese) {
 +
#&savesettings;
 +
for (qw(lq mq hq iq xq lqavi mqavi)) {
 +
my @t = @{ $qualities{$_} };
 +
#if this quality is not disabled for these content properties - then ask the user if they want to make it
 +
push(@encodethese, $_) if $t[0] and q_boo("$lang{QUESTION_CREATE_VIDEO} $t[2] (".($t[4]+($t[5]/1000))." kbit/sec)");
 +
}
 +
}
  
#:proc_check_settings_p2
+
for (@encodethese) {
 
+
my $idtag = $qualities{$_}[3];
#FOR %%A IN (dfnd_set d f twod fieldorder vhs onepixel nes gba gameboy deflicker trimarray) DO (SET %%A=)
+
if (
#SET batch=
+
((($d == 1) && ($f == 1)) && ($idtag =~ m/^_HQ$/)) #d1 f1 hq
 
+
or
&rm("${projname}_job.bat");
+
($idtag =~ m/^(_IQ|_XQ)$/) #any iq/xq
&rm("${projname}_job.bak");
+
) {
#GOTO proc_gameproperties
+
&nmf;
 
+
last;
############################################################################
+
# 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, arg1 (video bitrate in kbaud), arg2 (audio bitrate in baud), arg3 (minimum quantizer for x264), arg4 (delete 2pass stats), arg5 (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]");
+
 
}
 
}
 
}
 
}
+
 
 +
&out_cls_info($lang{NOW_ENCODING});
 +
for (@encodethese) {
 +
my @t = @{ $qualities{$_} };
 +
print "now encoding $t[2] ($projname.$t[3].$nmf, $projname.$t[3], @t[4..8])\n";
 +
$t[1]->($projname.$t[3].$nmf, $projname.$t[3], @t[4..8]);
 +
}
 +
} else {
 +
#save stuff
 
}
 
}
 
 
&nmf if (
+
mkdir('finished_'.$projname);
(($d&&$f) and ($_[3] eq "_HQ")) #only d1 f1 hq
+
&mv("*.mp4",'finished_'.$projname);
or
+
&mv("*.avi",'finished_'.$projname);
($_[3] ~ /^(_IQ|_XQ)$/) #any iq/xq
+
);
+
 
 
&out_cls_info("Now encoding ...");
+
&out_info($lang{ALL_DUN});
for (@encodethese) {
+
<STDIN>;
# 0 1      2    3    4    5    6
+
exit 0; #have to exit because we don't reset vars ...
eval($_[1] $projname.$_[3].$nmf.'.avs' $projname $_[4] $_[5] $_[6] $_[7] $_[8]);
+
}
+
 
+
sub nmf {
+
$nmf = '_nmf';
+
}
+
  
 
# MD finished > NUL 2>&1
 
# MD finished > NUL 2>&1
Line 685: Line 1,211:
 
# ATTRIB +H finished\%log:~0,-4%.bak
 
# ATTRIB +H finished\%log:~0,-4%.bak
 
#  
 
#  
# MOVE /Y %PROJNAME%_LQ.avi finished > NUL 2>&1
+
# MOVE /Y ${projname}_LQ.avi finished > NUL 2>&1
# MOVE /Y %PROJNAME%.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}_LQ.mp4 finished > NUL 2>&1
# MOVE /Y %PROJNAME%.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}_HQ.mp4 finished > NUL 2>&1
# MOVE /Y %PROJNAME%_IQ.mp4 finished > NUL 2>&1
+
# MOVE /Y ${projname}_IQ.mp4 finished > NUL 2>&1
# MOVE /Y %PROJNAME%_XQ.mp4 finished > NUL 2>&1
+
# MOVE /Y ${projname}_XQ.mp4 finished > NUL 2>&1
 
#  
 
#  
 
#  
 
#  
Line 706: Line 1,232:
 
# )
 
# )
 
# IF "%XQskipped%"=="notHD" (
 
# 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 You chose XQ for high definition video however Anri 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
 
#  ECHO. | "%anri_dir%tee.exe" -a finished\read.txt
 
# )
 
# )
Line 712: Line 1,238:
 
# ECHO.
 
# ECHO.
 
# GOTO die
 
# GOTO die
 +
 +
}
  
  
Line 740: Line 1,268:
  
 
sub samefiles {
 
sub samefiles {
open(FILEONE, $_[0]);
+
open(FILEONE, "${_[0]}");
 
@fileone=<FILEONE>;
 
@fileone=<FILEONE>;
 
close(FILEONE);
 
close(FILEONE);
open(FILETWO, $_[1]);
+
open(FILETWO, "${_[1]}");
 
@filetwo=<FILETWO>;
 
@filetwo=<FILETWO>;
 
close(FILETWO);
 
close(FILETWO);
Line 749: Line 1,277:
 
return 0 if @fileone != @filetwo;
 
return 0 if @fileone != @filetwo;
 
#compare each line ... can tell the line on which they differ but currently no use for it in anri
 
#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++) {
+
for (my $i = 0 ; $i < @fileone ; $i++) {
return 0 if $fileone[$f] ne $filetwo[$f];
+
return 0 if $fileone[$i] ne $filetwo[$i];
 
}
 
}
 
return 1;
 
return 1;
Line 757: Line 1,285:
 
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}");
&cp("${dgmpgdec_dir}/infotemplate.avs","${desktop}/${projname}");
+
if ($os eq 'windows') {
&cp("${anri_dir}/ntsc_d1.png","${desktop}/${projname}");
+
&cp("${dgmpgdec_dir}/infotemplate.avs","${desktop}/${projname}");
 +
&cp("${anri_dir}/ntsc_d1.png","${desktop}/${projname}");
 +
} else { #unix
 +
&cp("${anri_dir}/ntsc_d1.tga","${desktop}/${projname}");
 +
}
 
}
 
}
  
Line 768: Line 1,300:
 
&rm("*.avs") if -e "${projname}.avs";
 
&rm("*.avs") if -e "${projname}.avs";
 
&cp("${projname}.bak","${projname}.avs");
 
&cp("${projname}.bak","${projname}.avs");
&cp("plugins.bak","plugins.avs");
+
&cp("plugins.bak","plugins.avs") if $os eq 'windows';
 
}
 
}
  
Line 787: Line 1,319:
 
&cp("plugins.avs","plugins.bak");
 
&cp("plugins.avs","plugins.bak");
 
}
 
}
 +
 +
# simple multi-threaded map, currently used for nmf
 +
# one thread is created per argument (excluding the first)
 +
sub tmap (&@) {
 +
require threads;
 +
my $f = shift;
 +
map { $_->join() } map { threads->create($f, $_) } @_;
 +
}
 +
 +
sub nmf {
 +
&out_cls_section($lang{SECTION_NMF});
 +
&out_info($lang{NMF_INFO});
 +
&echo("");
 +
&out_info($lang{INFO_HQ_IQ_XQ_NMF});
 +
&echo("");
 +
if (q_boo($lang{QUESTION_CREATE_NMF},$make_nmf)) {
 +
        $nmf = '_nmf';
 +
&echo("");
 +
 +
$number_of_processors=1;
 +
if ($os eq 'windows') {
 +
$number_of_processors=$ENV{NUMBER_OF_PROCESSORS};
 +
#Set lagarith to yv12 under doze
 +
# $lagarith_settings = <<SABRAC;
 +
# [settings]
 +
# lossy_option=3
 +
# SABRAC
 +
#commented out until i can figure out how to detect vista
 +
# IF DEFINED LOCALAPPDATA (
 +
#  REM Vista
 +
#  ECHO [settings] > "%LOCALAPPDATA%\VirtualStore\Windows\lagarith.ini"
 +
#  ECHO lossy_option=3 >> "%LOCALAPPDATA%\VirtualStore\Windows\lagarith.ini"
 +
# ) ELSE (
 +
#  ECHO [settings] > %WINDIR%\lagarith.ini
 +
#  ECHO lossy_option=3 >> %WINDIR%\lagarith.ini
 +
# )
 +
} else {
 +
# use Sys::CPU;
 +
# $number_of_processors = Sys::CPU::cpu_count();
 +
}
 +
&rm("${projname}_HQ_nmf.avs") if -e "${projname}_HQ_nmf.avs";
 +
#:nmf_vdubloop
 +
#counterB
 +
@nmfcommands = ();
 +
$alignedsplice = "";
 +
foreach $i (1 .. $number_of_processors) {
 +
&echotofile($alignedsplice,">>","${projname}_HQ_nmf.avs");
 +
&echotofile("avisource(\"${projname}_HQIQXQ_${i}.avi\")\n",">>","${projname}_HQ_nmf.avs");
 +
&cp("${projname}_HQ.avs","${projname}_HQIQXQ_${i}.avs");
 +
&echotofile("trim(floor(last.framecount/${number_of_processors}.000*".($i-1).".000), floor(last.framecount/${number_of_processors}.000*${i}.000)-1)\n",">>","${projname}_HQIQXQ_${i}.avs");
 +
push @nmfcommands, qq("${vdub_dir}/${vdubcli}" "${projname}_HQIQXQ_${i}.avs" /i "${anri_dir}/nmf.vcf" "${projname}_HQIQXQ_${i}.avi");
 +
$alignedsplice = "\\++\\\n";
 +
}
 +
&echotofile("converttoyv12\n",">>","${projname}_HQ_nmf.avs");
 +
#yikes ... better use single quotes for this one
 +
&echotofile('WriteFileStart("resolution.log","last.width",""" "," """, "last.height")',">>","${projname}_HQ_nmf.avs");
 +
&echotofile("changefps(last.framerate)\n",">>","${projname}_HQ_nmf.avs");
 +
&cp("${projname}_HQ_nmf.avs","${projname}_IQ_nmf.avs");
 +
&cp("${projname}_HQ_nmf.avs","${projname}_XQ_nmf.avs");
 +
#for now lq and nq ignore the nmf
 +
&cp("${projname}_LQ.avs","${projname}_LQ_nmf.avs");
 +
&cp("${projname}_LQ_xvid.avs","${projname}_LQ_xvid_nmf.avs");
 +
&cp("${projname}.avs","${projname}_nmf.avs");
 +
&cp("${projname}_xvid.avs","${projname}_xvid_nmf.avs");
 +
&echo($lang{ENCODING_NMF});
 +
tmap { system($_) } @nmfcommands;
 +
&echo("");
 +
&out_info($lang{NMF_SUCCESSFULLY_CREATED});
 +
&echo("");
 +
sleep(5);
 +
}
 +
}
 +
 +
 +
############################################################################
 +
# function: script_buildfiles
 +
#
 +
# Delete all avs files and restore base avs which has video source lines.
 +
############################################################################
 +
 +
sub script_buildfiles {
 +
&wipe_avs;
 +
#handle trimming stuff - @trimarr must already have an even number of elements due to our input sanitation
 +
if ($trim) {
 +
for (my $i=0 ; $i < @trimarr ; $i=($i+2)) {
 +
&echotofile("\\++\\\n",">>","${projname}.avs") if $i > 0;
 +
&echotofile("trim(".$trimarr[$i].",".$trimarr[$i+1].")\n",">>","${projname}.avs");
 +
}
 +
}
 +
$fieldorder ? &echotofile("AssumeTFF()\n",">>","${projname}.avs") : &echotofile("AssumeBFF()\n",">>","${projname}.avs");
 +
&echotofile("global pal = (last.height==576) ? true : false\n",">>","${projname}.avs");
 +
#this $projtemp is like the old _temp.avs from doze batch anri - not sure if we still need to do this temporarily like this but it's way too complex for me to confidently say we don't so i'm going to keep it
 +
$projtemp = '';
 +
if ($isPCGAME) {
 +
&echotofile("global f1 = last.framerate\n",">>","${projname}.avs");
 +
&cp("${projname}.avs","${projname}_HQ.avs");
 +
#better use single quotes for this one
 +
&echotofile('WriteFileStart("resolution.log","last.width",""" "," """, "last.height")',">>","${projname}_HQ.avs");
 +
&cp("${projname}.avs","${projname}_IQ.avs");
 +
&cp("${projname}.avs","${projname}_XQ.avs");
 +
&echotofile("new_width = round(Sqrt(800*600*last.width/last.height))\n",">>","${projname}_IQ.avs");
 +
#Avoid weird res on at least the width.
 +
&echotofile("new_width = new_width - new_width % 16\n",">>","${projname}_IQ.avs");
 +
&echotofile("new_height = round(new_width*last.height/last.width)\n",">>","${projname}_IQ.avs");
 +
&echotofile("last.width*last.height > 800*600 ? Lanczos4Resize(new_width,new_height) : NOP\n",">>","${projname}_IQ.avs");
 +
&echotofile("last.height % 2 == 1 ? AddBorders(0,0,0,1) : NOP\n",">>","${projname}_IQ.avs");
 +
&echotofile("last.width*last.height > 640*512 ? Lanczos4Resize(640,round(last.height*(640.0000/last.width))) : NOP\n",">>","${projname}_HQ.avs");
 +
&echotofile("last.height % 2 == 1 ? AddBorders(0,0,0,1) : NOP\n",">>","${projname}_HQ.avs");
 +
&echotofile("last.width % 2 == 1 ? AddBorders(0,0,1,0) : NOP\n",">>","${projname}_HQ.avs");
 +
&echotofile("last.width*last.height > 320*256 ? Lanczos4Resize(320,round(last.height*(320.0000/last.width))) : NOP\n",">>","${projname}.avs");
 +
&echotofile("last.height % 2 == 1 ? AddBorders(0,0,0,1) : NOP\n",">>","${projname}.avs");
 +
&echotofile("last.width % 2 == 1 ? AddBorders(0,0,1,0) : NOP\n",">>","${projname}.avs");
 +
} else {
 +
&echotofile("global f1 = (pal==true) ? 50 : 59.94\n",">>","${projname}.avs");
 +
&cp("${projname}.avs","${projname}_HQ.avs");
 +
&echotofile('WriteFileStart("resolution.log","last.width",""" "," """, "last.height")'."\n",">>","${projname}_HQ.avs");
 +
#Set d1 either 704 or 640 (true), 352 or 320 (false)
 +
$dboo = ($d==1) ? "true" : "false";
 +
&echotofile("global d1 = ".$dboo." ? ((pal==true) ? 704 : 640) : ((pal==true) ? 352 : 320)\n",">>","${projname}_HQ.avs");
 +
&cp("${projname}_HQ.avs","${projname}_IQ.avs");
 +
#Set d1 either 352 or 320 for LQ/MQ
 +
&echotofile("global d1 = false ? ((pal==true) ? 704 : 640) : ((pal==true) ? 352 : 320)\n",">>","${projname}.avs");
 +
#d1 is set, but not yet resized.
 +
if ($prog) {
 +
$projtemp .= "pal==true ? d1==704 ? lanczos4resize(704,576) : lanczos4resize(352,288) : d1==640 ? lanczos4resize(640,480) : lanczos4resize(320,240)\n";
 +
} else {
 +
$projtemp .= "nate_vhs_head_change_erase\n" if $vhs;
 +
$projtemp .= "(pal==true ? d1==704 : d1==640) ? mvbob : separatefields\n";
 +
$projtemp .= "nate_1_pixel_bob_fix\n" if $onepixel;
 +
$projtemp .= "nate_retard_bob_2\n" if $deflicker;
 +
$projtemp .= "nate_nes\n" if $nes;
 +
$projtemp .= "lanczos4resize(d1,last.height)\n";
 +
$projtemp .= "nate_gba\n" if $gba;
 +
$projtemp .= "nate_gb\n" if $gb;
 +
}
 +
$projtemp .= "changefps(f1/".$f.")\n" if !$prog;
 +
}
 +
 +
$projtemp .= "run=converttoyv12\n";
 +
if ($statid) {
 +
$statidtype = "d1";
 +
$statidtype = "gba" if $gba;
 +
$statidtype = "gb" if $gb;
 +
$projtemp .= "statid=nate_statid_".$statidtype."(run,\"".$statidlines[0]."\",\"".$statidlines[1]."\",\"".$statidlines[2]."\",".($audio_commentary == 1 ? 1 : 0).").ConvertToRGB\n";
 +
$projtemp .= "statid = float(run.width) / run.height >= 4./3 ?\n";
 +
$projtemp .= "\\ statid.Lanczos4Resize(round(run.height*4./3),run.height).AddBorders(floor((run.width-round(run.height*4./3))/2.),0,ceil((run.width-round(run.height*4./3))/2.),0).ConvertToYv12 :\n";
 +
$projtemp .= "\\ statid.Lanczos4Resize(run.width,round(run.width*3./4)).AddBorders(0,floor((run.height-round(run.width*3./4))/2.),0,ceil((run.height-round(run.width*3./4))/2.)).ConvertToYv12\n";
 +
$projtemp .= "statid++run++statid\n";
 +
} else {
 +
$projtemp .= "run\n";
 +
}
 +
$projtemp .= "changefps(last.framerate)\n";
 +
$projtemp .= "converttoyv12\n";
 +
 +
&echotofile($projtemp,">>","${projname}.avs");
 +
&echotofile($projtemp,">>","${projname}_HQ.avs");
 +
&echotofile($projtemp,">>","${projname}_IQ.avs");
 +
&echotofile($projtemp,">>","${projname}_XQ.avs");
 +
&cp("${projname}.avs","${projname}_LQ.avs");
 +
 +
if ($twod) {
 +
&echotofile("(last.framerate > 31) ? changefps(f1/3) : last\n",">>","${projname}_LQ.avs");
 +
} else {
 +
&echotofile("(last.framerate > 31) ? changefps(f1/2) : last\n",">>","${projname}.avs");
 +
&echotofile("(last.framerate > 31) ? changefps(f1/2) : last\n",">>","${projname}_LQ.avs");
 +
}
 +
&cp("${projname}_LQ.avs","${projname}_xvid.avs");
 +
&cp("${projname}_LQ.avs","${projname}_LQ_xvid.avs");
 +
 +
&rm("${projname}_trimtemp.avs") if -e "${projname}_trimtemp.avs";
 +
}
 +
 +
 +
 +
# REM ------- SETTINGS MANAGER -------
 +
#
 +
# :find_existing_settings
 +
# IF EXIST "%projdirpath%\${projname}_job.bat" (
 +
# CALL "%projdirpath%\${projname}_job.bat"
 +
# SET using_settings=y
 +
# )
 +
# GOTO :EOF
 +
#
 +
# :check_settings
 +
# CALL :show_settings
 +
# :check_settings_p2
 +
# SET s=
 +
# SET /P s=Do you want to encode using these settings? If you choose No you will be prompted to enter them again. [$lang{y}/$lang{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. 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 )
 +
# IF "%dvdsource%"=="y" ( ECHO DVD Drive Letter: %driveletter% )
 +
# ECHO Project Name: ${projname}
 +
# IF DEFINED avifolder ECHO AVI folder: %avifolder%
 +
# 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 ) ELSE ( ECHO Not 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 "%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 "%trim%"=="y" ECHO Trim frame ranges %trimarray%
 +
# IF "%statid%"=="y" ECHO StatID: %statid1:"+chr(34)+"="% / %statid2:"+chr(34)+"="% / %statid3:"+chr(34)+"="%
 +
# ECHO.
 +
# GOTO :EOF
 +
#
 +
# :savesettings
 +
# ECHO @ECHO OFF > "${projname}_job.bat"
 +
# ECHO (SET proj_anriver=%anri_ver%) >> "${projname}_job.bat"
 +
# ECHO (SET using_settings=y) >> "${projname}_job.bat"
 +
# ECHO (SET dvdsource=%dvdsource%) >> "${projname}_job.bat"
 +
# ECHO (SET avifolder=%avifolder%) >> "${projname}_job.bat"
 +
# ECHO (SET avifiles=%avifiles%) >> "${projname}_job.bat"
 +
# ECHO (SET fieldorder=%fieldorder%) >> "${projname}_job.bat"
 +
# ECHO (SET d=%d%) >> "${projname}_job.bat"
 +
# ECHO (SET f=%f%) >> "${projname}_job.bat"
 +
# ECHO (SET vhs=%vhs%) >> "${projname}_job.bat"
 +
# ECHO (SET onepixel=%onepixel%) >> "${projname}_job.bat"
 +
# ECHO (SET nes=%nes%) >> "${projname}_job.bat"
 +
# ECHO (SET twod=%twod%) >> "${projname}_job.bat"
 +
# ECHO (SET statid=%statid%) >> "${projname}_job.bat"
 +
# ECHO (SET statid1=%statid1%) >> "${projname}_job.bat"
 +
# ECHO (SET statid2=%statid2%) >> "${projname}_job.bat"
 +
# ECHO (SET statid3=%statid3%) >> "${projname}_job.bat"
 +
# ECHO (SET driveletter=%driveletter%) >> "${projname}_job.bat"
 +
# ECHO (SET projname=${projname}) >> "${projname}_job.bat"
 +
# ECHO (SET gba=%gba%) >> "${projname}_job.bat"
 +
# ECHO (SET gameboy=%gameboy%) >> "${projname}_job.bat"
 +
# ECHO (SET deflicker=%deflicker%) >> "${projname}_job.bat"
 +
# ECHO (SET prog=%prog%) >> "${projname}_job.bat"
 +
# ECHO (SET trim=%trim%) >> "${projname}_job.bat"
 +
# ECHO (SET trimarray=%trimarray%) >> "${projname}_job.bat"
 +
# ECHO (SET maxaudiobitrate=%maxaudiobitrate%) >> "${projname}_job.bat"
 +
# ECHO (SET hqq=%hqq%) >> "${projname}_job.bat"
 +
# ECHO (SET isPCGAME=%isPCGAME%) >> "${projname}_job.bat"
 +
# ECHO IF NOT "%%in_anrichan%%"=="y" call "%anri_path%" >> "${projname}_job.bat"
 +
# COPY /Y "${projname}_job.bat" "${projname}_job.bak" > NUL
 +
# GOTO :EOF
 +
#
 +
# :createjob
 +
# CALL :savesettings
 +
# PAUSE
 +
# GOTO die
  
 
############################################################################
 
############################################################################
Line 796: Line 1,580:
 
#fullpathtokey, data, type
 
#fullpathtokey, data, type
 
sub update_registry_key {
 
sub update_registry_key {
use Win32::TieRegistry(Delimiter=>"/",ArrayValues=>0);
+
require Win32::TieRegistry;
 +
import  Win32::TieRegistry (Delimiter=>"/", ArrayValues=>0) unless defined $Registry;
 
$Registry->{$_[0]} = [ $_[1], $_[2] ];
 
$Registry->{$_[0]} = [ $_[1], $_[2] ];
 
}
 
}
Line 829: Line 1,614:
 
}
 
}
 
}
 
}
 +
 +
$secondarg = '.';
 +
$secondarg = $_[1] if $_[1];
 
 
 
$command = 'cp';
 
$command = 'cp';
Line 835: Line 1,623:
 
$flags = ' -R';
 
$flags = ' -R';
 
$flags = ' /Y /B' if $os eq 'windows';
 
$flags = ' /Y /B' if $os eq 'windows';
 +
 +
$redirect = '';
 +
$redirect = ' > NUL' if $os eq 'windows';
 +
 +
$command = "${command}${flags} \"${_[0]}\" \"${secondarg}\"${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 = '';
Line 882: Line 1,696:
 
system('declare -x PROMPT_COMMAND=\'printf "\e]0;'.$_[0].'\a"\'');
 
system('declare -x PROMPT_COMMAND=\'printf "\e]0;'.$_[0].'\a"\'');
 
}
 
}
 +
}
 +
 +
sub trim($) { #from http://www.somacon.com/p114.php
 +
my $string = shift;
 +
$string =~ s/^\s+//;
 +
$string =~ s/\s+$//;
 +
return $string;
 
}
 
}
  
Line 891: Line 1,712:
  
 
# function: q_boo
 
# function: q_boo
# sets boolean variable (0 or 1)
+
# returns boolean, optionally also sets boolean variable (0 or 1)
#variable to set, out_info text
+
#out_info text, [variable to set]
sub q_boo {
+
sub q_boo($;$) {
&out_info($_[1]);
+
if (defined $_[1]) {
 +
if ($_[1] == 1 or $_[1] eq $lang{"y"}) { #for some reason {y} causes textwrangler's syntax highlighting to break
 +
$_[1] = 1;
 +
return 1;
 +
} elsif ($_[1] == 0 or $_[1] eq $lang{n}) {
 +
$_[1] = 0;
 +
return 0;
 +
}
 +
}
 +
&out_info($_[0]." [$lang{y}/$lang{n}]");
 
print $prompt;
 
print $prompt;
while (<STDIN>) {
+
while (my $userinput = <STDIN>) {
chomp;
+
chomp($userinput);
if (m/^[yn]$/) {
+
if ($userinput eq $lang{"y"}) {
#t becomes 1 (true), b becomes 0 (false)
+
$_[1] = 1;
tr/yn/10/;
+
return 1;
$_[0] = $_;
+
} elsif ($userinput eq $lang{n}) {
last;
+
$_[1] = 0;
 +
return 0;
 +
} else {
 +
print "$lang{INVALID_INPUT}\n\n";
 +
print $prompt;
 
}
 
}
print "Invalid input.\n\n";
 
print $prompt;
 
 
}
 
}
return $_[0];
 
 
}
 
}
  
Line 913: Line 1,744:
 
# function: q_avi
 
# function: q_avi
 
#  
 
#  
# Ask the user if he wants to do manual input of file paths, or automatically
+
# Ask the user if they want to do manual input of file paths, or automatically
 
# by loading the files in a specified directory alphabetically.
 
# by loading the files in a specified directory alphabetically.
 
############################################################################
 
############################################################################
 
sub q_avi {
 
sub q_avi {
$maxaudiobr = 320000;
+
$maxaudiobr ||= 320000;
&out_cls_section("AVI SOURCE");
+
&out_cls_section($lang{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.");
+
if (@avifiles) {
&echo("");
+
#nothing to do here
print $prompt;
+
} elsif (defined $avidir) {
while (<STDIN>) {
+
&q_avi_a;
chomp;
+
} else {
if (m/([ia])$/) {
+
&out_info($lang{AVI_SOURCE_INFO});
#i becomes 1 (true), a becomes 0 (false)
+
&echo("");
tr/ia/10/;
+
print $prompt;
$_ ? &q_avi_i : &q_avi_a;
+
while (<STDIN>) {
last;
+
chomp;
 +
if (m/([ia])$/) {
 +
#i becomes 1 (true), a becomes 0 (false)
 +
tr/ia/10/;
 +
$_ ? &q_avi_i : &q_avi_a;
 +
last;
 +
}
 +
print "$lang{INVALID_INPUT}\n\n";
 +
print $prompt;
 
}
 
}
print "Invalid input.\n\n";
 
print $prompt;
 
 
}
 
}
 
#IF "%auto%"=="y" GOTO avimethod_skip
 
#:avimethod_skip
 
 
#AVI files loaded, generate avs source lines.
 
#AVI files loaded, generate avs source lines.
 
&echotofile("import(\"${anri_dir}/sda.avs\")\n",">>","${projname}.avs");
 
&echotofile("import(\"${anri_dir}/sda.avs\")\n",">>","${projname}.avs");
Line 941: Line 1,775:
 
$alignedsplice = '';
 
$alignedsplice = '';
 
for $avifile (@avifiles) {
 
for $avifile (@avifiles) {
&echotofile($alignedsplice,">>","${projname}.avs");
+
&echotofile($alignedsplice, ">>", "${projname}.avs");
if ($os eq 'windows') {
+
$fourcc = "";
@fourccstuff = qx("${anri_dir}/cfourcc.exe" "${avifile}");
+
open(AVIFILE, "<:raw", $avifile)
$fourcc = join('',@fourccstuff);
+
    and sysseek(AVIFILE, 0xBC, 0)
#"${anri_dir}/cfourcc.exe" "%avifolder%%%~G" >> running_log.txt
+
    and sysread(AVIFILE, $fourcc, 4);
$fourcc =~ s/.*Use : (....).*/$1/s;
+
close(AVIFILE);
open(DSHOW, "${anri_dir}/${directshowsourcelistfile}");
+
$sourcedecverb = 'avisource';
@directshowsourcelist=<DSHOW>;
+
$sourcedecverb = 'directshowsource' if grep {$_ eq lc($fourcc)} qw(tscc xvid dx50);
close(DSHOW);
+
&echotofile("${sourcedecverb}(\"${avifile}\")\n", ">>", "${projname}.avs");
for (@directshowsourcelist) {
+
$alignedsplice = "\\++\\\n";
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
 
#newline needed
Line 975: Line 1,799:
 
sub q_avi_i {
 
sub q_avi_i {
 
&echo("");
 
&echo("");
&out_info('Path to source video file e.g. c:\path to\video.avi without quotes.');
+
&out_info($lang{AVI_PATH_TO});
&out_info("  - Type n to quit -");
+
&out_info($lang{TYPE_N_TO_QUIT});
 
&echo("");
 
&echo("");
 
#:q_avi_i_p2
 
#:q_avi_i_p2
Line 984: Line 1,808:
 
#error codes' precedence is descending, e.g. empty string is first because it is the most serious error
 
#error codes' precedence is descending, e.g. empty string is first because it is the most serious error
 
if ($_ eq '') {
 
if ($_ eq '') {
$errormsg="You must enter a path, or type n to quit.";
+
$errormsg=$lang{AVI_BAD_INPUT};
 
} elsif (m/^n$/i) {
 
} elsif (m/^n$/i) {
 
if (@avifiles < 1) {
 
if (@avifiles < 1) {
$errormsg="You must load at least one avi file.";
+
$errormsg=$lang{AVI_NONE_ENTERED};
 
} else {
 
} else {
 
last;
 
last;
 
}
 
}
 
} elsif (!m/.*\.av[si]$/i) {
 
} elsif (!m/.*\.av[si]$/i) {
$errormsg="Must be an avi file, try again.";
+
$errormsg=$lang{AVI_NOT_AVI};
 
} elsif (! -e $_) {
 
} elsif (! -e $_) {
$errormsg="File does not exist, try again.";
+
$errormsg=$lang{FILE_NOT_FOUND};
 
} else {
 
} else {
 
push(@avifiles,$_);
 
push(@avifiles,$_);
&out_info('avi #'.@avifiles.' loaded successfully!');
+
&out_info($lang{AVI_LOADED_SUCCESSFULLY}.' #'.@avifiles);
 
&echo("");
 
&echo("");
 
print $prompt;
 
print $prompt;
Line 1,015: Line 1,839:
 
sub q_avi_a {
 
sub q_avi_a {
 
&echo("");
 
&echo("");
#saved this string in a variable for use later on down
+
&out_info($lang{AVI_DIR_LOAD_INFO});
$enterhelp = 'Enter the path to the avi folder e.g. c:\my video folder\ without quotes.';
+
while (1) {
&out_info($enterhelp);
+
if (defined $avidir) {
print $prompt;
+
$_ = $avidir;
#Validate avifolder. Check for blank, then :\ for full path if windows, then see whether it exists.
+
} else {
while (<STDIN>) {
+
print $prompt;
 +
$_ = <STDIN>;
 +
}
 
@avifiles = ();
 
@avifiles = ();
 
chomp;
 
chomp;
 +
#Validate avifolder. Check for blank, then :\ for full path if windows, then see whether it exists.
 
if (m/^$/) {
 
if (m/^$/) {
$errormsg="You must enter a path.";
+
$errormsg=$lang{AVI_DIR_LOAD_MUST_ENTER_PATH};
} elsif (m/^.[^:][^\\].*/) {
+
} elsif (m/^.[^:][^\\].*/ or $os ne 'windows') {
$errormsg="Must be full path.";
+
$errormsg=$lang{AVI_DIR_LOAD_MUST_BE_FULL_PATH};
 
} elsif (! -e $_) {
 
} elsif (! -e $_) {
$errormsg="Folder does not exist.";
+
$errormsg=$lang{AVI_DIR_LOAD_DIR_DOES_NOT_EXIST};
 
} else {
 
} else {
 
$avifolder = $_;
 
$avifolder = $_;
Line 1,035: Line 1,862:
 
 
 
#build list
 
#build list
for (<$avifolder/*.avi>) {
+
for (glob("$avifolder/*.avi")) {
 
push(@avifiles,$_);
 
push(@avifiles,$_);
 
print $_."\n";
 
print $_."\n";
Line 1,042: Line 1,869:
 
#user can accept if files were found
 
#user can accept if files were found
 
if (@avifiles == 0) {
 
if (@avifiles == 0) {
$errormsg = 'No avi files found in that folder!';
+
$errormsg = $lang{AVI_DIR_LOAD_NO_AVIS_FOUND_IN_DIR};
 
} else {
 
} else {
 
#Ask user if the list is good.
 
#Ask user if the list is good.
&echo('Continue [y] or rescan [n]?');
+
if ($auto or q_boo($lang{QUESTION_AVI_DIR_LOAD_CONTINUE_OR_RESCAN})) {
print $prompt;
+
last;
while (<STDIN>) {
+
} else {
chomp;
+
$errormsg = $lang{AVI_DIR_LOAD_INFO};
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;
 
 
}
 
}
 
}
 
}
 +
undef $avidir;
 
&out_error($errormsg);
 
&out_error($errormsg);
print $prompt;
+
}
 +
}
 +
 
 +
############################################################################
 +
# function: q_dfnd
 +
#
 +
# FIXME
 +
############################################################################
 +
sub q_dfnd {
 +
&out_info($lang{DFND_INFO});
 +
q_boo($lang{QUESTION_USE_DFND_DATABASE}, $dfnd);
 +
if ($dfnd) {
 +
#:dfnd
 +
&out_info($lang{INFO_CONNECTING_TO_DFND_DATABASE});
 +
&out_info($lang{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" "'.$lang{DFND_URL}.'"';
 +
$_ = 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; ###FIXME: this wipes out the user's cli-specified --gb or whatever if they don't specify --spec
 +
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;
 +
#right now only the accent in Pokemon and & need to be changed, but it'd be better for it to work with all utf chars
 +
$title=~s/(\xc3\xa9)/chr(130)/eg;
 +
$titles .= "".($i+1).": ${title}\n";
 +
#printing at most 50 lines at a time
 +
if(($i+1) % 50 == 0) {
 +
print $titles;
 +
$titles = '';
 +
&out_info($lang{PRESS_ENTER_PAGE});
 +
<STDIN>;
 +
}
 +
}
 +
print $titles;
 +
#system("echo \"${titles}\" | more");
 +
print $prompt;
 +
while (<STDIN>) {
 +
chomp;
 +
if (m/^$/) {
 +
$errormsg=$lang{DFND_MUST_CHOOSE_GAME};
 +
} elsif (m/[^0-9]/) {
 +
$errormsg=$lang{DFND_MUST_ENTER_GAME_NUMBER};
 +
} elsif (($_ > scalar @dfnddata) or ($_ < 0)) {
 +
$errormsg=$lang{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($lang{DFND_COULD_NOT_CONNECT_TO_SDA});
 +
&q_dfnd if q_boo($lang{QUESTION_DFND_COULD_NOT_CONNECT_TO_SDA_TRY_AGAIN});
 +
}
 
}
 
}
 
}
 
}
Line 1,100: Line 2,012:
 
$_[0] = '' if not defined $_[0];
 
$_[0] = '' if not defined $_[0];
 
&echo("${maroon_on_gray}[!]");
 
&echo("${maroon_on_gray}[!]");
&echo("${maroon_on_gray}[!] ${maroon_on_silver}".$_[0]);
+
for (@_) {
 +
&echo("${maroon_on_gray}[!] ${maroon_on_silver}".$_);
 +
}
 
&echo("${maroon_on_gray}[!]");
 
&echo("${maroon_on_gray}[!]");
 
system($reset_color);
 
system($reset_color);
Line 1,108: Line 2,022:
 
sub out_section {
 
sub out_section {
 
$_[0] = '' if not defined $_[0];
 
$_[0] = '' if not defined $_[0];
&title("Anri-chan ${version} - ".$_[0]);
+
&title("Anri ${version} - ".$_[0]);
 
&echo("${teal_on_gray}-------------------------");
 
&echo("${teal_on_gray}-------------------------");
 
&echo("${navy_on_gray}".$_[0]."");
 
&echo("${navy_on_gray}".$_[0]."");
Line 1,128: Line 2,042:
 
#print the numbered english half of a 2d array consisting of english,command pairs and show the anri prompt at the end
 
#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 {
 
sub out_menu {
for ($i = 0; $i < @_; $i++) {
+
for (my $i = 0; $i < @_; $i++) {
 
print " ".($i+1).". ".$_[$i][0]."\n";
 
print " ".($i+1).". ".$_[$i][0]."\n";
 
}
 
}
Line 1,151: Line 2,065:
 
############################################################################
 
############################################################################
  
sub index_dvd {
+
############################################################################
# SETLOCAL ENABLEDELAYEDEXPANSION
+
# function: rip_dvd
# 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 the editing phase 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 /P dvdchoice=[1-%index%]:
+
# # Start - Validate
+
# FOR %%G IN (%dvdchoice%) DO (
+
#   IF NOT DEFINED dvdfolder%%G (
+
#     CALL :out_error Folder %%G was not found.
+
#     GOTO :index_dvd_choice
+
#   )
+
# )
+
# # End - Validate
+
#  
+
# ECHO.
+
# CALL :out_info Now indexing MPEG-2 ...
+
#  
+
# # Start - AVS prep
+
# IF EXIST %projname%.avs DEL %projname%.avs
+
# ECHO loadplugin("%anri_dir%%dgmpgdec_dir%\DGDecode.dll") > %projname%.avs
+
# ECHO import("%anri_dir%nate.avs") >> %projname%.avs
+
# ECHO import("%projdirpath%\plugins.avs") >> %projname%.avs
+
# # End - AVS prep
+
 
#  
 
#  
# SET num=1
+
# If IFO files are present, rip with Mplayer. Otherwise just a straight copy.
# 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 (
+
sub rip_dvd {
#     IF %%~zH GTR 5000 (
+
&out_cls_section($lang{SECTION_RIP_DVD});
#       # Run current vob through dgindex. Set to demux all tracks. Place vid,aud,delay info into temporary avs file.
+
if (! defined $driveletter) {
#       "%anri_dir%%dgmpgdec_dir%\dgindex.exe" -IF=[%%H] -OF=[%projname%%%~nH] -PREVIEW -exit
+
if ($os eq 'windows') {
#       MOVE /Y "%dvdripto_parentdir%\!dvdfolder%%G!\%%~nH.log" "%projdirpath%\%projname%_!num!_%%~nH.log"
+
&out_info($lang{QUESTION_DVD_DRIVE_LETTER});
#       "%anri_dir%%dgmpgdec_dir%\dgindex.exe" -IF=[%%H] -OM=2 -OF=[%projname%_!num!_%%~nH] -AT=[infotemplate.avs] -exit
+
&out_info($lang{RIP_DVD_SOURCE_FILES_ON_HD_TIP});
#       # If there's more than one file to be joined, they must be appended together.
+
print $prompt;
#      IF NOT !num!==1 echo \++\ >> %projname%.avs
+
while (<STDIN>) {
#       # Detect audio type, set vid,aud,delay to parameters a, b and c, generate source line.
+
chomp;
#       IF EXIST "%projname%_!num!_*.ac3" (
+
if (m/^[a-z]$/i) {
#         FOR /F "tokens=1,2,3 delims=," %%A IN ('TYPE "%projname%_!num!_%%~nH.avs"') DO (
+
$driveletter = $_;
#           ECHO AC3source(MPEG2source("%%A"^,upConv=1),"%%B").DelayAudio(%%C) >> %projname%.avs
+
last;
#        )
+
} else {
#      ) ELSE (
+
$errormsg=$lang{DVD_MUST_ENTER_DRIVE_LETTER};
#        IF EXIST "%projname%_!num!_*.mp*" (
+
}
#          FOR /F "tokens=1,2,3 delims=," %%A IN ('TYPE "%projname%_!num!_%%~nH.avs"') DO (
+
&out_error($errormsg);
#            ECHO AudioDub(MPEG2source("%%A"^,upConv=1),mpasource("%%B")).DelayAudio(%%C) >> %projname%.avs
+
print $prompt;
#          )
+
}
#        ) ELSE (
+
} else { #unix
#          IF EXIST "%projname%_!num!_*.wav" (
+
&out_info($lang{QUESTION_DVD_DRIVE_PATH});
#            FOR /F "tokens=1,2 delims=," %%A IN ('TYPE "%projname%_!num!_%%~nH.avs"') DO (
+
&out_info($lang{RIP_DVD_SOURCE_FILES_ON_HD_TIP_UNIX});
#              ECHO AudioDub(MPEG2source("%%A"^,upConv=1),wavsource("%%B")) >> %projname%.avs
+
print $prompt;
#            )
+
while (<STDIN>) {
#          )
+
chomp;
#        )
+
if (!m/^$/) {
#      )
+
$driveletter = $_;
#      # Find max bitrate, unless PCM which will make it 320000
+
last;
#       FINDSTR /C:PCM "%projname%_!num!_%%~nH.log" > NUL
+
} else {
#      IF !ERRORLEVEL!==0 (
+
$errormsg=$lang{DVD_MUST_ENTER_DRIVE_PATH};
#        SET maxaudiobitrate=320000
+
}
#      ) ELSE (
+
&out_error($errormsg);
#        FOR /F "tokens=*" %%N in ('FINDSTR /C:Audio "%projname%_!num!_%%~nH.log"') DO SET bitrate=%%N
+
print $prompt;
#         SET bitrate=!bitrate:~-3!000
+
}
#         IF !bitrate! GTR !maxaudiobitrate! (
+
}
#           SET maxaudiobitrate=!bitrate!
+
}
#        )
+
#this is mainly because when you drag things onto a terminal window in os x it cats a space on the end of the path
#       )
+
$driveletter = &trim($driveletter);
#      # Delete infotemplate child
+
if (defined $dvdripto) {
#      DEL "%projname%_!num!_%%~nH.avs"
+
$dvdripto = "${dvdripto_parentdir}/${dvdripto}";
#      SET /A num+=1
+
} else {
#    )
+
&echo("");
#  )
+
&out_info("$lang{DVD_INFO_ANRI_WILL_EXTRACT_TO_DIR} $lang{QUESTION_DVD_RIPTO_DIR_NAME}");
# )
+
print $prompt;
# # Just in case
+
while (<STDIN>) {
# IF %maxaudiobitrate%==0 SET maxaudiobitrate=320000
+
chomp;
# ENDLOCAL ENABLEDELAYEDEXPANSION & SET maxaudiobitrate=%maxaudiobitrate%
+
if (!m/^$/) {
# ECHO. >> "%projname%.avs"
+
$dvdripto = "${dvdripto_parentdir}/${_}";
# COPY /Y "%projname%.avs" "%projname%.bak" > NUL
+
last;
 +
} else {
 +
$errormsg=$lang{DVD_MUST_ENTER_RIPTO_DIR_NAME};
 +
}
 +
&out_error($errormsg);
 +
print $prompt;
 +
}
 +
}
 +
mkdir($dvdripto_parentdir) if !-e $dvdripto_parentdir; #paranoia
 +
mkdir($dvdripto) if !-e $dvdripto;
 +
&echo("");
 +
&out_info($lang{DVD_INFO_ANRI_WILL_RIP_NOW});
 +
if (!$auto) {
 +
&out_info($lang{PRESS_ENTER_TO_CONTINUE});
 +
&echo("");
 +
<STDIN>;
 +
}
 +
my $video_ts_tmp=&chopper("${driveletter}${colon}/VIDEO_TS");
 +
if (-e ${video_ts_tmp}) {
 +
$video_ts = "${video_ts_tmp}";
 +
#if (glob("${video_ts}/VTS*.IFO")) { #glob is utterly broken on my 10.5 machine running perl 5.8.8
 +
@ifofiles = ();
 +
opendir(VTS, $video_ts);
 +
@ifofiles = grep { /^VTS.*\.IFO$/ } readdir(VTS);
 +
closedir(VTS);
 +
$_ = $video_ts.'/'.$_ for @ifofiles;
 +
if (@ifofiles) {
 +
&pgccount(sort @ifofiles);
 +
 
 +
# if ($advanced_mode) {
 +
#      IF NOT "%auto%"=="y" (
 +
#        ECHO.
 +
#        CALL :out_info $lang{DVD_ADVANCED_MODE}
 +
#        SET s=
 +
#        SET /P s=$lang{DVD_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
 +
#        )
 +
#      )
 +
#    )
 +
# }
 +
$end_bar = 0; #safety for multiple dvd rips
 +
share($end_bar);
 +
$mplayer_loop_thread = threads->create(\&mplayer_loop);
 +
$mplayer_loop_thread->detach();
 +
&progress_bar("${dvdripto}", "${video_ts}", 2, "vob", "VOB", "", "",40);
 +
} else {
 +
&cp("${video_ts}/*","${dvdripto}");
 +
}
 +
} else {
 +
if (-e "${driveletter}/DVD_RTAV") {
 +
&cp("${driveletter}/DVD_RTAV/*","${dvdripto}");
 +
} else {
 +
&echo($lang{DVD_VIDEOTS_NOT_FOUND});
 +
#GOTO DIE
 +
}
 +
}
 +
$mplayer_loop_thread->set_thread_exit_only(1);
 +
if (!$auto) {
 +
&out_info("$lang{DVD_FINISHED_RIPPING} $lang{PRESS_ENTER_TO_CONTINUE}");
 +
<STDIN>;
 +
}
 +
undef $dvdripto;
 +
undef $driveletter;
 +
}
 +
 
 +
# mplayer extraction loop, put in new thread for progress bar
 +
# to run simultaneously with it.
 +
sub mplayer_loop{
 +
my $redirect = "\&>\"${dvdripto}/mplayer.log\"";
 +
if($os eq 'windows'){
 +
$redirect = "> \"${dvdripto}/mplayer.log\" 2>\&1";
 +
}
 +
#Rip the titles with Mplayer using info from &pgccount()
 +
for (@pgclist) {
 +
m/^([^,]+),.+\/VTS_([0-9][0-9])_.*$/;
 +
#zero pad to 3 places to avoid sorting problems where 10 comes before 2.
 +
$expandpgc = sprintf("%03d", $1);
 +
#FIXME log this
 +
system("\"${anri_dir}/${mplayer}\" dvd://${1} -dvd-device \"${video_ts}\" -dumpstream -dumpfile \"${dvdripto}/I${2}_${expandpgc}.vob\" ${redirect}");
 +
}
 +
#used to kill the progress bar just in case it doesn't kill itself first.
 +
$end_bar=1;
 +
}
 +
 
 +
# finds all unique program chains in a set of IFO files, stores in @pgclist
 +
sub pgccount {
 +
use bytes;
 +
$pgctable = 0x1000;
 +
@pgclist = ();
 +
$currentpgc = 0;
 +
for $ifofile (@_) {
 +
next unless &check_ifo();
 +
@sectors = ();
 +
for (1 .. unpack('n', substr($buffer, $pgctable, 2))) {
 +
$pgcstart  = unpack('N', substr($buffer, $pgctable + $_ * 8 + 4,            4));
 +
$cellstart  = unpack('n', substr($buffer, $pgctable + $pgcstart + 0xE8,      2)) + 8;
 +
$cellsector = unpack('N', substr($buffer, $pgctable + $pgcstart + $cellstart, 4));
 +
$currentpgc++;
 +
unless (grep { $_ == $cellsector } @sectors) {
 +
push @sectors, $cellsector;
 +
push @pgclist, "${currentpgc},${ifofile}";
 +
}
 +
}
 +
}
 +
}
 +
 
 +
# performs error checking for pgccount
 +
sub check_ifo {
 +
-s $ifofile < 2**20 or return 0;
 +
open(IFO, '<:raw', $ifofile) or return 0;
 +
local $/;
 +
$buffer = <IFO>;
 +
close(IFO);
 +
substr($buffer, 0, 12) eq 'DVDVIDEO-VTS' or return 0;
 +
return 1;
 +
}
 +
 
 +
sub index_dvd {
 +
#we don't actually index anything under unix but we still need to pick from the ripped dvd sources, write the start of the main project .avs and set some variables
 +
$maxaudiobr ||= 320000;
 +
 +
&out_cls_info($lang{DVD_INDEX_INFO_FILELIST});
 +
&echo("");
 +
&echo($lang{DVD_INDEX_WARNING});
 +
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
 +
@dvdfilemasksorig = @dvdfilemasks;
 +
foreach $mask (@dvdfilemasksorig) {
 +
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($lang{DVD_INDEX_NO_FOLDERS_WITH_DVD_FILES_FOUND});
 +
<STDIN>;
 +
exit 1;
 +
} else {
 +
while (($key, $value) = each(%gooddvddirs)) {
 +
&echo("${key}\n");
 +
}
 +
}
 +
 
 +
if (@dvdchoices) {
 +
map { $_ = "${dvdripto_parentdir}/$_" } @dvdchoices;
 +
} else {
 +
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,$lang{INVALID_INPUT});
 +
} else {
 +
for (split(" ")) {
 +
if (defined($gooddvddirs{$_})) {
 +
push(@dvdchoices,$gooddvddirs{$_});
 +
} else {
 +
push(@errormsgs,"$lang{INVALID_SELECTION}: ${_}");
 +
}
 +
}
 +
last if @dvdchoices > 0;
 +
}
 +
&out_error(@errormsgs);
 +
print $prompt;
 +
}
 +
}
 +
&echo("");
 +
 +
&out_info($lang{DVD_INDEX_NOW_INDEXING});
 +
#Start - AVS prep
 +
&rm("${projname}.avs") if -e "${projname}.avs";
 +
&echotofile("loadplugin(\"${dgmpgdec_dir}/DGDecode.dll\")\n",">","${projname}.avs") if $os eq 'windows';
 +
&echotofile("import(\"${anri_dir}/sda.avs\")\n",">>","${projname}.avs") if $os eq 'windows';
 +
&echotofile("import(\"${desktop}/${projname}/plugins.avs\")\n",">>","${projname}.avs") if $os eq 'windows';
 +
# End - AVS prep
 +
 +
$alignedsplice = '';
 +
foreach $dvdchoice (@dvdchoices) {
 +
foreach $mask (@dvdfilemasks) {
 +
$i = 1;
 +
foreach $mpegfile (glob("${dvdchoice}/$mask")) {
 +
#ignore bad files
 +
if (-s $mpegfile > 5000) {
 +
&echotofile($alignedsplice,">>","${projname}.avs");
 +
#split into basename and extension
 +
$mpegfile =~ m/^.*[\\\/]([^\\\/.]+)\.([^.]+)$/;
 +
if ($os eq 'windows') {
 +
# 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
 +
#print "\"${dgmpgdec_dir}/${dgindex}\" -IF=[${mpegfile}] -OF=[${projname}_${i}_${1}] -PREVIEW -exit";
 +
#print "\n";
 +
system("\"${dgmpgdec_dir}/${dgindex}\" -IF=[${mpegfile}] -OF=[${projname}_${i}_${1}] -PREVIEW -exit");
 +
#print "\"${dgmpgdec_dir}/${dgindex}\" -IF=[${mpegfile}] -OM=2 -OF=[${projname}_${i}_${1}] -AT=[infotemplate.avs] -exit";
 +
#print "\n";
 +
system("\"${dgmpgdec_dir}/${dgindex}\" -IF=[${mpegfile}] -OM=2 -OF=[${projname}_${i}_${1}] -AT=[infotemplate.avs] -exit");
 +
###FIXME why is this missing? (next line)
 +
#&mv("${dvdchoice}/${1}.log","${desktop}/${projname}/${projname}_${i}_${1}.log");
 +
### FIXME sorting problems if we have over 9 input files?
 +
for (glob("${projname}_${i}_*")) {
 +
#warn 'glob stuff '.$_;
 +
&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);
 +
}
 +
}
 +
} else { #unix
 +
&cp($mpegfile,"${desktop}/${projname}");
 +
&echotofile("MPEG2source(\"${1}.${2}\",upconv=1)\n",">>","${projname}.avs");
 +
### FIXME get $maxaudiobr?
 +
}
 +
# If there's more than one file to be joined, they must be appended together.
 +
$alignedsplice = "\\++\\\n";
 +
$i++;
 +
}
 +
}
 +
}
 +
}
 +
&echotofile("\n",">>","${projname}.avs");
 +
#warn 'copying '."${projname}.avs";
 +
&cp("${projname}.avs","${projname}.bak");
 
}
 
}
  
Line 1,258: Line 2,383:
 
# Encode video in OS-specific ways.
 
# Encode video in OS-specific ways.
 
############################################################################
 
############################################################################
 +
 +
sub pipe_prepare($$) {
 +
$basename = shift;
 +
$mode = shift;
 +
 +
$avs = "${basename}.pipe";
 +
#system("rm", $avs) if -e $avs;
 +
system("mkfifo", $avs) if !-e $avs;
 +
 +
open(AVS, "${basename}.avs"); #must be unix text when running sasami under unix ...
 +
@avs = <AVS>;
 +
close(AVS);
 +
@sources = ();
 +
@trims = ();
 +
$f = 1;
 +
for (@avs) {
 +
chomp;
 +
next if m/^#/;
 +
push(@sources,$1) if m/^.*MPEG2source\("([^"]+)".*$/i;
 +
push(@sources,$1) if m/^.*avisource\("([^"]+)".*$/i;
 +
push(@sources,$1) if m/^.*directshowsource\("([^"]+)".*$/i;
 +
$fieldorder = 1 if m/^AssumeTFF\(\)/i;
 +
$fieldorder = 0 if m/^AssumeBFF\(\)/i;
 +
$d = 1 if m/^global d1 = true/;
 +
$d = 4 if m/^global d1 = false/;
 +
$d = 4 if m/^separatefields\(\)$/i; #for sample extraction
 +
$f = $1 if m/changefps\(f1\/([0-9])\)/; #source file may have changefps() multiple times (maybe to simulate deprecated nicefps() for 32-bit denominator); we only remember the last one
 +
$deflicker = 1 if m/^nate_retard_bob_2/;
 +
$vhs = 1 if m/^nate_vhs_head_change_erase/;
 +
$onepixel = 1 if m/^nate_1_pixel_bob_fix/;
 +
$nes = 1 if m/^nate_nes$/;
 +
push(@trims,"$1,$2") if m/trim\(([0-9]+),([0-9]+)\)/;
 +
$gba = 1 if m/^nate_gba$/;
 +
$gb = 1 if m/^nate_gb$/;
 +
#$resize = 1 if m/^lanczos4resize\(/;
 +
#nate format
 +
$statidlines[0] = $1 if m/^statid1="""(.*)"""$/;
 +
$statidlines[1] = $1 if m/^statid2="""(.*)"""$/;
 +
$statidlines[2] = $1 if m/^statid3="""(.*)"""$/;
 +
#anri format
 +
(@statidlines) = ($1, $2, $3) if m/^statid=.*\(run,"([^"])","([^"])","([^"])"\)/;
 +
}
 +
die 'sasami: no sources detected in .avs!' if @sources == 0;
 +
return @sources if $mode eq 'sources';
 +
 +
open(JS, ">${basename}.js") or die "could not open ${basename}.js for writing";
 +
print JS '//AD  <- Needed to identify//'."\n\nvar app = new Avidemux();\n\n";
 +
for (my $i = 0 ; $i < @sources ; $i++) {
 +
print JS "app.forceUnpack();\n";
 +
if ($i == 0) {
 +
print JS "app.load(\"${desktop}/${projname}/${sources[$i]}\");\n";
 +
} else {
 +
print JS "app.append(\"${desktop}/${projname}/${sources[$i]}\");\n";
 +
}
 +
}
 +
 +
# @mencoderargslist = ();
 +
# #build mencoder command to feed fifo
 +
# if ($mode eq "video") {
 +
# $mencoderargs = "\"${anri_dir}/${mencoder}\" ${really_quiet}";
 +
# } elsif ($mode eq "audio") {
 +
# $mencoderargs = "\"${anri_dir}/${mplayer}\" ${really_quiet}";
 +
# }
 +
 +
print JS "\napp.clearSegments();\n" if (@trims);
 +
my $sourcenum = 0;
 +
my $previous_sourcelength = 0;
 +
my $this_sourcelength;
 +
foreach $source (@sources) {
 +
#get vital info about source
 +
my $mplayeridentify = <<SABRAC;
 +
"${anri_dir}/${mplayer}" -identify -vo null -slave ${source} 2>&1 <<ENDOFSCRIPT
 +
quit
 +
ENDOFSCRIPT
 +
SABRAC
 +
for (qx($mplayeridentify)) {
 +
chomp;
 +
$width = $_ if s/ID_VIDEO_WIDTH=([0-9]+)/$1/;
 +
$height = $_ if s/ID_VIDEO_HEIGHT=([0-9]+)/$1/;
 +
$framerate = $_ if s/ID_VIDEO_FPS=([0-9.]+)/$1/;
 +
$maxaudiobitrate = $_ if s/ID_AUDIO_BITRATE=([0-9]+)/$1/;
 +
$this_sourcelength = &round($framerate * $_) if s/ID_LENGTH=([0-9.]+)/$1/;
 +
}
 +
# print "$width\n";
 +
# print "$height\n";
 +
# print "$framerate\n";
 +
# print "$maxaudiobitrate\n";
 +
die "sasami: could not determine video width etc" if !$width;
 +
$pal = ($height eq "576");
 +
### FIXME moved from above the foreach source block because it depends on $pal being set - check only first source and then set?
 +
$newframerate = ($pal ? (50/$f) : (59.94/$f)); #required for trimming
 +
 +
#trimming
 +
# $framerate = 29.97;
 +
# $framerate = 25 if $pal;
 +
my $sourcelength = ($previous_sourcelength + $this_sourcelength);
 +
for (@trims) {
 +
if ($_) {
 +
#print "popped: $_\n";
 +
my $trimone = '';
 +
my $trimtwo = '';
 +
m/^(.*),(.*)$/;
 +
if ($1) {
 +
if ($1 < $sourcelength) {
 +
$trimone = ($1 - $previous_sourcelength);
 +
$trimtwo = ($this_sourcelength - $trimone + 1);
 +
}
 +
}
 +
if ($2) {
 +
if ($2 < $sourcelength) {
 +
$trimone = 0 if !$trimone;
 +
$trimtwo = ($2 - $previous_sourcelength - $trimone + 1);
 +
}
 +
}
 +
if (($trimone ne '') && ($trimtwo ne '')) {
 +
print JS "app.addSegment(${sourcenum},${trimone},${trimtwo});\n";
 +
$_ = ",";
 +
#keep second trim point in case we haven't reached it yet
 +
$_ .= $2 if $2 > $sourcelength;
 +
}
 +
}
 +
}
 +
$previous_sourcelength = $sourcelength;
 +
$sourcenum++;
 +
}
 +
print JS "\n";
 +
 +
# app.video.addFilter("crop","left=14","right=16","top=22","bottom=30");
 +
# app.video.addFilter("mpresize","w=320","h=240","algo=2");
 +
# app.video.addFilter("resamplefps","newfps=29970","use_linear=0");
 +
# app.video.addFilter("YADIF","mode=3","order=1");
 +
# app.video.addFilter("mcdeinterlace","mode=2","qp=1","initial_parity=0");
 +
# app.video.addFilter("msharpen","mask=0","highq=1","strength=100","threshold=15");
 +
# app.video.addFilter("addblack","left=0","right=0","top=0","bottom=2");
 +
#one pixel bob
 +
# if ($onepixel) {
 +
# app.video.addFilter("crop","left=0","right=0","top=1","bottom=0");
 +
# app.video.addFilter("addblack","left=0","right=0","top=0","bottom=1");
 +
# $mencoderargs .= " -vf-add crop=${width}:".($height-1).":0:0,expand=${width}:${height}:0:1";
 +
# $fieldorder = 0 if $fieldorder == 1;
 +
# $fieldorder = 1 if $fieldorder == 0;
 +
# }
 +
 +
if ($nes) {
 +
print JS '//nes'."\n";
 +
print JS 'app.video.addFilter("crop","left=8","right=0","top=0","bottom=0");'."\n";
 +
print JS 'app.video.addFilter("addblack","left=8","right=0","top=0","bottom=0");'."\n";
 +
print JS "\n";
 +
#$mencoderargs .= " -vf-add crop=".($width-8).":${height}:8:0,expand=${width}:${height}:8:0" if $nes;
 +
#-af channels=6:4:0:0:0:1:0:2:0:3 media.avi
 +
#Would change the number of channels to 6 and set up 4 routes that copy channel 0 to channels 0 to 3.  Channel 4 and 5 will contain silence.
 +
}
 +
 +
print JS 'app.video.addFilter("YADIF","mode=3","order='.$fieldorder.'");'."\n";
 +
print JS 'app.video.addFilter("mcdeinterlace","mode=2","qp=1","initial_parity='.$fieldorder.'");'."\n" if ($d == 1) && ($mode ne "audio"); #for some reason the deinterlacing filter breaks audio output
 +
#$mencoderargs .= " -vf-add yadif=3 -vf-add mcdeint=1:${fieldorder}" if $d == 1;
 +
#$tfields = 0;
 +
#$tfields = 4 if $deflicker;
 +
#$mencoderargs .= " -vf-add tfields=${tfields}" if $d == 4;
 +
 +
#i just eyeballed this - someone will need to sync the avisynth and mencoder sharpen filters
 +
#apparently avidemux doesn't need de-deflickering ...
 +
#print JS 'app.video.addFilter("msharpen","mask=0","highq=1","strength=100","threshold=15");'."\n" if $deflicker;
 +
#$mencoderargs .= " -vf-add unsharp=l3x3:0.6:c3x3:0.6" if $deflicker;
 +
 +
if ($vhs && ($mode eq "video")) {
 +
print JS '//vhs'."\n";
 +
print JS 'app.video.addFilter("crop","left=0","right=0","top=0","bottom=12");'."\n";
 +
print JS 'app.video.addFilter("addblack","left=0","right=0","top=0","bottom=12");'."\n";
 +
print JS "\n";
 +
#$mencoderargs .= " -vf-add crop=${width}:".($height-12).":0:0,expand=0:-12:0:0" if $vhs;
 +
}
 +
 +
if ($gba && ($mode eq "video")) {
 +
$gba_crop_left = 44 if !defined $gba_crop_left;
 +
$gba_crop_top = 40 if !defined $gba_crop_top;
 +
$gba_crop_right = 44 if !defined $gba_crop_right;
 +
$gba_crop_bottom = 40 if !defined $gba_crop_bottom;
 +
for my $x ($gba_crop_left, $gba_crop_top, $gba_crop_right, $gba_crop_bottom) { #avidemux is stuck in yv12
 +
$x = $x + ($x % 4);
 +
}
 +
print JS 'app.video.addFilter("mpresize","w=320","h=240","algo=2");'."\n";
 +
#$mencoderargs .= " -vf-add scale=320:240";
 +
print JS 'app.video.addFilter("crop","left='.$gba_crop_left.'","right='.$gba_crop_right.'","top='.$gba_crop_top.'","bottom='.$gba_crop_bottom.'");'."\n";
 +
#$mencoderargs .= " -vf-add crop=".(320-$gba_crop_right-$gba_crop_left).":".(240-$gba_crop_bottom-$gba_crop_top).":${gba_crop_left}:${gba_crop_top}";
 +
print JS 'app.video.addFilter("mpresize","w=240","h=160","algo=2");'."\n";
 +
#$mencoderargs .= " -vf-add scale=240:160";
 +
$newwidth = 240;
 +
$newheight = 160;
 +
} elsif ($gb && ($mode eq "video")) {
 +
$gb_crop_left = 80 if !defined $gb_crop_left;
 +
$gb_crop_top = 48 if !defined $gb_crop_top;
 +
$gb_crop_right = 80 if !defined $gb_crop_right;
 +
$gb_crop_bottom = 48 if !defined $gb_crop_bottom;
 +
print JS 'app.video.addFilter("mpresize","w=320","h=240","algo=2");'."\n";
 +
#$mencoderargs .= " -vf-add scale=320:240";
 +
print JS 'app.video.addFilter("crop","left='.$gb_crop_left.'","right='.$gb_crop_right.'","top='.$gb_crop_top.'","bottom='.$gb_crop_bottom.'");'."\n";
 +
#$mencoderargs .= " -vf-add crop=".(320-$gb_crop_right-$gb_crop_left).":".(240-$gb_crop_bottom-$gb_crop_top).":${gb_crop_left}:${gb_crop_top}";
 +
$newwidth = (320-$gb_crop_right-$gb_crop_left);
 +
$newheight = (240-$gb_crop_bottom-$gb_crop_top);
 +
}
 +
 +
$newwidth  = (($d == 1) ? ($pal ? 704 : 640) : ($pal ? 352 : 320)) unless $newwidth;
 +
$newheight = (($d == 1) ? ($pal ? 576 : 480) : ($pal ? 288 : 240)) unless $newheight;
 +
print JS 'app.video.addFilter("resamplefps","newfps='.($newframerate*1000).'","use_linear=0");'."\n";
 +
#$mencoderargs .= " -vf-add framestep=${f}";
 +
$x264newframerate = "--fps ${newframerate}";
 +
$x264outext = '264';
 +
$x264dimensions = "${newwidth}x${newheight}";
 +
$ampersand = '&';
 +
$mp4boxnewframerate = "-fps ${newframerate}";
 +
 +
print JS 'app.video.addFilter("mpresize","w='.$newwidth.'","h='.$newheight.'","algo=2");'."\n";
 +
#$mencoderargs .= " -vf-add scale=${newwidth}:${newheight}";# if $resize;
 +
 +
if ($mode eq "video") {
 +
print JS 'app.video.codec("YV12","CQ=1","0 ");'."\n";
 +
print JS 'app.audio.load("NONE","");'."\n";
 +
print JS 'app.setContainer("OGM");'."\n";
 +
print JS 'app.save("'."${desktop}/${projname}/avidemux.pipe".'");'."\n";
 +
} elsif ($mode eq "audio") {
 +
print JS 'app.audio.codec("none",128,0,"");'."\n";
 +
print JS 'app.save("/dev/null");'."\n"; #can someone tell me why this is required - get truncated audio with app.audio.save() otherwise
 +
print JS 'app.audio.save("'."${desktop}/${projname}/${avs}".'");'."\n";
 +
}
 +
print JS "\n".'setSuccess(1);'."\n".'app.Exit();'."\n";
 +
close(JS);
 +
 +
# my $sourcesplit = '"'.$source.'"';
 +
# my $littleo = "-o \"${avs}\"";
 +
# $littleo = "-ao pcm:file=\"${avs}\":fast" if $mode eq "audio";
 +
# if (@trimargsarr) {
 +
# my $mencoderargstemp = '';
 +
# while (my $trimargs = shift(@trimargsarr)) {
 +
# $mencoderargstemp .= $mencoderargs." ${sourcesplit}".$trimargs." ${littleo}\n";
 +
# }
 +
# $mencoderargs = $mencoderargstemp;
 +
# } else {
 +
# $mencoderargs .= " ${sourcesplit} ${littleo}\n";
 +
# }
 +
#
 +
# push(@mencoderargslist,$mencoderargs);
 +
 +
if (($statidlines[0]) || ($statidlines[1]) || ($statidlines[2])) {
 +
require Imager;
 +
$img = Imager->new;
 +
$img->read(file=>"ntsc_d1.tga") or die "Cannot load statid image: ", $img->errstr;
 +
$font = Imager::Font->new(file=>$path_to_verdana); #will need to be changed for non-mac unix ...
 +
&statid_lines_write($statidlines[0], $img->getheight/2, 36, 'white'  ) if $statidlines[0];
 +
&statid_lines_write($statidlines[1], 360,              36, 'white'  ) if $statidlines[1];
 +
&statid_lines_write($statidlines[2], 400,              36, 'white'  ) if $statidlines[2];
 +
&statid_lines_write("Audio commentary on track 2", 460, 28, '#E1CE8B') if $audio_commentary;
 +
$img->write(file=>'statid.tga')
 +
or die 'Cannot save statid.tga: ', $img->errstr;
 +
open(MF,">statid.txt") or die "Could not open statid.txt for appending!";
 +
for (1..5) { #once for each second of the statid
 +
for (1..$newframerate) { #once for each frame this second
 +
print MF "statid.tga\n";
 +
}
 +
}
 +
close(MF);
 +
if ($mode eq "video") {
 +
$statidmencoderargs = "\"${anri_dir}/${mencoder}\" ${really_quiet} -vf-add scale=${newwidth}:${newheight} -vf-add format=i420 -ovc raw -of rawvideo -nosound -ofps ${newframerate} mf://\@statid.txt -mf fps=${newframerate}:type=tga -o \"${avs}\"";
 +
} elsif ($mode eq "audio") {
 +
$statidmencoderargs = "\"${anri_dir}/${mplayer}\" \"silence_stereo_48000.wav\" -vc null -vo null -ao pcm:file=\"${avs}\":fast";
 +
}
 +
}
 +
}
 +
 +
sub pipe_write {
 +
print "opening ${avs} ...\n";
 +
# sleep 2;
 +
open(FIFO,">${avs}");
 +
# sleep 2;
 +
#<STDIN>;
 +
print("$statidmencoderargs\n") if (($statidlines[0]) || ($statidlines[1]) || ($statidlines[2]));
 +
system($statidmencoderargs) if (($statidlines[0]) || ($statidlines[1]) || ($statidlines[2]));
 +
if ($mode eq "video") {
 +
print "making avidemux.pipe ...\n";
 +
system("mkfifo", "avidemux.pipe");
 +
print "made avidemux.pipe\n";
 +
system("\"${anri_dir}/${mencoder}\" ${really_quiet} -vf-add format=i420 -ovc raw -of rawvideo -nosound -o \"${avs}\" avidemux.pipe &");
 +
}
 +
 +
#  use Dumpvalue;
 +
#  my $dumper = new Dumpvalue;
 +
#  $dumper->set(globPrint => 1);
 +
#  $dumper->dumpValue(\*::);
 +
#  $dumper->dumpvars('main');
 +
 +
print "sh \"${avidemux}\" --autoindex --run \"${desktop}/${projname}/${basename}.js\"\n";
 +
system("sh \"${avidemux}\" --autoindex --run \"${desktop}/${projname}/${basename}.js\""); #need the full path to the js for some reason
 +
&rm("avidemux.pipe") if $mode eq "video";
 +
print("$statidmencoderargs\n") if (($statidlines[0]) || ($statidlines[1]) || ($statidlines[2]));
 +
system($statidmencoderargs) if (($statidlines[0]) || ($statidlines[1]) || ($statidlines[2]));
 +
print "closing FIFO...\n";
 +
#<STDIN>;
 +
# sleep 2;
 +
close(FIFO);
 +
# sleep 2;
 +
}
 +
 +
#statid line text, y-offset, text size, color
 +
sub statid_lines_write {
 +
$font->align(string => $_[0],
 +
aa => 1,
 +
size => $_[2],
 +
color => $_[3],
 +
x => $img->getwidth/2,
 +
y => $_[1],
 +
halign => 'center',
 +
valign => 'center',
 +
image => $img);
 +
}
 +
 +
sub round {
 +
return int($_[0] + .5 * ($_[0] <=> 0));
 +
}
  
 
#input filename, output basename, output audio bitrate in baud, x264 minimum quantizer, delete tempfiles boolean
 
#input filename, output basename, output audio bitrate in baud, x264 minimum quantizer, delete tempfiles boolean
 
sub onepass {
 
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]}\"");
+
#VIDEO
system("\"${vdub_dir}/${vdubcli}\" \"${_[0]}\" /i \"${anri_dir}/audioout.vcf\" \"${_[1]}_temp.wav\"");
+
$x264newframerate = '';
system("\"${anri_dir}/${naac}\" -br ${_[2]} -lc -if \"${_[1]}_temp.wav\" -of \"${_[1]}_audio.mp4\"");
+
$x264outext = 'mp4';
system("\"${anri_dir}/${mp4box}\" -tmp . -new -add \"${_[1]}_video.mp4\" -add \"${_[1]}_audio.mp4\" \"${_[1]}.mp4\"");
+
$x264dimensions = '';
 +
$ampersand = '';
 +
$mp4boxnewframerate = '';
 +
if ($os eq 'windows') {
 +
$avs = $_[0].'.avs';
 +
} else {
 +
&pipe_prepare($_[0],"video");
 +
$avs = $_[0].'.pipe';
 +
}
 +
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 ${x264newframerate} --output \"${_[1]}_video.${x264outext}\" \"${avs}\" ${x264dimensions} ${ampersand}");
 +
print "x264 is going ...\n";
 +
&pipe_write if $os ne 'windows';
 +
print "pipe_write is going ...\n";
 +
system("rm", $avs) if $os ne 'windows';
 +
 
 +
#AUDIO
 +
$audioext = 'mp4';
 +
if ($os eq 'windows') {
 +
system("\"${vdub_dir}/${vdubcli}\" \"${avs}\" /i \"${anri_dir}/audioout.vcf\" \"${_[1]}_temp.wav\"");
 +
system("\"${anri_dir}/${naac}\" -br ${_[2]} -lc -if \"${_[1]}_temp.wav\" -of \"${_[1]}_audio.${audioext}\"");
 +
} else {
 +
&pipe_prepare($_[0],"audio");
 +
system("\"${anri_dir}/${mplayer}\" -dumpstream -dumpfile \"${_[1]}_avidemux.wav\" \"${avs}\" &");
 +
&pipe_write;
 +
system("rm", $avs) if $os ne 'windows';
 +
system("\"${anri_dir}/${mplayer}\" -demuxer rawaudio -rawaudio channels=2:rate=48000 -ao pcm:file=\"${_[1]}_temp.wav\":fast \"${_[1]}_avidemux.wav\"");
 +
if ($faac) {
 +
$audioext = 'aac';
 +
#thanks grenola
 +
$faacq = "-q 65 -c 8000"; #default is for mq/lq
 +
$faacq = "-b 128" if $_[2] ge "128000";
 +
$faacq = "-b 256" if $_[2] ge "256000";
 +
system("\"${faac}\" --mpeg-vers 4 ${faacq} -o \"${_[1]}_audio.${audioext}\" \"${_[1]}_temp.wav\"");
 +
} else { #afconvert's only going to work under os x
 +
system("\"${anri_dir}/${afconvert}\" -f mp4f -d 'aac ' -b ${_[2]} -s 1 -v \"${_[1]}_temp.wav\" \"${_[1]}_audio.${audioext}\"");
 +
}
 +
}
 +
 +
#MUX
 +
if ($os eq 'windows') {
 +
system("\"${anri_dir}/${mp4box}\" ${mp4boxnewframerate} -tmp . -new -add \"${_[1]}_video.${x264outext}\" -add \"${_[1]}_audio.${audioext}\" \"${_[1]}.mp4\"");
 +
} else {
 +
system("export DYLD_LIBRARY_PATH=\"${anri_dir}\";\"${anri_dir}/${mp4box}\" ${mp4boxnewframerate} -tmp . -new -add \"${_[1]}_video.${x264outext}\" -add \"${_[1]}_audio.${audioext}\" \"${_[1]}.mp4\"");
 +
}
 +
 +
#CLEANUP
 
if (${_[4]}) {
 
if (${_[4]}) {
 
@todel = (
 
@todel = (
"${_[1]}_video.mp4",
+
"${_[1]}_video.${x264outext}",
 
"${_[1]}_temp.wav",
 
"${_[1]}_temp.wav",
"${_[1]}_audio.mp4",
+
"${_[1]}_audio.${audioext}",
 
);
 
);
 
&rm(@todel);
 
&rm(@todel);
Line 1,277: Line 2,765:
 
#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
 
#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 {
 
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]}\"");
+
&x264(
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\"");
+
'--level 4.1 --bframes 3 --vbv-bufsize 9000 --vbv-maxrate 25000 --threads auto --thread-input --progress --no-psnr --analyse none --no-ssim',
system("\"${anri_dir}/${naac}\" -br ${_[3]} -lc -if \"${_[1]}_temp.wav\" -of \"${_[1]}_audio.mp4\"");
+
'--level 4.1 --bframes 3 --vbv-bufsize 9000 --vbv-maxrate 25000 --threads auto --thread-input --progress --no-psnr --ref 3 --mixed-refs --no-fast-pskip --b-rdo --bime --weightb --direct auto --subme 7 --trellis 2 --partitions p8x8,b8x8,i4x4,i8x8 --8x8dct --me umh'
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
 
#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 {
 
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]}");
+
&x264(
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\"");
+
'--vbv-bufsize 512 --vbv-maxrate 768 --level 1.3 --no-cabac --threads auto --thread-input --progress --no-psnr --analyse none --no-ssim',
system("\"${anri_dir}/${naac}\" -br ${_[3]} -lc -if \"${_[1]}_temp.wav\" -of \"${_[1]}_audio.mp4\"");
+
'--vbv-bufsize 512 --vbv-maxrate 768 --level 1.3 --no-cabac --threads auto --thread-input --progress --no-psnr --analyse all --no-fast-pskip --subme 7 --trellis 2 --me umh'
system("\"${anri_dir}/${mp4box}\" -tmp . -new -add \"${_[1]}_video.mp4\" -add \"${_[1]}_audio.mp4\" \"${_[1]}.mp4\"");
+
);
 +
}
 +
 
 +
#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, x264argsfirstpass, x264argssecondpass
 +
sub x264 {
 +
$x264args_pass2 = pop;
 +
$x264args_pass1 = pop;
 +
 
 +
#VIDEO
 +
$x264newframerate = '';
 +
$x264outext = 'mp4';
 +
$x264dimensions = '';
 +
$ampersand = '';
 +
$mp4boxnewframerate = '';
 +
if ($os eq 'windows') {
 +
$avs = $_[0].'.avs';
 +
} else {
 +
&pipe_prepare($_[0],"video");
 +
#$avs = $_[0].'.pipe'; #already set in pipe_prepare()
 +
}
 +
system("\"${anri_dir}/${x264}\" --pass 1 --bitrate ${_[2]} --stats \"${_[1]}.stats\" --qpmin ${_[4]} ${x264newframerate} ${x264args_pass1} --output ${nul} \"${avs}\" ${x264dimensions} ${ampersand}");
 +
&pipe_write if $os ne 'windows';
 +
#this is a hack to deal with the fact that sometimes x264 takes a while to finish encoding and write out the statsfile - thanks grenola!
 +
while (!(-e "${_[1]}.stats")) {
 +
print("Waiting for stats file ...\n");
 +
sleep(1);
 +
}
 +
system("\"${anri_dir}/${x264}\" --pass 2 --bitrate ${_[2]} --stats \"${_[1]}.stats\" --qpmin ${_[4]} ${x264newframerate} ${x264args_pass2} --output \"${_[1]}_video.${x264outext}\" \"${avs}\" ${x264dimensions} ${ampersand}");
 +
&pipe_write if $os ne 'windows';
 +
#system("rm", $avs) if $os ne 'windows';
 +
 +
#AUDIO
 +
$audioext = 'mp4';
 +
if ($os eq 'windows') {
 +
system("\"${vdub_dir}/${vdubcli}\" ${avs} /i \"${anri_dir}/audioout.vcf\" \"${_[1]}_temp.wav\"");
 +
system("\"${anri_dir}/${naac}\" -br ${_[3]} -lc -if \"${_[1]}_temp.wav\" -of \"${_[1]}_audio.${audioext}\"");
 +
} else {
 +
&pipe_prepare($_[0],"audio");
 +
print "starting \"${anri_dir}/${mplayer}\" -dumpstream -dumpfile \"${_[1]}_avidemux.wav\" \"${avs}\" &\n";
 +
#<STDIN>;
 +
system("\"${anri_dir}/${mplayer}\" -dumpstream -dumpfile \"${_[1]}_avidemux.wav\" \"${avs}\" &");
 +
print "started, starting pipe_write ...\n";
 +
#<STDIN>;
 +
&pipe_write;
 +
print "pipe_write done ...\n";
 +
#<STDIN>;
 +
#system("rm", $avs) if $os ne 'windows'; #fixme 20090430
 +
print "starting mplayer ...\n";
 +
#<STDIN>;
 +
system("\"${anri_dir}/${mplayer}\" -demuxer rawaudio -rawaudio channels=2:rate=48000 -ao pcm:file=\"${_[1]}_temp.wav\":fast \"${_[1]}_avidemux.wav\"");
 +
print "done\n";
 +
#<STDIN>;
 +
if ($faac) {
 +
$audioext = 'aac';
 +
#thanks grenola
 +
$faacq = "-q 65 -c 8000"; #default is for mq/lq
 +
$faacq = "-b 128" if $_[3] ge "128000";
 +
$faacq = "-b 256" if $_[3] ge "256000";
 +
system("\"${faac}\" --mpeg-vers 4 ${faacq} -o \"${_[1]}_audio.${audioext}\" \"${_[1]}_temp.wav\"");
 +
} else { #afconvert's only going to work under os x ...
 +
system("\"${anri_dir}/${afconvert}\" -f mp4f -d 'aac ' -b ${_[3]} -s 1 -v \"${_[1]}_temp.wav\" \"${_[1]}_audio.${audioext}\"");
 +
}
 +
}
 +
 
 +
if ($os eq 'windows') {
 +
system("\"${anri_dir}/${mp4box}\" ${mp4boxnewframerate} -tmp . -new -add \"${_[1]}_video.${x264outext}\" -add \"${_[1]}_audio.${audioext}\" \"${_[1]}.mp4\"");
 +
} else {
 +
system("export DYLD_LIBRARY_PATH=\"${anri_dir}\";\"${anri_dir}/${mp4box}\" ${mp4boxnewframerate} -tmp . -new -add \"${_[1]}_video.${x264outext}\" -add \"${_[1]}_audio.${audioext}\" \"${_[1]}.mp4\"");
 +
}
 +
 +
#CLEANUP
 
if (${_[5]}) {
 
if (${_[5]}) {
 
@todel = (
 
@todel = (
Line 1,313: Line 2,857:
 
if (${_[6]}) {
 
if (${_[6]}) {
 
@todel = (
 
@todel = (
"${_[1]}_video.mp4",
+
"${_[1]}_video.${x264outext}",
"${_[1]}_temp.wav",
+
# "${_[1]}_temp.wav",
"${_[1]}_audio.mp4",
+
"${_[1]}_audio.${audioext}",
 
);
 
);
 
&rm(@todel);
 
&rm(@todel);
Line 1,323: Line 2,867:
 
#input filename, output basename, video output bitrate in kbaud, output audio bitrate in baud, empty, delete 2pass statsfile boolean, delete all other tempfiles boolean
 
#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 {
 
sub xvid {
system("\"${anri_dir}/${xvid}\" -i \"${_[0]}\" -bitrate ${_[2]} -pass1 \"${_[1]}.stats\"");
+
$avs = $_[0].'.avs';
system("\"${anri_dir}/${xvid}\" -i \"${_[0]}\" -bitrate ${_[2]} -pass2 \"${_[1]}.stats\" -avi \"${_[1]}v.avi\"");
+
system("\"${anri_dir}/${xvid}\" -i \"${avs}\" -bitrate ${_[2]} -pass1 \"${_[1]}.stats\" -progress");
system("\"${anri_dir}/${ffmpeg}\" -b ".($_[3]/1000)." -ac 2 -acodec mp3 -y -i \"${_[1]}v.avi\" -vcodec copy -i \"${_[0]}\" \"${_[1]}.avi\"");
+
system("\"${anri_dir}/${xvid}\" -i \"${avs}\" -bitrate ${_[2]} -pass2 \"${_[1]}.stats\" -progress -avi \"${_[1]}v.avi\"");
 +
system("\"${anri_dir}/${ffmpeg}\" -ab ${_[3]} -ac 2 -acodec mp3 -y -i \"${_[1]}v.avi\" -vcodec copy -i \"${avs}\" \"${_[1]}.avi\"");
 
if (${_[5]}) {
 
if (${_[5]}) {
 
@todel = (
 
@todel = (
Line 1,337: Line 2,882:
 
);
 
);
 
&rm(@todel);
 
&rm(@todel);
 +
}
 +
}
 +
 +
############################################################################
 +
# Progress bar package, self explanatory
 +
############################################################################
 +
{
 +
package PBar;
 +
use Class::Struct length => '$', portion => '$', max_num => '$';
 +
use List::Util qw( min );
 +
  use File::stat;
 +
 +
# writes the bar based on the int argument given.
 +
sub write_bar {
 +
local $| = 1;
 +
my ($self, $x, $max_num) = @_;
 +
$max_num ||= $self->max_num;
 +
my $old = $self->portion || 0;
 +
my $new_p = int( $self->length * $x / $max_num + 0.5 );
 +
       
 +
print "\b" x( 6 + $self->length
 +
                      - min( $new_p, $old ) )
 +
if defined $self->portion;
 +
       
 +
print "="  x( $new_p - $old ),
 +
            " "  x ( $self->length - $new_p ),
 +
sprintf " %3d%% ", int( 100 * $x / $max_num + 0.5 );
 +
$self->portion( $new_p );
 +
}
 +
 +
# Gets a set of files size based on the folder and ext given.
 +
# takes two args
 +
# arg1 = folder name containing files
 +
# arg2 = extension to use example: vob
 +
# returns the size in bytes
 +
sub get_folder_size{
 +
my ($self,$dir, $ext) = @_;
 +
my $count = 0;
 +
opendir(DIR,$dir);
 +
my @dir = readdir(DIR);
 +
close DIR;
 +
foreach(@dir){
 +
if(m/^([^.]+)\.$ext$/) {
 +
$count=$count+(stat($dir."/".$_)->size);
 +
}
 +
}
 +
return $count;
 +
        }
 +
 +
# use two integer values as args to be compared
 +
# arg1= new file being made/copied
 +
# arg2 = file to compare to
 +
# returns a number as a percent left to be copied.
 +
sub compare_file_sizes{
 +
my $percent_left = 100;
 +
my ($self,$new_filesize, $old_filesize) = @_;
 +
if($new_filesize<$old_filesize){
 +
$percent_left = int(($new_filesize*100)/$old_filesize + .5);
 +
}else{
 +
$percent_left=100;
 +
}
 +
return $percent_left;
 +
}
 +
1;
 +
}
 +
 +
############################################################################
 +
# Stand alone progress bar function
 +
# 8 Arguments needed
 +
# arg1 = new folder name
 +
# arg2 = old folder/files name being copied
 +
# arg3 = Files extension you want to use to compare(new files)
 +
# arg4 = Files extension you want to use to compare(old files)
 +
# arg5 = number of seconds to wait between checks
 +
# arg6 = Message at start you want to say to user
 +
# arg7 = Message at end you want to say to user
 +
# arg8 = number of bars in progress bar
 +
#
 +
############################################################################
 +
sub progress_bar{
 +
# Create new bar
 +
my $pb = PBar->new( length => $_[7], max_num => 100 );
 +
print "$_[5]\n";
 +
$j=0;
 +
$i=0;
 +
$old_folder_size = $pb->get_folder_size($_[1],$_[4]);
 +
for($i=0; $i<1;){
 +
$j=$pb->compare_file_sizes($pb->get_folder_size($_[0],$_[3]),$old_folder_size);
 +
$pb->write_bar($j);
 +
if($end_bar){
 +
$i=1;
 +
}elsif($j<101){
 +
sleep $_[2];
 +
}else{
 +
$i=1;
 +
}
 +
}
 +
print "\n";
 +
print "$_[6]\n";
 +
}
 +
 +
#give a string and it checks for "\" and removes it.
 +
sub chopper{
 +
if(${os} eq 'windows'){
 +
return $_[0];
 +
}else{
 +
my $string=$_[0];
 +
my $tmp="";
 +
my $i=length(${string})+1;
 +
my $not_chopped="";
 +
for(; ${i}>0;${i}--){
 +
${tmp}=chop(${string});
 +
if(${tmp} ne '\\'){
 +
${not_chopped}="${tmp}${not_chopped}";
 +
}
 +
}
 +
return ${not_chopped};
 
}
 
}
 
}
 
}
 
</nowiki></pre>
 
</nowiki></pre>

Latest revision as of 14:31, 13 September 2009

#!/usr/bin/perl

############################################################################
#                               Credits
#
# nathan jahnke <njahnke@gmail.com>
# Ian Bennett
# Philip "ballofsnow" Cornell
# Brett "Psonar" Ables
# Karol "dex" Urbanski
#
# 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;
use Getopt::Long qw(:config bundling);
use File::Find;
use File::Basename;
use File::Spec;
use threads;
use threads::shared;

#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";

#default
$language = "english";

#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 ...
	require Win32;
	
	#get the name of the work directory. this is the desktop by default under windows
	$desktop = Win32::GetFolderPath(Win32::CSIDL_DESKTOPDIRECTORY());
	
	#get the path to program files so we can build the anri program directory
	$programfiles = Win32::GetFolderPath(Win32::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
	$mplayer = "mplayer.exe";
	$wget = "wget.exe";

	#dunno about this
	$dvdripto_parentdir = "C:\\AnriMPEG";
	
	#goes after a drive letter
	$colon = ':';
	
	#black hole
	$nul = 'NUL';
	
	#to start programs/open urls
	$start = "START";

	#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}';
	$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 { #we're on unix
      $desktop = glob("~/Desktop");
	#os-dependent path to verdana stuff
	if ("$^O" eq "darwin") {
		$path_to_verdana = "/Library/Fonts/Verdana.ttf";
	} else {
		### FIXME NON-MAC UNIX PATH TO VERDANA
	}
	
	#anri program directory
      $anri_dir = File::Spec->rel2abs(dirname($0));
	
	#our encoders - invocation names only - path will be prepended later ...
	$x264 = 'bin/x264';
	$afconvert = 'bin/afconvert';
	#for mp4box
#	print "export DYLD_LIBRARY_PATH=${anri_dir}\n";
	$mp4box = 'bin/mp4box';
	$ffmpeg = 'bin/ffmpeg';
	
	#some anri support files
	$avidemux = $anri_dir.'/avidemux2_qt4.app/Contents/Resources/script'; #gui - for debugging
	$avidemux = $anri_dir.'/avidemux2_qt4.app/Contents/Resources/avi_cli';
	$mplayer = "bin/mplayer";
	$mencoder = "bin/mencoder";
	$really_quiet = "-really-quiet"; #for mencoder
	$wget = "bin/wget";

	#dunno about this
	$dvdripto_parentdir = "${anri_dir}/dvdripto"; ### FIXME
	
	#not needed under unix
	$colon = '';
	
	#black hole
	$nul = '/dev/null';

	#to start programs/open urls
	$start = "open";

	#color initialization
	require Term::ANSIColor;
	import Term::ANSIColor qw(color);
	$cecho = "echo";
	
	#fewer colors to choose from than under windows if we want to maintain portability ...
	$black_on_gray = color("black on_white");
	$gray_on_black = color("white on_black");
	$white_on_black = color("white on_black");
	$aqua_on_black = color("green on_black");
	$blue_on_black = color("blue on_black");
	$teal_on_gray = color("green on_white");
	$navy_on_gray = color("blue on_white");
	$maroon_on_gray = color("magenta on_white");
	$maroon_on_silver = color("magenta on_white");
	$white_on_gray = color("white on_black");
	$red_on_gray = color("red on_white");
	
	$reset_color = "\"${cecho}\" ".color("reset");
	
	#os-specific commands
	$clear = "clear";
}

#make sure we can find anri's libs
push @INC, $anri_dir;

#progress bar helper stuff
$mplayer_loop_thread=0;
$end_bar=0;

#load only if command line arguments are specified
&load_cli if @ARGV;

########################################################################################
#					CLI and config handling
# 
# This subroutine deals with the config/cli loading. Only fired up when command line args
# are specified, since you have to load the config that way.
#
# Not very well tested, so expect changes here.
#
# Things still to do: some error checking, it's not going to be hard to make but I want 
# to do that only after extensive testing.
# The qualities arg is glitchy when not lowercase, and lc() craps out. Probably gonna use
# td to deal with that later.
# Some cleanup is in order too.
#
########################################################################################

sub load_cli {
	#initialising some variables to avoid errors/enforce better behaviour
	$nes=0;
	$gb=0;
	$gba=0;
	$prog=0;
	$fieldorder=1; #this defaults to the top screen in the user test in manual mode
	$vhs=0;
	$onepixel=0;
	$deflicker=0;
	$make_nmf=0;
	$statid=0;
	$gb_crop='';
	$gba_crop='';
	$spec='';
	$rip_a_dvd='';
	$help=0;
	#load all args, some as string, some as int, some as boolean
	#all variables are temporary in order to enforce cli precedence over config
	GetOptions ('config|c=s' => \$config_file ,
		'statid1|1=s' => \$statidline1,
		'statid2|2=s' => \$statidline2,
		'statid3|3=s' => \$statidline3,
		'statid_lines|s=s' => \$statid_lines,
		'spec|S=s' => \$spec,
		'trim|t=s' => \$trim_arg ,
		'rip|r=s' => \$rip_a_dvd,
		'gb_crop|p=s' => \$gb_crop,
		'gba_crop|P=s' => \$gba_crop,
		'language|l=s' => \$lang,
		'qualities|q=s' => \$qual,
		'projectname|n=s' => \$project_name,
		'avidir|d=s' => \$avidirectory,
		'avifile|f=s' => \@avi_files,
		'dvdsource|D=s' => \$dvd_source,
		'sample_extraction|x=i' => \$start_frame,
		'database' => \$data_dfnd,
		'gb|g' => \$gb_source,
		'gba|G' => \$gba_source,
		'nes|N' => \$nes_source,
		'vhs|v' => \$vhs_source,
		'deflickered|F' => \$dflckrd,
		'progressive|R' => \$progressive_source,
		'field_order|L' => \$order_of_fields,
		'pixelbob|b' => \$pixel_bobbing,
		'nmf|m' => \$create_nmf,
		'no_statid|o' => \$nostatid,
		'no_trim|i'   => \$notrim,
		'maxaudbitrate|a=i' => \$maximal_bitrate,
		'pcgame|C' => \$is_pc,
		'quietmen|Q' => \$mencoder_quiet,
		'help|h' => \$help
	);
	#language
	$language=$lang if $lang;
	#if asked for help, print and exit
	if($help){
		#has to be added to load the help...
		require 'lang_english.pl';
		require "lang_${language}.pl" if $language ne "english";
		#clear print used because the other functions don't recognise \n, something to FIXME
		&out_cls;
		print $lang{COMMAND_LINE_HELP};	
		exit 0;
	}
	#load config if one specified
	&load_config($config_file) if $config_file;
	#qualities
	#can be provided in binary or decimal or as a string:
	#string: mq,lq,mqavi etc.
	#binary: 0b[7 digit binary number]. First digit corresponds to xq, second to iq, third to hq, fourth to mq, 
	#        fifth to lq, sixth to mqavi and seventh to lqavi. For instance, 0b1001000 will encode XQ and MQ.
	#decimal: [number from 1 to 127]. Add the values of these to get the qualities to encode: xq - 64, iq - 32, 
	#        hq - 16, mq - 8, lq - 4, mqavi - 2, lqavi - 1. For example, 72 will encode XQ and MQ.
	if($qual=~m/0b([10]{7})/){
		$qual=unpack("N", pack("B32", substr("0" x 32 . $1, -32)));
	}
	if($qual=~m/\d+/){
		@temp_qual_to_enc = qw(xq iq hq mq lq mqavi lqavi);
		$temp_for_qual = 64;
		while($qual){
			$temp_quality = shift(@temp_qual_to_enc);
			if($qual-$temp_for_qual>=0){
				push(@encodethese, $temp_quality);
				$qual-=$temp_for_qual;
			}
			$temp_for_qual>>=1;
		}
		
	} elsif($qual) {
		@encodethese=split (',',$qual);
	}
	#trim
	@trimarr=split(',', $trim_arg) if $trim_arg; 
	$trim=1 if @trimarr;
	$trim=0 if $notrim;
	#avis
	push(@avifiles,@avi_files);
	#statid
	@statidlines=split(',',$statid_lines) if $statid_lines;
	$statidlines[0] = $statidline1 if $statidline1;
	$statidlines[1] = $statidline2 if $statidline2;
	$statidlines[2] = $statidline3 if $statidline3;
	$statid=1 if @statidlines;
	$statid=0 if $nostatid;
	#project name
	$projname=$project_name if $project_name;
	#sample extraction
	$startframe=$start_frame if $start_frame;
	$isPCGAME=$is_pc if $is_pc;
	#avidir
	$avidir=$avidirectory if $avidirectory;
	#dvd dirs
	@dvdchoices=split (',',$dvd_source) if $dvd_source;
	$dvdsource=1 if $dvd_source;
	#source stuff
	$nes=$nes_source if $nes_source;
	$deflicker=$dflckrd if $dflckrd;
	$prog=$progressive_source if $progressive_source;
	$make_nmf=$create_nmf if $create_nmf;
	$onepixel=$pixel_bobbing if $pixel_bobbing;
	$vhs=$vhs_source if $vhs_source;
	$fieldorder=0 if $order_of_fields;
	$maxaudiobitrate=$maximal_bitrate if $maximal_bitrate;
	#quiet mode
	$really_quiet = "-really-quiet" if $mencoder_quiet;
	#gb and gba stuff
	if($gba_crop=~m/(.+),(.+),(.+),(.+)/){
		$gba_crop_left = $1;
		$gba_crop_top = $2;
		$gba_crop_right = $3;
		$gba_crop_bottom = $4;
	}
	if($gb_crop=~m/(.+),(.+),(.+),(.+)/){
		$gb_crop_left = $1;
		$gb_crop_top = $2;
		$gb_crop_right = $3;
		$gb_crop_bottom = $4;
	}
	$gba=1 if $gba_source || $gba_crop_left;
	$gb=1 if $gb_source || $gb_crop_left;
	#d, f, dimensions
	if($spec=~m/d(.)f(.)(.)d/i){
		$d=$1;
		$f=$2;
		if($3==2){
			$twod=1;
		} else {
			$twod=0;
		}
	}
	if($d && $f){
		$dfnd_set=1;
		$dfnd=0;
	}
	$dfnd=$data_dfnd;
	#rippin'
	if($rip_a_dvd=~m/(.+):(.+)/){
		$driveletter=$1;
		$dvdripto=$2;
		$rip=1;
	}
	$dvdsource=0 if $avidir || @avifiles;
	#auto mode if possible
	if( ((@avifiles || $avidir || $dvdsource ) && ($isPCGAME || $dvdsource)) || $rip ) {
		$auto = 1;
	}
	#choosing menu choices automagically
	@menuchoices=(2) if @avifiles;
	@menuchoices=(2) if $dvdsource;
	@menuchoices=(2) if $avidir;
	@menuchoices=(3) if $startframe;
	@menuchoices=(1) if $rip;
}
###############################################################
#                Config loading
#
# This just loads the config. No rocket science here.
#
###############################################################
sub load_config {
	open(CONFIG,$_[0]) if -e $_[0];
	while(<CONFIG>){
		if (m/^\#/)					{ next; } #this is a comment line
		if (m/^statid(\d)=(.+)/i)		{ $statidlines[$1-1] = ($2); next; } #statid
		if (m/^statid_lines=(.+)/i)		{ @statidlines=split(',',$1); next; } #statid
		if (m/^no_statid=1/i)			{ $statid=0; next; } #force no statid mode
		if (m/^spec=d(.)f(.)(.)d/i)		{ $d=$1; $f=$2; $3==2 ? $twod=1 : $twod=0; next; } #d,f, dim
		if (m/^rip=(.+):(.+)/i)			{ $driveletter=$1; $dvdripto=$2; $rip=1; next; } #ripping mode
		if (m/^quietmen=1/i)			{ $really_quiet = "-really-quiet"; next; } #quiet mencoder
		if (m/^pcgame=1/i)			{ $isPCGAME = 1; next; } #PC game
		if (m/^trim=(.+)/i)			{ @trimarr=split (',',$1); next; } #trimming
		if (m/^no_trim=1/i)			{ $notrim=1; next; } #force no trimming mode
		if (m/^nmf=1/i)				{ $make_nmf=1; next; } #create nmf
		if (m/^progressive=1/i)			{ $prog=1; next; } #progressive source
		if (m/^pixelbob=1/i)			{ $onepixel=1; next; } #one pixel bob
		if (m/^field_order=(\d)/i)		{ $fieldorder=$1; next; } #field order
		if (m/^gba=1/i)				{ $gba=1; next; } #gba source
		if (m/^gb=1/i)				{ $gb=1; next; } #gb source 
		if (m/^vhs=1/i)				{ $vhs=1; next; } #vhs source
		if (m/^nes=1/i)				{ $nes=1; next; } #nes source
		if (m/^database=1/i)			{ $dfnd=1; next; } #use database <useless really>
		if (m/^deflickered=1/i)			{ $deflicker=1; next; } #deflickered source
		if (m/^projectname=(.+)/i)		{ $projname=$1; next; } #name of the project
		if (m/^language=(.+)/i)			{ $language=$1; next; } #language
		if (m/^sample_extraction=(\d)/i)	{ $startframe=$1; next; } #sample extract mode
		if (m/gba_crop=(.+),(.+),(.+),(.+)/i){ $gba_crop_left = $1; $gba_crop_top = $2; $gba_crop_right = $3; $gba_crop_bottom = $4; next; } #gba cropping
		if (m/gb_crop=(.+),(.+),(.+),(.+)/i){ $gb_crop_left = $1; $gb_crop_top = $2; $gb_crop_right = $3; $gb_crop_bottom = $4; next; } #gb cropping
		if (m/dvdsource=(.+)/i) 		{ @dvdchoices=split(',',$1); $dvdsource=1; next; } #dvd source
		if (m/avidir=(.+)/i)			{ $avidir=$1; next; } #avi directory
		if (m/avifile=(.+)/i)			{ push(@avifiles,$1); next; } #avisource(s)
		if (m/qualities=(.+)/i)			{ @encodethese=split (',',$1); } #qualities to encode
	}
	close CONFIG;
	#require $_[0] if -e $_[0];
}


#load config file
#require 'config.ini' if -e 'config.ini';

#localization
require 'lang_english.pl';
#after having loaded english, load preferred language by using $language variable from config file, would be cool if we could set this in the installer
require "lang_${language}.pl" if $language ne "english";

#FIXME LOGFILE STUFF

#main menu

#FIXME: using_settings

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

&out_cls;
@mainmenu = (
	[$lang{MAINMENU_RIPDVD}, 		'&rip_dvd'],
	[$lang{MAINMENU_STARTNEWPROJECT}, 	'&project'],
	[$lang{MAINMENU_EXTRACTSAMPLE}, 	'&proc_sample'],
	[$lang{MAINMENU_STATIDPREVIEW}, 	'&statid_sample'],
	[$lang{MAINMENU_AUDIOCOMMENTARY}, 	'&audio_commentary'],
	[$lang{MAINMENU_EXIT}, 			'exit 0'],
);
$number_of_menu_choices = scalar @mainmenu;
while (1) {
	if (@menuchoices) {
		eval($mainmenu[shift(@menuchoices)-1][1]);
	} else {
		&out_cls;
		&out_info($lang{PROGRAM_START});
		&out_section($lang{MAINMENU});
		&out_menu(@mainmenu);
		while (<STDIN>) {
			chomp;
			if (m/([1-${number_of_menu_choices}])$/) {
				#execute the contents of this value in the array
				eval($mainmenu[$1-1][1]);
				last;
			}
			print "$lang{INVALID_INPUT}\n\n";
			&out_menu(@mainmenu);
		}
	}
	if($auto){
		exit 0;
	}
}

############################################################################
#                         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 if $os eq 'windows';
	&out_cls_section($lang{SECTION_SAMPLE_EXTRACTION});
	q_boo($lang{QUESTION_DVDMPEG_SOURCE}, $dvdsource);
	$dvdsource ? &index_dvd : &q_avi;
	&cp("${projname}.avs","${projname}_trimtemp.avs");
	&echotofile("lanczos4resize(320,240)\n",">>","${projname}_trimtemp.avs");
	if (! defined $startframe) {
		&out_info($lang{INFO_SAMPLE_LENGTH});
		&echo("");
		&out_info($lang{PRESS_ENTER_TO_CONTINUE});
		<STDIN>;
		if ($os eq 'windows') {
			system("${start} \"trimming vdub\" \"${vdub_dir}/${vdubgui}\" \"${projname}_trimtemp.avs\"");
		} else {
			@sources = &pipe_prepare($projname, "sources");
			$avidemuxarg = " --load";
			for (@sources) {
				$avidemuxargs .= "${avidemuxarg} \"${desktop}/anri_sample/${_}\"";
				$avidemuxarg = " --append";
			}
			#system("sh \"${avidemux}\" --autoindex ${avidemuxargs} &");
		}
		print $prompt;
		while (<STDIN>) {
			chomp;
			if (m/^[0-9]+$/) {
				$startframe = $_;
				last;
			}
			print "$lang{INVALID_INPUT}\n\n";
			print $prompt;
		}
	}
	if ($os ne 'windows') {
		### remove .idx files
	}
	&echotofile("trim(${startframe},".($startframe+299).")\n",">>","${projname}.avs");
	&echotofile("AssumeTFF()\nSeparateFields()\nconverttoyv12\n",">>","${projname}.avs");
	&onepass("${desktop}/${projname}/${projname}","${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}$lang{SAMPLE_EXTRACTION_DONE}");
	&echo("\n$lang{SAMPLE_EXTRACTION_README}");
	system($reset_color);
	<STDIN>;
	exit 0;
}



sub audio_commentary {
	&out_cls_section($lang{SECTION_AUDIO_COMMENTARY});
	&echo("");
	
	&out_info($lang{COMMENTARY_AUDIO_PATH_TO});
	&echo("");
	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=$lang{COMMENTARY_BAD_INPUT};
		} elsif (!m/.*\.wav$/i) {
			$errormsg=$lang{COMMENTARY_NOT_WAV};
		} elsif (! -e $_) {
			$errormsg=$lang{FILE_NOT_FOUND};
		} else {
			$audio_commentary_path = $_;
			&out_info($lang{COMMENTARY_AUDIO_LOADED_SUCCESSFULLY});
			&echo("");
			last;
		}
		&out_error($errormsg);
		print $prompt;
	}
	
	&out_info($lang{COMMENTARY_VIDEO_PATH_TO});
	&echo("");
	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=$lang{COMMENTARY_BAD_INPUT};
		} elsif (!m/.*\.mp4$/i) {
			$errormsg=$lang{COMMENTARY_NOT_MP4};
		} elsif (! -e $_) {
			$errormsg=$lang{FILE_NOT_FOUND};
		} else {
			$video_commentary_path = $_;
			&out_info($lang{COMMENTARY_VIDEO_LOADED_SUCCESSFULLY});
			&echo("");
			last;
		}
		&out_error($errormsg);
		print $prompt;
	}
	
	#BUILD PATH INFO
	@video_commentary_path_arr = split(/\\|\//,$video_commentary_path);
	$video_commentary_video = pop @video_commentary_path_arr;
	$video_commentary_video_base = $video_commentary_video;
	$video_commentary_video_base =~ s/\.mp4$//i;
	chdir(join('/',@video_commentary_path_arr)) or warn $!;
	
	#ENCODE AUDIO TO 32 KBIT AAC MP4
	if ($os eq 'windows') {
		if(system("\"${anri_dir}/${naac}\" -br 32000 -lc -if \"${audio_commentary_path}\" -of \"${video_commentary_video_base}_track3.mp4\"")) {
			&out_error($lang{ERROR_COULD_NOT_READ_COMMENTARY_WAV});
			system($reset_color);
			<STDIN>;
			exit 0;
		}
	} else {
		###FIXME UNIX
	}
		
	#MUX
	if ($os eq 'windows') {
		system("\"${anri_dir}/${mp4box}\" -single 1 \"${video_commentary_video}\"");
		system("\"${anri_dir}/${mp4box}\" -single 2 \"${video_commentary_video}\"");
		&mv("${video_commentary_video}","${video_commentary_video_base}.backup.mp4");
		system("\"${anri_dir}/${mp4box}\" -tmp . -new -add \"${video_commentary_video_base}_track1.mp4\" -add \"${video_commentary_video_base}_track2.mp4\" -add \"${video_commentary_video_base}_track3.mp4\" -disable 3 \"${video_commentary_video}\"");
		for my $track (1..3) {
			&rm("${video_commentary_video_base}_track${track}.mp4");
		}
	} else {
		#FIXME UNIX
		#system("export DYLD_LIBRARY_PATH=\"${anri_dir}\";\"${anri_dir}/${mp4box}\" ${mp4boxnewframerate} -tmp . -new -add \"${_[1]}_video.${x264outext}\" -add \"${_[1]}_audio.${audioext}\" \"${_[1]}.mp4\"");
	}
	
	
	
	
	&echo("\n\n${white_on_gray}$lang{AUDIO_COMMENTARY_DONE}");
	system($reset_color);
	<STDIN>;
	exit 0;
}




############################################################################
#                         Statid Sample
# 
# Statid preview mode shows users how their statid will look without having
# to encode anything.  A slimmed down version of the code from the main
# procedure and script_buildfiles is used.  The same temporary project
# name and directory from sample extraction mode are used and deleted.
# The user is sent back to the main menu but currently will need
# to enter the statid information again during the main script.
############################################################################

sub statid_sample {
	chdir($desktop);
	$projname = 'anri_sample';
	&make_projdir;
	&out_cls_section($lang{SECTION_STATID});
	&out_info($lang{STATID_ABOUT_EACH_LINE});
	if (!@statidlines) {
		foreach $i (1 .. 3) {
			&out_info($lang{STATID_LINE}." ${i}:");
			print $prompt;
			$statidline = <STDIN>;
			chomp($statidline);
			$statidline =~ s/"/"+chr(34)+"/g;
			push(@statidlines,$statidline);
			&echo("");
		}
	}
	&echotofile("global pal = false\n",">","${projname}.avs");
	&echotofile("import(\"${anri_dir}/sda.avs\")\n",">>","${projname}.avs");
	$projtemp  = "run = blankclip(width=640, height=480)";
	$projtemp .= "statid=nate_statid_d1(run,\"".$statidlines[0]."\",\"".$statidlines[1]."\",\"".$statidlines[2]."\",".($audio_commentary == 1 ? 1 : 0).").ConvertToRGB\n";
	$projtemp .= "statid = float(run.width) / run.height >= 4./3 ?\n";
	$projtemp .= "\\ statid.Lanczos4Resize(round(run.height*4./3),run.height).AddBorders(floor((run.width-round(run.height*4./3))/2.),0,ceil((run.width-round(run.height*4./3))/2.),0).ConvertToYv12 :\n";
	$projtemp .= "\\ statid.Lanczos4Resize(run.width,round(run.width*3./4)).AddBorders(0,floor((run.height-round(run.width*3./4))/2.),0,ceil((run.height-round(run.width*3./4))/2.)).ConvertToYv12\n";
	$projtemp .= "statid\n";
	&echotofile($projtemp,">>","${projname}.avs");
	system("\"${vdub_dir}/${vdubgui}\" \"${projname}.avs\"");
	chdir($desktop);
	&rm("${desktop}/${projname}");
}

############################################################################
#                             Main procedure
# 
# Anri'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($lang{PROGRAM_START});
	&out_section($lang{SECTION_PROJECT_SETUP});
	if (! defined $projname) {
		&out_info($lang{ENTER_PROJECT_NAME});
		&echo("");
		&echo("$lang{PROJECT_FILES_APPEAR_IN} ${navy_on_gray}${desktop}\\($lang{PROJECT_NAME})\n");
		system($reset_color);
		&echo("");
		print $prompt;
		while (<STDIN>) {
			chomp;
			if (!m/[% ]/) {
				$projname = $_;
				last;
			}
			print "$lang{PROJECT_NAME_ILLEGAL_CHARACTERS}\n\n";
			print $prompt;
		}
	}
	&make_projdir;
	&load_plugins if $os eq 'windows';
	#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
	# loads all AVI files alphabetically. There is currently no validation for
	# AVI files with different video properties.
	############################################################################
	
	&out_cls_section($lang{MOVIE_SOURCE});
	&out_info($lang{MOVIE_SOURCE_MPEG2_HINT});
	&echo("");
	#IF NOT "%auto%"=="y" CALL :q_dvdsource
	if (q_boo($lang{MPEG2_SOURCE_QUESTION}, $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($lang{SECTION_GAME_PROPERTIES});
	if ((!$dvdsource) and (!$auto)) {
		q_boo($lang{PC_GAME_QUESTION}, $isPCGAME);
	}
	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;
	} else {
		&q_dfnd if !$dfnd_set;
		if (!$dfnd_set) {
			&echo("");
			&out_info($lang{DF_EXPLAIN});
			&echo("");
			&out_info($lang{DF_FIND_AT_THIS_URL});
			&out_info($lang{DFND_URL});
			&echo("");
			&out_info($lang{DF_IF_NOT_FOUND_THEN_WHAT});
			&echo("");
			if (! defined $d) {
				&echo($lang{QUESTION_D});
				print $prompt;
				while (<STDIN>) {
					chomp;
					if (m/^[14]$/) {
						$d = $_;
						last;
					}
					print "$lang{INVALID_INPUT}\n\n";
					print $prompt;
				}
			}
			if (! defined $f) {
				&echo($lang{QUESTION_F});
				print $prompt;
				while (<STDIN>) {
					chomp;
					if (m/^[1-5]$/) {
						$f = $_;
						last;
					}
					print "$lang{INVALID_INPUT}\n\n";
					print $prompt;
				}
			}
			q_boo($lang{QUESTION_ND}, $twod) if ($f == 1);
			if (!$auto) {
				#:q_submit_dfnd
				&echo("");
				&out_info($lang{QUESTION_SUBMIT_DFND_WHY});
				&echo("");
				system($start, 'http://speeddemosarchive.com/forum/index.php?action=post;topic=6416.0') if q_boo($lang{QUESTION_SUBMIT_DFND});
				#: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($lang{SECTION_VIDEO_PROPERTIES});
		q_boo($lang{QUESTION_PROGRESSIVE_INTERLACED}, $prog);
		#IF "%prog%"=="y" GOTO proc_gameproperties_p2
		if($prog != 1){
	
			############################################################################
			# 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("");
			if (! defined $fieldorder) {
				&out_info($lang{FIELDORDER_VDUB_WINDOW_OPENS});
				&out_info($lang{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 "$lang{INVALID_INPUT}\n\n";
					print $prompt;
				}
				&out_info($lang{VDUB_WINDOW_CAN_CLOSE_NOW});
				&rm("${projname}_fieldordertemp.avs");
			}
			&echo("");

			#q_vhs
			q_boo($lang{QUESTION_VHS}, $vhs);

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

			q_boo($lang{QUESTION_1PIXEL_BOB}, $onepixel) if ($f != 2);

			q_boo($lang{QUESTION_NES}, $nes);
			#IF "%nes%"=="y" GOTO proc_gameproperties_p2

			q_boo($lang{QUESTION_GBA}, $gba);
			$deflicker=1 if $gba;
			#GOTO proc_gameproperties_p2

			q_boo($lang{QUESTION_GB}, $gb);
			$deflicker=1 if $gb;

			q_boo($lang{QUESTION_DEFLICKERED}, $deflicker) if ($f != 2);
		}
	} #end if($prog != 1)
	############################################################################
	# 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. If the frame range is like 50 to 30 an error is shown, same if a '-'
	# is inputted.
	# 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($lang{SECTION_CONTENT_PROPERTIES});
	if (! defined $trim) {
		&out_info($lang{INFO_TRIM});
		if (q_boo($lang{QUESTION_TRIM}, $trim)) {
			############################################################################
			# 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. Implemented basic checking if the frame range is valid.
			############################################################################
			&echo("");
			&out_info($lang{TRIM_VDUB_WINDOW_OPENS});
			&echo("");
			&out_info($lang{TRIM_MULTIPLE_RANGES});
			&out_info($lang{PRESS_ENTER_TO_CONTINUE});
			<STDIN>;
			&echo("");
			&cp("${projname}.bak","${projname}_trimtemp.avs");
			if ($isPCGAME) {
				&echotofile("Lanczos4Resize(320,round(last.height*(320.000/last.width)))\n",">>","${projname}_trimtemp.avs");
				&echotofile("last.height % 2 == 1 ? AddBorders(0,0,0,1) : NOP\n",">>","${projname}_trimtemp.avs");
				&echotofile("last\n",">>","${projname}_trimtemp.avs");
			} else {
				&echotofile("Lanczos4Resize(320,240)\n",">>","${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=$lang{TRIM_ILLEGAL_VALUE};
				} elsif (m/^n$/i) {
					if (@trimarr < 1) {
						&out_info($lang{TRIM_NO_VALUES_ENTERED});
						$trim=0;
						last;
					} elsif (@trimarr % 2) {
						&out_error($lang{TRIM_ODD_NUMBER_OF_FRAMES});
						@trimarr = ();
					} else {
						&out_info($lang{TRIM_DONE});
						last;
					}
				} elsif (!m/^[0-9]+$/i) {
					$errormsg=$lang{TRIM_INVALID_INPUT_MUST_BE_FRAME_NUMBER};
				} elsif ((@trimarr % 2) && ($trimarr[@trimarr-1] > $_)) {
					$errormsg=$lang{TRIM_INVALID_RANGE};
				} else {
					push(@trimarr,$_);
					&out_info($lang{TRIM_POINT_LOADED_SUCCESSFULLY}.' #'.@trimarr);
					&echo("");
					print $prompt;
					next;
				}
				&out_error($errormsg);
				print $prompt;
			}
			&rm("${projname}_trimtemp.avs");
		}
	}
	
	if (! defined $statid) {
		&out_cls_section($lang{SECTION_STATID});
		&out_info($lang{STATID_INFO});
		if (q_boo($lang{QUESTION_STATID}, $statid)) {
			q_boo($lang{QUESTION_AUDIOCOMMENTARY}, $audio_commentary) if ! defined $audio_commentary;
			@statidlines = ();
			&out_info($lang{STATID_ABOUT_EACH_LINE});
			for (my $i = 1 ; $i <= 3 ; $i++) {
				&out_info($lang{STATID_LINE}." ${i}:");
				print $prompt;
				$statidline = <STDIN>;
				chomp($statidline);
				$statidline =~ s/"/"+chr(34)+"/g;
				push(@statidlines,$statidline);
				&echo("");
			}
		} else {
			@statidlines = ('','','');
		}
	}

	############################################################################
	# 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
	chdir("${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($lang{SECTION_READY_TO_ENCODE});
	&out_info("$lang{SETTINGS_SAVED_TO_FILE} \"${projname}_job.bat\".");

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

	if ($auto or q_boo($lang{QUESTION_ENCODE_NOW_OR})) {
	
		#: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/XQ, and Xvid LQ/MQ.
		# 
		# IF D1 and the user is encoding HQ/IQ/XQ, they will be asked whether
		# they want 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.
		############################################################################
	
		&out_cls_section($lang{SECTION_ENCODING_OPTIONS});
		%qualities = (
				#makethisboolean, howtomake, english, id tag, video bitrate in kbaud, audio bitrate in baud, minimum quantizer for x264, delete 2pass stats, delete all other tempfiles
				#			0		1			2		3	4	5		6	7 8
			lq    => [			1,	\&twopass,	"Low quality H.264 MP4",	"_LQ",	128,	64000,		17,	1,1],
			mq    => [			1,	\&ipod,		"Medium quality H.264 MP4",	"",	512,	64000,		17,	1,1],
			hq    => [			1,	\&twopass,	"High quality H.264 MP4",	"_HQ",	2048,	128000,		$hqq,	1,1],
			iq    => [   (($d==1) && ($f==1)),	\&twopass,	"Insane quality H.264 MP4",	"_IQ",	5000,	$maxaudiobr,	19,	1,1],
			xq    => [   (($d==1) && ($f==1)),	\&twopass,	"X-Treme quality H.264 MP4",	"_XQ",	10000,	$maxaudiobr,	19,	1,1],
			lqavi => [			1,	\&xvid,		"Low quality XviD AVI",		"_LQ",	128,	64000,		"",	1,1],
			mqavi => [			1,	\&xvid,		"Medium quality XviD AVI",	"",	512,	64000,		"",	1,1],
		);
		
		if (!@encodethese) {
			#&savesettings;
			for (qw(lq mq hq iq xq lqavi mqavi)) {
				my @t = @{ $qualities{$_} };
				#if this quality is not disabled for these content properties - then ask the user if they want to make it
				push(@encodethese, $_) if $t[0] and q_boo("$lang{QUESTION_CREATE_VIDEO} $t[2] (".($t[4]+($t[5]/1000))." kbit/sec)");
			}
		}

		for (@encodethese) {
			my $idtag = $qualities{$_}[3];
			if (
				((($d == 1) && ($f == 1)) && ($idtag =~ m/^_HQ$/)) #d1 f1 hq
			or
				($idtag =~ m/^(_IQ|_XQ)$/) #any iq/xq
			) {
				&nmf;
				last;
			}
		}

		&out_cls_info($lang{NOW_ENCODING});
		for (@encodethese) {
			my @t = @{ $qualities{$_} };
			print "now encoding $t[2] ($projname.$t[3].$nmf, $projname.$t[3], @t[4..8])\n";
			$t[1]->($projname.$t[3].$nmf, $projname.$t[3], @t[4..8]);
		}
	} else {
		#save stuff
	}
	
	mkdir('finished_'.$projname);
	&mv("*.mp4",'finished_'.$projname);
	&mv("*.avi",'finished_'.$projname);
	
	&out_info($lang{ALL_DUN});
	<STDIN>;
	exit 0; #have to exit because we don't reset vars ...

# 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 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 (my $i = 0 ; $i < @fileone ; $i++) {
		return 0 if $fileone[$i] ne $filetwo[$i];
	}
	return 1;
}

sub make_projdir {
	chdir($desktop);
	mkdir($projname) if !-e $projname;
	chdir($projname);
	&cp("${anri_dir}/silence_stereo_48000.wav","${desktop}/${projname}");
	if ($os eq 'windows') {
		&cp("${dgmpgdec_dir}/infotemplate.avs","${desktop}/${projname}");
		&cp("${anri_dir}/ntsc_d1.png","${desktop}/${projname}");
	} else { #unix
		&cp("${anri_dir}/ntsc_d1.tga","${desktop}/${projname}");
	}
}

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

#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");
}

# simple multi-threaded map, currently used for nmf
# one thread is created per argument (excluding the first)
sub tmap (&@) {
	require threads;
	my $f = shift;
	map { $_->join() } map { threads->create($f, $_) } @_;
}

sub nmf {
	&out_cls_section($lang{SECTION_NMF});
	&out_info($lang{NMF_INFO});
	&echo("");
	&out_info($lang{INFO_HQ_IQ_XQ_NMF});
	&echo("");
	if (q_boo($lang{QUESTION_CREATE_NMF},$make_nmf)) {
	        $nmf = '_nmf';
		&echo("");
		
		$number_of_processors=1;
		if ($os eq 'windows') {
			$number_of_processors=$ENV{NUMBER_OF_PROCESSORS};
		#Set lagarith to yv12 under doze
# 		$lagarith_settings = <<SABRAC;
# [settings]
# lossy_option=3
# SABRAC
		#commented out until i can figure out how to detect vista
		# IF DEFINED LOCALAPPDATA (
		#   REM Vista
		#   ECHO [settings] > "%LOCALAPPDATA%\VirtualStore\Windows\lagarith.ini"
		#   ECHO lossy_option=3 >> "%LOCALAPPDATA%\VirtualStore\Windows\lagarith.ini"
		# ) ELSE (
		#   ECHO [settings] > %WINDIR%\lagarith.ini
		#   ECHO lossy_option=3 >> %WINDIR%\lagarith.ini
		# )
		} else {
#			use Sys::CPU;
#			$number_of_processors = Sys::CPU::cpu_count();
		}
		&rm("${projname}_HQ_nmf.avs") if -e "${projname}_HQ_nmf.avs";
		#:nmf_vdubloop
		#counterB
		@nmfcommands = ();
		$alignedsplice = "";
		foreach $i (1 .. $number_of_processors) {
			&echotofile($alignedsplice,">>","${projname}_HQ_nmf.avs");
			&echotofile("avisource(\"${projname}_HQIQXQ_${i}.avi\")\n",">>","${projname}_HQ_nmf.avs");
			&cp("${projname}_HQ.avs","${projname}_HQIQXQ_${i}.avs");
			&echotofile("trim(floor(last.framecount/${number_of_processors}.000*".($i-1).".000), floor(last.framecount/${number_of_processors}.000*${i}.000)-1)\n",">>","${projname}_HQIQXQ_${i}.avs");
			push @nmfcommands, qq("${vdub_dir}/${vdubcli}" "${projname}_HQIQXQ_${i}.avs" /i "${anri_dir}/nmf.vcf" "${projname}_HQIQXQ_${i}.avi");
			$alignedsplice = "\\++\\\n";
		}
		&echotofile("converttoyv12\n",">>","${projname}_HQ_nmf.avs");
		#yikes ... better use single quotes for this one
		&echotofile('WriteFileStart("resolution.log","last.width",""" "," """, "last.height")',">>","${projname}_HQ_nmf.avs");
		&echotofile("changefps(last.framerate)\n",">>","${projname}_HQ_nmf.avs");
		&cp("${projname}_HQ_nmf.avs","${projname}_IQ_nmf.avs");
		&cp("${projname}_HQ_nmf.avs","${projname}_XQ_nmf.avs");
		#for now lq and nq ignore the nmf
		&cp("${projname}_LQ.avs","${projname}_LQ_nmf.avs");
		&cp("${projname}_LQ_xvid.avs","${projname}_LQ_xvid_nmf.avs");
		&cp("${projname}.avs","${projname}_nmf.avs");
		&cp("${projname}_xvid.avs","${projname}_xvid_nmf.avs");
		&echo($lang{ENCODING_NMF});
		tmap { system($_) } @nmfcommands;
		&echo("");
		&out_info($lang{NMF_SUCCESSFULLY_CREATED});
		&echo("");
		sleep(5);
	}
}


############################################################################
# function: script_buildfiles
# 
# Delete all avs files and restore base avs which has video source lines.
############################################################################

sub script_buildfiles {
	&wipe_avs;
	#handle trimming stuff - @trimarr must already have an even number of elements due to our input sanitation
	if ($trim) {
		for (my $i=0 ; $i < @trimarr ; $i=($i+2)) {
			&echotofile("\\++\\\n",">>","${projname}.avs") if $i > 0;
			&echotofile("trim(".$trimarr[$i].",".$trimarr[$i+1].")\n",">>","${projname}.avs");
		}
	}
	$fieldorder ? &echotofile("AssumeTFF()\n",">>","${projname}.avs") : &echotofile("AssumeBFF()\n",">>","${projname}.avs");
	&echotofile("global pal = (last.height==576) ? true : false\n",">>","${projname}.avs");
	#this $projtemp is like the old _temp.avs from doze batch anri - not sure if we still need to do this temporarily like this but it's way too complex for me to confidently say we don't so i'm going to keep it
	$projtemp = '';
	if ($isPCGAME) {
		&echotofile("global f1 = last.framerate\n",">>","${projname}.avs");
		&cp("${projname}.avs","${projname}_HQ.avs");
		#better use single quotes for this one
		&echotofile('WriteFileStart("resolution.log","last.width",""" "," """, "last.height")',">>","${projname}_HQ.avs");
		&cp("${projname}.avs","${projname}_IQ.avs");
		&cp("${projname}.avs","${projname}_XQ.avs");
		&echotofile("new_width = round(Sqrt(800*600*last.width/last.height))\n",">>","${projname}_IQ.avs");
		#Avoid weird res on at least the width.
		&echotofile("new_width = new_width - new_width % 16\n",">>","${projname}_IQ.avs");
		&echotofile("new_height = round(new_width*last.height/last.width)\n",">>","${projname}_IQ.avs");
		&echotofile("last.width*last.height > 800*600 ? Lanczos4Resize(new_width,new_height) : NOP\n",">>","${projname}_IQ.avs");
		&echotofile("last.height % 2 == 1 ? AddBorders(0,0,0,1) : NOP\n",">>","${projname}_IQ.avs");
		&echotofile("last.width*last.height > 640*512 ? Lanczos4Resize(640,round(last.height*(640.0000/last.width))) : NOP\n",">>","${projname}_HQ.avs");
		&echotofile("last.height % 2 == 1 ? AddBorders(0,0,0,1) : NOP\n",">>","${projname}_HQ.avs");
		&echotofile("last.width % 2 == 1 ? AddBorders(0,0,1,0) : NOP\n",">>","${projname}_HQ.avs");
		&echotofile("last.width*last.height > 320*256 ? Lanczos4Resize(320,round(last.height*(320.0000/last.width))) : NOP\n",">>","${projname}.avs");
		&echotofile("last.height % 2 == 1 ? AddBorders(0,0,0,1) : NOP\n",">>","${projname}.avs");
		&echotofile("last.width % 2 == 1 ? AddBorders(0,0,1,0) : NOP\n",">>","${projname}.avs");
	} else {
		&echotofile("global f1 = (pal==true) ? 50 : 59.94\n",">>","${projname}.avs");
		&cp("${projname}.avs","${projname}_HQ.avs");
		&echotofile('WriteFileStart("resolution.log","last.width",""" "," """, "last.height")'."\n",">>","${projname}_HQ.avs");
		#Set d1 either 704 or 640 (true), 352 or 320 (false)
		$dboo = ($d==1) ? "true" : "false";
		&echotofile("global d1 = ".$dboo." ? ((pal==true) ? 704 : 640) : ((pal==true) ? 352 : 320)\n",">>","${projname}_HQ.avs");
		&cp("${projname}_HQ.avs","${projname}_IQ.avs");
		#Set d1 either 352 or 320 for LQ/MQ
		&echotofile("global d1 = false ? ((pal==true) ? 704 : 640) : ((pal==true) ? 352 : 320)\n",">>","${projname}.avs");
		#d1 is set, but not yet resized.
		if ($prog) {
			$projtemp .= "pal==true ? d1==704 ? lanczos4resize(704,576) : lanczos4resize(352,288) : d1==640 ? lanczos4resize(640,480) : lanczos4resize(320,240)\n";
		} else {
			$projtemp .= "nate_vhs_head_change_erase\n" if $vhs;
			$projtemp .= "(pal==true ? d1==704 : d1==640) ? mvbob : separatefields\n";
			$projtemp .= "nate_1_pixel_bob_fix\n" if $onepixel;
			$projtemp .= "nate_retard_bob_2\n" if $deflicker;
			$projtemp .= "nate_nes\n" if $nes;
			$projtemp .= "lanczos4resize(d1,last.height)\n";
			$projtemp .= "nate_gba\n" if $gba;
			$projtemp .= "nate_gb\n" if $gb;
		}
		$projtemp .= "changefps(f1/".$f.")\n" if !$prog;
	}
	
	$projtemp .= "run=converttoyv12\n";
	if ($statid) {
		$statidtype = "d1";
		$statidtype = "gba" if $gba;
		$statidtype = "gb" if $gb;
		$projtemp .= "statid=nate_statid_".$statidtype."(run,\"".$statidlines[0]."\",\"".$statidlines[1]."\",\"".$statidlines[2]."\",".($audio_commentary == 1 ? 1 : 0).").ConvertToRGB\n";
		$projtemp .= "statid = float(run.width) / run.height >= 4./3 ?\n";
		$projtemp .= "\\ statid.Lanczos4Resize(round(run.height*4./3),run.height).AddBorders(floor((run.width-round(run.height*4./3))/2.),0,ceil((run.width-round(run.height*4./3))/2.),0).ConvertToYv12 :\n";
		$projtemp .= "\\ statid.Lanczos4Resize(run.width,round(run.width*3./4)).AddBorders(0,floor((run.height-round(run.width*3./4))/2.),0,ceil((run.height-round(run.width*3./4))/2.)).ConvertToYv12\n";
		$projtemp .= "statid++run++statid\n";
	} else {
		$projtemp .= "run\n";
	}
	$projtemp .= "changefps(last.framerate)\n";
	$projtemp .= "converttoyv12\n";
	
	&echotofile($projtemp,">>","${projname}.avs");
	&echotofile($projtemp,">>","${projname}_HQ.avs");
	&echotofile($projtemp,">>","${projname}_IQ.avs");
	&echotofile($projtemp,">>","${projname}_XQ.avs");
	&cp("${projname}.avs","${projname}_LQ.avs");
	
	if ($twod) {
		&echotofile("(last.framerate > 31) ? changefps(f1/3) : last\n",">>","${projname}_LQ.avs");
	} else {
		&echotofile("(last.framerate > 31) ? changefps(f1/2) : last\n",">>","${projname}.avs");
		&echotofile("(last.framerate > 31) ? changefps(f1/2) : last\n",">>","${projname}_LQ.avs");
	}
	&cp("${projname}_LQ.avs","${projname}_xvid.avs");
	&cp("${projname}_LQ.avs","${projname}_LQ_xvid.avs");
	
	&rm("${projname}_trimtemp.avs") if -e "${projname}_trimtemp.avs";
}



# REM ------- SETTINGS MANAGER -------
# 
# :find_existing_settings
# IF EXIST "%projdirpath%\${projname}_job.bat" (
# 	CALL "%projdirpath%\${projname}_job.bat"
# 	SET using_settings=y
# )
# GOTO :EOF
# 
# :check_settings
# CALL :show_settings
# :check_settings_p2
# SET s=
# SET /P s=Do you want to encode using these settings? If you choose No you will be prompted to enter them again. [$lang{y}/$lang{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. 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 )
# IF "%dvdsource%"=="y" ( ECHO DVD Drive Letter: %driveletter% )
# ECHO Project Name: ${projname}
# IF DEFINED avifolder ECHO AVI folder: %avifolder%
# 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 ) ELSE ( ECHO Not 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 "%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 "%trim%"=="y" ECHO Trim frame ranges %trimarray%
# IF "%statid%"=="y" ECHO StatID: %statid1:"+chr(34)+"="% / %statid2:"+chr(34)+"="% / %statid3:"+chr(34)+"="%
# ECHO.
# GOTO :EOF
# 
# :savesettings
# ECHO @ECHO OFF > "${projname}_job.bat"
# ECHO (SET proj_anriver=%anri_ver%) >> "${projname}_job.bat"
# ECHO (SET using_settings=y) >> "${projname}_job.bat"
# ECHO (SET dvdsource=%dvdsource%) >> "${projname}_job.bat"
# ECHO (SET avifolder=%avifolder%) >> "${projname}_job.bat"
# ECHO (SET avifiles=%avifiles%) >> "${projname}_job.bat"
# ECHO (SET fieldorder=%fieldorder%) >> "${projname}_job.bat"
# ECHO (SET d=%d%) >> "${projname}_job.bat"
# ECHO (SET f=%f%) >> "${projname}_job.bat"
# ECHO (SET vhs=%vhs%) >> "${projname}_job.bat"
# ECHO (SET onepixel=%onepixel%) >> "${projname}_job.bat"
# ECHO (SET nes=%nes%) >> "${projname}_job.bat"
# ECHO (SET twod=%twod%) >> "${projname}_job.bat"
# ECHO (SET statid=%statid%) >> "${projname}_job.bat"
# ECHO (SET statid1=%statid1%) >> "${projname}_job.bat"
# ECHO (SET statid2=%statid2%) >> "${projname}_job.bat"
# ECHO (SET statid3=%statid3%) >> "${projname}_job.bat"
# ECHO (SET driveletter=%driveletter%) >> "${projname}_job.bat"
# ECHO (SET projname=${projname}) >> "${projname}_job.bat"
# ECHO (SET gba=%gba%) >> "${projname}_job.bat"
# ECHO (SET gameboy=%gameboy%) >> "${projname}_job.bat"
# ECHO (SET deflicker=%deflicker%) >> "${projname}_job.bat"
# ECHO (SET prog=%prog%) >> "${projname}_job.bat"
# ECHO (SET trim=%trim%) >> "${projname}_job.bat"
# ECHO (SET trimarray=%trimarray%) >> "${projname}_job.bat"
# ECHO (SET maxaudiobitrate=%maxaudiobitrate%) >> "${projname}_job.bat"
# ECHO (SET hqq=%hqq%) >> "${projname}_job.bat"
# ECHO (SET isPCGAME=%isPCGAME%) >> "${projname}_job.bat"
# ECHO IF NOT "%%in_anrichan%%"=="y" call "%anri_path%" >> "${projname}_job.bat"
# COPY /Y "${projname}_job.bat" "${projname}_job.bak" > NUL
# GOTO :EOF
# 
# :createjob
# CALL :savesettings
# PAUSE
# GOTO die

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

#fullpathtokey, data, type
sub update_registry_key {
	require Win32::TieRegistry;
	import  Win32::TieRegistry (Delimiter=>"/", ArrayValues=>0) unless defined $Registry;
	$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,/,;
		}
	}
	
	$secondarg = '.';
	$secondarg = $_[1] if $_[1];
	
	$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]}\" \"${secondarg}\"${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"\'');
	}
}

sub trim($) { #from http://www.somacon.com/p114.php
	my $string = shift;
	$string =~ s/^\s+//;
	$string =~ s/\s+$//;
	return $string;
}

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

# function: q_boo
# returns boolean, optionally also sets boolean variable (0 or 1)
#out_info text, [variable to set]
sub q_boo($;$) {
	if (defined $_[1]) {
		if ($_[1] == 1 or $_[1] eq $lang{"y"}) { #for some reason {y} causes textwrangler's syntax highlighting to break
			$_[1] = 1;
			return 1;
		} elsif ($_[1] == 0 or $_[1] eq $lang{n}) {
			$_[1] = 0;
			return 0;
		}
	}
	&out_info($_[0]." [$lang{y}/$lang{n}]");
	print $prompt;
	while (my $userinput = <STDIN>) {
		chomp($userinput);
		if ($userinput eq $lang{"y"}) {
			$_[1] = 1;
			return 1;
		} elsif ($userinput eq $lang{n}) {
			$_[1] = 0;
			return 0;
		} else {
			print "$lang{INVALID_INPUT}\n\n";
			print $prompt;
		}
	}
}

############################################################################
# function: q_avi
# 
# Ask the user if they want 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($lang{SECTION_AVI_SOURCE});
	if (@avifiles) {
		#nothing to do here
	} elsif (defined $avidir) {
		&q_avi_a;
	} else {
		&out_info($lang{AVI_SOURCE_INFO});
		&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 "$lang{INVALID_INPUT}\n\n";
			print $prompt;
		}
	}
	#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");
		$fourcc = "";
		open(AVIFILE, "<:raw", $avifile)
		    and sysseek(AVIFILE, 0xBC, 0)
		    and sysread(AVIFILE, $fourcc, 4);
		close(AVIFILE);
		$sourcedecverb = 'avisource';
		$sourcedecverb = 'directshowsource' if grep {$_ eq lc($fourcc)} qw(tscc xvid dx50);
		&echotofile("${sourcedecverb}(\"${avifile}\")\n", ">>", "${projname}.avs");
		$alignedsplice = "\\++\\\n";
	}
	#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($lang{AVI_PATH_TO});
	&out_info($lang{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=$lang{AVI_BAD_INPUT};
		} elsif (m/^n$/i) {
			if (@avifiles < 1) {
				$errormsg=$lang{AVI_NONE_ENTERED};
			} else {
				last;
			}
		} elsif (!m/.*\.av[si]$/i) {
			$errormsg=$lang{AVI_NOT_AVI};
		} elsif (! -e $_) {
			$errormsg=$lang{FILE_NOT_FOUND};
		} else {
			push(@avifiles,$_);
			&out_info($lang{AVI_LOADED_SUCCESSFULLY}.' #'.@avifiles);
			&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("");
	&out_info($lang{AVI_DIR_LOAD_INFO});
	while (1) {
		if (defined $avidir) {
			$_ = $avidir;
		} else {
			print $prompt;
			$_ = <STDIN>;
		}
		@avifiles = ();
		chomp;
		#Validate avifolder. Check for blank, then :\ for full path if windows, then see whether it exists.
		if (m/^$/) {
			$errormsg=$lang{AVI_DIR_LOAD_MUST_ENTER_PATH};
		} elsif (m/^.[^:][^\\].*/ or $os ne 'windows') {
			$errormsg=$lang{AVI_DIR_LOAD_MUST_BE_FULL_PATH};
		} elsif (! -e $_) {
			$errormsg=$lang{AVI_DIR_LOAD_DIR_DOES_NOT_EXIST};
		} else {
			$avifolder = $_;
			#remove any and all / or \ characters from the end of the path
			$avifolder =~ s/[\/]*$//;
			
			#build list
			for (glob("$avifolder/*.avi")) {
				push(@avifiles,$_);
				print $_."\n";
			}
			
			#user can accept if files were found
			if (@avifiles == 0) {
				$errormsg = $lang{AVI_DIR_LOAD_NO_AVIS_FOUND_IN_DIR};
			} else {
				#Ask user if the list is good.
				if ($auto or q_boo($lang{QUESTION_AVI_DIR_LOAD_CONTINUE_OR_RESCAN})) {
					last;
				} else {
					$errormsg = $lang{AVI_DIR_LOAD_INFO};
				}
			}
		}
		undef $avidir;
		&out_error($errormsg);
	}
}

############################################################################
# function: q_dfnd
# 
# FIXME
############################################################################
sub q_dfnd {
	&out_info($lang{DFND_INFO});
	q_boo($lang{QUESTION_USE_DFND_DATABASE}, $dfnd);
	if ($dfnd) {
		#:dfnd
		&out_info($lang{INFO_CONNECTING_TO_DFND_DATABASE});
		&out_info($lang{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" "'.$lang{DFND_URL}.'"';
		$_ = 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; ###FIXME: this wipes out the user's cli-specified --gb or whatever if they don't specify --spec
				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;
				#right now only the accent in Pokemon and & need to be changed, but it'd be better for it to work with all utf chars
				$title=~s/(\xc3\xa9)/chr(130)/eg;
				$titles .= "".($i+1).": ${title}\n";
				#printing at most 50 lines at a time
				if(($i+1) % 50 == 0) {
					print $titles;
					$titles = '';
					&out_info($lang{PRESS_ENTER_PAGE});
					<STDIN>;
				}
			}
			print $titles;
			#system("echo \"${titles}\" | more");
			print $prompt;
			while (<STDIN>) {
				chomp;
				if (m/^$/) {
					$errormsg=$lang{DFND_MUST_CHOOSE_GAME};
				} elsif (m/[^0-9]/) {
					$errormsg=$lang{DFND_MUST_ENTER_GAME_NUMBER};
				} elsif (($_ > scalar @dfnddata) or ($_ < 0)) {
					$errormsg=$lang{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($lang{DFND_COULD_NOT_CONNECT_TO_SDA});
			&q_dfnd if q_boo($lang{QUESTION_DFND_COULD_NOT_CONNECT_TO_SDA_TRY_AGAIN});
		}
	}
}

############################################################################
#                               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 ${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 (my $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($lang{SECTION_RIP_DVD});
	if (! defined $driveletter) {
		if ($os eq 'windows') {
			&out_info($lang{QUESTION_DVD_DRIVE_LETTER});
			&out_info($lang{RIP_DVD_SOURCE_FILES_ON_HD_TIP});
			print $prompt;
			while (<STDIN>) {
				chomp;
				if (m/^[a-z]$/i) {
					$driveletter = $_;
					last;
				} else {
					$errormsg=$lang{DVD_MUST_ENTER_DRIVE_LETTER};
				}
				&out_error($errormsg);
				print $prompt;
			}
		} else { #unix
			&out_info($lang{QUESTION_DVD_DRIVE_PATH});
			&out_info($lang{RIP_DVD_SOURCE_FILES_ON_HD_TIP_UNIX});
			print $prompt;
			while (<STDIN>) {
				chomp;
				if (!m/^$/) {
					$driveletter = $_;
					last;
				} else {
					$errormsg=$lang{DVD_MUST_ENTER_DRIVE_PATH};
				}
				&out_error($errormsg);
				print $prompt;
			}
		}
	}
	#this is mainly because when you drag things onto a terminal window in os x it cats a space on the end of the path
	$driveletter = &trim($driveletter);
	if (defined $dvdripto) {
		$dvdripto = "${dvdripto_parentdir}/${dvdripto}";
	} else {
		&echo("");
		&out_info("$lang{DVD_INFO_ANRI_WILL_EXTRACT_TO_DIR} $lang{QUESTION_DVD_RIPTO_DIR_NAME}");
		print $prompt;
		while (<STDIN>) {
			chomp;
			if (!m/^$/) {
				$dvdripto = "${dvdripto_parentdir}/${_}";
				last;
			} else {
				$errormsg=$lang{DVD_MUST_ENTER_RIPTO_DIR_NAME};
			}
			&out_error($errormsg);
			print $prompt;
		}
	}
	mkdir($dvdripto_parentdir) if !-e $dvdripto_parentdir; #paranoia
	mkdir($dvdripto) if !-e $dvdripto;
	&echo("");
	&out_info($lang{DVD_INFO_ANRI_WILL_RIP_NOW});
	if (!$auto) {
		&out_info($lang{PRESS_ENTER_TO_CONTINUE});
		&echo("");
		<STDIN>;
	}
	my $video_ts_tmp=&chopper("${driveletter}${colon}/VIDEO_TS");
	if (-e ${video_ts_tmp}) {
		$video_ts = "${video_ts_tmp}";
		#if (glob("${video_ts}/VTS*.IFO")) { #glob is utterly broken on my 10.5 machine running perl 5.8.8
		@ifofiles = ();
		opendir(VTS, $video_ts);
		@ifofiles = grep { /^VTS.*\.IFO$/ } readdir(VTS);
		closedir(VTS);
		$_ = $video_ts.'/'.$_ for @ifofiles;
		if (@ifofiles) {
			&pgccount(sort @ifofiles);

		#	if ($advanced_mode) {
		#       IF NOT "%auto%"=="y" (
		#         ECHO.
		#         CALL :out_info $lang{DVD_ADVANCED_MODE}
		#         SET s=
		#         SET /P s=$lang{DVD_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
		#         )
		#       )
		#     )
		#	}
			$end_bar = 0; #safety for multiple dvd rips
			share($end_bar);
			$mplayer_loop_thread = threads->create(\&mplayer_loop);
			$mplayer_loop_thread->detach();
			&progress_bar("${dvdripto}", "${video_ts}", 2, "vob", "VOB", "", "",40);
		} else {
			&cp("${video_ts}/*","${dvdripto}");
		}
	} else {
		if (-e "${driveletter}/DVD_RTAV") {
			&cp("${driveletter}/DVD_RTAV/*","${dvdripto}");
		} else {
			&echo($lang{DVD_VIDEOTS_NOT_FOUND});
			#GOTO DIE
		}
	}
	$mplayer_loop_thread->set_thread_exit_only(1);
	if (!$auto) {
		&out_info("$lang{DVD_FINISHED_RIPPING} $lang{PRESS_ENTER_TO_CONTINUE}");
		<STDIN>;
	}
	undef $dvdripto;
	undef $driveletter;
}

# mplayer extraction loop, put in new thread for progress bar
# to run simultaneously with it.
sub mplayer_loop{
	my $redirect = "\&>\"${dvdripto}/mplayer.log\"";
	if($os eq 'windows'){
		$redirect = "> \"${dvdripto}/mplayer.log\" 2>\&1";
	}
	#Rip the titles with Mplayer using info from &pgccount()
	for (@pgclist) {
		m/^([^,]+),.+\/VTS_([0-9][0-9])_.*$/;
		#zero pad to 3 places to avoid sorting problems where 10 comes before 2.
		$expandpgc = sprintf("%03d", $1);
		#FIXME log this
		system("\"${anri_dir}/${mplayer}\" dvd://${1} -dvd-device \"${video_ts}\" -dumpstream -dumpfile \"${dvdripto}/I${2}_${expandpgc}.vob\" ${redirect}");
	}
	#used to kill the progress bar just in case it doesn't kill itself first.
	$end_bar=1;
}

# finds all unique program chains in a set of IFO files, stores in @pgclist
sub pgccount {
	use bytes;
	$pgctable = 0x1000;
	@pgclist = ();
	$currentpgc = 0;
	for $ifofile (@_) {
		next unless &check_ifo();
		@sectors = ();
		for (1 .. unpack('n', substr($buffer, $pgctable, 2))) {
			$pgcstart   = unpack('N', substr($buffer, $pgctable + $_ * 8 + 4,             4));
			$cellstart  = unpack('n', substr($buffer, $pgctable + $pgcstart + 0xE8,       2)) + 8;
			$cellsector = unpack('N', substr($buffer, $pgctable + $pgcstart + $cellstart, 4));
			$currentpgc++;
			unless (grep { $_ == $cellsector } @sectors) {
				push @sectors, $cellsector;
				push @pgclist, "${currentpgc},${ifofile}";
			}
		}
	}
}

# performs error checking for pgccount
sub check_ifo {
	-s $ifofile < 2**20 or return 0;
	open(IFO, '<:raw', $ifofile) or return 0;
	local $/;
	$buffer = <IFO>;
	close(IFO);
	substr($buffer, 0, 12) eq 'DVDVIDEO-VTS' or return 0;
	return 1;
}

sub index_dvd {
	#we don't actually index anything under unix but we still need to pick from the ripped dvd sources, write the start of the main project .avs and set some variables
	$maxaudiobr ||= 320000;
	
	&out_cls_info($lang{DVD_INDEX_INFO_FILELIST});
	&echo("");
	&echo($lang{DVD_INDEX_WARNING});
	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
		@dvdfilemasksorig = @dvdfilemasks;
		foreach $mask (@dvdfilemasksorig) {
			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($lang{DVD_INDEX_NO_FOLDERS_WITH_DVD_FILES_FOUND});
		<STDIN>;
		exit 1;
	} else {
		while (($key, $value) = each(%gooddvddirs)) {
			&echo("${key}\n");
		}
	}

	if (@dvdchoices) {
		map { $_ = "${dvdripto_parentdir}/$_" } @dvdchoices;
	} else {
		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,$lang{INVALID_INPUT});
			} else {
				for (split(" ")) {
					if (defined($gooddvddirs{$_})) {
						push(@dvdchoices,$gooddvddirs{$_});
					} else {
						push(@errormsgs,"$lang{INVALID_SELECTION}: ${_}");
					}
				}
				last if @dvdchoices > 0;
			}
			&out_error(@errormsgs);
			print $prompt;
		}
	}
	&echo("");
	
	&out_info($lang{DVD_INDEX_NOW_INDEXING});
	#Start - AVS prep
	&rm("${projname}.avs") if -e "${projname}.avs";
	&echotofile("loadplugin(\"${dgmpgdec_dir}/DGDecode.dll\")\n",">","${projname}.avs") if $os eq 'windows';
	&echotofile("import(\"${anri_dir}/sda.avs\")\n",">>","${projname}.avs") if $os eq 'windows';
	&echotofile("import(\"${desktop}/${projname}/plugins.avs\")\n",">>","${projname}.avs") if $os eq 'windows';
	# End - AVS prep
	
	$alignedsplice = '';
	foreach $dvdchoice (@dvdchoices) {
		foreach $mask (@dvdfilemasks) {
			$i = 1;
			foreach $mpegfile (glob("${dvdchoice}/$mask")) {
				#ignore bad files
				if (-s $mpegfile > 5000) {
					&echotofile($alignedsplice,">>","${projname}.avs");
					#split into basename and extension
					$mpegfile =~ m/^.*[\\\/]([^\\\/.]+)\.([^.]+)$/;
					if ($os eq 'windows') {
						# 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
						#print "\"${dgmpgdec_dir}/${dgindex}\" -IF=[${mpegfile}] -OF=[${projname}_${i}_${1}] -PREVIEW -exit";
						#print "\n";
						system("\"${dgmpgdec_dir}/${dgindex}\" -IF=[${mpegfile}] -OF=[${projname}_${i}_${1}] -PREVIEW -exit");
						#print "\"${dgmpgdec_dir}/${dgindex}\" -IF=[${mpegfile}] -OM=2 -OF=[${projname}_${i}_${1}] -AT=[infotemplate.avs] -exit";
						#print "\n";
						system("\"${dgmpgdec_dir}/${dgindex}\" -IF=[${mpegfile}] -OM=2 -OF=[${projname}_${i}_${1}] -AT=[infotemplate.avs] -exit");
						###FIXME why is this missing? (next line)
						#&mv("${dvdchoice}/${1}.log","${desktop}/${projname}/${projname}_${i}_${1}.log");
						### FIXME sorting problems if we have over 9 input files?
						for (glob("${projname}_${i}_*")) {
							#warn 'glob stuff '.$_;
							&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);
							}
						}
					} else { #unix
						&cp($mpegfile,"${desktop}/${projname}");
						&echotofile("MPEG2source(\"${1}.${2}\",upconv=1)\n",">>","${projname}.avs");
						### FIXME get $maxaudiobr?
					}
					# If there's more than one file to be joined, they must be appended together.
					$alignedsplice = "\\++\\\n";
					$i++;
				}
			}
		}
	}
	&echotofile("\n",">>","${projname}.avs");
	#warn 'copying '."${projname}.avs";
	&cp("${projname}.avs","${projname}.bak");
}

############################################################################
#                               Encoding
#
# Encode video in OS-specific ways.
############################################################################

sub pipe_prepare($$) {
	$basename = shift;
	$mode = shift;

	$avs = "${basename}.pipe";
	#system("rm", $avs) if -e $avs;
	system("mkfifo", $avs) if !-e $avs;

	open(AVS, "${basename}.avs"); #must be unix text when running sasami under unix ...
	@avs = <AVS>;
	close(AVS);
	@sources = ();
	@trims = ();
	$f = 1;
	for (@avs) {
		chomp;
		next if m/^#/;
		push(@sources,$1) if m/^.*MPEG2source\("([^"]+)".*$/i;
		push(@sources,$1) if m/^.*avisource\("([^"]+)".*$/i;
		push(@sources,$1) if m/^.*directshowsource\("([^"]+)".*$/i;
		$fieldorder = 1 if m/^AssumeTFF\(\)/i;
		$fieldorder = 0 if m/^AssumeBFF\(\)/i;
		$d = 1 if m/^global d1 = true/;
		$d = 4 if m/^global d1 = false/;
		$d = 4 if m/^separatefields\(\)$/i; #for sample extraction
		$f = $1 if m/changefps\(f1\/([0-9])\)/; #source file may have changefps() multiple times (maybe to simulate deprecated nicefps() for 32-bit denominator); we only remember the last one
		$deflicker = 1 if m/^nate_retard_bob_2/;
		$vhs = 1 if m/^nate_vhs_head_change_erase/;
		$onepixel = 1 if m/^nate_1_pixel_bob_fix/;
		$nes = 1 if m/^nate_nes$/;
		push(@trims,"$1,$2") if m/trim\(([0-9]+),([0-9]+)\)/;
		$gba = 1 if m/^nate_gba$/;
		$gb = 1 if m/^nate_gb$/;
		#$resize = 1 if m/^lanczos4resize\(/;
		#nate format
		$statidlines[0] = $1 if m/^statid1="""(.*)"""$/;
		$statidlines[1] = $1 if m/^statid2="""(.*)"""$/;
		$statidlines[2] = $1 if m/^statid3="""(.*)"""$/;
		#anri format
		(@statidlines) = ($1, $2, $3) if m/^statid=.*\(run,"([^"])","([^"])","([^"])"\)/;
	}
	die 'sasami: no sources detected in .avs!' if @sources == 0;
	return @sources if $mode eq 'sources';
	
	open(JS, ">${basename}.js") or die "could not open ${basename}.js for writing";
	print JS '//AD  <- Needed to identify//'."\n\nvar app = new Avidemux();\n\n";
	for (my $i = 0 ; $i < @sources ; $i++) {
		print JS "app.forceUnpack();\n";
		if ($i == 0) {
			print JS "app.load(\"${desktop}/${projname}/${sources[$i]}\");\n";
		} else {
			print JS "app.append(\"${desktop}/${projname}/${sources[$i]}\");\n";
		}
	}
	
# 	@mencoderargslist = ();
# 	#build mencoder command to feed fifo
# 	if ($mode eq "video") {
# 		$mencoderargs = "\"${anri_dir}/${mencoder}\" ${really_quiet}";
# 	} elsif ($mode eq "audio") {
# 		$mencoderargs = "\"${anri_dir}/${mplayer}\" ${really_quiet}";
# 	}
	
	print JS "\napp.clearSegments();\n" if (@trims);
	my $sourcenum = 0;
	my $previous_sourcelength = 0;
	my $this_sourcelength;
	foreach $source (@sources) {
		#get vital info about source
		my $mplayeridentify = <<SABRAC;
"${anri_dir}/${mplayer}" -identify -vo null -slave ${source} 2>&1 <<ENDOFSCRIPT
quit
ENDOFSCRIPT
SABRAC
		for (qx($mplayeridentify)) {
			chomp;
			$width = $_ if s/ID_VIDEO_WIDTH=([0-9]+)/$1/;
			$height = $_ if s/ID_VIDEO_HEIGHT=([0-9]+)/$1/;
			$framerate = $_ if s/ID_VIDEO_FPS=([0-9.]+)/$1/;
			$maxaudiobitrate = $_ if s/ID_AUDIO_BITRATE=([0-9]+)/$1/;
			$this_sourcelength = &round($framerate * $_) if s/ID_LENGTH=([0-9.]+)/$1/;
		}
	# 	print "$width\n";
	# 	print "$height\n";
	# 	print "$framerate\n";
	# 	print "$maxaudiobitrate\n";
		die "sasami: could not determine video width etc" if !$width;
		$pal = ($height eq "576");
		### FIXME moved from above the foreach source block because it depends on $pal being set - check only first source and then set?
		$newframerate = ($pal ? (50/$f) : (59.94/$f)); #required for trimming
		
		#trimming
	# 	$framerate = 29.97;
	# 	$framerate = 25 if $pal;
		my $sourcelength = ($previous_sourcelength + $this_sourcelength);
		for (@trims) {
			if ($_) {
				#print "popped: $_\n";
				my $trimone = '';
				my $trimtwo = '';
				m/^(.*),(.*)$/;
				if ($1) {
					if ($1 < $sourcelength) {
						$trimone = ($1 - $previous_sourcelength);
						$trimtwo = ($this_sourcelength - $trimone + 1);
					}
				}
				if ($2) {
					if ($2 < $sourcelength) {
						$trimone = 0 if !$trimone;
						$trimtwo = ($2 - $previous_sourcelength - $trimone + 1);
					}
				}
				if (($trimone ne '') && ($trimtwo ne '')) {
					print JS "app.addSegment(${sourcenum},${trimone},${trimtwo});\n";
					$_ = ",";
					#keep second trim point in case we haven't reached it yet
					$_ .= $2 if $2 > $sourcelength;
				}
			}
		}
		$previous_sourcelength = $sourcelength;
		$sourcenum++;
	}
	print JS "\n";
		
# app.video.addFilter("crop","left=14","right=16","top=22","bottom=30");
# app.video.addFilter("mpresize","w=320","h=240","algo=2");
# app.video.addFilter("resamplefps","newfps=29970","use_linear=0");
# app.video.addFilter("YADIF","mode=3","order=1");
# app.video.addFilter("mcdeinterlace","mode=2","qp=1","initial_parity=0");
# app.video.addFilter("msharpen","mask=0","highq=1","strength=100","threshold=15");
# app.video.addFilter("addblack","left=0","right=0","top=0","bottom=2");
	#one pixel bob
# 		if ($onepixel) {
# 			app.video.addFilter("crop","left=0","right=0","top=1","bottom=0");
# 			app.video.addFilter("addblack","left=0","right=0","top=0","bottom=1");
# 			$mencoderargs .= " -vf-add crop=${width}:".($height-1).":0:0,expand=${width}:${height}:0:1";
# 			$fieldorder = 0 if $fieldorder == 1;
# 			$fieldorder = 1 if $fieldorder == 0;
# 		}
	
	if ($nes) {
		print JS '//nes'."\n";
		print JS 'app.video.addFilter("crop","left=8","right=0","top=0","bottom=0");'."\n";
		print JS 'app.video.addFilter("addblack","left=8","right=0","top=0","bottom=0");'."\n";
		print JS "\n";
		#$mencoderargs .= " -vf-add crop=".($width-8).":${height}:8:0,expand=${width}:${height}:8:0" if $nes;
		#-af channels=6:4:0:0:0:1:0:2:0:3 media.avi
		#Would change the number of channels to 6 and set up 4 routes that copy channel 0 to channels 0 to 3.  Channel 4 and 5 will contain silence.
	}
	
	print JS 'app.video.addFilter("YADIF","mode=3","order='.$fieldorder.'");'."\n";
	print JS 'app.video.addFilter("mcdeinterlace","mode=2","qp=1","initial_parity='.$fieldorder.'");'."\n" if ($d == 1) && ($mode ne "audio"); #for some reason the deinterlacing filter breaks audio output
	#$mencoderargs .= " -vf-add yadif=3 -vf-add mcdeint=1:${fieldorder}" if $d == 1;
	#$tfields = 0;
	#$tfields = 4 if $deflicker;
	#$mencoderargs .= " -vf-add tfields=${tfields}" if $d == 4;
	
	#i just eyeballed this - someone will need to sync the avisynth and mencoder sharpen filters
	#apparently avidemux doesn't need de-deflickering ...
	#print JS 'app.video.addFilter("msharpen","mask=0","highq=1","strength=100","threshold=15");'."\n" if $deflicker;
	#$mencoderargs .= " -vf-add unsharp=l3x3:0.6:c3x3:0.6" if $deflicker;

	if ($vhs && ($mode eq "video")) {
		print JS '//vhs'."\n";
		print JS 'app.video.addFilter("crop","left=0","right=0","top=0","bottom=12");'."\n";
		print JS 'app.video.addFilter("addblack","left=0","right=0","top=0","bottom=12");'."\n";
		print JS "\n";
		#$mencoderargs .= " -vf-add crop=${width}:".($height-12).":0:0,expand=0:-12:0:0" if $vhs;
	}
	
	if ($gba && ($mode eq "video")) {
		$gba_crop_left = 44 if !defined $gba_crop_left;
		$gba_crop_top = 40 if !defined $gba_crop_top;
		$gba_crop_right = 44 if !defined $gba_crop_right;
		$gba_crop_bottom = 40 if !defined $gba_crop_bottom;
		for my $x ($gba_crop_left, $gba_crop_top, $gba_crop_right, $gba_crop_bottom) { #avidemux is stuck in yv12
			$x = $x + ($x % 4);
		}
		print JS 'app.video.addFilter("mpresize","w=320","h=240","algo=2");'."\n";
		#$mencoderargs .= " -vf-add scale=320:240";
		print JS 'app.video.addFilter("crop","left='.$gba_crop_left.'","right='.$gba_crop_right.'","top='.$gba_crop_top.'","bottom='.$gba_crop_bottom.'");'."\n";
		#$mencoderargs .= " -vf-add crop=".(320-$gba_crop_right-$gba_crop_left).":".(240-$gba_crop_bottom-$gba_crop_top).":${gba_crop_left}:${gba_crop_top}";
		print JS 'app.video.addFilter("mpresize","w=240","h=160","algo=2");'."\n";
		#$mencoderargs .= " -vf-add scale=240:160";
		$newwidth = 240;
		$newheight = 160;
	} elsif ($gb && ($mode eq "video")) {
		$gb_crop_left = 80 if !defined $gb_crop_left;
		$gb_crop_top = 48 if !defined $gb_crop_top;
		$gb_crop_right = 80 if !defined $gb_crop_right;
		$gb_crop_bottom = 48 if !defined $gb_crop_bottom;
		print JS 'app.video.addFilter("mpresize","w=320","h=240","algo=2");'."\n";
		#$mencoderargs .= " -vf-add scale=320:240";
		print JS 'app.video.addFilter("crop","left='.$gb_crop_left.'","right='.$gb_crop_right.'","top='.$gb_crop_top.'","bottom='.$gb_crop_bottom.'");'."\n";
		#$mencoderargs .= " -vf-add crop=".(320-$gb_crop_right-$gb_crop_left).":".(240-$gb_crop_bottom-$gb_crop_top).":${gb_crop_left}:${gb_crop_top}";
		$newwidth = (320-$gb_crop_right-$gb_crop_left);
		$newheight = (240-$gb_crop_bottom-$gb_crop_top);
	}

	$newwidth  = (($d == 1) ? ($pal ? 704 : 640) : ($pal ? 352 : 320)) unless $newwidth;
	$newheight = (($d == 1) ? ($pal ? 576 : 480) : ($pal ? 288 : 240)) unless $newheight;
	print JS 'app.video.addFilter("resamplefps","newfps='.($newframerate*1000).'","use_linear=0");'."\n";
	#$mencoderargs .= " -vf-add framestep=${f}";
	$x264newframerate = "--fps ${newframerate}";
	$x264outext = '264';
	$x264dimensions = "${newwidth}x${newheight}";
	$ampersand = '&';
	$mp4boxnewframerate = "-fps ${newframerate}";
	
	print JS 'app.video.addFilter("mpresize","w='.$newwidth.'","h='.$newheight.'","algo=2");'."\n";
	#$mencoderargs .= " -vf-add scale=${newwidth}:${newheight}";# if $resize;
	
	if ($mode eq "video") {
		print JS 'app.video.codec("YV12","CQ=1","0 ");'."\n";
		print JS 'app.audio.load("NONE","");'."\n";
		print JS 'app.setContainer("OGM");'."\n";
		print JS 'app.save("'."${desktop}/${projname}/avidemux.pipe".'");'."\n";
	} elsif ($mode eq "audio") {
		print JS 'app.audio.codec("none",128,0,"");'."\n";
		print JS 'app.save("/dev/null");'."\n"; #can someone tell me why this is required - get truncated audio with app.audio.save() otherwise
		print JS 'app.audio.save("'."${desktop}/${projname}/${avs}".'");'."\n";
	}
	print JS "\n".'setSuccess(1);'."\n".'app.Exit();'."\n";
	close(JS);

# 	my $sourcesplit = '"'.$source.'"';
# 	my $littleo = "-o \"${avs}\"";
# 	$littleo = "-ao pcm:file=\"${avs}\":fast" if $mode eq "audio";
# 	if (@trimargsarr) {
# 		my $mencoderargstemp = '';
# 		while (my $trimargs = shift(@trimargsarr)) {
# 			$mencoderargstemp .= $mencoderargs." ${sourcesplit}".$trimargs." ${littleo}\n";
# 		}
# 		$mencoderargs = $mencoderargstemp;
# 	} else {
# 		$mencoderargs .= " ${sourcesplit} ${littleo}\n";
# 	}
# 	
# 	push(@mencoderargslist,$mencoderargs);
	
	if (($statidlines[0]) || ($statidlines[1]) || ($statidlines[2])) {
		require Imager;
		$img = Imager->new;
		$img->read(file=>"ntsc_d1.tga") or die "Cannot load statid image: ", $img->errstr;
		$font = Imager::Font->new(file=>$path_to_verdana); #will need to be changed for non-mac unix ...
		&statid_lines_write($statidlines[0], $img->getheight/2, 36, 'white'  ) if $statidlines[0];
		&statid_lines_write($statidlines[1], 360,               36, 'white'  ) if $statidlines[1];
		&statid_lines_write($statidlines[2], 400,               36, 'white'  ) if $statidlines[2];
		&statid_lines_write("Audio commentary on track 2", 460, 28, '#E1CE8B') if $audio_commentary;
		$img->write(file=>'statid.tga')
		or die 'Cannot save statid.tga: ', $img->errstr;
		open(MF,">statid.txt") or die "Could not open statid.txt for appending!";
		for (1..5) { #once for each second of the statid
			for (1..$newframerate) { #once for each frame this second
				print MF "statid.tga\n";
			}
		}
		close(MF);
		if ($mode eq "video") {
			$statidmencoderargs = "\"${anri_dir}/${mencoder}\" ${really_quiet} -vf-add scale=${newwidth}:${newheight} -vf-add format=i420 -ovc raw -of rawvideo -nosound -ofps ${newframerate} mf://\@statid.txt -mf fps=${newframerate}:type=tga -o \"${avs}\"";
		} elsif ($mode eq "audio") {
			$statidmencoderargs = "\"${anri_dir}/${mplayer}\" \"silence_stereo_48000.wav\" -vc null -vo null -ao pcm:file=\"${avs}\":fast";
		}
	}
}

sub pipe_write {
	print "opening ${avs} ...\n";
# 	sleep 2;
	open(FIFO,">${avs}");
# 	sleep 2;
	#<STDIN>;
	print("$statidmencoderargs\n") if (($statidlines[0]) || ($statidlines[1]) || ($statidlines[2]));
	system($statidmencoderargs) if (($statidlines[0]) || ($statidlines[1]) || ($statidlines[2]));
	if ($mode eq "video") {
		print "making avidemux.pipe ...\n";
		system("mkfifo", "avidemux.pipe");
		print "made avidemux.pipe\n";
		system("\"${anri_dir}/${mencoder}\" ${really_quiet} -vf-add format=i420 -ovc raw -of rawvideo -nosound -o \"${avs}\" avidemux.pipe &");
	}

#   use Dumpvalue;
#   my $dumper = new Dumpvalue;
#   $dumper->set(globPrint => 1);
#   $dumper->dumpValue(\*::);
#   $dumper->dumpvars('main');

	print "sh \"${avidemux}\" --autoindex --run \"${desktop}/${projname}/${basename}.js\"\n";
	system("sh \"${avidemux}\" --autoindex --run \"${desktop}/${projname}/${basename}.js\""); #need the full path to the js for some reason
	&rm("avidemux.pipe") if $mode eq "video";
	print("$statidmencoderargs\n") if (($statidlines[0]) || ($statidlines[1]) || ($statidlines[2]));
	system($statidmencoderargs) if (($statidlines[0]) || ($statidlines[1]) || ($statidlines[2]));
	print "closing FIFO...\n";
	#<STDIN>;
# 	sleep 2;
	close(FIFO);
# 	sleep 2;
}

#statid line text, y-offset, text size, color
sub statid_lines_write {
$font->align(string => $_[0],
	aa => 1,
	size => $_[2],
	color => $_[3],
	x => $img->getwidth/2,
	y => $_[1],
	halign => 'center',
	valign => 'center',
	image => $img);
}

sub round {
	return int($_[0] + .5 * ($_[0] <=> 0));
}

#input filename, output basename, output audio bitrate in baud, x264 minimum quantizer, delete tempfiles boolean
sub onepass {
	#VIDEO
	$x264newframerate = '';
	$x264outext = 'mp4';
	$x264dimensions = '';
	$ampersand = '';
	$mp4boxnewframerate = '';
	if ($os eq 'windows') {
		$avs = $_[0].'.avs';
	} else {
		&pipe_prepare($_[0],"video");
		$avs = $_[0].'.pipe';
	}
	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 ${x264newframerate} --output \"${_[1]}_video.${x264outext}\" \"${avs}\" ${x264dimensions} ${ampersand}");
	print "x264 is going ...\n";
	&pipe_write if $os ne 'windows';
	print "pipe_write is going ...\n";
	system("rm", $avs) if $os ne 'windows';

	#AUDIO
	$audioext = 'mp4';
	if ($os eq 'windows') {
		system("\"${vdub_dir}/${vdubcli}\" \"${avs}\" /i \"${anri_dir}/audioout.vcf\" \"${_[1]}_temp.wav\"");
		system("\"${anri_dir}/${naac}\" -br ${_[2]} -lc -if \"${_[1]}_temp.wav\" -of \"${_[1]}_audio.${audioext}\"");
	} else {
		&pipe_prepare($_[0],"audio");
		system("\"${anri_dir}/${mplayer}\" -dumpstream -dumpfile \"${_[1]}_avidemux.wav\" \"${avs}\" &");
		&pipe_write;
		system("rm", $avs) if $os ne 'windows';
		system("\"${anri_dir}/${mplayer}\" -demuxer rawaudio -rawaudio channels=2:rate=48000 -ao pcm:file=\"${_[1]}_temp.wav\":fast \"${_[1]}_avidemux.wav\"");
		if ($faac) {
			$audioext = 'aac';
			#thanks grenola
			$faacq = "-q 65 -c 8000"; #default is for mq/lq
			$faacq = "-b 128" if $_[2] ge "128000";
			$faacq = "-b 256" if $_[2] ge "256000";
			system("\"${faac}\" --mpeg-vers 4 ${faacq} -o \"${_[1]}_audio.${audioext}\" \"${_[1]}_temp.wav\"");
		} else { #afconvert's only going to work under os x
			system("\"${anri_dir}/${afconvert}\" -f mp4f -d 'aac ' -b ${_[2]} -s 1 -v \"${_[1]}_temp.wav\" \"${_[1]}_audio.${audioext}\"");
		}
	}
	
	#MUX
	if ($os eq 'windows') {
		system("\"${anri_dir}/${mp4box}\" ${mp4boxnewframerate} -tmp . -new -add \"${_[1]}_video.${x264outext}\" -add \"${_[1]}_audio.${audioext}\" \"${_[1]}.mp4\"");
	} else {
		system("export DYLD_LIBRARY_PATH=\"${anri_dir}\";\"${anri_dir}/${mp4box}\" ${mp4boxnewframerate} -tmp . -new -add \"${_[1]}_video.${x264outext}\" -add \"${_[1]}_audio.${audioext}\" \"${_[1]}.mp4\"");
	}
	
	#CLEANUP
	if (${_[4]}) {
		@todel = (
			"${_[1]}_video.${x264outext}",
			"${_[1]}_temp.wav",
			"${_[1]}_audio.${audioext}",
		);
		&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 {
	&x264(
		@_,
		'--level 4.1 --bframes 3 --vbv-bufsize 9000 --vbv-maxrate 25000 --threads auto --thread-input --progress --no-psnr --analyse none --no-ssim',
		'--level 4.1 --bframes 3 --vbv-bufsize 9000 --vbv-maxrate 25000 --threads auto --thread-input --progress --no-psnr --ref 3 --mixed-refs --no-fast-pskip --b-rdo --bime --weightb --direct auto --subme 7 --trellis 2 --partitions p8x8,b8x8,i4x4,i8x8 --8x8dct --me umh'
	);
}

#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 {
	&x264(
		@_,
		'--vbv-bufsize 512 --vbv-maxrate 768 --level 1.3 --no-cabac --threads auto --thread-input --progress --no-psnr --analyse none --no-ssim',
		'--vbv-bufsize 512 --vbv-maxrate 768 --level 1.3 --no-cabac --threads auto --thread-input --progress --no-psnr --analyse all --no-fast-pskip --subme 7 --trellis 2 --me umh'
	);
}

#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, x264argsfirstpass, x264argssecondpass
sub x264 {
	$x264args_pass2 = pop;
	$x264args_pass1 = pop;

	#VIDEO
	$x264newframerate = '';
	$x264outext = 'mp4';
	$x264dimensions = '';
	$ampersand = '';
	$mp4boxnewframerate = '';
	if ($os eq 'windows') {
		$avs = $_[0].'.avs';
	} else {
		&pipe_prepare($_[0],"video");
		#$avs = $_[0].'.pipe'; #already set in pipe_prepare()
	}
	system("\"${anri_dir}/${x264}\" --pass 1 --bitrate ${_[2]} --stats \"${_[1]}.stats\" --qpmin ${_[4]} ${x264newframerate} ${x264args_pass1} --output ${nul} \"${avs}\" ${x264dimensions} ${ampersand}");
	&pipe_write if $os ne 'windows';
	#this is a hack to deal with the fact that sometimes x264 takes a while to finish encoding and write out the statsfile - thanks grenola!
	while (!(-e "${_[1]}.stats")) {
		print("Waiting for stats file ...\n");
		sleep(1);
	}
	system("\"${anri_dir}/${x264}\" --pass 2 --bitrate ${_[2]} --stats \"${_[1]}.stats\" --qpmin ${_[4]} ${x264newframerate} ${x264args_pass2} --output \"${_[1]}_video.${x264outext}\" \"${avs}\" ${x264dimensions} ${ampersand}");
	&pipe_write if $os ne 'windows';
	#system("rm", $avs) if $os ne 'windows';
	
	#AUDIO
	$audioext = 'mp4';
	if ($os eq 'windows') {
		system("\"${vdub_dir}/${vdubcli}\" ${avs} /i \"${anri_dir}/audioout.vcf\" \"${_[1]}_temp.wav\"");
		system("\"${anri_dir}/${naac}\" -br ${_[3]} -lc -if \"${_[1]}_temp.wav\" -of \"${_[1]}_audio.${audioext}\"");
	} else {
		&pipe_prepare($_[0],"audio");
		print "starting \"${anri_dir}/${mplayer}\" -dumpstream -dumpfile \"${_[1]}_avidemux.wav\" \"${avs}\" &\n";
		#<STDIN>;
		system("\"${anri_dir}/${mplayer}\" -dumpstream -dumpfile \"${_[1]}_avidemux.wav\" \"${avs}\" &");
		print "started, starting pipe_write ...\n";
		#<STDIN>;
		&pipe_write;
		print "pipe_write done ...\n";
		#<STDIN>;
		#system("rm", $avs) if $os ne 'windows'; #fixme 20090430
		print "starting mplayer ...\n";
		#<STDIN>;
		system("\"${anri_dir}/${mplayer}\" -demuxer rawaudio -rawaudio channels=2:rate=48000 -ao pcm:file=\"${_[1]}_temp.wav\":fast \"${_[1]}_avidemux.wav\"");
		print "done\n";
		#<STDIN>;
		if ($faac) {
			$audioext = 'aac';
			#thanks grenola
			$faacq = "-q 65 -c 8000"; #default is for mq/lq
			$faacq = "-b 128" if $_[3] ge "128000";
			$faacq = "-b 256" if $_[3] ge "256000";
			system("\"${faac}\" --mpeg-vers 4 ${faacq} -o \"${_[1]}_audio.${audioext}\" \"${_[1]}_temp.wav\"");
		} else { #afconvert's only going to work under os x ...
			system("\"${anri_dir}/${afconvert}\" -f mp4f -d 'aac ' -b ${_[3]} -s 1 -v \"${_[1]}_temp.wav\" \"${_[1]}_audio.${audioext}\"");
		}
	}

	if ($os eq 'windows') {
		system("\"${anri_dir}/${mp4box}\" ${mp4boxnewframerate} -tmp . -new -add \"${_[1]}_video.${x264outext}\" -add \"${_[1]}_audio.${audioext}\" \"${_[1]}.mp4\"");
	} else {
		system("export DYLD_LIBRARY_PATH=\"${anri_dir}\";\"${anri_dir}/${mp4box}\" ${mp4boxnewframerate} -tmp . -new -add \"${_[1]}_video.${x264outext}\" -add \"${_[1]}_audio.${audioext}\" \"${_[1]}.mp4\"");
	}
	
	#CLEANUP
	if (${_[5]}) {
		@todel = (
			"${_[1]}.stats",
		);
		&rm(@todel);
	}
	if (${_[6]}) {
		@todel = (
			"${_[1]}_video.${x264outext}",
#			"${_[1]}_temp.wav",
			"${_[1]}_audio.${audioext}",
		);
		&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 {
	$avs = $_[0].'.avs';
	system("\"${anri_dir}/${xvid}\" -i \"${avs}\" -bitrate ${_[2]} -pass1 \"${_[1]}.stats\" -progress");
	system("\"${anri_dir}/${xvid}\" -i \"${avs}\" -bitrate ${_[2]} -pass2 \"${_[1]}.stats\" -progress -avi \"${_[1]}v.avi\"");
	system("\"${anri_dir}/${ffmpeg}\" -ab ${_[3]} -ac 2 -acodec mp3 -y -i \"${_[1]}v.avi\" -vcodec copy -i \"${avs}\" \"${_[1]}.avi\"");
	if (${_[5]}) {
		@todel = (
			"${_[1]}.stats",
		);
		&rm(@todel);
	}
	if (${_[6]}) {
		@todel = (
			"${_[1]}v.avi",
		);
		&rm(@todel);
	}
}

############################################################################
# Progress bar package, self explanatory
############################################################################
{
	package PBar;
	use Class::Struct length => '$', portion => '$', max_num => '$';
	use List::Util qw( min );
   	use File::stat;
	
		# writes the bar based on the int argument given.
		sub write_bar {
			local $| = 1;
			my ($self, $x, $max_num) = @_;
			$max_num ||= $self->max_num;
			my $old = $self->portion || 0;
			my $new_p = int( $self->length * $x / $max_num + 0.5 );
        
			print "\b" x( 6 + $self->length
                 	       - min( $new_p, $old ) )
			if defined $self->portion;
        
			print "="  x( $new_p - $old ),
           	  		 " "  x ( $self->length - $new_p ),
			sprintf " %3d%% ", int( 100 * $x / $max_num + 0.5 );
			$self->portion( $new_p );
		}
	
		# Gets a set of files size based on the folder and ext given.
		# takes two args
		# arg1 = folder name containing files
		# arg2 = extension to use example: vob
		# returns the size in bytes
		sub get_folder_size{
			my ($self,$dir, $ext) = @_;
			my $count = 0;
			opendir(DIR,$dir);
			my @dir = readdir(DIR);
			close DIR;
			foreach(@dir){
				if(m/^([^.]+)\.$ext$/) {
					$count=$count+(stat($dir."/".$_)->size);
				}
			}
			return $count;
        	}

		# use two integer values as args to be compared
		# arg1= new file being made/copied
		# arg2 = file to compare to
		# returns a number as a percent left to be copied.
		sub compare_file_sizes{
			my $percent_left = 100;
			my ($self,$new_filesize, $old_filesize) = @_;
			if($new_filesize<$old_filesize){
				$percent_left = int(($new_filesize*100)/$old_filesize + .5);
			}else{
				$percent_left=100;
			}
			return $percent_left;
		}
	1;
}

############################################################################
# Stand alone progress bar function
# 8 Arguments needed
# arg1 = new folder name
# arg2 = old folder/files name being copied
# arg3 = Files extension you want to use to compare(new files)
# arg4 = Files extension you want to use to compare(old files)
# arg5 = number of seconds to wait between checks
# arg6 = Message at start you want to say to user
# arg7 = Message at end you want to say to user
# arg8 = number of bars in progress bar
#
############################################################################
sub progress_bar{
	# Create new bar
	my $pb = PBar->new( length => $_[7], max_num => 100 );
	print "$_[5]\n";
	$j=0;
	$i=0;
	$old_folder_size = $pb->get_folder_size($_[1],$_[4]);
	for($i=0; $i<1;){
		$j=$pb->compare_file_sizes($pb->get_folder_size($_[0],$_[3]),$old_folder_size);
		$pb->write_bar($j);
		if($end_bar){
			$i=1;
		}elsif($j<101){
			sleep $_[2];
		}else{
			$i=1;
		}
	}
	print "\n";
	print "$_[6]\n";
}

#give a string and it checks for "\" and removes it.
sub chopper{
	if(${os} eq 'windows'){
		return $_[0];
	}else{
		my $string=$_[0];
		my $tmp="";
		my $i=length(${string})+1;
		my $not_chopped="";
		for(; ${i}>0;${i}--){
			${tmp}=chop(${string});
			if(${tmp} ne '\\'){
				${not_chopped}="${tmp}${not_chopped}";
			}
		}
		return ${not_chopped};
	}
}
Personal tools