5

I need to call the CMSampleBufferCreateCopy function to create a copy of the sampleBuffer, but I can't really figure out how to use it.

According to this solution it should work like that:

var bufferCopy: Unmanaged<CMSampleBuffer>!

let error = CMSampleBufferCreateCopy(kCFAllocatorDefault, sampleBuffer, &bufferCopy)

But it doesn't.

Error message I get:

Cannot invoke 'CMSampleBufferCreateCopy' with an argument list of type '(CFAllocator!, CMSampleBuffer!, inout Unmanaged<CMSampleBuffer>!)'

EDIT:

@availability(iOS, introduced=4.0)
func CMSampleBufferCreateCopy(allocator: CFAllocator!, sbuf: CMSampleBuffer!, sbufCopyOut: UnsafeMutablePointer<Unmanaged<CMSampleBuffer>?>) -> OSStatus

/*! @param allocator
                                                        The allocator to use for allocating the CMSampleBuffer object.
                                                        Pass kCFAllocatorDefault to use the default allocator. */
/*! @param sbuf
                                                        CMSampleBuffer being copied. */
/*! @param sbufCopyOut
                                                        Returned newly created CMSampleBuffer. */

/*!
    @function   CMSampleBufferCreateCopyWithNewTiming
    @abstract   Creates a CMSampleBuffer with new timing information from another sample buffer.
    @discussion This emulates CMSampleBufferCreateCopy, but changes the timing.
                Array parameters (sampleTimingArray) should have only one element if that same
                element applies to all samples. All parameters are copied; on return, the caller can release them,
                free them, reuse them or whatever.  Any outputPresentationTimestamp that has been set on the original Buffer
                will not be copied because it is no longer relevant.    On return, the caller owns the returned 
                CMSampleBuffer, and must release it when done with it.

 */
Community
  • 1
  • 1
hungrxyz
  • 745
  • 11
  • 20

1 Answers1

6

As you can see from the declaration of the last parameter,

sbufCopyOut: UnsafeMutablePointer<Unmanaged<CMSampleBuffer>?>

bufferCopy must be declared as optional, not as a implicitly unwrapped optional:

var bufferCopy: Unmanaged<CMSampleBuffer>?

Note that you have to call takeRetainedValue() on the result, so the complete solution would be:

var unmanagedBufferCopy: Unmanaged<CMSampleBuffer>?
if CMSampleBufferCreateCopy(kCFAllocatorDefault, sampleBuffer, &unmanagedBufferCopy) == noErr {
    let bufferCopy = unmanagedBufferCopy!.takeRetainedValue()
    // ...

} else {
    // failed
}

Update: In Swift 4 (and probably already in Swift 4), CMSampleBufferCreateCopy() returns a managed object, therefore the code simplifies to

var bufferCopy: CMSampleBuffer?
if CMSampleBufferCreateCopy(kCFAllocatorDefault, sampleBuffer, &bufferCopy) == noErr {
    // ... use bufferCopy! ...
} else {
    // failed
}
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382