@octane-xplat/camera 0.18.0 → 0.20.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 (67) hide show
  1. package/README.md +2 -132
  2. package/package.json +108 -103
  3. package/platforms/android/java/com/octanexplat/camera/CameraPreviewView.java +24 -0
  4. package/platforms/android/java/com/octanexplat/camera/CameraSessionBridge.java +153 -21
  5. package/platforms/ios/src/XplatSwitchingMovieWriter.swift +557 -0
  6. package/src/CameraView.android.tsrx +194 -118
  7. package/src/CameraView.ios.tsrx +129 -76
  8. package/src/CameraView.macos.tsrx +108 -70
  9. package/src/CameraView.tsrx +2 -0
  10. package/src/CameraView.web.tsrx +160 -125
  11. package/src/CameraView.windows.tsrx +141 -92
  12. package/src/camera-host.macos.ts +1059 -0
  13. package/src/camera-permission.mobile.ts +85 -81
  14. package/src/camera-permission.windows.ts +56 -53
  15. package/src/camera-session.ios.ts +89 -61
  16. package/src/camera-session.macos.ts +51 -49
  17. package/src/camera-session.windows.ts +113 -105
  18. package/src/host-movie.web.ts +266 -222
  19. package/src/index.ts +28 -26
  20. package/src/index.web.ts +27 -25
  21. package/src/layout-child.ts +88 -79
  22. package/src/layout-child.web.ts +57 -51
  23. package/src/layout-child.windows.ts +82 -71
  24. package/src/movie-metadata.web.ts +87 -74
  25. package/src/movie-storage.web.ts +142 -135
  26. package/src/movie-writer.ios.ts +170 -0
  27. package/src/photo-lifecycle.macos.ts +60 -0
  28. package/src/photo-sheet.macos.ts +505 -0
  29. package/src/preview-display.ios.ts +69 -0
  30. package/src/preview-pinch.ts +41 -0
  31. package/src/preview-tap.ts +22 -21
  32. package/src/props.ts +118 -68
  33. package/src/recording-haptics.ios.ts +39 -0
  34. package/src/recording-source.web.ts +159 -0
  35. package/src/session-backend.android.ts +552 -410
  36. package/src/session-backend.ios.ts +1500 -1148
  37. package/src/session-backend.linux.ts +886 -860
  38. package/src/session-backend.macos.ts +697 -679
  39. package/src/session-backend.ts +51 -49
  40. package/src/session-backend.web.ts +1181 -867
  41. package/src/session-backend.windows.ts +1556 -1467
  42. package/src/session-core.ts +925 -711
  43. package/src/session.ts +12 -12
  44. package/src/style-merge.ts +43 -43
  45. package/src/synthetic-session.ts +392 -333
  46. package/src/types.ts +384 -239
  47. package/types/generated/.tsrx-typegen-manifest.json +18 -0
  48. package/types/generated/CameraView.d.ts +2 -0
  49. package/types/generated/CameraView.web.d.ts +4 -0
  50. package/types/generated/camera-host.macos.d.ts +33 -0
  51. package/types/generated/index.d.ts +34 -0
  52. package/types/generated/layout-child.web.d.ts +7 -0
  53. package/types/generated/photo-lifecycle.macos.d.ts +12 -0
  54. package/types/generated/photo-sheet.macos.d.ts +36 -0
  55. package/types/generated/props.d.ts +111 -0
  56. package/types/generated/session-backend.d.ts +6 -0
  57. package/types/{session-core.d.ts → generated/session-core.d.ts} +30 -1
  58. package/types/generated/session.d.ts +16 -0
  59. package/types/{synthetic-session.d.ts → generated/synthetic-session.d.ts} +15 -1
  60. package/types/{types.d.ts → generated/types.d.ts} +145 -2
  61. package/LICENSE +0 -21
  62. package/platforms/macos/src/CameraOwnership.swift +0 -22
  63. package/platforms/macos/src/PhotoCaptureLifecycle.swift +0 -34
  64. package/platforms/macos/src/XplatCameraHost.swift +0 -639
  65. package/platforms/macos/src/XplatPhotoCaptureSheet.swift +0 -192
  66. package/types/index.d.ts +0 -48
  67. package/types/props.d.ts +0 -61
@@ -1,47 +1,48 @@
1
1
  import { File, knownFolders, path } from '@nativescript/core'
2
2
  import { CameraCaptureError } from './types'
3
3
  import { canonicalizePath } from './session-core'
4
+ import { IOSMovieWriterDriver } from './movie-writer.ios'
5
+ import { acquireRecordingHaptics } from './recording-haptics.ios'
6
+ import { observePreviewDisplay, previewLayerDisplaying } from './preview-display.ios'
7
+ import type { IOSMovieWriter } from './movie-writer.ios'
4
8
  import type {
5
- BackendCaptureRequest,
6
- BackendCaptureSink,
7
- BackendObserver,
8
- BackendPreviewListener,
9
- CameraSessionBackend,
9
+ BackendCaptureRequest,
10
+ BackendCaptureSink,
11
+ BackendObserver,
12
+ BackendPreviewListener,
13
+ CameraSessionBackend,
10
14
  } from './session-core'
11
15
 
12
16
  import type {
13
- CameraDeviceInfo,
14
- CameraInterruptionReason,
15
- CameraOrientation,
16
- CameraPermissionKind,
17
- CameraPermissionStatus,
18
- CaptureIssue,
19
- CameraSessionConfig,
20
- EffectiveCaptureConfig,
21
- MovieOutputHandle,
17
+ CameraDeviceInfo,
18
+ CameraInterruptionReason,
19
+ CameraOrientation,
20
+ CameraPermissionKind,
21
+ CameraPermissionStatus,
22
+ CaptureIssue,
23
+ CameraSessionConfig,
24
+ CameraZoomState,
25
+ EffectiveCaptureConfig,
26
+ MovieOutputHandle,
22
27
  } from './types'
23
28
 
24
29
  import {
25
- AVCaptureDevice,
26
- AVCaptureDeviceDiscoverySession,
27
- AVCaptureDeviceInput,
28
- AVCaptureMovieFileOutput,
29
- AVCaptureSession,
30
- AVCaptureVideoPreviewLayer,
31
- AVURLAsset,
32
- CGPointMake,
33
- NSBundle,
34
- NSError,
35
- NSFileManager,
36
- NSNotification,
37
- NSNotificationCenter,
38
- NSNumber,
39
- NSObject,
40
- NSOperationQueue,
41
- NSURL,
30
+ AVCaptureDevice,
31
+ AVCaptureDeviceDiscoverySession,
32
+ AVCaptureDeviceInput,
33
+ AVCaptureSession,
34
+ AVCaptureVideoPreviewLayer,
35
+ AVURLAsset,
36
+ CGPointMake,
37
+ NSBundle,
38
+ NSFileManager,
39
+ NSNotification,
40
+ NSNotificationCenter,
41
+ NSNumber,
42
+ NSOperationQueue,
43
+ NSURL,
42
44
  } from '@octane-xplat/platform/ios'
43
45
 
44
- import { AVCaptureFileOutputRecordingDelegate } from '@octane-xplat/platform/ios'
45
46
  import type { CGAffineTransform, NSObjectProtocol } from '@octane-xplat/platform/ios'
46
47
 
47
48
  // AVAuthorizationStatus numeric values — the ambient const enum cannot be
@@ -55,10 +56,9 @@ const authorizationAuthorized = 3
55
56
  // the handful of C functions this adapter needs instead of referencing the
56
57
  // full typings.
57
58
  declare function CMTimeGetSeconds(time: any): number
58
- declare function CMTimeMakeWithSeconds(seconds: number, preferredTimescale: number): any
59
59
  declare function CMVideoFormatDescriptionGetDimensions(videoDesc: any): {
60
- width: number
61
- height: number
60
+ width: number
61
+ height: number
62
62
  }
63
63
 
64
64
  // Ambient const enums cannot be read under verbatimModuleSyntax — keep the
@@ -75,7 +75,6 @@ const interruptionAudioDeviceInUseByAnotherClient = 2
75
75
  const interruptionVideoDeviceInUseByAnotherClient = 3
76
76
  const interruptionVideoDeviceNotAvailableWithMultipleForegroundApps = 4
77
77
  const interruptionVideoDeviceNotAvailableDueToSystemPressure = 5
78
- const avErrorMaximumDurationReached = -11810
79
78
  const videoStabilizationModeAuto = -1
80
79
 
81
80
  // AVCaptureFocusMode/AVCaptureExposureMode numeric values — tap-to-focus
@@ -84,162 +83,157 @@ const focusModeAutoFocus = 1
84
83
  const exposureModeAutoExpose = 1
85
84
 
86
85
  const mediaTypeFor = (kind: CameraPermissionKind): string =>
87
- kind === 'camera' ? AVMediaTypeVideo : AVMediaTypeAudio
86
+ kind === 'camera' ? AVMediaTypeVideo : AVMediaTypeAudio
88
87
 
89
88
  const usageKeyFor = (kind: CameraPermissionKind): string =>
90
- kind === 'camera' ? 'NSCameraUsageDescription' : 'NSMicrophoneUsageDescription'
89
+ kind === 'camera' ? 'NSCameraUsageDescription' : 'NSMicrophoneUsageDescription'
91
90
 
92
91
  const readPermission = (kind: CameraPermissionKind): CameraPermissionStatus => {
93
- const status = AVCaptureDevice.authorizationStatusForMediaType(
94
- mediaTypeFor(kind),
95
- ) as unknown as number
96
-
97
- switch (status) {
98
- case authorizationAuthorized:
99
- return 'granted'
100
- case authorizationDenied:
101
- return 'denied'
102
- case authorizationRestricted:
103
- return 'restricted'
104
- case authorizationNotDetermined:
105
- return 'notDetermined'
106
- default:
107
- return 'unknown'
108
- }
92
+ const status = AVCaptureDevice.authorizationStatusForMediaType(
93
+ mediaTypeFor(kind),
94
+ ) as unknown as number
95
+
96
+ switch (status) {
97
+ case authorizationAuthorized:
98
+ return 'granted'
99
+ case authorizationDenied:
100
+ return 'denied'
101
+ case authorizationRestricted:
102
+ return 'restricted'
103
+ case authorizationNotDetermined:
104
+ return 'notDetermined'
105
+ default:
106
+ return 'unknown'
107
+ }
109
108
  }
110
109
 
111
110
  const requestAccess = (kind: CameraPermissionKind): Promise<CameraPermissionStatus> => {
112
- const declaration = NSBundle.mainBundle.objectForInfoDictionaryKey(usageKeyFor(kind))
113
- if (!declaration) {
114
- // Requesting access without the usage-description key crashes the
115
- // host app — refuse before reaching AVFoundation.
116
- return Promise.reject(
117
- new CameraCaptureError({
118
- kind: 'configurationMissing',
119
- operation: 'requestPermission',
120
- permission: kind,
121
- message: `Missing ${usageKeyFor(kind)} in the host app's Info.plist`,
122
- }),
123
- )
124
- }
125
-
126
- const status = readPermission(kind)
127
- if (status !== 'notDetermined') {
128
- // Repeated requests must not pretend to show a prompt the system
129
- // will not display.
130
- return Promise.resolve(status)
131
- }
132
-
133
- return new Promise<CameraPermissionStatus>((resolve) => {
134
- AVCaptureDevice.requestAccessForMediaTypeCompletionHandler(mediaTypeFor(kind), () =>
135
- resolve(readPermission(kind)),
136
- )
137
- })
111
+ const declaration = NSBundle.mainBundle.objectForInfoDictionaryKey(usageKeyFor(kind))
112
+
113
+ if (!declaration) {
114
+ // Requesting access without the usage-description key crashes the
115
+ // host app — refuse before reaching AVFoundation.
116
+ return Promise.reject(
117
+ new CameraCaptureError({
118
+ kind: 'configurationMissing',
119
+ operation: 'requestPermission',
120
+ permission: kind,
121
+ message: `Missing ${usageKeyFor(kind)} in the host app's Info.plist`,
122
+ }),
123
+ )
124
+ }
125
+
126
+ const status = readPermission(kind)
127
+
128
+ if (status !== 'notDetermined') {
129
+ // Repeated requests must not pretend to show a prompt the system
130
+ // will not display.
131
+ return Promise.resolve(status)
132
+ }
133
+
134
+ return new Promise<CameraPermissionStatus>((resolve) => {
135
+ AVCaptureDevice.requestAccessForMediaTypeCompletionHandler(mediaTypeFor(kind), () =>
136
+ resolve(readPermission(kind)),
137
+ )
138
+ })
138
139
  }
139
140
 
140
141
  const facingForPosition = (position: number): 'front' | 'back' | undefined =>
141
- position === captureDevicePositionFront
142
- ? 'front'
143
- : position === captureDevicePositionBack
144
- ? 'back'
145
- : undefined
142
+ position === captureDevicePositionFront
143
+ ? 'front'
144
+ : position === captureDevicePositionBack
145
+ ? 'back'
146
+ : undefined
146
147
 
