brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: ffmpeg -crf sets video quality instead of a bitrate

Ffmpeg
~/tips/tip-ffmpeg-crf-quality-h264-h265

ffmpeg -i in.mp4 -c:v libx264 -crf 23 -preset medium -c:a copy out.mp4

Encodes video at constant quality with H.264 or H.265, so you pick a CRF number instead of a bitrate.

Guessing a bitrate for a video is a good way to end up with a file that is either blurry or ten times too big. CRF mode lets the encoder spend bits where the picture needs them.

ffmpeg -i in.mp4 -c:v libx264 -crf 23 -preset medium -c:a copy out.mp4
ffmpeg -i in.mp4 -c:v libx265 -crf 28 -tag:v hvc1 -c:a copy out-hevc.mp4

The number is the quality target, and lower means better quality and a bigger file. The FFmpeg H.264 guide says the scale for libx264 runs from 0 to 51, with 23 as the default and 17 to 28 as a subjectively sane range. About 17 or 18 should look close to visually lossless. A change of 6 roughly halves or doubles the bitrate, so it is a handy dial.

For libx265 the default is 28, which the FFmpeg H.265 guide says should look about like libx264 at 23 with a smaller file. If you copy your H.264 number straight into x265, you get files that are bigger than they need to be.

-preset is the other knob. Slower presets compress better at the same CRF, they just take longer. -c:a copy leaves the audio alone. The -tag:v hvc1 part is a tag I add for H.265 in MP4 files, which some players need to recognise the video.

The caveat is that CRF gives you a quality level, not a file size. A noisy, fast-moving clip at CRF 23 can be far larger than a calm screen recording at the same setting. If you need a file under a size limit, use two-pass bitrate encoding instead. Always try the setting on a short clip first.

Further reading: FFmpeg wiki: H.264 video encoding guide, FFmpeg wiki: H.265/HEVC encoding guide

More Ffmpeg tips ffmpeg -stream_loop 2 -i in.mp4 -c copy out.mp4 ffmpeg -i in.mp4 \ ffmpeg -i video.mp4 -i video.en.srt -map 0 -map 1 -c copy -c:s mov_text -metadata:s:s:0 language=eng video-subs.mp4 ffmpeg -i film.mkv -map 0:v -map 0:a:0 -c:v copy -c:a aac -b:a 192k -ac 2 film-stereo.mkv ffmpeg -i talk.mp4 -vn -c:a copy talk.m4a All Ffmpeg tips (38) All topics

Link