I have a swift function that takes an UIImage and returns a CVPixelBuffer. When running this function multiple times, the memory keeps growing, leading to a crash.
What I already figured out:
- With instruments I isolated the memory problem in the image.draw line of code. It shows a lot of CGImage data kept in memory over the time.
- I isolated the function, so I'm sure that the problem is not in something that happen outside of it (in the caller), cause I removed all the code from there and the memory keeps growing.
- I tried dispatching the calls to this method, with some delay, to give time to the system to deallocate, but it's not working
- I tried wrapping multiple part of the code in autoreleasepool, still not working.
- I tried on the main thread, on utility.qos thread, etc, nothing changes
- I read every other question on StackOverflow, but looks like other people solutions aren't working in my case.
This is my code. Any help is appreciated, since I'm really banging my head on this one.
fileprivate func CreatePixelBufferFromImage(_ image: UIImage) -> CVPixelBuffer?{
let size = image.size;
var pxbuffer : CVPixelBuffer?
let status = CVPixelBufferPoolCreatePixelBuffer(kCFAllocatorDefault, self.exportingAdaptor!.pixelBufferPool!, &pxbuffer)
guard (status == kCVReturnSuccess) else{
return nil
}
CVPixelBufferLockBaseAddress(pxbuffer!, CVPixelBufferLockFlags(rawValue: 0));
let pxdata = CVPixelBufferGetBaseAddress(pxbuffer!);
let rgbColorSpace = CGColorSpaceCreateDeviceRGB();
let context = CGContext(data: pxdata, width: Int(size.width),
height: Int(size.height), bitsPerComponent: 8, bytesPerRow: CVPixelBufferGetBytesPerRow(pxbuffer!), space: rgbColorSpace,
bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue);
context?.translateBy(x: 0, y: image.size.height);
context?.scaleBy(x: 1.0, y: -1.0);
UIGraphicsPushContext(context!)
image.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height));
//
UIGraphicsPopContext()
CVPixelBufferUnlockBaseAddress(pxbuffer!, CVPixelBufferLockFlags(rawValue: 0));
return pxbuffer
}