从VTCompressionOutputCallback中引用`self` [英] Referencing `self` from within a VTCompressionOutputCallback
问题描述
我目前正在尝试使用VideoToolbox对 AVCaptureVideoDataOutput
中的视频数据进行编码,但是在从 VTCompressionOutputCallback
.
I'm currently trying to use VideoToolbox to encode video data from an AVCaptureVideoDataOutput
, but I'm having an issue referencing self
from within the 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))
...
这可以正常工作,并且可以按预期方式输出打印结果,但是一旦我尝试在 VTCompressionOutputCallback
中添加对 self
的引用,就会出现编译器错误,指出
That works fine, and the print outputs as expected, but as soon as I try and add a reference to self
within the VTCompressionOutputCallback
, it get a compiler error stating
不能从捕获上下文的闭包中形成C函数指针
如何在回调中使用 self
?
预先感谢您的帮助.
推荐答案
我想出了一个解决方案.
I figured out a solution.
VTCompressionSessionCreate
调用具有用于 outputCallbackRefCon
的参数,该参数将传递给 VTCompressionOutputCallback
.
The VTCompressionSessionCreate
call has a parameter for outputCallbackRefCon
which gets passed along to the VTCompressionOutputCallback
.
通过像这样将自己包装在 UnsafeMutableRawPointer
中
By wrapping self in an UnsafeMutableRawPointer
like so
let unmanagedSelf = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque())
我能够将该值传递到 refcon
参数下的 VTCompressionSessionCreate
中.然后,在回调内部,我可以使用
I was able to pass that value into the VTCompressionSessionCreate
under the refcon
parameter. Inside of the callback I was then able to do pull that value back out using
let scopedSelf = Unmanaged<ViewController>.fromOpaque(unmanagedSelf).takeUnretainedValue()
这篇关于从VTCompressionOutputCallback中引用`self`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!