15

I want to combine four videos into a grid. Currently I'm using vstack to combine the rows and then hstack to combine the two outputs, as well as adding the audio.

ffmpeg -ss 0 -i 1.mp4 -ss 8 -i 3.mp4 -filter_complex vstack left.mp4
ffmpeg -ss 0 -i 2.mp4 -ss 0 -i 4.mp4 -filter_complex vstack right.mp4
ffmpeg -i left.mp4 -i right.mp4 -filter_complex hstack -i audio.mp4 output.mp4

It seams possible to do this in one operation using overlay and pad. However, the documentation states that using vstack and hstack is faster. Can those two filters be combined to one single operation?

MeinAccount
  • 523
  • 2
  • 6
  • 21

1 Answers1

21

enter image description here

You can do it all in one command using the hstack and vstack filters.

ffmpeg -i top_l.mp4 -i top_r.mp4 -i bottom_l.mp4 -i bottom_r.mp4 -i audio.mp4 \
-filter_complex "[0:v][1:v]hstack[t];[2:v][3:v]hstack[b];[t][b]vstack[v]" \
-map "[v]" -map 4:a -c:a copy -shortest output.mp4
  • The audio will be stream copied from audio.mp4 instead of being needlessly re-encoded.

If you want the audio from each input to be combined instead of providing a separate audio input then use the amerge filter. -ac 2 is added to downmix to stereo; otherwise the output would have a cumulative number of audio channels.

ffmpeg -i top_l.mp4 -i top_r.mp4 -i bottom_l.mp4 -i bottom_r.mp4 -filter_complex \
"[0:v][1:v]hstack[t];[2:v][3:v]hstack[b];[t][b]vstack[v]; \
 [0:a][1:a][2:a][3:a]amerge=inputs=4[a]" \
-map "[v]" -map "[a]" -ac 2 -shortest output.mp4
llogan
  • 121,796
  • 28
  • 232
  • 243
  • Great! But that filter looks a bit confusing. I cannot get the audio input to work. See the question for the error message. – MeinAccount Mar 28 '16 at 18:45
  • Works fantastically. Thank you! – MeinAccount Mar 28 '16 at 18:58
  • @MeinAccount There was a typo that @Mulvya fixed. I just added a few more options, so now it will stream copy the audio instead of re-encoding with `-c:a copy`, and finish encoding when the shortest input stream ends with `-shortest`. – llogan Mar 28 '16 at 19:40
  • Thanks. Even faster processing. – MeinAccount Mar 28 '16 at 20:11
  • A brief description or a link for further reading would be nice. For instance, ffmpeg filters are documented here: https://ffmpeg.org/ffmpeg-filters.html – Martin R. Jul 05 '16 at 22:22
  • 1
    @MartinR. Usually I provide links to filters used in my answers, but they were already present in the question in this case. I'll add them anyway. – llogan Jul 05 '16 at 23:00
  • also consider if you have more than 2 inputs, you have to provide the number of inputs like this `[0][1][2]hstack=inputs=3[top]; ...` – Dimitri Podborski Nov 27 '17 at 13:14