Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a MTLTexture backed by a CVPixelBuffer

Tags:

swift

metal

What's the correct way to generate a MTLTexture backed by a CVPixelBuffer?

I have the following code, but it seems to leak:

func PixelBufferToMTLTexture(pixelBuffer:CVPixelBuffer) -> MTLTexture
{
    var texture:MTLTexture!

    let width = CVPixelBufferGetWidth(pixelBuffer)
    let height = CVPixelBufferGetHeight(pixelBuffer)

    let format:MTLPixelFormat = .BGRA8Unorm


    var textureRef : Unmanaged<CVMetalTextureRef>?

    let status = CVMetalTextureCacheCreateTextureFromImage(nil,
                                                           videoTextureCache!.takeUnretainedValue(),
                                                           pixelBuffer,
                                                           nil,
                                                           format,
                                                           width,
                                                           height,
                                                           0,
                                                           &textureRef)

    if(status == kCVReturnSuccess)
    {
        texture = CVMetalTextureGetTexture(textureRef!.takeUnretainedValue())
    }

    return texture
}
like image 725
Chris Avatar asked May 25 '16 18:05

Chris


1 Answers

Ah, I was missing: textureRef?.release()

like image 93
Chris Avatar answered Nov 17 '22 16:11

Chris