10

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
}
Chris
  • 2,739
  • 4
  • 29
  • 57
  • How did you determine that there is a memory leak? What kinds of objects are leaking? – warrenm May 26 '16 at 17:20
  • Are you using this to render a liver camera feed with some kind of filters? Please have a look at my question: https://stackoverflow.com/questions/53898780/how-to-apply-a-vignette-cifilter-to-a-live-camera-feed-in-ios – nr5 Dec 24 '18 at 09:23
  • 2
    What is videoTextureCache? – Roi Mulia Jul 25 '19 at 08:19
  • @RoiMulia you can use https://developer.apple.com/documentation/metal/mixing_metal_and_opengl_rendering_in_a_view : it shows how to use CVMetalTextureCacheCreate to create a texture cache – Pavan K May 21 '20 at 23:04

1 Answers1

7

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

Chris
  • 2,739
  • 4
  • 29
  • 57
  • For those Objective-C guys who encountered the same problem: `CFRelease(textureRef)` after `CVMetalTextureGetTexture()`. – Shuai Jun 26 '23 at 03:58