Reduce memory usage of AVAssetWriter

Solution 1:

  1. When creating Dispatch Queue, ensure you create a queue with Autorlease Pool. Replace DISPATCH_QUEUE_SERIAL with DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL.

  2. Wrap each iteration of for loop into autorelease pool as well

like this:

[assetWriterInput requestMediaDataWhenReadyOnQueue:recordingQueue usingBlock:^{
        for (int i = 1; i < 200; ++i) {
            @autoreleasepool {
                while (![assetWriterInput isReadyForMoreMediaData]) {
                    [NSThread sleepForTimeInterval:0.01]; 
                }
                NSString *path = [NSString stringWithFormat:@"/Users/jontelang/Desktop/SnapperVideoDump/frames/frame_%i.jpg", i];
                UIImage *image = [UIImage imageWithContentsOfFile:path];
                CGImageRef ref = [image CGImage];
                CVPixelBufferRef buffer = [self pixelBufferFromCGImage:ref pool:writerAdaptor.pixelBufferPool];
                CMTime presentTime = CMTimeAdd(CMTimeMake(i, 60), CMTimeMake(1, 60));
                [writerAdaptor appendPixelBuffer:buffer withPresentationTime:presentTime];
                CVPixelBufferRelease(buffer);
            }
        }
        [assetWriterInput markAsFinished];
        [assetWriter finishWritingWithCompletionHandler:^{}];
    }];