FFmpeg optimize YouTube video

FFmpeg can optimally re-encode video from numerous formats for YouTube (or other service) upload. YouTube suggested settings for SDR video are implemented below. There are additional settings for HDR Video.

ffmpeg -colorspace bt709 -i in.avi -b:v 8M -bufsize 16M -c:v libx264 -preset slow -c:a aac -b:a 384k -pix_fmt yuv420p -movflags +faststart out.mp4
-colorspace bt709
BT.709 color space for SDR video. HDR should not use this flag.
-i in.avi
input file
-b:v 8M -bufsize 16M
8 Mbps video bitrate with 16 Mbps buffer size. This assumes 1080p input video–adjust this to the actual resolution of the input video. Use the bitrate table to choose appropriately.
-c:v libx264
H.264 video codec
-preset slow
better encoding quality at expense of more processing time
-c:a aac
AAC-LC audio codec
-b:a 384k
384 kbps audio bitrate (stereo) – this is not the sample rate which should be 48 kHz
-pix_fmt yuv420p
YUV 4:2:0 pixel format
-movflags +faststart
moov atom at the beginning of the file
out.mp4
MP4 container as suggested by YouTube

Additional flags that can be set, but require knowing the video parameters like frame rate:

-flags +cgop -g 30
GOP of 30 frames – should be 1/2 frame rate so here it was a 60 fps video

Video only, without audio

ffmpeg -i in.avi -c:v libx264 -preset slow -crf 18 -pix_fmt yuv420p -movflags +faststart out.mp4

Reference: FFmpeg for YouTube