@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
@@ -0,0 +1,37 @@
1
+ import Foundation
2
+
3
+ /// Flags coordinating `stop()` with an in-flight still capture. Mutate only on the main thread.
4
+ struct CaptureLifecycleState {
5
+ var isCapturingPhoto: Bool = false
6
+ var stopRequestedAfterCapture: Bool = false
7
+ }
8
+
9
+ enum CaptureLifecycleCoordination {
10
+ /// Handles `stop()` when a capture may be in flight. Call on the main thread only.
11
+ static func handleStop(
12
+ state: inout CaptureLifecycleState,
13
+ force: Bool,
14
+ cleanup: () -> Void
15
+ ) {
16
+ if state.isCapturingPhoto && !force {
17
+ state.stopRequestedAfterCapture = true
18
+ return
19
+ }
20
+ if force {
21
+ state.stopRequestedAfterCapture = false
22
+ }
23
+ cleanup()
24
+ }
25
+
26
+ /// Ends the capture lifecycle after processing completes. Call on the main thread only.
27
+ static func finishCapture(
28
+ state: inout CaptureLifecycleState,
29
+ cleanup: () -> Void
30
+ ) {
31
+ state.isCapturingPhoto = false
32
+ if state.stopRequestedAfterCapture {
33
+ cleanup()
34
+ state.stopRequestedAfterCapture = false
35
+ }
36
+ }
37
+ }
@@ -0,0 +1,23 @@
1
+ import AVFoundation
2
+ import Foundation
3
+
4
+ /// Selects whether still capture follows on-screen preview orientation or physical device tilt.
5
+ enum CaptureOrientationResolver {
6
+ static let orientationPreview = "preview"
7
+ static let orientationDevice = "device"
8
+
9
+ static func usesDeviceOrientation(mode: String?) -> Bool {
10
+ mode != orientationPreview
11
+ }
12
+
13
+ static func resolveOrientation(
14
+ mode: String?,
15
+ previewOrientation: AVCaptureVideoOrientation,
16
+ deviceOrientation: AVCaptureVideoOrientation
17
+ ) -> AVCaptureVideoOrientation {
18
+ if mode == orientationPreview {
19
+ return previewOrientation
20
+ }
21
+ return deviceOrientation
22
+ }
23
+ }
@@ -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
+ }
@@ -0,0 +1,133 @@
1
+ import AVFoundation
2
+ import Foundation
3
+
4
+ struct CaptureResolutionParseResult {
5
+ let width: Int?
6
+ let height: Int?
7
+ let errorMessage: String?
8
+
9
+ var isError: Bool { errorMessage != nil }
10
+
11
+ static func success(width: Int?, height: Int?) -> CaptureResolutionParseResult {
12
+ CaptureResolutionParseResult(width: width, height: height, errorMessage: nil)
13
+ }
14
+
15
+ static func error(_ message: String) -> CaptureResolutionParseResult {
16
+ CaptureResolutionParseResult(width: nil, height: nil, errorMessage: message)
17
+ }
18
+ }
19
+
20
+ enum CaptureResolutionSupport {
21
+ static func parseStartCaptureResolution(_ captureResolutionObject: Any?) -> CaptureResolutionParseResult {
22
+ guard let captureResolutionObject else {
23
+ return .success(width: nil, height: nil)
24
+ }
25
+
26
+ guard let captureResolution = captureResolutionObject as? [String: Any] else {
27
+ return .error("captureResolution must be an object with width and height")
28
+ }
29
+
30
+ guard captureResolution["width"] != nil, captureResolution["height"] != nil else {
31
+ return .error("captureResolution requires both width and height")
32
+ }
33
+
34
+ guard let captureWidth = parsePositivePixelDimension(captureResolution["width"]),
35
+ let captureHeight = parsePositivePixelDimension(captureResolution["height"]) else {
36
+ return .error("captureResolution width and height must be positive")
37
+ }
38
+
39
+ return .success(width: captureWidth, height: captureHeight)
40
+ }
41
+
42
+ static func parsePositivePixelDimension(_ value: Any?) -> Int? {
43
+ guard let value else { return nil }
44
+
45
+ if let number = value as? NSNumber {
46
+ return parsePositivePixelDimensionFromDouble(number.doubleValue)
47
+ }
48
+ if let string = value as? String {
49
+ let trimmed = string.trimmingCharacters(in: .whitespacesAndNewlines)
50
+ if trimmed.isEmpty { return nil }
51
+ guard let numeric = Double(trimmed) else { return nil }
52
+ return parsePositivePixelDimensionFromDouble(numeric)
53
+ }
54
+ return nil
55
+ }
56
+
57
+ private static func parsePositivePixelDimensionFromDouble(_ numeric: Double) -> Int? {
58
+ guard !numeric.isNaN, !numeric.isInfinite, numeric > 0 else { return nil }
59
+ guard numeric == floor(numeric), numeric <= Double(Int.max) else { return nil }
60
+ guard numeric <= Double(Int32.max) else { return nil }
61
+ return Int(numeric)
62
+ }
63
+
64
+ /// Matches Android `normalizedCaptureTargetResolution`: landscape-major width and height.
65
+ static func normalizedCaptureTargetResolution(configuredWidth: Int, configuredHeight: Int) -> (width: Int, height: Int) {
66
+ (max(configuredWidth, configuredHeight), min(configuredWidth, configuredHeight))
67
+ }
68
+
69
+ static func longEdge(_ dimensions: CMVideoDimensions) -> Int32 {
70
+ max(dimensions.width, dimensions.height)
71
+ }
72
+
73
+ static func shortEdge(_ dimensions: CMVideoDimensions) -> Int32 {
74
+ min(dimensions.width, dimensions.height)
75
+ }
76
+
77
+ static func pixelArea(_ dimensions: CMVideoDimensions) -> Int64 {
78
+ Int64(dimensions.width) * Int64(dimensions.height)
79
+ }
80
+
81
+ /// Picks a supported `maxPhotoDimensions` value at or below the configured cap.
82
+ static func photoMaxDimensions(
83
+ configuredWidth: Int,
84
+ configuredHeight: Int,
85
+ supportedDimensions: [CMVideoDimensions],
86
+ deviceMax: CMVideoDimensions
87
+ ) -> CMVideoDimensions {
88
+ let normalized = normalizedCaptureTargetResolution(configuredWidth: configuredWidth, configuredHeight: configuredHeight)
89
+ let targetLong = Int32(normalized.width)
90
+ let targetShort = Int32(normalized.height)
91
+
92
+ let fittingSupported = supportedDimensions.filter { dimension in
93
+ longEdge(dimension) <= targetLong && shortEdge(dimension) <= targetShort
94
+ }
95
+
96
+ if let bestFit = fittingSupported.max(by: { pixelArea($0) < pixelArea($1) }) {
97
+ return bestFit
98
+ }
99
+
100
+ return clampPhotoDimensions(
101
+ width: targetLong,
102
+ height: targetShort,
103
+ deviceMax: deviceMax
104
+ )
105
+ }
106
+
107
+ static func clampPhotoDimensions(width: Int32, height: Int32, deviceMax: CMVideoDimensions) -> CMVideoDimensions {
108
+ var clampedWidth = width
109
+ var clampedHeight = height
110
+ let deviceWidth = deviceMax.width
111
+ let deviceHeight = deviceMax.height
112
+ if clampedWidth > deviceWidth || clampedHeight > deviceHeight {
113
+ let scale = min(Double(deviceWidth) / Double(clampedWidth), Double(deviceHeight) / Double(clampedHeight))
114
+ clampedWidth = max(1, Int32((Double(clampedWidth) * scale).rounded(.down)))
115
+ clampedHeight = max(1, Int32((Double(clampedHeight) * scale).rounded(.down)))
116
+ }
117
+ return CMVideoDimensions(width: clampedWidth, height: clampedHeight)
118
+ }
119
+
120
+ static func shouldEnableHighResolutionPhoto(
121
+ captureResolutionWidth: Int?,
122
+ captureResolutionHeight: Int?,
123
+ captureMaxWidth: Int?,
124
+ captureMaxHeight: Int?
125
+ ) -> Bool {
126
+ if captureResolutionWidth != nil, captureResolutionHeight != nil {
127
+ return false
128
+ }
129
+ let widthExceedsDefault = captureMaxWidth.map { $0 > 1920 } ?? false
130
+ let heightExceedsDefault = captureMaxHeight.map { $0 > 1920 } ?? false
131
+ return widthExceedsDefault || heightExceedsDefault
132
+ }
133
+ }
@@ -0,0 +1,28 @@
1
+ import Foundation
2
+ import ImageIO
3
+ import MobileCoreServices
4
+
5
+ enum ImageIOJpegEncoding {
6
+ static func compressionQuality(forPercent qualityPercent: Int) -> CGFloat {
7
+ CGFloat(Double(qualityPercent) / 100.0)
8
+ }
9
+
10
+ static func applyingCompressionQuality(_ qualityPercent: Int, to properties: [String: Any]) -> [String: Any] {
11
+ var result = properties
12
+ result[kCGImageDestinationLossyCompressionQuality as String] = compressionQuality(forPercent: qualityPercent)
13
+ return result
14
+ }
15
+
16
+ static func encode(cgImage: CGImage, properties: [String: Any], qualityPercent: Int) -> Data? {
17
+ let finalProperties = applyingCompressionQuality(qualityPercent, to: properties)
18
+ let mutableData = NSMutableData()
19
+ guard let destination = CGImageDestinationCreateWithData(mutableData, kUTTypeJPEG, 1, nil) else {
20
+ return nil
21
+ }
22
+ CGImageDestinationAddImage(destination, cgImage, finalProperties as CFDictionary)
23
+ guard CGImageDestinationFinalize(destination) else {
24
+ return nil
25
+ }
26
+ return mutableData as Data
27
+ }
28
+ }
@@ -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.12.4"
38
+ private let pluginVersion: String = "8.13.0"
39
39
  public let identifier = "CameraPreviewPlugin"
