Search code examples
swiftmetal

How to create a MTLTexture backed by a CVPixelBuffer


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
}

Solution

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