EXC_BAD_ACCESS 尝试通过 VTDecompressionSessionDecodeFrame 传递和读取 UnsafeMutableRawPointer 时

EXC_BAD_ACCESS when trying to pass and read UnsafeMutableRawPointer through VTDecompressionSessionDecodeFrame

我认为这更像是一个指针问题,而不是 VideoToolbox 会话。我正在尝试做类似于 How to calculate FPS of Hardware Decode on iOS 8 exactly? 的事情,并通过 VTDecompressionSessionDecodeFrame 的 sourceFrameRefCon 传递一些元数据,以便我可以在另一端访问它。就我而言,我只想传递一个字符串。

我的解压代码的其他一切都正常。

这里我传了一个字符串

...

let string = "Test"
var cString = (string as NSString)

VTDecompressionSessionDecodeFrame(
     decompressionSession,
     sampleBuffer: sampleBuffer,
     flags: [
          ._EnableAsynchronousDecompression,
          ._EnableTemporalProcessing],
     frameRefcon: &cString,
     infoFlagsOut: &flagsOut)

在我的回调中,我尝试打印它:

callback = { (decompressionOutputRefCon: UnsafeMutableRawPointer?, sourceFrameRefCon: UnsafeMutableRawPointer?, status: OSStatus, infoFlags: VTDecodeInfoFlags, imageBuffer: CVBuffer?, presentationTimeStamp: CMTime, duration: CMTime) in
            
     if let sourceFrameRefCon = sourceFrameRefCon {
          let nsString = sourceFrameRefCon.load(as: NSString.self)
          let string = String(nsString)
          print(string)
     }
    ...

这确实有点用。我会在控制台中看到 Test 打印十几次,但随后我会在 .load

上看到 EXC_BAD_ACCESS

我猜想有一种更聪明的方法来传递这些 UnsafeMutableRawPointer。

使用以下方法完成了这项工作:

输入 VTDecompressionSessionDecodeFrameframeRefCon:

let nsString = NSString(string: "Anything")
let frameRefCon = Unmanaged.passRetained(nsString).toOpaque()

确保通过 frameRefCon &frameRefCon

关于参数为sourceFrameRefCon: UnsafeMutableRawPointer?的输出回调:

if let sourceFrameRefCon = sourceFrameRefCon {
   let nsString = Unmanaged<NSString>.fromOpaque(sourceFrameRefCon).takeRetainedValue()
   print(nsString)
}