Skip to content

Commit

Permalink
fix: remove strong reference retain cycle from camera preview view mo…
Browse files Browse the repository at this point in the history
…del (#135)
  • Loading branch information
phantumcode authored Apr 25, 2024
1 parent 83ac755 commit 930462b
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 12 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
//
// Copyright Amazon.com Inc. or its affiliates.
// All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//

import AVFoundation
import CoreImage

class CameraPreviewOutputSampleBufferDelegate: NSObject, AVCaptureVideoDataOutputSampleBufferDelegate {

let updateBufferHandler: ((CVImageBuffer) -> Void)

init(_ updateBufferHandler: @escaping (CVImageBuffer) -> Void) {
self.updateBufferHandler = updateBufferHandler
}

func captureOutput(
_ output: AVCaptureOutput,
didOutput sampleBuffer: CMSampleBuffer,
from connection: AVCaptureConnection
) {
if let buffer = sampleBuffer.imageBuffer {
updateBufferHandler(buffer)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,13 @@ class CameraPreviewViewModel: NSObject, ObservableObject {
position: .front
).devices.first

let outputDelegate = CameraPreviewOutputSampleBufferDelegate { [weak self] buffer in
self?.updateBuffer(buffer)
}

self.previewCaptureSession = LivenessCaptureSession(
captureDevice: .init(avCaptureDevice: avCaptureDevice),
outputDelegate: self
outputDelegate: outputDelegate
)

do {
Expand All @@ -52,18 +56,10 @@ class CameraPreviewViewModel: NSObject, ObservableObject {
func stopSession() {
previewCaptureSession?.stopRunning()
}
}

extension CameraPreviewViewModel: AVCaptureVideoDataOutputSampleBufferDelegate {
func captureOutput(
_ output: AVCaptureOutput,
didOutput sampleBuffer: CMSampleBuffer,
from connection: AVCaptureConnection
) {
if let buffer = sampleBuffer.imageBuffer {
DispatchQueue.main.async {
self.buffer = buffer
}
func updateBuffer(_ buffer: CVImageBuffer) {
DispatchQueue.main.async {
self.buffer = buffer
}
}
}

0 comments on commit 930462b

Please sign in to comment.