我目前正在尝试使用VideoToolbox对来自AVCaptureVideoDataOutput
的视频数据进行编码,但是在从self
内部引用VTCompressionOutputCallback
时遇到问题。
我的代码如下:
...
var sessionRef: VTCompressionSession?
let outputCallback: VTCompressionOutputCallback = { _, _, status, _, sampleBuffer in
guard status == noErr, let sampleBuffer = sampleBuffer else {
return
}
debugPrint("[INFO]: outputCallback: sampleBuffer: \(sampleBuffer)")
}
let sessionErr = VTCompressionSessionCreate(allocator: nil,
width: width,
height: height,
codecType: kCMVideoCodecType_H264,
encoderSpecification: nil,
imageBufferAttributes: nil,
compressedDataAllocator: nil,
outputCallback: outputCallback,
refcon: nil,
compressionSessionOut: UnsafeMutablePointer(&sessionRef))
...
这很好,并且打印输出符合预期,但是,一旦我尝试在self
中添加对VTCompressionOutputCallback
的引用,就会出现编译器错误说明
A C function pointer cannot be formed from a closure that captures context
如何在回调中使用self
?
预先感谢您的帮助。
答案 0 :(得分:0)
我想出了一个解决办法。
VTCompressionSessionCreate
调用具有用于outputCallbackRefCon
的参数,该参数将传递给VTCompressionOutputCallback
。
通过将自己包裹在UnsafeMutableRawPointer
中
let unmanagedSelf = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque())
我能够将该值传递到VTCompressionSessionCreate
参数下的refcon
中。然后,在回调内部,我可以使用
let scopedSelf = Unmanaged<ViewController>.fromOpaque(unmanagedSelf).takeUnretainedValue()