What is HTTP Live Streaming?
In short, HTTP Live Streaming (HLS) is a standardised protocol for delivering visual and audio media over the internet in smaller chunks. It supports the following:
- Live broadcasts and prerecorded content (video on demand, or VOD)
- Multiple alternate streams at different bit rates
- Intelligent switching of streams in response to network bandwidth changes
- Media encryption and user authentication
Starting playback of HLS
To play an HLS stream, a HTTP server needs to provide an M3U8 playlist file. This is a manifest file that serves as an index for the video chunks. Playing an HLS stream is rather simple. It works exactly the same as playing ordinary video files:
let path = "https://devstreaming-cdn.apple.com/videos/streaming/examples/bipbop_4x3/bipbop_4x3_variant.m3u8"
guard let url = URL(string: path) else { return }
let playerItem = AVPlayerItem(url: url)
AVPlayer(playerItem: playerItem)
Downloading HLS
Downloading an HLS stream is not as straight forward as downloading ordinary video files. We can not simply download the file at that url. This url points to an HLS manifest containing paths to all the video chunks of the stream, possibly also including alternate streams of varying bit rates and localisation options.
Additionally, iOS requires HLS to be downloaded and stored on the device in a very specific way. One of the main reasons being that the user can check which videos have been downloaded and optionally delete thesse videos from the Settings application.
Luckily AVFoundation
offers all the tools needed to download and retain HLS streams correctly. In short, we’ll need to:
- Configure AVAssetDownloadURLSession for HLS downloads
- Create an AVAssetDownloadTask and AVAggregateAssetDownloadTask
- Handle download related events using AVAssetDownloadDelegate
- Configure handling cellular access and discretionary downloading
- Optionally recreate our AVAssetDownloadURLSession to update the configuration
- And start playback of an HLS while downloading
This blogpost is part of a mini series of bite-sized blogs post dedicated to downloading HLS. In this series I will go over each step necessary to downloading HLS streams and handling downloaded HLS streams.