How to Use FFmpeg xfade Filter to Transition Videos

This article provides a straightforward guide on how to use the xfade (crossfade) filter in FFmpeg to create smooth transitions between concatenated video files. You will learn the basic syntax, how to calculate transition timings, how to handle accompanying audio, and see practical command-line examples to seamlessly merge your videos.


Understanding the xfade Filter

The xfade filter applies a transition effect between two video streams. Unlike the older fade filter, xfade supports dozens of transition custom shapes (such as fade, wipeleft, slideup, circleopen, etc.) and handles the overlap automatically.

To use xfade, you must define three main parameters: 1. transition: The visual effect applied (e.g., fade, wipeleft, dissolve). 2. duration: The length of the transition in seconds. 3. offset: The exact timestamp (in seconds) in the first video where the transition should start.

Calculating the Offset

The most critical step in using xfade is calculating the correct offset. Because the videos must overlap during the transition, the offset is calculated using this formula:

\[\text{Offset} = \text{Duration of Video 1} - \text{Transition Duration}\]

For example, if your first video is 10 seconds long and you want a 1-second transition: \[\text{Offset} = 10 - 1 = 9\text{ seconds}\]

Basic Command: Transitioning Two Videos

Here is the standard FFmpeg command to transition between two videos using a 1-second fade:

ffmpeg -i video1.mp4 -i video2.mp4 -filter_complex \
"[0:v][1:v]xfade=transition=fade:duration=1:offset=9[v]" \
-map "[v]" output.mp4

Adding Audio Transitions

The xfade filter only handles video. If your videos have audio, you must use the acrossfade filter to transition the audio simultaneously, otherwise the audio will go out of sync or cut abruptly.

Here is the complete command for both video and audio:

ffmpeg -i video1.mp4 -i video2.mp4 -filter_complex \
"[0:v][1:v]xfade=transition=fade:duration=1:offset=9[v]; \
 [0:a][1:a]acrossfade=d=1[a]" \
-map "[v]" -map "[a]" output.mp4

Transitioning Three or More Videos

To transition three or more videos, you must chain multiple xfade filters together. Each subsequent transition offset must account for the cumulative duration of the preceding merged videos.

Example Scenario: * Video 1: 10 seconds * Video 2: 10 seconds * Video 3: 10 seconds * Transition Duration: 1 second

Calculations: * First Offset (Video 1 to Video 2): \(10 - 1 = 9\) seconds. * Merged Video 1+2 Duration: \(10 + 10 - 1 = 19\) seconds. * Second Offset (Merged 1+2 to Video 3): \(19 - 1 = 18\) seconds.

Command:

ffmpeg -i video1.mp4 -i video2.mp4 -i video3.mp4 -filter_complex \
"[0:v][1:v]xfade=transition=fade:duration=1:offset=9[v1]; \
 [v1][2:v]xfade=transition=fade:duration=1:offset=18[v2]; \
 [0:a][1:a]acrossfade=d=1[a1]; \
 [a1][2:a]acrossfade=d=1[a2]" \
-map "[v2]" -map "[a2]" output.mp4