无法从CVMetalTextureGetTexture函数获取有效的MTLTexture

时间:2018-07-17 11:52:29

标签: ios objective-c swift metal core-video

我是金属新手。 我想从CVImageBufferRef制作MTLTexture。 我正在使用以下代码示例来做到这一点。

guard
        let unwrappedImageTexture = imageTexture,
        let texture = CVMetalTextureGetTexture(unwrappedImageTexture),
        result == kCVReturnSuccess
    else {
        throw MetalCameraSessionError.failedToCreateTextureFromImage
    }

此处,imageTexture:CVMetalTexture。 这是我在Obj C中的代码。

CVMetalTextureRef inputTexture;
NSString* key = (NSString*)kCVPixelBufferPixelFormatTypeKey;
NSNumber* value = [NSNumber numberWithUnsignedInt:kCVPixelFormatType_32BGRA];
AVAssetReaderTrackOutput track = [AVAssetReaderTrackOutput assetReaderTrackOutputWithTrack:video
                                                        outputSettings:@{
                                                            (NSString *)kCVPixelBufferMetalCompatibilityKey: @YES,
                                                            key:value
                                                        }];
sampleBuffer = [track copyNextSampleBuffer];
CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
size_t width = CVPixelBufferGetWidth(imageBuffer);
size_t height = CVPixelBufferGetHeight(imageBuffer);
if(kCVReturnSuccess != CVMetalTextureCacheCreateTextureFromImage(kCFAllocatorDefault, _context.textureCache , imageBuffer, NULL, MTLPixelFormatBGRA8Unorm, width, height, 0, &inputTexture)){
    __VMLog(@"Texture Creation Error");
}

id<MTLTexture> it = CVMetalTextureGetTexture(inputTexture); //Returns nil

我的MTLTexture变量总是无效。甚至纹理创建错误也没有发生。但不会生成MTLTexture。

1 个答案:

答案 0 :(得分:1)

我找到了解决方案。似乎需要ID数组才能获取MTLTexture。

    //Wrong approach
    id<MTLTexture> it = CVMetalTextureGetTexture(inputTexture);

    //Right approach
    id<MTLTexture> it[1];
    it[0] = CVMetalTextureGetTexture(inputTexture);