问题
In iOS6, I'm using OpenGL to do some rendering on AVFoundation video frames. I've seen a lot of example code that makes use of CVPixelBufferLockBaseAddress and CVPixelBufferUnlockBaseAddress, but it's unclear to me when exactly I perform the lock and unlock or why I'm doing it. Should I be locking the address when the CPU is modifying the memory? Or should I lock it when the GPU is reading from it? When should I unlock? Why would I ever even want to unlock? I've seen this Stack Overflow answer but it doesn't completely answer my question.
回答1:
You should lock each time you need to use it, and unlock when you are done and you don't need it anymore. This prevents the buffer from being overwritten, which can leave it in an inconsistent state.
A firmware expert once explained this to me: in general, when handling video output, you should be mindful that there are many indirect references with pointers, which is like saying: "Hey it's mine, I'm using it, point to the next frame somewhere else".
I can't tell based on your application when the buffer will no longer be needed, but that is something you should be able to figure out. If you had copied the buffer data somewhere else (such as creating a new object) it means that you could unlock it.
Hope this helps.
回答2:
You should only call this function in case you want to access the pixel buffer on the CPU, in case of GPU don't do it!, Apple doc is very clear on it.
Here is the information from official apple doc:
https://developer.apple.com/library/prerelease/ios/documentation/QuartzCore/Reference/CVPixelBufferRef/index.html#//apple_ref/c/func/CVPixelBufferLockBaseAddress
You must call the CVPixelBufferLockBaseAddress function before accessing pixel data with the CPU, and call the CVPixelBufferUnlockBaseAddress function afterward. If you include the kCVPixelBufferLock_ReadOnly value in the lockFlags parameter when locking the buffer, you must also include it when unlocking the buffer.
IMPORTANT
When accessing pixel data with the GPU, locking is not necessary and can impair performance.
来源:https://stackoverflow.com/questions/15558153/when-should-i-call-cvpixelbufferlockbaseaddress-and-cvpixelbufferunlockbaseaddre