CVMetalTextureCacheCreateTextureFromImage 总是 return null

CVMetalTextureCacheCreateTextureFromImage always return null

我正在尝试通过 MetalKit 渲染 I420(YCbCr 规划器)

大多数示例都使用来自 Camera 的 CMSampleBuffer,

但我的目标是使用给定的 I420 字节。

我是这样做的:

let data = NSMutableData(contentsOfURL: NSBundle.mainBundle().URLForResource("yuv_640_360", withExtension: "yuv")!)

// Cache for Y

CVMetalTextureCacheCreate(kCFAllocatorDefault, nil, self.device!, nil, &videoTextureCache)

var pixelBuffer: CVPixelBuffer?

CVPixelBufferCreateWithBytes(kCFAllocatorDefault, Int(size.width), Int(size.height), kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange, data.mutableBytes, Int(size.width), nil, nil, [
    "kCVPixelBufferMetalCompatibilityKey": true,
    "kCVPixelBufferOpenGLCompatibilityKey": true,
    "kCVPixelBufferIOSurfacePropertiesKey": []
    ]
    , &pixelBuffer)

// Y texture

var yTextureRef : Unmanaged<CVMetalTexture>?

let yWidth = CVPixelBufferGetWidthOfPlane(pixelBuffer, 0)

let yHeight = CVPixelBufferGetHeightOfPlane(pixelBuffer, 0)

let result = CVMetalTextureCacheCreateTextureFromImage(kCFAllocatorDefault, (videoTextureCache?.takeUnretainedValue())!, pixelBuffer, nil, MTLPixelFormat.R8Unorm, yWidth, yHeight, 0, &yTextureRef);

基本上代码与其他示例几乎相同,但我自己创建了自己的 CVPixelBuffer。

我在创建 CVPixelBuffer 和 CVMetalTexture 时没有出错,

但它总是 return yTexture 为 null。

如何创建正确的 CVPixelBuffer 并使用它进行渲染?

问题已解决。

iosurface 很重要,我发现如果通过 CVPixelBufferCreateWithBytes 或 CVPixelBufferCreateWithPlanarBytes 创建 CVPixelBuffer,iosurface 始终为 null。

一旦您使用 iosurface 为 null 的 CVPixelBuffer,MetalTexture 将始终为 null。

应该这样做:

let result = CVPixelBufferCreate(kCFAllocatorDefault, width, height, kCVPixelFormatType_420YpCbCr8Planar, [
    String(kCVPixelBufferIOSurfacePropertiesKey): [
        "IOSurfaceOpenGLESFBOCompatibility": true,
        "IOSurfaceOpenGLESTextureCompatibility": true,
        "IOSurfaceCoreAnimationCompatibility": true,
        ]
    ], &self.pixelBuffer)

CVPixelBufferLockBaseAddress(self.pixelBuffer!, 0)

for index in 0...2 {

    memcpy(CVPixelBufferGetBaseAddressOfPlane(self.pixelBuffer!, index), planesAddress[index], planesWidth[index] * planesHeight[index])

}

CVPixelBufferUnlockBaseAddress(self.pixelBuffer!, 0)