@capgo/camera-preview 8.12.4 → 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.
@@ -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 {
@@ -182,6 +182,7 @@ class CameraController: NSObject, CXCallObserverDelegate {
182
182
  private let sessionRecoveryQueue = DispatchQueue(label: "com.capgo.camera.sessionRecovery")
183
183
  private var activePrepareToken: UInt = 0
184
184
  private var audioInputEnabledByUser = false
185
+ var allowHapticsAndSystemSoundsDuringRecording = false
185
186
  private let applicationAudioSessionRestoreCoordinator = ApplicationAudioSessionRestoreCoordinator()
186
187
  private var recordingIdByOutputFileURL: [URL: UInt64] = [:]
187
188
  private let recordingIdQueue = DispatchQueue(label: "com.capgo.camera.recordingIds")
@@ -508,6 +509,63 @@ class CameraController: NSObject, CXCallObserverDelegate {
508
509
  var requestedAspectRatio: String?
509
510
  var requestedAspectMode: String = "contain"
510
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
+
511
569
  func calculateAspectRatioFrame(for aspectRatio: String, in bounds: CGRect) -> CGRect {
512
570
  guard let ratio = parseAspectRatio(aspectRatio) else {
513
571
  return bounds
@@ -563,6 +621,56 @@ class CameraController: NSObject, CXCallObserverDelegate {
563
621
 
564
622
  return (width: finalWidth, height: finalHeight)
565
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
+ }
566
674
  }
567
675
 
568
676
  extension CameraController {
@@ -698,9 +806,10 @@ extension CameraController {
698
806
  return token != 0 && token == self.activePrepareToken
699
807
  }
700
808
 
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)")
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)")
703
811
 
812
+ self.allowHapticsAndSystemSoundsDuringRecording = allowHapticsAndSystemSoundsDuringRecording
704
813
  self.applicationAudioSessionRestoreCoordinator.beginPreviewSession()
705
814
  self.activePrepareToken = startToken
706
815
 
@@ -775,6 +884,7 @@ extension CameraController {
775
884
  if let photoOutput = self.photoOutput, captureSession.canAddOutput(photoOutput) {
776
885
  photoOutput.isHighResolutionCaptureEnabled = true
777
886
  captureSession.addOutput(photoOutput)
887
+ self.applyConfiguredCaptureResolutionToPhotoOutputIfNeeded()
778
888
  // Set orientation immediately
779
889
  self.setVideoOrientation(videoOrientation, on: photoOutput.connections)
780
890
  }
@@ -813,6 +923,7 @@ extension CameraController {
813
923
 
814
924
  // Start the session - all outputs are already configured
815
925
  captureSession.startRunning()
926
+ self.applyAllowHapticsAndSystemSoundsDuringRecordingPolicy()
816
927
 
817
928
  // Bring to full opacity after a tiny moment to smooth any visual artifacts
818
929
  DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) { [weak self] in
@@ -1059,6 +1170,7 @@ extension CameraController {
1059
1170
  self.audioInput = try AVCaptureDeviceInput(device: audioDevice)
1060
1171
  if captureSession.canAddInput(self.audioInput!) {
1061
1172
  captureSession.addInput(self.audioInput!)
1173
+ self.applyAllowHapticsAndSystemSoundsDuringRecordingPolicy()
1062
1174
  } else {
1063
1175
  throw CameraControllerError.inputsAreInvalid
1064
1176
  }
@@ -1387,6 +1499,8 @@ extension CameraController {
1387
1499
  }
1388
1500
  }
1389
1501
 
1502
+ self.applyConfiguredCaptureResolutionToPhotoOutputIfNeeded()
1503
+
1390
1504
  // Keep orientation correct
1391
1505
  self.updateVideoOrientation()
1392
1506
  }
@@ -1408,9 +1522,16 @@ extension CameraController {
1408
1522
  let visibleFillRatio = self.visibleFillCaptureAspectRatio()
1409
1523
  let settings = AVCapturePhotoSettings()
1410
1524
  // 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
1525
+ let shouldUseHighRes = CaptureResolutionSupport.shouldEnableHighResolutionPhoto(
1526
+ captureResolutionWidth: self.configuredCaptureResolutionWidth,
1527
+ captureResolutionHeight: self.configuredCaptureResolutionHeight,
1528
+ captureMaxWidth: width,
1529
+ captureMaxHeight: height
1530
+ )
1413
1531
  settings.isHighResolutionPhotoEnabled = shouldUseHighRes
1532
+ if #available(iOS 16.0, *), let dimensions = self.configuredPhotoMaxDimensions() {
1533
+ settings.maxPhotoDimensions = dimensions
1534
+ }
1414
1535
  if #available(iOS 15.0, *) {
1415
1536
  if photoQualityPrioritization == "quality" {
1416
1537
  settings.photoQualityPrioritization = .quality
@@ -2643,6 +2764,8 @@ extension CameraController {
2643
2764
  }
2644
2765
  }
2645
2766
 
2767
+ self.applyConfiguredCaptureResolutionToPhotoOutputIfNeeded()
2768
+
2646
2769
  // Update video orientation
2647
2770
  self.updateVideoOrientation()
2648
2771
  }
@@ -2659,6 +2782,16 @@ extension CameraController {
2659
2782
  self.applicationAudioSessionRestoreCoordinator.captureSnapshotIfNeeded()
2660
2783
  }
2661
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
+
2662
2795
  private static let insufficientAudioPriorityOSStatus = 561017449
2663
2796
 
2664
2797
  private func isAudioPriorityError(_ error: NSError) -> Bool {
@@ -2721,6 +2854,7 @@ extension CameraController {
2721
2854
  if session.canAddInput(input) {
2722
2855
  session.addInput(input)
2723
2856
  self.audioInput = input
2857
+ self.applyAllowHapticsAndSystemSoundsDuringRecordingPolicy()
2724
2858
  }
2725
2859
  } catch {
2726
2860
  print("[CameraPreview] Failed to restore audio input after interruption: \(error)")
@@ -2808,6 +2942,8 @@ extension CameraController {
2808
2942
  func cleanup() {
2809
2943
  self.invalidateActivePrepare()
2810
2944
  self.cancelPendingFocusExposureRestore()
2945
+ self.configuredCaptureResolutionWidth = nil
2946
+ self.configuredCaptureResolutionHeight = nil
2811
2947
  configuredVideoFrameRate = nil
2812
2948
  stopBarcodeScanner()
2813
2949
  self.unregisterCaptureSessionObservers()
@@ -3296,12 +3432,13 @@ extension CameraController {
3296
3432
  // This reclaims the microphone even if other parts of the app changed the
3297
3433
  // AVAudioSession category (e.g. for UI sound effects) between recordings.
3298
3434
  if self.audioInput != nil {
3435
+ self.allowHapticsAndSystemSoundsDuringRecording = allowHapticsAndSystemSoundsDuringRecording
3299
3436
  self.captureApplicationAudioSessionSnapshotIfNeeded()
3300
3437
  do {
3301
3438
  let audioSession = AVAudioSession.sharedInstance()
3302
3439
  try audioSession.setCategory(.playAndRecord, mode: .videoRecording, options: [.defaultToSpeaker])
3303
3440
  try audioSession.setActive(true)
3304
- try audioSession.setAllowHapticsAndSystemSoundsDuringRecording(allowHapticsAndSystemSoundsDuringRecording)
3441
+ self.applyAllowHapticsAndSystemSoundsDuringRecordingPolicy()
3305
3442
  } catch {
3306
3443
  print("[CameraPreview] Failed to configure AVAudioSession for video recording: \(error)")
3307
3444
  }
@@ -3538,34 +3675,25 @@ extension CameraController: UIGestureRecognizerDelegate {
3538
3675
 
3539
3676
  extension CameraController: AVCapturePhotoCaptureDelegate {
3540
3677
  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
- }
3678
+ CapturePhotoProcessingQueue.async {
3679
+ if let error = error {
3680
+ self.photoCaptureCompletionBlock?(nil, nil, nil, error)
3681
+ return
3682
+ }
3545
3683
 
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
3684
  guard let imageData = photo.fileDataRepresentation() else {
3550
- DispatchQueue.main.async {
3551
- self.photoCaptureCompletionBlock?(nil, nil, nil, CameraControllerError.unknown)
3552
- }
3685
+ self.photoCaptureCompletionBlock?(nil, nil, nil, CameraControllerError.unknown)
3553
3686
  return
3554
3687
  }
3555
3688
 
3556
- // Create image from data
3557
3689
  guard let image = UIImage(data: imageData) else {
3558
- DispatchQueue.main.async {
3559
- self.photoCaptureCompletionBlock?(nil, nil, nil, CameraControllerError.unknown)
3560
- }
3690
+ self.photoCaptureCompletionBlock?(nil, nil, nil, CameraControllerError.unknown)
3561
3691
  return
3562
3692
  }
3563
3693
 
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
- }
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)
3569
3697
  }
3570
3698
  }
3571
3699
  }
@@ -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
+ }