Function

CVMetalTextureCacheCreateTextureFromImage

Creates a Core Video Metal texture buffer from an existing image buffer.

Declaration

CVReturn CVMetalTextureCacheCreateTextureFromImage(CFAllocatorRef allocator, CVMetalTextureCacheRef textureCache, CVImageBufferRef sourceImage, CFDictionaryRef textureAttributes, MTLPixelFormat pixelFormat, size_t width, size_t height, size_t planeIndex, CVMetalTextureRef  _Nullable *textureOut);

Parameters

allocator

The CFAllocatorRef to use for allocating the texture.

textureCache

The texture cache object that will create and manage the texture.

sourceImage

The Core Video image buffer from which to create a Metal texture.

textureAttributes

A dictionary specifying options for creating the texture from the cache, or NULL to use default options.

pixelFormat

The Metal pixel format constant describing the image buffer’s data.

width

The width, in pixels, of the texture image.

height

The height, in pixels, of the texture image.

planeIndex

If the image buffer is planar, the index of the plane from which to map texture data. Ignored for non-planar image buffers.

textureOut

Upon return, contains the newly created Metal texture buffer.

Return Value

Upon successful creation of the texture, this function returns kCVReturnSuccess.

Discussion

This function creates or returns a cached Core Video Metal texture buffer mapped to an image buffer according to the specified, creating a live binding between a device-based image buffer and a MTLTexture object.

Note that Core Video does not explicitly declare any pixel format types to be Metal compatible. If you specify YES for the kCVPixelBufferMetalCompatibilityKey option when creating or requesting Core Video pixel buffers, those buffers will be Metal compatible. Thus, it is your responsibility to choose an appropriate pixel format for the buffers.

The following code snippet demonstrates some example mappings:

// Mapping a BGRA buffer:
CVMetalTextureCacheCreateTextureFromImage(kCFAllocatorDefault, textureCache, pixelBuffer, NULL, MTLPixelFormatBGRA8Unorm, width, height, 0, &outTexture);
 
// Mapping the luma plane of a 420v buffer:
CVMetalTextureCacheCreateTextureFromImage(kCFAllocatorDefault, textureCache, pixelBuffer, NULL, MTLPixelFormatR8Unorm, width, height, 0, &outTexture);
 
// Mapping the chroma plane of a 420v buffer as a source texture:
CVMetalTextureCacheCreateTextureFromImage(kCFAllocatorDefault, textureCache, pixelBuffer, NULL, MTLPixelFormatRG8Unorm width/2, height/2, 1, &outTexture);
 
// Mapping a yuvs buffer as a source texture (note: yuvs/f and 2vuy are unpacked and resampled -- not colorspace converted)
CVMetalTextureCacheCreateTextureFromImage(kCFAllocatorDefault, textureCache, pixelBuffer, NULL, MTLPixelFormatGBGR422, width, height, 1, &outTexture);