How to Split RTMP Stream by Size in FFmpeg
This article explains how to capture an incoming live RTMP stream, save it to your local storage, and split the recorded files into manageable sizes using FFmpeg. Because splitting video files strictly by physical byte size can corrupt file headers and render the video unplayable, the most reliable method is to use FFmpeg’s segment muxer to split the files by time duration, calculated to match your target file size.
The FFmpeg Command
To capture an RTMP feed and split it, run the following command in your terminal:
ffmpeg -i rtmp://your_server_ip/live/stream_key -c copy -f segment -segment_time 600 -reset_timestamps 1 output_%03d.mp4Parameter Breakdown
-i rtmp://your_server_ip/live/stream_key: Specifies the input URL of your live RTMP stream.-c copy: Copies the video and audio codecs directly without re-encoding. This keeps CPU usage extremely low and preserves the original stream quality.-f segment: Tells FFmpeg to use the segment muxer, which splits the output into multiple sequential files.-segment_time 600: Sets the duration of each video segment in seconds. In this example, 600 seconds (10 minutes) is used.-reset_timestamps 1: Resets the timestamps at the beginning of each segment so that each output file starts at zero seconds, making them compatible with standard media players.output_%03d.mp4: Defines the naming convention for the output files.%03dis a placeholder that automatically formats the files sequentially (e.g.,output_001.mp4,output_002.mp4).
How to Calculate Segment Time for Target File Sizes
Since FFmpeg cannot split files natively by exact megabytes without
risking file corruption, you must calculate the
-segment_time based on your stream’s bitrate to achieve
your desired file size.
The Formula
\[\text{Segment Time (seconds)} = \frac{\text{Target File Size in Megabits (Mb)}}{\text{Total Stream Bitrate in Megabits per second (Mbps)}}\]
Example Calculation
If your RTMP stream has a combined video and audio bitrate of 4 Mbps (4000 kbps), and you want each split file to be approximately 500 MB (Megabytes) in size:
- Convert Megabytes to Megabits:
\[500 \text{ MB} \times 8 = 4000 \text{ Mb}\] - Divide by the stream bitrate:
\[\frac{4000 \text{ Mb}}{4 \text{ Mbps}} = 1000 \text{ seconds}\]
In this scenario, you would set your parameter to
-segment_time 1000 to get output files of approximately 500
MB each.