Maintaining good scroll performance when using AVPlayer

Build your AVPlayerItem in a background queue as much as possible (some operations you have to do on the main thread, but you can do setup operations and waiting for video properties to load on background queues – read the docs very carefully). This involves voodoo dances with KVO and is really not fun.

The hiccups happen while the AVPlayer is waiting for the AVPlayerItems status to become AVPlayerItemStatusReadyToPlay. To reduce the length of the hiccups you want to do as much as you can to bring the AVPlayerItem closer to AVPlayerItemStatusReadyToPlay on a background thread before assigning it to the AVPlayer.

It’s been a while since I actually implemented this, but IIRC the main thread blocks are caused because the underlying AVURLAsset‘s properties are lazy-loaded, and if you don’t load them yourself, they get busy-loaded on the main thread when the AVPlayer wants to play.

Check out the AVAsset documentation, especially the stuff around AVAsynchronousKeyValueLoading. I think we needed to load the values for duration and tracks before using the asset on an AVPlayer to minimize the main thread blocks. It’s possible we also had to walk through each of the tracks and do AVAsynchronousKeyValueLoading on each of the segments, but I don’t remember 100%.

Leave a Comment