Skip to content

Instantly share code, notes, and snippets.

@rampadc
Created February 21, 2021 09:22
Show Gist options
  • Save rampadc/10a7dc257552f1fb86c1fcc2d1671bd9 to your computer and use it in GitHub Desktop.
Save rampadc/10a7dc257552f1fb86c1fcc2d1671bd9 to your computer and use it in GitHub Desktop.
Create a CVPixelBuffer from a CIImage
// Usage - CVImageBuffer and CVPixelBuffer are the same types
let pixelBuffer: CVImageBuffer? = createPixelBufferFrom(image: image)
// How CIContext was declared - used in a MTKView class
device = MTLCreateSystemDefaultDevice()
framebufferOnly = false
colorPixelFormat = .bgra8Unorm
commandQueue = device!.makeCommandQueue()
Config.shared.ciContext = CIContext(mtlDevice: self.device!)
// Function
func createPixelBufferFrom(image: CIImage) -> CVPixelBuffer? {
// based on https://stackoverflow.com/questions/54354138/how-can-you-make-a-cvpixelbuffer-directly-from-a-ciimage-instead-of-a-uiimage-in
let attrs = [
kCVPixelBufferCGImageCompatibilityKey: false,
kCVPixelBufferCGBitmapContextCompatibilityKey: false,
kCVPixelBufferWidthKey: Int(image.extent.width),
kCVPixelBufferHeightKey: Int(image.extent.height)
] as CFDictionary
var pixelBuffer : CVPixelBuffer?
let status = CVPixelBufferCreate(kCFAllocatorDefault, Int(image.extent.width), Int(image.extent.height), kCVPixelFormatType_32BGRA, attrs, &pixelBuffer)
if status == kCVReturnInvalidPixelFormat {
print("status == kCVReturnInvalidPixelFormat")
}
if status == kCVReturnInvalidSize {
print("status == kCVReturnInvalidSize")
}
if status == kCVReturnPixelBufferNotMetalCompatible {
print("status == kCVReturnPixelBufferNotMetalCompatible")
}
if status == kCVReturnPixelBufferNotOpenGLCompatible {
print("status == kCVReturnPixelBufferNotOpenGLCompatible")
}
guard (status == kCVReturnSuccess) else {
return nil
}
Config.shared.ciContext?.render(image, to: pixelBuffer!)
return pixelBuffer
}
@fukemy
Copy link

fukemy commented Jun 23, 2023

I took much CPU and make app run slow, do you have another solution?

@rampadc
Copy link
Author

rampadc commented Jun 23, 2023

Hey @fukemy I ended up using MetalPetal. It dropped the CPU from 120+ to just above 60. https://github.com/MetalPetal/MetalPetal

@fukemy
Copy link

fukemy commented Jun 23, 2023

nice, I will look on this, thanks so much

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment