Split RTSP Stream into Multiple MP4s with FFmpeg
This article demonstrates how to continuously capture a live RTSP stream and save it into a series of sequentially numbered or timestamped MP4 files using FFmpeg’s segment muxer. By leveraging stream copying, this process splits the incoming video without re-encoding, preserving original quality while keeping CPU usage extremely low.
To write an RTSP stream to multiple MP4 files, use the following FFmpeg command:
ffmpeg -rtsp_transport tcp -i rtsp://your_rtsp_stream_url -f segment -segment_time 600 -segment_format mp4 -reset_timestamps 1 -c copy output_%03d.mp4Command Breakdown
-rtsp_transport tcp: Forces FFmpeg to use TCP instead of UDP to receive the RTSP stream. This prevents packet loss and packet corruption in the output MP4 files.-i rtsp://your_rtsp_stream_url: The input URL of your RTSP camera or stream.-f segment: Specifies the segment muxer, which instructs FFmpeg to split the output into multiple files.-segment_time 600: Sets the target duration for each segment in seconds. In this example,600tells FFmpeg to create a new MP4 file every 10 minutes.-segment_format mp4: Defines the container format for the generated segments as MP4.-reset_timestamps 1: Resets the timestamps at the beginning of each segment. This ensures each individual MP4 file starts at a timestamp of zero, making them compatible with standard media players.-c copy: Copies the input video and audio streams directly to the output files without re-encoding. This minimizes CPU load.output_%03d.mp4: The output naming pattern.%03dis a placeholder that produces sequentially numbered files, such asoutput_001.mp4,output_002.mp4, and so on.
Splitting at Precise Intervals
FFmpeg can only split a video segment on a keyframe (I-frame). If
your stream has a keyframe interval (GOP size) of every 5 seconds, the
segment boundaries will align closely with your specified
-segment_time. If the split timing is inaccurate, you must
configure your RTSP camera’s settings to output more frequent
keyframes.
Naming Files with Timestamps
If you prefer to name your MP4 files based on the actual date and
time of creation, use the -strftime option:
ffmpeg -rtsp_transport tcp -i rtsp://your_rtsp_stream_url -f segment -segment_time 600 -segment_format mp4 -reset_timestamps 1 -strftime 1 -c copy capture_%Y-%m-%d_%H-%M-%S.mp4In this command, -strftime 1 enables date and time
formatting, and capture_%Y-%m-%d_%H-%M-%S.mp4 generates
file names indicating the exact year, month, day, and time each segment
started recording.