Skip to content

Instantly share code, notes, and snippets.

@y4my4my4m
Created September 9, 2023 07:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save y4my4my4m/5c35c59e20fd88d1fe67ff2778204a75 to your computer and use it in GitHub Desktop.
Save y4my4my4m/5c35c59e20fd88d1fe67ff2778204a75 to your computer and use it in GitHub Desktop.
FFmpeg compress to filesize
#!/bin/bash
if [ "$#" -lt 2 ]; then
echo "Usage: $0 <input_file> <output_file> [target_size_MB]"
exit 1
fi
input="$1"
output="$2"
target_size=${3:-20} # Default to 20MB if not specified
# Get the duration of the video in seconds
duration=$(ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "$input")
# Calculate the bitrate to achieve the target size
bitrate=$(echo "$target_size*1024*1024*8/$duration" | bc)
# Determine the format from the output file extension and set codecs accordingly
case "${output##*.}" in
webm)
video_codec="libvpx-vp9" # Using VP9 for WebM
audio_codec="libvorbis"
hwaccel="-c:v h264_cuvid"
;;
mp4)
video_codec="h264_nvenc"
audio_codec="aac"
hwaccel="-c:v h264_cuvid"
;;
*)
echo "Unsupported format. Only webm and mp4 are supported."
exit 1
;;
esac
# Convert the video using the calculated bitrate and the determined codecs
ffmpeg $hwaccel -i "$input" -c:v $video_codec -b:v ${bitrate} -c:a $audio_codec "$output"
@y4my4my4m
Copy link
Author

It uses hardware acceleration so you need CUDA!

Usage:
ffmpeg input.mp4 output.mp4 49 to keep it under 50mb

you can also do it mp4 to webm, but it's slow (probably a bug/bad config) I recommend converting to mp4 first then using that to make it a webm.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment