Skip to content

Instantly share code, notes, and snippets.

@CallumDev
Last active September 16, 2022 14:23
Show Gist options
  • Save CallumDev/050076ead42371319b295991f6bac0fd to your computer and use it in GitHub Desktop.
Save CallumDev/050076ead42371319b295991f6bac0fd to your computer and use it in GitHub Desktop.
#!/bin/bash
# discordencode - encodes a video file to under 8MiB for Discord
usage () {
echo "Usage: [USEAUDIO=1] [VPRESET=x264-preset] discordencode input output.mp4"
}
if [ -z "$1" ]
then
usage
exit 1
fi
if [ -z "$2" ]
then
usage
exit 1
fi
if [ ! -f "$1" ]; then
echo "$1 does not exist"
exit 2
fi
# Bitrate math functions
# Bc and ffprobe are a bit arcane
duration_seconds () {
ffprobe -i "$1" -show_entries format=duration -v quiet -of csv="p=0"
}
subtract_and_truncate () {
echo "x = $1; scale = 0; x / 1 - $2" | bc -l
}
divide_floats() {
echo "scale=2; $1 / $2" | bc
}
audioargs="-an"
audiobits=0
if [[ $USEAUDIO ]] && [ "$USEAUDIO" -eq "1" ]
then
audioargs="-c:a aac -b:a 96k"
audiobits=96
echo "Using 96k aac audio"
fi
if [ -z "$VPRESET" ]
then
VPRESET=veryslow
fi
duration=$(duration_seconds "$1")
echo $1
echo Duration is $duration
kbits=$(subtract_and_truncate $(divide_floats 60630.8 $duration) $audiobits)
echo Video bitrate is $kbits kb/s
set -x
ffmpeg -y -i "$1" -c:v libx264 -preset $VPRESET -threads 0 -b:v ${kbits}k -pass 1 -an -f mp4 /dev/null
ffmpeg -i "$1" -c:v libx264 -preset $VPRESET -threads 0 -b:v ${kbits}k -pass 2 $audioargs "$2"
@N72826
Copy link

N72826 commented Sep 12, 2022

Ok I cannot for the life of me figure out how to enable audio, @xDShot @CallumDev

@xDShot
Copy link

xDShot commented Sep 13, 2022

Ok I cannot for the life of me figure out how to enable audio, @xDShot @CallumDev

Put USEAUDIO=1 env var USEAUDIO=1 ./discordencode.sh in.ext out.mp4

I've made a fork, it adds audio by default.

@N72826
Copy link

N72826 commented Sep 13, 2022

Put USEAUDIO=1 env var USEAUDIO=1 ./discordencode.sh in.ext out.mp4

I've made a fork, it adds audio by default.

@xDShot thank you so much! especially for replying that fast and forking with audio enabled by default. Me not being able to figure it out just goes to show how inexperienced I am when it comes to bash. But you can bet I will never forget how environment variables work again, so thanks.

@CallumDev
Copy link
Author

Hey guys @N72826 @xDShot this gist has been replaced by this repo: https://github.com/CallumDev/discordencode/

@N72826
Copy link

N72826 commented Sep 16, 2022

Hey guys @N72826 @xDShot this gist has been replaced by this repo: https://github.com/CallumDev/discordencode/

ah ok. thank you very much guys.

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