Resizing videos with ffmpeg/avconv to fit into static sized player

I have a html 5 video player which is 700px wide, 400px high. I’m trying to use avconv to use ffmpeg to resize (while retaining the aspect ratio) and making sure it fits into my player.

Input can be a file of any size, so I need to resize the larger ones but center the smaller ones with black bars. So far I’ve tried: -s and -aspect, I’ve seen pad being used with the -vf switch but don’t understand how it works enough to get what I need.

Images

This is a rough idea of what I need. I’m not sure if it’s even possible. It’s almost like CSS’s max-width/max-height. I realise this may just be a jumble of words but if anyone happens to understand what I’m talking about, I’d appreciate help, Thanks.

avconv command:

avconv -y -i control.avi -vcodec libx264 -b 2000k -bufsize 20M -acodec aac -strict experimental -ar 44100 -ab 256k bigbuck_out.mp4

Solution:

A simple method is to use the force_original_aspect_ratio option in the scale filter.

original image
Original image. Represents a 640×480, 4:3 aspect ratio video.

In these examples the original image will be scaled to fit into a 1280×720, 16:9 aspect ratio output while preserving the original aspect ratio. To do this you can either:


Pillarbox or letterbox to fit

pillarboxed image
Pillarboxed image. Fitting a 640×480 (4:3) input into a 1280×720 (16:9) output.

ffmpeg -i input -vf "scale=1280:720:force_original_aspect_ratio=decrease,pad=1280:720:-1:-1:color=black" output
  • This will upscale the image. If you want to avoid upscaling see the example below.

  • Letterboxing will occur instead of pillarboxing if the input aspect ratio is wider than the output aspect ratio. For example, an input with a 2.35:1 aspect ratio fit into a 16:9 output will result in letterboxing.

Same as above but without upscaling

no upscaling
640×480 (4:3) input into 1280×720 (16:9) output without upscaling.

ffmpeg -i input -vf "scale='min(1280,iw)':min'(720,ih)':force_original_aspect_ratio=decrease,pad=1280:720:-1:-1:color=black" output

Crop to fit

enter image description here
Cropped image. 4:3 input aspect ratio, 16:9 output aspect ratio.

Using the crop filter to cut off the excess:

ffmpeg -i input -vf "scale=1280:720:force_original_aspect_ratio=increase,crop=1280:720" output

Using input images that each vary in size

If you are inputting a series of images, and the images vary in size, add the eval=frame option in the scale filter, such as:

ffmpeg -i input -vf "scale=1280:720:force_original_aspect_ratio=decrease:eval=frame,pad=1280:720:-1:-1:color=black" output

Changing the background color

Use the color option in the pad filter. You can provide a hex value or use a supported color name.