@capgo/camera-preview 8.12.4 → 8.13.0

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 (30) hide show
  1. package/README.md +56 -51
  2. package/android/src/main/java/app/capgo/capacitor/camera/preview/CameraPreview.java +13 -2
  3. package/android/src/main/java/app/capgo/capacitor/camera/preview/CameraXView.java +17 -4
  4. package/android/src/main/java/app/capgo/capacitor/camera/preview/CaptureOrientationResolver.java +28 -0
  5. package/android/src/test/java/app/capgo/capacitor/camera/preview/CaptureOrientationResolverTest.java +31 -0
  6. package/dist/docs.json +24 -4
  7. package/dist/esm/definitions.d.ts +28 -8
  8. package/dist/esm/definitions.js.map +1 -1
  9. package/dist/esm/web.js +6 -3
  10. package/dist/esm/web.js.map +1 -1
  11. package/dist/plugin.cjs.js +6 -3
  12. package/dist/plugin.cjs.js.map +1 -1
  13. package/dist/plugin.js +6 -3
  14. package/dist/plugin.js.map +1 -1
  15. package/ios/Sources/CapgoCameraPreviewPlugin/AspectRatioLayout.swift +40 -0
  16. package/ios/Sources/CapgoCameraPreviewPlugin/CameraController.swift +246 -57
  17. package/ios/Sources/CapgoCameraPreviewPlugin/CaptureImageExifEncoder.swift +88 -0
  18. package/ios/Sources/CapgoCameraPreviewPlugin/CaptureLifecycleCoordination.swift +37 -0
  19. package/ios/Sources/CapgoCameraPreviewPlugin/CaptureOrientationResolver.swift +23 -0
  20. package/ios/Sources/CapgoCameraPreviewPlugin/CapturePhotoProcessingQueue.swift +20 -0
  21. package/ios/Sources/CapgoCameraPreviewPlugin/CaptureResolutionSupport.swift +133 -0
  22. package/ios/Sources/CapgoCameraPreviewPlugin/ImageIOJpegEncoding.swift +28 -0
  23. package/ios/Sources/CapgoCameraPreviewPlugin/Plugin.swift +74 -142
  24. package/ios/Tests/CameraPreviewPluginTests/CameraPreviewPluginTests.swift +26 -0
  25. package/ios/Tests/CameraPreviewPluginTests/CaptureImageExifEncoderTests.swift +141 -0
  26. package/ios/Tests/CameraPreviewPluginTests/CaptureLifecycleCoordinationTests.swift +73 -0
  27. package/ios/Tests/CameraPreviewPluginTests/CaptureOrientationResolverTests.swift +30 -0
  28. package/ios/Tests/CameraPreviewPluginTests/CaptureResolutionSupportTests.swift +133 -0
  29. package/ios/Tests/CameraPreviewPluginTests/ImageIOJpegEncodingTests.swift +42 -0
  30. package/package.json +5 -3
