How to Overlay Video in Video with Border in FFmpeg

This guide demonstrates how to overlay one video on top of another—commonly known as a picture-in-picture effect—and apply a custom-colored border to the overlay video using FFmpeg. You will learn the exact command-line syntax, how the padding and overlay filters work, and how to customize the border size, color, and position to suit your needs.

The FFmpeg Command

To achieve this effect, you need to scale the overlay video, apply a pad filter to create the border, and then use the overlay filter to position it on top of the background video.

Run the following command in your terminal:

ffmpeg -i background.mp4 -i overlay.mp4 -filter_complex "[1:v]scale=400:-1,pad=iw+10:ih+10:5:5:color=red[pip];[0:v][pip]overlay=W-w-20:20" -c:a copy output.mp4

How the Command Works

The command uses a filter_complex graph to process both video streams. Here is the step-by-step breakdown of how the filters work:

  1. [1:v]scale=400:-1: This takes the second input video (overlay.mp4) and scales its width to 400 pixels. The -1 automatically calculates the height to maintain the original aspect ratio.
  2. pad=iw+10:ih+10:5:5:color=red: This filter creates the custom border.
    • iw+10 and ih+10 increase the overall width and height of the overlay frame by 10 pixels (adding 5 pixels to each side).
    • The 5:5 offset places the original video 5 pixels from the top and left of the new, larger frame.
    • color=red fills the padded area with your custom color. You can use standard color names (like blue, green, yellow) or hex codes (like 0x00FF00).
    • [pip] names this processed stream “pip” (picture-in-picture).
  3. [0:v][pip]overlay=W-w-20:20: This merges the two streams.
    • [0:v] is the background video, and [pip] is the modified overlay.
    • W-w-20 places the overlay on the right side, 20 pixels away from the edge (W is background width, w is overlay width).
    • 20 places the overlay 20 pixels down from the top edge.
  4. -c:a copy: This copies the audio stream from the background video without re-encoding it, which saves processing time.

Customizing Your Setup