Skip to content

Instantly share code, notes, and snippets.

@transkatgirl
Last active October 29, 2022 11:33
Show Gist options
  • Save transkatgirl/19363e3ef458ea206aec141ad9d8b382 to your computer and use it in GitHub Desktop.
Save transkatgirl/19363e3ef458ea206aec141ad9d8b382 to your computer and use it in GitHub Desktop.
Encode a video for uploading to Twitter using FFMPEG and FDKAAC
#!/bin/bash
# https://developer.twitter.com/en/docs/twitter-api/v1/media/upload-media/uploading-media/media-best-practices
# - h.264 high profile
# - 60fps or less
# - aac-lc, he-aac not supported
# - 16:9 recommended
# - 512mb maximum
# - shorter than 140s
# - 1:1 pixel aspect ratio
# - yuv 4:2:0
# - up to stereo audio
# - no open gop
# - progressive scan
# - minimum recommended audio bitrate 128kbit/s
# https://help.twitter.com/en/using-twitter/twitter-videos
# - max resoultion 1920x1200
# - between 1:2.39 and 2.39:1
# - max video bitrate 25mbit/s
# https://help.twitter.com/en/using-twitter/how-to-use-live-producer
# - keyframe interval of fps*3
# a lot of these pages offered conflicting info (and sometimes outright wrong info too, like stating the max fps was 40 even though all the others stated 60), here's my attempt at trying to make sense of it all
# note that this script *may not* work with tweetdeck, it's only tested with the twitter web app
ffmpeg -i "$1" -vn -ac 2 -sample_fmt s16 "/tmp/audio.wav"
fdkaac -b 320k "/tmp/audio.wav" -o "/tmp/audio.m4a"
rm "/tmp/audio.wav"
vfilter="fps=fps=60,scale=-2:1080:flags=lanczos:out_color_matrix=bt709,setsar=1,format=yuv420p"
ffmpeg -i "$1" -i "/tmp/audio.m4a" -map 0:v:0 -map 1:a:0 -max_muxing_queue_size 1024 -t 2:19 -map_metadata -1 -vcodec libx264 -g 180 -keyint_min 180 -vf "$vfilter" -color_primaries bt709 -color_trc bt709 -b:v 25000k -bufsize 75M -acodec copy -movflags +faststart -map_metadata -1 output.mp4
rm "/tmp/audio.m4a"
#!/bin/bash
# same as encodetwitter.sh, but for encoding videos without audio
vfilter="fps=fps=60,scale=-2:1080:flags=lanczos:out_color_matrix=bt709,setsar=1,format=yuv420p"
ffmpeg -i "$1" -an -max_muxing_queue_size 1024 -t 2:19 -map_metadata -1 -vcodec libx264 -g 180 -keyint_min 180 -vf "$vfilter" -color_primaries bt709 -color_trc bt709 -b:v 25000k -bufsize 75M -movflags +faststart -map_metadata -1 output.mp4
@roblogic
Copy link

roblogic commented Mar 3, 2022

Very cool, thanks. Not sure why it adjusted the aspect ratio but it's not bad. I used the faac tool from homebrew instead of fdk-aac. It worked with the same inputs given in your script.

https://twitter.com/roblogic_/status/1499410750669934602?s=20&t=n2Sg7mKoik8sZfytT4EcTQ

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