I have written a code to download HLS video and play it in offline mode. This code works fine for encoded video. Now I have a video which is AES encrypted and we are having custom encryption key for it. After downloading AES encrypted HLS video I am using below given code to supply key for decryption of video.
- (BOOL)resourceLoader:(AVAssetResourceLoader *)resourceLoader shouldWaitForLoadingOfRequestedResource:(AVAssetResourceLoadingRequest *)loadingRequest {
NSString *scheme = loadingRequest.request.URL.scheme;
if ([scheme isEqualToString:@"ckey"]) {
NSString *request = loadingRequest.request.URL.host;
NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:request];
if (data) {
[loadingRequest.dataRequest respondWithData:data];
[loadingRequest finishLoading];
} else {
// Data loading fail
}
}
return NO; }
I am intercepting a request for a key and passing key stored in UserDefaults for decryption.
This AES encrypted HLS video with custom key plays well when my device's wifi or data connection is off.
If I start playing this video when my device's wifi or data connection is enabled or if I enable my device's wifi or data connection while playing video; video stops playing immediately without any error and never plays again.
I have checked accessLog and errorLog of playerItem but haven't found anything helpful.
To provide a custom URL key after downloading of HLS content I am updating a content of .m3u8 file by replacing
URI="..."
string with
URI="ckey://..."
Is this a correct way to provide key for AES encrypted video?
and what could be the reason of this behaviour and how to solve this issue?
Thanks in advance.
Finally I managed to solve this issue. Rough package structure of downloaded HLS video is like given below:
In offline mode HLS video was playing perfectly. But when network connection was enabled it was referring to https: URL instead of local .frag files.
I replaced https: scheme in these files with custom scheme (fakehttps:) to restrict AVPlayer going online for resources.
This thing solved my issue but I don't know the exact reason behind it and how HLS is played by AVPlayer.
I referred this and got some idea so tried something .
I am updating this answer further to explain how to play encrypted video in offline mode.
This will update your download package structure for playing encrypted video in offline mode.
Now last thing to do is implement below given method of AVAssetResourceLoader class as follows
This method will provide key to video while playing to decrypt it.