PageRenderTime 47ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/Dependencies/GPUImage/Source/GPUImageStillCamera.m

https://gitlab.com/Mr.Tomato/VideoEffects
Objective C | 338 lines | 245 code | 72 blank | 21 comment | 27 complexity | 66105935449d6de11f083effec7a4bcf MD5 | raw file
  1. // 2448x3264 pixel image = 31,961,088 bytes for uncompressed RGBA
  2. #import "GPUImageStillCamera.h"
  3. void stillImageDataReleaseCallback(void *releaseRefCon, const void *baseAddress)
  4. {
  5. free((void *)baseAddress);
  6. }
  7. void GPUImageCreateResizedSampleBuffer(CVPixelBufferRef cameraFrame, CGSize finalSize, CMSampleBufferRef *sampleBuffer)
  8. {
  9. // CVPixelBufferCreateWithPlanarBytes for YUV input
  10. CGSize originalSize = CGSizeMake(CVPixelBufferGetWidth(cameraFrame), CVPixelBufferGetHeight(cameraFrame));
  11. CVPixelBufferLockBaseAddress(cameraFrame, 0);
  12. GLubyte *sourceImageBytes = CVPixelBufferGetBaseAddress(cameraFrame);
  13. CGDataProviderRef dataProvider = CGDataProviderCreateWithData(NULL, sourceImageBytes, CVPixelBufferGetBytesPerRow(cameraFrame) * originalSize.height, NULL);
  14. CGColorSpaceRef genericRGBColorspace = CGColorSpaceCreateDeviceRGB();
  15. CGImageRef cgImageFromBytes = CGImageCreate((int)originalSize.width, (int)originalSize.height, 8, 32, CVPixelBufferGetBytesPerRow(cameraFrame), genericRGBColorspace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst, dataProvider, NULL, NO, kCGRenderingIntentDefault);
  16. GLubyte *imageData = (GLubyte *) calloc(1, (int)finalSize.width * (int)finalSize.height * 4);
  17. CGContextRef imageContext = CGBitmapContextCreate(imageData, (int)finalSize.width, (int)finalSize.height, 8, (int)finalSize.width * 4, genericRGBColorspace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst);
  18. CGContextDrawImage(imageContext, CGRectMake(0.0, 0.0, finalSize.width, finalSize.height), cgImageFromBytes);
  19. CGImageRelease(cgImageFromBytes);
  20. CGContextRelease(imageContext);
  21. CGColorSpaceRelease(genericRGBColorspace);
  22. CGDataProviderRelease(dataProvider);
  23. CVPixelBufferRef pixel_buffer = NULL;
  24. CVPixelBufferCreateWithBytes(kCFAllocatorDefault, finalSize.width, finalSize.height, kCVPixelFormatType_32BGRA, imageData, finalSize.width * 4, stillImageDataReleaseCallback, NULL, NULL, &pixel_buffer);
  25. CMVideoFormatDescriptionRef videoInfo = NULL;
  26. CMVideoFormatDescriptionCreateForImageBuffer(NULL, pixel_buffer, &videoInfo);
  27. CMTime frameTime = CMTimeMake(1, 30);
  28. CMSampleTimingInfo timing = {frameTime, frameTime, kCMTimeInvalid};
  29. CMSampleBufferCreateForImageBuffer(kCFAllocatorDefault, pixel_buffer, YES, NULL, NULL, videoInfo, &timing, sampleBuffer);
  30. CVPixelBufferUnlockBaseAddress(cameraFrame, 0);
  31. CFRelease(videoInfo);
  32. CVPixelBufferRelease(pixel_buffer);
  33. }
  34. @interface GPUImageStillCamera ()
  35. {
  36. AVCaptureStillImageOutput *photoOutput;
  37. }
  38. // Methods calling this are responsible for calling dispatch_semaphore_signal(frameRenderingSemaphore) somewhere inside the block
  39. - (void)capturePhotoProcessedUpToFilter:(GPUImageOutput<GPUImageInput> *)finalFilterInChain withImageOnGPUHandler:(void (^)(NSError *error))block;
  40. @end
  41. @implementation GPUImageStillCamera {
  42. BOOL requiresFrontCameraTextureCacheCorruptionWorkaround;
  43. }
  44. @synthesize currentCaptureMetadata = _currentCaptureMetadata;
  45. @synthesize jpegCompressionQuality = _jpegCompressionQuality;
  46. #pragma mark -
  47. #pragma mark Initialization and teardown
  48. - (id)initWithSessionPreset:(NSString *)sessionPreset cameraPosition:(AVCaptureDevicePosition)cameraPosition;
  49. {
  50. if (!(self = [super initWithSessionPreset:sessionPreset cameraPosition:cameraPosition]))
  51. {
  52. return nil;
  53. }
  54. /* Detect iOS version < 6 which require a texture cache corruption workaround */
  55. #pragma clang diagnostic push
  56. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  57. requiresFrontCameraTextureCacheCorruptionWorkaround = [[[UIDevice currentDevice] systemVersion] compare:@"6.0" options:NSNumericSearch] == NSOrderedAscending;
  58. #pragma clang diagnostic pop
  59. [self.captureSession beginConfiguration];
  60. photoOutput = [[AVCaptureStillImageOutput alloc] init];
  61. // Having a still photo input set to BGRA and video to YUV doesn't work well, so since I don't have YUV resizing for iPhone 4 yet, kick back to BGRA for that device
  62. // if (captureAsYUV && [GPUImageContext supportsFastTextureUpload])
  63. if (captureAsYUV && [GPUImageContext deviceSupportsRedTextures])
  64. {
  65. BOOL supportsFullYUVRange = NO;
  66. NSArray *supportedPixelFormats = photoOutput.availableImageDataCVPixelFormatTypes;
  67. for (NSNumber *currentPixelFormat in supportedPixelFormats)
  68. {
  69. if ([currentPixelFormat intValue] == kCVPixelFormatType_420YpCbCr8BiPlanarFullRange)
  70. {
  71. supportsFullYUVRange = YES;
  72. }
  73. }
  74. if (supportsFullYUVRange)
  75. {
  76. [photoOutput setOutputSettings:[NSDictionary dictionaryWithObject:[NSNumber numberWithInt:kCVPixelFormatType_420YpCbCr8BiPlanarFullRange] forKey:(id)kCVPixelBufferPixelFormatTypeKey]];
  77. }
  78. else
  79. {
  80. [photoOutput setOutputSettings:[NSDictionary dictionaryWithObject:[NSNumber numberWithInt:kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange] forKey:(id)kCVPixelBufferPixelFormatTypeKey]];
  81. }
  82. }
  83. else
  84. {
  85. captureAsYUV = NO;
  86. [photoOutput setOutputSettings:[NSDictionary dictionaryWithObject:[NSNumber numberWithInt:kCVPixelFormatType_32BGRA] forKey:(id)kCVPixelBufferPixelFormatTypeKey]];
  87. [videoOutput setVideoSettings:[NSDictionary dictionaryWithObject:[NSNumber numberWithInt:kCVPixelFormatType_32BGRA] forKey:(id)kCVPixelBufferPixelFormatTypeKey]];
  88. }
  89. [self.captureSession addOutput:photoOutput];
  90. [self.captureSession commitConfiguration];
  91. self.jpegCompressionQuality = 0.8;
  92. return self;
  93. }
  94. - (id)init;
  95. {
  96. if (!(self = [self initWithSessionPreset:AVCaptureSessionPresetPhoto cameraPosition:AVCaptureDevicePositionBack]))
  97. {
  98. return nil;
  99. }
  100. return self;
  101. }
  102. - (void)removeInputsAndOutputs;
  103. {
  104. [self.captureSession removeOutput:photoOutput];
  105. [super removeInputsAndOutputs];
  106. }
  107. #pragma mark -
  108. #pragma mark Photography controls
  109. - (void)capturePhotoAsSampleBufferWithCompletionHandler:(void (^)(CMSampleBufferRef imageSampleBuffer, NSError *error))block
  110. {
  111. NSLog(@"If you want to use the method capturePhotoAsSampleBufferWithCompletionHandler:, you must comment out the line in GPUImageStillCamera.m in the method initWithSessionPreset:cameraPosition: which sets the CVPixelBufferPixelFormatTypeKey, as well as uncomment the rest of the method capturePhotoAsSampleBufferWithCompletionHandler:. However, if you do this you cannot use any of the photo capture methods to take a photo if you also supply a filter.");
  112. /*dispatch_semaphore_wait(frameRenderingSemaphore, DISPATCH_TIME_FOREVER);
  113. [photoOutput captureStillImageAsynchronouslyFromConnection:[[photoOutput connections] objectAtIndex:0] completionHandler:^(CMSampleBufferRef imageSampleBuffer, NSError *error) {
  114. block(imageSampleBuffer, error);
  115. }];
  116. dispatch_semaphore_signal(frameRenderingSemaphore);
  117. */
  118. return;
  119. }
  120. - (void)capturePhotoAsImageProcessedUpToFilter:(GPUImageOutput<GPUImageInput> *)finalFilterInChain withCompletionHandler:(void (^)(UIImage *processedImage, NSError *error))block;
  121. {
  122. [self capturePhotoProcessedUpToFilter:finalFilterInChain withImageOnGPUHandler:^(NSError *error) {
  123. UIImage *filteredPhoto = nil;
  124. if(!error){
  125. filteredPhoto = [finalFilterInChain imageFromCurrentFramebuffer];
  126. }
  127. dispatch_semaphore_signal(frameRenderingSemaphore);
  128. block(filteredPhoto, error);
  129. }];
  130. }
  131. - (void)capturePhotoAsImageProcessedUpToFilter:(GPUImageOutput<GPUImageInput> *)finalFilterInChain withOrientation:(UIImageOrientation)orientation withCompletionHandler:(void (^)(UIImage *processedImage, NSError *error))block {
  132. [self capturePhotoProcessedUpToFilter:finalFilterInChain withImageOnGPUHandler:^(NSError *error) {
  133. UIImage *filteredPhoto = nil;
  134. if(!error) {
  135. filteredPhoto = [finalFilterInChain imageFromCurrentFramebufferWithOrientation:orientation];
  136. }
  137. dispatch_semaphore_signal(frameRenderingSemaphore);
  138. block(filteredPhoto, error);
  139. }];
  140. }
  141. - (void)capturePhotoAsJPEGProcessedUpToFilter:(GPUImageOutput<GPUImageInput> *)finalFilterInChain withCompletionHandler:(void (^)(NSData *processedJPEG, NSError *error))block;
  142. {
  143. // reportAvailableMemoryForGPUImage(@"Before Capture");
  144. [self capturePhotoProcessedUpToFilter:finalFilterInChain withImageOnGPUHandler:^(NSError *error) {
  145. NSData *dataForJPEGFile = nil;
  146. if(!error){
  147. @autoreleasepool {
  148. UIImage *filteredPhoto = [finalFilterInChain imageFromCurrentFramebuffer];
  149. dispatch_semaphore_signal(frameRenderingSemaphore);
  150. // reportAvailableMemoryForGPUImage(@"After UIImage generation");
  151. dataForJPEGFile = UIImageJPEGRepresentation(filteredPhoto,self.jpegCompressionQuality);
  152. // reportAvailableMemoryForGPUImage(@"After JPEG generation");
  153. }
  154. // reportAvailableMemoryForGPUImage(@"After autorelease pool");
  155. }else{
  156. dispatch_semaphore_signal(frameRenderingSemaphore);
  157. }
  158. block(dataForJPEGFile, error);
  159. }];
  160. }
  161. - (void)capturePhotoAsJPEGProcessedUpToFilter:(GPUImageOutput<GPUImageInput> *)finalFilterInChain withOrientation:(UIImageOrientation)orientation withCompletionHandler:(void (^)(NSData *processedImage, NSError *error))block {
  162. [self capturePhotoProcessedUpToFilter:finalFilterInChain withImageOnGPUHandler:^(NSError *error) {
  163. NSData *dataForJPEGFile = nil;
  164. if(!error) {
  165. @autoreleasepool {
  166. UIImage *filteredPhoto = [finalFilterInChain imageFromCurrentFramebufferWithOrientation:orientation];
  167. dispatch_semaphore_signal(frameRenderingSemaphore);
  168. dataForJPEGFile = UIImageJPEGRepresentation(filteredPhoto, self.jpegCompressionQuality);
  169. }
  170. } else {
  171. dispatch_semaphore_signal(frameRenderingSemaphore);
  172. }
  173. block(dataForJPEGFile, error);
  174. }];
  175. }
  176. - (void)capturePhotoAsPNGProcessedUpToFilter:(GPUImageOutput<GPUImageInput> *)finalFilterInChain withCompletionHandler:(void (^)(NSData *processedPNG, NSError *error))block;
  177. {
  178. [self capturePhotoProcessedUpToFilter:finalFilterInChain withImageOnGPUHandler:^(NSError *error) {
  179. NSData *dataForPNGFile = nil;
  180. if(!error){
  181. @autoreleasepool {
  182. UIImage *filteredPhoto = [finalFilterInChain imageFromCurrentFramebuffer];
  183. dispatch_semaphore_signal(frameRenderingSemaphore);
  184. dataForPNGFile = UIImagePNGRepresentation(filteredPhoto);
  185. }
  186. }else{
  187. dispatch_semaphore_signal(frameRenderingSemaphore);
  188. }
  189. block(dataForPNGFile, error);
  190. }];
  191. return;
  192. }
  193. - (void)capturePhotoAsPNGProcessedUpToFilter:(GPUImageOutput<GPUImageInput> *)finalFilterInChain withOrientation:(UIImageOrientation)orientation withCompletionHandler:(void (^)(NSData *processedPNG, NSError *error))block;
  194. {
  195. [self capturePhotoProcessedUpToFilter:finalFilterInChain withImageOnGPUHandler:^(NSError *error) {
  196. NSData *dataForPNGFile = nil;
  197. if(!error){
  198. @autoreleasepool {
  199. UIImage *filteredPhoto = [finalFilterInChain imageFromCurrentFramebufferWithOrientation:orientation];
  200. dispatch_semaphore_signal(frameRenderingSemaphore);
  201. dataForPNGFile = UIImagePNGRepresentation(filteredPhoto);
  202. }
  203. }else{
  204. dispatch_semaphore_signal(frameRenderingSemaphore);
  205. }
  206. block(dataForPNGFile, error);
  207. }];
  208. return;
  209. }
  210. #pragma mark - Private Methods
  211. - (void)capturePhotoProcessedUpToFilter:(GPUImageOutput<GPUImageInput> *)finalFilterInChain withImageOnGPUHandler:(void (^)(NSError *error))block
  212. {
  213. dispatch_semaphore_wait(frameRenderingSemaphore, DISPATCH_TIME_FOREVER);
  214. if(photoOutput.isCapturingStillImage){
  215. block([NSError errorWithDomain:AVFoundationErrorDomain code:AVErrorMaximumStillImageCaptureRequestsExceeded userInfo:nil]);
  216. return;
  217. }
  218. [photoOutput captureStillImageAsynchronouslyFromConnection:[[photoOutput connections] objectAtIndex:0] completionHandler:^(CMSampleBufferRef imageSampleBuffer, NSError *error) {
  219. if(imageSampleBuffer == NULL){
  220. block(error);
  221. return;
  222. }
  223. // For now, resize photos to fix within the max texture size of the GPU
  224. CVImageBufferRef cameraFrame = CMSampleBufferGetImageBuffer(imageSampleBuffer);
  225. CGSize sizeOfPhoto = CGSizeMake(CVPixelBufferGetWidth(cameraFrame), CVPixelBufferGetHeight(cameraFrame));
  226. CGSize scaledImageSizeToFitOnGPU = [GPUImageContext sizeThatFitsWithinATextureForSize:sizeOfPhoto];
  227. if (!CGSizeEqualToSize(sizeOfPhoto, scaledImageSizeToFitOnGPU))
  228. {
  229. CMSampleBufferRef sampleBuffer = NULL;
  230. if (CVPixelBufferGetPlaneCount(cameraFrame) > 0)
  231. {
  232. NSAssert(NO, @"Error: no downsampling for YUV input in the framework yet");
  233. }
  234. else
  235. {
  236. GPUImageCreateResizedSampleBuffer(cameraFrame, scaledImageSizeToFitOnGPU, &sampleBuffer);
  237. }
  238. dispatch_semaphore_signal(frameRenderingSemaphore);
  239. [finalFilterInChain useNextFrameForImageCapture];
  240. [self captureOutput:photoOutput didOutputSampleBuffer:sampleBuffer fromConnection:[[photoOutput connections] objectAtIndex:0]];
  241. dispatch_semaphore_wait(frameRenderingSemaphore, DISPATCH_TIME_FOREVER);
  242. if (sampleBuffer != NULL)
  243. CFRelease(sampleBuffer);
  244. }
  245. else
  246. {
  247. // This is a workaround for the corrupt images that are sometimes returned when taking a photo with the front camera and using the iOS 5.0 texture caches
  248. AVCaptureDevicePosition currentCameraPosition = [[videoInput device] position];
  249. if ( (currentCameraPosition != AVCaptureDevicePositionFront) || (![GPUImageContext supportsFastTextureUpload]) || !requiresFrontCameraTextureCacheCorruptionWorkaround)
  250. {
  251. dispatch_semaphore_signal(frameRenderingSemaphore);
  252. [finalFilterInChain useNextFrameForImageCapture];
  253. [self captureOutput:photoOutput didOutputSampleBuffer:imageSampleBuffer fromConnection:[[photoOutput connections] objectAtIndex:0]];
  254. dispatch_semaphore_wait(frameRenderingSemaphore, DISPATCH_TIME_FOREVER);
  255. }
  256. }
  257. CFDictionaryRef metadata = CMCopyDictionaryOfAttachments(NULL, imageSampleBuffer, kCMAttachmentMode_ShouldPropagate);
  258. _currentCaptureMetadata = (__bridge_transfer NSDictionary *)metadata;
  259. block(nil);
  260. _currentCaptureMetadata = nil;
  261. }];
  262. }
  263. @end