I use captureOutput:didOutputSampleBuffer:fromConnection:
to track frames. For my use case, I only need to save the last frame and use it if the application goes into the background.
This is a sample from my code:
@property (nonatomic, strong) AVCaptureVideoDataOutput *videoDataOutput;
@property (atomic) CMSampleBufferRef currentBuffer;
- (UIImage *) imageFromSampleBuffer:(CMSampleBufferRef) sampleBuffer
{
CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
CVPixelBufferLockBaseAddress(imageBuffer, 0);
void *baseAddress = CVPixelBufferGetBaseAddress(imageBuffer);
size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);
size_t width = CVPixelBufferGetWidth(imageBuffer);
size_t height = CVPixelBufferGetHeight(imageBuffer);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef con = CGBitmapContextCreate(baseAddress, width, height, 8,
bytesPerRow, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst);
CGImageRef quartzImage = CGBitmapContextCreateImage(con);
CVPixelBufferUnlockBaseAddress(imageBuffer,0);
CGContextRelease(con);
CGColorSpaceRelease(colorSpace);
UIImage *image = [UIImage imageWithCGImage:quartzImage scale:[[UIScreen mainScreen] scale] orientation:UIImageOrientationRight];
CGImageRelease(quartzImage);
return (image);
}
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection
{
CFRetain(sampleBuffer);
@synchronized (self) {
if (_currentBuffer) {
CFRelease(_currentBuffer);
}
self.currentBuffer = sampleBuffer;
}
}
- (void) goingToBackground:(NSNotification *) notification
{
UIImage *snapshot = [self imageFromSampleBuffer:_currentBuffer];
}
The problem is that in some cases I get this failure from the inside imageFromSampleBuffer
:
<Error>: copy_read_only: vm_copy failed: status 1.
Accident occurs on CGImageRef quartzImage = CGBitmapContextCreateImage(con);
What am I doing wrong?
source
share