ios - 如何在 AVCaptureSession 中为视频的每一帧应用过滤器?

标签 ios avcapturesession cifilter ciimage

我正在编写一个应用程序,它需要对使用 AVCaptureSession 捕获的视频应用过滤器。过滤后的输出被写入输出文件。我目前使用 CIFilter 和 CIImage 来过滤每个视频帧。 这是代码:

func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, from connection: AVCaptureConnection!) {
    ...
    let pixelBuffer = CMSampleBufferGetImageBuffer(samples)!
    let options = [kCVPixelBufferPixelFormatTypeKey as String : kCVPixelFormatType_420YpCbCr8BiPlanarFullRange]
    let cameraImage = CIImage(cvImageBuffer: pixelBuffer, options: options)
    let filter = CIFilter(name: "CIGaussianBlur")!
    filter.setValue((70.0), forKey: kCIInputRadiusKey)
    filter.setValue(cameraImage, forKey: kCIInputImageKey)
    let result = filter.outputImage!
    var pixBuffer:CVPixelBuffer? = nil;
    let fmt = CVPixelBufferGetPixelFormatType(pixelBuffer)
    CVPixelBufferCreate(kCFAllocatorSystemDefault,
                        CVPixelBufferGetWidth(pixelBuffer),
                        CVPixelBufferGetHeight(pixelBuffer),
                        fmt,
                        CVBufferGetAttachments(pixelBuffer, .shouldPropagate),
                        &pixBuffer);

    CVBufferPropagateAttachments(pixelBuffer, pixBuffer!)
    let eaglContext = EAGLContext(api: EAGLRenderingAPI.openGLES3)!
    eaglContext.isMultiThreaded = true
    let contextOptions = [kCIContextWorkingColorSpace : NSNull(), kCIContextOutputColorSpace: NSNull()]
    let context = CIContext(eaglContext: eaglContext, options: contextOptions)
    CVPixelBufferLockBaseAddress( pixBuffer!, CVPixelBufferLockFlags(rawValue: 0))
    context.render(result, to: pixBuffer!)
    CVPixelBufferUnlockBaseAddress( pixBuffer!, CVPixelBufferLockFlags(rawValue: 0))
    var timeInfo = CMSampleTimingInfo(duration: sampleBuffer.duration,
                                      presentationTimeStamp: sampleBuffer.presentationTimeStamp,
                                      decodeTimeStamp: sampleBuffer.decodeTimeStamp)
    var sampleBuf:CMSampleBuffer? = nil;
    CMSampleBufferCreateReadyWithImageBuffer(kCFAllocatorDefault,
                                             pixBuffer!,
                                             samples.formatDescription!,
                                             &timeInfo,
                                             &sampleBuf)

    // write to video file
    let ret = assetWriterInput.append(sampleBuf!)
    ...
}

来自 AVAssetWriterInput.append 的 ret 始终为 false。我在这里做错了什么?另外,我使用的方法效率很低。在此过程中会创建一些临时副本。是否可以就地进行?

最佳答案

我用了几乎相同的代码来解决同样的问题。我发现为渲染创建的像素缓冲区有问题。 append(sampleBuffer:) 总是返回 false 而 assetWriter.error

Error Domain=AVFoundationErrorDomain Code=-11800 "The operation could not be completed" UserInfo={NSUnderlyingError=0x17024ba30 {Error Domain=NSOSStatusErrorDomain Code=-12780 "(null)"}, NSLocalizedFailureReason=An unknown error occurred (-12780), NSLocalizedDescription=The operation could not be completed}

他们说这是一个错误(如 here 所述),已发布:https://bugreport.apple.com/web/?problemID=34574848 .

但没想到我发现使用原始像素缓冲区进行渲染时问题消失了。见下面的代码:

let sourcePixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)!
let sourceImage = CIImage(cvImageBuffer: sourcePixelBuffer)
let filter = CIFilter(name: "CIGaussianBlur", withInputParameters: [kCIInputImageKey: sourceImage])!
let filteredImage = filter.outputImage!

var pixelBuffer: CVPixelBuffer? = nil
let width = CVPixelBufferGetWidth(sourcePixelBuffer)
let height = CVPixelBufferGetHeight(sourcePixelBuffer)
let pixelFormat = CVPixelBufferGetPixelFormatType(sourcePixelBuffer)
let attributes = CVBufferGetAttachments(sourcePixelBuffer, .shouldPropagate)!
CVPixelBufferCreate(nil, width, height, pixelFormat, attributes, &pixelBuffer)
CVBufferPropagateAttachments(sourcePixelBuffer, pixelBuffer!)

var filteredPixelBuffer = pixelBuffer!      // this never works
filteredPixelBuffer = sourcePixelBuffer     // 0_0

let context = CIContext(options: [kCIContextOutputColorSpace: CGColorSpace(name: CGColorSpace.sRGB)!])
context.render(filteredImage, to: filteredPixelBuffer)  // modifying original image buffer here!

let presentationTimestamp = CMSampleBufferGetPresentationTimeStamp(sampleBuffer)
var timing = CMSampleTimingInfo(duration: kCMTimeInvalid, presentationTimeStamp: presentationTimestamp, decodeTimeStamp: kCMTimeInvalid)

var processedSampleBuffer: CMSampleBuffer? = nil
var formatDescription: CMFormatDescription? = nil
CMVideoFormatDescriptionCreateForImageBuffer(nil, filteredPixelBuffer, &formatDescription)
CMSampleBufferCreateReadyWithImageBuffer(nil, filteredPixelBuffer, formatDescription!, &timing, &processedSampleBuffer)

print(assetInput!.append(processedSampleBuffer!))

当然,我们都知道不允许修改样本缓冲区,但不知何故这种方法可以正常处理视频。技巧是肮脏的,我不能说在你有预览层或一些并发处理例程的情况下它是否会好。

关于ios - 如何在 AVCaptureSession 中为视频的每一帧应用过滤器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46216751/

相关文章:

ios - UIScrollView:缩放以适应屏幕宽度

ios - 删除委托(delegate)方法的 2 个实现中的重复代码

ios - 应用程序崩溃。日志显示原因 : 'Invalid query. You must not specify a starting point before specifying the order by.'

ios - 如何使用 captureStillImageAsynchronouslyFromConnection 实现多重拍摄(iOS AVFoundation)

ios - 在 iOS 13 上暂停时强制重绘 AVPlayerLayer

ios - 导航栏不显示 popViewController Animated() 不工作

ios - 更改 AVCaptureDeviceInput 导致 AVAssetWriterStatusFailed

iphone - NSRunLoop 和 GCD 队列

ios - CIGaussianBlur 质量 : Banding & Artifacts

ios - 为什么我不能在我的 Swift iOS 应用程序中使用 CIFilter 将我的图像反转回原始图像