How to Configure FFmpeg for Fragmented MP4 (fMP4)
This article provides a straightforward guide on how to configure FFmpeg to output fragmented MP4 (fMP4) files. You will learn the specific command-line flags required to enable fragmentation, understand how to control fragment duration, and see practical examples for remuxing and transcoding media into the fMP4 format.
Why Use Fragmented MP4?
Standard MP4 files write their metadata (the moov atom)
at the very beginning or end of the file. If a recording is interrupted,
or if you are streaming live video, a standard MP4 becomes unreadable.
Fragmented MP4 solves this by dividing the video into a sequence of
self-contained chunks (fragments), each with its own metadata. This
format is the standard for modern streaming protocols like MPEG-DASH and
HLS.
The Key FFmpeg Option: -movflags
To generate an fMP4 file in FFmpeg, you must use the
-movflags option. This option instructs the MP4 muxer to
change its default behavior. The two most critical flags for creating a
basic fMP4 are:
empty_moov: This writes an initial, emptymoovatom at the start of the file without any sample data, which is required for fMP4 compatibility.frag_keyframe: This tells FFmpeg to start a new fragment whenever it encounters a video keyframe (I-frame).
Example 1: Remuxing an Existing Video to fMP4
If your input file is already compressed with compatible codecs (like H.264 and AAC), you can package it into an fMP4 container without re-encoding. This process is extremely fast because it only copies the streams.
ffmpeg -i input.mp4 -codec copy -movflags empty_moov+frag_keyframe output.mp4Example 2: Transcoding and Customizing Fragment Duration
If you want to control how often fragments are created, you can define a specific duration instead of relying solely on keyframes.
frag_duration: Specifies the fragment duration in microseconds. For example,5000000equals 5 seconds.
To encode an input video to H.264/AAC and force fragments every 5 seconds, use the following command:
ffmpeg -i input.mkv -c:v libx264 -c:a aac -movflags empty_moov+frag_duration=5000000 output.mp4Additional Advanced Muxing Flags
Depending on your playback environment or streaming server, you may
need these additional -movflags configurations:
default_base_moof: Writes the absolute base data offset in each fragment’stfhdatom. This is highly recommended for DASH streaming and improves compatibility with various video players.omit_tfhd_offset: Omits the base data offset entirely from thetfhdatom, which can slightly reduce overhead.negative_cts_offsets: Enables negative composition time offsets, which improves handling of B-frames in modern players.
To combine these for maximum compatibility in modern streaming setups, use:
ffmpeg -i input.mp4 -codec copy -movflags empty_moov+frag_keyframe+default_base_moof output.mp4