How to Play Encrypted HTTP Live Streams Offline with AVFoundation for iOS using Swift 4

Date published: May 16, 2019
8 min read
How to Play Encrypted HTTP Live Streams Offline with AVFoundation for iOS using Swift 4
1. Introduction to AVFoundation
AVFoundation is a framework that provides APIs for various media activities including capturing, editing, exporting and the playback of videos. This article will mainly focus on the playback of videos and how AVFoundation works with the HLS format.
AVFoundation Playback supports a wide selection of media formats (e.g. .mpeg, .avi, .aac, etc.) that can be played from the local storage or played over the network on a server. When the media file is on a server, it gets played using the progressive download playback. Once the download starts, even if the network quality changes, it will continue with the same media file. To add a dynamic change, formats like the HTTP live stream (HLS) appeared, which can adapt to a network quality change.
The main classes that we will cover in this article are the following:
  1. AVPlayer: The core class of playing videos on iOS.
  2. AVPlayerLayer: This is a CALayer subclass that can display the playback of a given AVPlayer instance.
  3. AVAsset: This is a representation of a media asset. An asset object contains information such as duration and creation date.
  4. AVPlayerItem: This represents the current state of a playable video. This is what you need to provide to an AVPlayer to get things going.
2. HTTP Live Streaming (HLS)
HLS is a protocol that allows you to send on-demand video, live video or audio streams to your devices. This technology is developed by Apple and it is optimised to deliver the best possible quality.
 
How exactly does HLS work? In short, the base URL usually refers to a master playlist that contains a list of URLs for variant media playlists that can vary in bit rate, resolution or quality level. This enables automatic switching between streams as network conditions change.
 
Media playlists are represented as text files saved in the M3U format (.m3u8) and contain URLs to a series of small files called media segments and other information needed for playback.
 
Normally, a media segment is represented as a short MPEG-2 transport stream file (.ts) that contains video/audio content with a duration of 5 to 10 seconds per file.
 
HLS offers a method to protect the media content through content encryption. The most commonly used method for HLS encryption is AES-128 encryption.
 
⦁ Here we have an example of a master playlist with three available variants with different resolutions:
#EXTM3U
#EXT-X-VERSION:3
#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=1755600,CODECS="avc1.42001f,mp4a.40.2",RESOLUTION=640x360
media/hls_360.m3u8
#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=2855600,CODECS="avc1.4d001f,mp4a.40.2",RESOLUTION=960x540
media/hls_540.m3u8
#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=5605600,CODECS="avc1.640028,mp4a.40.2",RESOLUTION=1280x720
media/hls_720.m3u8
⦁ This is an example of one of the variants from the masterlist above:
#EXTM3U
#EXT-X-VERSION:3
#EXT-X-TARGETDURATION:10
#EXT-X-MEDIA-SEQUENCE:0
#EXT-X-PLAYLIST-TYPE:VOD
#EXTINF:9.9001,
http://www.example.com/segment0.ts
#EXTINF:9.9001,
http://www.example.com/wifi/segment1.ts
#EXTINF:9.9001,
http://www.example.com/segment2.ts
#EXT-X-ENDLIST

3. Play HTTP Live Streams

To play a media file, we need to create an AVPlayer instance pointing at the video URL. 

Then to play/pause, we use these obvious commands:

func initializePlayer(videoUrl: URL) {
	let videoAsset = AVURLAsset(url: videoUrl)
    let playerItem = AVPlayerItem(asset: videoAsset)
    player = AVPlayer(playerItem: playerItem)
    playerLayer = AVPlayerLayer(player: player)
}

1. Create an AVUrlAsset from the video URL.

2. Create an AVPlayerItem with the AVURLAsset so that the player can have playback control.
3. Create the player from the player item.
4. Finally, add the player to the AVPlayerLayer to display the playback.
 
Then to play/pause, we use these obvious commands:
func play() {
   player.play()
}
func pause() {
   player.pause()
}

