How to Overlay Video on Video with FFmpeg
This article provides a straightforward guide on how to use the
FFmpeg overlay filter to place one video on top of another.
You will learn the basic command syntax, how to position the overlay
video using coordinates and variables, and how to handle audio and video
duration sync.
To overlay one video on top of another in FFmpeg, you use the
-filter_complex option with the overlay
filter. This filter takes two video inputs, overlays the second input
(the foreground) onto the first input (the background), and outputs the
combined stream.
The Basic Command Syntax
The fundamental command structure for overlaying a video is as follows:
ffmpeg -i background.mp4 -i foreground.mp4 -filter_complex "[0:v][1:v]overlay=x=10:y=10[out]" -map "[out]" output.mp4In this command: * -i background.mp4 is the first input
(index 0). * -i foreground.mp4 is the second
input (index 1). * [0:v][1:v] tells FFmpeg to
send the video stream of the first input and the video stream of the
second input into the filter. * overlay=x=10:y=10 positions
the top-left corner of the foreground video 10 pixels from the left
(x) and 10 pixels from the top (y) of the
background video. * [out] names the output stream of the
filter, which is then mapped to the final output file via
-map "[out]".
Positioning the Overlay Using Variables
FFmpeg provides built-in variables to make positioning easier without
needing to calculate exact pixel values manually. The most common
variables are: * main_w or W: Width of the
background video. * main_h or H: Height of the
background video. * overlay_w or w: Width of
the foreground/overlay video. * overlay_h or
h: Height of the foreground/overlay video.
Using these variables, you can easily place the overlay in common positions:
Top-Right Corner:
overlay=W-w:0Bottom-Left Corner:
overlay=0:H-hBottom-Right Corner (with a 20-pixel padding):
overlay=W-w-20:H-h-20Center of the Screen:
overlay=(W-w)/2:(H-h)/2
Handling Video Endings and Audio
By default, the output video will keep playing until the longer of the two input videos finishes. If the overlay video is shorter, it will freeze on its last frame while the background continues. If the background video is shorter, the video will end but the file may continue encoding.
To force the output to stop encoding as soon as the shortest input
finishes, add the shortest=1 option inside the overlay
filter:
ffmpeg -i background.mp4 -i foreground.mp4 -filter_complex "[0:v][1:v]overlay=10:10:shortest=1[out]" -map "[out]" output.mp4To include the audio from the background video in the final output, map the audio channel from the first input:
ffmpeg -i background.mp4 -i foreground.mp4 -filter_complex "[0:v][1:v]overlay=10:10[out]" -map "[out]" -map 0:a output.mp4