How to Use the FFmpeg Overlay Filter

The FFmpeg overlay filter is a powerful tool used to place one video or image on top of another. This article provides a straightforward guide on how to use this filter, covering basic syntax, coordinate positioning, watermarking, and practical command-line examples to help you master video layering in FFmpeg.

The Basic Syntax

To use the overlay filter, you must use FFmpeg’s -filter_complex flag because the operation requires two distinct video inputs. The basic syntax is:

ffmpeg -i background.mp4 -i overlay.png -filter_complex "[0:v][1:v]overlay=X:Y[out]" -map "[out]" output.mp4

In this command: * [0:v] refers to the video stream of the first input (background.mp4). * [1:v] refers to the video stream of the second input (overlay.png). * overlay=X:Y defines the horizontal (X) and vertical (Y) coordinates where the top-left corner of the overlay image will be placed on the background. * [out] is the label assigned to the resulting output stream, which is then mapped to the output file using -map "[out]".

Positioning with Variables

FFmpeg provides built-in constants that make positioning overlays simple without needing to know the exact pixel dimensions of your files beforehand:

Using these variables, you can place your overlay in common positions:

Practical Examples

Adding a Watermark in the Bottom-Right with Padding

To place a logo in the bottom-right corner with a 10-pixel margin from the edges, use the following command:

ffmpeg -i input.mp4 -i logo.png -filter_complex "[0:v][1:v]overlay=W-w-10:H-h-10[out]" -map "[out]" -map 0:a? output.mp4

(Note: -map 0:a? ensures that any audio from the original video is copied to the output file).

Picture-in-Picture (PiP) Effect

If you want to overlay a smaller video onto a larger video in the top-right corner, you may need to scale the overlay video first:

ffmpeg -i main_video.mp4 -i pip_video.mp4 -filter_complex "[1:v]scale=320:-1[pip]; [0:v][pip]overlay=W-w-20:20[out]" -map "[out]" -map 0:a? output.mp4

In this command, the second video is scaled to a width of 320 pixels (preserving aspect ratio) before being overlaid 20 pixels from the top and right edges.

Showing an Overlay at a Specific Time

You can control when the overlay appears and disappears using the enable evaluation parameter:

ffmpeg -i input.mp4 -i logo.png -filter_complex "[0:v][1:v]overlay=10:10:enable='between(t,5,10)'[out]" -map "[out]" -map 0:a? output.mp4

This configuration displays the overlay at coordinates (10,10) only between the 5th and 10th seconds of the video.