Skip to content

Instantly share code, notes, and snippets.

@kshala-ford
Created February 19, 2019 10:14
Show Gist options
  • Save kshala-ford/5f10b8be912439da6e1d05bd489e1924 to your computer and use it in GitHub Desktop.
Save kshala-ford/5f10b8be912439da6e1d05bd489e1924 to your computer and use it in GitHub Desktop.
Crop a sample buffer to a view and return a pixel buffer
+ (CVPixelBufferRef)croppedPixelBufferFromSampleBuffer:(CMSampleBufferRef)buffer frame:(CGRect)frame {
if (buffer == nil) return nil;
CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(buffer);
if (imageBuffer == nil) return nil;
CIImage *ciImage = [CIImage imageWithCVPixelBuffer:imageBuffer];
ciImage = [ciImage imageByCroppingToRect:frame];
CFDictionaryRef empty; // empty value for attr IOSurface
empty = CFDictionaryCreate(kCFAllocatorDefault, NULL, NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
CFMutableDictionaryRef attrs = CFDictionaryCreateMutable(kCFAllocatorDefault, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
CFDictionarySetValue(attrs, kCVPixelBufferIOSurfacePropertiesKey, empty);
CVPixelBufferRef pixelBuffer;
CVPixelBufferCreate(kCFAllocatorSystemDefault, frame.size.width, frame.size.height, kCVPixelFormatType_32BGRA, attrs, &pixelBuffer);
CVPixelBufferLockBaseAddress(pixelBuffer, 0);
CIContext *ciContext = [CIContext contextWithOptions: nil];
[ciContext render:ciImage toCVPixelBuffer:pixelBuffer];
CVPixelBufferUnlockBaseAddress(pixelBuffer, 0);
CFRelease(attrs);
CFRelease(empty);
return pixelBuffer;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment