In a previous post I showed how to segment video for HLS using ffmpeg’s
segment muxer. In this one, I’ll demonstrate how to use ffmpeg’s
hls muxer. It has more features specific to HLS like support for encryption, subtitles, specifying the type of playlist, and so on.
To follow along, you’ll need a recent version of ffmpeg with support for HLS. (I used version 3.1.1 on Ubuntu 14.04.) To see if your version supports HLS, run the command below. You should see something like this:
$ ffmpeg -formats | grep hls
E hls Apple HTTP Live Streaming
D hls,applehttp Apple HTTP Live Streaming
If ffmpeg complains about an unrecognized option when executing the commands in this post, you can see what options are supported by running the following from a terminal:
$ ffmpeg -h muxer=hls
If an option is not supported, you’ll need to upgrade your version of ffmpeg.
Assuming the correct version of ffmpeg is installed, let’s jump right in and see how to use it to segment a video and create a video on-demand (VOD) playlist:
$ ffmpeg -y \
-i sample.mov \
-hls_time 9 \
-hls_segment_filename "/Library/WebServer/Documents/vod/fileSequence%d.ts" \
-hls_playlist_type vod \
Let’s break down the relevant parts of the above command. The segment duration (in seconds) is specified using the
-hls_time option. The location of where the segments should be written to is defined with the
-hls_segment_filename option; the path contains a format specifier (%d) similar to those supported by the printf function in C. The %d will be replaced with the current sequence number. In this case, the segments will be named fileSequence0.ts, fileSequence1.ts, fileSequence2.ts, and so on.
To create a VOD playlist we set the playlist type (
vod – the other possible value is
event. (For a live playlist, you don’t need to specify the type.) If your version of ffmpeg doesn’t support this option, omit it and add the
#EXT-X-PLAYLIST-TYPE:VOD tag to the playlist manually. However, if you do this you must set the list size to 0 (see below to see how to do this).
Let’s have a quick look at some of the other available options:
You can set the maximum number of entries in the playlist by using the
-hls_list_size option. Specifying the number of entries is only relevant when streaming live video; the default value is 5. Setting the playlist type to either
event implicitly sets the list size to 0, which means the playlist will contain all the segments.
Streaming live video can create a lot of segment files, particularly if the broadcast lasts several hours. This can require a lot of disk space. To avoid this problem, ffmpeg supports the
-hls_wrap option. Once the sequence number hits the specified limit, it wraps back to whatever the start number was set to. This effectively limits the maximum number of segment files written to disk.
For a complete list of the available options, take a look at the formats page on the official website.