Search code examples
macosmetalrender-to-texturecore-video

How to specify TextureUsage for Textures created with CVMetalTextureCache


I need to create textures from CVPixelBuffers so I'm using the CVMetalTextureCache to generate them. I would like to use those textures as a render target, but I haven't find the way to specify the MTLTextureUsage.

TextureAttributes argument is marked as "reserved for future use"

if there is no way to do it, would it be faster to continue using the TextureCache and perform a blit or create the texture from a textureDescriptor?


Solution

  • I'm using a CVMetalTextureCache to generate Metal textures that originate from a CVPixelBufferPool. I am using CVMetalTextureCacheCreateTextureFromImage to create the Metal texture itself, like this:

    var pixelBuffer:CVPixelBuffer // this I get from CVPixelBufferPoolCreatePixelBufferWithAuxAttributes
    
    var mTexture:CVMetalTexture?
    let textureAttributes = [kCVPixelBufferPoolAllocationThresholdKey as String : Int(maxBufferCount)] as CFDictionary
    
    if  CVMetalTextureCacheCreateTextureFromImage(kCFAllocatorDefault, metalTextureCache,pixelBuffer!,textureAttributes,MTLPixelFormat.bgra8Unorm,Int(globals_L.displaySize[0]),Int(globals_L.displaySize[1]), 0, &mTexture)  != kCVReturnSuccess {
        print("Problem creating a metal texture from pixel buffer")
    }
    else {
        metalTexture = mTexture  // now we use this metalTexture to render 
    }
    

    Would that work for you?