Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FFMPEG (libx264) "height not divisible by 2"

The answer to the original question which does not want to scale the video is:

-vf "pad=ceil(iw/2)*2:ceil(ih/2)*2"

Command:

ffmpeg -r 24 -i frame_%05d.jpg -vf "pad=ceil(iw/2)*2:ceil(ih/2)*2" -vcodec libx264 -y -an video.mp4 

Basically, .h264 needs even dimensions so this filter will:

  1. Divide the original height and width by 2
  2. Round it up to the nearest pixel
  3. Multiply it by 2 again, thus making it an even number
  4. Add black padding pixels up to this number

You can change the color of the padding by adding filter parameter :color=white. See the documentation of pad.


For width and height

Make width and height divisible by 2 with the crop filter:

ffmpeg -i input.mp4 -vf "crop=trunc(iw/2)*2:trunc(ih/2)*2" output.mp4

If you want to scale instead of crop change crop to scale.

For width or height

Using the scale filter. This will make width 1280. Height will be automatically calculated to preserve the aspect ratio, and the width will be divisible by 2:

ffmpeg -i input.mp4 -vf scale=1280:-2 output.mp4

Similar to above, but make height 720 and automatically calculate width:

ffmpeg -i input.mp4 -vf scale=-2:720 output.mp4

You can't use -2 for both width and height, but if you already specified one dimension then using -2 is a simple solution.


If you want to set some output width and have output with the same ratio as original

scale=720:-1 

and not to fall with this problem then you can use

scale="720:trunc(ow/a/2)*2"

(Just for people searching how to do that with scaling)


The problem with the scale solutions here is that they distort the source image/video which is almost never what you want.

Instead, I've found the best solution is to add a 1-pixel pad to the odd dimension. (By default, the pading is black and hard to notice.)

The problem with the other pad solutions is that they do not generalize over arbitrary dimensions because they always pad.

This solution only adds a 1-pixel pad to height and/or width if they are odd:

-vf pad="width=ceil(iw/2)*2:height=ceil(ih/2)*2"

This is ideal because it always does the right thing even when no padding is necessary.