Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Camera frames dropped after changing camera iOS

My method didOutputSampleBuffer is called successfully until I switch cameras using this function:

func switchCameras() {

    captureSession.beginConfiguration()
    captureSession.sessionPreset = AVCaptureSessionPresetMedium
    var error : NSError? = nil
    for input in captureSession.inputs {
        captureSession.removeInput(input as! AVCaptureInput)
    }
    if currentCamera == "back" {
        currentCamera = "front"

        if captureSession.canAddInput(AVCaptureDeviceInput(device: frontCamera, error: &error)) {
            captureSession.addInput(AVCaptureDeviceInput(device: frontCamera, error: &error))
        } else {
            print(error)
        }
    } else {
        currentCamera = "back"
        if captureSession.canAddInput(AVCaptureDeviceInput(device: backCamera, error: &error)) {
            captureSession.addInput(AVCaptureDeviceInput(device: backCamera, error: &error))
        } else {
        }
    }
    print("chagned")
    captureSession.commitConfiguration()
}

After switching, frames are sometimes dropped in this method, so I can't take a picture. After about 5 seconds, frames come back.

func captureOutput(captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, fromConnection connection: AVCaptureConnection!) {
    connection.videoOrientation = AVCaptureVideoOrientation.Portrait

    if capture == true {
        self.capture = false
        var newBuffer = sampleBuffer
            self.capturePicture(newBuffer)


    }
}

IF you need more code let me know.

like image 883
scott Avatar asked Nov 10 '22 06:11

scott


1 Answers

I solved this by changing the output queue to DISPATCH_QUEUE_SERIAL.

let output = AVCaptureVideoDataOutput()
output.videoSettings = [kCVPixelBufferPixelFormatTypeKey as NSString:kCVPixelFormatType_32BGRA]
let queue = dispatch_queue_create("cameraQueue", DISPATCH_QUEUE_SERIAL)
output.setSampleBufferDelegate(self, queue: dispatch_get_main_queue())
like image 85
scott Avatar answered Nov 14 '22 21:11

scott