How to convert a MTLTexture to CVpixelBuffer to write into an AVAssetWriter?

∥☆過路亽.° 提交于 2019-12-19 09:25:07

问题


I have a requirement to apply filters on the live video and I'm trying to do it in Metal.

But I have encountered problem with converting the MTLTexture into CVPixelBuffer after encoding the filter into destination filter. Reference (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.

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.

Converting MTLtexture into CVPixelBuffer is required to write into an AVAssetWriter and then saving it to the Library.


回答1:


Don't compute bytesPerRow yourself like that. It's being passed in to Metal to let Metal know how to arrange the rows. You want Metal to arrange them the way CVPixelBuffer expects them. Therefore, you should use CVPixelBufferGetBytesPerRow() to determine the value.



来源:https://stackoverflow.com/questions/44842661/how-to-convert-a-mtltexture-to-cvpixelbuffer-to-write-into-an-avassetwriter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!