40
40
  public let jsName = "CameraPreview"
41
41
  public let pluginMethods: [CAPPluginMethod] = [
@@ -491,12 +491,16 @@ public class CameraPreview: CAPPlugin, CAPBridgedPlugin, CLLocationManagerDelega
491
491
 
492
492
  self.updateCameraFrame()
493
493
 
494
- // Return the actual preview bounds
494
+ return self.visiblePreviewSizeJSObject()
495
+ }
496
+
497
+ private func visiblePreviewSizeJSObject() -> JSObject {
498
+ let rect = self.cameraController.visiblePreviewRect(in: self.previewView)
495
499
  var result = JSObject()
496
- result["x"] = Double(self.previewView.frame.origin.x)
497
- result["y"] = Double(self.previewView.frame.origin.y)
498
- result["width"] = Double(self.previewView.frame.width)
499
- result["height"] = Double(self.previewView.frame.height)
500
+ result["x"] = Double(rect.origin.x)
501
+ result["y"] = Double(rect.origin.y)
502
+ result["width"] = Double(rect.width)
503
+ result["height"] = Double(rect.height)
500
504
  return result
501
505
  }
502
506
 
@@ -663,6 +667,7 @@ public class CameraPreview: CAPPlugin, CAPBridgedPlugin, CLLocationManagerDelega
663
667
  print(" - force: \(call.getBool("force") ?? false)")
664
668
  print(" - videoQuality: \(call.getString("videoQuality") ?? "high")")
665
669
  print(" - videoStabilizationMode: \(call.getString("videoStabilizationMode") ?? "off")")
670
+ print(" - allowHapticsAndSystemSoundsDuringRecording: \(call.getBool("allowHapticsAndSystemSoundsDuringRecording") ?? false)")
666
671
 
667
672
  let force = call.getBool("force") ?? false
668
673
 
@@ -671,7 +676,10 @@ public class CameraPreview: CAPPlugin, CAPBridgedPlugin, CLLocationManagerDelega
671
676
  if let pendingStartCall = self.pendingStartCall, !self.hasResolvedStartCall {
672
677
  self.failPendingStart(pendingStartCall, message: "Camera start cancelled")
673
678
  }
674
- if self.isInitializing || self.isInitialized || self.cameraController.isCapturingPhoto || self.cameraController.stopRequestedAfterCapture {
679
+ let captureLifecycleBusy = DispatchQueue.main.sync {
680
+ self.cameraController.isCapturingPhoto || self.cameraController.stopRequestedAfterCapture
681
+ }
682
+ if self.isInitializing || self.isInitialized || captureLifecycleBusy {
675
683
  self.startGeneration += 1
676
684
  self.cancelFirstFrameTimeout()
677
685
  // Force stop everything synchronously
@@ -712,18 +720,46 @@ public class CameraPreview: CAPPlugin, CAPBridgedPlugin, CLLocationManagerDelega
712
720
  return
713
721
  }
714
722
  // Guard against starting while a deferred stop is pending due to in-flight capture
715
- if self.cameraController.isCapturingPhoto || self.cameraController.stopRequestedAfterCapture {
723
+ let captureLifecycleBusy = DispatchQueue.main.sync {
724
+ self.cameraController.isCapturingPhoto || self.cameraController.stopRequestedAfterCapture
725
+ }
726
+ if captureLifecycleBusy {
716
727
  call.reject("camera is stopping or busy, please retry shortly")
717
728
  return
718
729
  }
719
730
  }
720
731
 
732
+ let hasAspectRatio = call.getString("aspectRatio") != nil
733
+ let hasWidth = call.getInt("width") != nil
734
+ let hasHeight = call.getInt("height") != nil
735
+ if hasAspectRatio && (hasWidth || hasHeight) {
736
+ call.reject("Cannot set both aspectRatio and size (width/height). Use setPreviewSize after start.")
737
+ return
738
+ }
739
+
740
+ let captureResolutionParseResult = CaptureResolutionSupport.parseStartCaptureResolution(call.getObject("captureResolution"))
741
+ if captureResolutionParseResult.isError {
742
+ call.reject(captureResolutionParseResult.errorMessage ?? "Invalid captureResolution")
743
+ return
744
+ }
745
+ if captureResolutionParseResult.width != nil, captureResolutionParseResult.height != nil {
746
+ if #unavailable(iOS 16.0) {
747
+ call.reject("captureResolution requires iOS 16 or later")
748
+ return
749
+ }
750
+ }
751
+
721
752
  self.isInitializing = true
