从VTCompressionOutputCallback中引用`self`

时间:2019-03-29 15:47:49

标签: ios swift avfoundation video-toolbox

我目前正在尝试使用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

预先感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我想出了一个解决办法。

VTCompressionSessionCreate调用具有用于outputCallbackRefCon的参数,该参数将传递给VTCompressionOutputCallback

通过将自己包裹在UnsafeMutableRawPointer

let unmanagedSelf = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque())

我能够将该值传递到VTCompressionSessionCreate参数下的refcon中。然后,在回调内部,我可以使用

拉回该值
let scopedSelf = Unmanaged<ViewController>.fromOpaque(unmanagedSelf).takeUnretainedValue()