#!/bin/bash
#!/usr/bin/env bash
PATH=/usr/share/tovid:$PATH

#############################################################################
# Este programa é software livre, você pode redistribuí-lo ou modificá-lo   #
# sob os termos da GNU General Public License, versão 2 ou qualquer versão  #
# mais recente, conforme publicado pela Free Software Foundation.           #
#############################################################################

#################################################
#                 AVI para DVD		        #
#       Feito por: Bruno Nocera Zanette	        #
#	Email: brunonzanette@gmail.com          #
#                Data: 11/2008                  #
# 					        #
#===============================================#
#					        #	
#                 FINALIDADE:		        #
# Esse Script tem como finalidade automatizar   #
# o processo de conversão de arquivos AVI para  #
# DVD, com Menu e Legendas. Para isso utiliza   # 
# um arquivo de configuração criado na          #
# primeira vez que o programa for executado.    #
#					        #
#               COMO EXECUTAR:	  	        #
# Para executar o programa basta escrever no    #
# Terminal:				        #	
# ./CriaDVD <video1> <video2> ...               #
# Onde <video1,2,...> é o nome do filme com o   # 
# caminho.				        #	
# Ex.: 					        #	
# ./CriaDVD_gtk ~/viagem.avi ~/Ferias/casa.avi  #
# 						#	
# Ou apenas:					#
# ./CriaDVD_gtk					#
#						#
#		   OPCOES:			#
# -> config : Remove a configuração existente e #
#             cria uma nova configuração	#
#						#
#################################################			

#################################################
#                DEPENDENCIAS: 			#
# - avidemux-cli			        #
# - avidemux-common		 		# 
# - tovid					#
# - mencoder					#
# - lame					#
# - toolame					#
# - mjpegtools					#
# - imagemagick					#	
# - zenity					#
#################################################

#################################################
# INICIA O PROGRAMA E TESTA SE A PASTA $dir     #
# ESTA CRIADA                                   #
#################################################
user=`ps aux | grep CriaDVD_gtk | grep -m1 bash | tr -s " " | cut -d" " -f1`
dir="/home/$user/.dvd"

if ! [ -d $dir ]
then
	mkdir $dir
fi

if ! [ -d $dir/tmp ]
then
	mkdir $dir/tmp
