How to Use the FFmpeg hstack Filter
This article explains how to use the FFmpeg hstack
filter to combine multiple video streams side-by-side into a single
horizontal layout. You will learn the basic command syntax for merging
two videos, how to handle videos with different heights using scaling,
how to stack three or more inputs, and how to manage the accompanying
audio tracks.
Basic Syntax for Two Equal-Height Videos
The hstack (horizontal stack) filter requires all input
videos to have the exact same height in pixels. If your input videos
already share the same height, you can merge them side-by-side using the
following basic command:
ffmpeg -i input1.mp4 -i input2.mp4 -filter_complex hstack output.mp4In this command: * -i input1.mp4 and
-i input2.mp4 specify the two input video files. *
-filter_complex hstack tells FFmpeg to apply the horizontal
stacking filter to the video streams. * output.mp4 is the
resulting combined video.
Handling Videos with Different Heights
If your input videos have different heights, the basic
hstack command will fail with an error. To resolve this,
you must scale the videos to a matching height before stacking them.
The following command scales both videos to a height of 720 pixels while automatically adjusting the width to maintain their original aspect ratios:
ffmpeg -i input1.mp4 -i input2.mp4 -filter_complex "[0:v]scale=-1:720[v0];[1:v]scale=-1:720[v1];[v0][v1]hstack=inputs=2" output.mp4How this filter graph works: * [0:v]scale=-1:720[v0]
takes the video stream of the first input (0:v), scales its
height to 720 pixels, and labels the output stream as
[v0]. * [1:v]scale=-1:720[v1] does the same
for the second input (1:v), scaling it to 720
pixels and labeling it [v1]. *
[v0][v1]hstack=inputs=2 takes the two scaled streams and
horizontally stacks them.
Stacking Three or More Videos
To stack more than two videos, you must explicitly define the number
of inputs using the inputs parameter. Below is an example
of horizontally stacking three videos of equal height:
ffmpeg -i input1.mp4 -i input2.mp4 -i input3.mp4 -filter_complex "[0:v][1:v][2:v]hstack=inputs=3" output.mp4For three videos with different heights, scale them first before passing them to the filter:
ffmpeg -i input1.mp4 -i input2.mp4 -i input3.mp4 -filter_complex "[0:v]scale=-1:720[v0];[1:v]scale=-1:720[v1];[2:v]scale=-1:720[v2];[v0][v1][v2]hstack=inputs=3" output.mp4Combining Audio Streams
By default, the hstack filter only processes video
streams. If your input videos contain audio and you want to hear both
tracks simultaneously in the output file, you must mix the audio using
the amix filter:
ffmpeg -i input1.mp4 -i input2.mp4 -filter_complex "[0:v][1:v]hstack[v];[0:a][1:a]amix=inputs=2[a]" -map "[v]" -map "[a]" output.mp4[0:a][1:a]amix=inputs=2[a]mixes the audio from both inputs into a single audio stream labeled[a].-map "[v]"and-map "[a]"instruct FFmpeg to use the stacked video and the mixed audio in the final container.