title: Deep copy CVPixelBuffer for depth data in Swift
body: <p>I'm getting a stream of depth data from AVCaptureSynchronizedDataCollection and trying to do some processing on the depthDataMap asynchronously. I tried to deep copy the CVPixelBuffer since I don't want to block the camera while processing, but it doesn't seem the copied buffer is correct because I keep getting bad access errors. Here is the code I'm using to deep copy the CVPixelBuffer:</p>
  <pre><code>func duplicatePixelBuffer(input: CVPixelBuffer) -&gt; CVPixelBuffer {
      var copyOut: CVPixelBuffer?
      let bufferWidth = CVPixelBufferGetWidth(input)
      let bufferHeight = CVPixelBufferGetHeight(input)
      let bytesPerRow = CVPixelBufferGetBytesPerRow(input)
      let bufferFormat = CVPixelBufferGetPixelFormatType(input)
          
      _ = CVPixelBufferCreate(kCFAllocatorDefault, bufferWidth, bufferHeight, bufferFormat, CVBufferGetAttachments(input, CVAttachmentMode.shouldPropagate), &amp;copyOut)
      let output = copyOut!
      // Lock the depth map base address before accessing it
      CVPixelBufferLockBaseAddress(input, CVPixelBufferLockFlags.readOnly)
      CVPixelBufferLockBaseAddress(output, CVPixelBufferLockFlags.readOnly)
      let baseAddress = CVPixelBufferGetBaseAddress(input)
      let baseAddressCopy = CVPixelBufferGetBaseAddress(output)
      memcpy(baseAddressCopy, baseAddress, bufferHeight * bytesPerRow)
          
      // Unlock the base address when finished accessing the buffer
      CVPixelBufferUnlockBaseAddress(input, CVPixelBufferLockFlags.readOnly)
      CVPixelBufferUnlockBaseAddress(output, CVPixelBufferLockFlags.readOnly)
      NSLog(&quot;Pixel buffer original: \(input)&quot;)
      NSLog(&quot;Pixel buffer copy: \(output)&quot;)
      return output
  }
  </code></pre>
  <p>I checked the two CVPixelBuffer objects before the return and it seems like there is no iosurface for the copied buffer. Also, there is a MetadataDictionary object in propagatedAttachments in the original, but in the copy the MetadataDictionary object is directly in attributes.</p>
  <p>I've tried some of the other solutions on Stack Overflow with no luck since my planes are non-planar. Would appreciate any insights on this or if I should try a different approach entirely. Thanks!</p>