For encrypted HLS, the playlist contains the URL of the decryption key as shown below:

#EXTM3U
#EXT-X-VERSION:3
#EXT-X-TARGETDURATION:10
#EXT-X-MEDIA-SEQUENCE:0
#EXT-X-PLAYLIST-TYPE:VOD
#EXT-X-KEY:METHOD=AES-128,URI="https://www.example.com/hls.key",IV=0xecd0d06aef664d8226c33816e78efa44 
The video playback will work with the same method as the unencrypted HLS and the player will automatically access the key URL and download it.

4. Download encrypted HTTP Live Streams

To download an HLS asset, we will use an instance of the AVAssetDownloadURLSession, which is a class that supports the creation and execution of asset download tasks.

Because it’s an encrypted HLS, besides downloading the media file, we also need to download and save the encryption key locally. For this task, we will trigger the asset resource loader to access the .m3u8 files manually:
func initialiseDownloadSession() {
	let configuration = URLSessionConfiguration.background(withIdentifier: downloadIdentifier)
      downloadURLSession = AVAssetDownloadURLSession(
   	    configuration: configuration,
          assetDownloadDelegate: self,
          delegateQueue: OperationQueue.main
      )
}

We pass an AVURLAsset with the video URL to AVAssetDownloadURLSession, but before this, we need to replace the URL schema of the video URL with a fake one (“nothttps”).


This method forces the download task to call the AVAssetResourceLoader delegate because it cannot handle the fake URL:
func downloadTask(videoUrl: URL) {
	var urlComponents = URLComponents(
			url: videoUrl,
 			resolvingAgainstBaseURL: false
	)!
      urlComponents.scheme = "nothttps"  
      do {
          let asset = try AVURLAsset(url: urlComponents.asURL())
          asset.resourceLoader.setDelegate(self, queue: DispatchQueue(label: "com.example.AssetResourceLoaderDelegateQueue"))
          downloadURLSession
              .makeAssetDownloadTask(
				asset: asset,
			  	assetTitle: "My Video", 
				assetArtworkData: nil,
				options: nil
			 )?.resume()
      } catch { print("Erorr while parsing the URL.") }
}
In the resource loader, we check if the request has the URL we just modified. Then we change the schema back to the correct one and download the file with a URLSession.

Next, we return true to indicate that the delegate will load the requested resource:
func resourceLoader(
        _ resourceLoader: AVAssetResourceLoader,
        shouldWaitForLoadingOfRequestedResource loadingRequest:          AVAssetResourceLoadingRequest
        ) throws -> Bool {
    guard let url = loadingRequest.request.url else { return false }
    if url.scheme == "nothttps" {
           var urlComponents = URLComponents(
             url: url, 
		      resolvingAgainstBaseURL: false
		  )
     		  urlComponents!.scheme = "https"       
         let newUrl = try urlComponents!.asURL()
         downloadHlsFile(videoUrl: newUrl, loadingRequest: loadingRequest)
         return true
   }
	return false
}
The resource loader will be called as many times as the AVPlayer fails to interpret a resource. We are aiming to get inside a playlist variant, which is where the encryption key is located.
 
So, in the first request, we will get the master playlist and replace all the URL schemas for all the playlist variants with fake ones. Next, we will return the modified data in the loading request and then finish loading the request.
 
Now that we have replaced all the schemas with fake ones, when AVFoundation selects the best media stream, the shouldWaitForLoadingOfRequestedResource method from the delegate will be triggered again with one of the URLs from the master playlist.
 
