-
-
Save shalom-aviv/b1d3b6edaba65b86df10cca62b0bd3d8 to your computer and use it in GitHub Desktop.
Creates a deep copy of a CVPixelBuffer. Compatible with Swift 2.3.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension CVPixelBuffer | |
{ | |
/// Deep copy a CVPixelBuffer: | |
/// http://stackoverflow.com/questions/38335365/pulling-data-from-a-cmsamplebuffer-in-order-to-create-a-deep-copy | |
func copy() -> CVPixelBuffer | |
{ | |
precondition(CFGetTypeID(self) == CVPixelBufferGetTypeID(), "copy() cannot be called on a non-CVPixelBuffer") | |
var _copy: CVPixelBuffer? | |
CVPixelBufferCreate( | |
nil, | |
CVPixelBufferGetWidth(self), | |
CVPixelBufferGetHeight(self), | |
CVPixelBufferGetPixelFormatType(self), | |
CVBufferGetAttachments(self, .ShouldPropagate), | |
&_copy) | |
guard let copy = _copy else { fatalError() } | |
CVPixelBufferLockBaseAddress(self, .ReadOnly) | |
CVPixelBufferLockBaseAddress(copy, []) | |
defer | |
{ | |
CVPixelBufferUnlockBaseAddress(copy, []) | |
CVPixelBufferUnlockBaseAddress(self, .ReadOnly) | |
} | |
for plane in 0 ..< CVPixelBufferGetPlaneCount(self) | |
{ | |
let dest = CVPixelBufferGetBaseAddressOfPlane(copy, plane) | |
let source = CVPixelBufferGetBaseAddressOfPlane(self, plane) | |
let height = CVPixelBufferGetHeightOfPlane(self, plane) | |
let bytesPerRow = CVPixelBufferGetBytesPerRowOfPlane(self, plane) | |
memcpy(dest, source, height * bytesPerRow) | |
} | |
return copy | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment