#! /bin/bash ################################################################################# # File Name : media_converter.sh # Created By : jguer # Creation Date : [2016-06-15 20:31] # Last Modified : [2016-08-17 20:54] # Description : Jguer's media defaults for conversion ################################################################################# readonly WORK_DIR="$(dirname "$(readlink -f "$0")")" readonly OUTPUT_FOLDER=$(date +%Y-%m-%d-%H) # Usage Function function usage() { cat <<_EOT_ Usage: $0 -m mediatype -i extension [-d target_directory] Description: Converts files to more convenient format Options: -m audio|video|pic-lossy|pic-loss -i input extension -d target directory -h display help _EOT_ exit 1 } function validate_filetype() { local _input=$1 local _message=$2 count=$(find ./*."$_input" 2>/dev/null | wc -l) if [ "$count" = 0 ]; then echo "$_message" 1>&2 exit 1 fi } function validate_folder() { local _foldername=$1 local _message=$2 if [ ! -d "$_foldername" ]; then echo "$_message" 1>&2 exit 1 fi return 0 } # Main ## check options and arguments if [ $# = 0 ]; then usage exit 1 fi if [ "$OPTIND" = 1 ]; then while getopts m:i:d:h OPT do case $OPT in m) readonly MEDIA=$OPTARG ;; i) readonly INPUT=$OPTARG ;; d) readonly FOLDERNAME=$OPTARG validate_folder "$FOLDERNAME" "No such folder: '${FOLDERNAME}'" ;; h) usage ;; \?) echo "Try to enter the h option" 1>&2 ;; esac done else echo "No installed getopts-command" 1>&2 exit 1 fi shift $((OPTIND - 1)) if [[ -z $MEDIA || -z $INPUT ]]; then echo "No specify argument(s) of -m option or -i option" 1>&2 exit 1 fi ## main if [ ! -z "$FOLDERNAME" ]; then cd "$FOLDERNAME" || exit fi validate_filetype "$INPUT" "No files of selected extension" if [ ! -d "$OUTPUT_FOLDER" ]; then mkdir "$OUTPUT_FOLDER" fi i=0 echo -ne 'Progress '"$i"/"$count"' \r' for FILE in *."$INPUT"; do case "$MEDIA" in audio) output="m4a" ffmpeg -loglevel panic -i "$FILE" -c:a aac -q:a 2 -vn "${OUTPUT_FOLDER}/${FILE/%"$INPUT"/m4a}"; ;; video) output="mkv" subtitle=${FILE/%"$INPUT"/srt} if [ -e "$subtitle" ]; then ffmpeg -hide_banner -loglevel panic -i "$FILE" -f srt -i "$subtitle" -c:v libx265 -preset medium -x265-params crf=26 -c:a aac -strict experimental -b:a 128k -metadata:s:s:0 language=en "${OUTPUT_FOLDER}/${FILE/%"$INPUT"/mkv}" else ffmpeg -hide_banner -loglevel panic -i "$FILE" -c:v libx265 -preset medium -x265-params crf=28 -c:a aac -strict experimental -b:a 128k "${OUTPUT_FOLDER}/${FILE/%"$INPUT"/mkv}" fi ;; pic-lossy) output="webp" cwebp -quiet -q 90 "$FILE" -o "${OUTPUT_FOLDER}/${FILE/%"$INPUT"/$output}" ;; pic-loss) output="webp" cwebp -quiet -lossless "$FILE" -o "${OUTPUT_FOLDER}/${FILE/%"$INPUT"/$output}" ;; *) echo "Invalid Media Mode" ;; esac ((i++)) echo -ne 'Progress '"$i"/"$count"' \r' if [ "$i" = "$count" ]; then echo -ne '\n' fi done