Configure MP4 Fragment Duration and Options in FFmpeg

This guide explains how to configure fragment duration and fragmentation options in the FFmpeg MP4 muxer. You will learn how to use specific command-line flags, such as -movflags and -frag_duration, to split MP4 files into sequential fragments, a crucial process for adaptive streaming protocols like DASH, HLS, and low-latency playback.

By default, the standard MP4 format writes its metadata (the moov atom) at the end of the file, making it unsuitable for live streaming or immediate playback. Fragmented MP4 (fMP4) solves this by dividing the video into a series of smaller, self-contained fragments.

To configure fragmentation in FFmpeg, you must use a combination of -movflags and fragment-specific options.

Step 1: Enable MP4 Fragmentation Using -movflags

Before you can set fragment durations, you must instruct the FFmpeg MP4 muxer to output a fragmented file. This is done using the -movflags option. The most common flags for fragmentation include:

Step 2: Set Fragment Duration Options

Once fragmentation is enabled, you can control the duration of these fragments using the following muxer private options:

Configuration Examples

Example 1: Fragmenting by Keyframe with a 5-Second Maximum

This command fragments the output MP4 at every keyframe, with a target maximum duration of 5 seconds per fragment:

ffmpeg -i input.mp4 -c:v libx264 -c:a aac -movflags frag_keyframe+empty_moov+default_base_moof -frag_duration 5000000 output.mp4

Example 2: Fragmenting with Exact Duration for Streaming (DASH/HLS Compatibility)

For precise adaptive bitrate streaming compliance, you should ensure your keyframe interval (GOP size) matches your desired fragment duration. If you want 4-second fragments, set your keyframe interval to 4 seconds and use the following command:

ffmpeg -i input.mp4 -c:v libx264 -g 100 -keyint_min 100 -sc_threshold 0 -c:a aac -movflags frag_keyframe+empty_moov+default_base_moof -frag_duration 4000000 output.mp4

(Note: -g 100 forces a keyframe every 100 frames. At 25 frames per second, this equals exactly 4 seconds, matching the -frag_duration 4000000 setting).

Verifying Fragmented Output

You can verify that your MP4 file has been successfully fragmented by inspecting the structure using ffprobe. Run the following command:

ffprobe -v trace output.mp4

Look for repeating moof (movie fragment) and mdat (media data) atoms throughout the console output. If you see multiple moof blocks instead of a single large moov block at the end, your fragmentation settings have been applied correctly.