How to Overlay Video in Video Using FFmpeg
This article explains how to use the FFmpeg overlay
video filter to create a picture-in-picture (PiP) effect. You will learn
the exact command-line syntax required to scale a secondary video and
position it over a main background video at specific coordinates.
To overlay a second video inside a main video, you must use FFmpeg’s
filter_complex flag. This allows you to scale the secondary
video (so it does not block the entire background) and then position it
using coordinates.
Here is the standard command to scale a picture-in-picture video and position it in the bottom-right corner:
ffmpeg -i main_video.mp4 -i pip_video.mp4 -filter_complex "[1:v]scale=400:-1[pip];[0:v][pip]overlay=main_w-overlay_w-20:main_h-overlay_h-20:shortest=1" -c:a aac output.mp4How the Command Works
-i main_video.mp4: Defines the main background video (Input 0).-i pip_video.mp4: Defines the secondary video to be overlaid (Input 1).[1:v]scale=400:-1[pip]: Takes the video stream of the second input ([1:v]), scales its width to 400 pixels while keeping the aspect ratio (-1), and labels this new temporary stream as[pip].[0:v][pip]overlay=...: Takes the main video stream ([0:v]) and places the[pip]stream on top of it.main_w-overlay_w-20: Calculates the X-coordinate for the overlay. It subtracts the width of the overlay video (overlay_w) from the width of the main video (main_w), minus an extra 20 pixels for padding from the right edge.main_h-overlay_h-20: Calculates the Y-coordinate. It subtracts the height of the overlay video (overlay_h) from the height of the main video (main_h), minus 20 pixels for padding from the bottom edge.shortest=1: Tells FFmpeg to stop encoding when the shortest input video ends.-c:a aac: Encodes the audio of the output file using the AAC codec.
Alternative Positioning Coordinates
You can change the positioning of the picture-in-picture video by
adjusting the x and y mathematical expressions
inside the overlay filter:
- Top-Left Corner (with 20px padding):
overlay=20:20 - Top-Right Corner (with 20px padding):
overlay=main_w-overlay_w-20:20 - Center of the Screen:
overlay=(main_w-overlay_w)/2:(main_h-overlay_h)/2