I am trying to add chapter markers (text + images) to an existing video in iOS. Reading them is trivially easy with builtin functions:
NSLocale * locale = [chapterLocalications lastObject];
NSLog(@"Locale: %@", [locale localeIdentifier]);
NSArray *keys = @[AVMetadataCommonKeyTitle, AVMetadataCommonKeyArtwork];
NSArray *chapters = [asset chapterMetadataGroupsWithTitleLocale:locale containingItemsWithCommonKeys:keys];
for (AVTimedMetadataGroup * metadataGroup in chapters) {
NSArray * items = metadataGroup.items;
CMTimeRange timeRange = metadataGroup.timeRange;
NSLog(@"time: %@", CMTimeCopyDescription(NULL, timeRange.start));
for (AVMetadataItem * metadataItem in items) {
NSLog(@"key: %@", metadataItem.commonKey);
NSLog(@"value: %@", metadataItem.value);
}
}
So far I have not found a way to write timed metadata to a file. I can easily write normal metadata (like title text or pictures) using AVAssetExportSession and AVMutableMetadataItem. There is a AVMutableTimedMetadataGroup, but frustratingly there doesn't seem to be a way to actually write these to a track.
My current thinking is that I need to write chapter information into a temporary file and then use AVMutableComposition to merge the chapter track into the existing video. Of course, that leaves the problem of writing the chapter information. I could write an MP4 container manually or with a third party library (which I'd like to avoid), or I could try to convince AVAssetWriter to somehow write timed metadata tracks, though that is not documented, either. And then I still don't know if AVMutableComposition is able to merge chapter tracks.
Has anyone found a way to do this, before I go mad? I'm tempted to drop this whole chapter idea and just save an application-specific file that references the video.