@capgo/camera-preview 8.14.1 → 8.14.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,6 +9,7 @@ import CallKit
9
9
  class CameraController: NSObject, CXCallObserverDelegate {
10
10
  override init() {
11
11
  super.init()
12
+ CaptureSessionMutationExecutor.register(queue: self.captureSessionQueue)
12
13
  self.callObserver.setDelegate(self, queue: nil)
13
14
  }
14
15
 
@@ -16,8 +17,8 @@ class CameraController: NSObject, CXCallObserverDelegate {
16
17
  guard call.hasEnded,
17
18
  callObserver.calls.allSatisfy({ $0.hasEnded }),
18
19
  let session = self.captureSession else { return }
19
- self.sessionRecoveryQueue.async { [weak self] in
20
- guard let self = self, self.captureSession === session else { return }
20
+ self.performCaptureSessionMutationAsync { [weak self] in
21
+ guard let self = self else { return }
21
22
  self.restoreAudioInputIfNeeded(for: session)
22
23
  }
23
24
  }
@@ -195,7 +196,29 @@ class CameraController: NSObject, CXCallObserverDelegate {
195
196
 
196
197
  private let callObserver = CXCallObserver()
197
198
  private weak var observedCaptureSession: AVCaptureSession?
198
- private let sessionRecoveryQueue = DispatchQueue(label: "com.capgo.camera.sessionRecovery")
199
+ private let captureSessionQueue = DispatchQueue(label: "com.capgo.camera.captureSession")
200
+
201
+ private func performCaptureSessionMutationSync(_ block: () -> Void) {
202
+ CaptureSessionMutationExecutor.performSync(on: self.captureSessionQueue, block)
203
+ }
204
+
205
+ private func performCaptureSessionMutationAsync(_ block: @escaping () -> Void) {
206
+ CaptureSessionMutationExecutor.performAsync(on: self.captureSessionQueue, block)
207
+ }
208
+
209
+ private func performCaptureSessionMutationSyncThrowing(_ block: () throws -> Void) throws {
210
+ var thrown: Error?
211
+ self.performCaptureSessionMutationSync {
212
+ do {
213
+ try block()
214
+ } catch {
215
+ thrown = error
216
+ }
217
+ }
218
+ if let thrown {
219
+ throw thrown
220
+ }
221
+ }
199
222
  private var activePrepareToken: UInt = 0
200
223
  private var audioInputEnabledByUser = false
201
224
  var allowHapticsAndSystemSoundsDuringRecording = false
@@ -247,7 +270,9 @@ class CameraController: NSObject, CXCallObserverDelegate {
247
270
  throw CameraControllerError.invalidOperation
248
271
  }
249
272
  self.videoQuality = quality.lowercased()
250
- self.configureSessionPreset(for: self.requestedAspectRatio)
273
+ self.configureCaptureSession {
274
+ self.configureSessionPreset(for: self.requestedAspectRatio)
275
+ }
251
276
  }
252
277
 
253
278
  func getVideoQuality() -> String {
@@ -382,14 +407,15 @@ class CameraController: NSObject, CXCallObserverDelegate {
382
407
  }
383
408
 
384
409
  private func configureCaptureSession(_ block: () -> Void) {
385
- guard let captureSession = self.captureSession else {
410
+ self.performCaptureSessionMutationSync {
411
+ guard let captureSession = self.captureSession, !self.captureSessionTeardownStarted else {
412
+ return
413
+ }
414
+
415
+ captureSession.beginConfiguration()
416
+ defer { captureSession.commitConfiguration() }
386
417
  block()
387
- return
388
418
  }
389
-
390
- captureSession.beginConfiguration()
391
- defer { captureSession.commitConfiguration() }
392
- block()
393
419
  }
394
420
 
395
421
  private func activeVideoCaptureDevice() -> AVCaptureDevice? {
@@ -542,7 +568,9 @@ class CameraController: NSObject, CXCallObserverDelegate {
542
568
  func finishPhotoCaptureLifecycle() {
543
569
  let work = { [weak self] in
544
570
  guard let self = self else { return }
545
- CaptureLifecycleCoordination.finishCapture(state: &self.captureLifecycle, cleanup: { self.cleanup() })
571
+ if CaptureLifecycleCoordination.finishCapture(state: &self.captureLifecycle) {
572
+ self.cleanup()
573
+ }
546
574
  }
547
575
  if Thread.isMainThread {
548
576
  work()
@@ -877,6 +905,50 @@ extension CameraController {
877
905
  return token != 0 && token == self.activePrepareToken
878
906
  }
879
907
 
908
+ /// Must run on the capture session queue.
909
+ private func beginPrepareOnCaptureQueue(startToken: UInt) -> Bool {
910
+ guard self.isPrepareTokenValid(startToken) else { return false }
911
+ return CaptureSessionPrepareGate.applyBeginIfAllowed(
912
+ sessionTeardownStarted: &self.captureSessionTeardownStarted,
913
+ hasLiveCaptureSession: self.captureSession != nil
914
+ )
915
+ }
916
+
917
+ /// Runs the capture-queue prepare begin gate used by `prepare(startToken:)`. For unit tests.
918
+ internal func runPrepareBeginGateForTesting(startToken: UInt) -> Bool {
919
+ self.activePrepareToken = startToken
920
+ var allowed = false
921
+ self.performCaptureSessionMutationSync {
922
+ allowed = self.beginPrepareOnCaptureQueue(startToken: startToken)
923
+ }
924
+ return allowed
925
+ }
926
+
927
+ /// Marks teardown in progress without running full `cleanup()`. For unit tests.
928
+ internal func markCaptureSessionTeardownInProgressForTesting() {
929
+ self.captureSessionTeardownStarted = true
930
+ }
931
+
932
+ /// Holds the capture queue after passing the prepare begin gate. For unit tests.
933
+ internal func holdCaptureSessionQueueAfterPrepareBeginForTesting(
934
+ startToken: UInt,
935
+ passedGate: DispatchSemaphore,
936
+ releaseHold: DispatchSemaphore
937
+ ) {
938
+ self.activePrepareToken = startToken
939
+ self.performCaptureSessionMutationAsync {
940
+ guard self.beginPrepareOnCaptureQueue(startToken: startToken) else {
941
+ passedGate.signal()
942
+ return
943
+ }
944
+ if self.captureSession == nil {
945
+ self.captureSession = AVCaptureSession()
946
+ }
947
+ passedGate.signal()
948
+ _ = releaseHold.wait(timeout: .now() + 5)
949
+ }
950
+ }
951
+
880
952
  func prepare(cameraPosition: String, deviceId: String? = nil, disableAudio: Bool, cameraMode: Bool, aspectRatio: String? = nil, aspectMode: String = "contain", initialZoomLevel: Float?, disableFocusIndicator: Bool = false, videoQuality: String = "high", allowHapticsAndSystemSoundsDuringRecording: Bool = false, startToken: UInt, completionHandler: @escaping (Error?) -> Void) {
881
953
  print("[CameraPreview] 🎬 Starting prepare - position: \(cameraPosition), deviceId: \(deviceId ?? "nil"), disableAudio: \(disableAudio), cameraMode: \(cameraMode), aspectRatio: \(aspectRatio ?? "nil"), aspectMode: \(aspectMode), zoom: \(initialZoomLevel ?? 1), allowHapticsAndSystemSoundsDuringRecording: \(allowHapticsAndSystemSoundsDuringRecording)")
882
954
 
@@ -907,96 +979,112 @@ extension CameraController {
907
979
  }
908
980
 
909
981
  do {
910
- // Create session if needed
911
- if self.captureSession == nil {
912
- self.captureSessionTeardownStarted = false
913
- self.captureSession = AVCaptureSession()
914
- }
915
-
916
- guard let captureSession = self.captureSession else {
917
- throw CameraControllerError.captureSessionIsMissing
918
- }
919
-
920
- // Set quality of video
921
- self.videoQuality = videoQuality
922
-
923
- // Prepare outputs early
924
- self.prepareOutputs()
925
-
926
- // Single configuration block for all initial setup
927
- captureSession.beginConfiguration()
928
-
929
- // Set aspect ratio preset and remember requested ratio
930
- self.requestedAspectRatio = aspectRatio
931
- self.requestedAspectMode = aspectMode
932
- self.configureSessionPreset(for: aspectRatio)
933
-
934
- // Set disableFocusIndicator
935
- self.disableFocusIndicator = disableFocusIndicator
936
-
937
- // Configure device inputs
938
- try self.configureDeviceInputs(cameraPosition: cameraPosition, deviceId: deviceId, disableAudio: disableAudio)
939
-
940
- // Add ALL outputs BEFORE starting session to avoid flashes from reconfiguration
941
-
942
- // Get orientation in a thread-safe way
982
+ var prepareError: Error?
943
983
  let videoOrientation = self.getVideoOrientation()
984
+ self.performCaptureSessionMutationSync {
985
+ guard self.beginPrepareOnCaptureQueue(startToken: startToken) else {
986
+ return
987
+ }
944
988
 
945
- // Add data output for preview
946
- if let dataOutput = self.dataOutput, captureSession.canAddOutput(dataOutput) {
947
- captureSession.addOutput(dataOutput)
948
- // Use dedicated queue for better performance
949
- let videoQueue = DispatchQueue(label: "com.camera.videoQueue", qos: .userInteractive)
950
- dataOutput.setSampleBufferDelegate(self, queue: videoQueue)
951
- // Set orientation immediately
952
- self.setVideoOrientation(videoOrientation, on: dataOutput.connections)
953
- }
954
-
955
- // Add photo output immediately to avoid later reconfiguration
956
- if let photoOutput = self.photoOutput, captureSession.canAddOutput(photoOutput) {
957
- photoOutput.isHighResolutionCaptureEnabled = true
958
- captureSession.addOutput(photoOutput)
959
- self.applyConfiguredCaptureResolutionToPhotoOutputIfNeeded()
960
- // Set orientation immediately
961
- self.setVideoOrientation(videoOrientation, on: photoOutput.connections)
989
+ do {
990
+ // Create session if needed
991
+ if self.captureSession == nil {
992
+ self.captureSession = AVCaptureSession()
993
+ }
994
+
995
+ guard let captureSession = self.captureSession else {
996
+ throw CameraControllerError.captureSessionIsMissing
997
+ }
998
+
999
+ // Set quality of video
1000
+ self.videoQuality = videoQuality
1001
+
1002
+ // Prepare outputs early
1003
+ self.prepareOutputs()
1004
+
1005
+ // Single configuration block for all initial setup
1006
+ captureSession.beginConfiguration()
1007
+
1008
+ // Set aspect ratio preset and remember requested ratio
1009
+ self.requestedAspectRatio = aspectRatio
1010
+ self.requestedAspectMode = aspectMode
1011
+ self.configureSessionPreset(for: aspectRatio)
1012
+
1013
+ // Set disableFocusIndicator
1014
+ self.disableFocusIndicator = disableFocusIndicator
1015
+
1016
+ // Configure device inputs
1017
+ try self.configureDeviceInputs(cameraPosition: cameraPosition, deviceId: deviceId, disableAudio: disableAudio)
1018
+
1019
+ // Add ALL outputs BEFORE starting session to avoid flashes from reconfiguration
1020
+
1021
+ // Add data output for preview
1022
+ if let dataOutput = self.dataOutput, captureSession.canAddOutput(dataOutput) {
1023
+ captureSession.addOutput(dataOutput)
1024
+ // Use dedicated queue for better performance
1025
+ let videoQueue = DispatchQueue(label: "com.camera.videoQueue", qos: .userInteractive)
1026
+ dataOutput.setSampleBufferDelegate(self, queue: videoQueue)
1027
+ // Set orientation immediately
1028
+ self.setVideoOrientation(videoOrientation, on: dataOutput.connections)
1029
+ }
1030
+
1031
+ // Add photo output immediately to avoid later reconfiguration
1032
+ if let photoOutput = self.photoOutput, captureSession.canAddOutput(photoOutput) {
1033
+ photoOutput.isHighResolutionCaptureEnabled = true
1034
+ captureSession.addOutput(photoOutput)
1035
+ self.applyConfiguredCaptureResolutionToPhotoOutputIfNeeded()
1036
+ // Set orientation immediately
1037
+ self.setVideoOrientation(videoOrientation, on: photoOutput.connections)
1038
+ }
1039
+
1040
+ // Add video output if in camera mode
1041
+ if cameraMode, let fileVideoOutput = self.fileVideoOutput, captureSession.canAddOutput(fileVideoOutput) {
1042
+ captureSession.addOutput(fileVideoOutput)
1043
+ // Set orientation immediately
1044
+ self.setVideoOrientation(videoOrientation, on: fileVideoOutput.connections)
1045
+ try self.refreshVideoStabilizationAfterMovieOutputAttached()
1046
+ }
1047
+
1048
+ // Set up preview layer session in the same configuration block
1049
+ if let layer = self.previewLayer {
1050
+ layer.session = captureSession
1051
+ // Set orientation for preview layer
1052
+ if let connection = layer.connection { self.setVideoOrientation(videoOrientation, on: connection) }
1053
+ // Start with a very subtle fade to smooth any remaining visual artifacts
1054
+ layer.opacity = 0.95
1055
+ }
1056
+
1057
+ captureSession.commitConfiguration()
1058
+
1059
+ guard self.isPrepareTokenValid(startToken), !self.captureSessionTeardownStarted else {
1060
+ return
1061
+ }
1062
+
1063
+ // Set initial zoom
1064
+ self.setInitialZoom(level: initialZoomLevel)
1065
+
1066
+ self.registerCaptureSessionObservers(for: captureSession)
1067
+
1068
+ // Start the session - all outputs are already configured
1069
+ captureSession.startRunning()
1070
+ self.applyAllowHapticsAndSystemSoundsDuringRecordingPolicy()
1071
+ } catch {
1072
+ prepareError = error
1073
+ }
962
1074
  }
963
1075
 
964
- // Add video output if in camera mode
965
- if cameraMode, let fileVideoOutput = self.fileVideoOutput, captureSession.canAddOutput(fileVideoOutput) {
966
- captureSession.addOutput(fileVideoOutput)
967
- // Set orientation immediately
968
- self.setVideoOrientation(videoOrientation, on: fileVideoOutput.connections)
969
- try self.refreshVideoStabilizationAfterMovieOutputAttached()
1076
+ if let prepareError {
1077
+ throw prepareError
970
1078
  }
971
1079
 
972
- // Set up preview layer session in the same configuration block
973
- if let layer = self.previewLayer {
974
- layer.session = captureSession
975
- // Set orientation for preview layer
976
- if let connection = layer.connection { self.setVideoOrientation(videoOrientation, on: connection) }
977
- // Start with a very subtle fade to smooth any remaining visual artifacts
978
- layer.opacity = 0.95
1080
+ guard self.isPrepareTokenValid(startToken), !self.captureSessionTeardownStarted else {
1081
+ return
979
1082
  }
980
1083
 
981
- captureSession.commitConfiguration()
982
-
983
- // Set initial zoom
984
- self.setInitialZoom(level: initialZoomLevel)
985
-
986
1084
  // Set up listener for change in subject area of camera feed
987
1085
  NotificationCenter.default.removeObserver(self, name: .AVCaptureDeviceSubjectAreaDidChange, object: nil)
988
1086
  NotificationCenter.default.addObserver(self, selector: #selector(self.subjectAreaDidChange), name: .AVCaptureDeviceSubjectAreaDidChange, object: nil)
989
1087
 
990
- self.registerCaptureSessionObservers(for: captureSession)
991
-
992
- guard self.isPrepareTokenValid(startToken) else {
993
- return
994
- }
995
-
996
- // Start the session - all outputs are already configured
997
- captureSession.startRunning()
998
- self.applyAllowHapticsAndSystemSoundsDuringRecordingPolicy()
999
-
1000
1088
  // Bring to full opacity after a tiny moment to smooth any visual artifacts
1001
1089
  DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) { [weak self] in
1002
1090
  guard let self = self, self.isPrepareTokenValid(startToken) else { return }
@@ -1113,10 +1201,8 @@ extension CameraController {
1113
1201
  }
1114
1202
 
1115
1203
  // Reconfigure session preset to match the new ratio for optimal capture resolution
1116
- if let captureSession = self.captureSession {
1117
- captureSession.beginConfiguration()
1204
+ self.configureCaptureSession {
1118
1205
  self.configureSessionPreset(for: aspectRatio)
1119
- captureSession.commitConfiguration()
1120
1206
  }
1121
1207
 
1122
1208
  // Restore zoom level after session reconfiguration
@@ -1366,12 +1452,9 @@ extension CameraController {
1366
1452
  }
1367
1453
 
1368
1454
  func updateVideoOrientation() {
1369
- // Get orientation in a thread-safe way
1370
- let videoOrientation = self.getVideoOrientation()
1371
-
1372
- // Apply orientation asynchronously on main thread
1373
1455
  let updateBlock = { [weak self] in
1374
1456
  guard let self = self else { return }
1457
+ let videoOrientation = self.getVideoOrientation()
1375
1458
  if let connection = self.previewLayer?.connection { self.setVideoOrientation(videoOrientation, on: connection) }
1376
1459
  if let connections = self.dataOutput?.connections { self.setVideoOrientation(videoOrientation, on: connections) }
1377
1460
  if let connections = self.photoOutput?.connections { self.setVideoOrientation(videoOrientation, on: connections) }
@@ -1457,6 +1540,15 @@ extension CameraController {
1457
1540
  }
1458
1541
 
1459
1542
  func switchCameras() throws {
1543
+ try self.performCaptureSessionMutationSyncThrowing {
1544
+ guard !self.captureSessionTeardownStarted else {
1545
+ throw CameraControllerError.captureSessionIsMissing
1546
+ }
1547
+ try self.switchCamerasOnCaptureSessionQueue()
1548
+ }
1549
+ }
1550
+
1551
+ private func switchCamerasOnCaptureSessionQueue() throws {
1460
1552
  self.cancelPendingFocusExposureRestore()
1461
1553
  configuredVideoFrameRate = nil
1462
1554
  guard let currentCameraPosition = currentCameraPosition,
@@ -2250,18 +2342,25 @@ extension CameraController {
2250
2342
  self.barcodeDetectionInterval = TimeInterval(max(100, detectionIntervalMs)) / 1000.0
2251
2343
  self.lastBarcodeDetectionAt = 0
2252
2344
 
2253
- captureSession.beginConfiguration()
2254
- captureSession.addOutput(output)
2255
- captureSession.commitConfiguration()
2345
+ try self.performCaptureSessionMutationSyncThrowing {
2346
+ guard !self.captureSessionTeardownStarted else {
2347
+ throw CameraControllerError.captureSessionIsMissing
2348
+ }
2349
+ captureSession.beginConfiguration()
2350
+ captureSession.addOutput(output)
2351
+ captureSession.commitConfiguration()
2352
+ }
2256
2353
 
2257
2354
  let requestedTypes = metadataObjectTypes(for: formats)
2258
2355
  let availableTypes = output.availableMetadataObjectTypes
2259
2356
  let enabledTypes = requestedTypes.isEmpty ? availableTypes : requestedTypes.filter { availableTypes.contains($0) }
2260
2357
 
2261
2358
  guard !enabledTypes.isEmpty else {
2262
- captureSession.beginConfiguration()
2263
- captureSession.removeOutput(output)
2264
- captureSession.commitConfiguration()
2359
+ try self.performCaptureSessionMutationSyncThrowing {
2360
+ captureSession.beginConfiguration()
2361
+ captureSession.removeOutput(output)
2362
+ captureSession.commitConfiguration()
2363
+ }
2265
2364
  self.barcodeScannerCallback = nil
2266
2365
  throw CameraControllerError.invalidOperation
2267
2366
  }
@@ -2276,9 +2375,12 @@ extension CameraController {
2276
2375
  if let output = metadataOutput,
2277
2376
  let captureSession = captureSession,
2278
2377
  captureSession.outputs.contains(output) {
2279
- captureSession.beginConfiguration()
2280
- captureSession.removeOutput(output)
2281
- captureSession.commitConfiguration()
2378
+ self.performCaptureSessionMutationSync {
2379
+ guard !self.captureSessionTeardownStarted, self.captureSession === captureSession else { return }
2380
+ captureSession.beginConfiguration()
2381
+ captureSession.removeOutput(output)
2382
+ captureSession.commitConfiguration()
2383
+ }
2282
2384
  }
2283
2385
  metadataOutput = nil
2284
2386
  barcodeScannerCallback = nil
@@ -2806,6 +2908,15 @@ extension CameraController {
2806
2908
  }
2807
2909
 
2808
2910
  func swapToDevice(deviceId: String) throws {
2911
+ try self.performCaptureSessionMutationSyncThrowing {
2912
+ guard !self.captureSessionTeardownStarted else {
2913
+ throw CameraControllerError.captureSessionIsMissing
2914
+ }
2915
+ try self.swapToDeviceOnCaptureSessionQueue(deviceId: deviceId)
2916
+ }
2917
+ }
2918
+
2919
+ private func swapToDeviceOnCaptureSessionQueue(deviceId: String) throws {
2809
2920
  self.cancelPendingFocusExposureRestore()
2810
2921
  guard let captureSession = self.captureSession else {
2811
2922
  throw CameraControllerError.captureSessionIsMissing
@@ -2964,8 +3075,13 @@ extension CameraController {
2964
3075
  }
2965
3076
 
2966
3077
  private func restoreAudioInputIfNeeded(for session: AVCaptureSession) {
3078
+ if CaptureSessionRecoveryGate.shouldSkipRecovery(
3079
+ sessionTeardownStarted: self.captureSessionTeardownStarted,
3080
+ isObservedSession: self.captureSession === session
3081
+ ) {
3082
+ return
3083
+ }
2967
3084
  guard self.audioInputEnabledByUser, self.audioInput == nil, !self.isPhoneCallActive() else { return }
2968
- guard self.captureSession === session else { return }
2969
3085
 
2970
3086
  do {
2971
3087
  session.beginConfiguration()
@@ -2989,7 +3105,12 @@ extension CameraController {
2989
3105
  }
2990
3106
 
2991
3107
  private func dropAudioInputAndRestartSession(for session: AVCaptureSession) {
2992
- guard self.captureSession === session else { return }
3108
+ if CaptureSessionRecoveryGate.shouldSkipRecovery(
3109
+ sessionTeardownStarted: self.captureSessionTeardownStarted,
3110
+ isObservedSession: self.captureSession === session
3111
+ ) {
3112
+ return
3113
+ }
2993
3114
 
2994
3115
  session.beginConfiguration()
2995
3116
  for input in session.inputs {
@@ -3001,6 +3122,13 @@ extension CameraController {
3001
3122
  self.audioInput = nil
3002
3123
  session.commitConfiguration()
3003
3124
 
3125
+ if CaptureSessionRecoveryGate.shouldSkipRecovery(
3126
+ sessionTeardownStarted: self.captureSessionTeardownStarted,
3127
+ isObservedSession: self.captureSession === session
3128
+ ) {
3129
+ return
3130
+ }
3131
+
3004
3132
  if session.isRunning {
3005
3133
  session.stopRunning()
3006
3134
  }
@@ -3014,7 +3142,7 @@ extension CameraController {
3014
3142
  let audioConflict = self.isAudioPriorityError(error)
3015
3143
  guard let session = notification.object as? AVCaptureSession else { return }
3016
3144
  if audioConflict {
3017
- self.sessionRecoveryQueue.async { [weak self] in
3145
+ self.performCaptureSessionMutationAsync { [weak self] in
3018
3146
  self?.dropAudioInputAndRestartSession(for: session)
3019
3147
  }
3020
3148
  }
@@ -3023,8 +3151,14 @@ extension CameraController {
3023
3151
  guard let self = self else { return }
3024
3152
  self.onCameraInterrupted?("runtimeError", audioConflict)
3025
3153
  if !audioConflict && !self.hasReceivedFirstFrame {
3026
- self.sessionRecoveryQueue.async { [weak self] in
3027
- guard let self = self, self.captureSession === session else { return }
3154
+ self.performCaptureSessionMutationAsync { [weak self] in
3155
+ guard let self = self else { return }
3156
+ if CaptureSessionRecoveryGate.shouldSkipRecovery(
3157
+ sessionTeardownStarted: self.captureSessionTeardownStarted,
3158
+ isObservedSession: self.captureSession === session
3159
+ ) {
3160
+ return
3161
+ }
3028
3162
  session.stopRunning()
3029
3163
  DispatchQueue.main.async {
3030
3164
  self.onStartFailure?(error)
@@ -3041,7 +3175,7 @@ extension CameraController {
3041
3175
  let reason = AVCaptureSession.InterruptionReason(rawValue: reasonValue),
3042
3176
  reason == .audioDeviceInUseByAnotherClient {
3043
3177
  audioRelated = true
3044
- self.sessionRecoveryQueue.async { [weak self] in
3178
+ self.performCaptureSessionMutationAsync { [weak self] in
3045
3179
  self?.dropAudioInputAndRestartSession(for: session)
3046
3180
  }
3047
3181
  }
@@ -3053,8 +3187,14 @@ extension CameraController {
3053
3187
 
3054
3188
  @objc private func handleCaptureSessionInterruptionEnded(_ notification: Notification) {
3055
3189
  guard let session = notification.object as? AVCaptureSession else { return }
3056
- self.sessionRecoveryQueue.async { [weak self] in
3057
- guard let self = self, self.captureSession === session else { return }
3190
+ self.performCaptureSessionMutationAsync { [weak self] in
3191
+ guard let self = self else { return }
3192
+ if CaptureSessionRecoveryGate.shouldSkipRecovery(
3193
+ sessionTeardownStarted: self.captureSessionTeardownStarted,
3194
+ isObservedSession: self.captureSession === session
3195
+ ) {
3196
+ return
3197
+ }
3058
3198
  self.restoreAudioInputIfNeeded(for: session)
3059
3199
  if !session.isRunning {
3060
3200
  session.startRunning()
@@ -3066,6 +3206,12 @@ extension CameraController {
3066
3206
  }
3067
3207
  }
3068
3208
 
3209
+ private func tearDownCaptureSession(_ captureSession: AVCaptureSession) {
3210
+ captureSession.stopRunning()
3211
+ captureSession.inputs.forEach { captureSession.removeInput($0) }
3212
+ captureSession.outputs.forEach { captureSession.removeOutput($0) }
3213
+ }
3214
+
3069
3215
  func cleanup() {
3070
3216
  self.captureSessionTeardownStarted = true
3071
3217
  self.cancelPendingSampleCapture()
@@ -3089,10 +3235,11 @@ extension CameraController {
3089
3235
  isRecording: isFileOutputRecording,
3090
3236
  pendingRecordingIds: pendingRecordingIds
3091
3237
  )
3092
- if let captureSession = self.captureSession {
3093
- captureSession.stopRunning()
3094
- captureSession.inputs.forEach { captureSession.removeInput($0) }
3095
- captureSession.outputs.forEach { captureSession.removeOutput($0) }
3238
+ if self.captureSession != nil {
3239
+ self.performCaptureSessionMutationSync {
3240
+ guard let sessionToTeardown = self.captureSession else { return }
3241
+ self.tearDownCaptureSession(sessionToTeardown)
3242
+ }
3096
3243
  }
3097
3244
  if shouldRestoreAfterTeardown {
3098
3245
  self.applicationAudioSessionRestoreCoordinator.restoreAfterCaptureSessionTeardown()
@@ -51,30 +51,29 @@ enum CaptureLifecycleCoordination {
51
51
  return true
52
52
  }
53
53
  /// Handles `stop()` when a capture may be in flight. Call on the main thread only.
54
+ /// Returns whether the caller should run teardown cleanup after this call returns (avoids `inout` overlap).
55
+ @discardableResult
54
56
  static func handleStop(
55
57
  state: inout CaptureLifecycleState,
56
- force: Bool,
57
- cleanup: () -> Void
58
- ) {
58
+ force: Bool
59
+ ) -> Bool {
59
60
  if state.isCapturingPhoto && !force {
60
61
  state.stopRequestedAfterCapture = true
61
- return
62
+ return false
62
63
  }
63
64
  if force {
64
65
  state.stopRequestedAfterCapture = false
65
66
  }
66
- cleanup()
67
+ return true
67
68
  }
68
69
 
69
70
  /// Ends the capture lifecycle after processing completes. Call on the main thread only.
70
- static func finishCapture(
71
- state: inout CaptureLifecycleState,
72
- cleanup: () -> Void
73
- ) {
71
+ /// Returns whether the caller should run teardown cleanup after this call returns (avoids `inout` overlap).
72
+ @discardableResult
73
+ static func finishCapture(state: inout CaptureLifecycleState) -> Bool {
74
74
  state.isCapturingPhoto = false
75
- if state.stopRequestedAfterCapture {
76
- cleanup()
77
- state.stopRequestedAfterCapture = false
78
- }
75
+ guard state.stopRequestedAfterCapture else { return false }
76
+ state.stopRequestedAfterCapture = false
77
+ return true
79
78
  }
80
79
  }
@@ -0,0 +1,57 @@
1
+ import Foundation
2
+
3
+ /// Guards prepare against reusing a session that cleanup is still tearing down on the capture queue.
4
+ enum CaptureSessionPrepareGate {
5
+ static func mayBeginPrepareOnQueue(sessionTeardownStarted: Bool, hasLiveCaptureSession: Bool) -> Bool {
6
+ !(sessionTeardownStarted && hasLiveCaptureSession)
7
+ }
8
+
9
+ static func shouldClearTeardownStartedBeforePrepare(sessionTeardownStarted: Bool, hasLiveCaptureSession: Bool) -> Bool {
10
+ sessionTeardownStarted && !hasLiveCaptureSession
11
+ }
12
+
13
+ /// Applies prepare begin gating on the capture queue (see `CameraController.prepare`).
14
+ static func applyBeginIfAllowed(sessionTeardownStarted: inout Bool, hasLiveCaptureSession: Bool) -> Bool {
15
+ guard mayBeginPrepareOnQueue(
16
+ sessionTeardownStarted: sessionTeardownStarted,
17
+ hasLiveCaptureSession: hasLiveCaptureSession
18
+ ) else {
19
+ return false
20
+ }
21
+ if shouldClearTeardownStartedBeforePrepare(
22
+ sessionTeardownStarted: sessionTeardownStarted,
23
+ hasLiveCaptureSession: hasLiveCaptureSession
24
+ ) {
25
+ sessionTeardownStarted = false
26
+ }
27
+ return true
28
+ }
29
+ }
30
+
31
+ /// Guards interruption / runtime-error recovery against overlapping teardown.
32
+ enum CaptureSessionRecoveryGate {
33
+ static func shouldSkipRecovery(sessionTeardownStarted: Bool, isObservedSession: Bool) -> Bool {
34
+ sessionTeardownStarted || !isObservedSession
35
+ }
36
+ }
37
+
38
+ /// Serializes mutation work onto the capture session queue without deadlocking when already on that queue.
39
+ enum CaptureSessionMutationExecutor {
40
+ private static let queueKey = DispatchSpecificKey<ObjectIdentifier>()
41
+
42
+ static func register(queue: DispatchQueue) {
43
+ queue.setSpecific(key: queueKey, value: ObjectIdentifier(queue))
44
+ }
45
+
46
+ static func performSync(on queue: DispatchQueue, _ block: () -> Void) {
47
+ if DispatchQueue.getSpecific(key: queueKey) == ObjectIdentifier(queue) {
48
+ block()
49
+ } else {
50
+ queue.sync(execute: block)
51
+ }
52
+ }
53
+
54
+ static func performAsync(on queue: DispatchQueue, _ block: @escaping () -> Void) {
55
+ queue.async(execute: block)
56
+ }
57
+ }
@@ -35,7 +35,7 @@ extension UIWindow {
35
35
  */
36
36
  @objc(CameraPreview)
37
37
  public class CameraPreview: CAPPlugin, CAPBridgedPlugin, CLLocationManagerDelegate {
38
- private let pluginVersion: String = "8.14.1"
38
+ private let pluginVersion: String = "8.14.3"
39
39
  public let identifier = "CameraPreviewPlugin"
40
40
  public let jsName = "CameraPreview"
41
41
  public let pluginMethods: [CAPPluginMethod] = [
@@ -1182,11 +1182,12 @@ public class CameraPreview: CAPPlugin, CAPBridgedPlugin, CLLocationManagerDelega
1182
1182
 
1183
1183
  self.cameraController.cancelPendingSampleCapture()
1184
1184
 
1185
- CaptureLifecycleCoordination.handleStop(
1185
+ if CaptureLifecycleCoordination.handleStop(
1186
1186
  state: &self.cameraController.captureLifecycle,
1187
- force: force,
1188
- cleanup: { self.cameraController.cleanup() }
1189
- )
1187
+ force: force
1188
+ ) {
1189
+ self.cameraController.cleanup()
1190
+ }
1190
1191
 
1191
1192
  call.resolve()
1192
1193
  }
@@ -69,13 +69,15 @@ final class CaptureLifecycleCoordinationTests: XCTestCase {
69
69
  state.isCapturingPhoto = true
70
70
  var cleanupCount = 0
71
71
 
72
- CaptureLifecycleCoordination.handleStop(state: &state, force: false, cleanup: { cleanupCount += 1 })
72
+ XCTAssertFalse(CaptureLifecycleCoordination.handleStop(state: &state, force: false))
73
73
 
74
74
  XCTAssertTrue(state.stopRequestedAfterCapture)
75
75
  XCTAssertTrue(state.isCapturingPhoto)
76
76
  XCTAssertEqual(cleanupCount, 0)
77
77
 
78
- CaptureLifecycleCoordination.finishCapture(state: &state, cleanup: { cleanupCount += 1 })
78
+ if CaptureLifecycleCoordination.finishCapture(state: &state) {
79
+ cleanupCount += 1
80
+ }
79
81
 
80
82
  XCTAssertFalse(state.isCapturingPhoto)
81
83
  XCTAssertFalse(state.stopRequestedAfterCapture)
@@ -87,7 +89,9 @@ final class CaptureLifecycleCoordinationTests: XCTestCase {
87
89
  state.isCapturingPhoto = true
88
90
  var cleanupCount = 0
89
91
 
90
- CaptureLifecycleCoordination.handleStop(state: &state, force: true, cleanup: { cleanupCount += 1 })
92
+ if CaptureLifecycleCoordination.handleStop(state: &state, force: true) {
93
+ cleanupCount += 1
94
+ }
91
95
 
92
96
  XCTAssertFalse(state.stopRequestedAfterCapture)
93
97
  XCTAssertEqual(cleanupCount, 1)
@@ -98,7 +102,9 @@ final class CaptureLifecycleCoordinationTests: XCTestCase {
98
102
  state.isCapturingPhoto = true
99
103
  var cleanupCount = 0
100
104
 
101
- CaptureLifecycleCoordination.finishCapture(state: &state, cleanup: { cleanupCount += 1 })
105
+ if CaptureLifecycleCoordination.finishCapture(state: &state) {
106
+ cleanupCount += 1
107
+ }
102
108
 
103
109
  XCTAssertFalse(state.isCapturingPhoto)
104
110
  XCTAssertFalse(state.stopRequestedAfterCapture)
@@ -110,7 +116,9 @@ final class CaptureLifecycleCoordinationTests: XCTestCase {
110
116
  state.isCapturingPhoto = false
111
117
  var cleanupCount = 0
112
118
 
113
- CaptureLifecycleCoordination.handleStop(state: &state, force: false, cleanup: { cleanupCount += 1 })
119
+ if CaptureLifecycleCoordination.handleStop(state: &state, force: false) {
120
+ cleanupCount += 1
121
+ }
114
122
 
115
123
  XCTAssertFalse(state.stopRequestedAfterCapture)
116
124
  XCTAssertEqual(cleanupCount, 1)
@@ -123,8 +131,12 @@ final class CaptureLifecycleCoordinationTests: XCTestCase {
123
131
  let finishExpectation = expectation(description: "finish on main")
124
132
 
125
133
  DispatchQueue.main.async {
126
- CaptureLifecycleCoordination.handleStop(state: &state, force: false, cleanup: { cleanupCount += 1 })
127
- CaptureLifecycleCoordination.finishCapture(state: &state, cleanup: { cleanupCount += 1 })
134
+ if CaptureLifecycleCoordination.handleStop(state: &state, force: false) {
135
+ cleanupCount += 1
136
+ }
137
+ if CaptureLifecycleCoordination.finishCapture(state: &state) {
138
+ cleanupCount += 1
139
+ }
128
140
  finishExpectation.fulfill()
129
141
  }
130
142
 
@@ -132,4 +144,31 @@ final class CaptureLifecycleCoordinationTests: XCTestCase {
132
144
  XCTAssertEqual(cleanupCount, 1)
133
145
  XCTAssertFalse(state.stopRequestedAfterCapture)
134
146
  }
147
+
148
+ /// Mirrors `stop()` -> `cleanup()` -> `cancelPendingSampleCapture()` reading `captureLifecycle` after coordination returns.
149
+ func testStopCoordinationReleasesStateBeforeCleanupReadsLifecycle() {
150
+ final class LifecycleHost {
151
+ var captureLifecycle = CaptureLifecycleState()
152
+ var cleanupInvocationCount = 0
153
+
154
+ func runStop(force: Bool) {
155
+ if CaptureLifecycleCoordination.handleStop(state: &captureLifecycle, force: force) {
156
+ performCleanup()
157
+ }
158
+ }
159
+
160
+ private func performCleanup() {
161
+ cleanupInvocationCount += 1
162
+ CaptureLifecycleCoordination.cancelAwaitingSampleCaptureIfNeeded(
163
+ isAwaiting: captureLifecycle.isAwaitingSampleCapture
164
+ ) {}
165
+ }
166
+ }
167
+
168
+ let host = LifecycleHost()
169
+ host.captureLifecycle.isAwaitingSampleCapture = true
170
+ host.runStop(force: false)
171
+ XCTAssertEqual(host.cleanupInvocationCount, 1)
172
+ XCTAssertTrue(host.captureLifecycle.isAwaitingSampleCapture)
173
+ }
135
174
  }
@@ -0,0 +1,152 @@
1
+ import AVFoundation
2
+ import XCTest
3
+ @testable import CapgoCameraPreview
4
+
5
+ final class CaptureSessionCoordinationTests: XCTestCase {
6
+ func testRecoverySkippedWhenTeardownStarted() {
7
+ XCTAssertTrue(
8
+ CaptureSessionRecoveryGate.shouldSkipRecovery(sessionTeardownStarted: true, isObservedSession: true)
9
+ )
10
+ }
11
+
12
+ func testRecoverySkippedWhenSessionDoesNotMatch() {
13
+ XCTAssertTrue(
14
+ CaptureSessionRecoveryGate.shouldSkipRecovery(sessionTeardownStarted: false, isObservedSession: false)
15
+ )
16
+ }
17
+
18
+ func testRecoverySkippedWhenTeardownStartedForStaleSession() {
19
+ XCTAssertTrue(
20
+ CaptureSessionRecoveryGate.shouldSkipRecovery(sessionTeardownStarted: true, isObservedSession: false)
21
+ )
22
+ }
23
+
24
+ func testRecoveryAllowedWhenSessionActiveAndNotTearingDown() {
25
+ XCTAssertFalse(
26
+ CaptureSessionRecoveryGate.shouldSkipRecovery(sessionTeardownStarted: false, isObservedSession: true)
27
+ )
28
+ }
29
+
30
+ func testPrepareAbortsWhenTeardownInProgressOnLiveSession() {
31
+ XCTAssertFalse(
32
+ CaptureSessionPrepareGate.mayBeginPrepareOnQueue(sessionTeardownStarted: true, hasLiveCaptureSession: true)
33
+ )
34
+ }
35
+
36
+ func testPrepareClearsTeardownFlagAfterCleanupWhenSessionNil() {
37
+ XCTAssertTrue(
38
+ CaptureSessionPrepareGate.shouldClearTeardownStartedBeforePrepare(
39
+ sessionTeardownStarted: true,
40
+ hasLiveCaptureSession: false
41
+ )
42
+ )
43
+ XCTAssertTrue(
44
+ CaptureSessionPrepareGate.mayBeginPrepareOnQueue(sessionTeardownStarted: true, hasLiveCaptureSession: false)
45
+ )
46
+ }
47
+
48
+ func testControllerPrepareBeginGateClearsTeardownAfterCleanupWithNilSession() {
49
+ let controller = CameraController()
50
+ controller.cleanup()
51
+
52
+ XCTAssertNil(controller.captureSession)
53
+ XCTAssertTrue(controller.captureSessionTeardownStarted)
54
+
55
+ XCTAssertTrue(controller.runPrepareBeginGateForTesting(startToken: 1))
56
+ XCTAssertFalse(controller.captureSessionTeardownStarted)
57
+ }
58
+
59
+ func testControllerPrepareBeginGateBlocksWhileLiveSessionIsTearingDown() {
60
+ let controller = CameraController()
61
+ controller.captureSession = AVCaptureSession()
62
+ controller.markCaptureSessionTeardownInProgressForTesting()
63
+
64
+ XCTAssertFalse(controller.runPrepareBeginGateForTesting(startToken: 1))
65
+ XCTAssertTrue(controller.captureSessionTeardownStarted)
66
+ XCTAssertNotNil(controller.captureSession)
67
+ }
68
+
69
+ func testControllerCleanupThenPrepareBeginGateDoesNotReuseTornDownSession() {
70
+ let controller = CameraController()
71
+ controller.captureSession = AVCaptureSession()
72
+ controller.markCaptureSessionTeardownInProgressForTesting()
73
+
74
+ XCTAssertFalse(controller.runPrepareBeginGateForTesting(startToken: 1))
75
+
76
+ controller.cleanup()
77
+
78
+ XCTAssertNil(controller.captureSession)
79
+ XCTAssertTrue(controller.captureSessionTeardownStarted)
80
+ XCTAssertTrue(controller.runPrepareBeginGateForTesting(startToken: 2))
81
+ XCTAssertFalse(controller.captureSessionTeardownStarted)
82
+ }
83
+
84
+ func testControllerCleanupWhilePrepareMutationHeldOnCaptureQueueClearsSession() {
85
+ let controller = CameraController()
86
+ let passedGate = DispatchSemaphore(value: 0)
87
+ let releaseHold = DispatchSemaphore(value: 0)
88
+ let cleanupFinished = expectation(description: "cleanup finished")
89
+
90
+ controller.holdCaptureSessionQueueAfterPrepareBeginForTesting(
91
+ startToken: 1,
92
+ passedGate: passedGate,
93
+ releaseHold: releaseHold
94
+ )
95
+
96
+ XCTAssertEqual(passedGate.wait(timeout: .now() + 5), .success)
97
+ XCTAssertNotNil(controller.captureSession)
98
+
99
+ DispatchQueue.global(qos: .userInitiated).async {
100
+ controller.cleanup()
101
+ cleanupFinished.fulfill()
102
+ }
103
+
104
+ releaseHold.signal()
105
+
106
+ wait(for: [cleanupFinished], timeout: 5)
107
+ XCTAssertNil(controller.captureSession)
108
+ XCTAssertTrue(controller.runPrepareBeginGateForTesting(startToken: 2))
109
+ }
110
+
111
+ func testMutationExecutorSyncDoesNotDeadlockWhenReentrant() {
112
+ let queue = DispatchQueue(label: "com.capgo.camera.test.captureSession")
113
+ let queueKey = DispatchSpecificKey<Bool>()
114
+ queue.setSpecific(key: queueKey, value: true)
115
+ CaptureSessionMutationExecutor.register(queue: queue)
116
+ var outerRan = false
117
+ var innerRan = false
118
+ var outerOnQueue = false
119
+
120
+ CaptureSessionMutationExecutor.performSync(on: queue) {
121
+ outerOnQueue = DispatchQueue.getSpecific(key: queueKey) == true
122
+ outerRan = true
123
+ CaptureSessionMutationExecutor.performSync(on: queue) {
124
+ innerRan = true
125
+ }
126
+ }
127
+
128
+ XCTAssertTrue(outerOnQueue)
129
+ XCTAssertTrue(outerRan)
130
+ XCTAssertTrue(innerRan)
131
+ }
132
+
133
+ func testMutationExecutorAsyncEventuallyRuns() {
134
+ let queue = DispatchQueue(label: "com.capgo.camera.test.captureSession.async")
135
+ let queueKey = DispatchSpecificKey<Bool>()
136
+ queue.setSpecific(key: queueKey, value: true)
137
+ CaptureSessionMutationExecutor.register(queue: queue)
138
+ let expectation = expectation(description: "async mutation")
139
+ var ran = false
140
+ var ranOnQueue = false
141
+
142
+ CaptureSessionMutationExecutor.performAsync(on: queue) {
143
+ ranOnQueue = DispatchQueue.getSpecific(key: queueKey) == true
144
+ ran = true
145
+ expectation.fulfill()
146
+ }
147
+
148
+ waitForExpectations(timeout: 5)
149
+ XCTAssertTrue(ran)
150
+ XCTAssertTrue(ranOnQueue)
151
+ }
152
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capgo/camera-preview",
3
- "version": "8.14.1",
3
+ "version": "8.14.3",
4
4
  "description": "Camera preview",
5
5
  "license": "MPL-2.0",
6
6
  "repository": {