In the second request, we will finally get access to the encryption key URL. Then we will extract the URL from the file and save it temporarily. We will then replace the key URL in the file with a fake one („notkeyhttps”) and respond with the modified data to the loading request.
func downloadHlsFile(videoUrl: URL, loadingRequest: AVAssetResourceLoadingRequest) {
    var request = URLRequest(url: videoUrl)
    request.httpMethod = "GET"
    let session = URLSession(configuration: URLSessionConfiguration.default)
    let task = session.dataTask(with: request) { data, response, _ in
        guard let data = data else { return }
        let strData = String(data: data, encoding: .utf8)!
        let modifiedData: Data!
        if strData.contains("EXT-X-KEY") {
            let start = strData.range(of: "URI=\"")!.upperBound
            let end = strData[start...].range(of: "\"")!.lowerBound
            let keyUrl = strData[start..<end]
            downloadHlsKey(keyUrl: keyUrl)
            let replacedKey = strData.replacingOccurrences(
                of: keyUrl,
                with: "notkeyhttps://example.com/hlsKey"
            )
            modifiedData = replacedKey.data(using: .utf8)
        } else {
            let replacedSchema = strData.replacingOccurrences(of: "https", with: "nothttps")
            modifiedData = replacedSchema.data(using: .utf8)
        }
        
        loadingRequest.contentInformationRequest?.contentType = response?.mimeType
        loadingRequest.contentInformationRequest?.isByteRangeAccessSupported = true
        loadingRequest.contentInformationRequest?.contentLength = response!.expectedContentLength
        loadingRequest.dataRequest?.respond(with: modifiedData)
        loadingRequest.finishLoading()
    }
    task.resume()
}
Now that we have modified the key URL schema, the delegate method shouldWaitForLoadingOfRequestedResource will trigger for a third time. We will detect when this happens and modify the data with the persistent key, which is the key that we saved locally.

Notice that for the previous requests, we used the MIME content type for the loading request; this time we will use AVStreamingKeyDeliveryPersistentContentKeyType as the content type. This will tell AVFoundation that the content contains the encryption key. 
 
So, the final version of shouldWaitForLoadingRequestedResource will look like this:
func resourceLoader(
        _ resourceLoader: AVAssetResourceLoader,
        shouldWaitForLoadingOfRequestedResource loadingRequest:          AVAssetResourceLoadingRequest
        ) throws -> Bool {
    guard let url = loadingRequest.request.url else { return false }
    if url.scheme == "nothttps" {
           var urlComponents = URLComponents(
             url: url, 
		      resolvingAgainstBaseURL: false
		  )
     		  urlComponents!.scheme = "https"       
         let newUrl = try urlComponents!.asURL()
         downloadHlsFile(videoUrl: newUrl, loadingRequest: loadingRequest)
         return true
   }
	return false
} else if url.scheme == "notkeyhttps" {
      let hlsKey = Keychain.getData(key: .hlsKey)
      loadingRequest.contentInformationRequest?.contentType = AVStreamingKeyDeliveryPersistentContentKeyType
        loadingRequest.contentInformationRequest?.isByteRangeAccessSupported = true
      loadingRequest.contentInformationRequest?.contentLength = hlsKey.count
      loadingRequest.dataRequest?.respond(with: hlsKey)
      loadingRequest.finishLoading()
      return true
}
While the AVFoundation is downloading each segment of the media file, we can monitor the progress using the AVAssetDownloadDelegate method. With this method, you can update the download progress in your app: 
func urlSession(_ session: URLSession, assetDownloadTask: AVAssetDownloadTask, didLoad timeRange: CMTimeRange, totalTimeRangesLoaded loadedTimeRanges: [NSValue], timeRangeExpectedToLoad: CMTimeRange) {
	var percentageComplete = 0.0
      for value in loadedTimeRanges {
          let loadedTimeRange = value.timeRangeValue
          percentageComplete += loadedTimeRange.duration.seconds / timeRangeExpectedToLoad.duration.seconds
      }
    	percentageComplete *= 100
      DispatchQueue.main.async { 
		  self.progressView.updateProgress(percentageComplete.toCGFloat) 
	}
}
When the download is finished, the following method will be called:
func urlSession(_ session: URLSession, assetDownloadTask: AVAssetDownloadTask, didFinishDownloadingTo location: URL) {
	OfflineHandler.save(key: .location, data: location.relativePath)
      let storageManager = AVAssetDownloadStorageManager.shared()
      let newPolicy = AVMutableAssetDownloadStorageManagementPolicy()
      newPolicy.expirationDate = Date().addYears(1)!
      newPolicy.priority = .important
      let baseURL = URL(fileURLWithPath: NSHomeDirectory())
      let assetURL = baseURL.appendingPathComponent(location.relativePath)
      storageManager.setStorageManagementPolicy(newPolicy, for: assetURL)
}
In this method, we get the location where the media file was downloaded. You should save this location because we will use it when the device is offline. Also, notice that the storage manager from iOS will delete files that it doesn’t consider to be very important from time to time.

In this case, we will set a policy for the new downloaded file with a duration and a priority level.
 

5. Play encrypted HTTP Live Streams Offline

func initializePlayer() {
	let assetPath = OfflineHandler.get(.location) as! String
	let baseURL = URL(fileURLWithPath: NSHomeDirectory())
      let assetURL = baseURL.appendingPathComponent(assetPath)
	let videoAsset = AVURLAsset(url: assetURL)
      videoAsset.resourceLoader.setDelegate(self, queue: DispatchQueue(label: "com.example.AssetResourceLoaderDelegateQueue"))
      let playerItem = AVPlayerItem(asset: videoAsset)
      player = AVPlayer(playerItem: playerItem)
      playerLayer = AVPlayerLayer(player: player)
}
To play the media asset offline, we will need to get the location of the file that we downloaded, make a URL from it, and pass it to an AVURLAsset. 
 
The data in the playlist file still has the fake URL schema for the encryption key, so the resource loader will still need to be called to interpret the key and when that happens, we will provide the key we saved locally.
func resourceLoader(
        _ resourceLoader: AVAssetResourceLoader,
        shouldWaitForLoadingOfRequestedResource loadingRequest:          AVAssetResourceLoadingRequest
        ) throws -> Bool {
    guard let url = loadingRequest.request.url else { return false }
    if url.scheme == "notkeyhttps" {
      let hlsKey = Keychain.getData(key: .hlsKey)
      loadingRequest.contentInformationRequest?.contentType = AVStreamingKeyDeliveryPersistentContentKeyType
loadingRequest.contentInformationRequest?.isByteRangeAccessSupported = true
      loadingRequest.contentInformationRequest?.contentLength = hlsKey.count
      loadingRequest.dataRequest?.respond(with: hlsKey)
      loadingRequest.finishLoading()
      return true
	}
	return false
}

Share on:

I have read and understood the ASSIST Software website's Terms of Use and Privacy Policy.

Want to stay on top of everything?

Get updates on industry developments and the software solutions we can now create for a smooth digital transformation.

Frequently Asked Questions

1. Can you integrate AI into an existing software product?

Absolutely. Our team can assess your current system and recommend how artificial intelligence features, such as automation, recommendation engines, or predictive analytics, can be integrated effectively. Whether it's enhancing user experience or streamlining operations, we ensure AI is added where it delivers real value without disrupting your core functionality.

2. What types of AI projects has ASSIST Software delivered?

We’ve developed AI solutions across industries, from natural language processing in customer support platforms to computer vision in manufacturing and agriculture. Our expertise spans recommendation systems, intelligent automation, predictive analytics, and custom machine learning models tailored to specific business needs.

3. What is ASSIST Software's development process?  

The Software Development Life Cycle (SDLC) we employ defines the stages for a software project. Our SDLC phases include planning, requirement gathering, product design, development, testing, deployment, and maintenance.

4. What software development methodology does ASSIST Software use?  

ASSIST Software primarily leverages Agile principles for flexibility and adaptability. This means we break down projects into smaller, manageable sprints, allowing continuous feedback and iteration throughout the development cycle. We also incorporate elements from other methodologies to increase efficiency as needed. For example, we use Scrum for project roles and collaboration, and Kanban boards to see workflow and manage tasks. As per the Waterfall approach, we emphasize precise planning and documentation during the initial stages.

