Record a video at >1x speed (i.e. 2x, 3x, etc.)

Hello, I am trying to record a video using AVFoundation with a higher than normal playback speed. So for example instead of playing back at 1x speed, the video should play back at 3x speed. Ideally I'd be able to set the playback speed per frame, so some parts of the video would be 1x and others, 3x.

I found there is something called kCMSampleBufferAttachmentKey_SpeedMultiplier that seems like it should do what I want, but it doesn't seem to have any effect at all - the final recording plays back at 1x.

I also heard from Apple that I'm supposed to set kCMSampleBufferAttachmentKey_TrimDurationAtEnd and kCMSampleBufferAttachmentKey_TrimDurationAtStart.

So I do all this (with the code below), but the result is a normal 1x speed recording.

Here is the code I'm using:

extension CMSampleBuffer {
func changePlaybackSpeed(to speedMultiplier: Double) {
        
        let multipliedSpeed = NSNumber(value: speedMultiplier)
        CMSetAttachment(self, key: kCMSampleBufferAttachmentKey_SpeedMultiplier, value: multipliedSpeed, attachmentMode: kCMAttachmentMode_ShouldPropagate)
        
        if outputDuration != .invalid {
            let amountToTrim =  0.5 (1 - (1 / speedMultiplier) )
            let timeToTrim = CMTime(value: Int64(  amountToTrim * Double(outputDuration.value) ), timescale: outputDuration.timescale)
            
            let trimFromEndDict = CMTimeCopyAsDictionary(timeToTrim, allocator: kCFAllocatorDefault)
            CMSetAttachment(self, key: kCMSampleBufferAttachmentKey_TrimDurationAtEnd, value: trimFromEndDict, attachmentMode: kCMAttachmentMode_ShouldPropagate)

            let trimFromBeginningDict = CMTimeCopyAsDictionary(timeToTrim, allocator: kCFAllocatorDefault)
            CMSetAttachment(self, key: kCMSampleBufferAttachmentKey_TrimDurationAtEnd, value: trimFromBeginningDict, attachmentMode: kCMAttachmentMode_ShouldPropagate)
        }
    }

Another mystery is that for video frame CMSampleBuffers, they are always returning outputDuration as kCMTimeInvalid. Even in the Apple sample app AVMultiCam this is the case. So I can't calculate the trim values from the duration. The documentation says this should only return 'invalid' if there is an error, but I have no idea how to check for this error.

Record a video at >1x speed (i.e. 2x, 3x, etc.)
 
 
Q