I am using GPUImage library function to manipulate height and width of CVPixelbuffer. I am recording a video in portrait and when the user rotates the device my screen adjusts itself to a landscape mode. I want landscape frame to be aspect fit in the screen.
For example:- I start a video in Portrait mode 320x568 and when I turn my device to landscape my frame is of 568x320 which I want to fit in 320x568. To adjust this thing I thought to manipulate CVPixelBuffer. But this is eating a lot of memory and at the end my app crashes.
- (CVPixelBufferRef) GPUImageCreateResizedSampleBufferWithBuffer:(CVPixelBufferRef)cameraFrame withBuffer:(CGSize)finalSize withSampleBuffer:(CMSampleBufferRef)sampleBuffer
{
CVPixelBufferRef pixel_buffer = NULL;
// CVPixelBufferCreateWithPlanarBytes for YUV input
@autoreleasepool {
CGSize originalSize = CGSizeMake(CVPixelBufferGetWidth(cameraFrame), CVPixelBufferGetHeight(cameraFrame));
CVPixelBufferLockBaseAddress(cameraFrame, 0);
GLubyte *sourceImageBytes = (GLubyte *)CVPixelBufferGetBaseAddress(cameraFrame);
CGDataProviderRef dataProvider = CGDataProviderCreateWithData(NULL, sourceImageBytes, CVPixelBufferGetBytesPerRow(cameraFrame) * originalSize.height, NULL);
CGColorSpaceRef genericRGBColorspace = CGColorSpaceCreateDeviceRGB();
CGImageRef cgImageFromBytes = CGImageCreate((int)originalSize.width, (int)originalSize.height, 8, 32, CVPixelBufferGetBytesPerRow(cameraFrame), genericRGBColorspace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst, dataProvider, NULL, NO, kCGRenderingIntentDefault);
GLubyte *imageData = (GLubyte *) calloc(1, ((int)finalSize.width * (int)finalSize.height * 4));
CGContextRef imageContext = CGBitmapContextCreate(imageData, (int)finalSize.width, (int)finalSize.height, 8, (int)finalSize.width * 4, genericRGBColorspace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst);
CGRect scaledRect = AVMakeRectWithAspectRatioInsideRect(originalSize, CGRectMake(0, 0, finalSize.width, finalSize.height));
CGContextDrawImage(imageContext, scaledRect, cgImageFromBytes);
CGImageRelease(cgImageFromBytes);
CGContextRelease(imageContext);
CGColorSpaceRelease(genericRGBColorspace);
CGDataProviderRelease(dataProvider);
CVPixelBufferCreateWithBytes(kCFAllocatorDefault, finalSize.width, finalSize.height, kCVPixelFormatType_32BGRA, imageData, finalSize.width * 4, stillImageDataReleaseCallback, NULL, NULL, &pixel_buffer);
CMVideoFormatDescriptionRef videoInfo = NULL;
CMVideoFormatDescriptionCreateForImageBuffer(NULL, pixel_buffer, &videoInfo);
CMTime frameTime = CMTimeMake(1, 30);
CMSampleTimingInfo timing = {frameTime, frameTime, kCMTimeInvalid};
CMSampleBufferCreateForImageBuffer(kCFAllocatorDefault, pixel_buffer, YES, NULL, NULL, videoInfo, &timing, &sampleBuffer);
CVPixelBufferUnlockBaseAddress(cameraFrame, 0);
CFRelease(videoInfo);
// CVPixelBufferRelease(pixel_buffer);
}
return pixel_buffer;
}
CG* - CoreGraphics use CPU and is too slow for realtime video, use CV* and GPU