5. I'm considering a custom application. Should I focus on a desktop, mobile or web app?  

We can offer software consultancy services to determine the type of software you need based on your specific requirements. Please explore what type of app development would suit your custom build product.   

  • A web application runs on a web browser and is accessible from any device with an internet connection. (e.g., online store, social media platform)   
  • Mobile app developers design applications mainly for smartphones and tablets, such as games and productivity tools. However, they can be extended to other devices, such as smartwatches.    
  • Desktop applications are installed directly on a computer (e.g., photo editing software, word processors).   
  • Enterprise software manages complex business functions within an organization (e.g., Customer Relationship Management (CRM), Enterprise Resource Planning (ERP)).

6. My software product is complex. Are you familiar with the Scaled Agile methodology?

We have been in the software engineering industry for 30 years. During this time, we have worked on bespoke software that needed creative thinking, innovation, and customized solutions. 

Scaled Agile refers to frameworks and practices that help large organizations adopt Agile methodologies. Traditional Agile is designed for small, self-organizing teams. Scaled Agile addresses the challenges of implementing Agile across multiple teams working on complex projects.  

SAFe provides a structured approach for aligning teams, coordinating work, and delivering value at scale. It focuses on collaboration, communication, and continuous delivery for optimal custom software development services. 

7. How do I choose the best collaboration model with ASSIST Software?  

We offer flexible models. Think about your project and see which model would be right for you.   

  • Dedicated Team: Ideal for complex, long-term projects requiring high continuity and collaboration.   
  • Team Augmentation: Perfect for short-term projects or existing teams needing additional expertise.   
  • Project-Based Model: Best for well-defined projects with clear deliverables and a fixed budget.   

Contact us to discuss the advantages and disadvantages of each model. 

1. Is ASSIST Software a reliable company for custom engineering?

Absolutely. Our partners have given us great recommendations and reviews, leading us to win The Manifest Award for Most Reviewed Software Developers. Further proof comes from our 97% employee retention rate and ongoing client partnerships for over 8 years.  

2. Are the ASSIST Software Romanian software engineers certified?

Yes. 85% of our software programmers are certified.  

At a company level, ASSIST Software is certified and recognized by industry players such as Microsoft, AWS, Google Cloud, Adobe, Drupal, Fujitsu, ISTQB, and others.  

Our employee certifications are tremendously important as they reflect the shared commitment to long-term growth.

3. Why should I choose Romania for custom software development? 

Romania has become a significant player in custom software development, attracting businesses worldwide. Romania boasts the highest number of certified IT specialists in Europe and ranks sixth globally, surpassing even the US in tech specialists per capita.  

At ASSIST Software, what sets us apart is our team and our location: our engineers are certified, experienced, and flexible, while being in the +2 GMT time zone allows us to easily facilitate meetings with clients all over the world.

4. What team will work on my project, and where will it be located?

ASSIST Software's headquarters is in Romania, a prime country for software development outsourcing. Our 350+ software engineers speak English and have a deep passion for innovation.  

We provide regular project updates through reports, meetings, and online dashboards. Generally, you'll have access to a dedicated project manager who will be your point of contact for any questions or concerns.  

5. How much will my project cost me?

Our prices are competitive, and as per our working model, we guarantee you will be satisfied with the result. Frequent meetings, check-ins, and a great communication structure will ensure this outcome.   

Project costs depend on various factors, including complexity, scope, required technologies, and team size. We'll gather detailed information about your project during the initial consultation to provide a customized quote and we guarantee that you will be able to see the benefits of bespoke software.  

1. What technologies do you work with?

ASSIST Software tackles your projects with a robust tech stack. We build native and cross-platform mobile apps, craft user-friendly web experiences, and create stunning visuals. 

