I have a PIP camera that is streaming from the front and back based on AVCaptureMultiCamSession. It works fine, but when i go to swap the camera it crashes. This is code that works with a single camera, so not sure what is wrong. Also the object appears valid in the debugger.
This is the snippit where the camera is swapped
private func updateSessionConfiguration() {
guard isCaptureSessionConfigured else { return }
captureSession.beginConfiguration()
defer { captureSession.commitConfiguration() }
// Remove all current inputs
for input in captureSession.inputs {
if let deviceInput = input as? AVCaptureDeviceInput {
captureSession.removeInput(deviceInput)
app_log("removing input for \(input)")
}
}
// Add the primary device input
if let deviceInput = deviceInputFor(device: captureDevice) {
app_log("device input \(deviceInput)")
if !captureSession.inputs.contains(deviceInput), captureSession.canAddInput(deviceInput) {
captureSession.addInput(deviceInput)
}
}
if let secondaryDeviceInput = deviceInputFor(device: secondaryCaptureDevice) {
app_log("Secondary device input \(secondaryDeviceInput)")
if !captureSession.inputs.contains(secondaryDeviceInput), captureSession.canAddInput(secondaryDeviceInput) {
captureSession.addInput(secondaryDeviceInput)
}
}
updateVideoOutputConnection()
}
It crashes at: captureSession.addInput(deviceInput) with: Thread 10: EXC_BAD_ACCESS (code=1, address=0xcaeb36b964f0)
which is strange because canAdd is checked prior to this call. Totally stumped here. Please help. Not sure if this is an AVCaptureMuliCamSession issue or something.
To work around this in the end I moved up to the view level and swapped the image streams when the user requested a camera swap (so the image feed to the main view went into the inset and the image feed to the inset went into the main view). This feels like a hack but it is sort of working.
If I'm interpreting this correctly, this is actually what AVMultiCamPiP does. Rather than reconfigure the capture session to swap the full-screen and pip devices, it just swaps the views.
But am i correct in thinking this SHOULD work that i should be able to detach the front and back camera and then reattach them as different devices as I show in my description? I did confirm in logging and debugger that they are properly detached and then reattached. I'm not sure if i am missing some preconditions on how to handle the stream or if this should work.
In principle, yes you should be able to detach them and then reattach them. The issue you are seeing might be fallout from adding your inputs with implicit connections rather than explicit connections, see https://developer.apple.com/videos/play/wwdc2019/249/?time=382
I wouldn't be able to say for sure without a focused sample to reproduce the issue.
-- Greg