Configure FFmpeg xstack Layouts and Background Color

This article explains how to use the FFmpeg xstack filter to arrange multiple video inputs into custom grid layouts and define a custom background color for any empty or unfilled areas in the output canvas.

The xstack filter allows you to stitch multiple input videos into a single output stream. To control the positioning of these videos and customize the background color behind them, you use the layout and fill options.

1. Positioning Videos with the layout Option

The layout parameter defines the exact X and Y coordinates for the top-left corner of each input video. Coordinates are separated by a pipe symbol (|).

FFmpeg provides variables to make positioning easier, based on the width (w) and height (h) of the inputs: * w0, h0: Width and height of the first input. * w1, h1: Width and height of the second input, and so on.

Example: 2x2 Grid Layout

To arrange four inputs of equal size (e.g., 1920x1080) into a 2x2 grid: * Top-Left (Input 0): 0_0 (X=0, Y=0) * Top-Right (Input 1): w0_0 (X=width of first video, Y=0) * Bottom-Left (Input 2): 0_h0 (X=0, Y=height of first video) * Bottom-Right (Input 3): w0_h0 (X=width of first video, Y=height of first video)

The layout string is: layout=0_0|w0_0|0_h0|w0_h0

2. Setting a Custom Background Color with fill

By default, any unused space on the canvas is colored black. You can change this using the fill option (also referred to as fill_color in some FFmpeg builds).

The fill parameter accepts: * Standard color names (e.g., red, blue, green, white, darkgray). * Hexadecimal color codes (e.g., 0x1A1A1A or #1A1A1A).

3. Complete Command Example

The following command merges four video inputs into a 2x2 grid with a custom forestgreen background. The canvas is deliberately made slightly larger than the videos by using custom coordinates to show the background color as a border.

ffmpeg -i input1.mp4 -i input2.mp4 -i input3.mp4 -i input4.mp4 -filter_complex \
"xstack=inputs=4:layout=0_0|w0+10_0|0_h0+10|w0+10_h0+10:fill=forestgreen" \
output.mp4

Key Parameters in This Command: