Skip to content

Instantly share code, notes, and snippets.

@tokland
Last active December 25, 2017 22:31
Show Gist options
  • Save tokland/a8197edb5786c6709f94 to your computer and use it in GitHub Desktop.
Save tokland/a8197edb5786c6709f94 to your computer and use it in GitHub Desktop.
Resize videos to a fixed size with avconv
#!/bin/sh
#
# Resize videos to a given size.
# Depedencies: libav
debug() {
echo "$@" >&2
}
to_num() { local NUM_STRING=$1
echo $NUM_STRING |
sed -e 's/t/kg/i;s/g/km/i;s/m/kk/i;s/k/*1000/ig;s/b//i' | bc
}
get_video_duration() { local VIDEO=$1
avconv -i "$VIDEO" 2>&1 |
awk '/Duration/ {split($2,a,":");print a[1]*3600+a[2]*60+a[3]}'
}
resize_video() { local INPUT=$1 OUTPUT=$2; ESIZE=$3; shift 3;
local AUDIO_RATE=128000
local DURATION=$(get_video_duration "$INPUT")
local SIZE=$(to_num $ESIZE)
local VIDEO_RATE=$(echo "($SIZE * 8) / $DURATION - $AUDIO_RATE" | bc)
if ! echo "$VIDEO_RATE < 0" | bc -l >/dev/null; then
debug "Negative video rate. Increase file size"
return 1
else
debug "Audio rate: $AUDIO_RATE - Video rate: $VIDEO_RATE"
avconv -loglevel info -i "$INPUT" \
-f mp4 -movflags frag_keyframe+empty_moov \
-codec:v libx264 -b:v $VIDEO_RATE \
-codec:a ac3 -b:a $AUDIO_RATE \
"$@" -strict -2 -y "$OUTPUT"
fi
}
# Main
if test $# -ne 3; then
echo "Usage: video-resize INPUT_FILE OUTPUT_FILE OUTPUT_FILE_SIZE"
else
resize_video "$@"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment