#!/bin/bash
#
# Purpose: Use ffmpeg to normalize ".mp3" audio files to bring them up to max volume,
# if they at first have negative db volume. Doesn't process them if not. 
# Keeps bitrate same as source files.
#
INPUTDIR=/mnt/usb/Compartilhada/mp3
OUTPUTDIR=/tmp/mp3-novo
#
IFS=$(echo -en "\n\b")
#
# Regular Colors
Black='\e[0;30m'  # Black
Red='\e[0;31m'    # Red
Green='\e[0;32m'  # Green
Yellow='\e[0;33m' # Yellow
Blue='\e[0;34m'   # Blue
Purple='\e[0;35m' # Purple
Cyan='\e[0;36m'   # Cyan
White='\e[0;37m'  # White
# Bold
BBlack='\e[1;30m'  # Black
BRed='\e[1;31m'    # Red
BGreen='\e[1;32m'  # Green
BYellow='\e[1;33m' # Yellow
BBlue='\e[1;34m'   # Blue
BPurple='\e[1;35m' # Purple
BCyan='\e[1;36m'   # Cyan
BWhite='\e[1;37m'  # White
#
if [[ -d ${OUTPUTDIR} ]]; then
    echo -e "Diretorio$BGreen ja Existe!$BWhite"
else
    echo -e "Diretorio$BRed Não Existe!$BWhite Criando.: $BGreen$OUTPUTDIR"
    mkdir $OUTPUTDIR
fi
#
function normalizeAudioFile {

    DBLEVEL=`ffmpeg -i $1 -af "volumedetect" -f null /dev/null 2>&1 | grep max_volume | awk -F': ' '{print $2}' | cut -d' ' -f1`

    # We're only going to increase db level if max volume has negative db level.
    # Bash doesn't do floating comparison directly
    COMPRESULT=`echo ${DBLEVEL}'<'0 | bc -l`
    if [ ${COMPRESULT} -eq 1 ]; then
        DBLEVEL=`echo "-(${DBLEVEL})" | bc -l`
        BITRATE=`ffmpeg -i $1 2>&1 | grep Audio | awk -F', ' '{print $5}' | cut -d' ' -f1`

        echo -e "DBLEVEL.: $BYellow$DBLEVEL$BWhite"
        echo -e "BITRATE.: $BBlue$BITRATE$BWhite"

        ffmpeg -loglevel quiet -i $1 -af "volume=${DBLEVEL}dB" -c:a libmp3lame -ac 2 -b:a 128k -ar 44100 $2
    else
        echo -e "$BRed Ja esta no Nivel de db!$BWhite $DBLEVEL$BGreen Copiando o Mesmo Arquivo!$BWhite"
        cp $1 $2
    fi
}

for inputFilePath in ${INPUTDIR}/*; do
    inputFile=$(basename $inputFilePath)
    echo -e "Processando o Arquivo.: \033[01;32m$inputFile\033[01;37m"
    outputFilePath=${OUTPUTDIR}/$inputFile
    normalizeAudioFile ${inputFilePath} ${outputFilePath}
done
