Skip to content

Instantly share code, notes, and snippets.

@fabriziogiordano
Forked from trvswgnr/compress_video
Last active August 22, 2024 16:08
Show Gist options
  • Save fabriziogiordano/b69e86c6bdd06973ab1e765b1ea032db to your computer and use it in GitHub Desktop.
Save fabriziogiordano/b69e86c6bdd06973ab1e765b1ea032db to your computer and use it in GitHub Desktop.
portable shell script to compress videos with ffmpeg
#!/bin/sh
print_usage() {
echo "usage: compress_video <input_file> [half]"
echo "supported formats: mp4, webm, mkv, mov, avi, flv"
echo "[half] is an optional argument to scale the video to half the width and height"
}
get_extension() {
f="${1##*/}"
case "$f" in
.*) get_extension "${f#.}" && return 0 ;;
esac
case "$f" in
.*.*) echo "${f#.}" ;;
*.*) echo "${f#*.}" ;;
*) return 0 ;;
esac
}
get_filepath_without_extension() {
ext=$(get_extension "$1")
echo "${1%."$ext"}"
}
if [ $# -lt 1 ] || [ $# -gt 2 ]; then
echo "ERROR: input file is required"
print_usage
exit 1
fi
input_file="$1"
scale_option="$2"
if [ ! -f "$input_file" ]; then
echo "ERROR: input file '$input_file' does not exist"
exit 1
fi
input_file_ext="$(get_extension "$input_file")"
output_file="$(get_filepath_without_extension "$input_file")_compressed.$input_file_ext"
# Default to libx264 and aac for unknown formats
vcodec="libx264"
acodec="aac"
format_opt=""
scale_filter=""
# Check for scaling option
if [ "$scale_option" = "half" ]; then
scale_filter="-vf scale=iw/2:ih/2"
fi
case $input_file_ext in
mp4)
vcodec="libx264"
acodec="aac"
;;
mov)
vcodec="libx264"
acodec="aac"
format_opt="-f mov"
;;
webm)
vcodec="libvpx-vp9"
acodec="libopus"
;;
mkv)
vcodec="libx265"
acodec="libopus"
;;
avi|flv)
vcodec="libx264"
acodec="aac"
format_opt="-f mp4"
output_file="$(get_filepath_without_extension "$input_file")_compressed.mp4"
;;
*)
echo "WARNING: unsupported video format - trying with default codecs"
;;
esac
echo "compressing video. this could take a while..."
if ffmpeg -i "$input_file" $scale_filter -c:v $vcodec -crf 23 -preset medium -c:a $acodec $format_opt "$output_file"; then
echo "compression completed successfully"
echo "output file: $output_file"
else
echo "ERROR: compression failed"
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment