Concatenating or stitching videos involves merging multiple video clips into a single, cohesive video. Stitching multiple videos together fits many use cases, whether it's a quick sports highlight reel, an educational lecture or module, or even photo montages. Sometimes it's easier to perform this action without the use of a video editor and instead use a one-line command with ffmpeg.
Method 1: Using the concat demuxer
The concat demuxer is the most flexible and recommended method for joining videos.
First, create a text file (e.g., input.txt) listing the videos you want to concatenate:
Note that these can be either relative or absolute paths. Next, use the following commands:
Option 1: Without transcoding
Without the stream copy option your files will be re-encoded
Option 2: With transcoding
Feel free to insert other transcode options according to the ffmpeg documentation
Breakdown:
- -f concat: Specifies the concat format
- -safe 0: Allows ffmpeg to read files in the current directory
- -i input.txt: Input file containing the list of videos
- -c copy: Copies the codecs without re-encoding (faster)
- -c:v libx264: uses the x264 (H.264) video encoder
- -c:a aac: uses the AAC audio encoder
- output.mp4: Name of the output file
Notes: You can stream copy or re-encode your files. However, if you choose to stream copy, the files must possess the same specifications (codecs, resolutions, frame rate, etc..). If the files are of differing specifications, you may see unwanted results in the output file.
Method 2: Using the concat filter
The concat filter is useful when you need to re-encode the videos, which can be necessary if the input videos have different codecs or formats.
Breakdown:
- -i input1.mp4 -i input2.mp4 -i input3.mp4: Input video files
- -filter_complex: Applies complex filtering
- concat=n=3:v=1:a=1: Concatenates 3 inputs with 1 video and 1 audio stream each
- [outv][outa]: Labels for the output video and audio streams
- -map "[outv]" -map "[outa]": Maps the labeled streams to the output
Tips for Successful Video Concatenation
- Ensure format compatibility: When using the copy method, make sure all input videos have the same codec, resolution, and frame rate.
- Check audio streams: Ensure all videos have audio, or use the concat filter to handle videos with and without audio.
- Handle different resolutions: If videos have different resolutions, you may need to scale them before concatenating: