Created
December 1, 2020 02:04
-
-
Save Luxter77/452fbd32f01094ea717af44e967d5bd5 to your computer and use it in GitHub Desktop.
use ffmpeg to compress video to a specific size in MB
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 [ "$#" -ne 2 ]; then | |
echo "You must enter exactly 2 command line arguments" | |
echo "Usage: "`basename "$0"`" video [target size in mb]" | |
exit | |
fi | |
target_video_size_MB="$2" | |
origin_duration_s=$(ffprobe -v error -show_streams -select_streams a "$1" | grep -Po "(?<=^duration\=)\d*\.\d*") | |
origin_audio_bitrate_kbit_s=$(ffprobe -v error -pretty -show_streams -select_streams a "$1" | grep -Po "(?<=^bit_rate\=)\d*\.\d*") | |
target_audio_bitrate_kbit_s=$origin_audio_bitrate_kbit_s # TODO for now, make audio bitrate the same | |
target_video_bitrate_kbit_s=$(\ | |
awk \ | |
-v size="$target_video_size_MB" \ | |
-v duration="$origin_duration_s" \ | |
-v audio_rate="$target_audio_bitrate_kbit_s" \ | |
'BEGIN { print ( ( size * 8192.0 ) / ( 1.048576 * duration ) - audio_rate ) }') | |
ffmpeg \ | |
-y \ | |
-i "$1" \ | |
-c:v libx264 \ | |
-b:v "$target_video_bitrate_kbit_s"k \ | |
-pass 1 \ | |
-an \ | |
-f mp4 \ | |
/dev/null \ | |
&& \ | |
ffmpeg \ | |
-i "$1" \ | |
-c:v libx264 \ | |
-b:v "$target_video_bitrate_kbit_s"k \ | |
-pass 2 \ | |
-c:a aac \ | |
-b:a "$target_audio_bitrate_kbit_s"k \ | |
"${1%.*}-$2mB.mp4" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment