iosobjective-cavcapturesession

Cannot add multiple inputs to AVCaptureMultiCamSession


I'm just getting started using AVFoundation to capture video from an iPhone's cameras. I've been successful in capturing from either front or back camera individually. However, I've run into trouble when attempting to capture from both simultaneously:

bool
addDevice(AVCaptureSession *session, bool front)
{
    AVCaptureDevicePosition position = front? AVCaptureDevicePositionFront: AVCaptureDevicePositionBack;
    AVCaptureDevice *device;
    AVCaptureDeviceInput *input;
    NSError *error;

    device = [AVCaptureDevice defaultDeviceWithDeviceType:AVCaptureDeviceTypeBuiltinWideAngleCamera mediaType:AVMediaTypeVideo position:position];
    if ( !device ) {
        NSLog(@"Cannot create %s device", front? "front" : "back");
        return false;
    }

    input = [AVCaptureDeviceInput deviceInputWithDevice:device error&error];
    if ( !input ) {
        NSLog(@"Cannot create input for %s device: %@", front? "front" : "back", [error localizedDescription]);
        return false;
    }

    if ( ![session canAddInput:input] ) {
        NSLog(@"Cannot add input for %s device", front? "front" : "back");
        return false;
    }
    [session addInput:input];
    
    return true;
}

AVCaptureSession *
startSession()
{
    AVCaptureMultiCamSession *session;

    session = [AVCaptureMultiCamSession new];
    if ( !addDevice(session, true) || !addDevice(session, false) ) {
        return nil;
    }

    // add output

    [session startRunning];

    return session;
}

The front device is added successfully but [session canAddInput:input] fails for the back device. As I mentioned before, I can take pictures from either device individually.

I've tried reversing the order in which I add the cameras and then it's the front camera that can't be added. So, the issue does appear to be adding multiple inputs.


Solution

  • Not all devices support multi-camera sessions (even though the AVCaptureMultiCamSession can still be instantiated).

    You can determine at runtime whether or not they're supported via the multiCamSupported class property:

    if ( !AVCaptureMultiCamSession.multiCamSupported ) {
        // can't add multiple inputs
    }