Skip to content

Commit

Permalink
fix: resolve race condition when starting AVCaptureSession (#93)
Browse files Browse the repository at this point in the history
  • Loading branch information
phantumcode authored Jan 10, 2024
1 parent bebdb60 commit b28c192
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 4 deletions.
7 changes: 3 additions & 4 deletions Sources/FaceLiveness/AV/LivenessCaptureSession.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import AVFoundation
class LivenessCaptureSession {
let captureDevice: LivenessCaptureDevice
private let captureQueue = DispatchQueue(label: "com.amazonaws.faceliveness.cameracapturequeue")
private let configurationQueue = DispatchQueue(label: "com.amazonaws.faceliveness.sessionconfiguration", qos: .userInitiated)
let outputDelegate: AVCaptureVideoDataOutputSampleBufferDelegate
var captureSession: AVCaptureSession?

Expand Down Expand Up @@ -43,6 +44,7 @@ class LivenessCaptureSession {
else { throw LivenessCaptureSessionError.cameraUnavailable }

let cameraInput = try AVCaptureDeviceInput(device: camera)
let videoOutput = AVCaptureVideoDataOutput()

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

try setupInput(cameraInput, for: captureSession)
captureSession.sessionPreset = captureDevice.preset

let videoOutput = AVCaptureVideoDataOutput()
try setupOutput(videoOutput, for: captureSession)

try captureDevice.configure()

DispatchQueue.global().async {
configurationQueue.async {
captureSession.startRunning()
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,9 @@ public struct FaceLivenessDetectorView: View {
UIScreen.main.brightness = 1.0
}
}
.onDisappear() {
viewModel.stopRecording()
}
.onReceive(viewModel.$livenessState) { output in
switch output.state {
case .completed:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,12 @@ final class _LivenessViewController: UIViewController {
}
}
}

deinit {
self.previewLayer.removeFromSuperlayer()
(self.previewLayer as? AVCaptureVideoPreviewLayer)?.session = nil
self.previewLayer = nil
}

override func viewDidLoad() {
super.viewDidLoad()
Expand Down Expand Up @@ -110,6 +116,7 @@ extension _LivenessViewController: FaceLivenessViewControllerPresenter {
imageView.frame = self.previewLayer.frame
self.view.addSubview(imageView)
self.previewLayer.removeFromSuperlayer()
(self.previewLayer as? AVCaptureVideoPreviewLayer)?.session = nil
self.viewModel.stopRecording()
}
}
Expand Down

0 comments on commit b28c192

Please sign in to comment.