GPUImage icon indicating copy to clipboard operation
GPUImage copied to clipboard

Crashing when saving an image from GPUImageStillCamera

Open rafiki270 opened this issue 14 years ago • 34 comments

the app is crashing on 4s if an image is taken and is being manipulated (with original code, with UIImageWriteToSavedPhotosAlbum() as well as with ALAssetsLibrary)

So far it looks like not enough memory on the device to process the image, this is just a guess as I am not getting any message even with zombies enabled. 8 maga pixel camera might be just too much for image handling? I have even tried to save the image on a separate thread (don't really kno why) :(

rafiki270 avatar Apr 19 '12 23:04 rafiki270

Does this happen after you have the UIImage from the photo? When I try using the SimplePhotoFilter to take a photo on my iPhone 4S, it is able to take the photo and save it to disk without crashing. It looks like the memory spikes to 70 MB when doing so, but I think that should still be within the safe limits on the 4S.

When it crashes, does the crash log in the Organizer show that it was due to memory?

BradLarson avatar Apr 20 '12 00:04 BradLarson

I had to "downgrade" the resolution as the app is crashing is I use AVCaptureSessionPresetPhoto ... this relates to the other thing which is the broken picture

strange thing is, and to be honest that's the only reason I have filed an issue here, that the output image size 2448x3264 and quite often it crashes even before I can NSLog the size which is the first thing I do ... so it might be in the block that returns the image ... and there is no crash report in organizer, in the debug window and only thing I can see is just a memory warning from time to time ...

rafiki270 avatar Apr 20 '12 07:04 rafiki270

and on iPhone 4 I get:

2012-04-20 09:14:54.700 PhotoApp[21719:707] *** Assertion failure in -[GPUImageRotationFilter createFilterFBOofSize:], /Projects/iOS/GPUImage/framework/Source/GPUImageFilter.m:198 2012-04-20 09:14:54.711 PhotoApp[21719:707] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Incomplete filter FBO: 36054' *** First throw call stack: (0x34dda88f 0x36201259 0x34dda789 0x30c553a3 0xf677 0xf765 0x1016f 0x10263 0x154ed 0x1248b 0x12c5d 0x13423 0x12b83 0x160ed 0x319484db 0x3194877b 0x3193f7ed 0x31961fdf 0x34da67cf 0x34da6547 0x34d32097 0x34d3a1cd 0x335dfeb7 0x36099817 0x36075b73 0x360756c1 0x3607567f 0x36074649 0x34da3f13 0x34dae523 0x34dae4c5 0x34dad313 0x34d304a5 0x34d3036d 0x3602c439 0x31e26e7d 0xb973 0xb918) terminate called throwing an exception

rafiki270 avatar Apr 20 '12 08:04 rafiki270

For the possibly memory-related crashes, do you encounter these same crashes on your device with the SimplePhotoFilter example when you take photos using it? If not, you could try extending that sample until it crashes like it does in your application, and find what triggers the crash in your case.

The iPhone 4 is a special case, in that it can take photos large enough (2592x1936) that they just exceed the maximum texture size of the GPU on those devices (2048x2048). This causes the processing to fail, currently. All other devices either don't take photos that large, or support larger texture sizes (the iPad 2, iPad 3, and iPhone 4S support these larger sizes).

Core Image falls back to really slow CPU-bound processing in this case, but I'm working on a tiling implementation to allow the full processing of these images on the GPU.

BradLarson avatar Apr 20 '12 17:04 BradLarson

I've made some significant memory-related improvements in the latest code on iOS 5.x. Look at the new SimplePhotoFilter example to see how this works.

Basically, when you create your filters, if you call [filter prepareForImageCapture] on the one that you will be grabbing photos from, it now will use iOS 5.0 texture caches to read the image data. Not only is this more than 10-20% faster than the old approach, it more than halves the memory usage of the photo processing.

I also found and removed a potential source of memory buildup, so try this and see if it works better for you. On my iPhone 4S, capturing and processing full-frame photos now never causes the SimplePhotoFilter to spike above 38 MB and I haven't once seen a memory warning while doing this.

BradLarson avatar Apr 22 '12 02:04 BradLarson

brilliant! :)

rafiki270 avatar Apr 23 '12 14:04 rafiki270

Hi Brad,

I am still getting this issue on iPhone 4 unfortunately ... the process looks much better on the other devices but iPhone 4 doesn't work:

2012-04-30 23:35:49.620 SimplePhotoFilter[217:707] *** Assertion failure in -[GPUImageRotationFilter createFilterFBOofSize:], /Projects/iOS/GPUImage/framework/Source/GPUImageFilter.m:281 2012-04-30 23:35:49.628 SimplePhotoFilter[217:707] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Incomplete filter FBO: 36054' *** First throw call stack: (0x34f5188f 0x36378259 0x34f51789 0x30dcc3a3 0x522b 0x546d 0x5fd7 0x60cb 0xb94d 0x86c1 0x8f7d 0x9847 0x8ea3 0xc4d1 0x31abf4db 0x31abf77b 0x31ab67ed 0x31ad8fdf 0x34f1d7cf 0x34f1d547 0x34ea9097 0x34eb11cd 0x33756eb7 0x36210817 0x361ecb73 0x361ec6c1 0x361ec67f 0x361eb649 0x34f1af13 0x34f25523 0x34f254c5 0x34f24313 0x34ea74a5 0x34ea736d 0x361a3439 0x31f9de7d 0x2e45 0x28e0) terminate called throwing an exception(lldb)

Would it be possible to reduce the image size that comes from the camera. I've been trying to capture the photo without any filter, resize and apply the filter afterwards but no luck either ... the crash apparently happens before, somewhere in the capturePhotoProcessedUpToFilter method.

Btw, this is from your example code, latest code pulled from git ...

Cheers,

Ondrej

rafiki270 avatar Apr 30 '12 22:04 rafiki270

Yes, as I note in the documentation, the iPhone 4 generates photos at the photo preset which are larger than its maximum texture size. This means that these photos cannot currently be processed by the framework.

The problem comes in at the moment of capture, so it's well before any filters are applied. The only way around this would be to resize the image somehow before it is passed into the filter pipeline. This could be done using Core Graphics, but it would be a very slow operation. You'd have to modify the GPUImageVideoCamera to detect this particular device and implement the scaling down within the -processVideoSampleBuffer: method.

A final solution will be to use tiling for these images to break them into smaller chunks that could be processed on the GPU, and I'm working on this. However, that might not be ready for a little while.

BradLarson avatar Apr 30 '12 22:04 BradLarson

ah, ok ... sorry I didn't get the not ready part. Could you point me to the the bit that would be the tiling happening, I am not very good with OpenGL but I would like to give it to our developers to look at it ... maybe we'll be able to save you some time ...

in the meantime, I'll try to get the image directly just on iPhone 4 and resize using CG as you suggested.

rafiki270 avatar Apr 30 '12 23:04 rafiki270

This might help (at least for now):

#import "GPUImageStillCamera.h"
#include <sys/types.h>
#include <sys/sysctl.h>


@interface GPUImageStillCamera ()
{
    AVCaptureStillImageOutput *photoOutput;
}

@end

@implementation GPUImageStillCamera


#pragma mark -
#pragma mark Device identification

- (NSString *)platform
{
    int mib[2];
    size_t len;
    char *machine;

    mib[0] = CTL_HW;
    mib[1] = HW_MACHINE;
    sysctl(mib, 2, NULL, &len, NULL, 0);
    machine = malloc(len);
    sysctl(mib, 2, machine, &len, NULL, 0);

    NSString *platform = [NSString stringWithCString:machine encoding:NSASCIIStringEncoding];
    free(machine);
    return platform;
}


#pragma mark -
#pragma mark Initialization and teardown

