@capgo/camera-preview 8.13.3 → 8.14.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 (27) hide show
  1. package/README.md +40 -39
  2. package/android/src/main/java/app/capgo/capacitor/camera/preview/CameraPreview.java +15 -0
  3. package/android/src/main/java/app/capgo/capacitor/camera/preview/CameraXView.java +21 -0
  4. package/android/src/main/java/app/capgo/capacitor/camera/preview/VideoRecordingOptions.java +53 -0
  5. package/android/src/main/java/app/capgo/capacitor/camera/preview/model/CameraSessionConfiguration.java +9 -0
  6. package/android/src/test/java/app/capgo/capacitor/camera/preview/VideoRecordingOptionsTest.java +65 -0
  7. package/dist/docs.json +21 -1
  8. package/dist/esm/definitions.d.ts +9 -1
  9. package/dist/esm/definitions.js.map +1 -1
  10. package/dist/esm/web.d.ts +3 -0
  11. package/dist/esm/web.js +23 -2
  12. package/dist/esm/web.js.map +1 -1
  13. package/dist/plugin.cjs.js +23 -1
  14. package/dist/plugin.cjs.js.map +1 -1
  15. package/dist/plugin.js +23 -1
  16. package/dist/plugin.js.map +1 -1
  17. package/ios/Sources/CapgoCameraPreviewPlugin/CameraController.swift +125 -17
  18. package/ios/Sources/CapgoCameraPreviewPlugin/CaptureImageExifEncoder.swift +4 -20
  19. package/ios/Sources/CapgoCameraPreviewPlugin/CaptureLifecycleCoordination.swift +43 -0
  20. package/ios/Sources/CapgoCameraPreviewPlugin/ExifGpsMetadata.swift +44 -0
  21. package/ios/Sources/CapgoCameraPreviewPlugin/Plugin.swift +63 -4
  22. package/ios/Sources/CapgoCameraPreviewPlugin/VideoRecordingOptions.swift +56 -0
  23. package/ios/Tests/CameraPreviewPluginTests/CaptureImageExifEncoderTests.swift +121 -0
  24. package/ios/Tests/CameraPreviewPluginTests/CaptureLifecycleCoordinationTests.swift +62 -0
  25. package/ios/Tests/CameraPreviewPluginTests/ExifGpsMetadataTests.swift +187 -0
  26. package/ios/Tests/CameraPreviewPluginTests/VideoRecordingOptionsTests.swift +58 -0
  27. package/package.json +2 -2