722
753
  self.hasResolvedStartCall = false
723
754
  self.pendingStartCall = call
724
755
  self.startGeneration += 1
725
756
  let startToken = self.startGeneration
726
757
 
758
+ self.cameraController.setConfiguredCaptureResolution(
759
+ width: captureResolutionParseResult.width,
760
+ height: captureResolutionParseResult.height
761
+ )
762
+
727
763
  self.cameraPosition = call.getString("position") ?? "rear"
728
764
  let deviceId = call.getString("deviceId")
729
765
  let cameraMode = call.getBool("enableVideoMode") ?? call.getBool("cameraMode") ?? false
@@ -781,17 +817,8 @@ public class CameraPreview: CAPPlugin, CAPBridgedPlugin, CLLocationManagerDelega
781
817
  self.pendingStartBarcodeScannerOptions = self.barcodeScannerStartOptions(from: call)
782
818
 
783
819
  let initialZoomLevel = call.getFloat("initialZoomLevel")
820
+ let allowHapticsAndSystemSoundsDuringRecording = call.getBool("allowHapticsAndSystemSoundsDuringRecording") ?? false
784
821
 
785
- // Check for conflict between aspectRatio and size (width/height)
786
- let hasAspectRatio = call.getString("aspectRatio") != nil
787
- let hasWidth = call.getInt("width") != nil
788
- let hasHeight = call.getInt("height") != nil
789
-
790
- if hasAspectRatio && (hasWidth || hasHeight) {
791
- self.pendingStartBarcodeScannerOptions = nil
792
- call.reject("Cannot set both aspectRatio and size (width/height). Use setPreviewSize after start.")
793
- return
794
- }
795
822
  let beginStart: () -> Void = {
796
823
  if (self.cameraController.captureSession?.isRunning ?? false) && !force {
797
824
  DispatchQueue.main.async {
@@ -830,7 +857,7 @@ public class CameraPreview: CAPPlugin, CAPBridgedPlugin, CLLocationManagerDelega
830
857
  }
831
858
  }
832
859
 
833
- self.cameraController.prepare(cameraPosition: self.cameraPosition, deviceId: deviceId, disableAudio: self.disableAudio, cameraMode: cameraMode, aspectRatio: self.aspectRatio, aspectMode: self.aspectMode, initialZoomLevel: initialZoomLevel, disableFocusIndicator: self.disableFocusIndicator, videoQuality: videoQuality, startToken: startToken) { error in
860
+ self.cameraController.prepare(cameraPosition: self.cameraPosition, deviceId: deviceId, disableAudio: self.disableAudio, cameraMode: cameraMode, aspectRatio: self.aspectRatio, aspectMode: self.aspectMode, initialZoomLevel: initialZoomLevel, disableFocusIndicator: self.disableFocusIndicator, videoQuality: videoQuality, allowHapticsAndSystemSoundsDuringRecording: allowHapticsAndSystemSoundsDuringRecording, startToken: startToken) { error in
834
861
  if let error = error {
835
862
  print(error)
836
863
  DispatchQueue.main.async {
@@ -994,12 +1021,7 @@ public class CameraPreview: CAPPlugin, CAPBridgedPlugin, CLLocationManagerDelega
994
1021
 
995
1022
  DispatchQueue.main.async {
996
1023
  guard startToken == self.startGeneration else { return }
997
- var returnedObject = JSObject()
998
- returnedObject["width"] = self.previewView.frame.width as any JSValue
999
- returnedObject["height"] = self.previewView.frame.height as any JSValue
1000
- returnedObject["x"] = self.previewView.frame.origin.x as any JSValue
1001
- returnedObject["y"] = self.previewView.frame.origin.y as any JSValue
1002
- self.resolveStartCall(call, returnedObject: returnedObject)
1024
+ self.resolveStartCall(call, returnedObject: self.visiblePreviewSizeJSObject())
1003
1025
  }
1004
1026
  }
1005
1027
 
@@ -1009,12 +1031,7 @@ public class CameraPreview: CAPPlugin, CAPBridgedPlugin, CLLocationManagerDelega
1009
1031
  if self.cameraController.hasReceivedFirstFrame {
1010
1032
  DispatchQueue.main.async {
1011
1033
  guard startToken == self.startGeneration else { return }
1012
- var returnedObject = JSObject()
1013
- returnedObject["width"] = self.previewView.frame.width as any JSValue
1014
- returnedObject["height"] = self.previewView.frame.height as any JSValue
1015
- returnedObject["x"] = self.previewView.frame.origin.x as any JSValue
1016
- returnedObject["y"] = self.previewView.frame.origin.y as any JSValue
1017
- self.resolveStartCall(call, returnedObject: returnedObject)
1034
+ self.resolveStartCall(call, returnedObject: self.visiblePreviewSizeJSObject())
1018
1035
  }
1019
1036
  }
1020
1037
  }
@@ -1160,16 +1177,11 @@ public class CameraPreview: CAPPlugin, CAPBridgedPlugin, CLLocationManagerDelega
1160
1177
  self.isGeneratingDeviceOrientationNotifications = false
1161
1178
  }
1162
1179
 
1163
- if self.cameraController.isCapturingPhoto && !force {
1164
- // Defer heavy cleanup until capture callback completes (only if not forcing)
1165
- self.cameraController.stopRequestedAfterCapture = true
1166
- } else {
1167
- // Force stop or no capture pending; cleanup now
1168
- if force {
1169
- self.cameraController.stopRequestedAfterCapture = false
1170
- }
1171
- self.cameraController.cleanup()
1172
- }
1180
+ CaptureLifecycleCoordination.handleStop(
1181
+ state: &self.cameraController.captureLifecycle,
1182
+ force: force,
1183
+ cleanup: { self.cameraController.cleanup() }
1184
+ )
1173
1185
 
1174
1186
  call.resolve()
1175
1187
  }
@@ -1356,10 +1368,11 @@ public class CameraPreview: CAPPlugin, CAPBridgedPlugin, CLLocationManagerDelega
1356
1368
  let height = call.getInt("height")
1357
1369
  let photoQualityPrioritization = call.getString("photoQualityPrioritization", "speed")
1358
1370
  let mirrorFrontCamera = call.getBool("mirrorFrontCamera", false) ?? false
1371
+ let captureOrientation = call.getString("orientation", CaptureOrientationResolver.orientationDevice)
1359
1372
 
1360
1373
  print("[CameraPreview] Raw parameter values - width: \(String(describing: width)), height: \(String(describing: height))")
1361
1374
 
1362
- print("[CameraPreview] Capture params - quality: \(quality), saveToGallery: \(saveToGallery), withExifLocation: \(withExifLocation ?? false), embedTimestamp: \(embedTimestamp), embedLocation: \(effectiveEmbedLocation) (requested=\(embedLocationRequested)), width: \(width ?? -1), height: \(height ?? -1), mirrorFrontCamera: \(mirrorFrontCamera)")
1375
+ print("[CameraPreview] Capture params - quality: \(quality), saveToGallery: \(saveToGallery), withExifLocation: \(withExifLocation ?? false), embedTimestamp: \(embedTimestamp), embedLocation: \(effectiveEmbedLocation) (requested=\(embedLocationRequested)), width: \(width ?? -1), height: \(height ?? -1), mirrorFrontCamera: \(mirrorFrontCamera), orientation: \(captureOrientation ?? CaptureOrientationResolver.orientationDevice)")
1363
1376
  print("[CameraPreview] Current location: \(self.currentLocation?.description ?? "nil")")
1364
1377
  // Safely read frame from main thread for logging
1365
1378
  let (previewWidth, previewHeight): (CGFloat, CGFloat) = {
@@ -1378,15 +1391,19 @@ public class CameraPreview: CAPPlugin, CAPBridgedPlugin, CLLocationManagerDelega
1378
1391
 
1379
1392
  let capturedFromFrontCamera = self.cameraController.currentCameraPosition == .front
1380
1393
  let gpsForThisCapture = (withExifLocation ?? false) ? self.currentLocation : nil
1381
- self.cameraController.captureImage(width: width, height: height, quality: quality, gpsLocation: gpsForThisCapture, embedTimestamp: embedTimestamp, embedLocation: effectiveEmbedLocation, photoQualityPrioritization: photoQualityPrioritization) { (image, originalPhotoData, _, error) in
1394
+ let locationForExif = (withExifLocation ?? false) ? self.currentLocation : nil
1395
+ let headingForExif = (withExifLocation ?? false) ? self.currentHeading : nil
1396
+ let storeToFile = self.storeToFile
1397
+ self.cameraController.captureImage(width: width, height: height, quality: quality, gpsLocation: gpsForThisCapture, embedTimestamp: embedTimestamp, embedLocation: effectiveEmbedLocation, photoQualityPrioritization: photoQualityPrioritization, captureOrientationMode: captureOrientation) { (image, originalPhotoData, _, error) in
1382
1398
  print("[CameraPreview] captureImage callback received")
1383
- DispatchQueue.main.async {
1384
- print("[CameraPreview] Processing capture on main thread")
1385
- // Ensure heading updates are stopped on all exit paths (error, guard failure, or success)
1399
+ CapturePhotoProcessingQueue.async {
1400
+ print("[CameraPreview] Processing capture on background queue (isMain=\(Thread.isMainThread))")
1386
1401
  defer {
1387
1402
  if withExifLocation ?? false {
1388
- self.locationManager?.stopUpdatingHeading()
1389
- self.currentHeading = nil
1403
+ DispatchQueue.main.async {
1404
+ self.locationManager?.stopUpdatingHeading()
1405
+ self.currentHeading = nil
1406
+ }
1390
1407
  }
1391
1408
  }
1392
1409
  if let error = error {
@@ -1408,11 +1425,11 @@ public class CameraPreview: CAPPlugin, CAPBridgedPlugin, CLLocationManagerDelega
1408
1425
  imageToEncode = capturedImage
1409
1426
  }
1410
1427
 
1411
- guard let imageDataWithExif = self.createImageDataWithExif(
1428
+ guard let imageDataWithExif = CaptureImageExifEncoder.createImageData(
1412
1429
  from: imageToEncode,
1413
1430
  quality: Int(quality),
1414
- location: withExifLocation ? self.currentLocation : nil,
1415
- heading: withExifLocation ? self.currentHeading : nil,
1431
+ location: locationForExif,
1432
+ heading: headingForExif,
1416
1433
  originalPhotoData: originalPhotoData
1417
1434
  )
1418
1435
  else {
@@ -1423,13 +1440,12 @@ public class CameraPreview: CAPPlugin, CAPBridgedPlugin, CLLocationManagerDelega
1423
1440
 
1424
1441
  print("[CameraPreview] Image data created, size: \(imageDataWithExif.count) bytes")
1425
1442
 
1426
- // Prepare the result first
1427
1443
  let exifData = self.getExifData(from: imageDataWithExif)
1428
1444
 
1429
1445
  var result = JSObject()
1430
1446
  result["exif"] = exifData
1431
1447
 
1432
- if self.storeToFile == false {
1448
+ if storeToFile == false {
1433
1449
  let base64Image = imageDataWithExif.base64EncodedString()
1434
1450
  result["value"] = base64Image
1435
1451
  } else {
@@ -1443,7 +1459,6 @@ public class CameraPreview: CAPPlugin, CAPBridgedPlugin, CLLocationManagerDelega
1443
1459
  }
1444
1460
  }
1445
1461
 
1446
- // Save to gallery asynchronously if requested
1447
1462
  if saveToGallery {
1448
1463
  print("[CameraPreview] Saving to gallery asynchronously...")
1449
1464
  DispatchQueue.global(qos: .utility).async {
@@ -1453,7 +1468,7 @@ public class CameraPreview: CAPPlugin, CAPBridgedPlugin, CLLocationManagerDelega
1453
1468
  }
1454
1469
  }
1455
1470
 
1456
- print("[CameraPreview] Resolving capture call immediately")
1471
+ print("[CameraPreview] Resolving capture call from background queue")
1457
1472
  call.resolve(result)
1458
1473
  }
1459
1474
  }
@@ -1549,79 +1564,6 @@ public class CameraPreview: CAPPlugin, CAPBridgedPlugin, CLLocationManagerDelega
1549
1564
  }
1550
1565
  }
1551
1566
 
1552
- private func createImageDataWithExif(from image: UIImage, quality: Int, location: CLLocation?, heading: CLHeading?, originalPhotoData: Data?) -> Data? {
1553
- guard let jpegDataAtQuality = image.jpegData(compressionQuality: CGFloat(Double(quality) / 100.0)) else {
1554
- return nil
1555
- }
1556
-
1557
- // Prefer metadata from the original AVCapturePhoto file data to preserve lens/EXIF
1558
- let sourceDataForMetadata = (originalPhotoData ?? jpegDataAtQuality) as CFData
1559
- guard let imageSource = CGImageSourceCreateWithData(sourceDataForMetadata, nil),
1560
- let imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) as? [String: Any],
1561
- let cgImage = image.cgImage else {
1562
- return jpegDataAtQuality
1563
- }
1564
-
1565
- let mutableData = NSMutableData()
1566
- guard let destination = CGImageDestinationCreateWithData(mutableData, kUTTypeJPEG, 1, nil) else {
1567
- return jpegDataAtQuality
1568
- }
1569
-
1570
- var finalProperties = imageProperties
1571
-
1572
- // Ensure orientation reflects the pixel data (we pass an orientation-fixed UIImage)
1573
- finalProperties[kCGImagePropertyOrientation as String] = 1
1574
-
1575
- // Add GPS location if available
1576
- if let location = location {
1577
- let formatter = DateFormatter()
1578
- formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
1579
- formatter.timeZone = TimeZone(abbreviation: "UTC")
1580
-
1581
- var gpsDict: [String: Any] = [
1582
- kCGImagePropertyGPSLatitude as String: abs(location.coordinate.latitude),
1583
- kCGImagePropertyGPSLatitudeRef as String: location.coordinate.latitude >= 0 ? "N" : "S",
1584
- kCGImagePropertyGPSLongitude as String: abs(location.coordinate.longitude),
1585
- kCGImagePropertyGPSLongitudeRef as String: location.coordinate.longitude >= 0 ? "E" : "W",
1586
- kCGImagePropertyGPSTimeStamp as String: formatter.string(from: location.timestamp),
1587
- kCGImagePropertyGPSAltitude as String: location.altitude,
1588
- kCGImagePropertyGPSAltitudeRef as String: location.altitude >= 0 ? 0 : 1
1589
- ]
1590
-
1591
- // Add image direction (compass heading) when available
1592
- if let heading = heading {
1593
- let directionDegrees: Double
1594
- let directionRef: String
1595
- if heading.trueHeading >= 0 {
1596
- directionDegrees = heading.trueHeading
1597
- directionRef = "T"
1598
- } else {
1599
- directionDegrees = heading.magneticHeading
1600
- directionRef = "M"
1601
- }
1602
- gpsDict[kCGImagePropertyGPSImgDirection as String] = directionDegrees
1603
- gpsDict[kCGImagePropertyGPSImgDirectionRef as String] = directionRef
1604
- }
1605
-
1606
- finalProperties[kCGImagePropertyGPSDictionary as String] = gpsDict
1607
- }
1608
-
1609
- // Create or update TIFF dictionary for device info and set orientation to Up
1610
- var tiffDict = finalProperties[kCGImagePropertyTIFFDictionary as String] as? [String: Any] ?? [:]
1611
- tiffDict[kCGImagePropertyTIFFMake as String] = "Apple"
1612
- tiffDict[kCGImagePropertyTIFFModel as String] = UIDevice.current.model
1613
- tiffDict[kCGImagePropertyTIFFOrientation as String] = 1
1614
- finalProperties[kCGImagePropertyTIFFDictionary as String] = tiffDict
1615
-
1616
- CGImageDestinationAddImage(destination, cgImage, finalProperties as CFDictionary)
1617
-
1618
- if CGImageDestinationFinalize(destination) {
1619
- return mutableData as Data
1620
- }
1621
-
1622
- return jpegDataAtQuality
1623
- }
1624
-
1625
1567
  @objc func captureSample(_ call: CAPPluginCall) {
1626
1568
  let quality: Int = call.getInt("quality") ?? 85
1627
1569
  let mirrorFrontCamera = call.getBool("mirrorFrontCamera", false) ?? false
@@ -1821,7 +1763,8 @@ public class CameraPreview: CAPPlugin, CAPBridgedPlugin, CLLocationManagerDelega
1821
1763
  if let frameRate = call.getInt("frameRate") {
1822
1764
  try self.cameraController.setVideoFrameRate(frameRate)
1823
1765
  }
1824
- let allowHapticsAndSystemSoundsDuringRecording = call.getBool("allowHapticsAndSystemSoundsDuringRecording") ?? false
1766
+ let allowHapticsAndSystemSoundsDuringRecording = call.getBool("allowHapticsAndSystemSoundsDuringRecording")
1767
+ ?? self.cameraController.allowHapticsAndSystemSoundsDuringRecording
1825
1768
  let mirrorFrontCamera = call.getBool("mirrorFrontCamera") ?? false
1826
1769
  try self.cameraController.captureVideo(
1827
1770
  maxDuration: maxDuration,
@@ -2438,12 +2381,7 @@ public class CameraPreview: CAPPlugin, CAPBridgedPlugin, CLLocationManagerDelega
2438
2381
  }
2439
2382
 
2440
2383
  DispatchQueue.main.async {
2441
- var result = JSObject()
2442
- result["x"] = Double(self.previewView.frame.origin.x)
2443
- result["y"] = Double(self.previewView.frame.origin.y)
2444
- result["width"] = Double(self.previewView.frame.width)
2445
- result["height"] = Double(self.previewView.frame.height)
2446
- call.resolve(result)
2384
+ call.resolve(self.visiblePreviewSizeJSObject())
2447
2385
  }
2448
2386
  }
2449
2387
 
@@ -2480,13 +2418,7 @@ public class CameraPreview: CAPPlugin, CAPBridgedPlugin, CLLocationManagerDelega
2480
2418
  self.updateCameraFrame()
2481
2419
  self.makeWebViewTransparent()
2482
2420
 
2483
- // Return the actual preview bounds
2484
- var result = JSObject()
2485
- result["x"] = Double(self.previewView.frame.origin.x)
2486
- result["y"] = Double(self.previewView.frame.origin.y)
2487
- result["width"] = Double(self.previewView.frame.width)
2488
- result["height"] = Double(self.previewView.frame.height)
2489
- call.resolve(result)
2421
+ call.resolve(self.visiblePreviewSizeJSObject())
2490
2422
  }
2491
2423
  }
2492
2424
 
@@ -43,6 +43,32 @@ final class AspectRatioLayoutTests: XCTestCase {
43
43
  XCTAssertGreaterThan(dimensions.height, 500)
44
44
  }
45
45
 
46
+ func testContainContentRectLetterboxesFourThreeInTallContainer() {
47
+ let container = CGRect(x: 0, y: 0, width: 390, height: 700)
48
+ let content = AspectRatioLayout.containContentRect(
49
+ contentSize: CGSize(width: 3, height: 4),
50
+ inside: container
51
+ )
52
+
53
+ XCTAssertEqual(content.width, 390, accuracy: 0.5)
54
+ XCTAssertEqual(content.height, 520, accuracy: 0.5)
55
+ XCTAssertEqual(content.origin.x, 0, accuracy: 0.5)
56
+ XCTAssertEqual(content.origin.y, 90, accuracy: 0.5)
57
+ }
58
+
59
+ func testPreviewContentRectInWebViewCoordinatesOffsetsByPreviewViewOrigin() {
60
+ let content = CGRect(x: 0, y: 90, width: 390, height: 520)
61
+ let mapped = AspectRatioLayout.previewContentRectInWebViewCoordinates(
62
+ contentRectInPreviewView: content,
63
+ previewViewFrame: CGRect(x: 12, y: 48, width: 390, height: 700)
64
+ )
65
+
66
+ XCTAssertEqual(mapped.origin.x, 12, accuracy: 0.5)
67
+ XCTAssertEqual(mapped.origin.y, 138, accuracy: 0.5)
68
+ XCTAssertEqual(mapped.width, 390, accuracy: 0.5)
69
+ XCTAssertEqual(mapped.height, 520, accuracy: 0.5)
70
+ }
71
+
46
72
  func testMalformedRatioFallsBackToFullViewport() {
47
73
  XCTAssertNil(AspectRatioLayout.parseViewportAspectRatio("4:bad:3", isPortrait: true))
48
74