- (id)init;
{
    NSString *p = AVCaptureSessionPresetPhoto;
    NSString *platform = [self platform];
    if ([platform isEqualToString:@"iPhone3,1"] || [platform isEqualToString:@"iPhone3,3"]) p = AVCaptureSessionPresetMedium; // For iPhone 4 and Verizon iPhone 4
    if (!(self = [self initWithSessionPreset:p cameraPosition:AVCaptureDevicePositionBack]))
    {
        return nil;
    }

    [self.captureSession beginConfiguration];

    photoOutput = [[AVCaptureStillImageOutput alloc] init];
    [photoOutput setOutputSettings:[NSDictionary dictionaryWithObject:[NSNumber numberWithInt:kCVPixelFormatType_32BGRA] forKey:(id)kCVPixelBufferPixelFormatTypeKey]];

    [self.captureSession addOutput:photoOutput];

    [self.captureSession commitConfiguration];

    return self;
}

- (void)removeInputsAndOutputs;
{
    [self.captureSession removeOutput:photoOutput];
}

#pragma mark -
#pragma mark Photography controls

- (void)capturePhotoProcessedUpToFilter:(GPUImageOutput<GPUImageInput> *)finalFilterInChain withCompletionHandler:(void (^)(UIImage *processedImage, NSError *error))block;
{
    [photoOutput captureStillImageAsynchronouslyFromConnection:[[photoOutput connections] objectAtIndex:0] completionHandler:^(CMSampleBufferRef imageSampleBuffer, NSError *error) {

        [self captureOutput:photoOutput didOutputSampleBuffer:imageSampleBuffer fromConnection:[[photoOutput connections] objectAtIndex:0]];

        UIImage *filteredPhoto = [finalFilterInChain imageFromCurrentlyProcessedOutput];

        block(filteredPhoto, error);        
    }];

    return;
}
@end

Of course I'll be cropping the picture on the output so it will fill the screen properly (preview and photo) ... now I have to wait for my wife to come home with her iPhone 4 so I can test :)

rafiki270 avatar May 01 '12 11:05 rafiki270

Rather than checking for the device ID, I recommend using +maximumTextureSizeForThisDevice from GPUImageOpenGLESContext and comparing that against the target image size. That's completely device-independent, in case Apple decides to roll out another slight variant on the iPhone 4 in the future.

The tiling design I have so far is nonfunctional, and not in the repository, but I'll roll it into the repository as soon as it's even moderately usable.

BradLarson avatar May 02 '12 16:05 BradLarson

brilliant, thanks

rafiki270 avatar May 02 '12 17:05 rafiki270

Hi Brad,

I have solved the resizing issue with CoreImage and trying to apply the filters again using the still image processing. Is there any way how to get through to those from the GPUImageStillCamera?


- (void)capturePhotoProcessedUpToFilter:(GPUImageOutput<GPUImageInput> *)finalFilterInChain withCompletionHandler:(void (^)(UIImage *processedImage, NSError *error))block;
{
    [photoOutput captureStillImageAsynchronouslyFromConnection:[[photoOutput connections] objectAtIndex:0] completionHandler:^(CMSampleBufferRef imageSampleBuffer, NSError *error) {
        @autoreleasepool {
            UIImage *filteredPhoto;
            CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(imageSampleBuffer);
            CVPixelBufferLockBaseAddress(imageBuffer,0); 
            size_t width = CVPixelBufferGetWidth(imageBuffer); 
            size_t height = CVPixelBufferGetHeight(imageBuffer);

            int maxTextureSize = ([GPUImageOpenGLESContext maximumTextureSizeForThisDevice] - 32);

            // Dev hack to get inside even on iPhone 4s !!!!!!
            maxTextureSize = (maxTextureSize / 2);


            if (width >= maxTextureSize || height >= maxTextureSize) {
//              CGFloat v1 = (((float)maxTextureSize * 100.0f) / (float)width);
//              CGFloat v2 = (((float)maxTextureSize * 100.0f) / (float)height);
//              CGFloat v = (v1 < v2) ? v1 : v2;

                CIImage *image = [CIImage imageWithCVPixelBuffer:imageBuffer];
                CIContext *context = [CIContext contextWithOptions:nil];                
                CGAffineTransform t = CGAffineTransformMakeScale(0.59, 0.59);
                t = CGAffineTransformRotate(t, (M_PI * -90 / 180.0));
                image = [image imageByApplyingTransform:t];

                CGImageRef cgimg = [context createCGImage:image fromRect:[image extent]];
                filteredPhoto = [UIImage imageWithCGImage:cgimg];

                CGImageRelease(cgimg);

                // Trying to implement the filters I have used here but no luck so far ...
                GPUImagePicture *stillImageSource = [[GPUImagePicture alloc] initWithImage:filteredPhoto];
                GPUImageSepiaFilter *stillImageFilter = [[GPUImageSepiaFilter alloc] init];
                [stillImageSource addTarget:stillImageFilter];
                [stillImageSource processImage];
                filteredPhoto = [stillImageFilter imageFromCurrentlyProcessedOutput];

            }
            else {
                [self captureOutput:photoOutput didOutputSampleBuffer:imageSampleBuffer fromConnection:[[photoOutput connections] objectAtIndex:0]];
                filteredPhoto = [finalFilterInChain imageFromCurrentlyProcessedOutput];
            }
            CVPixelBufferUnlockBaseAddress(imageBuffer, 0);
            block(filteredPhoto, error);
        }
    }];

    return;
}


