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 -vf scale=1280:-2 resizes video and keeps the aspect ratio

Ffmpeg
~/tips/tip-ffmpeg-scale-keep-aspect-ratio

ffmpeg -i in.mp4 -vf scale=1280:-2 -c:a copy out.mp4

Scales a video to a fixed width and works out an even height so the picture is not stretched.

Resizing a video to 720p width sounds simple until you do the maths for the height and end up with an odd number. FFmpeg can do the maths for you.

ffmpeg -i in.mp4 -vf scale=1280:-2 -c:a copy out.mp4

The first number is the new width. The -2 as height tells the scale filter to calculate the height from the aspect ratio of the source. It is the same idea as -1, with one difference: -2 also makes sure the result is divisible by 2. Plain -1 keeps the aspect ratio but does not care whether the height ends up odd or even.

That matters because libx264 refuses odd dimensions. You get an error like height not divisible by 2 when you resize a 1920×1080 video to a width of 1281, say, or when a source has an odd size. With -2 that error disappears.

You can also fix the height and let the width follow:

ffmpeg -i in.mp4 -vf scale=-2:720 -c:a copy out.mp4

Scaling to a smaller size is the usual job, but the filter will happily scale up too, and that only makes a bigger, blurry file.

The caveat is that the filter only keeps the aspect ratio when you use a negative value for one side. If you give both a width and a height, the picture is stretched to fit exactly. Re-encoding is also needed for a resize, so -c:v copy cannot be combined with a filter.

Further reading: FFmpeg documentation: scale filter, FFmpeg wiki: scaling

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