Skip to content

Instantly share code, notes, and snippets.

@xDShot
Forked from CallumDev/discordencode.sh
Last active March 23, 2025 22:04
Show Gist options
  • Save xDShot/142428f8fe8a2f2ea19a7582f3534a43 to your computer and use it in GitHub Desktop.
Save xDShot/142428f8fe8a2f2ea19a7582f3534a43 to your computer and use it in GitHub Desktop.
Bash script to encode videos with ffmpeg to under discord's 8MiB file limit
#!/bin/bash
# discordencode - encodes a video file to under 8MiB for Discord
#VF="scale=1280:-2"
usage () {
echo "Usage: [WEBM=1] [VCODEC=libx264] [ACODEC=aac] [VF=filter] [NOAUDIO=1] [VPRESET=x264-preset] $0 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
}
audiocodec="aac"
if [[ $WEBM ]] && [ "$WEBM" -eq "1" ]
then
audiocodec="libopus"
fi
if [[ ! -z $ACODEC ]]
then
audiocodec="$ACODEC"
echo "audiocodec! $audiocodec"
fi
audioargs="-c:a $audiocodec -b:a 128k"
audiobits=128
if [[ $NOAUDIO ]] && [ "$NOAUDIO" -eq "1" ]
then
audioargs="-an"
audiobits=0
echo "Using no audio"
fi
if [ -z "$VPRESET" ]
then
VPRESET=veryslow
fi
encodeparams="-preset $VPRESET -threads 0"
if [[ $WEBM ]] && [ "$WEBM" -eq "1" ]
then
encodeparams="-cpu-used 3 -row-mt 1"
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
videocodec="libx264"
if [[ $WEBM ]] && [ "$WEBM" -eq "1" ]
then
videocodec="libvpx-vp9"
fi
if [[ ! -z $VCODEC ]]
then
videocodec="$VCODEC"
echo "videocodec! $videocodec"
fi
videoargs=""
if [[ ! -z $VF ]]
then
videoargs="-vf $VF"
echo "videoargs! $videoargs"
fi
videoformat="mp4"
if [[ $WEBM ]] && [ "$WEBM" -eq "1" ]
then
videoformat="webm"
fi
# temporary logfile
TMPDIR=$(mktemp -d)
PASSLOGFILE="$TMPDIR/ffmpeg2pass"
set -x
ffmpeg -hide_banner -y -i "$1" -c:v $videocodec -passlogfile $PASSLOGFILE $encodeparams -b:v ${kbits}k $videoargs -pass 1 -an -f $videoformat /dev/null
ffmpeg -hide_banner -i "$1" -c:v $videocodec -passlogfile $PASSLOGFILE $encodeparams -b:v ${kbits}k $videoargs -pass 2 $audioargs "$2"
{ set +x; } 2>/dev/null
# clean tmp
rm -rf "$TMPDIR"
@N72826
Copy link

N72826 commented Sep 13, 2022

Appreciate you for forking and modifying it for me!

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