rafiki270 avatar May 03 '12 16:05 rafiki270

hi, Brad,

The latest SimplePhotoFilter sample code still crashes after taking the photo on my iphone4s (iOS 5.0.1) today. Tried it so many times, and still no avail though. I checked the logs and it seems to be the "Received Memory Warnings". Please advise.

andrewzeus avatar May 06 '12 01:05 andrewzeus

I had the same issue on 4s for a while and it actually helped to restart the phone and do a clean build. I know this is probably not the answer you'd like to hear but it's wort a shot :)

rafiki270 avatar May 06 '12 01:05 rafiki270

hmm...thanks for the tips...actually I also did find restarting the phone help quite a bit. but as time goes by, the phone will start to crash again with the memory warning.

cheers, Andrew

On May 6, 2012, at 9:34 AM, Ondrej Rafaj wrote:

I had the same issue on 4s for a while and it actually helped to restart the phone and do a clean build. I know this is probably not the answer you'd like to hear but it's wort a shot :)


Reply to this email directly or view it on GitHub: https://github.com/BradLarson/GPUImage/issues/69#issuecomment-5531957

andrewzeus avatar May 06 '12 01:05 andrewzeus

I believe I've reduced the memory pressure when saving images in the latest code. Rather than keeping a UIImage around and letting the AVAssetLibrary process that in the background, I generate a JPEG image, get rid of the large uncompressed image, and send the compressed JPEG to the photo library.

Also, I was leaking OpenGL ES textures when taking photos, which might have built up outside of the application, leading to the eventual crashes you saw with the capture process. Try it now and see if these crashes recur.

BradLarson avatar May 07 '12 19:05 BradLarson

I'm getting the following as well when using SimplePhotoFilter on my iPhone 4 (pulled code from Git earlier this morning). Was this supposed to have been fixed in one of your latest releases or did I understand this thread incorrectly?

2012-05-08 13:16:54.158 PhotoApp[338:707] *** Assertion failure in -[GPUImageRotationFilter createFilterFBOofSize:], /Frameworks/GPUImage/Source/GPUImageFilter.m:291 2012-05-08 13:16:54.166 PhotoApp[338:707] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Incomplete filter FBO: 36054'

joshholat avatar May 08 '12 18:05 joshholat

The iPhone 4 still generates photos larger than the maximum texture size on that device. You can implement Ondrej's workaround from above to deal with this for now by resizing these photos to be just under the maximum texture size.

BradLarson avatar May 08 '12 18:05 BradLarson

Hi Josh,

If you'll make the photoOutput variable in GPUImageStillCamera public, you can use following category to get the picture back into your code. Works for me, just keep in mind that you have to apply the filters again on the image that comes back.

