How to Force FFmpeg Video Dimensions Divisible by 16
Many modern video codecs, such as H.264 (AVC) and H.265 (HEVC), require video dimensions to be divisible by 2, 8, or 16 to function correctly or to utilize hardware acceleration. If your input video has odd or non-standard dimensions, FFmpeg will throw an error during the encoding process. This guide demonstrates how to quickly resolve this issue using FFmpeg’s video filters to force output dimensions to be divisible by 16 through scaling, auto-calculating, or padding.
Method 1: The Negative Value Scaling Method (Preserves Aspect Ratio)
If you want to set one specific dimension (like a width of 1280
pixels) and let FFmpeg automatically calculate the other dimension while
forcing it to be divisible by 16, use a negative value in the
scale filter. Passing -16 tells FFmpeg to
calculate the missing dimension based on the aspect ratio and round it
to the nearest multiple of 16.
ffmpeg -i input.mp4 -vf "scale=1280:-16" output.mp4In this example, the width is locked to 1280, and the height is automatically scaled to the closest value divisible by 16. You can do the same for height by locking the height and letting the width auto-scale:
ffmpeg -i input.mp4 -vf "scale=-16:720" output.mp4Method 2: The Math Formula Method (Scales Both Dimensions)
If you want to keep the input video’s rough size but force both the width and height to the nearest multiple of 16, you can use mathematical expressions within the scale filter.
To scale the video down to the nearest multiple of 16:
ffmpeg -i input.mp4 -vf "scale='trunc(iw/16)*16:trunc(ih/16)*16'" output.mp4To scale the video up to the nearest multiple of 16:
ffmpeg -i input.mp4 -vf "scale='ceil(iw/16)*16:ceil(ih/16)*16'" output.mp4- iw and ih represent the input width and height.
- trunc rounds down, while ceil rounds up to the nearest integer.
Method 3: The Padding Method (No Distortion)
If you do not want to stretch or scale the video pixels at all, you can pad the video instead. This method adds a black border around the video to bring the dimensions up to a multiple of 16.
ffmpeg -i input.mp4 -vf "pad=width='ceil(iw/16)*16':height='ceil(ih/16)*16':x='(ow-iw)/2':y='(oh-ih)/2'" output.mp4- This formula calculates the required padding.
x='(ow-iw)/2'andy='(oh-ih)/2'center the original video inside the new padded frame.