How to directly update pixels - with CGImage and direct CGDataProvider

我与影子孤独终老i 提交于 2019-11-29 22:42:12

Thanks to Brad Larson and David H for helping out with this one (see our full discussion in comments). Turns out using OpenGL and CoreVideo with CVOpenGLESTextureCache ended up being the fastest way to push raw images to the screen (I knew CoreGraphics couldn't be the fastest!), giving me 60 fps with fullscreen 1024x768 images on an iPad 1. There is little documentation on this now so I will try and explain as much as possible to help people:

CVOpenGLESTextureCacheCreateTextureFromImage allows you to create an OpenGL texture that has memory directly mapped to the CVImageBuffer you use to create it. This allows you to create say a CVPixelBuffer with your raw data and modify the data pointer gathered from CVPixelBufferGetBaseAddress. This gives you instant results in OpenGL without any need to modify or reupload the actual texture. Just be sure to lock with CVPixelBufferLockBaseAddress before modifying pixels and unlock when your done. Note, At this time this does not work in the iOS Simulator, only on device which I speculate to be from VRAM/RAM division, where the CPU has no direct access to VRAM. Brad recommended using a conditional compiler check to switch between a raw glTexImage2D updates and using texture caches.

Several things to watch out for (a combination of these caused it to not work for me):

  1. Test on device
  2. Make sure you CVPixelBuffer is backed with kCVPixelBufferIOSurfacePropertiesKey see link for example (Thanks again Brad).
  3. You must use GL_CLAMP_TO_EDGE for NPOT texture data with OpenGL ES 2.0
  4. Bind texture caches with glBindTexture(CVOpenGLESTextureGetTarget(_cvTexture), CVOpenGLESTextureGetName(_cvTexture)); don't be stupid like me and use CVOpenGLESTextureGetTarget for both parameters.
  5. Don't recreate the texture every frame simply copy image data into the pointer obtained from CVPixelBufferGetBaseAddress to update the texture.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!