Skip to content

Instantly share code, notes, and snippets.

@ioggstream
Created August 30, 2026 14:31
Show Gist options
  • Select an option

  • Save ioggstream/38fc9569b673f9b56bf1ec5abdb98c95 to your computer and use it in GitHub Desktop.

Select an option

Save ioggstream/38fc9569b673f9b56bf1ec5abdb98c95 to your computer and use it in GitHub Desktop.
Compress mp4 video
#!/usr/bin/bash
# ffmpeg script to compress video files,
# taken from https://unix.stackexchange.com/questions/28803/how-can-i-reduce-a-videos-size-with-ffmpeg
#
# USAGE
# compress-mp4.sh INPUT OUTPUT [SUFFIX]
#
# ARGUMENTS
# INPUT Path to the source video file (any format ffmpeg can read).
# OUTPUT Path for the compressed output file.
# SUFFIX Optional label appended before the extension of OUTPUT.
# When provided the script rewrites the output filename as:
# <basename>-<SUFFIX>.<ext>
# and skips compression if INPUT already ends with -<SUFFIX>.<ext>
# (useful for idempotent batch loops).
#
# EXAMPLES
# # Basic 720p compression
# compress-mp4.sh recording.mp4 recording-small.mp4
#
# # With suffix: writes recording-720p.mp4
# compress-mp4.sh recording.mp4 recording.mp4 720p
#
# # Re-running with the same suffix is a no-op (input already has the suffix)
# compress-mp4.sh recording-720p.mp4 recording.mp4 720p
#
# FFMPEG SETTINGS
# Codec : libx265 (H.265/HEVC) — ~40-50 % smaller than H.264 at equal quality
# CRF : 28 (x265 default; lower = better quality/larger file; range 0-51)
# Preset : medium (speed/compression tradeoff; slower = smaller file)
# Audio : copied without re-encoding (-c:a copy)
# Scale : 720p height, width auto-calculated and rounded to nearest even number
# (-vf "scale=-2:720")
#
# TIPS
# • Lower CRF (e.g. 24) for higher quality; raise it (e.g. 32) for smaller files.
# • Change -preset to 'slow' or 'veryslow' for better compression at the cost of time.
# • Remove -vf scale if you want to keep the original resolution.
# • Use -c:a aac -b:a 128k instead of -c:a copy to also compress audio.
if [[ "${1:-}" == "-h" || "${1:-}" == "--help" || $# -lt 2 ]]; then
sed -n '/^# USAGE/,/^[^#]/{ /^[^#]/d; s/^# \?//; p }' "$0"
[[ $# -lt 2 ]] && exit 1
exit 0
fi
outfile="${2}"
if [ -n "$3" ]; then
extension="${outfile##*.}"
filename="${outfile%.*}"
outfile="${filename}-${3}.${extension}"
if [[ "${1}" == *"${3}.${extension}" ]]; then
echo "Input file already ends with ${3}, skipping compression"
exit 0
fi
fi
if [ -f "${outfile}" ]; then
echo "File exists: ${outfile}"
exit 1
fi
ffmpeg -i "${1}" -c:v libx265 -crf 28 -preset medium -c:a copy -vf "scale=-2:720" "${outfile}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment