Created
July 28, 2017 23:33
-
-
Save omarojo/adaa7395c4861ed09c27b3361046d5ff to your computer and use it in GitHub Desktop.
This file contains 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
//self.inputVideoData is an instanace of RawDataOutput | |
if let rawData = self.inputVideoData { | |
rawData.dataAvailableCallbackWithSize = {[weak self] dataArray, frameSize in | |
let numberOfBytesPerRow = frameSize.width; | |
let data = Data.init(bytes: dataArray) | |
data.withUnsafeBytes { (u8Ptr: UnsafePointer<UInt8>) -> Void in | |
let rawPtr = UnsafeMutableRawPointer(mutating: u8Ptr) | |
var pixelBuffer : CVPixelBuffer?; | |
_ = CVPixelBufferCreateWithBytes(kCFAllocatorDefault, | |
Int(frameSize.width), | |
Int(frameSize.height), | |
kCVPixelFormatType_32BGRA, | |
rawPtr, | |
Int(numberOfBytesPerRow*4), nil, nil, nil, | |
&pixelBuffer); | |
if pixelBuffer != nil { | |
//You can use this pixelBuffer for whatever you want. | |
self?.DoWhatever(pixelbuffer) | |
//or get a deepCopy.. and save it to a property | |
self?.samplePixelBufferCopy = pixelBuffer?.deepcopy() | |
} | |
} | |
} | |
} | |
///////////////////////////////////////////////////////// | |
///////////////////////////////////////////////////////// | |
extension CVPixelBuffer { | |
func deepcopy() -> CVPixelBuffer? { | |
let width = CVPixelBufferGetWidth(self) | |
let height = CVPixelBufferGetHeight(self) | |
let format = CVPixelBufferGetPixelFormatType(self) | |
var pixelBufferCopyOptional:CVPixelBuffer? | |
CVPixelBufferCreate(nil, width, height, format, nil, &pixelBufferCopyOptional) | |
if let pixelBufferCopy = pixelBufferCopyOptional { | |
CVPixelBufferLockBaseAddress(self, .readOnly) | |
CVPixelBufferLockBaseAddress(pixelBufferCopy, CVPixelBufferLockFlags(rawValue: 0)) | |
let baseAddress = CVPixelBufferGetBaseAddress(self) | |
let dataSize = CVPixelBufferGetDataSize(self) | |
//print("dataSize: \(dataSize)") | |
let target = CVPixelBufferGetBaseAddress(pixelBufferCopy) | |
memcpy(target, baseAddress, dataSize) | |
CVPixelBufferUnlockBaseAddress(pixelBufferCopy, CVPixelBufferLockFlags(rawValue: 0)) | |
CVPixelBufferUnlockBaseAddress(self, .readOnly) | |
} | |
return pixelBufferCopyOptional | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment