Created
September 9, 2023 07:06
-
-
Save y4my4my4m/5c35c59e20fd88d1fe67ff2778204a75 to your computer and use it in GitHub Desktop.
FFmpeg compress to filesize
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It uses hardware acceleration so you need CUDA!
Usage:
ffmpeg input.mp4 output.mp4 49
to keep it under 50mbyou 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.