I use AVAssetResourceLoaderDelegate to decode on MacOS MP4 media fetched from network. The code works, but I am not sure that it properly handles nested calls to -shouldWaitForLoadingOfRequestedResource. That is, while the code fetches the data for one request asynchronously, another shouldWaitForLoadingOfRequestedResource arrives.
From logs I see that in most cases before the new request is issued the previous one is cancelled via didCancelLoadingRequest which the code handles. But sometimes the new request arrives without the cancelation.
Typically for the initial request
AVAssetResourceLoadingRequest.requestsAllDataToEndOfResource is true. The code handles that by asking the network subsystem to read the data in 64k chunks asynchronously until the end of the media. When each chunk arrives, the code calls
[[loadingRequest dataRequest] respondWithData:ns_data].
But then after few 64K chunks are delivered another AVAssetResourceLoadingRequest arrives. So far I see that it is always the request to read 64K with an earlier offset in the media file. What is the proper way to handle it?
The current code waits for the network to finish fetching the last asked 64K chunk for the previous request and deliver it with respondWithData. Then that request is set aside and the code asks to fetch 64K for the new request with the earlier offset in the media. When the data arrives, the code calls respondWithData and finishLoading on the new request and then continues to read the initial request. This seems to work, but I would like to make sure that this is the right way.
For example, if I change the code to queue the new request and just continue to read the data for the initial request until it is explicitly cancelled, then I got sometimes decoding errors from AVAssetReader. So it seems there are some ordering requirements for handling the nested shouldWaitForLoadingOfRequestedResource.