Use the FFmpeg concat demuxer with a text file listing your segments to join recordings while preserving continuous timestamps. This method avoids re-encoding, ensuring that timecodes remain sequential and accurate across all merged files without gaps or resets.
The Problem with Standard Concatenation
When you record video in segments using FFmpeg, each segment typically starts with its own timestamp counter. If you simply concatenate these files using standard tools or basic piping, the playback software often sees disjointed streams. The result is a video where the timecode jumps back to zero at the start of every new segment. This breaks continuity for forensic analysis, security monitoring, or any application requiring precise chronological data. A common mistake is attempting to use theconcat protocol directly on the command line with multiple input files like -i seg1.mp4 -i seg2.mp4. While this works for simple merging, it does not guarantee that the internal metadata regarding timebase and start times is handled correctly for all container formats. More importantly, if you need to process dozens or hundreds of segments, managing inputs manually becomes error-prone and inefficient. The solution lies in using the concat demuxer, which reads a manifest file to understand how to stitch the streams together logically rather than just physically.
Preparing the Segment List File
The core of this technique is creating a plain text file that lists your video segments in the correct order. This file acts as a manifest for the FFmpeg demuxer. It must follow a strict syntax to ensure compatibility. Each line in the file should contain a directive specifying the path to a video file. Create a file namedsegments.txt. Inside this file, list each segment on a separate line. The format requires the keyword file followed by a single space and then the filename enclosed in single quotes. For example:
file 'segment_001.mp4'
file 'segment_002.mp4'
file 'segment_003.mp4'
Ensure that all segments are in the same directory as the text file, or provide the full absolute path to each file. Consistency is key; mixing relative and absolute paths can cause the demuxer to fail silently or throw errors. Also, verify that all segments have the same codec parameters (resolution, frame rate, pixel format). The concat demuxer cannot automatically reconcile different codecs or resolutions during the merge process. If your segments vary, you must normalize them first.
For more details on handling complex concatenation scenarios, see FFmpeg: Honoring Outpoint Timestamps with Concat Demuxer and Preserving Input Codec Parameters.
Executing the Concatenation Command
Once your list file is ready, you can run the FFmpeg command to merge the segments. Use the-f concat flag to specify the format, and -safe 0 to allow the reading of local files safely. The -i flag points to your text file instead of individual video files.
The command structure looks like this:
ffmpeg -f concat -safe 0 -i segments.txt -c copy output.mp4
Let's break down the critical components. The -c copy flag tells FFmpeg to stream-copy the audio and video tracks without re-encoding. This is crucial for two reasons: speed and integrity. Re-encoding would reset timestamps and potentially degrade quality. By copying, you preserve the original bitstream and the internal timecode information. The -safe 0 option is necessary because FFmpeg restricts access to certain files by default for security reasons; disabling this allows it to read the paths listed in your text file.
If you encounter issues with specific containers, such as MKV or TS, you might need to adjust the flags. For instance, some formats require an intermediate step to fix headers. However, for standard MP4 or MOV files generated by typical recording scripts, the above command usually suffices. Always check the console output for warnings about unsupported codecs or mismatched parameters.
Handling Timestamp Continuity
By using the concat demuxer with stream copying, FFmpeg attempts to maintain the continuity of the presentation timestamps (PTS). However, this depends heavily on how the segments were originally created. If your recording script ensures that each segment starts exactly where the previous one ended, the timestamps will be seamless. If there are gaps or overlaps in the source files, the output may still exhibit discontinuities. In such cases, you may need to preprocess the segments to align their start times or use filter graphs to adjust timestamps, though this is rare for simple sequential recordings.Troubleshooting Common Issues
Even with the correct command, users often face hurdles. One frequent issue is the "Invalid data found when processing input" error. This usually indicates that one of the files in your list is corrupted, empty, or has an incompatible header. Verify the integrity of each segment by playing them individually before adding them to the list. Another common problem arises from mixed container formats. Ensure that all segments are in the same format. Mixing MP4 and AVI files will almost certainly fail. If you have diverse sources, convert them to a uniform format first. You can do this quickly using a loop script that converts all files in a directory to MP4 before generating the list file. Additionally, some older versions of FFmpeg may struggle with large numbers of segments. If you are merging hundreds of files, consider splitting the task into smaller batches or upgrading to the latest stable release. Performance can also be impacted by disk I/O speeds. Using fast SSDs for both input and output directories significantly reduces processing time. For related troubleshooting techniques, you might find Troubleshooting FFmpeg-Recorded RTSP Video Stream Not Displayed in VLC Media Player useful, as it covers general media player compatibility issues that often stem from improper encoding or concatenation.Best Practices for Long-Term Recording
To prevent timestamp issues from occurring in the first place, design your recording pipeline carefully. Use a consistent naming convention for your segments, such as zero-padded numbers (seg_001, seg_002). This makes sorting and list generation automated and reliable. Consider using a script to generate the segments.txt file dynamically based on the sorted list of available video files.
Furthermore, monitor the health of your storage medium. Corrupted writes during recording can lead to broken segments that fail during concatenation. Regularly verify checksums or hash values of recorded segments if long-term archival is required.
Finally, always test the concatenation process with a small sample set before committing to a full-scale merge. This allows you to catch configuration errors early. Remember that while the concat demuxer is powerful, it is not a magic bullet for poorly formed source files. Clean, consistent inputs yield clean, continuous outputs.
Frequently Asked Questions
Can I concatenate video files with different resolutions?
No, the concat demuxer requires all input files to have identical codec parameters, including resolution, frame rate, and pixel format. If your segments differ, you must resize and re-encode them to match before merging. Attempting to mix different resolutions will result in an error or undefined behavior.Does this method preserve audio timestamps accurately?
Yes, provided that the audio streams in all segments are synchronized and have the same codec and sample rate. The concat demuxer handles audio and video tracks simultaneously. If the audio timestamps in the source segments are aligned with the video, the output will maintain perfect sync without drift.What should I do if my output file is black but has sound?
This usually indicates a codec mismatch or a problem with the video stream copy operation. Check if the input files are valid and playable. Ensure that you are using a recent version of FFmpeg that supports the container format of your inputs. Sometimes, forcing the output format with-vcodec copy explicitly can resolve ambiguous codec selection issues.
Is it possible to add silence between segments?
The standard concat demuxer does not support inserting silence or other content between segments. To achieve this, you would need to create temporary filler videos containing silence and include them in your list file, or use a more complex filter graph withamix or overlay filters after concatenation.
How do I handle thousands of segments efficiently?
For large volumes, avoid listing every file manually. Use a shell script or a programming language to generate thesegments.txt file automatically by iterating through your directory of recorded files. Sorting the filenames numerically is critical to ensure the correct chronological order in the final output.