2

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:

  1. 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.
  2. 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.
  3. I tried dispatching the calls to this method, with some delay, to give time to the system to deallocate, but it's not working
  4. I tried wrapping multiple part of the code in autoreleasepool, still not working.
  5. I tried on the main thread, on utility.qos thread, etc, nothing changes
  6. 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
}
4

2 回答 2

4

我发现问题不是像素缓冲区,而是图像参考。
当我在上下文中绘制图像时,看起来(这只是我基于这里的行为的看法),大量图像像素数据存储在image.cgimage对象中。因此,我通过在每次调用此函数后释放对我刚刚绘制的图像的引用来解决,并且内存在所有过程中保持稳定。

于 2017-05-28T02:36:23.420 回答
0

您需要删除您创建的引用,否则像素缓冲区将保持保留,然后在每次调用时创建一个新的。将 ref 删除到像素缓冲区会将其放回池中,以便可以在下一次调用时使用。

于 2017-05-26T03:22:13.723 回答