Generating HLS m3u8 and TS Segments with FFmpeg

ffmpeg hlsm3u8 generationvideo segmentationhls playlistffmpeg commands
Published·Modified·

FFmpeg can split a complete video into TS segments and generate an m3u8 file, but the m3u8-segmenter tool previously used for this purpose has been abandoned by its author and is now deprecated. The author notes that both FFmpeg and libav now have direct support for segmenting and creating m3u files.

Conversion Method 1

  1. Convert the media file directly to TS:
ffmpeg -i cat.mp4 -c copy -bsf h264_mp4toannexb cat.ts
  1. Use the segment parameter to slice the video:
ffmpeg -i cat.ts -c copy -map 0 -f segment -segment_list playlist.m3u8 -segment_time 2 cat_output%03d.ts

Conversion Method 2

  1. Use FFmpeg slicing commands to output video in H264 and AAC formats:
ffmpeg -i input.mp4 -c:v libx264 -c:a aac -strict -2 -f hls output.m3u8
  1. Key FFmpeg HLS parameters:
  • -hls_time n: Sets the duration of each segment in seconds (default is 2).
  • -hls_list_size n: Sets the maximum number of entries to keep in the playlist (set to 0 to keep all segments; default is 5).
  • -hls_wrap n: Sets how many segments to store before overwriting (set to 0 to disable overwriting; default is 0). This helps limit disk usage.
  • -hls_start_number n: Sets the starting sequence number in the playlist (default is 0).
  1. Example usage of FFmpeg slicing:
ffmpeg -i output.mp4 -c:v libx264 -c:a aac -strict -2 -f hls -hls_list_size 0 -hls_time 5 data/output.m3u8

Note: When opening the generated m3u8 file in VLC, dragging the timeline may result in missing video frames. This issue requires further investigation.

References