69
Any more efficient ways to convert a video (eg: MP4) to a GIF than with AVAssetImageGenerator generateCGImagesAsynchronously? Not exactly the fastest. :(
Post Body

For an app I build I'm trying to convert regular MP4 videos to GIFs. (Why? Lots of users are asking for it. Despite MP4s being more efficient, GIFs have better iOS support in things like Messages where they'll auto-play, loop, etc.)

This has proved a little tricky in terms of performance. AVAssetImageGenerator seems to be the main, built-in way to do this.

With it, Solution A is to either loop through each frame of the video individually and call copyCGImage to create an array of images that is then all shoved into an animated UIImage.

Solution B is similar but uses generateCGImagesAsynchronously, which Apple recommends when you're doing multiple frames like this and is a bit more efficient, plus effectively handles the frame-by-frame creation for you.

On an iPhone 11 with Solution A I'm seeing a conversion time of about 50% the length of the original video. (30 second video -> 15 seconds to convert to GIF)

With Solution B I'm seeing better, about 30% of the length of the original video. (30 second video -> 9 seconds to convert to GIF) An improvement no doubt, but still not fast.

This works okay, but isn't exactly the fastest. Is there some lower level functions I should be looking at that anyone would recommend? Preferably I'd rather not have users wait ~10 seconds when they tap save/copy on a GIF, and that's on the fastest iPhone currently available.

Updates

Tried playing around with popular video library ffmpeg, which has an iOS version. Long story short, it seems to be much faster, resulting in 2s to export the GIF compared to about 9s for AVAssetImageGenerator. But ffmpeg is absolutely enormous and adds 12MB to the app binary alone, so it's not really a solution I'd prefer.

Test Code if You Want to Play

Here's the basic code, it's pretty simple if you wanted to play around and see if you can speed it up at all. Should be able to copy and paste it into any view controller, for instance. This code takes about 8s on my iPhone 11 for reference.

https://gist.github.com/christianselig/50b9cd47ed9e5f7a7e580930f4c8c2b5

Author
Account Strength
100%
Account Age
13 years
Verified Email
Yes
Verified Flair
No
Total Karma
1,715,057
Link Karma
529,042
Comment Karma
607,499
Profile updated: 1 day ago
Posts updated: 1 month ago
Objective-C / Swift

Subreddit

Post Details

We try to extract some basic information from the post title. This is not always successful or accurate, please use your best judgement and compare these values to the post title and body for confirmation.
Posted
4 years ago