How to Overlay Video with Alpha Channel in FFmpeg
Overplaying a video with transparency (an alpha channel) onto a
background video is a common task in video editing and automated
rendering. This article provides a straightforward guide on how to use
the FFmpeg overlay filter to correctly handle alpha
channels, ensuring that transparent backgrounds are rendered properly
without visual artifacts or solid black backgrounds.
The Basic Command for Alpha Overlay
To overlay a video with an alpha channel (such as a WebM VP9, ProRes
4444, or a PNG sequence) onto a background video, use the
filter_complex option with the overlay
filter.
Here is the standard command:
ffmpeg -i background.mp4 -i overlay_with_alpha.webm -filter_complex "[0:v][1:v]overlay=format=auto[out]" -map "[out]" -map 0:a? output.mp4Key Parameters Explained
[0:v][1:v]: This inputs the video stream of the first file (the background) and the second file (the overlay) into the filter.overlay=format=auto: This is the crucial setting for alpha channels. Settingformat=autoforces the overlay filter to automatically detect the color space and correctly blend the alpha (transparency) channel of the overlay video onto the background. If you omit this, you may experience color degradation or issues with alpha blending.-map "[out]": This maps the output of the filter complex to the final output file.-map 0:a?: This includes the audio from the background video if it exists (the?prevents the command from failing if there is no audio).
Adjusting Position and Timing
You can customize the position of the overlay and how the video behaves when one stream ends.
Positioning the Overlay
By default, the overlay is placed in the top-left corner
(x=0:y=0). To position it elsewhere, use the x
and y variables:
Center the overlay:
overlay=(W-w)/2:(H-h)/2:format=auto(Where
W/Hare the background width/height, andw/hare the overlay width/height).Bottom-right corner (with a 10px margin):
overlay=W-w-10:H-h-10:format=auto
Handling Video Length Differences
If your overlay video is shorter than the background video and you
want it to disappear after it finishes, add the
eof_action=pass parameter:
overlay=format=auto:eof_action=passIf you want the output video to stop completely as soon as the
shortest video ends, use the shortest=1 option:
ffmpeg -i background.mp4 -i overlay_with_alpha.webm -filter_complex "[0:v][1:v]overlay=format=auto:shortest=1[out]" -map "[out]" output.mp4Troubleshooting Premultiplied Alpha (Halo Effect)
If you notice a strange dark or light “halo” border around the edges
of your transparent overlay, it is likely because the source video uses
premultiplied alpha. You can resolve this by adding the
premultiplied parameter to the filter:
overlay=format=auto:premultiplied=1