dotfiles/dotfiles/bin/convert-video-to-mp4

97 lines
2.5 KiB
Bash

#!/usr/bin/env bash
# This is for reencoding a non-mp4 video to mp4 using an mpeg4 encoder.
# Can optionally compress the video.
if which tput >/dev/null 2>&1; then
ncolors=$(tput colors)
fi
if [ -t 1 ] && [ -n "$ncolors" ] && [ "$ncolors" -ge 8 ]; then
RED="$(tput setaf 1)"
GREEN="$(tput setaf 2)"
YELLOW="$(tput setaf 3)"
BLUE="$(tput setaf 4)"
MAGENTA="$(tput setaf 5)"
CYAN="$(tput setaf 6)"
BOLD="$(tput bold)"
NORMAL="$(tput sgr0)"
else
RED=""
GREEN=""
YELLOW=""
BLUE=""
MAGENTA=""
CYAN=""
BOLD=""
NORMAL=""
fi
compress="$1"
filename="$2"
output_name="$3"
bitrate="$4"
if [[ $compress == "" || $filename == "" || $output_name == "" ]]; then
printf "${BOLD}${RED}Usage: convert-video-to-mp4 <compress 1|0> <filename> <output name> <optional: bitrate, e.g. \"4000k\", defaults to source>${NORMAL}\n"
exit 1
fi
filename=$(basename -- "$filename")
extension="${filename##*.}"
extension="${extension,,}" # go lower-case
filename="${filename%.*}"
output="$output_name.mp4"
bitrate_args=""
if [[ $compress -eq 1 ]]; then
temp_output="temp_$output"
else
temp_output="$output"
fi
# convert first.
# we convert then compress instead of compressing on first pass because this results in a slightly higher bitrate.
cmd=""
if [[ $extension == "mkv" || $extension == "mpg" ]]; then
if [[ $bitrate != "" ]]; then
bitrate_args="-b:v $bitrate"
else
bitrate="<source value>"
fi
cmd="ffmpeg -y -stats -loglevel level+error -i \"$filename.$extension\" -vcodec copy -acodec copy $bitrate_args \"$temp_output\""
elif [[ $extension == "flv" ]]; then
if [[ $bitrate == "" ]]; then
bitrate="5M"
fi
bitrate_args="-b:v $bitrate"
cmd="ffmpeg -y -stats -loglevel level+error -vsync 0 -hwaccel cuvid -c:v h264_cuvid -i \"$filename.$extension\" -c:a aac -c:v h264_nvenc $bitrate_args \"$temp_output\""
elif [[ $extension == "avi" || $extension == "wmv" ]]; then
cmd="ffmpeg -y -stats -loglevel level+error -i \"$filename.$extension\" -c:a aac -c:v mpeg4 $bitrate_args \"$output\""
else
printf "${BOLD}${RED}Don't know how to convert a '$extension' to mp4. Add support!${NORMAL}\n"
exit 1
fi
printf "\n${YELLOW}${BOLD}Encoding '$filename.$extension' | compress: $compress | output: $output | bitrate: $bitrate${NORMAL}\n"
eval "$cmd"
if [[ $compress -eq 1 ]]; then
compress-video 1 "$temp_output" "$output"
rm "$temp_output"
else
printf "\n"
fi
printf "${GREEN}${BOLD}Done encoding '$filename.$extension' to '$output'${NORMAL}\n\n"