CVMetalTextureCacheCreateTextureFromImage在macOS 10.13上返回-6660

Mar*_*bar 5 macos objective-c metal

我正在将屏幕从iPhone设备记录到Mac。作为预览层,我直接从中收集样本缓冲区AVCaptureVideoDataOutput,从中创建纹理并使用渲染它们Metal。我遇到的问题是,在macOS中工作的代码10.13在更新到后就停止工作了10.13。即

CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(_currentSampleBuffer);

if (!imageBuffer) return;

CVPixelBufferLockBaseAddress(imageBuffer,0);
size_t width = CVPixelBufferGetWidth(imageBuffer);
size_t height = CVPixelBufferGetHeight(imageBuffer);

CVMetalTextureRef metalTexture = NULL;
CVReturn result = CVMetalTextureCacheCreateTextureFromImage(nil,
                                                            self.textureCache,
                                                            imageBuffer,
                                                            nil,
                                                            self.pixelFormat,
                                                            width,
                                                            height,
                                                            0,
                                                            &metalTexture);

if (result == kCVReturnSuccess) {
    self.texture = CVMetalTextureGetTexture(metalTexture);
}
Run Code Online (Sandbox Code Playgroud)

返回值result = -6660(可以转换为通用值)kCVReturnError,可以在官方的Apple文档中看到,以及metalTexture = NULL

我使用的是像素格式MTLPixelFormatBGRG422,因为来自相机的样本是2vuy

作为metalTexture从创建的替代方法sampleBuffer,我现在正在创建一个中间件,NSImage如下所示:

    CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(_currentSampleBuffer);
    NSCIImageRep *imageRep = [NSCIImageRep imageRepWithCIImage:[CIImage imageWithCVImageBuffer:imageBuffer]];

    NSImage *image = [[NSImage alloc] initWithSize:[imageRep size]];
    [image addRepresentation:imageRep];
Run Code Online (Sandbox Code Playgroud)

然后MTLTexture从中创建一个。这显然是CVMetalTextureCacheCreateTextureFromImage直接使用的次等解决方案。

同样,有问题的代码在中也可以正常工作macOS < 10.13,我想知道是否有人遇到过类似的问题,如果有,您是否有解决此问题的想法?

Eli*_*eda 5

我碰到过同样的问题,问题不是在配置时要求Metal兼容性AVCaptureVideoDataOutput。我想系统开始在macOS 10.13中进行检查,可能会在不要求时进行一些优化。

解决方案是将添加kCVPixelBufferMetalCompatibilityKey到的videoSettings属性AVCaptureVideoDataOutput

在Objective-C中:

outputCapture.videoSettings = @{
  /* ... */
  (NSString *)kCVPixelBufferMetalCompatibilityKey: @YES
};
Run Code Online (Sandbox Code Playgroud)

在Swift中:

outputCapture.videoSettings = [
  /* ... */
  kCVPixelBufferMetalCompatibilityKey as String: true
]
Run Code Online (Sandbox Code Playgroud)

我认为这值得一看,要求苹果至少在发生这种情况时打印警告消息。我会更新的。