對(duì)于 iOS 5.0+ 的設(shè)備境肾,Core Video 允許 OpenGL ES 的 texture 和一個(gè) image buffer 綁定,從而省略掉創(chuàng)建 texture 的步驟约急,也方便對(duì) image buffer 操作述雾,例如以多種格式讀取其中的數(shù)據(jù)而不是用 glReadPixels
這樣比較費(fèi)時(shí)的方法奶卓。Core Video 中的 OpenGL ES texture 類型為 CVOpenGLESTextureRef
评甜,定義為
A texture-based image buffer that supplies source image data to OpenGL ES.
image buffer 類型為 CVImageBufferRef
,在文檔中可以看到兩個(gè)類型其實(shí)是一回事:
typedef CVImageBufferRef CVOpenGLESTextureRef;
這些 texture 是由 CVOpenGLESTextureCache
緩存隶校、管理的漏益。可以用 CVOpenGLESTextureCacheCreateTextureFromImage
來(lái)從 image buffer 得到 texture 并將兩者綁定深胳,該 texture 可能是新建的或緩存的但未使用的绰疤。用 CVOpenGLESTextureCacheFlush
來(lái)清理未使用的緩存。
以上的 image buffer 需要滿足一定條件:
To create a
CVOpenGLESTexture
object successfully, the pixel buffer passed toCVOpenGLESTextureCacheCreateTextureFromImage()
must be backed by an IOSurface.
camera API 得到的 image buffer(CVPixelBufferRef
)已經(jīng)滿足條件舞终,在 Apple 的官方 sample code 中有從視頻文件的一幀 image buffer 映射到相應(yīng) texture 并在 shader 中使用的示例轻庆。
但如果要自己創(chuàng)建空的 image buffer 并和 texture 綁定用來(lái) render,那么創(chuàng)建時(shí)需要為 dictionary 指定一個(gè)特殊的 key:kCVPixelBufferIOSurfacePropertiesKey
权埠。代碼示例:
CFDictionaryRef empty; // empty value for attr value.
CFMutableDictionaryRef attrs;
empty = CFDictionaryCreate(kCFAllocatorDefault, NULL, NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); // our empty IOSurface properties dictionary
attrs = CFDictionaryCreateMutable(kCFAllocatorDefault, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
CFDictionarySetValue(attrs, kCVPixelBufferIOSurfacePropertiesKey, empty);
CVPixelBufferRef renderTarget;
CVReturn err = CVPixelBufferCreate(kCFAllocatorDefault, (int)_size.width, (int)_size.height, kCVPixelFormatType_32BGRA, attrs, &renderTarget);
接下來(lái)的使用方法就和 sample code 中類似了榨了。
參考: