@capgo/camera-preview 8.14.2 → 8.14.4

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? {
@@ -879,6 +905,50 @@ extension CameraController {
879
905
  return token != 0 && token == self.activePrepareToken
880
906
  }
881
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
+
882
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) {
883
953
  print("[CameraPreview] 🎬 Starting prepare - position: \(cameraPosition), deviceId: \(deviceId ?? "nil"), disableAudio: \(disableAudio), cameraMode: \(cameraMode), aspectRatio: \(aspectRatio ?? "nil"), aspectMode: \(aspectMode), zoom: \(initialZoomLevel ?? 1), allowHapticsAndSystemSoundsDuringRecording: \(allowHapticsAndSystemSoundsDuringRecording)")
884
954
 
@@ -909,96 +979,112 @@ extension CameraController {
909
979
  }
910
980
 
911
981
  do {
912
- // Create session if needed
913
- if self.captureSession == nil {
914
- self.captureSessionTeardownStarted = false
915
- self.captureSession = AVCaptureSession()
916
- }
917
-
918
- guard let captureSession = self.captureSession else {
919
- throw CameraControllerError.captureSessionIsMissing
920
- }
921
-
922
- // Set quality of video
923
- self.videoQuality = videoQuality
924
-
925
- // Prepare outputs early
926
- self.prepareOutputs()
927
-
928
- // Single configuration block for all initial setup
929
- captureSession.beginConfiguration()
930
-
931
- // Set aspect ratio preset and remember requested ratio
932
- self.requestedAspectRatio = aspectRatio
933
- self.requestedAspectMode = aspectMode
934
- self.configureSessionPreset(for: aspectRatio)
935
-
936
- // Set disableFocusIndicator
937
- self.disableFocusIndicator = disableFocusIndicator
938
-
939
- // Configure device inputs
940
- try self.configureDeviceInputs(cameraPosition: cameraPosition, deviceId: deviceId, disableAudio: disableAudio)
941
-
942
- // Add ALL outputs BEFORE starting session to avoid flashes from reconfiguration
943
-
944
- // Get orientation in a thread-safe way
982
+ var prepareError: Error?
945
983
  let videoOrientation = self.getVideoOrientation()
984
+ self.performCaptureSessionMutationSync {
985
+ guard self.beginPrepareOnCaptureQueue(startToken: startToken) else {
986
+ return
987
+ }
946
988
 
947
- // Add data output for preview
948
- if let dataOutput = self.dataOutput, captureSession.canAddOutput(dataOutput) {
949
- captureSession.addOutput(dataOutput)
950
- // Use dedicated queue for better performance
951
- let videoQueue = DispatchQueue(label: "com.camera.videoQueue", qos: .userInteractive)
952
- dataOutput.setSampleBufferDelegate(self, queue: videoQueue)
953
- // Set orientation immediately
954
- self.setVideoOrientation(videoOrientation, on: dataOutput.connections)
955
- }
956
-
957
- // Add photo output immediately to avoid later reconfiguration
958
- if let photoOutput = self.photoOutput, captureSession.canAddOutput(photoOutput) {
959
- photoOutput.isHighResolutionCaptureEnabled = true
960
- captureSession.addOutput(photoOutput)
961
- self.applyConfiguredCaptureResolutionToPhotoOutputIfNeeded()
962
- // Set orientation immediately
963
- 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
+ }
964
1074
  }
965
1075
 
966
- // Add video output if in camera mode
967
- if cameraMode, let fileVideoOutput = self.fileVideoOutput, captureSession.canAddOutput(fileVideoOutput) {
968
- captureSession.addOutput(fileVideoOutput)
969
- // Set orientation immediately
970
- self.setVideoOrientation(videoOrientation, on: fileVideoOutput.connections)
971
- try self.refreshVideoStabilizationAfterMovieOutputAttached()
1076
+ if let prepareError {
1077
+ throw prepareError
972
1078
  }
973
1079
 
974
- // Set up preview layer session in the same configuration block
975
- if let layer = self.previewLayer {
976
- layer.session = captureSession
977
- // Set orientation for preview layer
978
- if let connection = layer.connection { self.setVideoOrientation(videoOrientation, on: connection) }
979
- // Start with a very subtle fade to smooth any remaining visual artifacts
980
- layer.opacity = 0.95
1080
+ guard self.isPrepareTokenValid(startToken), !self.captureSessionTeardownStarted else {
1081
+ return
981
1082
  }
982
1083
 
983
- captureSession.commitConfiguration()
984
-
985
- // Set initial zoom
986
- self.setInitialZoom(level: initialZoomLevel)
987
-
988
1084
  // Set up listener for change in subject area of camera feed
989
1085
  NotificationCenter.default.removeObserver(self, name: .AVCaptureDeviceSubjectAreaDidChange, object: nil)
990
1086
  NotificationCenter.default.addObserver(self, selector: #selector(self.subjectAreaDidChange), name: .AVCaptureDeviceSubjectAreaDidChange, object: nil)
991
1087
 
992
- self.registerCaptureSessionObservers(for: captureSession)
993
-
994
- guard self.isPrepareTokenValid(startToken) else {
995
- return
996
- }
997
-
998
- // Start the session - all outputs are already configured
999
- captureSession.startRunning()
1000
- self.applyAllowHapticsAndSystemSoundsDuringRecordingPolicy()
1001
-
1002
1088
  // Bring to full opacity after a tiny moment to smooth any visual artifacts
1003
1089
  DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) { [weak self] in
1004
1090
  guard let self = self, self.isPrepareTokenValid(startToken) else { return }
@@ -1115,10 +1201,8 @@ extension CameraController {
1115
1201
  }
1116
1202
 
1117
1203
  // Reconfigure session preset to match the new ratio for optimal capture resolution
1118
- if let captureSession = self.captureSession {
1119
- captureSession.beginConfiguration()
1204
+ self.configureCaptureSession {
1120
1205
  self.configureSessionPreset(for: aspectRatio)
1121
- captureSession.commitConfiguration()
1122
1206
  }
1123
1207
 
1124
1208
  // Restore zoom level after session reconfiguration
@@ -1368,12 +1452,9 @@ extension CameraController {
1368
1452
  }
1369
1453
 
1370
1454
  func updateVideoOrientation() {
1371
- // Get orientation in a thread-safe way
1372
- let videoOrientation = self.getVideoOrientation()
1373
-
1374
- // Apply orientation asynchronously on main thread
1375
1455
  let updateBlock = { [weak self] in
1376
1456
  guard let self = self else { return }
1457
+ let videoOrientation = self.getVideoOrientation()
1377
1458
  if let connection = self.previewLayer?.connection { self.setVideoOrientation(videoOrientation, on: connection) }
1378
1459
  if let connections = self.dataOutput?.connections { self.setVideoOrientation(videoOrientation, on: connections) }
1379
1460
  if let connections = self.photoOutput?.connections { self.setVideoOrientation(videoOrientation, on: connections) }
@@ -1459,6 +1540,15 @@ extension CameraController {
1459
1540
  }
1460
1541
 
1461
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 {
1462
1552
  self.cancelPendingFocusExposureRestore()
1463
1553
  configuredVideoFrameRate = nil
1464
1554
  guard let currentCameraPosition = currentCameraPosition,
@@ -2252,18 +2342,25 @@ extension CameraController {
2252
2342
  self.barcodeDetectionInterval = TimeInterval(max(100, detectionIntervalMs)) / 1000.0
2253
2343
  self.lastBarcodeDetectionAt = 0
2254
2344
 
2255
- captureSession.beginConfiguration()
2256
- captureSession.addOutput(output)
2257
- 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
+ }
2258
2353
 
2259
2354
  let requestedTypes = metadataObjectTypes(for: formats)
2260
2355
  let availableTypes = output.availableMetadataObjectTypes
2261
2356
  let enabledTypes = requestedTypes.isEmpty ? availableTypes : requestedTypes.filter { availableTypes.contains($0) }
2262
2357
 
2263
2358
  guard !enabledTypes.isEmpty else {
2264
- captureSession.beginConfiguration()
2265
- captureSession.removeOutput(output)
2266
- captureSession.commitConfiguration()
2359
+ try self.performCaptureSessionMutationSyncThrowing {
2360
+ captureSession.beginConfiguration()
2361
+ captureSession.removeOutput(output)
2362
+ captureSession.commitConfiguration()
2363
+ }
2267
2364
  self.barcodeScannerCallback = nil
2268
2365
  throw CameraControllerError.invalidOperation
2269
2366
  }
@@ -2278,9 +2375,12 @@ extension CameraController {
2278
2375
  if let output = metadataOutput,
2279
2376
  let captureSession = captureSession,
2280
2377
  captureSession.outputs.contains(output) {
2281
- captureSession.beginConfiguration()
2282
- captureSession.removeOutput(output)
2283
- 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
+ }
2284
2384
  }
2285
2385
  metadataOutput = nil
2286
2386
  barcodeScannerCallback = nil
@@ -2808,6 +2908,15 @@ extension CameraController {
2808
2908
  }
2809
2909
 
2810
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 {
2811
2920
  self.cancelPendingFocusExposureRestore()
2812
2921
  guard let captureSession = self.captureSession else {
2813
2922
  throw CameraControllerError.captureSessionIsMissing
@@ -2966,8 +3075,13 @@ extension CameraController {
2966
3075
  }
2967
3076
 
2968
3077
  private func restoreAudioInputIfNeeded(for session: AVCaptureSession) {
3078
+ if CaptureSessionRecoveryGate.shouldSkipRecovery(
3079
+ sessionTeardownStarted: self.captureSessionTeardownStarted,
3080
+ isObservedSession: self.captureSession === session
3081
+ ) {
3082
+ return
3083
+ }
2969
3084
  guard self.audioInputEnabledByUser, self.audioInput == nil, !self.isPhoneCallActive() else { return }
2970
- guard self.captureSession === session else { return }
2971
3085
 
2972
3086
  do {
2973
3087
  session.beginConfiguration()
@@ -2991,7 +3105,12 @@ extension CameraController {
2991
3105
  }
2992
3106
 
2993
3107
  private func dropAudioInputAndRestartSession(for session: AVCaptureSession) {
2994
- guard self.captureSession === session else { return }
3108
+ if CaptureSessionRecoveryGate.shouldSkipRecovery(
3109
+ sessionTeardownStarted: self.captureSessionTeardownStarted,
3110
+ isObservedSession: self.captureSession === session
3111
+ ) {
3112
+ return
3113
+ }
2995
3114
 
2996
3115
  session.beginConfiguration()
2997
3116
  for input in session.inputs {
@@ -3003,6 +3122,13 @@ extension CameraController {
3003
3122
  self.audioInput = nil
3004
3123
  session.commitConfiguration()
3005
3124
 
3125
+ if CaptureSessionRecoveryGate.shouldSkipRecovery(
3126
+ sessionTeardownStarted: self.captureSessionTeardownStarted,
3127
+ isObservedSession: self.captureSession === session
3128
+ ) {
3129
+ return
3130
+ }
3131
+
3006
3132
  if session.isRunning {
3007
3133
  session.stopRunning()
3008
3134
  }
@@ -3016,7 +3142,7 @@ extension CameraController {
3016
3142
  let audioConflict = self.isAudioPriorityError(error)
3017
3143
  guard let session = notification.object as? AVCaptureSession else { return }
3018
3144
  if audioConflict {
3019
- self.sessionRecoveryQueue.async { [weak self] in
3145
+ self.performCaptureSessionMutationAsync { [weak self] in
3020
3146
  self?.dropAudioInputAndRestartSession(for: session)
3021
3147
  }
3022
3148
  }
@@ -3025,8 +3151,14 @@ extension CameraController {
3025
3151
  guard let self = self else { return }
3026
3152
  self.onCameraInterrupted?("runtimeError", audioConflict)
3027
3153
  if !audioConflict && !self.hasReceivedFirstFrame {
3028
- self.sessionRecoveryQueue.async { [weak self] in
3029
- 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
+ }
3030
3162
  session.stopRunning()
3031
3163
  DispatchQueue.main.async {
3032
3164
  self.onStartFailure?(error)
@@ -3043,7 +3175,7 @@ extension CameraController {
3043
3175
  let reason = AVCaptureSession.InterruptionReason(rawValue: reasonValue),
3044
3176
  reason == .audioDeviceInUseByAnotherClient {
3045
3177
  audioRelated = true
3046
- self.sessionRecoveryQueue.async { [weak self] in
3178
+ self.performCaptureSessionMutationAsync { [weak self] in
3047
3179
  self?.dropAudioInputAndRestartSession(for: session)
3048
3180
  }
3049
3181
  }
@@ -3055,8 +3187,14 @@ extension CameraController {
3055
3187
 
3056
3188
  @objc private func handleCaptureSessionInterruptionEnded(_ notification: Notification) {
3057
3189
  guard let session = notification.object as? AVCaptureSession else { return }
3058
- self.sessionRecoveryQueue.async { [weak self] in
3059
- 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
+ }
3060
3198
  self.restoreAudioInputIfNeeded(for: session)
3061
3199
  if !session.isRunning {
3062
3200
  session.startRunning()
@@ -3068,6 +3206,12 @@ extension CameraController {
3068
3206
  }
3069
3207
  }
3070
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
+
3071
3215
  func cleanup() {
3072
3216
  self.captureSessionTeardownStarted = true
3073
3217
  self.cancelPendingSampleCapture()
@@ -3091,10 +3235,11 @@ extension CameraController {
3091
3235
  isRecording: isFileOutputRecording,
3092
3236
  pendingRecordingIds: pendingRecordingIds
3093
3237
  )
3094
- if let captureSession = self.captureSession {
3095
- captureSession.stopRunning()
3096
- captureSession.inputs.forEach { captureSession.removeInput($0) }
3097
- 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
+ }
3098
3243
  }
3099
3244
  if shouldRestoreAfterTeardown {
3100
3245
  self.applicationAudioSessionRestoreCoordinator.restoreAfterCaptureSessionTeardown()
@@ -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.2"
38
+ private let pluginVersion: String = "8.14.4"
39
39
  public let identifier = "CameraPreviewPlugin"
40
40
  public let jsName = "CameraPreview"
41
41
  public let pluginMethods: [CAPPluginMethod] = [
@@ -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.2",
3
+ "version": "8.14.4",
4
4
  "description": "Camera preview",
5
5
  "license": "MPL-2.0",
6
6
  "repository": {
@@ -84,7 +84,7 @@
84
84
  "swiftlint": "^2.0.0",
85
85
  "typescript": "^6.0.3",
86
86
  "prettier-pretty-check": "^0.2.0",
87
- "happy-dom": "^20.0.0"
87
+ "happy-dom": "^21.0.0"
88
88
  },
89
89
  "peerDependencies": {
90
90
  "@capacitor/core": ">=8.0.0"