FFmpeg Dynamic Video Padding Based on Frame Size

This article explains how to use the FFmpeg pad filter with dynamic expressions to adjust a video’s canvas size based on its input frame dimensions. You will learn the core variables used for dynamic sizing, how to format the expressions, and practical examples for centering videos, creating square outputs, and adding percentage-based borders.

The FFmpeg Pad Filter Syntax

To pad a video dynamically, you must use the pad filter. The basic syntax of the filter is:

pad=width:height:x:y:color

To make these parameters dynamic, FFmpeg allows you to use mathematical expressions and variables that reference the input frame’s dimensions in real-time. The primary variables you will use are:

Because FFmpeg evaluates these variables for every frame, any change in the input frame size will dynamically scale the padding to match.


Practical Examples of Dynamic Padding

1. Dynamic Square Padding (Centering the Video)

If you want to pad a video into a perfect square based on whichever dimension is larger (width or height) while keeping the video centered, use the max() function:

ffmpeg -i input.mp4 -vf "pad='max(iw,ih):max(iw,ih):(ow-iw)/2:(oh-ih)/2:black'" output.mp4

2. Adding a Percentage-Based Border

To add a dynamic border that scales relative to the size of the input video (for example, adding a 10% border around the video), multiply the input dimensions:

ffmpeg -i input.mp4 -vf "pad='iw*1.2:ih*1.2:(ow-iw)/2:(oh-ih)/2:blue'" output.mp4

3. Dynamic 16:9 Aspect Ratio Padding

If you have videos of varying dimensions and want to force them into a 16:9 aspect ratio container without cropping or stretching, use this expression:

ffmpeg -i input.mp4 -vf "pad='max(iw,ih*16/9):max(ih,iw*9/16):(ow-iw)/2:(oh-ih)/2:black'" output.mp4

Important Rules for Dynamic Expressions

  1. Quotes are Required: Wrap the entire filter argument in double quotes, and the mathematical expressions in single quotes (e.g., "pad='expr:expr...'"). This prevents command line shells from misinterpreting characters like * or /.
  2. Order of Evaluation: FFmpeg evaluates width first, then height, then x, and finally y. This means you can use ow in your expression for height, and both ow and oh in your expressions for x and y. You cannot, however, use oh in the expression for width.