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:

  1. Target Size: 50 MB = 400,000,000 bits (using \(50 \times 1024 \times 1024 \times 8\)).
  2. Video Bitrate: 4000 Kbps (4,000,000 bps)
  3. Audio Bitrate: 128 Kbps (128,000 bps)
  4. Total Bitrate: 4128 Kbps (4,128,000 bps)
  5. 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.mp4

Parameter Breakdown