Our wide-ranging expertise starts from Java, Python, and JavaScript frameworks to cutting-edge solutions like AR/VR, blockchain, and AI/ML. We also manage databases, leverage cloud platforms, and ensure flawless project execution. We're your one-stop shop for exceptional software development from concept to deployment. You can view our expertise for more details.   

2. Are you experienced in AI/ML development?

Yes. We have extensive experience in data engineering and machine learning operations (MLOps). We can employ neural networks, computer vision, and AI models to benefit your ideas.   

You can trust our long-term experience with big data, NLP, and sentiment analysis, as over the past three years, we led a European security project with 15 partners focused on detecting radicalization on social media and the dark web.

3. Do you have a research and development department and work on European Projects?

We know R&D is crucial for businesses to stay competitive and thrive in dynamic markets. Successful R&D efforts lead to developing exceptional products or services, improved efficiency and effectiveness in operations, and enhanced market positioning.   

We have established solid partnerships with 160+ European research companies, universities, and research centers (e.g., Fraunhofer, TWI, University of Heidelberg, REWE Group, SINTEF, etc.) and have participated as technical partners in over 25 EU-funded projects.  

4. Besides custom software solutions, what other services do you offer?

  • Design Thinking for Breakthrough Products:  

    We craft user experiences that resonate. Our design process is an immersive collaboration, starting with workshops to uncover your vision and user needs. We conduct market research, analyze the competition, and guide you toward cutting-edge solutions in accordance with your business requirements.  

  • Digital Transformation to Reimagine Your Business:

    Digital transformation is nothing less than a strategic shift. We empower you to become more agile and data-driven, optimizing core processes for the digital age.  

  • Scale with Confidence as We Build for Growth:  

    We understand that business success and development mean new challenges. Our solutions are built to scale seamlessly, accommodating increasing user bases and data volumes without sacrificing performance or security.  

5. As a company, does ASSIST have its own software products?

Yes, ASSIST Software teams have been involved in designing and developing innovative products that address community needs. One such example is the web and mobile platform Autisma. This therapy assistant enables continued learning for children diagnosed with autism spectrum disorder.   

Our extensive knowledge of the Unity and Unreal engines has allowed us to develop two mobile games, Elly and the Ruby Atlas and Hooman Invaders, as well as various Unity Assets, such as the Real-Time Weather PRO and Easy Sky. These two Unity assets allow Unity developers to control the weather and sky in their projects.   

1. Is ASSIST Software hiring right now?

We are always looking for great people to join our team, whether you're a senior software engineer or a new talent seeking an IT career. Please check our careers page and contact us. Our HR department will contact you as soon as possible.   

2. Is ASSIST Software organizing internships?

Yes. Each year, we organize individual and group internships for students. Our long-term partnership with the Stefan cel Mare University of Suceava allows us to put together great events for students and help them get started in the industry. 

3. What type of learning culture does ASSIST Software encourage?

Our focus on innovation comes from a 'can do' attitude and the continuous learning we encourage our colleagues to pursue. We frequently organize workshops, learning sessions, presentations, and masterclasses. All these events are free and open to our colleagues and aim to support their professional and personal development. 

4. How does ASSIST Software focus on teamwork?

The key to stellar teamwork is the quality time we spend together. ASSIST employees and their families are frequently invited to participate in all activities. We encourage a healthy lifestyle by promoting and organizing hikes, bike riding sessions, marathons, volleyball, football and tennis matches, ping-pong championships, and many more.   

We show our care for the environment through reforestation campaigns and forest cleaning activities.   

We also have an English-speaking club, e-sports gaming nights, tech discussions, networking parties, and board game sessions.   

5. How does ASSIST Software give back to the community?

Volunteering and charity are essential to us, which is why we founded the ASSIST Humanitarian Foundation. We genuinely care about our community and want to improve the future. We invest in IT equipment for schools and award excellent teachers. We also help hospitals and fire departments enter the 21st century.   

We sponsor cultural events and deliver humanitarian aid to those in need. If you agree with our views, you can also donate.   

ASSIST Software Team Members