@@ -220,6 +220,8 @@ class CameraController: NSObject, CXCallObserverDelegate {
220
220
  var videoQuality: String = "high"
221
221
  private var configuredVideoFrameRate: Int?
222
222
  var videoCodec: String = "avc1"
223
+ var videoBitrate: Int?
224
+ private var previewVideoBitrate: Int?
223
225
  var videoStabilizationMode: String = "off"
224
226
  private var cachedSupportedVideoStabilizationModes: [String] = []
225
227
  private var isSupportedVideoStabilizationModesCacheValid = false
@@ -281,6 +283,31 @@ class CameraController: NSObject, CXCallObserverDelegate {
281
283
  return self.videoCodec
282
284
  }
283
285
 
286
+ func setPreviewVideoBitrate(_ bitrate: Int?) {
287
+ if let bitrate = bitrate, bitrate > 0 {
288
+ self.previewVideoBitrate = bitrate
289
+ } else {
290
+ self.previewVideoBitrate = nil
291
+ }
292
+ self.videoBitrate = self.previewVideoBitrate
293
+ }
294
+
295
+ func getPreviewVideoBitrate() -> Int? {
296
+ return self.previewVideoBitrate
297
+ }
298
+
299
+ func applyRecordingVideoBitrateOverride(_ bitrate: Int?) {
300
+ if let bitrate = bitrate, bitrate > 0 {
301
+ self.videoBitrate = bitrate
302
+ } else {
303
+ self.videoBitrate = self.previewVideoBitrate
304
+ }
305
+ }
306
+
307
+ func getVideoBitrate() -> Int? {
308
+ return self.videoBitrate
309
+ }
310
+
284
311
  func isVideoStabilizationSupported() -> Bool {
285
312
  guard let connection = self.fileVideoOutput?.connection(with: .video) else {
286
313
  return false
@@ -500,6 +527,7 @@ class CameraController: NSObject, CXCallObserverDelegate {
500
527
 
501
528
  // Capture/stop coordination (main-thread only; see CaptureLifecycleCoordination)
502
529
  var captureLifecycle = CaptureLifecycleState()
530
+ private(set) var captureSessionTeardownStarted = false
503
531
 
504
532
  var isCapturingPhoto: Bool {
505
533
  get { self.captureLifecycle.isCapturingPhoto }
@@ -721,6 +749,7 @@ extension CameraController {
721
749
  // Kept for backward compatibility
722
750
  guard self.captureSession == nil else { return }
723
751
 
752
+ self.captureSessionTeardownStarted = false
724
753
  self.captureSession = AVCaptureSession()
725
754
  }
726
755
 
@@ -880,6 +909,7 @@ extension CameraController {
880
909
  do {
881
910
  // Create session if needed
882
911
  if self.captureSession == nil {
912
+ self.captureSessionTeardownStarted = false
883
913
  self.captureSession = AVCaptureSession()
884
914
  }
885
915
 
@@ -1553,6 +1583,15 @@ extension CameraController {
1553
1583
  return
1554
1584
  }
1555
1585
 
1586
+ let sessionRunning = self.captureSession?.isRunning ?? false
1587
+ if CaptureSubmissionGate.blocksPhotoCaptureSubmission(
1588
+ sessionTeardownStarted: self.captureSessionTeardownStarted,
1589
+ isCaptureSessionRunning: sessionRunning
1590
+ ) {
1591
+ completion(nil, nil, nil, CameraControllerError.captureSessionIsMissing)
1592
+ return
1593
+ }
1594
+
1556
1595
  var orientationUsedForCapture = self.getPhysicalOrientation()
1557
1596
  if let connection = photoOutput.connection(with: .video) {
1558
1597
  let previewOrientation = self.getPreviewLayerVideoOrientation() ?? self.getVideoOrientation()
@@ -1613,12 +1652,17 @@ extension CameraController {
1613
1652
  }
1614
1653
  }
1615
1654
 
1616
- if Thread.isMainThread {
1617
- self.isCapturingPhoto = true
1618
- } else {
1619
- DispatchQueue.main.sync {
1620
- self.isCapturingPhoto = true
1621
- }
1655
+ let claimSubmission: () -> Bool = {
1656
+ CaptureSubmissionGate.tryClaimPhotoCapture(
1657
+ sessionTeardownStarted: self.captureSessionTeardownStarted,
1658
+ isCaptureSessionRunning: self.captureSession?.isRunning ?? false,
1659
+ isCapturingPhoto: &self.captureLifecycle.isCapturingPhoto
1660
+ )
1661
+ }
1662
+ let claimed = Thread.isMainThread ? claimSubmission() : DispatchQueue.main.sync(execute: claimSubmission)
1663
+ guard claimed else {
1664
+ completion(nil, nil, nil, CameraControllerError.captureSessionIsMissing)
1665
+ return
1622
1666
  }
1623
1667
 
1624
1668
  self.photoCaptureCompletionBlock = { [weak self] (image, photoData, metadata, error) in
@@ -2130,13 +2174,63 @@ extension CameraController {
2130
2174
  }
2131
2175
 
2132
2176
  func captureSample(completion: @escaping (UIImage?, Error?) -> Void) {
2133
- guard let captureSession = captureSession,
2134
- captureSession.isRunning else {
2177
+ let wrappedCompletion: (UIImage?, Error?) -> Void = { [weak self] image, error in
2178
+ guard let self = self else { return }
2179
+ let claimDelivery: () -> Bool = {
2180
+ guard CaptureLifecycleCoordination.claimAwaitingSampleCapture(state: &self.captureLifecycle) else {
2181
+ return false
2182
+ }
2183
+ self.sampleBufferCaptureCompletionBlock = nil
2184
+ return true
2185
+ }
2186
+ let claimed = Thread.isMainThread
2187
+ ? claimDelivery()
2188
+ : DispatchQueue.main.sync(execute: claimDelivery)
2189
+ guard claimed else { return }
2190
+ CapturePhotoProcessingQueue.async {
2191
+ completion(image, error)
2192
+ }
2193
+ }
2194
+
2195
+ let claimAndRegister: () -> Bool = { [weak self] in
2196
+ guard let self = self else { return false }
2197
+ let sessionRunning = self.captureSession?.isRunning ?? false
2198
+ if CaptureSubmissionGate.blocksPhotoCaptureSubmission(
2199
+ sessionTeardownStarted: self.captureSessionTeardownStarted,
2200
+ isCaptureSessionRunning: sessionRunning
2201
+ ) {
2202
+ return false
2203
+ }
2204
+ self.captureLifecycle.isAwaitingSampleCapture = true
2205
+ self.sampleBufferCaptureCompletionBlock = wrappedCompletion
2206
+ return true
2207
+ }
2208
+
2209
+ let registered = Thread.isMainThread ? claimAndRegister() : DispatchQueue.main.sync(execute: claimAndRegister)
2210
+ if !registered {
2135
2211
  completion(nil, CameraControllerError.captureSessionIsMissing)
2136
- return
2137
2212
  }
2213
+ }
2214
+
2215
+ func cancelPendingSampleCapture() {
2216
+ let cancel = { [weak self] in
2217
+ guard let self = self else { return }
2218
+ CaptureLifecycleCoordination.cancelAwaitingSampleCaptureIfNeeded(
2219
+ isAwaiting: self.captureLifecycle.isAwaitingSampleCapture
2220
+ ) {
2221
+ self.deliverPendingSampleCapture(image: nil, error: CameraControllerError.captureSessionIsMissing)
2222
+ }
2223
+ }
2224
+ if Thread.isMainThread {
2225
+ cancel()
2226
+ } else {
2227
+ DispatchQueue.main.sync(execute: cancel)
2228
+ }
2229
+ }
2138
2230
 
2139
- self.sampleBufferCaptureCompletionBlock = completion
2231
+ private func deliverPendingSampleCapture(image: UIImage?, error: Error?) {
2232
+ guard let handler = sampleBufferCaptureCompletionBlock else { return }
2233
+ handler(image, error)
2140
2234
  }
2141
2235
 
2142
2236
  func startBarcodeScanner(formats: [String], detectionIntervalMs: Int, callback: @escaping ([[String: Any]]) -> Void) throws {
@@ -2973,11 +3067,15 @@ extension CameraController {
2973
3067
  }
2974
3068
 
2975
3069
  func cleanup() {
3070
+ self.captureSessionTeardownStarted = true
3071
+ self.cancelPendingSampleCapture()
2976
3072
  self.invalidateActivePrepare()
2977
3073
  self.cancelPendingFocusExposureRestore()
2978
3074
  self.configuredCaptureResolutionWidth = nil
2979
3075
  self.configuredCaptureResolutionHeight = nil
2980
3076
  configuredVideoFrameRate = nil
3077
+ self.previewVideoBitrate = nil
3078
+ self.videoBitrate = nil
2981
3079
  stopBarcodeScanner()
2982
3080
  self.unregisterCaptureSessionObservers()
2983
3081
  self.onCameraInterrupted = nil
@@ -3529,7 +3627,14 @@ extension CameraController {
3529
3627
  if let connection = fileVideoOutput.connection(with: .video),
3530
3628
  let codecType = avVideoCodecType(for: self.videoCodec),
3531
3629
  fileVideoOutput.availableVideoCodecTypes.contains(codecType) {
3532
- fileVideoOutput.setOutputSettings([AVVideoCodecKey: codecType], for: connection)
3630
+ let supportedKeys = fileVideoOutput.supportedOutputSettingsKeys(for: connection)
3631
+ let outputSettings = VideoRecordingOptions.movieFileOutputSettings(
3632
+ codecType: codecType,
3633
+ videoBitrate: supportedKeys.contains(AVVideoCompressionPropertiesKey)
3634
+ ? self.videoBitrate
3635
+ : nil
3636
+ )
3637
+ fileVideoOutput.setOutputSettings(outputSettings, for: connection)
3533
3638
  }
3534
3639
 
3535
3640
  self.configureCaptureSession {
@@ -3745,10 +3850,15 @@ extension CameraController: AVCaptureVideoDataOutputSampleBufferDelegate, AVCapt
3745
3850
  }
3746
3851
  }
3747
3852
 
3748
- guard let completion = sampleBufferCaptureCompletionBlock else { return }
3853
+ guard sampleBufferCaptureCompletionBlock != nil else { return }
3854
+
3855
+ if captureSessionTeardownStarted {
3856
+ deliverPendingSampleCapture(image: nil, error: CameraControllerError.captureSessionIsMissing)
3857
+ return
3858
+ }
3749
3859
 
3750
3860
  guard let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {
3751
- completion(nil, CameraControllerError.unknown)
3861
+ deliverPendingSampleCapture(image: nil, error: CameraControllerError.unknown)
3752
3862
  return
3753
3863
  }
3754
3864
 
@@ -3774,14 +3884,12 @@ extension CameraController: AVCaptureVideoDataOutputSampleBufferDelegate, AVCapt
3774
3884
  )
3775
3885
 
3776
3886
  guard let cgImage = context?.makeImage() else {
3777
- completion(nil, CameraControllerError.unknown)
3887
+ deliverPendingSampleCapture(image: nil, error: CameraControllerError.unknown)
3778
3888
  return
3779
3889
  }
3780
3890
 
3781
3891
  let image = UIImage(cgImage: cgImage)
3782
- completion(image.fixedOrientation(), nil)
3783
-
3784
- sampleBufferCaptureCompletionBlock = nil
3892
+ deliverPendingSampleCapture(image: image.fixedOrientation(), error: nil)
3785
3893
  }
3786
3894
 
3787
3895
  func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
@@ -38,26 +38,10 @@ enum CaptureImageExifEncoder {
38
38
  finalProperties[kCGImagePropertyOrientation as String] = 1
39
39
 
40
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 direction = heading.flatMap(CaptureExifGps.imageDirection) {
56
- gpsDict[kCGImagePropertyGPSImgDirection as String] = direction.degrees
57
- gpsDict[kCGImagePropertyGPSImgDirectionRef as String] = direction.reference
58
- }
59
-
60
- finalProperties[kCGImagePropertyGPSDictionary as String] = gpsDict
41
+ finalProperties[kCGImagePropertyGPSDictionary as String] = ExifGpsMetadata.gpsDictionary(
42
+ for: location,
43
+ heading: heading
44
+ )
61
45
  }
62
46
 
63
47
  var tiffDict = finalProperties[kCGImagePropertyTIFFDictionary as String] as? [String: Any] ?? [:]
@@ -4,9 +4,52 @@ import Foundation
4
4
  struct CaptureLifecycleState {
5
5
  var isCapturingPhoto: Bool = false
6
6
  var stopRequestedAfterCapture: Bool = false
7
+ var isAwaitingSampleCapture: Bool = false
8
+ }
9
+
10
+ enum CaptureReadiness {
11
+ /// Matches `isRunning()` and capture guards: preview started and capture session active.
12
+ static func canPerformCapture(isInitialized: Bool, isCaptureSessionRunning: Bool) -> Bool {
13
+ isInitialized && isCaptureSessionRunning
14
+ }
15
+ }
16
+
17
+ enum CaptureSubmissionGate {
18
+ /// Blocks still capture submission once teardown started or the session stopped.
19
+ static func blocksPhotoCaptureSubmission(sessionTeardownStarted: Bool, isCaptureSessionRunning: Bool) -> Bool {
20
+ sessionTeardownStarted || !isCaptureSessionRunning
21
+ }
22
+
23
+ /// Main-thread only: gate check and `isCapturingPhoto = true` in one step.
24
+ static func tryClaimPhotoCapture(
25
+ sessionTeardownStarted: Bool,
26
+ isCaptureSessionRunning: Bool,
27
+ isCapturingPhoto: inout Bool
28
+ ) -> Bool {
29
+ if blocksPhotoCaptureSubmission(
30
+ sessionTeardownStarted: sessionTeardownStarted,
31
+ isCaptureSessionRunning: isCaptureSessionRunning
32
+ ) {
33
+ return false
34
+ }
35
+ isCapturingPhoto = true
36
+ return true
37
+ }
7
38
  }
8
39
 
9
40
  enum CaptureLifecycleCoordination {
41
+ /// Rejects a pending sample-buffer capture when teardown begins (call on the main thread).
42
+ static func cancelAwaitingSampleCaptureIfNeeded(isAwaiting: Bool, cancel: () -> Void) {
43
+ guard isAwaiting else { return }
44
+ cancel()
45
+ }
46
+
47
+ /// Main-thread only: one-shot claim before delivering a sample capture result.
48
+ static func claimAwaitingSampleCapture(state: inout CaptureLifecycleState) -> Bool {
49
+ guard state.isAwaitingSampleCapture else { return false }
50
+ state.isAwaitingSampleCapture = false
51
+ return true
52
+ }
10
53
  /// Handles `stop()` when a capture may be in flight. Call on the main thread only.
11
54
  static func handleStop(
12
55
  state: inout CaptureLifecycleState,
@@ -0,0 +1,44 @@
1
+ import CoreLocation
2
+ import ImageIO
3
+
4
+ enum ExifGpsMetadata {
5
+ private static let posixLocale = Locale(identifier: "en_US_POSIX")
6
+ private static let utcTimeZone = TimeZone(secondsFromGMT: 0)!
7
+
8
+ static func gpsDateStamp(from date: Date) -> String {
9
+ let formatter = DateFormatter()
10
+ formatter.locale = posixLocale
11
+ formatter.timeZone = utcTimeZone
12
+ formatter.dateFormat = "yyyy:MM:dd"
13
+ return formatter.string(from: date)
14
+ }
15
+
16
+ static func gpsTimeStamp(from date: Date) -> String {
17
+ let formatter = DateFormatter()
18
+ formatter.locale = posixLocale
19
+ formatter.timeZone = utcTimeZone
20
+ formatter.dateFormat = "HH:mm:ss.SS"
21
+ return formatter.string(from: date)
22
+ }
23
+
24
+ static func gpsDictionary(for location: CLLocation, heading: CLHeading? = nil) -> [String: Any] {
25
+ let timestamp = location.timestamp
26
+ var gpsDict: [String: Any] = [
27
+ kCGImagePropertyGPSLatitude as String: abs(location.coordinate.latitude),
28
+ kCGImagePropertyGPSLatitudeRef as String: location.coordinate.latitude >= 0 ? "N" : "S",
29
+ kCGImagePropertyGPSLongitude as String: abs(location.coordinate.longitude),
30
+ kCGImagePropertyGPSLongitudeRef as String: location.coordinate.longitude >= 0 ? "E" : "W",
31
+ kCGImagePropertyGPSDateStamp as String: gpsDateStamp(from: timestamp),
32
+ kCGImagePropertyGPSTimeStamp as String: gpsTimeStamp(from: timestamp),
33
+ kCGImagePropertyGPSAltitude as String: location.altitude,
34
+ kCGImagePropertyGPSAltitudeRef as String: location.altitude >= 0 ? 0 : 1
35
+ ]
36
+
37
+ if let direction = heading.flatMap(CaptureExifGps.imageDirection) {
38
+ gpsDict[kCGImagePropertyGPSImgDirection as String] = direction.degrees
39
+ gpsDict[kCGImagePropertyGPSImgDirectionRef as String] = direction.reference
40
+ }
41
+
42
+ return gpsDict
43
+ }
44
+ }
@@ -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.13.3"
38
+ private let pluginVersion: String = "8.14.0"
39
39
  public let identifier = "CameraPreviewPlugin"
40
40
  public let jsName = "CameraPreview"
41
41
  public let pluginMethods: [CAPPluginMethod] = [
@@ -813,6 +813,9 @@ public class CameraPreview: CAPPlugin, CAPBridgedPlugin, CLLocationManagerDelega
813
813
 
814
814
  // Default to high if not provided
815
815
  let videoQuality = call.getString("videoQuality") ?? "high"
816
+ self.cameraController.setPreviewVideoBitrate(
817
+ VideoRecordingOptions.parseVideoBitrate(from: call.options["videoBitrate"])
818
+ )
816
819
  let videoStabilizationMode = call.getString("videoStabilizationMode")
817
820
  self.pendingStartBarcodeScannerOptions = self.barcodeScannerStartOptions(from: call)
818
821
 
@@ -1177,6 +1180,8 @@ public class CameraPreview: CAPPlugin, CAPBridgedPlugin, CLLocationManagerDelega
1177
1180
  self.isGeneratingDeviceOrientationNotifications = false
1178
1181
  }
1179
1182
 
1183
+ self.cameraController.cancelPendingSampleCapture()
1184
+
1180
1185
  CaptureLifecycleCoordination.handleStop(
1181
1186
  state: &self.cameraController.captureLifecycle,
1182
1187
  force: force,
@@ -1285,8 +1290,48 @@ public class CameraPreview: CAPPlugin, CAPBridgedPlugin, CLLocationManagerDelega
1285
1290
  return fileUrl
1286
1291
  }
1287
1292
 
1293
+ private func stopExifHeadingUpdatesAfterAbortedCapture() {
1294
+ let work = {
1295
+ self.locationManager?.stopUpdatingHeading()
1296
+ self.currentHeading = CaptureExifHeadingLifecycle.heading(
1297
+ after: .captureExifFinished,
1298
+ current: self.currentHeading
1299
+ )
1300
+ }
1301
+ if Thread.isMainThread {
1302
+ work()
1303
+ } else {
1304
+ DispatchQueue.main.async(execute: work)
1305
+ }
1306
+ }
1307
+
1308
+ private func rejectUnlessCameraRunning(_ call: CAPPluginCall) -> Bool {
1309
+ let canCapture: Bool = {
1310
+ if Thread.isMainThread {
1311
+ return CaptureReadiness.canPerformCapture(
1312
+ isInitialized: self.isInitialized,
1313
+ isCaptureSessionRunning: self.cameraController.captureSession?.isRunning ?? false
1314
+ )
1315
+ }
1316
+ return DispatchQueue.main.sync {
1317
+ CaptureReadiness.canPerformCapture(
1318
+ isInitialized: self.isInitialized,
1319
+ isCaptureSessionRunning: self.cameraController.captureSession?.isRunning ?? false
1320
+ )
1321
+ }
1322
+ }()
1323
+ if !canCapture {
1324
+ call.reject("Camera is not running")
1325
+ return false
1326
+ }
1327
+ return true
1328
+ }
1329
+
1288
1330
  @objc func capture(_ call: CAPPluginCall) {
1289
1331
  print("[CameraPreview] capture called with options: \(call.options ?? [:])")
1332
+ guard rejectUnlessCameraRunning(call) else {
1333
+ return
1334
+ }
1290
1335
  let withExifLocation = call.getBool("withExifLocation", false)
1291
1336
  print("[CameraPreview] capture called, withExifLocation: \(withExifLocation)")
1292
1337
 
@@ -1357,6 +1402,12 @@ public class CameraPreview: CAPPlugin, CAPBridgedPlugin, CLLocationManagerDelega
1357
1402
 
1358
1403
  private func performCapture(call: CAPPluginCall) {
1359
1404
  print("[CameraPreview] performCapture called")
1405
+ guard rejectUnlessCameraRunning(call) else {
1406
+ if call.getBool("withExifLocation", false) ?? false {
1407
+ self.stopExifHeadingUpdatesAfterAbortedCapture()
1408
+ }
1409
+ return
1410
+ }
1360
1411
  print("[CameraPreview] Call parameters: \(call.options ?? [:])")
1361
1412
  let quality = call.getFloat("quality", 85)
1362
1413
  let saveToGallery = call.getBool("saveToGallery", false)
@@ -1377,13 +1428,13 @@ public class CameraPreview: CAPPlugin, CAPBridgedPlugin, CLLocationManagerDelega
1377
1428
  // Safely read frame from main thread for logging
1378
1429
  let (previewWidth, previewHeight): (CGFloat, CGFloat) = {
1379
1430
  if Thread.isMainThread {
1380
- return (self.previewView.frame.width, self.previewView.frame.height)
1431
+ return (self.previewView?.frame.width ?? 0, self.previewView?.frame.height ?? 0)
1381
1432
  }
1382
1433
  var width: CGFloat = 0
1383
1434
  var height: CGFloat = 0
1384
1435
  DispatchQueue.main.sync {
1385
- width = self.previewView.frame.width
1386
- height = self.previewView.frame.height
1436
+ width = self.previewView?.frame.width ?? 0
1437
+ height = self.previewView?.frame.height ?? 0
1387
1438
  }
1388
1439
  return (width, height)
1389
1440
  }()
@@ -1574,6 +1625,9 @@ public class CameraPreview: CAPPlugin, CAPBridgedPlugin, CLLocationManagerDelega
1574
1625
  }
1575
1626
 
1576
1627
  @objc func captureSample(_ call: CAPPluginCall) {
1628
+ guard rejectUnlessCameraRunning(call) else {
1629
+ return
1630
+ }
1577
1631
  let quality: Int = call.getInt("quality") ?? 85
1578
1632
  let mirrorFrontCamera = call.getBool("mirrorFrontCamera", false) ?? false
1579
1633
  let capturedFromFrontCamera = self.cameraController.currentCameraPosition == .front
@@ -1754,6 +1808,11 @@ public class CameraPreview: CAPPlugin, CAPBridgedPlugin, CLLocationManagerDelega
1754
1808
  if let videoCodec = call.getString("videoCodec") {
1755
1809
  try? self.cameraController.setVideoCodec(videoCodec)
1756
1810
  }
1811
+ let recordingVideoBitrate = VideoRecordingOptions.resolveRecordingVideoBitrateOverride(
1812
+ from: call.options["videoBitrate"],
1813
+ isKeyPresent: call.options["videoBitrate"] != nil
1814
+ )
1815
+ self.cameraController.applyRecordingVideoBitrateOverride(recordingVideoBitrate)
1757
1816
  if let videoStabilizationMode = call.getString("videoStabilizationMode") {
1758
1817
  do {
1759
1818
  try self.cameraController.setVideoStabilizationMode(videoStabilizationMode)
@@ -0,0 +1,56 @@
1
+ import AVFoundation
2
+ import Foundation
3
+
4
+ enum VideoRecordingOptions {
5
+ /// Returns a positive bits-per-second value, or `nil` when omitted or invalid.
6
+ static func parseVideoBitrate(from value: Any?) -> Int? {
7
+ guard let value = value else {
8
+ return nil
9
+ }
10
+ if value is Bool {
11
+ return nil
12
+ }
13
+ if let number = value as? NSNumber, CFGetTypeID(number) == CFBooleanGetTypeID() {
14
+ return nil
15
+ }
16
+ if let intValue = value as? Int {
17
+ return intValue > 0 ? intValue : nil
18
+ }
19
+ if let doubleValue = value as? Double {
20
+ return positiveInt(from: doubleValue)
21
+ }
22
+ if let stringValue = value as? String, let doubleValue = Double(stringValue) {
23
+ return positiveInt(from: doubleValue)
24
+ }
25
+ if let numberValue = value as? NSNumber {
26
+ return positiveInt(from: numberValue.doubleValue)
27
+ }
28
+ return nil
29
+ }
30
+
31
+ private static func positiveInt(from doubleValue: Double) -> Int? {
32
+ guard doubleValue.isFinite, doubleValue > 0, doubleValue.rounded() == doubleValue else {
33
+ return nil
34
+ }
35
+ return Int(exactly: doubleValue)
36
+ }
37
+
38
+ /// Per-call override when the key is present and valid; `nil` when omitted or invalid (restore preview bitrate).
39
+ static func resolveRecordingVideoBitrateOverride(from value: Any?, isKeyPresent: Bool) -> Int? {
40
+ guard isKeyPresent else {
41
+ return nil
42
+ }
43
+ return parseVideoBitrate(from: value)
44
+ }
45
+
46
+ static func movieFileOutputSettings(
47
+ codecType: AVVideoCodecType,
48
+ videoBitrate: Int?
49
+ ) -> [String: Any] {
50
+ var settings: [String: Any] = [AVVideoCodecKey: codecType]
51
+ if let videoBitrate = videoBitrate, videoBitrate > 0 {
52
+ settings[AVVideoCompressionPropertiesKey] = [AVVideoAverageBitRateKey: videoBitrate]
53
+ }
54
+ return settings
55
+ }
56
+ }