FFmpeg HLS: Custom Segment Names and M3U8 Guide

This guide explains how to use FFmpeg's HTTP Live Streaming (HLS) muxer to slice video files into discrete segments, configure custom file-naming schemes using format specifiers, and automatically generate the corresponding .m3u8 playlist file. By utilizing flags like -hls_segment_filename and setting appropriate segment durations, you can tailor your HLS output for standard video-on-demand (VOD) or live streaming workflows.

Basic Command Structure

To generate an M3U8 playlist and split a video into segments, use the -f hls muxer option. You specify the segment naming convention with -hls_segment_filename and supply the playlist name as the final output argument.

ffmpeg -i input.mp4 -codec: copy -start_number 0 -hls_time 10 -hls_list_size 0 -hls_segment_filename "segment_%03d.ts" -f hls playlist.m3u8

Key Parameters Explained

  • -f hls: Instructs FFmpeg to use the HLS muxer.
  • -hls_time <seconds>: Sets the target segment duration in seconds. The actual duration depends on keyframe placement unless keyframes are forced.
  • -hls_segment_filename <pattern>: Defines the naming pattern for the generated media chunks.
  • -start_number <number>: Sets the starting index number for the segment sequence (default is 0).
  • -hls_list_size <number>: Defines the maximum number of playlist entries. Setting this to 0 includes all segments in the .m3u8 file, which is required for Video-on-Demand (VOD).
  • playlist.m3u8: The final positional argument serves as the output destination for the index playlist file.

Configuring Segment Naming Patterns

FFmpeg utilizes standard printf-style string formatting to generate sequence numbers for segment files:

  • Three-digit zero-padded numbers (%03d): Produces segment_000.ts, segment_001.ts, segment_002.ts.
  • Four-digit zero-padded numbers (%04d): Produces segment_0000.ts, segment_0001.ts, useful for longer streams.
  • Non-padded numbers (%d): Produces segment_0.ts, segment_1.ts.

Example with subdirectories and custom prefixes:

ffmpeg -i input.mp4 -c:v libx264 -c:a aac -hls_time 6 -hls_playlist_type vod -hls_segment_filename "chunks/stream_%04d.ts" chunks/index.m3u8

Date and Timestamp Formatting

You can include date and time information in the segment filenames by combining -strftime 1 with standard strftime format codes:

ffmpeg -i input.mp4 -f hls -hls_time 5 -strftime 1 -hls_segment_filename "segment_%Y%m%d_%H%M%S.ts" live.m3u8

This pattern generates files named according to the time of generation, such as segment_20231024_143000.ts. Note that when using -strftime 1, sequential integer formatting like %d is replaced by time specifiers.