Cheers,

Ondrej

Making the photoOutput public:


@property (nonatomic, strong) AVCaptureStillImageOutput *photoOutput;

Category header file:


//
//  GPUImageStillCamera+LowPixelHandling.h
//  PhotoApp
//
//  Created by Ondrej Rafaj on 08/05/2012.
//  Copyright (c) 2012 Fuerte International. All rights reserved.
//

#import "GPUImageStillCamera.h"

@interface GPUImageStillCamera (LowPixelHandling)

- (void)capturePhotoAsJPEGProcessedUpToFilter:(GPUImageOutput<GPUImageInput> *)finalFilterInChain withCompletionHandler:(void (^)(NSData *processedJPEG, NSError *error))block andLowPixelTextureHandler:(void (^)(NSData *processedJPEG, NSError *error))lowPixelBlock;


@end

and the implementation file:

//
//  GPUImageStillCamera+LowPixelHandling.m
//  PhotoApp
//
//  Created by Ondrej Rafaj on 08/05/2012.
//  Copyright (c) 2012 Fuerte International. All rights reserved.
//

#import "GPUImageStillCamera+LowPixelHandling.h"
#import <CoreImage/CoreImage.h>


@implementation GPUImageStillCamera (LowPixelHandling)

- (void)capturePhotoAsJPEGProcessedUpToFilter:(GPUImageOutput<GPUImageInput> *)finalFilterInChain withCompletionHandler:(void (^)(NSData *, NSError *))block andLowPixelTextureHandler:(void (^)(NSData *, NSError *))lowPixelBlock {
    report_memory(@"Before still image capture");
    [photoOutput captureStillImageAsynchronouslyFromConnection:[[photoOutput connections] objectAtIndex:0] completionHandler:^(CMSampleBufferRef imageSampleBuffer, NSError *error) {
        report_memory(@"Before filter processing");

        NSData *dataForJPEGFile = nil;

        //*
        CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(imageSampleBuffer);
        CVPixelBufferLockBaseAddress(imageBuffer,0); 
        size_t width = CVPixelBufferGetWidth(imageBuffer); 
        size_t height = CVPixelBufferGetHeight(imageBuffer);
        int maxTextureSize = ([GPUImageOpenGLESContext maximumTextureSizeForThisDevice] - 32);
        // Dev hack to get inside even on iPhone 4s !!!!!!
        //maxTextureSize = (maxTextureSize / 2);
        if (width >= maxTextureSize || height >= maxTextureSize) {
            CIImage *image = [CIImage imageWithCVPixelBuffer:imageBuffer];
            CIContext *context = [CIContext contextWithOptions:nil];                
            CGAffineTransform t = CGAffineTransformMakeScale(0.59, 0.59);
            //t = CGAffineTransformRotate(t, (M_PI * -90 / 180.0));
            image = [image imageByApplyingTransform:t];

            CGImageRef cgimg = [context createCGImage:image fromRect:[image extent]];
            UIImage *filteredPhoto = filteredPhoto = [UIImage imageWithCGImage:cgimg];
            dataForJPEGFile = UIImageJPEGRepresentation(filteredPhoto, 0.8);

            CGImageRelease(cgimg);

            lowPixelBlock(dataForJPEGFile, error);
        }

        [self captureOutput:photoOutput didOutputSampleBuffer:imageSampleBuffer fromConnection:[[photoOutput connections] objectAtIndex:0]];
        report_memory(@"After filter processing");

        @autoreleasepool {
            UIImage *filteredPhoto = [finalFilterInChain imageFromCurrentlyProcessedOutput];

            report_memory(@"After UIImage generation");

            dataForJPEGFile = UIImageJPEGRepresentation(filteredPhoto, 0.8);
            report_memory(@"After JPEG generation");
        }

        report_memory(@"After autorelease pool");

        block(dataForJPEGFile, error);        
    }];

    return;
}

@end



rafiki270 avatar May 08 '12 18:05 rafiki270