FFmpeg Segment Muxer: Split Live Stream by Size
This article explains how to use FFmpeg’s segment muxer
to split an incoming live stream into smaller, sequential files based on
target file sizes. Because FFmpeg’s segment muxer natively
splits files by duration rather than exact byte size, you will learn how
to achieve precise size-based splitting by combining Constant Bitrate
(CBR) encoding with calculated segment times and strict keyframe
intervals.
The Methodology
Since the segment muxer does not have a direct
-segment_size option, you must calculate the required
segment duration (in seconds) to achieve your target file size.
Use this formula: Segment Time (seconds) = Target File Size (bits) / Total Bitrate (bits per second)
To ensure the file sizes remain consistent, you must enforce a Constant Bitrate (CBR) for both video and audio, and force keyframes at regular intervals. FFmpeg can only split segments at keyframes (I-frames); without regular keyframes, your segments will be uneven in both duration and file size.
Example Calculation
If you want to split a live RTMP stream into 50 MB segments:
- Target Size: 50 MB = 400,000,000 bits (using \(50 \times 1024 \times 1024 \times 8\)).
- Video Bitrate: 4000 Kbps (4,000,000 bps)
- Audio Bitrate: 128 Kbps (128,000 bps)
- Total Bitrate: 4128 Kbps (4,128,000 bps)
- Segment Time: 400,000,000 / 4,128,000 \(\approx\) 97 seconds
The FFmpeg Command
Use the following command structure to ingest a live stream, apply
CBR, force keyframes, and split the output using the
segment muxer:
ffmpeg -i rtmp://source.stream.com/live/input \
-c:v libx264 -b:v 4000k -maxrate 4000k -bufsize 2000k \
-g 50 -keyint_min 50 -sc_threshold 0 \
-c:a aac -b:a 128k \
-f segment -segment_time 97 -reset_timestamps 1 \
-map 0 output_%03d.mp4Parameter Breakdown
-c:v libx264: Encodes the video stream using H.264.-b:v 4000k -maxrate 4000k -bufsize 2000k: Enforces Constant Bitrate (CBR). The-bufsizecontrols the rate-control buffer; keeping it tight ensures the bitrate does not spike, keeping file sizes predictable.-g 50 -keyint_min 50 -sc_threshold 0: Forces a keyframe exactly every 50 frames (which is every 2 seconds on a 25fps stream) and disables scene-change detection to ensure keyframes occur at strict, predictable intervals.-f segment: Invokes the segment muxer.-segment_time 97: Sets the segment duration to the 97-second interval calculated earlier.-reset_timestamps 1: Resets timestamps at the beginning of each segment so that each output file starts at zero.output_%03d.mp4: Defines the output naming convention, generating sequential files likeoutput_001.mp4,output_002.mp4, etc.