I'm trying to play a mp4 video on my server and I'd like to cache this video to disk simultaneously.
I know that I can just use 2 requests to do this, one for download another one created by AVPlayer to play the video, but this will waste the network bandwidth.
So I need to use just one outer request to download the data and capture all NSURLRequest from AVPlayer in MyNSURLProtocol and manually create NSHTTPURLResponse for them.
This is how the workflow looks like:
AVPlayer <--> MyNSURLProtocol <--> mp4 over network.
By using Charles I can see that AVPlayer takes 2 steps to play a video on the Internet. The 1st step is to download the first 2 bytes in order to know the whole video file size. The following requests will download different parts of the file concurrently.
So what MyNSURLProtocol does is just downloading for the whole mp4 file with an outer request and when there's enough data, it will create responses that are sent to AVPlayer (also the data).
This is how it creates and sends the response.. for the 2-bytes request.
NSMutableDictionary* headers = ... // Config the headers like this:
{
"Accept-Ranges" = bytes;
"Cache-Control" = public;
"Content-Length" = 2;
"Content-Range" = "bytes 0-1/6581417";
"Content-Type" = "video/3gpp";
Date = "Thu, 18 Apr 2013 08:34:35 GMT";
Expires = "Wed, 12 Feb 2014 08:34:35 GMT";
"Last-Modified" = "Tue, 16 Apr 2013 09:03:35 GMT";
"Connection" = Close;
Server = "gvs 1.0";
"X-Content-Type-Options" = nosniff;
}
NSHTTPURLResponse* response = [[NSHTTPURLResponse alloc] initWithURL:
self.request.URL statusCode:206 HTTPVersion:@"HTTP/1.1" headerFields:headers];
[self.client URLProtocol:self didReceiveResponse:response
cacheStoragePolicy:NSURLCacheStorageAllowed];
The problem is AVPlayer doesn't send following requests to fetch the actual data, hm... Any clue?
OK, finally I found this: How to play movie with a URL using a custom NSURLProtocol?
It seems that custom NSURLProtocol can not work with AVPlayer. So I give up.