147
148
  const listCameras = (): AVCaptureDevice[] => {
148
- const types = [
149
- AVCaptureDeviceTypeBuiltInWideAngleCamera,
150
- AVCaptureDeviceTypeBuiltInUltraWideCamera,
151
- AVCaptureDeviceTypeBuiltInTelephotoCamera,
152
- AVCaptureDeviceTypeBuiltInDualCamera,
153
- AVCaptureDeviceTypeBuiltInDualWideCamera,
154
- AVCaptureDeviceTypeBuiltInTripleCamera,
155
- AVCaptureDeviceTypeBuiltInTrueDepthCamera,
156
- ].filter((entry) => typeof entry === 'string')
157
-
158
- const discovery =
159
- AVCaptureDeviceDiscoverySession.discoverySessionWithDeviceTypesMediaTypePosition(
160
- types,
161
- AVMediaTypeVideo,
162
- captureDevicePositionUnspecified,
163
- )
164
-
165
- const devices: AVCaptureDevice[] = []
166
- const found = discovery?.devices
167
- const count = found?.count ?? 0
168
- for (let index = 0; index < count; index++) {
169
- devices.push(found.objectAtIndex(index))
170
- }
171
-
172
- if (!devices.length) {
173
- // Older runtime or no discovery support — fall back to the flat
174
- // device list so simulator-style "no camera" stays honest.
175
- const legacy = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo)
176
- for (let index = 0; index < (legacy?.count ?? 0); index++) {
177
- devices.push(legacy.objectAtIndex(index))
178
- }
179
- }
180
-
181
- return devices
149
+ const types = [
150
+ AVCaptureDeviceTypeBuiltInWideAngleCamera,
151
+ AVCaptureDeviceTypeBuiltInUltraWideCamera,
152
+ AVCaptureDeviceTypeBuiltInTelephotoCamera,
153
+ AVCaptureDeviceTypeBuiltInDualCamera,
154
+ AVCaptureDeviceTypeBuiltInDualWideCamera,
155
+ AVCaptureDeviceTypeBuiltInTripleCamera,
156
+ AVCaptureDeviceTypeBuiltInTrueDepthCamera,
157
+ ].filter((entry) => typeof entry === 'string')
158
+
159
+ const discovery =
160
+ AVCaptureDeviceDiscoverySession.discoverySessionWithDeviceTypesMediaTypePosition(
161
+ types,
162
+ AVMediaTypeVideo,
163
+ captureDevicePositionUnspecified,
164
+ )
165
+
166
+ const devices: AVCaptureDevice[] = []
167
+ const found = discovery?.devices
168
+ const count = found?.count ?? 0
169
+
170
+ for (let index = 0; index < count; index++) {
171
+ devices.push(found.objectAtIndex(index))
172
+ }
173
+
174
+ if (!devices.length) {
175
+ // Older runtime or no discovery support — fall back to the flat
176
+ // device list so simulator-style "no camera" stays honest.
177
+ const legacy = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo)
178
+
179
+ for (let index = 0; index < (legacy?.count ?? 0); index++) {
180
+ devices.push(legacy.objectAtIndex(index))
181
+ }
182
+ }
183
+
184
+ return devices
182
185
  }
183
186
 
184
187
  const selectDevice = (
185
- camera: CameraSessionConfig['camera'],
186
- devices: AVCaptureDevice[],
188
+ camera: CameraSessionConfig['camera'],
189
+ devices: AVCaptureDevice[],
187
190
  ): AVCaptureDevice | undefined => {
188
- if (camera && typeof camera === 'object' && 'deviceId' in camera) {
189
- return devices.find((device) => device.uniqueID === camera.deviceId)
190
- }
191
+ if (camera && typeof camera === 'object' && 'deviceId' in camera) {
192
+ return devices.find((device) => device.uniqueID === camera.deviceId)
193
+ }
191
194
 
192
- if (camera === 'front' || camera === 'back') {
193
- const position = camera === 'front' ? captureDevicePositionFront : captureDevicePositionBack
194
- return devices.find((device) => device.position === position)
195
- }
195
+ if (camera === 'front' || camera === 'back') {
196
+ const position = camera === 'front' ? captureDevicePositionFront : captureDevicePositionBack
196
197
 
197
- return devices.find((device) => device.position === captureDevicePositionBack) ?? devices[0]
198
- }
198
+ return devices.find((device) => device.position === position)
199
+ }
199
200
 
200
- const orientationToRotationAngle = (orientation: CameraOrientation): number | undefined =>
201
- orientation === 'portrait'
202
- ? 90
203
- : orientation === 'portraitUpsideDown'
204
- ? 270
205
- : orientation === 'landscapeLeft'
206
- ? 180
207
- : orientation === 'landscapeRight'
208
- ? 0
209
- : undefined
201
+ return devices.find((device) => device.position === captureDevicePositionBack) ?? devices[0]
202
+ }
210
203
 
211
204
  const orientationToLegacyConstant = (orientation: CameraOrientation): number | undefined =>
212
- orientation === 'portrait'
213
- ? videoOrientationPortrait
214
- : orientation === 'portraitUpsideDown'
215
- ? videoOrientationPortraitUpsideDown
216
- : orientation === 'landscapeLeft'
217
- ? videoOrientationLandscapeLeft
218
- : orientation === 'landscapeRight'
219
- ? videoOrientationLandscapeRight
220
- : undefined
205
+ orientation === 'portrait'
206
+ ? videoOrientationPortrait
207
+ : orientation === 'portraitUpsideDown'
208
+ ? videoOrientationPortraitUpsideDown
209
+ : orientation === 'landscapeLeft'
210
+ ? videoOrientationLandscapeLeft
211
+ : orientation === 'landscapeRight'
212
+ ? videoOrientationLandscapeRight
213
+ : undefined
221
214
 
222
215
  /** Derive the cardinal capture orientation from a video track's
223
216
  * preferred transform; `undefined` when it cannot be told honestly. */
224
217
  const orientationFromTransform = (transform: CGAffineTransform): CameraOrientation => {
225
- const { a, b, c, d } = transform
226
- if (a === 0 && b === 1 && c === -1 && d === 0) {
227
- return 'portrait'
228
- }
218
+ const { a, b, c, d } = transform
219
+
220
+ if (a === 0 && b === 1 && c === -1 && d === 0) {
221
+ return 'portrait'
222
+ }
229
223
 
230
- if (a === 0 && b === -1 && c === 1 && d === 0) {
231
- return 'portraitUpsideDown'
232
- }
224
+ if (a === 0 && b === -1 && c === 1 && d === 0) {
225
+ return 'portraitUpsideDown'
226
+ }
233
227
 
234
- if (a === 1 && b === 0 && c === 0 && d === 1) {
235
- return 'landscapeRight'
236
- }
228
+ if (a === 1 && b === 0 && c === 0 && d === 1) {
229
+ return 'landscapeRight'
230
+ }
237
231
 
238
- if (a === -1 && b === 0 && c === 0 && d === -1) {
239
- return 'landscapeLeft'
240
- }
232
+ if (a === -1 && b === 0 && c === 0 && d === -1) {
233
+ return 'landscapeLeft'
234
+ }
241
235
 
242
- return 'unspecified'
236
+ return 'unspecified'
243
237
  }
244
238
 
245
239
  /** Prefer Apple's automatic stabilization on a capture connection when the
@@ -248,54 +242,55 @@ const orientationFromTransform = (transform: CGAffineTransform): CameraOrientati
248
242
  * typings, so it is invoked dynamically with `supportsVideoStabilization`
249
243
  * as the older-runtime fallback. */
250
244
  const preferAutoStabilization = (connection: AVCaptureConnection | undefined | null) => {
251
- if (!connection) {
252
- return
253
- }
254
-
255
- const check = (connection as any).isVideoStabilizationModeSupported
256
- const supported =
257
- typeof check === 'function'
258
- ? Boolean(check.call(connection, videoStabilizationModeAuto))
259
- : Boolean(connection.supportsVideoStabilization)
260
-
261
- if (supported) {
262
- connection.preferredVideoStabilizationMode = videoStabilizationModeAuto
263
- }
245
+ if (!connection) {
246
+ return
247
+ }
248
+
249
+ const check = (connection as any).isVideoStabilizationModeSupported
250
+ const supported =
251
+ typeof check === 'function'
252
+ ? Boolean(check.call(connection, videoStabilizationModeAuto))
253
+ : Boolean(connection.supportsVideoStabilization)
254
+
255
+ if (supported) {
256
+ connection.preferredVideoStabilizationMode = videoStabilizationModeAuto
257
+ }
264
258
  }
265
259
 
266
260
  const mapInterruptionReason = (raw: number | undefined): CameraInterruptionReason => {
267
- switch (raw) {
268
- case interruptionVideoDeviceNotAvailableInBackground:
269
- return 'background'
270
- case interruptionAudioDeviceInUseByAnotherClient:
271
- return 'audioInUse'
272
- case interruptionVideoDeviceInUseByAnotherClient:
273
- return 'cameraInUse'
274
- case interruptionVideoDeviceNotAvailableWithMultipleForegroundApps:
275
- return 'multitasking'
276
- case interruptionVideoDeviceNotAvailableDueToSystemPressure:
277
- return 'systemPressure'
278
- default:
279
- return 'unknown'
280
- }
261
+ switch (raw) {
262
+ case interruptionVideoDeviceNotAvailableInBackground:
263
+ return 'background'
264
+ case interruptionAudioDeviceInUseByAnotherClient:
265
+ return 'audioInUse'
266
+ case interruptionVideoDeviceInUseByAnotherClient:
267
+ return 'cameraInUse'
268
+ case interruptionVideoDeviceNotAvailableWithMultipleForegroundApps:
269
+ return 'multitasking'
270
+ case interruptionVideoDeviceNotAvailableDueToSystemPressure:
271
+ return 'systemPressure'
272
+ default:
273
+ return 'unknown'
274
+ }
281
275
  }
282
276
 
283
277
  const recordingsDirectory = (): string => {
284
- const directory = path.join(knownFolders.documents().path, 'octane-camera')
285
- if (!File.exists(directory)) {
286
- NSFileManager.defaultManager.createDirectoryAtPathWithIntermediateDirectoriesAttributesError(
287
- directory,
288
- true,
289
- null,
290
- undefined,
291
- )
292
- }
293
-
294
- return directory
278
+ const directory = path.join(knownFolders.documents().path, 'octane-camera')
279
+
280
+ if (!File.exists(directory)) {
281
+ NSFileManager.defaultManager.createDirectoryAtPathWithIntermediateDirectoriesAttributesError(
282
+ directory,
283
+ true,
284
+ null,
285
+ undefined,
286
+ )
287
+ }
288
+
289
+ return directory
295
290
  }
296
291
 
297
292
  const hasUsageDeclaration = (kind: CameraPermissionKind): boolean =>
298
- Boolean(NSBundle.mainBundle.objectForInfoDictionaryKey(usageKeyFor(kind)))
293
+ Boolean(NSBundle.mainBundle.objectForInfoDictionaryKey(usageKeyFor(kind)))
299
294
 
300
295
  const minFreeDiskBytes = 64 * 1024 * 1024
301
296
 
@@ -304,955 +299,1312 @@ const minFreeDiskBytes = 64 * 1024 * 1024
304
299
  * boolean), not an NSNumber instance. Accept either shape so numeric reads
305
300
  * stay correct under both conventions. */
306
301
  const numericValue = (value: unknown): number | undefined => {
307
- try {
308
- if (typeof value === 'number') {
309
- return value
310
- }
311
-
312
- if (typeof value === 'boolean') {
313
- return value ? 1 : 0
314
- }
315
-
316
- const boxed = value as NSNumber | undefined
317
- const raw = boxed?.longLongValue ?? boxed?.doubleValue
318
- return typeof raw === 'number' ? raw : undefined
319
- } catch {
320
- return undefined
321
- }
302
+ try {
303
+ if (typeof value === 'number') {
304
+ return value
305
+ }
306
+
307
+ if (typeof value === 'boolean') {
308
+ return value ? 1 : 0
309
+ }
310
+
311
+ const boxed = value as NSNumber | undefined
312
+ const raw = boxed?.longLongValue ?? boxed?.doubleValue
313
+
314
+ return typeof raw === 'number' ? raw : undefined
315
+ } catch {
316
+ return undefined
317
+ }
322
318
  }
323
319
 
324
320
  const freeDiskBytes = (): number => {
325
- try {
326
- const attributes = NSFileManager.defaultManager.attributesOfFileSystemForPathError(
327
- knownFolders.documents().path,
328
- undefined,
329
- )
330
-
331
- return numericValue(attributes?.objectForKey(NSFileSystemFreeSize)) ?? Number.MAX_SAFE_INTEGER
332
- } catch {
333
- return Number.MAX_SAFE_INTEGER
334
- }
321
+ try {
322
+ const attributes = NSFileManager.defaultManager.attributesOfFileSystemForPathError(
323
+ knownFolders.documents().path,
324
+ undefined,
325
+ )
326
+
327
+ return numericValue(attributes?.objectForKey(NSFileSystemFreeSize)) ?? Number.MAX_SAFE_INTEGER
328
+ } catch {
329
+ return Number.MAX_SAFE_INTEGER
330
+ }
335
331
  }