else
	rm -r $dir/tmp/* 2>/dev/null
fi

if [[ $1 == 'config' && -e $dir/.dvd_config ]]
then
        rm $dir/.dvd_config
fi

if [[ `df -lk | egrep '\/$' | tr -s " " | cut -d" " -f4` -le 10000000 ]]
then
	zenity --info -title "AVI_DVD" --text "O seu HD não possui espaço em disco suficiente (9Gb) para rodar o script.\nLibere mais espaço e tente denovo."
	exit 1
fi

#################################################
# CONFIGURA O PROGRAMA E SALVA A CONFIGURAÇÂO   #
# EM $dir/.dvd_config				#
#################################################
if ! [ -e $dir/.dvd_config ]
then
	#clear
	zenity --info --title "AVI_DVD" --text "Bem Vindo ao AVI_DVD\!\nPor Favor responda o questionário a seguir."

	###############
	#### VIDEO ####
	###############
	
	opcao=`zenity --width=350 --height=250 --title "AVI_DVD" --text "Qual formato o seu DVD Player aceita?" --list --radiolist --hide-column=2 --column "" --column "" --column "Opções" FALSE 1 NTSC FALSE 2 PAL TRUE 2 Ambos`
		case $opcao in
			1) echo "ntsc" >>  $dir/.dvd_config; res=480;;
			2) echo "pal" >> $dir/.dvd_config; res=576;;
			*) echo "ERRO!"; exit 1;;
		esac

	opcao=`zenity --width=350 --height=250 --title "AVI_DVD" --text "Qual codec você deseja usar para o vídeo?" --list --radiolist --hide-column=2 --column "" --column "" --column "Opções" TRUE 1 LAVC FALSE 2 MPEG2Enc`
		case $opcao in
			1) echo "XDVD" >> $dir/.dvd_config;;
			2) echo "DVD" >> $dir/.dvd_config;;
			*) echo "ERRO!"; exit 1;;
		esac
	
	#### CONFIGURA O VIDEO DEPENDENDO DO CODEC ####
	#### CODEC ESCOLHIDO (LAVC / MPEG2ENC)     ####	
	if [[ $opcao == 1 ]]
	then
		opcao=`zenity --width=350 --height=250 --title "AVI_DVD" --text "Que tipo de codificação você deseja?" --list --radiolist --hide-column=2 --column "" --column "" --column "Opções" TRUE 1 Default FALSE 2 TMPGEnc FALSE 3 Anime`
			case $opcao in
                                1) echo "160 05 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 1f 00 00 00 03 00 00 00 02 00 00 00 01 00 00 00 01 00 00 00 fe ff ff ff 01 00 00 00 fb ff ff ff cd cc 4c 3d 01 00 00 00 0a d7 23 3c 01 00 00 00 00 00 00 3f 00 00 00 3f 00 00 00 00 28 23 00 00 00 00 00 00 0c 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 40 1f 00 00 00 00 00 00 00 00 00 3f 00 00 00 00 00 00 00 3f 00 00 00 00 01 00 00 00 e0 00 00 00 00 00 00 00 00 00 00 00" >> $dir/.dvd_config;;
                                2) echo "160 05 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 1f 00 00 00 03 00 00 00 02 00 00 00 01 00 00 00 01 00 00 00 fe ff ff ff 01 00 00 00 fb ff ff ff cd cc 4c 3d 01 00 00 00 0a d7 23 3c 01 00 00 00 00 00 00 3f 00 00 00 3f 00 00 00 00 28 23 00 00 01 00 00 00 0c 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 40 1f 00 00 00 00 00 00 00 00 00 3f 00 00 00 00 00 00 00 3f 00 00 00 00 01 00 00 00 e0 00 00 00 00 00 00 00 00 00 00 00" >> $dir/.dvd_config;;
				3) echo "160 05 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 1f 00 00 00 03 00 00 00 02 00 00 00 01 00 00 00 01 00 00 00 fe ff ff ff 01 00 00 00 fb ff ff ff cd cc 4c 3d 01 00 00 00 0a d7 23 3c 01 00 00 00 00 00 00 3f 00 00 00 3f 00 00 00 00 28 23 00 00 02 00 00 00 0c 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 40 1f 00 00 00 00 00 00 00 00 00 3f 00 00 00 00 00 00 00 3f 00 00 00 00 01 00 00 00 e0 00 00 00 00 00 00 00 00 00 00 00" >> $dir/.dvd_config;;
                                *) echo "ERRO!"; exit 1;;
                        esac

		opcao=`zenity --width=350 --height=250 --title "AVI_DVD" --text "Que tipo de encode você deseja usar?" --list --radiolist --hide-column=2 --column "" --column "" --column "Opções" TRUE 1 "Video Size" FALSE 2 "Bitrate"`
                case $opcao in
                        1) echo "2PASS" >> $dir/.dvd_config;;
                        2) echo "2PASSBITRATE" >> $dir/.dvd_config;;
                        *) echo "ERRO!"; exit 1;;
                esac
	
	else

		opcao=`zenity --width=350 --height=250 --title "AVI_DVD" --text "Que tipo de codificação você deseja usar?" --list --radiolist --hide-column=2 --column "" --column "" --column "Opções" TRUE 1 "Default" FALSE 2 "TMPGEnc" FALSE 3 "Anime"`
                        case $opcao in
                                1) echo "24 28 23 00 00 0c 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00" >> $dir/.dvd_config;;
                                2) echo "24 28 23 00 00 0c 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00" >> $dir/.dvd_config;;
                                3) echo "24 28 23 00 00 0c 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00" >> $dir/.dvd_config;;
                                *) echo "ERRO!"; exit 1;;
                        esac

		opcao=`zenity --width=350 --height=250 --title "AVI_DVD" --text "Que tipo de encode você deseja usar?" --list --radiolist --hide-column=2 --column "" --column "" --column "Opções" TRUE 1 "Video Size" FALSE 2 "Bitrate" FALSE 3 "Constant Quality"`
                        case $opcao in
                                1) echo "2PASS" >> $dir/.dvd_config;;
                                2) echo "CBR" >> $dir/.dvd_config;;
				3) echo "CQ" >> $dir/.dvd_config;;
                                *) echo "ERRO!"; exit 1;;
                        esac
	fi
	
	opcao=`zenity --width=350 --height=250 --title "AVI_DVD" --text "Que resolução você deseja usar?" --list --radiolist --hide-column=2 --column "" --column "" --column "Opções" TRUE 1 "4:3 (FullScreen)" FALSE 2 "16:9 (WideScreen)"`
		case $opcao in
			1) echo "43" >> $dir/.dvd_config;;
			2) echo "169" >> $dir/.dvd_config;;
			*) echo "ERRO!"; exit 1;;
		esac

	###############
	#### AUDIO ####
	###############

	opcao=`zenity --width=350 --height=250 --title "AVI_DVD" --text "Qual codec você deseja usar?" --list --radiolist --hide-column=2 --column "" --column "" --column "Opções" FALSE 1 "MP2" FALSE 2 "MP2 - TwoLAME" TRUE 3 "AC3"`
		case $opcao in
			1) echo "mp2" >> $dir/.dvd_config;;
			2) echo "twolame" >> $dir/.dvd_config;;
			3) echo "ac3" >> $dir/.dvd_config;;
			*) echo "ERRO!"; exit 1;;
                esac

	opcao=`zenity --width=350 --height=250 --title "AVI_DVD" --text "Qual bitrate você deseja usar?" --list --radiolist --hide-column=2 --column "" --column "" --column "Opções" FALSE 1 "128" FALSE 2 "192" FALSE 3 "224" TRUE 4 "384"`
		case $opcao in
			1) echo "128" >> $dir/.dvd_config;;
			2) echo "192" >> $dir/.dvd_config;;
			3) echo "224" >> $dir/.dvd_config;;
			4) echo "384" >> $dir/.dvd_config;;
			*) echo "ERRO!"; exit 1;;
                esac

	#################
	#### LEGENDA ####
	#################

	opcao=`zenity --width=350 --height=250 --title "AVI_DVD" --text "Qual fonte você deseja usar para legenda?" --list --radiolist --hide-column=2 --column "" --column "" --column "Opções" FALSE 1 "Arial" FALSE 2 "Lucida Sans" TRUE 3 "DejaVu" FALSE 4 "Outro"`
		case $opcao in
                        1) echo "/usr/share/fonts/truetype/msttcorefonts/arial.ttf" >> $dir/.dvd_config;;
                        2) echo "/usr/share/fonts/truetype/ttf-lucida/LucidaSansRegular.ttf" >> $dir/.dvd_config;;
			3) echo "/usr/share/fonts/truetype/ttf-dejavu/DejaVuSansCondensed-Bold.ttf" >> $dir/.dvd_config;;
                        4) echo `zenity --file-selection --title "AVI_DVD - Escolha a fonte que você deseja usar: (/usr/share/fonts/)"` >>  $dir/.dvd_config;;
			*) echo "ERRO!"; exit 1;;
                esac       
 
	opcao=`zenity --width=350 --height=250 --title "AVI_DVD" --text "Qual cor você prefere para a legenda?" --list --radiolist --hide-column=2 --column "" --column "" --column "Opções" FALSE 1 "Branco" TRUE 2 "Amarelo" FALSE 3 "Outro"`
		case $opcao in 
                	1) echo "255,255,255" >> $dir/.dvd_config;;
                        2) echo "255,255,000" >> $dir/.dvd_config;;
                        3) echo `zenity --entry --title "AVI_DVD" --text "Digite o número da cor no formato RGB:" --entry-text "RRR:GGG:BBB"` >> $dir/.dvd_config;;
			*) echo "ERRO!"; exit 1;;
		esac
		
	tam_fonte=`zenity --title "AVI_DVD" --text "Qual tamanho da fonte da legenda?" --scale --value=26`
	echo $tam_fonte >> $dir/.dvd_config


	#### CALCULA POSICAO MAX E IDEAL DA LEGENDA ####
	posicao_max=$(($res -($tam_fonte*3)))
	if [[ $res == 576 ]]
	then
		posicao_inicial=$(($posicao_max - (92 -($tam_fonte*2))))
	else
		posicao_inicial=$(($posicao_max - (44 - $tam_fonte)))
	fi	
				
	zenity --title "AVI_DVD" --text "Qual posicao da legenda? (Quanto maior, mais embaixo)" --scale --min-value=0 --max-value=$posicao_max --value=$posicao_inicial --print-partial >> $dir/.dvd_config

	###############	
	#### MENU: ####
	###############
	
	echo `zenity --width=500 --entry --title "AVI_DVD" --text "Qual o titúlo que você deseja que o menu tenha?"` >> $dir/.dvd_config

	opcao=`zenity --width=350 --height=250 --title "AVI_DVD" --text "Qual fonte você deseja usar para o titulo do Menu?" --list --radiolist --hide-column=2 --column "" --column "" --column "Opções" FALSE 1 "Arial" FALSE 2 "Lucida Sans" TRUE 3 "DejaVu" FALSE 4 "Outro"`
                case $opcao in
                        1) echo "/usr/share/fonts/truetype/msttcorefonts/arial.ttf" >> $dir/.dvd_config;;
                        2) echo "/usr/share/fonts/truetype/ttf-lucida/LucidaSansRegular.ttf" >> $dir/.dvd_config;;
                        3) echo "/usr/share/fonts/truetype/ttf-dejavu/DejaVuSansCondensed-Bold.ttf" >> $dir/.dvd_config;;
                        4) echo `zenity --file-selection --title "AVI_DVD - Escolha a fonte que você deseja usar: (/usr/share/fonts/)"` >>  $dir/.dvd_config;;
                        *) echo "ERRO!"; exit 1;;
                esac

	opcao=`zenity --width=350 --height=250 --title "AVI_DVD" --text "Qual fonte você deseja usar para o Menu?" --list --radiolist --hide-column=2 --column "" --column "" --column "Opções" FALSE 1 "Arial" FALSE 2 "Lucida Sans" TRUE 3 "DejaVu" FALSE 4 "Outro"`
                case $opcao in
                        1) echo "/usr/share/fonts/truetype/msttcorefonts/arial.ttf" >> $dir/.dvd_config;;
                        2) echo "/usr/share/fonts/truetype/ttf-lucida/LucidaSansRegular.ttf" >> $dir/.dvd_config;;
                        3) echo "/usr/share/fonts/truetype/ttf-dejavu/DejaVuSansCondensed-Bold.ttf" >> $dir/.dvd_config;;
                        4) echo `zenity --file-selection --title "AVI_DVD - Escolha a fonte que você deseja usar: (/usr/share/fonts/)"` >>  $dir/.dvd_config;;
                        *) echo "ERRO!"; exit 1;;
                esac

	opcao=`zenity --title "AVI_DVD" --text "Qual a cor da fonte do menu?" --list --radiolist --hide-column=2 --column "" --column "" --column "Opções" TRUE 1 "Branco" FALSE 2 "Amarelo" FALSE 3 "Preto" FALSE 4 "Azul" FALSE 5 "Outro"`
		case $opcao in
                        1) echo "255,255,255" >> $dir/.dvd_config;;
                        2) echo "255,255,000" >> $dir/.dvd_config;;
			3) echo "000,000,000" >> $dir/.dvd_config;;
			4) echo "000,000,255" >> $dir/.dvd_config;;		
			5) echo `zenity --entry --title "AVI_DVD" --text "Digite o número da cor no formato RGB:" --entry-text "RRR:GGG:BBB"` >> $dir/.dvd_config;;
                        *) echo "ERRO!"; exit 1;;
                esac

	zenity --file-selection --title "AVI_DVD - Escolha a imagem que você deseja usar como plano de fundo:" >> $dir/.dvd_config	
	
	#####################
	#### DRIVER DVD: ####
	#####################

	zenity --question --title "AVI_DVD" --text "Você deseja gravar o DVD após a conversão?"
	if [[ $? == 0 ]]
	then
		echo "SIM" >> $dir/.dvd_config
		echo `zenity --entry --title "AVI_DVD" --text "Digite um título para o DVD:"` >> $dir/.dvd_config
	else
		echo "NAO" >> $dir/.dvd_config
		echo "NAO" >> $dir/.dvd_config
	fi

	zenity --info --title "AVI_DVD" --text "Configuração realizada com sucesso\!"

	exit 0
fi
				
#################################################
#   SELECIONA OS VIDEOS QUE SERÃO CONVERTIDOS   #
#################################################
if [[ $# == "0" ]]
then
	args=`zenity --title "AVI_DVD - Selecione os arquivos que você deseja converter" --file-selection --multiple | sed s#\|#" "#g`

	if [[ $args == "" ]]
	then
		exit 1
	fi
		
	zenity --title "AVI_DVD" --question --text "Deseja adicionar mais algum vídeo?"
	while [[ $? == 0 ]]
	do
		args_2=`zenity --title "AVI_DVD - Selecione os arquivos que você deseja converter" --file-selection --multiple | sed s#\|#" "#g`
		args=`echo "$args $args_2"`
		zenity --title "AVI_DVD" --question --text "Deseja adicionar mais algum vídeo?"
	done	
else
	args=$*	
fi	

#################################################
# PEGA AS INFORMACOES: NOME DO FILME E DURACAO  #
#################################################	
num_args=0
for x in $args
do
	num_args=$(($num_args + 1))
       	if [[ -e $x && `echo $x | grep -c .avi` -ge 1 ]]
        then
		filme[$num_args]=filme$num_args

		nome[$num_args]=`zenity --title "AVI_DVD" --entry --text "Qual o nome do filme do arquivo \"$x\"?"`
		
		#### SE ENCONTRAR "." COMO PRIMEIRO CARACTERE ####
		#### SUBSTITUI PELO DIRETORIO CORRENTE        ####
		if [[ `echo $x | grep -c '^\.'` -ge 1 ]]
		then
			dir_atual=`pwd`
			filme_caminho[$num_args]=`echo $x | sed s#^\.\/#$dir_atual/#g | sed s#.avi##g`
		#### SE ENCONTRAR "/home/" NO COMEÇO APENAS   ####
		#### SALVA $x EM FILME_CAMINHO                ####
		elif [[ `echo $x | grep -c '^/home'` -ge 1 ]]
		then
			filme_caminho[$num_args]=`echo $x | sed s#.avi##g`
		#### SENAO, APENAS ADICIONA O DIRETORIO       ####
		#### CORRENTE NO COMECO DO CAMINHO	      ####	
		else
			dir_atual=`pwd`	
			filme_caminho[$num_args]=`echo $dir_atual/$x | sed s#.avi##g`
		fi

		legenda[$num_args]="true"
		if ! [ -e ${filme_caminho[$num_args]}.srt ]
		then
			zenity --title "AVI_DVD" --question --text "O arquivo \"$x\" não possui legenda.\nDeseja continuar?"
			if [[ $? == 0 ]]
			then
				legenda[$num_args]="false"
			else
				exit 1
			fi
		fi
        else
		zenity --title "AVI_DVD" --warning --text "ERRO! O arquivo \"$x\" não existe ou não está no formato \".avi\"."
               	exit 1
        fi
done

#################################################
# LE AS INFORMACOES DO ARQUIVO DE CONFIGURACAO  #
#################################################
i=1
while read x
do
	case $i in
		1) padrao_dvd=$x;;
		2) video_codec=$x;;
		3) video_matriz=$x;;
		4) tipo_encode=$x;;
		5) resolucao=$x;;	
		6) audio_codec=$x;;
		7) audio_bitrate=$x;;
		8) legenda_fonte=$x;;
		9) legenda_cor=$x;;
		10) legenda_tamanho=$x;;
		11) legenda_posicao=$x;;
		12) menu_titulo=$x;;
		13) menu_titulo_fonte=$x;;
		14) menu_fonte=$x;;
		15) menu_fonte_cor=$x;;
		16) menu_imagem=$x;;
		17) grava_dvd=$x;;
		18) titulo_dvd=$x;;
		*) echo "";;
	esac
	i=$(($i + 1))
done < $dir/.dvd_config
						
#################################################
# COLETA AS INFORMAÇÕES RELACIONADAS AO FILME   #
#################################################
duracao_total=0

for ((i=1; i<=$num_args; i=i+1))
do
	avidemux2_cli --nogui --load ${filme_caminho[$i]}.avi --info > $dir/tmp/${filme[$i]}.info 2> $dir/tmp/${filme[$i]}.erro

	total_frames[$i]=`grep -m1 dwTotalFrames $dir/tmp/${filme[$i]}.info | cut -d":" -f3`
	markerb[$i]=$(( ${total_frames[$i]} - 1 ))
	fps[$i]=`grep -m1 fps $dir/tmp/${filme[$i]}.info | cut -d" " -f6 | sed s#,##g`
	if [[ ${fps[$i]} -lt 9999 ]]
	then
		fps[$i]=$(( ${fps[$i]} * 1000 ))
	elif [[ ${fps[$i]} -gt 99999 ]]
	then
		fps[$i]=$(( ${fps[$i]} / 1000 ))
	fi	

	video_x[$i]=`grep -m2 biWidth $dir/tmp/${filme[$i]}.info | cut -d":" -f3`
	video_y[$i]=`grep -m1 biHeight $dir/tmp/${filme[$i]}.info | cut -d":" -f3`

        duracao[$i]=`grep -m1 Duration $dir/tmp/${filme[$i]}.info | cut -d":" -f2 | cut -d"," -f1 | sed s#' '##g`
	duracao_total=$(( $duracao_total + ${duracao[$i]} ))
	
	###############################################
	#           DETECTA OS ERROS NO VIDEO         #
	#  (SE ENCONTRAR O TEXTO UMA OU MAIS VEZES)   #
	###############################################
	if [[ `grep -c "Packed Bitstream detected" $dir/tmp/${filme[$i]}.erro` -ge 1 ]]
	then
		force_unpack[$i]="app.forceUnpack();"
	else
		force_unpack[$i]=""
	fi

        if [[ `grep -c "Index is not up to date" $dir/tmp/${filme[$i]}.erro` -ge 1 ]]
        then
		avidemux --nogui --load ${filme_caminho[$i]}.avi --autoindex --rebuild-index --save $dir/tmp/${filme[$i]}_OK.avi --quit > $dir/tmp/${filme[$i]}_index.log 2> $dir/tmp/${filme[$i]}_index.erro
		cp ${filme_caminho[$i]}.srt $dir/tmp/${filme[$i]}_OK.srt
 	        filme_caminho[$i]="$dir/tmp/${filme[$i]}_OK"
        fi

	if [[ `grep -c "Build Time Map" $dir/tmp/${filme[$i]}.erro` -ge 1 ]]
        then
                build_time_map[$i]="app.audio.scanVBR();"
        else
                build_time_map[$i]=""
        fi
done

#################################################
# TESTA SE A DURACAO TOTAL É MUITO GRANDE       #
# SE FOR, PERGUNTA SE CONTINUA OU NAO           # 		
#################################################
if [[ $duracao_total -ge 12000 ]]
then
	zenity --title "AVI_DVD" --question --text "A duracao total dos filmes é muito grande.\nDeseja continuar?"
	if [[ $? == 1 ]]
	then
               	exit 1
	fi
fi
						
#################################################
# CONVERTE O FORMATO DA COR DA LEGENDA          #
#           (RGB -> YUV)                        #
#################################################
rgb_r=`echo $legenda_cor | cut -d"," -f1`
rgb_g=`echo $legenda_cor | cut -d"," -f2`
rgb_b=`echo $legenda_cor | cut -d"," -f3`

yuv_y=$((((299 * $rgb_r) + (587 * $rgb_g) + (114 * $rgb_b)) / 1000))
yuv_u=$((((500 * $rgb_r) - (419 * $rgb_g) - (81 * $rgb_b)) / 1000))
yuv_v=$((((-169 * $rgb_r) - (331 * $rgb_g) + (500 * $rgb_b)) / 1000))

#################################################
# CALCULA OS VALORES NECESSARIOS PARA           #
# A CONVERSAO, DEPENDENDO DO TIPO               #
#################################################
caminho_projeto="$dir/tmp/"

for ((i=1; i<=$num_args; i=i+1))
do
	#### CONVERTE PAL->NTSC / NTSC->PAL ####
	#### PADRAO    /   FPS              ####
	#### NTSC      /   29970-23976      ####
	#### PAL       /   25000	    ####				
	if [[ $padrao_dvd == "ntsc" ]]
	then
		if [[ ${fps[$i]} == 25000 ]]
		then
			resample_fps_video[$i]="app.video.addFilter(\"resamplefps\",\"newfps=29970\",\"use_linear=0\");"
			#resample_fps_audio[$i]="app.audio.pal2film=true;"
		else
			resample_fps_video[$i]=""
			#resample_fps_audio[$i]=""
		fi
	else
		if [[ ${fps[$i]} != 25000 ]]
                then
                        fps_resample_video[$i]="app.video.addFilter(\"resamplefps\",\"newfps=25000\",\"use_linear=0\");"
			#fps_resample_audio[$i]="app.audio.film2pal=true;"
                else
                        fps_resample_video[$i]=""
			#fps_resample_audio[$i]=""
                fi
	fi

	if [[ `grep "Audio codec" $dir/tmp/${filme[$i]}.info | cut -d":" -f2 | tr -d " "` == 'AC3'
                && `grep "Frequency" $dir/tmp/${filme[$i]}.info | cut -d":" -f2 | cut -d" " -f2` == 48000 ]]
        then
                temp=`grep BitRate $dir/tmp/${filme[$i]}.info | cut -d"/" -f2 | cut -d" " -f2`
                audio_tamanho[$i]=$(((($temp * 71) * ${duracao[$i]}) / 600000))
                audio_comando[$i]="app.audio.codec(\"copy\",128,0,\"\");"
		audio_resample[$i]=""
        else
		if [[ $audio_codec == "twolame" ]]
		then
			audio_comando[$i]="app.audio.codec(\"$audio_codec\",$audio_bitrate,4,\"01 00 00 00\");"
                        audio_resample[$i]="app.audio.resample=48000;"
                        audio_tamanho[$i]=$(((($audio_bitrate * 71) * ${duracao[$i]}) / 600000))
		else
	                audio_comando[$i]="app.audio.codec(\"$audio_codec\",$audio_bitrate,0,\"\");"
			audio_resample[$i]="app.audio.resample=48000;"
                	audio_tamanho[$i]=$(((($audio_bitrate * 71) * ${duracao[$i]}) / 600000))
		fi
        fi

	if [[ $tipo_encode == '2PASS' ]]
        then	
		### VALOR = VIDEO TAMANHO ###
		tamanho_total[$i]=$(((4300 * ${duracao[$i]}) / $duracao_total ))
		valor_conversao[$i]=$((((${tamanho_total[$i]} - ${audio_tamanho[$i]}) * 9785 ) / 10000))
        elif [[ $tipo_encode == '2PASSBITRATE' || $tipo_encode == 'CBR' ]]
       	then
		### VALOR = BITRATE ###
		tamanho_total[$i]=$(((4300 * ${duracao[$i]}) / $duracao_total ))
    	        video_tamanho[$i]=$((((${tamanho_total[$i]} - ${audio_tamanho[$i]}) * 9785 ) / 10000))
		valor_conversao[$i]=$((( ${video_tamanho[$i]} * 8382) / ${duracao[$i]}))
		if [[ ${valor_conversao[$i]} -ge 9000 ]]
		then
			valor_conversao[$i]=9000
		fi
        else
       		#### VALOR = CONSTANT_QUALITY ####
		valor_conversao[$i]=4
	fi

	#### CONFIGURA A RESOLUCAO DO VIDEO CONFORME ####
	#### O PADRAO DE DVD E RESOLUCAO DA TV       ####
	
	#### PADRAO    /  RESOLUCAO ####
	#### NTSC      /  720x480   ####
	#### PAL       /  720x576   ####

	if [[ $resolucao == 43 ]]
	then
		if [[ $padrao_dvd == "ntsc" ]]
	        then
        	        res_y_final=480
	        else
        	        res_y_final=576
	        fi	

		#### RESOLUCAO FINAL NÃO PODE SER IMPAR ####
		resolucao_x[$i]=720
	        resolucao_y[$i]=$(((720 * ${video_y[$i]}) / ${video_x[$i]}))

		if [[ ${resolucao_y[$i]} -gt $res_y_final ]]
                then
                        resolucao_y[$i]=$res_y_final
                fi		
		
		if [[ $(( ${resolucao_y[$i]} % 2 )) == 1 ]]
		then
			resolucao_y[$i]=$(( ${resolucao_y[$i]} + 1 ))
		fi

		#### VALOR BLACK NÃO PODE SER IMPAR ####
		black_top[$i]=$((($res_y_final - ${resolucao_y[$i]}) / 2))
		if [[ $(( ${black_top[$i]} % 2 )) == 1 ]]
		then	
			resolucao_y[$i]=$(( ${resolucao_y[$i]} + 2 ))
			black_top[$i]=$(( ${black_top[$i]} - 1 ))
		fi

		black_bottom[$i]=${black_top[$i]}
		black_left[$i]=0
		black_right[$i]=0
	else
		if [[ $padrao_dvd == "NTSC" ]]
                then
			res_x_prop=833
                        res_y_final=480
                else
			res_x_prop=1024
                        res_y_final=576
                fi

		#### RESOLUCAO FINAL NÃO PODE SER IMPAR ####
                resolucao_x[$i]=720
                resolucao_y[$i]=$((($res_x_prop * ${video_y[$i]}) / ${video_x[$i]}))

		if [[ ${resolucao_y[$i]} -gt $res_y_final ]]
		then
			resolucao_y[$i]=$res_y_final
		fi
		
		if [[ $(( ${resolucao_y[$i]} % 2 )) == 1 ]]
                then
                        resolucao_y[$i]=$(( ${resolucao_y[$i]} + 1 ))
		fi

                #### VALOR BLACK NÃO PODE SER IMPAR ####
                black_top[$i]=$((($res_y_final - ${resolucao_y[$i]}) / 2))
                if [[ $(( ${black_top[$i]} % 2 )) == 1 ]]
                then
                        resolucao_y[$i]=$(( ${resolucao_y[$i]} + 2 ))
                        black_top[$i]=$(( ${black_top[$i]} - 1 ))
                fi

                black_bottom[$i]=${black_top[$i]}
                black_left[$i]=0
                black_right[$i]=0
	fi

	if [[ ${legenda[$i]} == "true" ]]
	then
		comando_legenda[$i]="app.video.addFilter(\"subtitle\",\"_fontsize=$legenda_tamanho\",\"_subname=${filme_caminho[$i]}.srt\",\"_fontname=$legenda_fonte\",\"_charset=ISO-8859-1\",\"_baseLine=$legenda_posicao\",\"_Y_percent=$yuv_y\",\"_U_percent=$yuv_u\",\"_V_percent=$yuv_v\",\"_selfAdjustable=0\",\"_delay=0\",\"_useBackgroundColor=0\",\"_bg_Y_percent=0\",\"_bg_U_percent=0\",\"_bg_V_percent=0\",\"_blend=1\");"
	else
		comando_legenda[$i]=""
	fi
done

#################################################
# CRIA O ARQUIVO FILME[]_DECODER.JS COM AS      #
# INFORMACOES OBTIDAS E FAZ A CONVERSAO	        #
#################################################
for ((i=1; i<=$num_args; i=i+1))
do
echo -e "//AD  <- Needed to identify//
//--automatically built--
//--Project: $caminho_projeto${filme[$i]}_decoder.js

var app = new Avidemux();

//** Video **
// 01 videos source 
${force_unpack[$i]}
app.load(\"${filme_caminho[$i]}.avi\");
//01 segments
app.clearSegments();
app.addSegment(0,0,${total_frames[$i]});
app.markerA=0;
app.markerB=${markerb[$i]};

//** Postproc **
app.video.setPostProc(3,3,0);

app.video.setFps1000(${fps[$i]});

//** Filters **
app.video.addFilter(\"mpresize\",\"w=${resolucao_x[$i]}\",\"h=${resolucao_y[$i]}\",\"algo=0\");
app.video.addFilter(\"addblack\",\"left=${black_left[$i]}\",\"right=${black_right[$i]}\",\"top=${black_top[$i]}\",\"bottom=${black_bottom[$i]}\");
${comando_legenda[$i]}
${fps_resample_video[$i]}

//** Video Codec conf **
app.video.codec(\"$video_codec\",\"$tipo_encode=${valor_conversao[$i]}\",\"$video_matriz \");

//** Audio **
app.audio.reset();
${audio_comando[$i]}
app.audio.normalizeMode=0;
app.audio.normalizeValue=0;
app.audio.delay=0;
app.audio.mixer(\"NONE\");
${build_time_map[$i]}
${audio_resample[$i]}
app.setContainer(\"PS\");
setSuccess(1);
//app.Exit();

//End of script
" > $dir/tmp/${filme[$i]}_decoder.js	

avidemux2_cli --nogui --run $dir/tmp/${filme[$i]}_decoder.js --output-format PS --save $dir/tmp/${filme[$i]}.mpeg --quit >$dir/tmp/${filme[$i]}_conversao.log 2>$dir/tmp/processo &

pid_avidemux=`ps aux | grep -m1 avidemux2_cli | grep ${filme[$i]}_decoder.js | tr -s " " | cut -d" " -f2`

tail -f --pid=$pid_avidemux ~/.dvd/tmp/processo | awk -vRS="\r" -v filme=${filme_caminho[$i]}.avi \
        '/Encoding Phase/ {
		x=1; 
		while ($x !~ /Pass/) 
			x++; 
		passo=$(x+1)
	}
	$1 ~ /Done/ {
	        gsub("Done:","");
        	gsub("%","");
		print $1"\n#Convertendo: "filme"\\nPasso: "passo"\\nCompleto: "$1"%\\nTempo Restante: "$5;
        	fflush();
        }' | zenity --width=500 --title "AVI_DVD" --progress --auto-close

if [[ $? == 1 || `grep -c Error $dir/tmp/processo` -ge 1 ]]
then
	kill -9 $pid_avidemux 2>/dev/null

	zenity --title "AVI_DVD" --question --text "Ocorreu um erro durante a conversão.\nDeseja ver o log?"
        if [[ $? == 0 ]]
        then
                zenity --title "AVI_DVD" --width=640 --height=480 --text-info --filename $dir/tmp/processo
                zenity --title "AVI_DVD" --width=640 --height=480 --text-info --filename $dir/tmp/${filme[$i]}\_decoder.js
		zenity --title "AVI_DVD" --width=640 --height=480 --text-info --filename $dir/tmp/${filme[$i]}\_conversao.log
        fi

	rm -r $dir/tmp/*
	exit 1
fi
done

#################################################
# OBTEM AS INFORMACOES NECESSARIAS PARA A       #
# CRIACAO DO MENU                               #
#################################################
titulo_filme="\"${nome[1]}\""
nome_mpeg="\"$dir/tmp/${filme[1]}.mpeg\""

for ((i=2; i<=$num_args; i=i+1))
do
       titulo_filme="$titulo_filme \"${nome[$i]}\""
       nome_mpeg="$nome_mpeg \"$dir/tmp/${filme[$i]}.mpeg\""
done

driver_dvd="/dev/`dmesg | grep dvd | grep writer | tr -d " " | cut -d"]" -f2 | cut -d":" -f1`"

if [[ $grava_dvd == "SIM" ]]
then
        makedvd="makedvd -quiet -device $driver_dvd -label $titulo_dvd -burn $dir/tmp/DVD_FILME.xml"
else
        makedvd="makedvd -quiet -author $dir/tmp/DVD_FILME.xml"
fi

#################################################
# CRIA O ARQUIVO MENU.CONFIG COM AS             #
# INFORMACOES OBTIDAS                           #
#################################################
echo -e "
makemenu -noask -quiet -overwrite -$padrao_dvd -dvd -align northwest -menu-title \"$menu_titulo\" -menu-title-fontsize 32 -background \"$menu_imagem\" -font \"$menu_titulo_fonte\" -fontsize 24 -textcolor \"rgb($menu_fonte_cor)\" -fontdeco '-stroke rgb(0,0,0) -strokewidth 1' -button-font \"$menu_fonte\" -button \">\" -highlightcolor \"rgb(255,255,0)\" -selectcolor \"rgb(255,0,0)\" -button-outline \"rgb(140,140,140)\" $titulo_filme -out \"$dir/tmp/DVD_MENU\"
makexml -quiet -overwrite -dvd -menu \"$dir/tmp/DVD_MENU.mpg\" $nome_mpeg -out \"$dir/tmp/DVD_FILME\"
$makedvd
" > $dir/tmp/menu.config

#################################################
#       CRIA O MENU E A ESTRUTURA DO DVD        #
#################################################
chmod 777 $dir/tmp/menu.config
$dir/tmp/menu.config 2> $dir/tmp/menu.erro | tee > $dir/tmp/menu.log >(awk '
	$2 ~ /Processing/ {
		print "#Processando: "$3;
		fflush();
	} 
	$2 ~ /done/ {
		gsub("%","");
		print $1"\n#Gravando o DVD...Tempo Restante"$8; 
		fflush();
	} 
	/Trying/ && $4 ~ /[12345]/ {
		RS="\r"; 
		print "#Insira um DVD.\\nTentando denovo em: "$4"s";
		fflush();
	}' | zenity --progress --pulsate --title "AVI_DVD" --text "Criando o menu..." --auto-close)

if [[ $? == 1 ]]
then
	zenity --title "AVI_DVD" --question --text "Ocorreu um erro durante a criação do menu.\nDeseja ver o log?"
	if [[ $? == 0 ]]
	then
		zenity --title "AVI_DVD" --width=640 --height=480 --text-info --filename $dir/tmp/menu.config
		zenity --title "AVI_DVD" --width=640 --height=480 --text-info --filename $dir/tmp/menu.log
		zenity --title "AVI_DVD" --width=640 --height=480 --text-info --filename $dir/tmp/menu.erro
	fi
	
	rm -r $dir/tmp/*
	exit 1
fi
										
#################################################
# FINALIZA E REMOVE OS ARQUIVOS TEMPORARIOS     #
#################################################
if [[ $grava_dvd == "SIM" ]]
then
	zenity --title "AVI_DVD" --info --text "DVD criado com sucesso\!"
	
	zenity --title "AVI_DVD" --question "Deseja deletar os arquivos convertidos?"
	if [[ $? == 0 ]]
	then
		rm -r $dir/tmp/*
	else
		dir_dvd="DVD_FILME"
	        if [ -e ~/"$dir_dvd" ]
        	then
                	i=1
	                dir_dvd="DVD_FILME_$i"
        	        while [ -e ~/"$dir_dvd" ]
                	do
                        	i=$(($i + 1))
	                        dir_dvd="DVD_FILME_$i"
        	        done
                	mkdir ~/$dir_dvd
	        else
        	        mkdir ~/$dir_dvd
	        fi

        	mv $dir/tmp/DVD_FILME/* ~/$dir_dvd
	        rm -r $dir/tmp/*
	fi
else
	dir_dvd="DVD_FILME"
	if [ -e ~/"$dir_dvd" ]
	then
        	i=1
	        dir_dvd="DVD_FILME_$i"
        	while [ -e ~/"$dir_dvd" ]
	        do
        	        i=$(($i + 1))
                	dir_dvd="DVD_FILME_$i"
	        done
        	mkdir ~/$dir_dvd
	else
        	mkdir ~/$dir_dvd
	fi

	mv $dir/tmp/DVD_FILME/* ~/$dir_dvd
	rm -r $dir/tmp/*

	zenity --title "AVI_DVD" --info --text "DVD criado com sucesso\!\nAgora utilize seu programa de gravação preferido para gravar a pasta \"~/$dir_dvd\" em DVD."
fi

exit 0
