@capgo/camera-preview 8.12.3 → 8.12.5

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.
Files changed (29) hide show
  1. package/README.md +43 -39
  2. package/android/src/main/java/app/capgo/capacitor/camera/preview/CameraXView.java +26 -28
  3. package/android/src/main/java/app/capgo/capacitor/camera/preview/PhysicalOrientationResolver.java +72 -0
  4. package/android/src/test/java/app/capgo/capacitor/camera/preview/PhysicalOrientationResolverTest.java +90 -0
  5. package/dist/docs.json +8 -4
  6. package/dist/esm/definitions.d.ts +20 -8
  7. package/dist/esm/definitions.js.map +1 -1
  8. package/dist/esm/web.js +6 -3
  9. package/dist/esm/web.js.map +1 -1
  10. package/dist/plugin.cjs.js +6 -3
  11. package/dist/plugin.cjs.js.map +1 -1
  12. package/dist/plugin.js +6 -3
  13. package/dist/plugin.js.map +1 -1
  14. package/ios/Sources/CapgoCameraPreviewPlugin/ApplicationAudioSessionRestoreCoordinator.swift +136 -0
  15. package/ios/Sources/CapgoCameraPreviewPlugin/ApplicationAudioSessionSnapshot.swift +28 -0
  16. package/ios/Sources/CapgoCameraPreviewPlugin/AspectRatioLayout.swift +40 -0
  17. package/ios/Sources/CapgoCameraPreviewPlugin/CameraController.swift +204 -34
  18. package/ios/Sources/CapgoCameraPreviewPlugin/CapturePhotoProcessingQueue.swift +20 -0
  19. package/ios/Sources/CapgoCameraPreviewPlugin/CaptureResolutionSupport.swift +133 -0
  20. package/ios/Sources/CapgoCameraPreviewPlugin/ImageIOJpegEncoding.swift +28 -0
  21. package/ios/Sources/CapgoCameraPreviewPlugin/PhysicalOrientationResolver.swift +59 -0
  22. package/ios/Sources/CapgoCameraPreviewPlugin/Plugin.swift +59 -63
  23. package/ios/Tests/CameraPreviewPluginTests/ApplicationAudioSessionRestoreCoordinatorTests.swift +279 -0
  24. package/ios/Tests/CameraPreviewPluginTests/ApplicationAudioSessionSnapshotTests.swift +25 -0
  25. package/ios/Tests/CameraPreviewPluginTests/CameraPreviewPluginTests.swift +26 -0
  26. package/ios/Tests/CameraPreviewPluginTests/CaptureResolutionSupportTests.swift +133 -0
  27. package/ios/Tests/CameraPreviewPluginTests/ImageIOJpegEncodingTests.swift +42 -0
  28. package/ios/Tests/CameraPreviewPluginTests/PhysicalOrientationResolverTests.swift +89 -0
  29. package/package.json +5 -3
@@ -0,0 +1,136 @@
1
+ import AVFoundation
2
+ import Foundation
3
+
4
+ /// Serializes capture, deferred restore, and completion for the app `AVAudioSession` around preview and recording.
5
+ final class ApplicationAudioSessionRestoreCoordinator {
6
+ private let queue = DispatchQueue(label: "com.capgo.camera.applicationAudioSessionRestore")
7
+
8
+ private var snapshot: ApplicationAudioSessionSnapshot?
9
+ private var snapshotPreviewGeneration: UInt64?
10
+ private var previewGeneration: UInt64 = 0
11
+ private var activeRecordingId: UInt64?
12
+ private var nextRecordingId: UInt64 = 1
13
+ private var deferredRecordingIds: Set<UInt64> = []
14
+ private var deferredPreviewGeneration: UInt64?
15
+ private var captureSessionTeardownComplete = false
16
+ private var finishedBeforeDeferral: Set<UInt64> = []
17
+
18
+ var isDeferredRestorePending: Bool {
19
+ self.queue.sync { !self.deferredRecordingIds.isEmpty }
20
+ }
21
+
22
+ func beginPreviewSession() {
23
+ self.queue.sync {
24
+ self.previewGeneration += 1
25
+ if !self.deferredRecordingIds.isEmpty {
26
+ self.clearDeferredRestoreWithoutApplying()
27
+ }
28
+ }
29
+ }
30
+
31
+ func captureSnapshotIfNeeded() {
32
+ self.queue.sync {
33
+ guard self.snapshot == nil else { return }
34
+ self.snapshot = ApplicationAudioSessionSnapshot.capture()
35
+ self.snapshotPreviewGeneration = self.previewGeneration
36
+ }
37
+ }
38
+
39
+ /// Registers deferred restore before capture session teardown. Returns `true` if the snapshot should be applied after teardown.
40
+ func beginCaptureSessionTeardown(isRecording: Bool, pendingRecordingIds: Set<UInt64> = []) -> Bool {
41
+ self.queue.sync {
42
+ if !self.deferredRecordingIds.isEmpty {
43
+ return false
44
+ }
45
+ var ids = pendingRecordingIds
46
+ if isRecording, let active = self.activeRecordingId {
47
+ ids.insert(active)
48
+ }
49
+ ids.subtract(self.finishedBeforeDeferral)
50
+ self.finishedBeforeDeferral.removeAll()
51
+ guard !ids.isEmpty else {
52
+ return true
53
+ }
54
+ self.deferredRecordingIds = ids
55
+ self.deferredPreviewGeneration = self.previewGeneration
56
+ self.captureSessionTeardownComplete = false
57
+ return false
58
+ }
59
+ }
60
+
61
+ /// Call after capture session `stopRunning()` and input/output removal when restore was deferred for active recordings.
62
+ func completeCaptureSessionTeardown() {
63
+ self.queue.sync {
64
+ guard self.deferredPreviewGeneration != nil else { return }
65
+ self.captureSessionTeardownComplete = true
66
+ self.tryCompleteDeferredRestore()
67
+ }
68
+ }
69
+
70
+ func restoreAfterCaptureSessionTeardown() {
71
+ self.queue.sync {
72
+ self.restoreNow()
73
+ }
74
+ }
75
+
76
+ func beginRecording() -> UInt64 {
77
+ self.queue.sync {
78
+ let id = self.nextRecordingId
79
+ self.nextRecordingId += 1
80
+ self.activeRecordingId = id
81
+ return id
82
+ }
83
+ }
84
+
85
+ func finishRecording(recordingId: UInt64) {
86
+ self.queue.sync {
87
+ self.noteRecordingFinished(recordingId)
88
+ }
89
+ }
90
+
91
+ func finishRecordingAsync(recordingId: UInt64) {
92
+ self.queue.async {
93
+ self.noteRecordingFinished(recordingId)
94
+ }
95
+ }
96
+
97
+ func syncWithQueueForTesting() {
98
+ self.queue.sync {}
99
+ }
100
+
101
+ private func noteRecordingFinished(_ recordingId: UInt64) {
102
+ if self.activeRecordingId == recordingId {
103
+ self.activeRecordingId = nil
104
+ }
105
+ if self.deferredRecordingIds.isEmpty {
106
+ self.finishedBeforeDeferral.insert(recordingId)
107
+ return
108
+ }
109
+ self.deferredRecordingIds.remove(recordingId)
110
+ self.tryCompleteDeferredRestore()
111
+ }
112
+
113
+ private func tryCompleteDeferredRestore() {
114
+ guard self.deferredRecordingIds.isEmpty else { return }
115
+ guard self.captureSessionTeardownComplete else { return }
116
+ if self.deferredPreviewGeneration != self.previewGeneration {
117
+ self.clearDeferredRestoreWithoutApplying()
118
+ return
119
+ }
120
+ self.deferredPreviewGeneration = nil
121
+ self.restoreNow()
122
+ }
123
+
124
+ private func clearDeferredRestoreWithoutApplying() {
125
+ self.deferredRecordingIds.removeAll()
126
+ self.deferredPreviewGeneration = nil
127
+ self.captureSessionTeardownComplete = false
128
+ }
129
+
130
+ private func restoreNow() {
131
+ guard let snap = self.snapshot else { return }
132
+ self.snapshot = nil
133
+ self.snapshotPreviewGeneration = nil
134
+ snap.apply()
135
+ }
136
+ }
@@ -0,0 +1,28 @@
1
+ import AVFoundation
2
+ import Foundation
3
+
4
+ /// Captures and restores the app `AVAudioSession` category, mode, and options.
5
+ struct ApplicationAudioSessionSnapshot {
6
+ private let category: AVAudioSession.Category
7
+ private let mode: AVAudioSession.Mode
8
+ private let categoryOptions: AVAudioSession.CategoryOptions
9
+
10
+ static func capture(from session: AVAudioSession = .sharedInstance()) -> ApplicationAudioSessionSnapshot {
11
+ ApplicationAudioSessionSnapshot(
12
+ category: session.category,
13
+ mode: session.mode,
14
+ categoryOptions: session.categoryOptions
15
+ )
16
+ }
17
+
18
+ @discardableResult
19
+ func apply(to session: AVAudioSession = .sharedInstance()) -> Bool {
20
+ do {
21
+ try session.setCategory(category, mode: mode, options: categoryOptions)
22
+ return true
23
+ } catch {
24
+ print("[CameraPreview] Failed to restore AVAudioSession: \(error)")
25
+ return false
26
+ }
27
+ }
28
+ }
@@ -84,6 +84,46 @@ enum AspectRatioLayout {
84
84
  return interfaceIsPortrait == captureIsPortrait ? ratio : 1 / ratio
85
85
  }
86
86
 
87
+ /// Rect of content with `contentSize` aspect ratio centered inside `container`
88
+ /// using `resizeAspect` / FIT_CENTER letterboxing.
89
+ static func containContentRect(contentSize: CGSize, inside container: CGRect) -> CGRect {
90
+ guard contentSize.width.isFinite, contentSize.height.isFinite,
91
+ contentSize.width > 0, contentSize.height > 0,
92
+ container.width.isFinite, container.height.isFinite,
93
+ container.width > 0, container.height > 0 else {
94
+ return container
95
+ }
96
+
97
+ let contentAspect = contentSize.width / contentSize.height
98
+ let containerAspect = container.width / container.height
99
+
100
+ let fittedSize: CGSize
101
+ if containerAspect > contentAspect {
102
+ fittedSize = CGSize(width: container.height * contentAspect, height: container.height)
103
+ } else {
104
+ fittedSize = CGSize(width: container.width, height: container.width / contentAspect)
105
+ }
106
+
107
+ let origin = CGPoint(
108
+ x: container.origin.x + (container.width - fittedSize.width) / 2,
109
+ y: container.origin.y + (container.height - fittedSize.height) / 2
110
+ )
111
+ return CGRect(origin: origin, size: fittedSize)
112
+ }
113
+
114
+ /// Maps a rect in preview-view coordinates to the same space as `previewView.frame`.
115
+ static func previewContentRectInWebViewCoordinates(
116
+ contentRectInPreviewView: CGRect,
117
+ previewViewFrame: CGRect
118
+ ) -> CGRect {
119
+ CGRect(
120
+ x: previewViewFrame.origin.x + contentRectInPreviewView.origin.x,
121
+ y: previewViewFrame.origin.y + contentRectInPreviewView.origin.y,
122
+ width: contentRectInPreviewView.width,
123
+ height: contentRectInPreviewView.height
124
+ )
125
+ }
126
+
87
127
  /// Centered crop rect with `targetAspectRatio` (width / height) inside `imageSize`,
88
128
  /// matching how `resizeAspectFill` centers the visible area.
89
129
  static func centerCropRect(imageSize: CGSize, targetAspectRatio: CGFloat) -> CGRect {
@@ -56,21 +56,27 @@ class CameraController: NSObject, CXCallObserverDelegate {
56
56
  }
57
57
 
58
58
  // For capture only - uses accelerometer to detect physical orientation to properly position videos/images
59
+ private var lastReliableCaptureOrientation: AVCaptureVideoOrientation?
60
+
59
61
  private func getPhysicalOrientation() -> AVCaptureVideoOrientation {
62
+ let fallback = getVideoOrientation()
60
63
  guard let accelerometerData = motionManager.accelerometerData else {
61
- return lastCaptureOrientation ?? getVideoOrientation() // Fallback to interface in case of accelerometer fail
64
+ return lastReliableCaptureOrientation ?? lastCaptureOrientation ?? fallback
62
65
  }
63
66
 
64
- let x = accelerometerData.acceleration.x
65
- let y = accelerometerData.acceleration.y
66
-
67
- if abs(x) > abs(y) {
68
- // Landscape
69
- return x > 0 ? .landscapeLeft : .landscapeRight
70
- } else {
71
- // Portrait
72
- return y > 0 ? .portraitUpsideDown : .portrait
67
+ let result = PhysicalOrientationResolver.resolve(
68
+ acceleration: PhysicalOrientationResolver.Acceleration(
69
+ x: accelerometerData.acceleration.x,
70
+ y: accelerometerData.acceleration.y,
71
+ z: accelerometerData.acceleration.z
72
+ ),
73
+ lastReliableOrientation: lastReliableCaptureOrientation,
74
+ fallbackOrientation: fallback
75
+ )
76
+ if result.isReliable {
77
+ lastReliableCaptureOrientation = result.orientation
73
78
  }
79
+ return result.orientation
74
80
  }
75
81
 
76
82
  private func setVideoOrientation(_ orientation: AVCaptureVideoOrientation, on connection: AVCaptureConnection) {
@@ -176,6 +182,10 @@ class CameraController: NSObject, CXCallObserverDelegate {
176
182
  private let sessionRecoveryQueue = DispatchQueue(label: "com.capgo.camera.sessionRecovery")
177
183
  private var activePrepareToken: UInt = 0
178
184
  private var audioInputEnabledByUser = false
185
+ var allowHapticsAndSystemSoundsDuringRecording = false
186
+ private let applicationAudioSessionRestoreCoordinator = ApplicationAudioSessionRestoreCoordinator()
187
+ private var recordingIdByOutputFileURL: [URL: UInt64] = [:]
188
+ private let recordingIdQueue = DispatchQueue(label: "com.capgo.camera.recordingIds")
179
189
 
180
190
  var audioDevice: AVCaptureDevice?
181
191
  var audioInput: AVCaptureDeviceInput?
@@ -499,6 +509,63 @@ class CameraController: NSObject, CXCallObserverDelegate {
499
509
  var requestedAspectRatio: String?
500
510
  var requestedAspectMode: String = "contain"
501
511
 
512
+ /// Still-capture sensor cap from `start({ captureResolution })`, when set on iOS.
513
+ var configuredCaptureResolutionWidth: Int?
514
+ var configuredCaptureResolutionHeight: Int?
515
+
516
+ func setConfiguredCaptureResolution(width: Int?, height: Int?) {
517
+ self.configuredCaptureResolutionWidth = width
518
+ self.configuredCaptureResolutionHeight = height
519
+ }
520
+
521
+ private func activeCaptureDevice() -> AVCaptureDevice? {
522
+ if let captureSession = self.captureSession {
523
+ for input in captureSession.inputs {
524
+ guard let deviceInput = input as? AVCaptureDeviceInput,
525
+ deviceInput.device.hasMediaType(.video) else {
526
+ continue
527
+ }
528
+ return deviceInput.device
529
+ }
530
+ }
531
+
532
+ switch currentCameraPosition {
533
+ case .front:
534
+ return self.frontCamera
535
+ case .rear:
536
+ return self.rearCamera
537
+ default:
538
+ return nil
539
+ }
540
+ }
541
+
542
+ private func configuredPhotoMaxDimensions() -> CMVideoDimensions? {
543
+ guard #available(iOS 16.0, *),
544
+ let photoOutput = self.photoOutput,
545
+ let width = self.configuredCaptureResolutionWidth,
546
+ let height = self.configuredCaptureResolutionHeight,
547
+ let device = self.activeCaptureDevice() else {
548
+ return nil
549
+ }
550
+
551
+ return CaptureResolutionSupport.photoMaxDimensions(
552
+ configuredWidth: width,
553
+ configuredHeight: height,
554
+ supportedDimensions: device.activeFormat.supportedMaxPhotoDimensions,
555
+ deviceMax: photoOutput.maxPhotoDimensions
556
+ )
557
+ }
558
+
559
+ private func applyConfiguredCaptureResolutionToPhotoOutputIfNeeded() {
560
+ guard #available(iOS 16.0, *),
561
+ let photoOutput = self.photoOutput,
562
+ let dimensions = self.configuredPhotoMaxDimensions() else {
563
+ return
564
+ }
565
+
566
+ photoOutput.maxPhotoDimensions = dimensions
567
+ }
568
+
502
569
  func calculateAspectRatioFrame(for aspectRatio: String, in bounds: CGRect) -> CGRect {
503
570
  guard let ratio = parseAspectRatio(aspectRatio) else {
504
571
  return bounds
@@ -554,6 +621,56 @@ class CameraController: NSObject, CXCallObserverDelegate {
554
621
 
555
622
  return (width: finalWidth, height: finalHeight)
556
623
  }
624
+
625
+ /// Pixel dimensions of the active camera preview stream in the current interface orientation.
626
+ func capturePreviewContentSize() -> CGSize? {
627
+ let device = (currentCameraPosition == .rear) ? rearCamera : frontCamera
628
+ guard let device = device else {
629
+ return nil
630
+ }
631
+
632
+ let dimensions = CMVideoFormatDescriptionGetDimensions(device.activeFormat.formatDescription)
633
+ var width = CGFloat(dimensions.width)
634
+ var height = CGFloat(dimensions.height)
635
+ guard width > 0, height > 0 else {
636
+ return nil
637
+ }
638
+
639
+ let orientation = self.getVideoOrientation()
640
+ let isPortrait = orientation == .portrait || orientation == .portraitUpsideDown
641
+ if isPortrait {
642
+ swap(&width, &height)
643
+ }
644
+
645
+ return CGSize(width: width, height: height)
646
+ }
647
+
648
+ /// Web-view coordinates of the visible camera image (after letterboxing / pillarboxing).
649
+ func visiblePreviewRect(in previewView: UIView) -> CGRect {
650
+ let containerFrame = previewView.frame
651
+ guard let previewLayer = self.previewLayer else {
652
+ return containerFrame
653
+ }
654
+
655
+ let layerFrame = previewLayer.frame
656
+ let contentRectInPreviewView: CGRect
657
+
658
+ if self.requestedAspectMode == "cover" {
659
+ contentRectInPreviewView = layerFrame
660
+ } else if let contentSize = self.capturePreviewContentSize() {
661
+ contentRectInPreviewView = AspectRatioLayout.containContentRect(
662
+ contentSize: contentSize,
663
+ inside: layerFrame
664
+ )
665
+ } else {
666
+ contentRectInPreviewView = layerFrame
667
+ }
668
+
669
+ return AspectRatioLayout.previewContentRectInWebViewCoordinates(
670
+ contentRectInPreviewView: contentRectInPreviewView,
671
+ previewViewFrame: containerFrame
672
+ )
673
+ }
557
674
  }
558
675
 
559
676
  extension CameraController {
@@ -689,9 +806,11 @@ extension CameraController {
689
806
  return token != 0 && token == self.activePrepareToken
690
807
  }
691
808
 
692
- 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", startToken: UInt, completionHandler: @escaping (Error?) -> Void) {
693
- print("[CameraPreview] 🎬 Starting prepare - position: \(cameraPosition), deviceId: \(deviceId ?? "nil"), disableAudio: \(disableAudio), cameraMode: \(cameraMode), aspectRatio: \(aspectRatio ?? "nil"), aspectMode: \(aspectMode), zoom: \(initialZoomLevel ?? 1)")
809
+ 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) {
810
+ print("[CameraPreview] 🎬 Starting prepare - position: \(cameraPosition), deviceId: \(deviceId ?? "nil"), disableAudio: \(disableAudio), cameraMode: \(cameraMode), aspectRatio: \(aspectRatio ?? "nil"), aspectMode: \(aspectMode), zoom: \(initialZoomLevel ?? 1), allowHapticsAndSystemSoundsDuringRecording: \(allowHapticsAndSystemSoundsDuringRecording)")
694
811
 
812
+ self.allowHapticsAndSystemSoundsDuringRecording = allowHapticsAndSystemSoundsDuringRecording
813
+ self.applicationAudioSessionRestoreCoordinator.beginPreviewSession()
695
814
  self.activePrepareToken = startToken
696
815
 
697
816
  DispatchQueue.global(qos: .userInitiated).async { [weak self] in
@@ -765,6 +884,7 @@ extension CameraController {
765
884
  if let photoOutput = self.photoOutput, captureSession.canAddOutput(photoOutput) {
766
885
  photoOutput.isHighResolutionCaptureEnabled = true
767
886
  captureSession.addOutput(photoOutput)
887
+ self.applyConfiguredCaptureResolutionToPhotoOutputIfNeeded()
768
888
  // Set orientation immediately
769
889
  self.setVideoOrientation(videoOrientation, on: photoOutput.connections)
770
890
  }
@@ -803,6 +923,7 @@ extension CameraController {
803
923
 
804
924
  // Start the session - all outputs are already configured
805
925
  captureSession.startRunning()
926
+ self.applyAllowHapticsAndSystemSoundsDuringRecordingPolicy()
806
927
 
807
928
  // Bring to full opacity after a tiny moment to smooth any visual artifacts
808
929
  DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) { [weak self] in
@@ -1041,6 +1162,7 @@ extension CameraController {
1041
1162
 
1042
1163
  // Add audio input if needed (skip while a phone call owns the audio session)
1043
1164
  if self.shouldAttachAudioInput(disableAudio: disableAudio) {
1165
+ self.captureApplicationAudioSessionSnapshotIfNeeded()
1044
1166
  if self.audioDevice == nil {
1045
1167
  self.audioDevice = AVCaptureDevice.default(for: AVMediaType.audio)
1046
1168
  }
@@ -1048,6 +1170,7 @@ extension CameraController {
1048
1170
  self.audioInput = try AVCaptureDeviceInput(device: audioDevice)
1049
1171
  if captureSession.canAddInput(self.audioInput!) {
1050
1172
  captureSession.addInput(self.audioInput!)
1173
+ self.applyAllowHapticsAndSystemSoundsDuringRecordingPolicy()
1051
1174
  } else {
1052
1175
  throw CameraControllerError.inputsAreInvalid
1053
1176
  }
@@ -1376,6 +1499,8 @@ extension CameraController {
1376
1499
  }
1377
1500
  }
1378
1501
 
1502
+ self.applyConfiguredCaptureResolutionToPhotoOutputIfNeeded()
1503
+
1379
1504
  // Keep orientation correct
1380
1505
  self.updateVideoOrientation()
1381
1506
  }
@@ -1397,9 +1522,16 @@ extension CameraController {
1397
1522
  let visibleFillRatio = self.visibleFillCaptureAspectRatio()
1398
1523
  let settings = AVCapturePhotoSettings()
1399
1524
  // Configure photo capture settings optimized for speed
1400
- // Only use high res if explicitly requesting large dimensions
1401
- let shouldUseHighRes = width.map { $0 > 1920 } ?? false || height.map { $0 > 1920 } ?? false
1525
+ let shouldUseHighRes = CaptureResolutionSupport.shouldEnableHighResolutionPhoto(
1526
+ captureResolutionWidth: self.configuredCaptureResolutionWidth,
1527
+ captureResolutionHeight: self.configuredCaptureResolutionHeight,
1528
+ captureMaxWidth: width,
1529
+ captureMaxHeight: height
1530
+ )
1402
1531
  settings.isHighResolutionPhotoEnabled = shouldUseHighRes
1532
+ if #available(iOS 16.0, *), let dimensions = self.configuredPhotoMaxDimensions() {
1533
+ settings.maxPhotoDimensions = dimensions
1534
+ }
1403
1535
  if #available(iOS 15.0, *) {
1404
1536
  if photoQualityPrioritization == "quality" {
1405
1537
  settings.photoQualityPrioritization = .quality
@@ -2632,6 +2764,8 @@ extension CameraController {
2632
2764
  }
2633
2765
  }
2634
2766
 
2767
+ self.applyConfiguredCaptureResolutionToPhotoOutputIfNeeded()
2768
+
2635
2769
  // Update video orientation
2636
2770
  self.updateVideoOrientation()
2637
2771
  }
@@ -2644,6 +2778,20 @@ extension CameraController {
2644
2778
  return !disableAudio && !self.isPhoneCallActive()
2645
2779
  }
2646
2780
 
2781
+ private func captureApplicationAudioSessionSnapshotIfNeeded() {
2782
+ self.applicationAudioSessionRestoreCoordinator.captureSnapshotIfNeeded()
2783
+ }
2784
+
2785
+ private func applyAllowHapticsAndSystemSoundsDuringRecordingPolicy() {
2786
+ guard self.audioInput != nil else { return }
2787
+ do {
2788
+ try AVAudioSession.sharedInstance()
2789
+ .setAllowHapticsAndSystemSoundsDuringRecording(self.allowHapticsAndSystemSoundsDuringRecording)
2790
+ } catch {
2791
+ print("[CameraPreview] Failed to set allowHapticsAndSystemSoundsDuringRecording: \(error)")
2792
+ }
2793
+ }
2794
+
2647
2795
  private static let insufficientAudioPriorityOSStatus = 561017449
2648
2796
 
2649
2797
  private func isAudioPriorityError(_ error: NSError) -> Bool {
@@ -2695,6 +2843,7 @@ extension CameraController {
2695
2843
  do {
2696
2844
  session.beginConfiguration()
2697
2845
  defer { session.commitConfiguration() }
2846
+ self.captureApplicationAudioSessionSnapshotIfNeeded()
2698
2847
  if self.audioDevice == nil {
2699
2848
  self.audioDevice = AVCaptureDevice.default(for: AVMediaType.audio)
2700
2849
  }
@@ -2705,6 +2854,7 @@ extension CameraController {
2705
2854
  if session.canAddInput(input) {
2706
2855
  session.addInput(input)
2707
2856
  self.audioInput = input
2857
+ self.applyAllowHapticsAndSystemSoundsDuringRecordingPolicy()
2708
2858
  }
2709
2859
  } catch {
2710
2860
  print("[CameraPreview] Failed to restore audio input after interruption: \(error)")
@@ -2792,21 +2942,38 @@ extension CameraController {
2792
2942
  func cleanup() {
2793
2943
  self.invalidateActivePrepare()
2794
2944
  self.cancelPendingFocusExposureRestore()
2945
+ self.configuredCaptureResolutionWidth = nil
2946
+ self.configuredCaptureResolutionHeight = nil
2795
2947
  configuredVideoFrameRate = nil
2796
2948
  stopBarcodeScanner()
2797
2949
  self.unregisterCaptureSessionObservers()
2798
2950
  self.onCameraInterrupted = nil
2799
2951
  self.onCameraInterruptionEnded = nil
2800
2952
  self.onStartFailure = nil
2953
+ let isFileOutputRecording = self.fileVideoOutput?.isRecording == true
2954
+ let pendingRecordingIds = self.recordingIdQueue.sync {
2955
+ Set(self.recordingIdByOutputFileURL.values)
2956
+ }
2957
+ let shouldRestoreAfterTeardown = self.applicationAudioSessionRestoreCoordinator.beginCaptureSessionTeardown(
2958
+ isRecording: isFileOutputRecording,
2959
+ pendingRecordingIds: pendingRecordingIds
2960
+ )
2801
2961
  if let captureSession = self.captureSession {
2802
2962
  captureSession.stopRunning()
2803
2963
  captureSession.inputs.forEach { captureSession.removeInput($0) }
2804
2964
  captureSession.outputs.forEach { captureSession.removeOutput($0) }
2805
2965
  }
2966
+ if shouldRestoreAfterTeardown {
2967
+ self.applicationAudioSessionRestoreCoordinator.restoreAfterCaptureSessionTeardown()
2968
+ } else {
2969
+ self.applicationAudioSessionRestoreCoordinator.completeCaptureSessionTeardown()
2970
+ }
2806
2971
  // Remove listener for subject area change
2807
2972
  NotificationCenter.default.removeObserver(self, name: .AVCaptureDeviceSubjectAreaDidChange, object: nil)
2808
2973
 
2809
2974
  self.motionManager.stopAccelerometerUpdates()
2975
+ self.lastCaptureOrientation = nil
2976
+ self.lastReliableCaptureOrientation = nil
2810
2977
  self.previewLayer?.removeFromSuperlayer()
2811
2978
  self.previewLayer = nil
2812
2979
 
@@ -3265,11 +3432,13 @@ extension CameraController {
3265
3432
  // This reclaims the microphone even if other parts of the app changed the
3266
3433
  // AVAudioSession category (e.g. for UI sound effects) between recordings.
3267
3434
  if self.audioInput != nil {
3435
+ self.allowHapticsAndSystemSoundsDuringRecording = allowHapticsAndSystemSoundsDuringRecording
3436
+ self.captureApplicationAudioSessionSnapshotIfNeeded()
3268
3437
  do {
3269
3438
  let audioSession = AVAudioSession.sharedInstance()
3270
3439
  try audioSession.setCategory(.playAndRecord, mode: .videoRecording, options: [.defaultToSpeaker])
3271
3440
  try audioSession.setActive(true)
3272
- try audioSession.setAllowHapticsAndSystemSoundsDuringRecording(allowHapticsAndSystemSoundsDuringRecording)
3441
+ self.applyAllowHapticsAndSystemSoundsDuringRecordingPolicy()
3273
3442
  } catch {
3274
3443
  print("[CameraPreview] Failed to configure AVAudioSession for video recording: \(error)")
3275
3444
  }
@@ -3333,6 +3502,11 @@ extension CameraController {
3333
3502
  self.applyVideoStabilizationMode()
3334
3503
  }
3335
3504
 
3505
+ let recordingId = self.applicationAudioSessionRestoreCoordinator.beginRecording()
3506
+ self.recordingIdQueue.sync {
3507
+ self.recordingIdByOutputFileURL[fileUrl] = recordingId
3508
+ }
3509
+
3336
3510
  // Start recording video
3337
3511
  fileVideoOutput.startRecording(to: fileUrl, recordingDelegate: self)
3338
3512
 
@@ -3501,34 +3675,25 @@ extension CameraController: UIGestureRecognizerDelegate {
3501
3675
 
3502
3676
  extension CameraController: AVCapturePhotoCaptureDelegate {
3503
3677
  public func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
3504
- if let error = error {
3505
- self.photoCaptureCompletionBlock?(nil, nil, nil, error)
3506
- return
3507
- }
3678
+ CapturePhotoProcessingQueue.async {
3679
+ if let error = error {
3680
+ self.photoCaptureCompletionBlock?(nil, nil, nil, error)
3681
+ return
3682
+ }
3508
3683
 
3509
- // Process photo in background to avoid blocking main thread
3510
- DispatchQueue.global(qos: .userInitiated).async {
3511
- // Get the photo data using the modern API
3512
3684
  guard let imageData = photo.fileDataRepresentation() else {
3513
- DispatchQueue.main.async {
3514
- self.photoCaptureCompletionBlock?(nil, nil, nil, CameraControllerError.unknown)
3515
- }
3685
+ self.photoCaptureCompletionBlock?(nil, nil, nil, CameraControllerError.unknown)
3516
3686
  return
3517
3687
  }
3518
3688
 
3519
- // Create image from data
3520
3689
  guard let image = UIImage(data: imageData) else {
3521
- DispatchQueue.main.async {
3522
- self.photoCaptureCompletionBlock?(nil, nil, nil, CameraControllerError.unknown)
3523
- }
3690
+ self.photoCaptureCompletionBlock?(nil, nil, nil, CameraControllerError.unknown)
3524
3691
  return
3525
3692
  }
3526
3693
 
3527
- // Pass through original file data and metadata so callers can preserve EXIF
3528
- // Don't call fixedOrientation() here - let the completion block handle it after cropping
3529
- DispatchQueue.main.async {
3530
- self.photoCaptureCompletionBlock?(image, imageData, photo.metadata, nil)
3531
- }
3694
+ // Pass through original file data and metadata so callers can preserve EXIF.
3695
+ // Don't call fixedOrientation() here; the completion block handles cropping.
3696
+ self.photoCaptureCompletionBlock?(image, imageData, photo.metadata, nil)
3532
3697
  }
3533
3698
  }
3534
3699
  }
@@ -3735,6 +3900,11 @@ extension CameraController: AVCaptureFileOutputRecordingDelegate {
3735
3900
  let reason = recordingFinishReason(from: error)
3736
3901
  let stopCompletion = self.stopRecordingCompletion
3737
3902
  self.stopRecordingCompletion = nil
3903
+ let recordingSessionId = self.recordingIdQueue.sync {
3904
+ self.recordingIdByOutputFileURL.removeValue(forKey: outputFileURL) ?? 0
3905
+ }
3906
+
3907
+ self.applicationAudioSessionRestoreCoordinator.finishRecordingAsync(recordingId: recordingSessionId)
3738
3908
 
3739
3909
  if let stopCompletion = stopCompletion {
3740
3910
  DispatchQueue.main.async {
@@ -0,0 +1,20 @@
1
+ import Foundation
2
+
3
+ /// Serial queue for still-capture pixel work (crop, resize, mirror, JPEG/EXIF, file I/O).
4
+ enum CapturePhotoProcessingQueue {
5
+ private static let queueKey = DispatchSpecificKey<UInt8>()
6
+
7
+ static let queue: DispatchQueue = {
8
+ let queue = DispatchQueue(label: "com.capgo.camera-preview.capture-processing", qos: .userInitiated)
9
+ queue.setSpecific(key: queueKey, value: 1)
10
+ return queue
11
+ }()
12
+
13
+ static func async(execute work: @escaping () -> Void) {
14
+ queue.async(execute: work)
15
+ }
16
+
17
+ static var isCurrentQueue: Bool {
18
+ DispatchQueue.getSpecific(key: queueKey) != nil
19
+ }
20
+ }