Segmented and Fragmented MP4 Recording with FFmpeg

Abstract: Split long FFmpeg recordings into playable fragmented MP4 segments using segment muxer and movflags to prevent playback issues and manage disk space.

Created: 2026-10-02 by
Use the -f segment muxer with -segment_time and -reset_timestamps 1 to split recordings into manageable chunks. Append -movflags +frag_keyframe+empty_moov to ensure each segment is a valid, playable fragmented MP4 file that can be concatenated later without re-encoding.

Understanding Fragmented MP4 Structure

Standard MP4 files store metadata in a single header at the beginning of the file. This structure works well for short clips but becomes problematic for long recordings because the entire file must be written before it is fully playable or seekable. Fragmented MP4 (fMP4) changes this by distributing metadata across multiple moof (movie fragment) boxes throughout the stream. This allows players to start playback almost immediately after receiving the first few kilobytes of data, which is critical for live streaming and continuous recording scenarios. When you record in segments, you are essentially creating a series of these small, self-contained fragments rather than one monolithic container.

Essential FFmpeg Flags for Segmentation

To achieve this behavior, you need to combine several specific flags. The core mechanism is the segment muxer, which handles the splitting logic. You must specify the format as -f segment. Then, use -segment_time to define the duration of each chunk in seconds. For example, setting this to 60 creates a new file every minute. It is crucial to add -reset_timestamps 1. Without this, timestamps accumulate across all segments, causing playback issues when individual files are opened in isolation. Each segment should appear as if it started at time zero. The most important flag for MP4 compatibility is -movflags. You should use +frag_keyframe+empty_moov. The frag_keyframe option ensures that each segment starts with a keyframe, making it independently decodable. The empty_moov flag prevents the creation of a large initial index, keeping the file size minimal and allowing for faster writes. If you omit these, you might get standard MP4 segments that cannot be played until the recording stops, defeating the purpose of real-time segmentation. For more information on stabilizing large video files during processing, see our guide on stabilizing large videos with Linux Mint and ffmpeg. This technique often pairs well with segmented recording when dealing with high-motion content.

Constructing the Command Line

A typical command for recording a webcam or screen input looks like this:
ffmpeg -f v4l2 -i /dev/video0 \
-c:v libx264 -preset ultrafast -tune zerolatency \
-f segment -segment_time 300 -reset_timestamps 1 \
-movflags +frag_keyframe+empty_moov \
output_%03d.mp4
Here, -c:v libx264 uses the H.264 encoder, which is widely supported. The -preset ultrafast minimizes CPU load, which is vital for long-term recording stability. The output pattern output_%03d.mp4 generates files named output_001.mp4, output_002.mp4, etc. Adjust the codec settings based on your hardware capabilities. If you are using hardware acceleration, such as NVENC, you may encounter errors related to version queries. Refer to the article on solving failed to query nvenc max version error if you face driver-specific issues while trying to optimize encoding speed.

Managing Disk Space and File Growth

Continuous recording will eventually fill your storage. Since each segment is an independent file, you can implement simple shell scripts to monitor disk usage. For instance, you can set up a cron job that checks the total size of the output_*.mp4 files and deletes the oldest ones when a threshold is reached. Because the files are fragmented MP4s, they do not require complex merging to be viewed individually. However, if you need a single consolidated file for archival, you can concatenate them using the concat demuxer. Note that concatenation requires all segments to have identical parameters; otherwise, you must remux them into a common format first.

Playback and Compatibility Considerations

Fragmented MP4 files are supported by modern web browsers and mobile devices, including iOS and Android. However, some older media players might struggle with the empty_moov structure. If you need maximum compatibility for offline playback, consider converting the final segments back to standard MP4 containers after the recording session ends. This post-processing step adds overhead but ensures universal playability. For users looking to optimize their videos for specific devices like iPhones, check out converting video to play on iPhone with ffmpeg on Linux for detailed profile adjustments.

Frequently Asked Questions

Can I merge fragmented MP4 segments without re-encoding?

Yes, you can use the FFmpeg concat demuxer to join them losslessly. Create a text file listing the filenames and run ffmpeg -f concat -i list.txt -c copy merged.mp4. Ensure all segments were created with identical codecs and resolutions.

Why does my player freeze when opening a single segment?

This usually happens if you omitted -movflags +frag_keyframe. Without a keyframe at the start, the decoder cannot locate the beginning of the frame data efficiently. Adding the flag ensures each file is self-contained and seekable from the first frame.

How do I handle audio synchronization across segments?

Always include -reset_timestamps 1 for both video and audio streams. This resets the internal clock for each new file, preventing drift or silence gaps between segments. Verify that your audio codec matches the video codec's timing assumptions.

Is it better to use MKV or MP4 for long recordings?

MKV is generally more robust for live recording because it handles interruptions gracefully. However, MP4 is preferred for web distribution and mobile playback. Use MP4 if you need broad compatibility; choose MKV if you prioritize ease of recovery after crashes.

What happens if the recording process crashes?

Since each segment is written separately, partial corruption usually affects only the current chunk. The previous segments remain intact and playable. You can restart the recording process, and FFmpeg will continue generating new numbered files, leaving old data untouched.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More