@@ -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 {
@@ -55,6 +55,22 @@ class CameraController: NSObject, CXCallObserverDelegate {
55
55
  return orientation
56
56
  }
57
57
 
58
+ private func getPreviewLayerVideoOrientation() -> AVCaptureVideoOrientation? {
59
+ if Thread.isMainThread {
60
+ if let connection = self.previewLayer?.connection, connection.isVideoOrientationSupported {
61
+ return connection.videoOrientation
62
+ }
63
+ return nil
64
+ }
65
+ var orientation: AVCaptureVideoOrientation?
66
+ DispatchQueue.main.sync {
67
+ if let connection = self.previewLayer?.connection, connection.isVideoOrientationSupported {
68
+ orientation = connection.videoOrientation
69
+ }
70
+ }
71
+ return orientation
72
+ }
73
+
58
74
  // For capture only - uses accelerometer to detect physical orientation to properly position videos/images
59
75
  private var lastReliableCaptureOrientation: AVCaptureVideoOrientation?
60
76
 
@@ -182,6 +198,7 @@ class CameraController: NSObject, CXCallObserverDelegate {
182
198
  private let sessionRecoveryQueue = DispatchQueue(label: "com.capgo.camera.sessionRecovery")
183
199
  private var activePrepareToken: UInt = 0
184
200
  private var audioInputEnabledByUser = false
201
+ var allowHapticsAndSystemSoundsDuringRecording = false
185
202
  private let applicationAudioSessionRestoreCoordinator = ApplicationAudioSessionRestoreCoordinator()
186
203
  private var recordingIdByOutputFileURL: [URL: UInt64] = [:]
187
204
  private let recordingIdQueue = DispatchQueue(label: "com.capgo.camera.recordingIds")
@@ -481,9 +498,30 @@ class CameraController: NSObject, CXCallObserverDelegate {
481
498
  // Track output preparation status
482
499
  private var outputsPrepared: Bool = false
483
500
 
484
- // Capture/stop coordination
485
- var isCapturingPhoto: Bool = false
486
- var stopRequestedAfterCapture: Bool = false
501
+ // Capture/stop coordination (main-thread only; see CaptureLifecycleCoordination)
502
+ var captureLifecycle = CaptureLifecycleState()
503
+
504
+ var isCapturingPhoto: Bool {
505
+ get { self.captureLifecycle.isCapturingPhoto }
506
+ set { self.captureLifecycle.isCapturingPhoto = newValue }
507
+ }
508
+
509
+ var stopRequestedAfterCapture: Bool {
510
+ get { self.captureLifecycle.stopRequestedAfterCapture }
511
+ set { self.captureLifecycle.stopRequestedAfterCapture = newValue }
512
+ }
513
+
514
+ func finishPhotoCaptureLifecycle() {
515
+ let work = { [weak self] in
516
+ guard let self = self else { return }
517
+ CaptureLifecycleCoordination.finishCapture(state: &self.captureLifecycle, cleanup: { self.cleanup() })
518
+ }
519
+ if Thread.isMainThread {
520
+ work()
521
+ } else {
522
+ DispatchQueue.main.async(execute: work)
523
+ }
524
+ }
487
525
 
488
526
  var isUsingMultiLensVirtualCamera: Bool {
489
527
  guard let device = (currentCameraPosition == .rear) ? rearCamera : frontCamera else { return false }
@@ -508,6 +546,63 @@ class CameraController: NSObject, CXCallObserverDelegate {
508
546
  var requestedAspectRatio: String?
509
547
  var requestedAspectMode: String = "contain"
510
548
 
549
+ /// Still-capture sensor cap from `start({ captureResolution })`, when set on iOS.
550
+ var configuredCaptureResolutionWidth: Int?
551
+ var configuredCaptureResolutionHeight: Int?
552
+
553
+ func setConfiguredCaptureResolution(width: Int?, height: Int?) {
554
+ self.configuredCaptureResolutionWidth = width
555
+ self.configuredCaptureResolutionHeight = height
556
+ }
557
+
558
+ private func activeCaptureDevice() -> AVCaptureDevice? {
559
+ if let captureSession = self.captureSession {
560
+ for input in captureSession.inputs {
561
+ guard let deviceInput = input as? AVCaptureDeviceInput,
562
+ deviceInput.device.hasMediaType(.video) else {
563
+ continue
564
+ }
565
+ return deviceInput.device
566
+ }
567
+ }
568
+
569
+ switch currentCameraPosition {
570
+ case .front:
571
+ return self.frontCamera
572
+ case .rear:
573
+ return self.rearCamera
574
+ default:
575
+ return nil
576
+ }
577
+ }
578
+
579
+ private func configuredPhotoMaxDimensions() -> CMVideoDimensions? {
580
+ guard #available(iOS 16.0, *),
581
+ let photoOutput = self.photoOutput,
582
+ let width = self.configuredCaptureResolutionWidth,
583
+ let height = self.configuredCaptureResolutionHeight,
584
+ let device = self.activeCaptureDevice() else {
585
+ return nil
586
+ }
587
+
588
+ return CaptureResolutionSupport.photoMaxDimensions(
589
+ configuredWidth: width,
590
+ configuredHeight: height,
591
+ supportedDimensions: device.activeFormat.supportedMaxPhotoDimensions,
592
+ deviceMax: photoOutput.maxPhotoDimensions
593
+ )
594
+ }
595
+
596
+ private func applyConfiguredCaptureResolutionToPhotoOutputIfNeeded() {
597
+ guard #available(iOS 16.0, *),
598
+ let photoOutput = self.photoOutput,
599
+ let dimensions = self.configuredPhotoMaxDimensions() else {
600
+ return
601
+ }
602
+
603
+ photoOutput.maxPhotoDimensions = dimensions
604
+ }
605
+
511
606
  func calculateAspectRatioFrame(for aspectRatio: String, in bounds: CGRect) -> CGRect {
512
607
  guard let ratio = parseAspectRatio(aspectRatio) else {
513
608
  return bounds
@@ -563,6 +658,56 @@ class CameraController: NSObject, CXCallObserverDelegate {
563
658
 
564
659
  return (width: finalWidth, height: finalHeight)
565
660
  }
661
+
662
+ /// Pixel dimensions of the active camera preview stream in the current interface orientation.
663
+ func capturePreviewContentSize() -> CGSize? {
664
+ let device = (currentCameraPosition == .rear) ? rearCamera : frontCamera
665
+ guard let device = device else {
666
+ return nil
667
+ }
668
+
669
+ let dimensions = CMVideoFormatDescriptionGetDimensions(device.activeFormat.formatDescription)
670
+ var width = CGFloat(dimensions.width)
671
+ var height = CGFloat(dimensions.height)
672
+ guard width > 0, height > 0 else {
673
+ return nil
674
+ }
675
+
676
+ let orientation = self.getVideoOrientation()
677
+ let isPortrait = orientation == .portrait || orientation == .portraitUpsideDown
678
+ if isPortrait {
679
+ swap(&width, &height)
680
+ }
681
+
682
+ return CGSize(width: width, height: height)
683
+ }
684
+
685
+ /// Web-view coordinates of the visible camera image (after letterboxing / pillarboxing).
686
+ func visiblePreviewRect(in previewView: UIView) -> CGRect {
687
+ let containerFrame = previewView.frame
688
+ guard let previewLayer = self.previewLayer else {
689
+ return containerFrame
690
+ }
691
+
692
+ let layerFrame = previewLayer.frame
693
+ let contentRectInPreviewView: CGRect
694
+
695
+ if self.requestedAspectMode == "cover" {
696
+ contentRectInPreviewView = layerFrame
697
+ } else if let contentSize = self.capturePreviewContentSize() {
698
+ contentRectInPreviewView = AspectRatioLayout.containContentRect(
699
+ contentSize: contentSize,
700
+ inside: layerFrame
701
+ )
702
+ } else {
703
+ contentRectInPreviewView = layerFrame
704
+ }
705
+
706
+ return AspectRatioLayout.previewContentRectInWebViewCoordinates(
707
+ contentRectInPreviewView: contentRectInPreviewView,
708
+ previewViewFrame: containerFrame
709
+ )
710
+ }
566
711
  }
567
712
 
568
713
  extension CameraController {
@@ -698,9 +843,10 @@ extension CameraController {
698
843
  return token != 0 && token == self.activePrepareToken
699
844
  }
700
845
 
701
- 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) {
702
- print("[CameraPreview] 🎬 Starting prepare - position: \(cameraPosition), deviceId: \(deviceId ?? "nil"), disableAudio: \(disableAudio), cameraMode: \(cameraMode), aspectRatio: \(aspectRatio ?? "nil"), aspectMode: \(aspectMode), zoom: \(initialZoomLevel ?? 1)")
846
+ 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) {
847
+ print("[CameraPreview] 🎬 Starting prepare - position: \(cameraPosition), deviceId: \(deviceId ?? "nil"), disableAudio: \(disableAudio), cameraMode: \(cameraMode), aspectRatio: \(aspectRatio ?? "nil"), aspectMode: \(aspectMode), zoom: \(initialZoomLevel ?? 1), allowHapticsAndSystemSoundsDuringRecording: \(allowHapticsAndSystemSoundsDuringRecording)")
703
848
 
849
+ self.allowHapticsAndSystemSoundsDuringRecording = allowHapticsAndSystemSoundsDuringRecording
704
850
  self.applicationAudioSessionRestoreCoordinator.beginPreviewSession()
705
851
  self.activePrepareToken = startToken
706
852
 
@@ -775,6 +921,7 @@ extension CameraController {
775
921
  if let photoOutput = self.photoOutput, captureSession.canAddOutput(photoOutput) {
776
922
  photoOutput.isHighResolutionCaptureEnabled = true
777
923
  captureSession.addOutput(photoOutput)
924
+ self.applyConfiguredCaptureResolutionToPhotoOutputIfNeeded()
778
925
  // Set orientation immediately
779
926
  self.setVideoOrientation(videoOrientation, on: photoOutput.connections)
780
927
  }
@@ -813,6 +960,7 @@ extension CameraController {
813
960
 
814
961
  // Start the session - all outputs are already configured
815
962
  captureSession.startRunning()
963
+ self.applyAllowHapticsAndSystemSoundsDuringRecordingPolicy()
816
964
 
817
965
  // Bring to full opacity after a tiny moment to smooth any visual artifacts
818
966
  DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) { [weak self] in
@@ -1059,6 +1207,7 @@ extension CameraController {
1059
1207
  self.audioInput = try AVCaptureDeviceInput(device: audioDevice)
1060
1208
  if captureSession.canAddInput(self.audioInput!) {
1061
1209
  captureSession.addInput(self.audioInput!)
1210
+ self.applyAllowHapticsAndSystemSoundsDuringRecordingPolicy()
1062
1211
  } else {
1063
1212
  throw CameraControllerError.inputsAreInvalid
1064
1213
  }
@@ -1387,30 +1536,47 @@ extension CameraController {
1387
1536
  }
1388
1537
  }
1389
1538
 
1539
+ self.applyConfiguredCaptureResolutionToPhotoOutputIfNeeded()
1540
+
1390
1541
  // Keep orientation correct
1391
1542
  self.updateVideoOrientation()
1392
1543
  }
1393
1544
 
1394
- func captureImage(width: Int?, height: Int?, quality: Float, gpsLocation: CLLocation?, embedTimestamp: Bool, embedLocation: Bool, photoQualityPrioritization: String, completion: @escaping (UIImage?, Data?, [AnyHashable: Any]?, Error?) -> Void) {
1545
+ func captureImage(width: Int?, height: Int?, quality: Float, gpsLocation: CLLocation?, embedTimestamp: Bool, embedLocation: Bool, photoQualityPrioritization: String, captureOrientationMode: String?, completion: @escaping (UIImage?, Data?, [AnyHashable: Any]?, Error?) -> Void) {
1395
1546
  guard let photoOutput = self.photoOutput else {
1396
1547
  completion(nil, nil, nil, NSError(domain: "Camera", code: 0, userInfo: [NSLocalizedDescriptionKey: "Photo output is not available"]))
1397
1548
  return
1398
1549
  }
1399
1550
 
1400
- // Make sure capture is getting the physical orientation not interface orientation
1551
+ var orientationUsedForCapture = self.getPhysicalOrientation()
1401
1552
  if let connection = photoOutput.connection(with: .video) {
1402
- let captureOrientation = self.getPhysicalOrientation()
1403
- self.lastCaptureOrientation = captureOrientation
1553
+ let previewOrientation = self.getPreviewLayerVideoOrientation() ?? self.getVideoOrientation()
1554
+ let captureOrientation = CaptureOrientationResolver.resolveOrientation(
1555
+ mode: captureOrientationMode,
1556
+ previewOrientation: previewOrientation,
1557
+ deviceOrientation: self.getPhysicalOrientation()
1558
+ )
1559
+ orientationUsedForCapture = captureOrientation
1560
+ if CaptureOrientationResolver.usesDeviceOrientation(mode: captureOrientationMode) {
1561
+ self.lastCaptureOrientation = captureOrientation
1562
+ }
1404
1563
  self.setVideoOrientation(captureOrientation, on: connection)
1405
1564
  }
1406
1565
  // For fill + cover the preview shows a centered crop of the frame. Snapshot its
1407
1566
  // shape now so the photo can be cropped to the same visible area.
1408
- let visibleFillRatio = self.visibleFillCaptureAspectRatio()
1567
+ let visibleFillRatio = self.visibleFillCaptureAspectRatio(captureOrientation: orientationUsedForCapture)
1409
1568
  let settings = AVCapturePhotoSettings()
1410
1569
  // Configure photo capture settings optimized for speed
1411
- // Only use high res if explicitly requesting large dimensions
1412
- let shouldUseHighRes = width.map { $0 > 1920 } ?? false || height.map { $0 > 1920 } ?? false
1570
+ let shouldUseHighRes = CaptureResolutionSupport.shouldEnableHighResolutionPhoto(
1571
+ captureResolutionWidth: self.configuredCaptureResolutionWidth,
1572
+ captureResolutionHeight: self.configuredCaptureResolutionHeight,
1573
+ captureMaxWidth: width,
1574
+ captureMaxHeight: height
1575
+ )
1413
1576
  settings.isHighResolutionPhotoEnabled = shouldUseHighRes
1577
+ if #available(iOS 16.0, *), let dimensions = self.configuredPhotoMaxDimensions() {
1578
+ settings.maxPhotoDimensions = dimensions
1579
+ }
1414
1580
  if #available(iOS 15.0, *) {
1415
1581
  if photoQualityPrioritization == "quality" {
1416
1582
  settings.photoQualityPrioritization = .quality
@@ -1442,27 +1608,25 @@ extension CameraController {
1442
1608
  }
1443
1609
  }
1444
1610
 
1445
- self.isCapturingPhoto = true
1611
+ if Thread.isMainThread {
1612
+ self.isCapturingPhoto = true
1613
+ } else {
1614
+ DispatchQueue.main.sync {
1615
+ self.isCapturingPhoto = true
1616
+ }
1617
+ }
1446
1618
 
1447
1619
  self.photoCaptureCompletionBlock = { [weak self] (image, photoData, metadata, error) in
1448
1620
  guard let self = self else { return }
1449
1621
  if let error = error {
1450
1622
  completion(nil, nil, nil, error)
1451
- // End capture lifecycle
1452
- self.isCapturingPhoto = false
1453
- if self.stopRequestedAfterCapture {
1454
- DispatchQueue.main.async { self.cleanup(); self.stopRequestedAfterCapture = false }
1455
- }
1623
+ self.finishPhotoCaptureLifecycle()
1456
1624
  return
1457
1625
  }
1458
1626
 
1459
1627
  guard let image = image else {
1460
1628
  completion(nil, nil, nil, NSError(domain: "Camera", code: 0, userInfo: [NSLocalizedDescriptionKey: "Failed to capture image"]))
1461
- // End capture lifecycle
1462
- self.isCapturingPhoto = false
1463
- if self.stopRequestedAfterCapture {
1464
- DispatchQueue.main.async { self.cleanup(); self.stopRequestedAfterCapture = false }
1465
- }
1629
+ self.finishPhotoCaptureLifecycle()
1466
1630
  return
1467
1631
  }
1468
1632
 
@@ -1477,7 +1641,12 @@ extension CameraController {
1477
1641
  // When max dimensions are specified, we used high-res capture
1478
1642
  // First crop to aspect ratio if needed, then resize to max dimensions
1479
1643
  if let aspectRatio = self.requestedAspectRatio {
1480
- finalImage = self.cropCapturedImage(image, aspectRatio: aspectRatio, visibleFillRatio: visibleFillRatio)
1644
+ finalImage = self.cropCapturedImage(
1645
+ image,
1646
+ aspectRatio: aspectRatio,
1647
+ visibleFillRatio: visibleFillRatio,
1648
+ captureOrientation: orientationUsedForCapture
1649
+ )
1481
1650
  print("[CameraPreview] Cropped high-res image to aspect ratio \(aspectRatio)")
1482
1651
  }
1483
1652
  // Then resize to fit within maximum dimensions while maintaining aspect ratio
@@ -1486,7 +1655,12 @@ extension CameraController {
1486
1655
  } else if let aspectRatio = self.requestedAspectRatio {
1487
1656
  // No max dimensions specified, but aspect ratio is specified
1488
1657
  // Always apply aspect ratio cropping to ensure correct orientation
1489
- finalImage = self.cropCapturedImage(image, aspectRatio: aspectRatio, visibleFillRatio: visibleFillRatio)
1658
+ finalImage = self.cropCapturedImage(
1659
+ image,
1660
+ aspectRatio: aspectRatio,
1661
+ visibleFillRatio: visibleFillRatio,
1662
+ captureOrientation: orientationUsedForCapture
1663
+ )
1490
1664
  print("[CameraPreview] Applied aspect ratio cropping for \(aspectRatio): \(finalImage.size.width)x\(finalImage.size.height)")
1491
1665
  }
1492
1666
 
@@ -1508,12 +1682,7 @@ extension CameraController {
1508
1682
  }
1509
1683
 
1510
1684
  completion(finalImage, photoData, metadata, nil)
1511
-
1512
- // End capture lifecycle
1513
- self.isCapturingPhoto = false
1514
- if self.stopRequestedAfterCapture {
1515
- DispatchQueue.main.async { self.cleanup(); self.stopRequestedAfterCapture = false }
1516
- }
1685
+ self.finishPhotoCaptureLifecycle()
1517
1686
  }
1518
1687
 
1519
1688
  photoOutput.capturePhoto(with: settings, delegate: self)
@@ -1805,7 +1974,7 @@ extension CameraController {
1805
1974
 
1806
1975
  /// Ratio of the visible preview area for `fill` + `cover`, in capture orientation.
1807
1976
  /// Returns `nil` for numeric ratios and for `contain`, where the full frame is visible.
1808
- func visibleFillCaptureAspectRatio() -> CGFloat? {
1977
+ func visibleFillCaptureAspectRatio(captureOrientation: AVCaptureVideoOrientation? = nil) -> CGFloat? {
1809
1978
  guard let aspectRatio = self.requestedAspectRatio,
1810
1979
  AspectRatioLayout.isFillMode(aspectRatio),
1811
1980
  self.requestedAspectMode == "cover",
@@ -1813,7 +1982,7 @@ extension CameraController {
1813
1982
  return nil
1814
1983
  }
1815
1984
 
1816
- let orientation = self.lastCaptureOrientation ?? self.getPhysicalOrientation()
1985
+ let orientation = captureOrientation ?? self.lastCaptureOrientation ?? self.getPhysicalOrientation()
1817
1986
  let captureIsPortrait = orientation == .portrait || orientation == .portraitUpsideDown
1818
1987
  let screenBounds = UIScreen.main.bounds
1819
1988
  return AspectRatioLayout.visibleFillCaptureAspectRatio(
@@ -1824,7 +1993,12 @@ extension CameraController {
1824
1993
  }
1825
1994
 
1826
1995
  /// Crops a captured photo so it matches what the preview shows.
1827
- func cropCapturedImage(_ image: UIImage, aspectRatio: String, visibleFillRatio: CGFloat?) -> UIImage {
1996
+ func cropCapturedImage(
1997
+ _ image: UIImage,
1998
+ aspectRatio: String,
1999
+ visibleFillRatio: CGFloat?,
2000
+ captureOrientation: AVCaptureVideoOrientation? = nil
2001
+ ) -> UIImage {
1828
2002
  if AspectRatioLayout.isFillMode(aspectRatio) {
1829
2003
  guard let ratio = visibleFillRatio else {
1830
2004
  // fill + contain shows the whole frame, so keep the full photo.
@@ -1832,7 +2006,11 @@ extension CameraController {
1832
2006
  }
1833
2007
  return cropImage(image, toAspectRatio: ratio) ?? image
1834
2008
  }
1835
- return cropImageToAspectRatio(image: image, aspectRatio: aspectRatio) ?? image
2009
+ return cropImageToAspectRatio(
2010
+ image: image,
2011
+ aspectRatio: aspectRatio,
2012
+ captureOrientation: captureOrientation
2013
+ ) ?? image
1836
2014
  }
1837
2015
 
1838
2016
  /// Center-crops `image` (after normalizing its orientation) to a width / height ratio.
@@ -1852,7 +2030,11 @@ extension CameraController {
1852
2030
  return UIImage(cgImage: croppedCGImage, scale: normalizedImage.scale, orientation: .up)
1853
2031
  }
1854
2032
 
1855
- func cropImageToAspectRatio(image: UIImage, aspectRatio: String) -> UIImage? {
2033
+ func cropImageToAspectRatio(
2034
+ image: UIImage,
2035
+ aspectRatio: String,
2036
+ captureOrientation: AVCaptureVideoOrientation? = nil
2037
+ ) -> UIImage? {
1856
2038
  let components = aspectRatio.split(separator: ":").compactMap {Float(String($0))}
1857
2039
  guard components.count == 2 else {
1858
2040
  print("[CameraPreview] cropImageToAspectRatio - Failed to parse aspect ratio: \(aspectRatio)")
@@ -1860,7 +2042,7 @@ extension CameraController {
1860
2042
  }
1861
2043
 
1862
2044
  // Use physical orientation for capture works with portrait lock
1863
- let orientation = self.lastCaptureOrientation ?? self.getPhysicalOrientation()
2045
+ let orientation = captureOrientation ?? self.lastCaptureOrientation ?? self.getPhysicalOrientation()
1864
2046
  let isPortrait = (orientation == .portrait || orientation == .portraitUpsideDown)
1865
2047
 
1866
2048
  let ratioWidth: CGFloat
@@ -2643,6 +2825,8 @@ extension CameraController {
2643
2825
  }
2644
2826
  }
2645
2827
 
2828
+ self.applyConfiguredCaptureResolutionToPhotoOutputIfNeeded()
2829
+
2646
2830
  // Update video orientation
2647
2831
  self.updateVideoOrientation()
2648
2832
  }
@@ -2659,6 +2843,16 @@ extension CameraController {
2659
2843
  self.applicationAudioSessionRestoreCoordinator.captureSnapshotIfNeeded()
2660
2844
  }
2661
2845
 
2846
+ private func applyAllowHapticsAndSystemSoundsDuringRecordingPolicy() {
2847
+ guard self.audioInput != nil else { return }
2848
+ do {
2849
+ try AVAudioSession.sharedInstance()
2850
+ .setAllowHapticsAndSystemSoundsDuringRecording(self.allowHapticsAndSystemSoundsDuringRecording)
2851
+ } catch {
2852
+ print("[CameraPreview] Failed to set allowHapticsAndSystemSoundsDuringRecording: \(error)")
2853
+ }
2854
+ }
2855
+
2662
2856
  private static let insufficientAudioPriorityOSStatus = 561017449
2663
2857
 
2664
2858
  private func isAudioPriorityError(_ error: NSError) -> Bool {
@@ -2721,6 +2915,7 @@ extension CameraController {
2721
2915
  if session.canAddInput(input) {
2722
2916
  session.addInput(input)
2723
2917
  self.audioInput = input
2918
+ self.applyAllowHapticsAndSystemSoundsDuringRecordingPolicy()
2724
2919
  }
2725
2920
  } catch {
2726
2921
  print("[CameraPreview] Failed to restore audio input after interruption: \(error)")
@@ -2808,6 +3003,8 @@ extension CameraController {
2808
3003
  func cleanup() {
2809
3004
  self.invalidateActivePrepare()
2810
3005
  self.cancelPendingFocusExposureRestore()
3006
+ self.configuredCaptureResolutionWidth = nil
3007
+ self.configuredCaptureResolutionHeight = nil
2811
3008
  configuredVideoFrameRate = nil
2812
3009
  stopBarcodeScanner()
2813
3010
  self.unregisterCaptureSessionObservers()
@@ -3296,12 +3493,13 @@ extension CameraController {
3296
3493
  // This reclaims the microphone even if other parts of the app changed the
3297
3494
  // AVAudioSession category (e.g. for UI sound effects) between recordings.
3298
3495
  if self.audioInput != nil {
3496
+ self.allowHapticsAndSystemSoundsDuringRecording = allowHapticsAndSystemSoundsDuringRecording
3299
3497
  self.captureApplicationAudioSessionSnapshotIfNeeded()
3300
3498
  do {
3301
3499
  let audioSession = AVAudioSession.sharedInstance()
3302
3500
  try audioSession.setCategory(.playAndRecord, mode: .videoRecording, options: [.defaultToSpeaker])
3303
3501
  try audioSession.setActive(true)
3304
- try audioSession.setAllowHapticsAndSystemSoundsDuringRecording(allowHapticsAndSystemSoundsDuringRecording)
3502
+ self.applyAllowHapticsAndSystemSoundsDuringRecordingPolicy()
3305
3503
  } catch {
3306
3504
  print("[CameraPreview] Failed to configure AVAudioSession for video recording: \(error)")
3307
3505
  }
@@ -3538,34 +3736,25 @@ extension CameraController: UIGestureRecognizerDelegate {
3538
3736
 
3539
3737
  extension CameraController: AVCapturePhotoCaptureDelegate {
3540
3738
  public func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
3541
- if let error = error {
3542
- self.photoCaptureCompletionBlock?(nil, nil, nil, error)
3543
- return
3544
- }
3739
+ CapturePhotoProcessingQueue.async {
3740
+ if let error = error {
3741
+ self.photoCaptureCompletionBlock?(nil, nil, nil, error)
3742
+ return
3743
+ }
3545
3744
 
3546
- // Process photo in background to avoid blocking main thread
3547
- DispatchQueue.global(qos: .userInitiated).async {
3548
- // Get the photo data using the modern API
3549
3745
  guard let imageData = photo.fileDataRepresentation() else {
3550
- DispatchQueue.main.async {
3551
- self.photoCaptureCompletionBlock?(nil, nil, nil, CameraControllerError.unknown)
3552
- }
3746
+ self.photoCaptureCompletionBlock?(nil, nil, nil, CameraControllerError.unknown)
3553
3747
  return
3554
3748
  }
3555
3749
 
3556
- // Create image from data
3557
3750
  guard let image = UIImage(data: imageData) else {
3558
- DispatchQueue.main.async {
3559
- self.photoCaptureCompletionBlock?(nil, nil, nil, CameraControllerError.unknown)
3560
- }
3751
+ self.photoCaptureCompletionBlock?(nil, nil, nil, CameraControllerError.unknown)
3561
3752
  return
3562
3753
  }
3563
3754
 
3564
- // Pass through original file data and metadata so callers can preserve EXIF
3565
- // Don't call fixedOrientation() here - let the completion block handle it after cropping
3566
- DispatchQueue.main.async {
3567
- self.photoCaptureCompletionBlock?(image, imageData, photo.metadata, nil)
3568
- }
3755
+ // Pass through original file data and metadata so callers can preserve EXIF.
3756
+ // Don't call fixedOrientation() here; the completion block handles cropping.
3757
+ self.photoCaptureCompletionBlock?(image, imageData, photo.metadata, nil)
3569
3758
  }
3570
3759
  }
3571
3760
  }
@@ -0,0 +1,88 @@
1
+ import CoreLocation
2
+ import ImageIO
3
+ import MobileCoreServices
4
+ import UIKit
5
+
6
+ enum CaptureImageExifEncoder {
7
+ typealias JpegEncoder = (UIImage, Int) -> Data?
8
+
9
+ static func createImageData(
10
+ from image: UIImage,
11
+ quality: Int,
12
+ location: CLLocation?,
13
+ heading: CLHeading?,
14
+ originalPhotoData: Data?,
15
+ jpegEncoder: JpegEncoder = defaultJpegEncoder
16
+ ) -> Data? {
17
+ guard let cgImage = image.cgImage else {
18
+ return jpegEncoder(image, quality)
19
+ }
20
+
21
+ let sourceDataForMetadata: CFData
22
+ if let originalPhotoData {
23
+ sourceDataForMetadata = originalPhotoData as CFData
24
+ } else if let encoded = jpegEncoder(image, quality) {
25
+ sourceDataForMetadata = encoded as CFData
26
+ } else {
27
+ return nil
28
+ }
29
+
30
+ guard let imageSource = CGImageSourceCreateWithData(sourceDataForMetadata, nil),
31
+ let imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) as? [String: Any] else {
32
+ return jpegEncoder(image, quality)
33
+ }
34
+
35
+ var finalProperties = imageProperties
36
+
37
+ // Ensure orientation reflects the pixel data (we pass an orientation-fixed UIImage)
38
+ finalProperties[kCGImagePropertyOrientation as String] = 1
39
+
40
+ if let location {
41
+ let formatter = DateFormatter()
42
+ formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
43
+ formatter.timeZone = TimeZone(abbreviation: "UTC")
44
+
45
+ var gpsDict: [String: Any] = [
46
+ kCGImagePropertyGPSLatitude as String: abs(location.coordinate.latitude),
47
+ kCGImagePropertyGPSLatitudeRef as String: location.coordinate.latitude >= 0 ? "N" : "S",
48
+ kCGImagePropertyGPSLongitude as String: abs(location.coordinate.longitude),
49
+ kCGImagePropertyGPSLongitudeRef as String: location.coordinate.longitude >= 0 ? "E" : "W",
50
+ kCGImagePropertyGPSTimeStamp as String: formatter.string(from: location.timestamp),
51
+ kCGImagePropertyGPSAltitude as String: location.altitude,
52
+ kCGImagePropertyGPSAltitudeRef as String: location.altitude >= 0 ? 0 : 1
53
+ ]
54
+
55
+ if let heading {
56
+ let directionDegrees: Double
57
+ let directionRef: String
58
+ if heading.trueHeading >= 0 {
59
+ directionDegrees = heading.trueHeading
60
+ directionRef = "T"
61
+ } else {
62
+ directionDegrees = heading.magneticHeading
63
+ directionRef = "M"
64
+ }
65
+ gpsDict[kCGImagePropertyGPSImgDirection as String] = directionDegrees
66
+ gpsDict[kCGImagePropertyGPSImgDirectionRef as String] = directionRef
67
+ }
68
+
69
+ finalProperties[kCGImagePropertyGPSDictionary as String] = gpsDict
70
+ }
71
+
72
+ var tiffDict = finalProperties[kCGImagePropertyTIFFDictionary as String] as? [String: Any] ?? [:]
73
+ tiffDict[kCGImagePropertyTIFFMake as String] = "Apple"
74
+ tiffDict[kCGImagePropertyTIFFModel as String] = UIDevice.current.model
75
+ tiffDict[kCGImagePropertyTIFFOrientation as String] = 1
76
+ finalProperties[kCGImagePropertyTIFFDictionary as String] = tiffDict
77
+
78
+ if let encoded = ImageIOJpegEncoding.encode(cgImage: cgImage, properties: finalProperties, qualityPercent: quality) {
79
+ return encoded
80
+ }
81
+
82
+ return jpegEncoder(image, quality)
83
+ }
84
+
85
+ private static func defaultJpegEncoder(image: UIImage, quality: Int) -> Data? {
86
+ image.jpegData(compressionQuality: CGFloat(Double(quality) / 100.0))
87
+ }
88
+ }