I have a running session and a preview layer that is presented inside my view.
I need to change the output several times in my application among AVCaptureStillImageOutput, AVCaptureMetadataOutput and AVCaptureVideoDataOutput, while my preview should appear smoothly without blinking.
The problem: when I add an output to this session then the preview is blinking (please find my attached gif).
The specific lines causes the problem:
self.stillImageOutput = AVCaptureStillImageOutput()
self.stillImageOutput?.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]
if session.canAddOutput(self.stillImageOutput) {
session.addOutput(self.stillImageOutput)
}
My question: How to avoid AVCaptureVideoPreviewLayer from blinking when adding output to a running session?
I found a solution for iPhone 6 and above in this article which describes how to capture high resolution still images during video:
New AV Foundation Camera Features for the iPhone 6 and iPhone 6 Plus
...
..capture full resolution still images without interrupting preview and reconfiguring the device.
The solution:
Instead of adding and removing the outputs, I add all outputs to the session.
For video capture I set the required resolution (1280x720) at the session preset:
session.sessionPreset = AVCaptureSessionPreset1280x720
The outcome of this line is that the active format of the capture device (the back camera in my case) changed.
Each format has HRSI (high resolution still image) which described the dimensions of high resolution images.
This feature is off by default. To enable it, you call AVCaptureStillImageOutput setHighResolutionStillImageOutputEnabled:.
For taking high resolution still images the flag highResolutionStillImageOutputEnabled should set to true:
self.stillImageOutput?.highResolutionStillImageOutputEnabled = true
For iPhone 6 for example, the still image resolution is: 3264x1836 and the preview of the camera doesn't blinking.