Can't swap camera with AVCaptureMultiCamSession

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.

Hi,

Can you provide a focused sample project?

-- Greg

I'll have to work that up and it might be quite complicated because if it is a memory issue it might be impacted by other things around it. It would be easier to provide the bigger section of the code base. Would that work? Or I can do a live debugging session with someone.

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.

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.

Can't swap camera with AVCaptureMultiCamSession
 
 
Q