3

我正在尝试让一个简单的渲染相机输出到金属层管道运行,它在 Objective-C 中运行良好(有 MetalVideoCapture 示例应用程序)但是当我尝试时似乎有一些格式怪异把它翻译成swift。我的超简单捕获缓冲区看起来像这样(忽略缺乏清理...)

    func captureOutput(captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, fromConnection connection: AVCaptureConnection!) {
    var error: CVReturn! = nil
    let sourceImageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)
    let width = CVPixelBufferGetWidth(sourceImageBuffer!)
    let height = CVPixelBufferGetHeight(sourceImageBuffer!)
    var outTexture: CVMetalTextureRef? = nil

    error  = CVMetalTextureCacheCreateTextureFromImage(kCFAllocatorDefault, videoTextureCache!, sourceImageBuffer!, nil, MTLPixelFormat.BGRA8Unorm, width, height, 0, &outTexture!)

    if error != nil {
        print("Error! \(error)")
    }

    let videoTexture = CVMetalTextureGetTexture(outTexture!)
    self.imageTexture = videoTexture!
}

videoTextureCache 在哪里var videoTextureCache: CVMetalTextureCache? = nil

但它给了我Cannot invoke 'CVMetalTextureCacheCreateTextureFromImage' with an argument list of type '(CFAllocator!, CVMetalTextureCache, CVImageBuffer, nil, MTLPixelFormat, Int, Int, Int, inout CVMetalTextureRef)'

问题是,如果我用 nil 替换 outTexture 它会停止抛出错误,但显然这对我没有帮助。根据函数的参考,我需要 UnsafeMutablePointer?> 作为最后一个值。我不知道如何得到。

4

2 回答 2

3

尝试提前分配你的纹理缓存,这是我用作成员变量的内容:

var _videoTextureCache : Unmanaged<CVMetalTextureCacheRef>?

然后我通过初始化方法分配纹理缓存

CVMetalTextureCacheCreate(kCFAllocatorDefault, nil, _context.device, nil, &_videoTextureCache)

其中 _context.device 是 MTLDevice。然后,在 captureOutput 方法中,我使用以下内容(请注意,此处不包含错误检查)

var textureRef : Unmanaged<CVMetalTextureRef>?
CVMetalTextureCacheCreateTextureFromImage(kCFAllocatorDefault, _videoTextureCache!.takeUnretainedValue(), imageBuffer, nil, MTLPixelFormat.BGRA8Unorm, width, height, 0, &textureRef)

我希望这有帮助!

于 2015-07-06T09:45:03.120 回答
2

更新@peacer212 对 Swift 3 的回答。

你不再需要UnmanagedtakeUnretainedValue。所以代码应该是:

var textureCache: CVMetalTextureCache?

...
CVMetalTextureCacheCreate(kCFAllocatorDefault, nil, _context.device, nil, &_videoTextureCache)

...

var textureRef : CVMetalTexture?
CVMetalTextureCacheCreateTextureFromImage(kCFAllocatorDefault, textureCache!, imageBuffer, nil, .bgra8Unorm, width, height, 0, & textureRef)
于 2017-04-04T02:51:50.940 回答