简体   繁体   English

如何将MTLTexture转换为CVpixelBuffer以写入AVAssetWriter?

[英]How to convert a MTLTexture to CVpixelBuffer to write into an AVAssetWriter?

I have a requirement to apply filters on the live video and I'm trying to do it in Metal. 我要求在实时视频上应用过滤器,我正在尝试在Metal中进行过滤。

But I have encountered problem with converting the MTLTexture into CVPixelBuffer after encoding the filter into destination filter. 但是在将过滤器编码为目标过滤器之后,我遇到了将MTLTexture转换为CVPixelBuffer的问题。 Reference ( https://github.com/oklyc/MetalCameraSample-master-2 ) 参考( https://github.com/oklyc/MetalCameraSample-master-2

Here are my codes. 这是我的代码。

if let pixelBuffer = pixelBuffer {
                CVPixelBufferLockBaseAddress(pixelBuffer, CVPixelBufferLockFlags.init(rawValue: 0))             
                let region = MTLRegionMake2D(0, 0, Int(currentDrawable.layer.drawableSize.width), Int(currentDrawable.layer.drawableSize.height))                    
                let bytesPerPixel = 4;
                let bytesPerRow = CGFloat(bytesPerPixel) * currentDrawable.layer.drawableSize.width

                let tempBuffer = CVPixelBufferGetBaseAddress(pixelBuffer)
                destinationTexture.getBytes(tempBuffer!, bytesPerRow: Int(bytesPerRow), from: region1, mipmapLevel: 0)

                let image = self.imageFromCVPixelBuffer(buffer: pixelBuffer)
                CVPixelBufferUnlockBaseAddress(pixelBuffer, CVPixelBufferLockFlags.init(rawValue: 0))

            }

The method imageFromCVPixelBuffer looks like this. imageFromCVPixelBuffer方法看起来像这样。

func imageFromCVPixelBuffer(buffer: CVPixelBuffer) -> UIImage {

    let ciimage = CIImage(cvPixelBuffer: buffer)
    let context = CIContext(options: nil)
    let cgimgage = context.createCGImage(ciimage, from: CGRect(x: 0, y: 0, width: CVPixelBufferGetWidth(buffer), height: CVPixelBufferGetHeight(buffer)))

    let uiimage = UIImage(cgImage: cgimgage!)

    return uiimage
}

Here is the screen shot of the image rendering through metal 这是通过金属渲染图像的屏幕截图

在此输入图像描述

Here is the screen shot of the same image converting MTLTexture to CVPixelBuffer. 以下是将MTLTexture转换为CVPixelBuffer的同一图像的屏幕截图。

在此输入图像描述

Converting MTLtexture into CVPixelBuffer is required to write into an AVAssetWriter and then saving it to the Library. 将MTLtexture转换为CVPixelBuffer需要写入AVAssetWriter,然后将其保存到库中。

Don't compute bytesPerRow yourself like that. 不要bytesPerRow自己计算bytesPerRow It's being passed in to Metal to let Metal know how to arrange the rows. 它被传递给Metal以让Metal知道如何排列行。 You want Metal to arrange them the way CVPixelBuffer expects them. 您希望Metal以CVPixelBuffer期望的方式CVPixelBuffer它们。 Therefore, you should use CVPixelBufferGetBytesPerRow() to determine the value. 因此,您应该使用CVPixelBufferGetBytesPerRow()来确定值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM