假设我想存储相机输出的一帧
let imageBuffer:CVPixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)
some_list.append(imageBuffer.copy())
这是如何通过扩展 CVPixelBuffer 来定义复制函数
extension CVPixelBuffer {
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, CVAttachmentMode.shouldPropagate),
&_copy)
guard let copy = _copy else { fatalError() }
CVPixelBufferLockBaseAddress(self, CVPixelBufferLockFlags.readOnly)
CVPixelBufferLockBaseAddress(copy, CVPixelBufferLockFlags(rawValue: 0))
let dest = CVPixelBufferGetBaseAddress(copy)
let source = CVPixelBufferGetBaseAddress(self)
let height = CVPixelBufferGetHeight(self)
let bytesPerRow = CVPixelBufferGetBytesPerRow(self)
memcpy(dest, source, height * bytesPerRow)
CVPixelBufferUnlockBaseAddress(copy, CVPixelBufferLockFlags(rawValue: 0))
CVPixelBufferUnlockBaseAddress(self, CVPixelBufferLockFlags.readOnly)
return copy
}
}
问题是:我是否需要显式管理我创建的 CVPixelBuffer 副本?或者 Swift 通过引用计数来处理它?
Swift 管理你的缓冲区对象,所以你不必考虑释放它。
从带注释的 API 返回的 Core Foundation 对象在 Swift 中自动进行内存管理 - 您无需自己调用 CFRetain、CFRelease 或 CFAutorelease 函数。
事实上,
CVPixelBufferRelease
函数没有Swift版本。
https://developer.apple.com/documentation/corevideo/1563589-cvpixelbufferrelease