Search code examples
iosswift2avfoundationunsafe-pointerscore-media

Create a copy of CMSampleBuffer in Swift 2.0


This has been asked before, but something must have changed in Swift since it was asked. I am trying to store CMSampleBuffer objects returned from an AVCaptureSession to be processed later. After some experimentation I discovered that AVCaptureSession must be reusing its CMSampleBuffer references. When I try to keep more than 15 the session hangs. So I thought I would make copies of the sample buffers. But I can't seem to get it to work. Here is what I have written:

var allocator: Unmanaged<CFAllocator>! = CFAllocatorGetDefault()
var bufferCopy: UnsafeMutablePointer<CMSampleBuffer?>
let err = CMSampleBufferCreateCopy(allocator.takeRetainedValue(), sampleBuffer, bufferCopy)
if err == noErr {
    bufferArray.append(bufferCopy.memory!)
} else {
    NSLog("Failed to copy buffer. Error: \(err)")
}

This won't compile because it says that Variable 'bufferCopy' used before being initialized. I've looked at many examples and they'll either compile and not work or they won't compile.

Anyone see what I'm doing wrong here?


Solution

  • Literally you're attempting to use the variable bufferCopy before it is initialized.

    You've declared a type for it, but haven't allocated the memory it's pointing to.

    You should instead create CMSampleBuffers using the following call https://developer.apple.com/library/tvos/documentation/CoreMedia/Reference/CMSampleBuffer/index.html#//apple_ref/c/func/CMSampleBufferCreate

    You should be able to copy the buffer into this then (as long as the format of the buffer matches the one you're copying from).