Dispatch_async 在 captureOutput:(AVCaptureOutput*)captureOutput didOutputSampleBuffer 中,EXC_BAD_ACCESS 样本缓冲区错误

Dispatch_async in captureOutput:(AVCaptureOutput*)captureOutput didOutputSampleBuffer, EXC_BAD_ACCESS error on sample buffer

我正在尝试从 captureOutput:(AVCaptureOutput*)captureOutput didOutputSampleBuffer 获取样本缓冲区,对其进行处理,然后将其附加到 AVAssetWriter。整个代码有效,但它变得非常慢,我在旧设备上的 fps 很低。
我想把它放在 dispatch_async 中以提高性能,但是一旦访问样本缓冲区就会导致 EXC_BAD_ACCESS 错误。
我该如何修复它,同时将代码保留在后台?

queue1 = dispatch_queue_create("testqueue", DISPATCH_QUEUE_SERIAL);
...

-(void) captureOutput:(AVCaptureOutput*)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection*)connection{
    
dispatch_async(queue1, ^{
...
if(captureOutput == videoOutput){
//I process the buffer by appending an image to an adaptor
if([writerVideoInput isReadyForMoreMediaData] && recordingAssetWriter.status == 1)
    [adaptor appendPixelBuffer:pxBuffer withPresentationTime:CMSampleBufferGetPresentationTimeStamp(sampleBuffer)]) //<-- here I get EXC_BAD_ACCESS
}
if(captureOutput == audioOutput){
...
// I then append the audio buffer
if([assetWriterAudioInput isReadyForMoreMediaData] && recordingAssetWriter.status == 1)
    [assetWriterAudioInput appendSampleBuffer:sampleBuffer];
...
}
});

}

来自 AVCaptureVideoDataOutput.h 头文件中的 captureOutput:didOutputSampleBuffer:fromConnection: 讨论:

Clients that need to reference the CMSampleBuffer object outside of the scope of this method must CFRetain it and then CFRelease it when they are finished with it.

看来您需要保留那些示例缓冲区,因为它们超出了范围!不要忘记稍后释放它们,否则会泄漏大量内存。

我忘记了 Objective-C 中的 ARC 不管理 CoreFoundation 个对象。

然后头文件继续警告不要将样本缓冲区保留太久以免丢帧。