Skip to content

Commit b28c192

Browse files
authored
fix: resolve race condition when starting AVCaptureSession (#93)
1 parent bebdb60 commit b28c192

File tree

3 files changed

+13
-4
lines changed

3 files changed

+13
-4
lines changed

Sources/FaceLiveness/AV/LivenessCaptureSession.swift

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import AVFoundation
1111
class LivenessCaptureSession {
1212
let captureDevice: LivenessCaptureDevice
1313
private let captureQueue = DispatchQueue(label: "com.amazonaws.faceliveness.cameracapturequeue")
14+
private let configurationQueue = DispatchQueue(label: "com.amazonaws.faceliveness.sessionconfiguration", qos: .userInitiated)
1415
let outputDelegate: AVCaptureVideoDataOutputSampleBufferDelegate
1516
var captureSession: AVCaptureSession?
1617

@@ -43,6 +44,7 @@ class LivenessCaptureSession {
4344
else { throw LivenessCaptureSessionError.cameraUnavailable }
4445

4546
let cameraInput = try AVCaptureDeviceInput(device: camera)
47+
let videoOutput = AVCaptureVideoDataOutput()
4648

4749
teardownExistingSession(input: cameraInput)
4850
captureSession = AVCaptureSession()
@@ -53,13 +55,10 @@ class LivenessCaptureSession {
5355

5456
try setupInput(cameraInput, for: captureSession)
5557
captureSession.sessionPreset = captureDevice.preset
56-
57-
let videoOutput = AVCaptureVideoDataOutput()
5858
try setupOutput(videoOutput, for: captureSession)
59-
6059
try captureDevice.configure()
6160

62-
DispatchQueue.global().async {
61+
configurationQueue.async {
6362
captureSession.startRunning()
6463
}
6564

Sources/FaceLiveness/Views/Liveness/FaceLivenessDetectionView.swift

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,9 @@ public struct FaceLivenessDetectorView: View {
172172
UIScreen.main.brightness = 1.0
173173
}
174174
}
175+
.onDisappear() {
176+
viewModel.stopRecording()
177+
}
175178
.onReceive(viewModel.$livenessState) { output in
176179
switch output.state {
177180
case .completed:

Sources/FaceLiveness/Views/Liveness/LivenessViewController.swift

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,12 @@ final class _LivenessViewController: UIViewController {
3737
}
3838
}
3939
}
40+
41+
deinit {
42+
self.previewLayer.removeFromSuperlayer()
43+
(self.previewLayer as? AVCaptureVideoPreviewLayer)?.session = nil
44+
self.previewLayer = nil
45+
}
4046

4147
override func viewDidLoad() {
4248
super.viewDidLoad()
@@ -110,6 +116,7 @@ extension _LivenessViewController: FaceLivenessViewControllerPresenter {
110116
imageView.frame = self.previewLayer.frame
111117
self.view.addSubview(imageView)
112118
self.previewLayer.removeFromSuperlayer()
119+
(self.previewLayer as? AVCaptureVideoPreviewLayer)?.session = nil
113120
self.viewModel.stopRecording()
114121
}
115122
}

0 commit comments

Comments
 (0)