How to Change Video SAR Dynamically in FFmpeg

This guide explains how to dynamically modify a video’s Sample Aspect Ratio (SAR) using the FFmpeg setsar filter. You will learn how to use FFmpeg’s built-in mathematical expressions and video variables—such as input width, height, and existing display aspect ratio—to calculate and apply SAR changes programmatically during the encoding process.

Understanding the setsar Filter

The setsar filter sets the Sample Aspect Ratio (the ratio of a single pixel’s width to its height) for the output video. Instead of passing a static ratio (like 1:1 or 4:3), you can pass an expression that FFmpeg evaluates for each input video.

The basic syntax is:

ffmpeg -i input.mp4 -vf "setsar=expression" output.mp4

Available Variables

When writing dynamic expressions for setsar, you can use the following variables:


Practical Examples of Dynamic SAR Calculation

1. Scaling the Existing SAR

If you want to dynamically double the current SAR of any input video, multiply the sar variable by a factor:

ffmpeg -i input.mp4 -vf "setsar=sar*2" output.mp4

2. Calculating SAR Based on a Target DAR

The relationship between Display Aspect Ratio (DAR), Sample Aspect Ratio (SAR), and frame dimensions is:

\[\text{DAR} = \text{SAR} \times \left(\frac{\text{Width}}{\text{Height}}\right)\]

To dynamically force a specific DAR (for example, 16:9) regardless of the input dimensions, calculate the SAR using the formula \(\text{SAR} = \text{DAR} / (\text{Width}/\text{Height})\):

ffmpeg -i input.mp4 -vf "setsar=(16/9)/(iw/ih)" output.mp4

Alternatively, you can write this using the dar variable to adapt to whatever the input display ratio is:

ffmpeg -i input.mp4 -vf "setsar=dar/(iw/ih)" output.mp4

3. Conditional SAR Assignment

FFmpeg supports conditional evaluation using the if(x, y, z) function (if x is true, return y, else z).

To set the SAR to 1:1 (square pixels) if the input SAR is greater than 1, but otherwise keep the original SAR:

ffmpeg -i input.mp4 -vf "setsar='if(gt(sar,1), 1, sar)'" output.mp4

4. Handling Anamorphic Video Formats

If you are processing files where you need to scale the horizontal aspect of the pixels based on whether the video is portrait or landscape, you can use comparison operators:

ffmpeg -i input.mp4 -vf "setsar='if(lt(iw,ih), 1, 12/11)'" output.mp4

This expression checks if the width (iw) is less than the height (ih). If true (portrait), it sets the SAR to 1. If false (landscape/square), it sets the SAR to 12/11.