CVMetalTextureCacheCreateTextureFromImage始终返回null

时间:2016-06-30 10:16:17

标签: ios metal core-video cvpixelbuffer metalkit

我正在尝试通过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时没有错误,

但它总是为yTexture返回null。

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

1 个答案:

答案 0 :(得分:8)

问题解决了。

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

一旦你使用了iosurface为null的CVPixelBuffer,那么MetalTexture总是为空。

应该做这样的事情:

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)