336
332
 
337
- /** iOS adapter: one AVCaptureSession shared between the attached preview
338
- * and a single AVCaptureMovieFileOutput capture attempt. */
339
- export function createSessionBackend(config: CameraSessionConfig): CameraSessionBackend {
340
- let currentConfig = { ...config }
341
- let session: AVCaptureSession | undefined
342
- let videoInput: AVCaptureDeviceInput | undefined
343
- let audioInput: AVCaptureDeviceInput | undefined
344
- let movieOutput: AVCaptureMovieFileOutput | undefined
345
- let previewLayer: AVCaptureVideoPreviewLayer | undefined
346
- let previewHost: any
347
- let detachFrame: (() => void) | undefined
348
- let previewReadyFlag = false
349
- let device: AVCaptureDevice | undefined
350
- let observer: BackendObserver | undefined
351
- let observers: NSObjectProtocol[] = []
352
- let captureSink: BackendCaptureSink | undefined
353
- let captureRequest: BackendCaptureRequest | undefined
354
- let limitRequested = false
355
- let noDurationLimit: any
356
- let interrupted = false
357
-
358
- const RecordingDelegate = (NSObject as any).extend(
359
- {
360
- captureOutputDidStartRecordingToOutputFileAtURLFromConnections(
361
- _output: unknown,
362
- _url: unknown,
363
- _connections: unknown,
364
- ) {
365
- onCaptureStarted()
366
- },
367
- captureOutputDidFinishRecordingToOutputFileAtURLFromConnectionsError(
368
- _output: unknown,
369
- url: NSURL,
370
- _connections: unknown,
371
- error: NSError | null,
372
- ) {
373
- onCaptureFinished(url, error)
374
- },
375
- },
376
- { protocols: [AVCaptureFileOutputRecordingDelegate] },
377
- )
378
-
379
- const recordingDelegate = RecordingDelegate.new()
380
-
381
- const emitIssue = (
382
- kind: CaptureIssue['kind'],
383
- operation: string,
384
- message: string,
385
- cause?: unknown,
386
- ): CaptureIssue => ({
387
- kind,
388
- operation,
389
- message,
390
- cause,
391
- })
392
-
393
- const notify = (phase: 'began' | 'ended', reason?: CameraInterruptionReason) => {
394
- interrupted = phase === 'began'
395
- observer?.interruption(phase, reason)
396
- observer?.previewReady(previewReadyFlag && !interrupted)
397
- }
398
-
399
- const observeSession = (target: AVCaptureSession) => {
400
- const center = NSNotificationCenter.defaultCenter
401
- const add = (name: string, object: unknown, handler: (note: NSNotification) => void) => {
402
- observers.push(
403
- center.addObserverForNameObjectQueueUsingBlock(
404
- name,
405
- object as any,
406
- NSOperationQueue.mainQueue,
407
- handler,
408
- ),
409
- )
410
- }
411
-
412
- add(AVCaptureSessionWasInterruptedNotification, target, (note) => {
413
- const raw = note.userInfo?.objectForKey(AVCaptureSessionInterruptionReasonKey)
414
-
415
- notify('began', mapInterruptionReason(numericValue(raw)))
416
- })
417
-
418
- add(AVCaptureSessionInterruptionEndedNotification, target, () => {
419
- notify('ended')
420
- })
421
-
422
- add(AVCaptureSessionRuntimeErrorNotification, target, () => {
423
- observer?.availability(false)
424
- })
425
-
426
- // Filter by the ACTIVE device — `device` is reassigned on
427
- // configure(), so an observer bound to the captured object would
428
- // keep reporting on the stale one while the active camera's
429
- // disconnect went unreported (and any device's connect reported
430
- // availability(true)).
431
- add(AVCaptureDeviceWasDisconnectedNotification, null, (note) => {
432
- if (device && note.object === device) {
433
- observer?.availability(false)
434
- }
435
- })
436
-
437
- add(AVCaptureDeviceWasConnectedNotification, null, (note) => {
438
- if (device && note.object === device) {
439
- observer?.availability(true)
440
- }
441
- })
442
-
443
- add(UIApplicationDidEnterBackgroundNotification, null, () => {
444
- notify('began', 'background')
445
- })
446
-
447
- add(UIApplicationWillEnterForegroundNotification, null, () => {
448
- notify('ended', 'background')
449
- })
450
- }
451
-
452
- const clearObservers = () => {
453
- const center = NSNotificationCenter.defaultCenter
454
- for (const entry of observers) {
455
- center.removeObserver(entry)
456
- }
457
-
458
- observers = []
459
- }
460
-
461
- const supportedPreset = (target: AVCaptureSession, captureDevice: AVCaptureDevice) =>
462
- target.canSetSessionPreset(AVCaptureSessionPreset1280x720) &&
463
- captureDevice.supportsAVCaptureSessionPreset(AVCaptureSessionPreset1280x720)
464
-
465
- /** Resolve the effective standard profile for the current camera:
466
- * 720p/30 when the device supports it, otherwise the device's own
467
- * active format disclosed honestly. */
468
- const standardProfile = (captureDevice: AVCaptureDevice | undefined) => {
469
- if (captureDevice && session && supportedPreset(session, captureDevice)) {
470
- return { width: 1280, height: 720, frameRate: 30 }
471
- }
472
-
473
- const format = captureDevice?.activeFormat
474
- const dimensions = format
475
- ? CMVideoFormatDescriptionGetDimensions(format.formatDescription)
476
- : undefined
477
-
478
- const range = captureDevice?.activeVideoMinFrameDuration
479
- const frameRate =
480
- range && range.timescale > 0 && range.value > 0
481
- ? Math.round(range.timescale / range.value)
482
- : 30
483
-
484
- return {
485
- width: dimensions?.width ?? 1280,
486
- height: dimensions?.height ?? 720,
487
- frameRate,
488
- }
489
- }
490
-
491
- const ensureAudioInput = (target: AVCaptureSession): boolean => {
492
- if (audioInput) {
493
- return true
494
- }
495
-
496
- const mic = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeAudio)
497
- if (!mic) {
498
- return false
499
- }
500
-
501
- const input = AVCaptureDeviceInput.deviceInputWithDeviceError(mic, undefined)
502
- if (!input || !target.canAddInput(input)) {
503
- return false
504
- }
505
-
506
- target.addInput(input)
507
- audioInput = input
508
- return true
509
- }
510
-
511
- const ensureSession = (): AVCaptureSession => {
512
- if (session) {
513
- return session
514
- }
515
-
516
- const target = AVCaptureSession.new()
517
- target.beginConfiguration()
518
- device = selectDevice(currentConfig.camera, listCameras())
519
- if (!device) {
520
- target.commitConfiguration()
521
- throw new CameraCaptureError({
522
- kind: 'unavailable',
523
- operation: 'startPreview',
524
- message: 'No camera device is available',
525
- })
526
- }
527
-
528
- if (supportedPreset(target, device)) {
529
- target.sessionPreset = AVCaptureSessionPreset1280x720
530
- }
531
-
532
- const input = AVCaptureDeviceInput.deviceInputWithDeviceError(device, undefined)
533
- if (!input || !target.canAddInput(input)) {
534
- target.commitConfiguration()
535
- throw new CameraCaptureError({
536
- kind: 'unavailable',
537
- operation: 'startPreview',
538
- message: 'Camera input is unavailable',
539
- })
540
- }
541
-
542
- target.addInput(input)
543
- videoInput = input
544
- const output = AVCaptureMovieFileOutput.new()
545
- if (target.canAddOutput(output)) {
546
- target.addOutput(output)
547
- movieOutput = output
548
- noDurationLimit = output.maxRecordedDuration
549
- } else {
550
- target.commitConfiguration()
551
- throw new CameraCaptureError({
552
- kind: 'unsupportedPlatform',
553
- operation: 'startPreview',
554
- message: 'Movie file output is unavailable on this device',
555
- })
556
- }
557
-
558
- if (currentConfig.audio && readPermission('microphone') === 'granted') {
559
- ensureAudioInput(target)
560
- }
561
-
562
- target.commitConfiguration()
563
- session = target
564
- observeSession(target)
565
- return target
566
- }
567
-
568
- const stopSessionIfIdle = () => {
569
- if (!session || captureSink || previewHost) {
570
- return
571
- }
572
-
573
- session.stopRunning()
574
- clearObservers()
575
- if (interrupted) {
576
- // The 'ended' notification can be lost when the session is
577
- // torn down mid-interruption — report it so the flag does not
578
- // wedge previewReady/startRecording for the next session.
579
- notify('ended')
580
- }
581
-
582
- // A destroyed session's runtime error must not wedge the next
583
- // one — AVCaptureDeviceWasConnected never fires for built-in
584
- // cameras, so cameraAvailable would otherwise stay false forever.
585
- observer?.availability(true)
586
-
587
- session = undefined
588
- videoInput = undefined
589
- audioInput = undefined
590
- movieOutput = undefined
591
- previewLayer = undefined
592
- device = undefined
593
- }
594
-
595
- const onCaptureStarted = () => {
596
- const request = captureRequest
597
- const sink = captureSink
598
- if (!request || !sink || !device) {
599
- return
600
- }
601
-
602
- const profile = standardProfile(device)
603
- const configuration: EffectiveCaptureConfig = {
604
- cameraId: device.uniqueID,
605
- facing: facingForPosition(device.position),
606
- audio: request.audio && audioInput !== undefined,
607
- width: profile.width,
608
- height: profile.height,
609
- frameRate: profile.frameRate,
610
- orientation: request.orientation ?? 'unspecified',
611
- mimeType: 'video/quicktime',
612
- container: 'mov',
613
- }
614
-
615
- sink.started(configuration)
616
- }
617
-
618
- const onCaptureFinished = (url: NSURL, error: NSError | null) => {
619
- const request = captureRequest
620
- const sink = captureSink
621
- captureRequest = undefined
622
- captureSink = undefined
623
- if (!request || !sink) {
624
- return
625
- }
626
-
627
- const filePath = url?.path ? String(url.path) : ''
628
- const succeeded =
629
- !error ||
630
- numericValue(error.userInfo?.objectForKey(AVErrorRecordingSuccessfullyFinishedKey)) === 1
631
-
632
- if (!succeeded) {
633
- // Clean up only the file this attempt created — never a
634
- // pre-existing app file (admission rejects existing paths).
635
- try {
636
- if (filePath && File.exists(filePath)) {
637
- NSFileManager.defaultManager.removeItemAtPathError(filePath, undefined)
638
- }
639
- } catch {
640
- // Temporary leftovers are reclaimed by the OS.
641
- }
642
-
643
- sink.settled({
644
- kind: 'failed',
645
- stage: 'capture',
646
- issue: emitIssue(
647
- 'captureFailed',
648
- 'finalize',
649
- error?.localizedDescription ?? 'Movie recording did not complete',
650
- error,
651
- ),
652
- })
653
-
654
- stopSessionIfIdle()
655
- return
656
- }
657
-
658
- const limitReached = limitRequested && error?.code === avErrorMaximumDurationReached
659
- try {
660
- const asset = AVURLAsset.assetWithURL(url)
661
- const durationSeconds = asset ? CMTimeGetSeconds(asset.duration) : 0
662
- const videoTracks = asset?.tracksWithMediaType(AVMediaTypeVideo)
663
- const audioTracks = asset?.tracksWithMediaType(AVMediaTypeAudio)
664
- const track = videoTracks && videoTracks.count > 0 ? videoTracks.objectAtIndex(0) : null
665
- if (!track || !(durationSeconds > 0)) {
666
- try {
667
- if (filePath && File.exists(filePath)) {
668
- NSFileManager.defaultManager.removeItemAtPathError(filePath, undefined)
669
- }
670
- } catch {
671
- // Temporary leftovers are reclaimed by the OS.
672
- }
673
-
674
- sink.settled({
675
- kind: 'failed',
676
- stage: 'capture',
677
- issue: emitIssue('noMedia', 'finalize', 'The finalized movie contains no playable media'),
678
- })
679
-
680
- stopSessionIfIdle()
681
- return
682
- }
683
-
684
- const naturalSize = track.naturalSize
685
- const transform = track.preferredTransform
686
- const orientation =
687
- request.orientation && request.orientation !== 'unspecified'
688
- ? request.orientation
689
- : orientationFromTransform(transform)
690
-
691
- const rotated = Math.abs(transform.b) === 1 && Math.abs(transform.c) === 1
692
- const width = rotated ? naturalSize.height : naturalSize.width
693
- const height = rotated ? naturalSize.width : naturalSize.height
694
- if (request.audio && !(audioTracks && audioTracks.count > 0)) {
695
- // Requested audio missing must not masquerade as silent
696
- // capture — classify as failure, not a successful clip.
697
- try {
698
- if (filePath && File.exists(filePath)) {
699
- NSFileManager.defaultManager.removeItemAtPathError(filePath, undefined)
700
- }
701
- } catch {
702
- // Temporary leftovers are reclaimed by the OS.
703
- }
704
-
705
- sink.settled({
706
- kind: 'failed',
707
- stage: 'capture',
708
- issue: emitIssue(
709
- 'captureFailed',
710
- 'finalize',
711
- 'Requested audio track is missing from the finalized movie',
712
- ),
713
- })
714
-
715
- stopSessionIfIdle()
716
- return
717
- }
718
-
719
- sink.settled({
720
- kind: 'clip',
721
- output: {
722
- kind: 'nativeFile',
723
- resourceId: `file:${filePath}`,
724
- fileUrl: `file://${filePath}`,
725
- },
726
- mimeType: 'video/quicktime',
727
- durationMs: Math.round(durationSeconds * 1000),
728
- width,
729
- height,
730
- orientation,
731
- hasAudio: request.audio && (audioTracks?.count ?? 0) > 0,
732
- limitReached,
733
- })
734
- } catch (cause) {
735
- sink.settled({
736
- kind: 'failed',
737
- stage: 'finalization',
738
- issue: emitIssue(
739
- 'finalizationFailed',
740
- 'finalize',
741
- cause instanceof Error ? cause.message : String(cause),
742
- cause,
743
- ),
744
- })
745
- }
746
-
747
- stopSessionIfIdle()
748
- }
749
-
750
- return {
751
- platform: 'ios',
752
- supported: typeof AVCaptureMovieFileOutput !== 'undefined',
753
- checkPermission: async (kind) => {
754
- if (!hasUsageDeclaration(kind)) {
755
- // Missing declarations are a setup error, not a permission
756
- // status — surface through start/configure failures instead of
757
- // pretending a status.
758
- return 'unknown'
759
- }
760
-
761
- return readPermission(kind)
762
- },
763
- requestPermission: (kind) => requestAccess(kind),
764
- getCapabilities: async () => {
765
- const devices = listCameras()
766
- const cameras: CameraDeviceInfo[] = devices.map((entry) => ({
767
- id: entry.uniqueID,
768
- label: entry.localizedName ?? entry.uniqueID,
769
- facing: facingForPosition(entry.position),
770
- }))
771
-
772
- const selected = device ?? selectDevice(currentConfig.camera, devices)
773
- const profile = selected
774
- ? (() => {
775
- const probe = AVCaptureSession.new()
776
- probe.beginConfiguration()
777
- const supported = supportedPreset(probe, selected)
778
- probe.commitConfiguration()
779
- return supported
780
- ? { width: 1280, height: 720, frameRate: 30 }
781
- : standardProfile(selected)
782
- })()
783
- : { width: 1280, height: 720, frameRate: 30 }
784
-
785
- const available = cameras.length > 0
786
- const supported = typeof AVCaptureMovieFileOutput !== 'undefined' && available
787
- return {
788
- supported,
789
- reason: !available
790
- ? 'No camera device is available on this host'
791
- : typeof AVCaptureMovieFileOutput === 'undefined'
792
- ? 'Movie file output is unsupported by this runtime'
793
- : undefined,
794
- available,
795
- cameras,
796
- profiles: [{ profile: 'standard', ...profile }],
797
- audio: typeof AVCaptureDevice.defaultDeviceWithMediaType === 'function',
798
- focusPointOfInterest: selected?.focusPointOfInterestSupported === true,
799
- exposurePointOfInterest: selected?.exposurePointOfInterestSupported === true,
800
- orientations: ['portrait', 'portraitUpsideDown', 'landscapeLeft', 'landscapeRight'],
801
- durationLimit: 'native',
802
- elapsedTime: 'nativeMedia',
803
- output: {
804
- mimeType: 'video/quicktime',
805
- container: 'mov',
806
- storage: 'appPrivateFile',
807
- destinationFileUrl: true,
808
- },
809
- }
810
- },
811
- previewReady: () => previewReadyFlag && !interrupted,
812
- attachPreview: (host, listener?: BackendPreviewListener) => {
813
- let target: AVCaptureSession
814
- try {
815
- target = ensureSession()
816
- } catch (error) {
817
- throw error instanceof CameraCaptureError
818
- ? error
819
- : new CameraCaptureError({
820
- kind: 'unavailable',
821
- operation: 'startPreview',
822
- message: error instanceof Error ? error.message : String(error),
823
- cause: error,
824
- })
825
- }
826
-
827
- const view = host as any
828
- const nativeView = view?.ios ?? view?.nativeViewProtected
829
- if (!nativeView?.layer) {
830
- throw new CameraCaptureError({
831
- kind: 'invalidArgument',
832
- operation: 'attachPreview',
833
- message: 'Camera preview host is unavailable',
834
- })
835
- }
836
-
837
- const layer = AVCaptureVideoPreviewLayer.layerWithSession(target)
838
- layer.videoGravity = AVLayerVideoGravityResizeAspectFill
839
- const connection = layer.connection
840
- if (connection) {
841
- connection.automaticallyAdjustsVideoMirroring = false
842
- if (connection.supportsVideoMirroring) {
843
- connection.videoMirrored = device?.position === captureDevicePositionFront
844
- }
845
-
846
- preferAutoStabilization(connection)
847
- }
848
-
849
- nativeView.layer.addSublayer(layer)
850
- previewLayer = layer
851
- previewHost = view
852
- const updateFrame = () => {
853
- layer.frame = nativeView.bounds
854
- }
855
-
856
- detachFrame = () => view.off?.('layoutChanged', updateFrame)
857
- view.on?.('layoutChanged', updateFrame)
858
- updateFrame()
859
- target.startRunning()
860
- previewReadyFlag = true
861
- observer?.previewReady(true)
862
- listener?.onReady?.()
863
- return () => {
864
- previewReadyFlag = false
865
- view.off?.('layoutChanged', updateFrame)
866
- layer.removeFromSuperlayer()
867
- previewLayer = undefined
868
- previewHost = undefined
869
- detachFrame = undefined
870
- observer?.previewReady(false)
871
- stopSessionIfIdle()
872
- }
873
- },
874
- configure: (next) => {
875
- const previous = currentConfig
876
- currentConfig = { ...next }
877
- const target = session
878
- if (!target || !device) {
879
- return
880
- }
881
-
882
- target.beginConfiguration()
883
- const wanted = selectDevice(next.camera ?? previous.camera, listCameras())
884
- if (wanted && wanted !== device && videoInput) {
885
- const input = AVCaptureDeviceInput.deviceInputWithDeviceError(wanted, undefined)
886
- if (input && target.canAddInput(input)) {
887
- target.removeInput(videoInput)
888
- target.addInput(input)
889
- videoInput = input
890
- device = wanted
891
- }
892
- }
893
-
894
- if (next.audio === true && readPermission('microphone') === 'granted') {
895
- ensureAudioInput(target)
896
- } else if (next.audio === false && audioInput) {
897
- target.removeInput(audioInput)
898
- audioInput = undefined
899
- }
900
-
901
- target.commitConfiguration()
902
- // Swapping the video input recreates the preview connection — the
903
- // stabilization preference must be restated.
904
- preferAutoStabilization(previewLayer?.connection)
905
- },
906
- focusAtPoint: (point) => {
907
- const captureDevice = device
908
- const layer = previewLayer
909
- if (!captureDevice || !layer) {
910
- return
911
- }
912
-
913
- // Front cameras are commonly fixed-focus — meter only the
914
- // dimensions the device actually supports.
915
- const focus =
916
- captureDevice.focusPointOfInterestSupported === true &&
917
- captureDevice.isFocusModeSupported?.(focusModeAutoFocus) !== false
918
-
919
- const expose =
920
- captureDevice.exposurePointOfInterestSupported === true &&
921
- captureDevice.isExposureModeSupported?.(exposureModeAutoExpose) !== false
922
-
923
- if (!focus && !expose) {
924
- return
925
- }
926
-
927
- // The preview layer converts view space into device space —
928
- // aspect-fill cropping, sensor orientation, and the front
929
- // camera's mirrored connection are all accounted for. Without
930
- // it there is no honest mapping, so bail rather than meter the
931
- // wrong point.
932
- const bounds = layer.bounds
933
- const layerPoint = CGPointMake(point.x * bounds.size.width, point.y * bounds.size.height)
934
-
935
- if (typeof layer.captureDevicePointOfInterestForPoint !== 'function') {
936
- return
937
- }
938
-
939
- const devicePoint = layer.captureDevicePointOfInterestForPoint(layerPoint)
940
-
941
- try {
942
- if (captureDevice.lockForConfiguration?.(undefined) !== true) {
943
- return
944
- }
945
-
946
- // Single-shot AF/AE at the point — the Apple AVCam
947
- // tap-to-focus convention; the device locks after metering.
948
- if (focus) {
949
- captureDevice.focusPointOfInterest = devicePoint
950
- captureDevice.focusMode = focusModeAutoFocus
951
- }
952
-
953
- if (expose) {
954
- captureDevice.exposurePointOfInterest = devicePoint
955
- captureDevice.exposureMode = exposureModeAutoExpose
956
- }
957
-
958
- captureDevice.unlockForConfiguration()
959
- } catch {
960
- // A missed metering pass must not fault the session.
961
- }
962
- },
963
- startCapture: (request, sink) => {
964
- const target = session
965
- if (!target || !movieOutput || !device) {
966
- sink.settled({
967
- kind: 'failed',
968
- stage: 'preparation',
969
- issue: emitIssue('unavailable', 'startRecording', 'The camera session is not running'),
970
- })
971
-
972
- return
973
- }
974
-
975
- if (!hasUsageDeclaration('camera')) {
976
- sink.settled({
977
- kind: 'failed',
978
- stage: 'preparation',
979
- issue: emitIssue(
980
- 'configurationMissing',
981
- 'startRecording',
982
- "Missing NSCameraUsageDescription in the host app's Info.plist",
983
- ),
984
- })
985
-
986
- return
987
- }
988
-
989
- if (request.audio) {
990
- if (!hasUsageDeclaration('microphone')) {
991
- sink.settled({
992
- kind: 'failed',
993
- stage: 'preparation',
994
- issue: emitIssue(
995
- 'configurationMissing',
996
- 'startRecording',
997
- "Missing NSMicrophoneUsageDescription in the host app's Info.plist",
998
- ),
999
- })
1000
-
1001
- return
1002
- }
1003
-
1004
- const micStatus = readPermission('microphone')
1005
- if (micStatus !== 'granted') {
1006
- sink.settled({
1007
- kind: 'failed',
1008
- stage: 'preparation',
1009
- issue: emitIssue(
1010
- micStatus === 'restricted' ? 'permissionRestricted' : 'permissionDenied',
1011
- 'startRecording',
1012
- `Microphone permission is ${micStatus}`,
1013
- { permission: 'microphone' },
1014
- ),
1015
- })
1016
-
1017
- return
1018
- }
1019
-
1020
- if (!audioInput) {
1021
- target.beginConfiguration()
1022
- const added = ensureAudioInput(target)
1023
- target.commitConfiguration()
1024
- if (!added) {
1025
- sink.settled({
1026
- kind: 'failed',
1027
- stage: 'preparation',
1028
- issue: emitIssue(
1029
- 'unavailable',
1030
- 'startRecording',
1031
- 'No audio input device is available',
1032
- ),
1033
- })
1034
-
1035
- return
1036
- }
1037
- }
1038
- }
1039
-
1040
- const connection = movieOutput.connectionWithMediaType(AVMediaTypeVideo)
1041
- if (request.orientation) {
1042
- const angle = orientationToRotationAngle(request.orientation)
1043
- const legacy = orientationToLegacyConstant(request.orientation)
1044
- let applied = false
1045
- if (
1046
- connection &&
1047
- angle !== undefined &&
1048
- typeof connection.isVideoRotationAngleSupported === 'function' &&
1049
- connection.isVideoRotationAngleSupported(angle)
1050
- ) {
1051
- connection.videoRotationAngle = angle
1052
- applied = true
1053
- } else if (connection && legacy !== undefined && connection.supportsVideoOrientation) {
1054
- connection.videoOrientation = legacy
1055
- applied = true
1056
- }
1057
-
1058
- if (!applied) {
1059
- sink.settled({
1060
- kind: 'failed',
1061
- stage: 'preparation',
1062
- issue: emitIssue(
1063
- 'unsupportedConfiguration',
1064
- 'startRecording',
1065
- `Orientation '${request.orientation}' is not supported by this connection`,
1066
- ),
1067
- })
1068
-
1069
- return
1070
- }
1071
- }
1072
-
1073
- if (connection) {
1074
- // Recorded output is unmirrored, including the front camera —
1075
- // the preview may stay mirrored under its existing behavior.
1076
- connection.automaticallyAdjustsVideoMirroring = false
1077
- if (connection.supportsVideoMirroring) {
1078
- connection.videoMirrored = false
1079
- }
1080
-
1081
- preferAutoStabilization(connection)
1082
- }
1083
-
1084
- let filePath: string
1085
- if (request.destinationPath) {
1086
- // Durable output stays app-private — canonicalize first so a
1087
- // '..' segment cannot keep the Documents prefix while
1088
- // resolving outside it.
1089
- const destination = canonicalizePath(request.destinationPath)
1090
- const documents = knownFolders.documents().path
1091
- const inside = destination.startsWith(`${documents}/`)
1092
- const directory = destination.slice(0, destination.lastIndexOf('/'))
1093
- if (!inside || !File.exists(directory) || File.exists(destination)) {
1094
- sink.settled({
1095
- kind: 'failed',
1096
- stage: 'preparation',
1097
- issue: emitIssue(
1098
- 'destinationUnavailable',
1099
- 'startRecording',
1100
- !inside
1101
- ? 'destinationFileUrl must resolve inside the app-private documents directory'
1102
- : File.exists(destination)
1103
- ? 'destinationFileUrl already exists'
1104
- : 'destinationFileUrl directory does not exist',
1105
- ),
1106
- })
1107
-
1108
- return
1109
- }
1110
-
1111
- filePath = destination
1112
- } else {
1113
- try {
1114
- filePath = path.join(
1115
- recordingsDirectory(),
1116
- `clip-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.mov`,
1117
- )
1118
- } catch (cause) {
1119
- sink.settled({
1120
- kind: 'failed',
1121
- stage: 'preparation',
1122
- issue: emitIssue(
1123
- 'destinationUnavailable',
1124
- 'startRecording',
1125
- cause instanceof Error ? cause.message : String(cause),
1126
- cause,
1127
- ),
1128
- })
1129
-
1130
- return
1131
- }
1132
- }
1133
-
1134
- if (freeDiskBytes() < minFreeDiskBytes) {
1135
- sink.settled({
1136
- kind: 'failed',
1137
- stage: 'preparation',
1138
- issue: emitIssue(
1139
- 'insufficientStorage',
1140
- 'startRecording',
1141
- 'Not enough local storage for a movie recording',
1142
- ),
1143
- })
1144
-
1145
- return
1146
- }
1147
-
1148
- limitRequested = request.maximumDurationMs !== undefined
1149
- movieOutput.maxRecordedDuration =
1150
- request.maximumDurationMs !== undefined
1151
- ? CMTimeMakeWithSeconds(request.maximumDurationMs / 1000, 600)
1152
- : (noDurationLimit ?? movieOutput.maxRecordedDuration)
1153
-
1154
- captureRequest = request
1155
- captureSink = sink
1156
- try {
1157
- movieOutput.startRecordingToOutputFileURLRecordingDelegate(
1158
- NSURL.fileURLWithPath(filePath),
1159
- recordingDelegate,
1160
- )
1161
- } catch (cause) {
1162
- captureRequest = undefined
1163
- captureSink = undefined
1164
- sink.settled({
1165
- kind: 'failed',
1166
- stage: 'preparation',
1167
- issue: emitIssue(
1168
- 'captureFailed',
1169
- 'startRecording',
1170
- cause instanceof Error ? cause.message : String(cause),
1171
- cause,
1172
- ),
1173
- })
1174
- }
1175
- },
1176
- stopCapture: () => {
1177
- try {
1178
- if (movieOutput?.recording) {
1179
- movieOutput.stopRecording()
1180
- }
1181
- } catch {
1182
- // Settlement still arrives through the delegate callback.
1183
- }
1184
- },
1185
- elapsedMs: () => {
1186
- try {
1187
- const duration = movieOutput?.recordedDuration
1188
- if (!duration) {
1189
- return 0
1190
- }
1191
-
1192
- return Math.max(0, Math.round(CMTimeGetSeconds(duration) * 1000))
1193
- } catch {
1194
- return 0
1195
- }
1196
- },
1197
- openOutput: async (output) => {
1198
- if (output.kind !== 'nativeFile') {
1199
- throw new CameraCaptureError({
1200
- kind: 'invalidArgument',
1201
- operation: 'openOutput',
1202
- message: 'Only file-backed output can be opened on iOS',
1203
- })
1204
- }
1205
-
1206
- const filePath = output.fileUrl.slice('file://'.length)
1207
- if (!File.exists(filePath)) {
1208
- throw new CameraCaptureError({
1209
- kind: 'unavailable',
1210
- operation: 'openOutput',
1211
- message: `Movie file is missing at ${output.fileUrl}`,
1212
- })
1213
- }
1214
-
1215
- const handle: MovieOutputHandle = {
1216
- url: output.fileUrl,
1217
- fileUrl: output.fileUrl,
1218
- release: () => {},
1219
- }
1220
-
1221
- return handle
1222
- },
1223
- release: async () => {
1224
- previewReadyFlag = false
1225
- detachFrame?.()
1226
- detachFrame = undefined
1227
- if (previewHost) {
1228
- try {
1229
- previewLayer?.removeFromSuperlayer()
1230
- } catch {}
1231
- }
1232
-
1233
- previewHost = undefined
1234
- previewLayer = undefined
1235
- captureRequest = undefined
1236
- captureSink = undefined
1237
- clearObservers()
1238
- interrupted = false
1239
- try {
1240
- session?.stopRunning()
1241
- } catch {}
1242
-
1243
- session = undefined
1244
- videoInput = undefined
1245
- audioInput = undefined
1246
- movieOutput = undefined
1247
- device = undefined
1248
- },
1249
- onPreviewDetached: () => {
1250
- // The view went away; if a settle is still in flight the session
1251
- // stays alive until it arrives (stopSessionIfIdle re-checks).
1252
- stopSessionIfIdle()
1253
- },
1254
- setObserver: (next) => {
1255
- observer = next
1256
- },
1257
- }
333
+ /** iOS adapter: one video session and an independent microphone session feed
334
+ * a single sample writer shared with the attached preview. */
335
+ declare const XplatSwitchingMovieWriter: { new: () => IOSMovieWriter }
336
+
337
+ export function createSessionBackend(
338
+ config: CameraSessionConfig,
339
+ writerDiagnostics?: (type: string, payload: string) => void,
340
+ ): CameraSessionBackend {
341
+ let currentConfig = { ...config }
342
+ let session: AVCaptureSession | undefined
343
+ let videoInput: AVCaptureDeviceInput | undefined
344
+ let writerHasAudio = false
345
+ let releaseRecordingHaptics: (() => void) | undefined
346
+ let previewLayer: AVCaptureVideoPreviewLayer | undefined
347
+ let previewHost: any
348
+ let detachFrame: (() => void) | undefined
349
+ let detachDisplay: (() => void) | undefined
350
+ let displayReady = false
351
+ let previewReadyFlag = false
352
+ let device: AVCaptureDevice | undefined
353
+ let observer: BackendObserver | undefined
354
+ let observers: NSObjectProtocol[] = []
355
+ let captureSink: BackendCaptureSink | undefined
356
+ let captureRequest: BackendCaptureRequest | undefined
357
+ let nativeLimitReached = false
358
+ let interrupted = false
359
+ let nativeWriter: IOSMovieWriter | undefined
360
+ let writerDriver: IOSMovieWriterDriver | undefined
361
+ let writerSourceReady = false
362
+ let initialWriterReady: (() => void) | undefined
363
+ let writerWarning: CaptureIssue | undefined
364
+ let writerRelease: Promise<void> = Promise.resolve()
365
+ /** Connection state of the video-data output feeding the writer. */
366
+ const recordingConnectionState = () => {
367
+ const outputs = session?.outputs
368
+ const connection =
369
+ outputs &&
370
+ Array.from({ length: outputs.count }, (_, index) =>
371
+ outputs.objectAtIndex(index).connectionWithMediaType(AVMediaTypeVideo),
372
+ ).find(Boolean)
373
+
374
+ return {
375
+ videoMirrored: !!connection?.videoMirrored,
376
+ orientation: connection?.videoOrientation,
377
+ preferredStabilization: connection?.preferredVideoStabilizationMode,
378
+ activeStabilization: connection?.activeVideoStabilizationMode,
379
+ previewMirrored: !!previewLayer?.connection?.videoMirrored,
380
+ previewMirrorSupported: !!previewLayer?.connection?.supportsVideoMirroring,
381
+ }
382
+ }
383
+
384
+ const mirrorPreview = () => {
385
+ const connection = previewLayer?.connection
386
+
387
+ if (connection) {
388
+ connection.automaticallyAdjustsVideoMirroring = false
389
+ if (connection.supportsVideoMirroring) {
390
+ connection.videoMirrored = device?.position === captureDevicePositionFront
391
+ }
392
+
393
+ preferAutoStabilization(connection)
394
+ }
395
+ }
396
+
397
+ const emitIssue = (
398
+ kind: CaptureIssue['kind'],
399
+ operation: string,
400
+ message: string,
401
+ cause?: unknown,
402
+ ): CaptureIssue => ({
403
+ kind,
404
+ operation,
405
+ message,
406
+ cause,
407
+ })
408
+
409
+ const notify = (phase: 'began' | 'ended', reason?: CameraInterruptionReason) => {
410
+ interrupted = phase === 'began'
411
+ observer?.interruption(phase, reason)
412
+ observer?.previewReady(previewReadyFlag && !interrupted && writerSourceReady)
413
+ }
414
+
415
+ const observeSession = (target: AVCaptureSession) => {
416
+ const center = NSNotificationCenter.defaultCenter
417
+ const add = (name: string, object: unknown, handler: (note: NSNotification) => void) => {
418
+ observers.push(
419
+ center.addObserverForNameObjectQueueUsingBlock(
420
+ name,
421
+ object as any,
422
+ NSOperationQueue.mainQueue,
423
+ handler,
424
+ ),
425
+ )
426
+ }
427
+
428
+ add(AVCaptureSessionWasInterruptedNotification, target, (note) => {
429
+ const raw = note.userInfo?.objectForKey(AVCaptureSessionInterruptionReasonKey)
430
+
431
+ notify('began', mapInterruptionReason(numericValue(raw)))
432
+ })
433
+
434
+ add(AVCaptureSessionInterruptionEndedNotification, target, () => {
435
+ notify('ended')
436
+ })
437
+
438
+ add(AVCaptureSessionRuntimeErrorNotification, target, () => {
439
+ observer?.availability(false)
440
+ })
441
+
442
+ // Filter by the ACTIVE device — `device` is reassigned on
443
+ // configure(), so an observer bound to the captured object would
444
+ // keep reporting on the stale one while the active camera's
445
+ // disconnect went unreported (and any device's connect reported
446
+ // availability(true)).
447
+ add(AVCaptureDeviceWasDisconnectedNotification, null, (note) => {
448
+ if (device && note.object === device) {
449
+ observer?.availability(false)
450
+ }
451
+ })
452
+
453
+ add(AVCaptureDeviceWasConnectedNotification, null, (note) => {
454
+ if (device && note.object === device) {
455
+ observer?.availability(true)
456
+ }
457
+ })
458
+
459
+ add(UIApplicationDidEnterBackgroundNotification, null, () => {
460
+ notify('began', 'background')
461
+ })
462
+
463
+ add(UIApplicationWillEnterForegroundNotification, null, () => {
464
+ notify('ended', 'background')
465
+ })
466
+ }
467
+
468
+ const clearObservers = () => {
469
+ const center = NSNotificationCenter.defaultCenter
470
+
471
+ for (const entry of observers) {
472
+ center.removeObserver(entry)
473
+ }
474
+
475
+ observers = []
476
+ }
477
+
478
+ const supportedPreset = (target: AVCaptureSession, captureDevice: AVCaptureDevice) =>
479
+ target.canSetSessionPreset(AVCaptureSessionPreset1280x720) &&
480
+ captureDevice.supportsAVCaptureSessionPreset(AVCaptureSessionPreset1280x720)
481
+
482
+ /** Resolve the effective standard profile for the current camera:
483
+ * 720p/30 when the device supports it, otherwise the device's own
484
+ * active format disclosed honestly. */
485
+ const standardProfile = (captureDevice: AVCaptureDevice | undefined) => {
486
+ if (captureDevice && session && supportedPreset(session, captureDevice)) {
487
+ return { width: 1280, height: 720, frameRate: 30 }
488
+ }
489
+
490
+ const format = captureDevice?.activeFormat
491
+ const dimensions = format
492
+ ? CMVideoFormatDescriptionGetDimensions(format.formatDescription)
493
+ : undefined
494
+
495
+ const range = captureDevice?.activeVideoMinFrameDuration
496
+ const frameRate =
497
+ range && range.timescale > 0 && range.value > 0
498
+ ? Math.round(range.timescale / range.value)
499
+ : 30
500
+
501
+ return {
502
+ width: dimensions?.width ?? 1280,
503
+ height: dimensions?.height ?? 720,
504
+ frameRate,
505
+ }
506
+ }
507
+
508
+ const ensureAudioInput = (): boolean => {
509
+ const optedIn = currentConfig.ios?.allowHapticsAndSystemSoundsDuringRecording === true
510
+ const acquired = optedIn && !releaseRecordingHaptics ? acquireRecordingHaptics() : undefined
511
+
512
+ try {
513
+ writerHasAudio = !!nativeWriter && !nativeWriter.configureAudio(true)
514
+ if (writerHasAudio && optedIn) {
515
+ releaseRecordingHaptics ??= acquired
516
+ } else {
517
+ acquired?.()
518
+ releaseRecordingHaptics?.()
519
+ releaseRecordingHaptics = undefined
520
+ }
521
+
522
+ return writerHasAudio
523
+ } catch (error) {
524
+ acquired?.()
525
+ throw error
526
+ }
527
+ }
528
+
529
+ const ensureSession = (): AVCaptureSession => {
530
+ if (session) {
531
+ return session
532
+ }
533
+
534
+ const target = AVCaptureSession.new()
535
+
536
+ target.beginConfiguration()
537
+ device = selectDevice(currentConfig.camera, listCameras())
538
+ if (!device) {
539
+ target.commitConfiguration()
540
+ throw new CameraCaptureError({
541
+ kind: 'unavailable',
542
+ operation: 'startPreview',
543
+ message: 'No camera device is available',
544
+ })
545
+ }
546
+
547
+ if (supportedPreset(target, device)) {
548
+ target.sessionPreset = AVCaptureSessionPreset1280x720
549
+ }
550
+
551
+ const input = AVCaptureDeviceInput.deviceInputWithDeviceError(device, undefined)
552
+
553
+ if (!input || !target.canAddInput(input)) {
554
+ target.commitConfiguration()
555
+ throw new CameraCaptureError({
556
+ kind: 'unavailable',
557
+ operation: 'startPreview',
558
+ message: 'Camera input is unavailable',
559
+ })
560
+ }
561
+
562
+ target.addInput(input)
563
+ videoInput = input
564
+
565
+ if (typeof XplatSwitchingMovieWriter === 'undefined') {
566
+ target.commitConfiguration()
567
+ throw new CameraCaptureError({
568
+ kind: 'unsupportedPlatform',
569
+ operation: 'startPreview',
570
+ message: 'Movie writer is not linked; rebuild the iOS app',
571
+ })
572
+ }
573
+
574
+ nativeWriter = XplatSwitchingMovieWriter.new()
575
+
576
+ const problem = nativeWriter.install(target)
577
+
578
+ if (problem) {
579
+ target.commitConfiguration()
580
+ throw new CameraCaptureError({
581
+ kind: 'unavailable',
582
+ operation: 'startPreview',
583
+ message: problem,
584
+ })
585
+ }
586
+
587
+ writerDriver = new IOSMovieWriterDriver(nativeWriter)
588
+
589
+ const sourceOwner = nativeWriter
590
+
591
+ nativeWriter.observeSource((ready) => {
592
+ if (nativeWriter !== sourceOwner) {
593
+ return
594
+ }
595
+
596
+ writerSourceReady = ready
597
+ observer?.previewReady(previewReadyFlag && ready && !interrupted)
598
+ if (ready && initialWriterReady && !captureSink) {
599
+ const callback = initialWriterReady
600
+
601
+ initialWriterReady = undefined
602
+ callback()
603
+ }
604
+ })
605
+
606
+ try {
607
+ if (currentConfig.audio && readPermission('microphone') === 'granted') {
608
+ ensureAudioInput()
609
+ }
610
+ } catch (error) {
611
+ const driver = writerDriver
612
+
613
+ writerDriver = undefined
614
+ nativeWriter = undefined
615
+ writerRelease = Promise.all([writerRelease, driver.release()]).then(() => {})
616
+ videoInput = undefined
617
+ device = undefined
618
+ throw error
619
+ } finally {
620
+ target.commitConfiguration()
621
+ }
622
+
623
+ session = target
624
+ observeSession(target)
625
+ return target
626
+ }
627
+
628
+ const stopSessionIfIdle = () => {
629
+ if (!session || captureSink || previewHost) {
630
+ return
631
+ }
632
+
633
+ session.stopRunning()
634
+ if (writerDriver) {
635
+ const releasePolicy = releaseRecordingHaptics
636
+
637
+ releaseRecordingHaptics = undefined
638
+ writerRelease = Promise.all([
639
+ writerRelease,
640
+ writerDriver.release().then(() => releasePolicy?.()),
641
+ ]).then(() => {})
642
+ }
643
+
644
+ writerDriver = undefined
645
+ nativeWriter = undefined
646
+ writerSourceReady = false
647
+ clearObservers()
648
+ if (interrupted) {
649
+ // The 'ended' notification can be lost when the session is
650
+ // torn down mid-interruption — report it so the flag does not
651
+ // wedge previewReady/startRecording for the next session.
652
+ notify('ended')
653
+ }
654
+
655
+ // A destroyed session's runtime error must not wedge the next
656
+ // one — AVCaptureDeviceWasConnected never fires for built-in
657
+ // cameras, so cameraAvailable would otherwise stay false forever.
658
+ observer?.availability(true)
659
+
660
+ session = undefined
661
+ videoInput = undefined
662
+ writerHasAudio = false
663
+ previewLayer = undefined
664
+ device = undefined
665
+ }
666
+
667
+ const onCaptureStarted = (dimensions?: { width: number; height: number }) => {
668
+ const request = captureRequest
669
+ const sink = captureSink
670
+
671
+ if (!request || !sink || !device) {
672
+ return
673
+ }
674
+
675
+ const profile = standardProfile(device)
676
+ const configuration: EffectiveCaptureConfig = {
677
+ cameraId: device.uniqueID,
678
+ facing: facingForPosition(device.position),
679
+ audio: request.audio && writerHasAudio,
680
+ width: dimensions?.width ?? profile.width,
681
+ height: dimensions?.height ?? profile.height,
682
+ frameRate: profile.frameRate,
683
+ orientation: request.orientation ?? 'unspecified',
684
+ mimeType: 'video/quicktime',
685
+ container: 'mov',
686
+ }
687
+
688
+ sink.started(configuration)
689
+ }
690
+
691
+ const onCaptureFinished = (url: NSURL) => {
692
+ const request = captureRequest
693
+ const sink = captureSink
694
+
695
+ captureRequest = undefined
696
+ captureSink = undefined
697
+ if (!request || !sink) {
698
+ return
699
+ }
700
+
701
+ const filePath = url?.path ? String(url.path) : ''
702
+ const limitReached = nativeLimitReached
703
+
704
+ try {
705
+ const asset = AVURLAsset.assetWithURL(url)
706
+ const durationSeconds = asset ? CMTimeGetSeconds(asset.duration) : 0
707
+ const videoTracks = asset?.tracksWithMediaType(AVMediaTypeVideo)
708
+ const audioTracks = asset?.tracksWithMediaType(AVMediaTypeAudio)
709
+ const track = videoTracks && videoTracks.count > 0 ? videoTracks.objectAtIndex(0) : null
710
+
711
+ if (!track || !(durationSeconds > 0)) {
712
+ sink.settled({
713
+ kind: 'failed',
714
+ stage: 'capture',
715
+ issue: emitIssue('noMedia', 'finalize', 'The finalized movie contains no playable media'),
716
+ })
717
+
718
+ stopSessionIfIdle()
719
+ return
720
+ }
721
+
722
+ const naturalSize = track.naturalSize
723
+ const transform = track.preferredTransform
724
+ const orientation =
725
+ request.orientation && request.orientation !== 'unspecified'
726
+ ? request.orientation
727
+ : orientationFromTransform(transform)
728
+
729
+ const rotated = Math.abs(transform.b) === 1 && Math.abs(transform.c) === 1
730
+ const width = rotated ? naturalSize.height : naturalSize.width
731
+ const height = rotated ? naturalSize.width : naturalSize.height
732
+
733
+ if (request.audio && !(audioTracks && audioTracks.count > 0)) {
734
+ // Requested audio missing must not masquerade as silent
735
+ // capture — classify as failure, not a successful clip.
736
+
737
+ sink.settled({
738
+ kind: 'failed',
739
+ stage: 'capture',
740
+ issue: emitIssue(
741
+ 'captureFailed',
742
+ 'finalize',
743
+ 'Requested audio track is missing from the finalized movie',
744
+ ),
745
+ })
746
+
747
+ stopSessionIfIdle()
748
+ return
749
+ }
750
+
751
+ sink.settled({
752
+ kind: 'clip',
753
+ output: {
754
+ kind: 'nativeFile',
755
+ resourceId: `file:${filePath}`,
756
+ fileUrl: `file://${filePath}`,
757
+ },
758
+ mimeType: 'video/quicktime',
759
+ durationMs: Math.round(durationSeconds * 1000),
760
+ width,
761
+ height,
762
+ orientation,
763
+ hasAudio: request.audio && (audioTracks?.count ?? 0) > 0,
764
+ limitReached,
765
+ warning: writerWarning,
766
+ })
767
+ } catch (cause) {
768
+ sink.settled({
769
+ kind: 'failed',
770
+ stage: 'finalization',
771
+ issue: emitIssue(
772
+ 'finalizationFailed',
773
+ 'finalize',
774
+ cause instanceof Error ? cause.message : String(cause),
775
+ cause,
776
+ ),
777
+ })
778
+ }
779
+
780
+ stopSessionIfIdle()
781
+ }
782
+
783
+ const failWriter = (cause: unknown, details?: unknown) => {
784
+ const sink = captureSink
785
+
786
+ captureSink = undefined
787
+ captureRequest = undefined
788
+ sink?.settled({
789
+ kind: 'failed',
790
+ stage: 'capture',
791
+ issue: emitIssue(
792
+ 'captureFailed',
793
+ 'capture',
794
+ cause instanceof Error ? cause.message : String(cause),
795
+ details ?? cause,
796
+ ),
797
+ })
798
+
799
+ stopSessionIfIdle()
800
+ }
801
+
802
+ return {
803
+ platform: 'ios',
804
+ supported: typeof XplatSwitchingMovieWriter !== 'undefined',
805
+ checkPermission: async (kind) => {
806
+ if (!hasUsageDeclaration(kind)) {
807
+ // Missing declarations are a setup error, not a permission
808
+ // status — surface through start/configure failures instead of
809
+ // pretending a status.
810
+ return 'unknown'
811
+ }
812
+
813
+ return readPermission(kind)
814
+ },
815
+ requestPermission: (kind) => requestAccess(kind),
816
+ getCapabilities: async () => {
817
+ const devices = listCameras()
818
+ const cameras: CameraDeviceInfo[] = devices.map((entry) => ({
819
+ id: entry.uniqueID,
820
+ label: entry.localizedName ?? entry.uniqueID,
821
+ facing: facingForPosition(entry.position),
822
+ }))
823
+
824
+ const selected = device ?? selectDevice(currentConfig.camera, devices)
825
+ const profile = selected
826
+ ? (() => {
827
+ const probe = AVCaptureSession.new()
828
+
829
+ probe.beginConfiguration()
830
+
831
+ const supported = supportedPreset(probe, selected)
832
+
833
+ probe.commitConfiguration()
834
+ return supported
835
+ ? { width: 1280, height: 720, frameRate: 30 }
836
+ : standardProfile(selected)
837
+ })()
838
+ : { width: 1280, height: 720, frameRate: 30 }
839
+
840
+ const available = cameras.length > 0
841
+ const supported = typeof XplatSwitchingMovieWriter !== 'undefined' && available
842
+
843
+ return {
844
+ supported,
845
+ reason: !available
846
+ ? 'No camera device is available on this host'
847
+ : typeof XplatSwitchingMovieWriter === 'undefined'
848
+ ? 'Movie writer is not linked; rebuild the iOS app'
849
+ : undefined,
850
+ available: available && writerSourceReady,
851
+ cameras,
852
+ profiles: [{ profile: 'standard', ...profile }],
853
+ audio: typeof AVCaptureDevice.defaultDeviceWithMediaType === 'function',
854
+ focusPointOfInterest: selected?.focusPointOfInterestSupported === true,
855
+ exposurePointOfInterest: selected?.exposurePointOfInterestSupported === true,
856
+ zoom:
857
+ typeof selected?.maxAvailableVideoZoomFactor === 'number' &&
858
+ typeof selected?.minAvailableVideoZoomFactor === 'number' &&
859
+ selected.maxAvailableVideoZoomFactor > selected.minAvailableVideoZoomFactor,
860
+ orientations: ['portrait', 'portraitUpsideDown', 'landscapeLeft', 'landscapeRight'],
861
+ cameraSwitchDuringRecording: typeof XplatSwitchingMovieWriter !== 'undefined',
862
+ durationLimit: 'native',
863
+ elapsedTime: 'nativeMedia',
864
+ output: {
865
+ mimeType: 'video/quicktime',
866
+ container: 'mov',
867
+ storage: 'appPrivateFile',
868
+ destinationFileUrl: true,
869
+ },
870
+ }
871
+ },
872
+ previewReady: () => previewReadyFlag && !interrupted && writerSourceReady,
873
+ attachPreview: (host, listener?: BackendPreviewListener) => {
874
+ let target: AVCaptureSession
875
+
876
+ try {
877
+ target = ensureSession()
878
+ } catch (error) {
879
+ throw error instanceof CameraCaptureError
880
+ ? error
881
+ : new CameraCaptureError({
882
+ kind: 'unavailable',
883
+ operation: 'startPreview',
884
+ message: error instanceof Error ? error.message : String(error),
885
+ cause: error,
886
+ })
887
+ }
888
+
889
+ const view = host as any
890
+ const nativeView = view?.ios ?? view?.nativeViewProtected
891
+
892
+ if (!nativeView?.layer) {
893
+ throw new CameraCaptureError({
894
+ kind: 'invalidArgument',
895
+ operation: 'attachPreview',
896
+ message: 'Camera preview host is unavailable',
897
+ })
898
+ }
899
+
900
+ const layer = AVCaptureVideoPreviewLayer.layerWithSession(target)
901
+
902
+ layer.videoGravity = AVLayerVideoGravityResizeAspectFill
903
+
904
+ const connection = layer.connection
905
+
906
+ if (connection) {
907
+ connection.automaticallyAdjustsVideoMirroring = false
908
+ if (connection.supportsVideoMirroring) {
909
+ connection.videoMirrored = device?.position === captureDevicePositionFront
910
+ }
911
+
912
+ preferAutoStabilization(connection)
913
+ }
914
+
915
+ nativeView.layer.addSublayer(layer)
916
+ previewLayer = layer
917
+ nativeWriter?.setPreviewLayer(layer)
918
+ previewHost = view
919
+
920
+ const updateFrame = () => {
921
+ layer.frame = nativeView.bounds
922
+ nativeWriter?.setPreviewLayer(layer)
923
+ }
924
+
925
+ detachFrame = () => view.off?.('layoutChanged', updateFrame)
926
+ view.on?.('layoutChanged', updateFrame)
927
+ updateFrame()
928
+
929
+ // Display readiness is its own signal: `previewing` flips true
930
+ // asynchronously after startRunning returns, and only while the
931
+ // layer is actually rendering into non-empty bounds. onReady stays
932
+ // admission readiness — writer frames flowing, preview attached.
933
+ const evaluateDisplay = () => {
934
+ const showing = previewLayerDisplaying(layer)
935
+
936
+ if (showing === displayReady) {
937
+ return
938
+ }
939
+
940
+ displayReady = showing
941
+ if (showing) {
942
+ listener?.onDisplayReady?.()
943
+ }
944
+ }
945
+
946
+ detachDisplay?.()
947
+ detachDisplay = observePreviewDisplay(layer, evaluateDisplay)
948
+ evaluateDisplay()
949
+ target.startRunning()
950
+ previewReadyFlag = true
951
+
952
+ initialWriterReady = () => {
953
+ if (writerDiagnostics) {
954
+ try {
955
+ writerDiagnostics('previewConnection', JSON.stringify(recordingConnectionState()))
956
+ } catch {
957
+ /* Diagnostics cannot own capture completion. */
958
+ }
959
+ }
960
+
961
+ listener?.onReady?.()
962
+ }
963
+
964
+ observer?.previewReady(writerSourceReady)
965
+ if (writerSourceReady) {
966
+ initialWriterReady()
967
+ initialWriterReady = undefined
968
+ }
969
+
970
+ return () => {
971
+ previewReadyFlag = false
972
+ initialWriterReady = undefined
973
+ detachDisplay?.()
974
+ detachDisplay = undefined
975
+ displayReady = false
976
+ nativeWriter?.setPreviewLayer(null)
977
+ view.off?.('layoutChanged', updateFrame)
978
+ layer.removeFromSuperlayer()
979
+ previewLayer = undefined
980
+ previewHost = undefined
981
+ detachFrame = undefined
982
+ observer?.previewReady(false)
983
+ stopSessionIfIdle()
984
+ }
985
+ },
986
+ configure: (next) => {
987
+ const previous = currentConfig
988
+
989
+ currentConfig = { ...next }
990
+
991
+ const target = session
992
+
993
+ if (!target || !device) {
994
+ return
995
+ }
996
+
997
+ target.beginConfiguration()
998
+
999
+ const wanted = selectDevice(next.camera ?? previous.camera, listCameras())
1000
+ const hasSelectedInput =
1001
+ wanted &&
1002
+ Array.from({ length: target.inputs.count }, (_, index) =>
1003
+ target.inputs.objectAtIndex(index),
1004
+ ).some(
1005
+ (input) =>
1006
+ input instanceof AVCaptureDeviceInput && input.device.uniqueID === wanted.uniqueID,
1007
+ )
1008
+
1009
+ if (wanted && videoInput && (wanted !== device || !hasSelectedInput)) {
1010
+ const input = AVCaptureDeviceInput.deviceInputWithDeviceError(wanted, undefined)
1011
+
1012
+ const previousInput = videoInput
1013
+
1014
+ writerSourceReady = false
1015
+ observer?.previewReady(false)
1016
+ for (const entry of Array.from({ length: target.inputs.count }, (_, index) =>
1017
+ target.inputs.objectAtIndex(index),
1018
+ )) {
1019
+ if (
1020
+ entry instanceof AVCaptureDeviceInput &&
1021
+ entry.device.hasMediaType(AVMediaTypeVideo)
1022
+ ) {
1023
+ target.removeInput(entry)
1024
+ }
1025
+ }
1026
+
1027
+ if (!input || !target.canAddInput(input)) {
1028
+ if (target.canAddInput(previousInput)) {
1029
+ target.addInput(previousInput)
1030
+ }
1031
+
1032
+ target.commitConfiguration()
1033
+ currentConfig = previous
1034
+ nativeWriter?.expectCamera(device.uniqueID)
1035
+ throw new CameraCaptureError({
1036
+ kind: 'unsupportedConfiguration',
1037
+ operation: 'configure',
1038
+ message: 'Camera input is incompatible',
1039
+ })
1040
+ }
1041
+
1042
+ target.addInput(input)
1043
+ videoInput = input
1044
+ device = wanted
1045
+ }
1046
+
1047
+ try {
1048
+ if (next.audio === true && readPermission('microphone') === 'granted') {
1049
+ ensureAudioInput()
1050
+ } else if (next.audio === false) {
1051
+ const problem = nativeWriter?.configureAudio(false)
1052
+
1053
+ if (problem) {
1054
+ throw new CameraCaptureError({
1055
+ kind: 'unavailable',
1056
+ operation: 'configure',
1057
+ message: problem,
1058
+ })
1059
+ }
1060
+
1061
+ writerHasAudio = false
1062
+ releaseRecordingHaptics?.()
1063
+ releaseRecordingHaptics = undefined
1064
+ }
1065
+ } catch (error) {
1066
+ currentConfig = previous
1067
+ throw error
1068
+ } finally {
1069
+ target.commitConfiguration()
1070
+ }
1071
+
1072
+ if (device) {
1073
+ writerSourceReady = false
1074
+ observer?.previewReady(false)
1075
+ nativeWriter?.expectCamera(device.uniqueID)
1076
+ }
1077
+
1078
+ // Swapping the video input recreates the preview connection — the
1079
+ // stabilization preference must be restated.
1080
+ preferAutoStabilization(previewLayer?.connection)
1081
+ },
1082
+ focusAtPoint: (point) => {
1083
+ const captureDevice = device
1084
+ const layer = previewLayer
1085
+
1086
+ if (!captureDevice || !layer) {
1087
+ return
1088
+ }
1089
+
1090
+ // Front cameras are commonly fixed-focus — meter only the
1091
+ // dimensions the device actually supports.
1092
+ const focus =
1093
+ captureDevice.focusPointOfInterestSupported === true &&
1094
+ captureDevice.isFocusModeSupported?.(focusModeAutoFocus) !== false
1095
+
1096
+ const expose =
1097
+ captureDevice.exposurePointOfInterestSupported === true &&
1098
+ captureDevice.isExposureModeSupported?.(exposureModeAutoExpose) !== false
1099
+
1100
+ if (!focus && !expose) {
1101
+ return
1102
+ }
1103
+
1104
+ // The preview layer converts view space into device space —
1105
+ // aspect-fill cropping, sensor orientation, and the front
1106
+ // camera's mirrored connection are all accounted for. Without
1107
+ // it there is no honest mapping, so bail rather than meter the
1108
+ // wrong point.
1109
+ const bounds = layer.bounds
1110
+ const layerPoint = CGPointMake(point.x * bounds.size.width, point.y * bounds.size.height)
1111
+
1112
+ if (typeof layer.captureDevicePointOfInterestForPoint !== 'function') {
1113
+ return
1114
+ }
1115
+
1116
+ const devicePoint = layer.captureDevicePointOfInterestForPoint(layerPoint)
1117
+
1118
+ try {
1119
+ if (captureDevice.lockForConfiguration?.(undefined) !== true) {
1120
+ return
1121
+ }
1122
+
1123
+ // Single-shot AF/AE at the point — the Apple AVCam
1124
+ // tap-to-focus convention; the device locks after metering.
1125
+ if (focus) {
1126
+ captureDevice.focusPointOfInterest = devicePoint
1127
+ captureDevice.focusMode = focusModeAutoFocus
1128
+ }
1129
+
1130
+ if (expose) {
1131
+ captureDevice.exposurePointOfInterest = devicePoint
1132
+ captureDevice.exposureMode = exposureModeAutoExpose
1133
+ }
1134
+
1135
+ captureDevice.unlockForConfiguration()
1136
+ } catch {
1137
+ // A missed metering pass must not fault the session.
1138
+ }
1139
+ },
1140
+ zoomState: (): CameraZoomState | undefined => {
1141
+ const captureDevice = device
1142
+
1143
+ if (!captureDevice || typeof captureDevice.videoZoomFactor !== 'number') {
1144
+ return undefined
1145
+ }
1146
+
1147
+ // min/maxAvailableVideoZoomFactor are iOS 11+; older runtimes only
1148
+ // expose the format maximum — report what the device proves.
1149
+ const minZoom =
1150
+ typeof captureDevice.minAvailableVideoZoomFactor === 'number'
1151
+ ? captureDevice.minAvailableVideoZoomFactor
1152
+ : 1
1153
+
1154
+ const maxZoom =
1155
+ typeof captureDevice.maxAvailableVideoZoomFactor === 'number'
1156
+ ? captureDevice.maxAvailableVideoZoomFactor
1157
+ : minZoom
1158
+
1159
+ return { zoom: captureDevice.videoZoomFactor, minZoom, maxZoom }
1160
+ },
1161
+ setZoom: (ratio) => {
1162
+ const captureDevice = device
1163
+
1164
+ if (!captureDevice || typeof captureDevice.videoZoomFactor !== 'number') {
1165
+ return
1166
+ }
1167
+
1168
+ const min =
1169
+ typeof captureDevice.minAvailableVideoZoomFactor === 'number'
1170
+ ? captureDevice.minAvailableVideoZoomFactor
1171
+ : 1
1172
+
1173
+ const max =
1174
+ typeof captureDevice.maxAvailableVideoZoomFactor === 'number'
1175
+ ? captureDevice.maxAvailableVideoZoomFactor
1176
+ : Math.max(min, ratio)
1177
+
1178
+ try {
1179
+ if (captureDevice.lockForConfiguration?.(undefined) !== true) {
1180
+ return
1181
+ }
1182
+
1183
+ // Out-of-range writes raise NSRangeException — clamp against the
1184
+ // live device bounds even though the shared session already did.
1185
+ try {
1186
+ captureDevice.videoZoomFactor = Math.min(max, Math.max(min, ratio))
1187
+ } finally {
1188
+ captureDevice.unlockForConfiguration()
1189
+ }
1190
+ } catch {
1191
+ // A refused zoom write must not fault the session.
1192
+ }
1193
+ },
1194
+ switchCamera: (selection) => {
1195
+ if (!writerDriver || !captureSink || !writerSourceReady) {
1196
+ throw new CameraCaptureError({
1197
+ kind: 'invalidState',
1198
+ operation: 'switchCamera',
1199
+ message: 'Movie writer is not active',
1200
+ })
1201
+ }
1202
+
1203
+ const wanted = selectDevice(selection, listCameras())
1204
+
1205
+ if (!wanted) {
1206
+ throw new CameraCaptureError({
1207
+ kind: 'unavailable',
1208
+ operation: 'switchCamera',
1209
+ message: 'Selected camera is unavailable',
1210
+ })
1211
+ }
1212
+
1213
+ const operation = writerDriver.switchCamera({
1214
+ id: wanted.uniqueID,
1215
+ label: wanted.localizedName,
1216
+ facing: facingForPosition(wanted.position),
1217
+ })
1218
+
1219
+ let cancelled = false
1220
+
1221
+ return {
1222
+ completion: operation.completion,
1223
+ commit: () => {
1224
+ if (cancelled) {
1225
+ throw new CameraCaptureError({
1226
+ kind: 'invalidState',
1227
+ operation: 'switchCamera',
1228
+ message: 'Camera switching was cancelled',
1229
+ })
1230
+ }
1231
+
1232
+ const selectedInput =
1233
+ session?.inputs &&
1234
+ (Array.from({ length: session.inputs.count }, (_, index) =>
1235
+ session!.inputs.objectAtIndex(index),
1236
+ ).find(
1237
+ (input) =>
1238
+ input instanceof AVCaptureDeviceInput && input.device.uniqueID === wanted.uniqueID,
1239
+ ) as AVCaptureDeviceInput | undefined)
1240
+
1241
+ if (!selectedInput) {
1242
+ throw new CameraCaptureError({
1243
+ kind: 'unavailable',
1244
+ operation: 'switchCamera',
1245
+ message: 'The acquired camera input disappeared before commit',
1246
+ })
1247
+ }
1248
+
1249
+ operation.commit?.()
1250
+ device = wanted
1251
+ videoInput = selectedInput
1252
+ currentConfig = { ...currentConfig, camera: selection }
1253
+ try {
1254
+ mirrorPreview()
1255
+ } catch {
1256
+ /* The source commit must survive a preview preference failure. */
1257
+ }
1258
+
1259
+ if (writerDiagnostics) {
1260
+ try {
1261
+ writerDiagnostics(
1262
+ 'cameraCommitted',
1263
+ JSON.stringify({ id: wanted.uniqueID, ...recordingConnectionState() }),
1264
+ )
1265
+ } catch {
1266
+ /* Diagnostics cannot own capture completion. */
1267
+ }
1268
+ }
1269
+ },
1270
+ cancel: () => {
1271
+ cancelled = true
1272
+ operation.cancel()
1273
+ },
1274
+ }
1275
+ },
1276
+ startCapture: (request, sink) => {
1277
+ const target = session
1278
+
1279
+ if (!target || !writerDriver || !device) {
1280
+ sink.settled({
1281
+ kind: 'failed',
1282
+ stage: 'preparation',
1283
+ issue: emitIssue('unavailable', 'startRecording', 'The camera session is not running'),
1284
+ })
1285
+
1286
+ return
1287
+ }
1288
+
1289
+ if (!hasUsageDeclaration('camera')) {
1290
+ sink.settled({
1291
+ kind: 'failed',
1292
+ stage: 'preparation',
1293
+ issue: emitIssue(
1294
+ 'configurationMissing',
1295
+ 'startRecording',
1296
+ "Missing NSCameraUsageDescription in the host app's Info.plist",
1297
+ ),
1298
+ })
1299
+
1300
+ return
1301
+ }
1302
+
1303
+ if (request.audio) {
1304
+ if (!hasUsageDeclaration('microphone')) {
1305
+ sink.settled({
1306
+ kind: 'failed',
1307
+ stage: 'preparation',
1308
+ issue: emitIssue(
1309
+ 'configurationMissing',
1310
+ 'startRecording',
1311
+ "Missing NSMicrophoneUsageDescription in the host app's Info.plist",
1312
+ ),
1313
+ })
1314
+
1315
+ return
1316
+ }
1317
+
1318
+ const micStatus = readPermission('microphone')
1319
+
1320
+ if (micStatus !== 'granted') {
1321
+ sink.settled({
1322
+ kind: 'failed',
1323
+ stage: 'preparation',
1324
+ issue: emitIssue(
1325
+ micStatus === 'restricted' ? 'permissionRestricted' : 'permissionDenied',
1326
+ 'startRecording',
1327
+ `Microphone permission is ${micStatus}`,
1328
+ { permission: 'microphone' },
1329
+ ),
1330
+ })
1331
+
1332
+ return
1333
+ }
1334
+
1335
+ if (!ensureAudioInput()) {
1336
+ sink.settled({
1337
+ kind: 'failed',
1338
+ stage: 'preparation',
1339
+ issue: emitIssue('unavailable', 'startRecording', 'No audio input device is available'),
1340
+ })
1341
+
1342
+ return
1343
+ }
1344
+ }
1345
+
1346
+ let filePath: string
1347
+
1348
+ if (request.destinationPath) {
1349
+ // Durable output stays app-private — canonicalize first so a
1350
+ // '..' segment cannot keep the Documents prefix while
1351
+ // resolving outside it.
1352
+ const destination = canonicalizePath(request.destinationPath)
1353
+ const documents = knownFolders.documents().path
1354
+ const inside = destination.startsWith(`${documents}/`)
1355
+ const directory = destination.slice(0, destination.lastIndexOf('/'))
1356
+
1357
+ if (!inside || !File.exists(directory) || File.exists(destination)) {
1358
+ sink.settled({
1359
+ kind: 'failed',
1360
+ stage: 'preparation',
1361
+ issue: emitIssue(
1362
+ 'destinationUnavailable',
1363
+ 'startRecording',
1364
+ !inside
1365
+ ? 'destinationFileUrl must resolve inside the app-private documents directory'
1366
+ : File.exists(destination)
1367
+ ? 'destinationFileUrl already exists'
1368
+ : 'destinationFileUrl directory does not exist',
1369
+ ),
1370
+ })
1371
+
1372
+ return
1373
+ }
1374
+
1375
+ filePath = destination
1376
+ } else {
1377
+ try {
1378
+ filePath = path.join(
1379
+ recordingsDirectory(),
1380
+ `clip-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.mov`,
1381
+ )
1382
+ } catch (cause) {
1383
+ sink.settled({
1384
+ kind: 'failed',
1385
+ stage: 'preparation',
1386
+ issue: emitIssue(
1387
+ 'destinationUnavailable',
1388
+ 'startRecording',
1389
+ cause instanceof Error ? cause.message : String(cause),
1390
+ cause,
1391
+ ),
1392
+ })
1393
+
1394
+ return
1395
+ }
1396
+ }
1397
+
1398
+ if (freeDiskBytes() < minFreeDiskBytes) {
1399
+ sink.settled({
1400
+ kind: 'failed',
1401
+ stage: 'preparation',
1402
+ issue: emitIssue(
1403
+ 'insufficientStorage',
1404
+ 'startRecording',
1405
+ 'Not enough local storage for a movie recording',
1406
+ ),
1407
+ })
1408
+
1409
+ return
1410
+ }
1411
+
1412
+ captureRequest = {
1413
+ ...request,
1414
+ orientation:
1415
+ request.orientation && request.orientation !== 'unspecified'
1416
+ ? request.orientation
1417
+ : 'portrait',
1418
+ }
1419
+
1420
+ captureSink = sink
1421
+ nativeLimitReached = false
1422
+ writerWarning = undefined
1423
+ try {
1424
+ writerDriver.start(
1425
+ filePath,
1426
+ request.audio,
1427
+ orientationToLegacyConstant(request.orientation ?? 'portrait') ?? 1,
1428
+ request.maximumDurationMs ?? 0,
1429
+ (type, payload) => {
1430
+ try {
1431
+ writerDiagnostics?.(type, payload)
1432
+ } catch {
1433
+ /* Diagnostics cannot own capture completion. */
1434
+ }
1435
+
1436
+ if (type === 'started') {
1437
+ if (writerDiagnostics) {
1438
+ try {
1439
+ writerDiagnostics(
1440
+ 'recordingConnection',
1441
+ JSON.stringify(recordingConnectionState()),
1442
+ )
1443
+ } catch {
1444
+ /* Diagnostics cannot own capture completion. */
1445
+ }
1446
+ }
1447
+
1448
+ try {
1449
+ onCaptureStarted(JSON.parse(payload))
1450
+ } catch (error) {
1451
+ writerWarning = emitIssue(
1452
+ 'captureFailed',
1453
+ 'capture',
1454
+ 'Writer start metadata was malformed; recording was stopped for verification',
1455
+ error,
1456
+ )
1457
+
1458
+ sink.finishing('captureError')
1459
+ writerDriver?.stop()
1460
+ }
1461
+ } else if (type === 'limit') {
1462
+ nativeLimitReached = true
1463
+ sink.finishing('maximumDuration')
1464
+ } else if (type === 'sourceLost') {
1465
+ sink.finishing('cameraUnavailable')
1466
+ } else if (type === 'finishing') {
1467
+ sink.finishing(
1468
+ nativeLimitReached
1469
+ ? 'maximumDuration'
1470
+ : payload === 'captureError'
1471
+ ? 'captureError'
1472
+ : 'stopped',
1473
+ )
1474
+ } else if (type === 'finished') {
1475
+ try {
1476
+ const result = JSON.parse(payload)
1477
+
1478
+ if (result?.warning) {
1479
+ writerWarning = emitIssue('captureFailed', 'capture', result.warning)
1480
+ }
1481
+ } catch (error) {
1482
+ writerWarning = emitIssue(
1483
+ 'captureFailed',
1484
+ 'finalize',
1485
+ 'Writer completion metadata was malformed; the movie was verified separately',
1486
+ error,
1487
+ )
1488
+ }
1489
+
1490
+ onCaptureFinished(NSURL.fileURLWithPath(filePath))
1491
+ } else if (type === 'failed') {
1492
+ let result:
1493
+ | {
1494
+ ownsOutput?: boolean
1495
+ hasVideo?: boolean
1496
+ canInspectOutput?: boolean
1497
+ message?: string
1498
+ }
1499
+ | undefined
1500
+
1501
+ try {
1502
+ result = JSON.parse(payload)
1503
+ } catch {
1504
+ /* Preserve the original native error below. */
1505
+ }
1506
+
1507
+ if (
1508
+ result?.ownsOutput === true &&
1509
+ result.hasVideo === true &&
1510
+ result.canInspectOutput === true
1511
+ ) {
1512
+ writerWarning = emitIssue(
1513
+ 'captureFailed',
1514
+ 'capture',
1515
+ result.message ?? 'Native writer failed',
1516
+ )
1517
+
1518
+ sink.finishing('captureError')
1519
+ onCaptureFinished(NSURL.fileURLWithPath(filePath))
1520
+ } else {
1521
+ failWriter(result?.message ?? payload, {
1522
+ native: result,
1523
+ candidateFileUrl: `file://${filePath}`,
1524
+ })
1525
+ }
1526
+ }
1527
+ },
1528
+ )
1529
+ } catch (error) {
1530
+ failWriter(error)
1531
+ }
1532
+
1533
+ return
1534
+ },
1535
+ stopCapture: () => writerDriver?.stop(),
1536
+ elapsedMs: () => nativeWriter?.elapsedMs() ?? 0,
1537
+ openOutput: async (output) => {
1538
+ if (output.kind !== 'nativeFile') {
1539
+ throw new CameraCaptureError({
1540
+ kind: 'invalidArgument',
1541
+ operation: 'openOutput',
1542
+ message: 'Only file-backed output can be opened on iOS',
1543
+ })
1544
+ }
1545
+
1546
+ const filePath = output.fileUrl.slice('file://'.length)
1547
+
1548
+ if (!File.exists(filePath)) {
1549
+ throw new CameraCaptureError({
1550
+ kind: 'unavailable',
1551
+ operation: 'openOutput',
1552
+ message: `Movie file is missing at ${output.fileUrl}`,
1553
+ })
1554
+ }
1555
+
1556
+ const handle: MovieOutputHandle = {
1557
+ url: output.fileUrl,
1558
+ fileUrl: output.fileUrl,
1559
+ release: () => {},
1560
+ }
1561
+
1562
+ return handle
1563
+ },
1564
+ release: async () => {
1565
+ const driver = writerDriver
1566
+
1567
+ writerDriver = undefined
1568
+ nativeWriter = undefined
1569
+ initialWriterReady = undefined
1570
+ previewReadyFlag = false
1571
+ await driver?.release()
1572
+ releaseRecordingHaptics?.()
1573
+ releaseRecordingHaptics = undefined
1574
+ await writerRelease
1575
+ detachFrame?.()
1576
+ detachFrame = undefined
1577
+ detachDisplay?.()
1578
+ detachDisplay = undefined
1579
+ displayReady = false
1580
+ if (previewHost) {
1581
+ try {
1582
+ previewLayer?.removeFromSuperlayer()
1583
+ } catch {}
1584
+ }
1585
+
1586
+ previewHost = undefined
1587
+ previewLayer = undefined
1588
+ captureRequest = undefined
1589
+ captureSink = undefined
1590
+ clearObservers()
1591
+ interrupted = false
1592
+ try {
1593
+ session?.stopRunning()
1594
+ } catch {}
1595
+
1596
+ session = undefined
1597
+ videoInput = undefined
1598
+ writerHasAudio = false
1599
+ device = undefined
1600
+ },
1601
+ onPreviewDetached: () => {
1602
+ // The view went away; if a settle is still in flight the session
1603
+ // stays alive until it arrives (stopSessionIfIdle re-checks).
1604
+ stopSessionIfIdle()
1605
+ },
1606
+ setObserver: (next) => {
1607
+ observer = next
1608
+ },
1609
+ }
1258
1610
  }