Discord 8MiB Limit

2020/05/30

ffmpeg is an amazing piece of software used for any general purpose video encoding / decoding. Using ffmpeg and a bit of math you’re able to encode a video to an almost exact filesize, which is very helpful if your trying to stay within Discords 8MiB filesize. All using POSIX sh.

First we start by defining what the target filesize is (in bits)

#8M is the max file size for Discord
#Take 3% off to account for any extra data / muxing overhead
#((8 Mebibytes * 8388608 bits) * .97%) = 63753420 bits
MAX_SIZE=65095598

The number used for the max size of the file is somewhat magic. If you tried to encode for an exact 8MiB filesize, you’ll end up with something just slightly larger than what you were aiming for. After some experimentation I learned that taking 3% off seems to keep it just under the target filesize.

Now we need to calculate the bitrate

#Get duration
duration=$(ffprobe -v error -show_format $1 | grep duration | cut -d "=" -f 2)
#Calculate bitrate
bitrate=$(echo "$MAX_SIZE / $duration" | bc)

Using ffprobe we can simply get the videos duration in seconds, and since bitrate just bits / second, we just do a simple division to get the target bitrate

ffmpeg -y -i $1 -c:v libvpx-vp9 -b:v $bitrate -pass 1 -deadline good -an -f webm /dev/null && \
ffmpeg -i $1 -c:v libvpx-vp9 -b:v $bitrate -pass 2 -deadline good -an "$1.webm"

Now we use VP9 2 pass encoding to achieve the best possible quality out of the small 8MiB limit. I personally like to strip the audio out mainly because it isn’t really important to my content. If your planning on having audio, just remember to subtract some bitrate off to account for the additional audio bitrate.

#!/bin/sh

#8M is the max file size for Discord
#Take 3% off to account for any extra data / muxing overhead
#((8 Mebibytes * 8388608 bits) * .97%) = 63753420 bits
MAX_SIZE=65095598

#Get duration
duration=$(ffprobe -v error -show_format $1 | grep duration | cut -d "=" -f 2)
#Calculate bitrate
bitrate=$(echo "$MAX_SIZE / $duration" | bc)

ffmpeg -y -i $1 -c:v libvpx-vp9 -b:v $bitrate -pass 1 -deadline good -an -f webm /dev/null && \
ffmpeg -i $1 -c:v libvpx-vp9 -b:v $bitrate -pass 2 -deadline good -an "$1.webm"

The end result looks okay for the small bitrate, but the flexibilty to turn any video into something that can be shared on Discord is something I thought was worth making a script out of.