Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialise CVPixelBufferRef in Swift

We used to initialize CVPixelBufferRef like below.

  CVPixelBufferRef pxbuffer = NULL;

But in Swift we can not use NULL, so we tried following but of course XCODE want us to have it initalized to use it

let pxbuffer: CVPixelBufferRef

but how ?

In Obj_C we were creating buffer like this, but as I was trying to explain above when converting to Swift I have been stopped at first line.

 CVPixelBufferRef pxbuffer = NULL;

CVPixelBufferCreate(kCFAllocatorDefault, picGenislik,
                    frameHeight, kCVPixelFormatType_32ARGB, (__bridge         CFDictionaryRef) options,
                    &pxbuffer);
like image 516
Hope Avatar asked Oct 10 '15 11:10

Hope


2 Answers

Use CVPixelBufferCreate(_:_:_:_:_:_:) to create the object

Adding some demo code, hope this helps you. Also do read Using Legacy C APIs with Swift

var keyCallBack: CFDictionaryKeyCallBacks
var valueCallBacks: CFDictionaryValueCallBacks

var empty: CFDictionaryRef = CFDictionaryCreate(kCFAllocatorDefault, nil, nil, 0, &keyCallBack, &valueCallBacks)

var attributes = CFDictionaryCreateMutable(kCFAllocatorDefault,
    1,
    &keyCallBack,
    &valueCallBacks);


var iOSurfacePropertiesKey = kCVPixelBufferIOSurfacePropertiesKey

withUnsafePointer(&iOSurfacePropertiesKey) { unsafePointer in
    CFDictionarySetValue(attributes, unsafePointer, empty)
}

var width = 10
var height = 12
var pixelBuffer: CVPixelBufferRef? = nil
var status: CVReturn = CVPixelBufferCreate(kCFAllocatorDefault, width, height, kCVPixelFormatType_32BGRA, attributes, &pixelBuffer)
like image 98
Inder Kumar Rathore Avatar answered Oct 29 '22 09:10

Inder Kumar Rathore


Here is another way to do it (Swift 3):

var pixelBuffer: UnsafeMutablePointer<CVPixelBuffer?>!
if pixelBuffer == nil {
pixelBuffer = UnsafeMutablePointer<CVPixelBuffer?>.allocate(capacity: MemoryLayout<CVPixelBuffer?>.size)
}
CVPixelBufferCreate(kCFAllocatorDefault, width, height, kCVPixelFormatType_32BGRA, attributes, pixelBuffer)

and then you can access the buffer object like this:

pixelBuffer.pointee

EDIT:

    pixelBuffer = UnsafeMutablePointer<CVPixelBuffer?>.allocate(capacity: MemoryLayout<CVPixelBuffer?>.size)

Creates a memory leak if you don't manually deallocate the pointer when you're done with it, to avoid this change your code to the following:

var pixelBuffer : CVPixelBuffer? = nil
CVPixelBufferCreate(kCFAllocatorDefault, cgimg.width, cgimg.height, kCVPixelFormatType_32BGRA, nil, &pixelBuffer)
like image 5
Samer Murad Avatar answered Oct 29 '22 09:10

Samer Murad