@octane-xplat/camera 0.19.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 (84) hide show
  1. package/README.md +2 -132
  2. package/package.json +20 -25
  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 +187 -154
  7. package/src/CameraView.ios.tsrx +124 -110
  8. package/src/CameraView.macos.tsrx +103 -96
  9. package/src/CameraView.tsrx +2 -0
  10. package/src/CameraView.web.tsrx +157 -146
  11. package/src/CameraView.windows.tsrx +134 -125
  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 +257 -231
  19. package/src/index.ts +28 -26
  20. package/src/index.web.ts +27 -25
  21. package/src/layout-child.ts +86 -79
  22. package/src/layout-child.web.ts +54 -53
  23. package/src/layout-child.windows.ts +80 -74
  24. package/src/movie-metadata.web.ts +84 -81
  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 +115 -93
  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 +1540 -1467
  42. package/src/session-core.ts +925 -714
  43. package/src/session.ts +12 -12
  44. package/src/style-merge.ts +40 -37
  45. package/src/synthetic-session.ts +391 -339
  46. package/src/types.ts +372 -298
  47. package/types/generated/.tsrx-typegen-manifest.json +4 -24
  48. package/types/generated/CameraView.d.ts +2 -0
  49. package/types/generated/camera-host.macos.d.ts +33 -0
  50. package/types/generated/index.d.ts +27 -26
  51. package/types/generated/photo-lifecycle.macos.d.ts +12 -0
  52. package/types/generated/photo-sheet.macos.d.ts +36 -0
  53. package/types/generated/props.d.ts +24 -2
  54. package/types/generated/session-core.d.ts +30 -1
  55. package/types/generated/synthetic-session.d.ts +7 -0
  56. package/types/generated/types.d.ts +75 -1
  57. package/platforms/macos/src/CameraOwnership.swift +0 -22
  58. package/platforms/macos/src/PhotoCaptureLifecycle.swift +0 -34
  59. package/platforms/macos/src/XplatCameraHost.swift +0 -639
  60. package/platforms/macos/src/XplatPhotoCaptureSheet.swift +0 -192
  61. package/types/generated/CameraView.android.d.ts +0 -9
  62. package/types/generated/CameraView.ios.d.ts +0 -5
  63. package/types/generated/CameraView.macos.d.ts +0 -5
  64. package/types/generated/CameraView.mobile.d.ts +0 -5
  65. package/types/generated/CameraView.windows.d.ts +0 -11
  66. package/types/generated/camera-permission.mobile.d.ts +0 -2
  67. package/types/generated/camera-permission.windows.d.ts +0 -6
  68. package/types/generated/camera-session.ios.d.ts +0 -2
  69. package/types/generated/camera-session.macos.d.ts +0 -10
  70. package/types/generated/camera-session.windows.d.ts +0 -9
  71. package/types/generated/host-movie.web.d.ts +0 -100
  72. package/types/generated/index.web.d.ts +0 -7
  73. package/types/generated/layout-child.d.ts +0 -11
  74. package/types/generated/layout-child.windows.d.ts +0 -13
  75. package/types/generated/movie-metadata.web.d.ts +0 -9
  76. package/types/generated/movie-storage.web.d.ts +0 -5
  77. package/types/generated/preview-tap.d.ts +0 -7
  78. package/types/generated/session-backend.android.d.ts +0 -3
  79. package/types/generated/session-backend.ios.d.ts +0 -5
  80. package/types/generated/session-backend.linux.d.ts +0 -3
  81. package/types/generated/session-backend.macos.d.ts +0 -8
  82. package/types/generated/session-backend.web.d.ts +0 -3
  83. package/types/generated/session-backend.windows.d.ts +0 -37
  84. package/types/generated/style-merge.d.ts +0 -8
@@ -2,17 +2,18 @@ import { Application } from '@nativescript/core'
2
2
  import { CameraCaptureError } from './types'
3
3
  import { canonicalizePath } from './session-core'
4
4
  import type {
5
- BackendCaptureSink,
6
- BackendObserver,
7
- BackendPreviewListener,
8
- CameraSessionBackend,
5
+ BackendCaptureSink,
6
+ BackendObserver,
7
+ BackendPreviewListener,
8
+ CameraSessionBackend,
9
9
  } from './session-core'
10
10
 
11
11
  import type {
12
- CameraPermissionKind,
13
- CameraPermissionStatus,
14
- CameraSessionConfig,
15
- CaptureIssue,
12
+ CameraPermissionKind,
13
+ CameraPermissionStatus,
14
+ CameraSessionConfig,
15
+ CameraDeviceInfo,
16
+ CaptureIssue,
16
17
  } from './types'
17
18
 
18
19
  let requestCode = 7820
@@ -21,419 +22,560 @@ let owner: object | undefined
21
22
 
22
23
  const nativeBridge = () => (globalThis as any).com?.octanexplat?.camera?.CameraSessionBridge
23
24
  const permissionName = (kind: CameraPermissionKind) =>
24
- kind === 'camera' ? 'android.permission.CAMERA' : 'android.permission.RECORD_AUDIO'
25
+ kind === 'camera' ? 'android.permission.CAMERA' : 'android.permission.RECORD_AUDIO'
25
26
 
26
27
  const error = (kind: CaptureIssue['kind'], operation: string, message: string, cause?: unknown) =>
27
- new CameraCaptureError({ kind, operation, message, cause })
28
+ new CameraCaptureError({ kind, operation, message, cause })
28
29
 
29
30
  const context = () => Application.android.context
30
31
  const preferences = () => context().getSharedPreferences('octane-camera-permissions', 0)
31
32
 
32
33
  async function checkPermission(kind: CameraPermissionKind): Promise<CameraPermissionStatus> {
33
- const activity = Application.android.foregroundActivity ?? Application.android.startActivity
34
- if (!activity) {
35
- return 'unavailable'
36
- }
37
-
38
- const permission = permissionName(kind)
39
- if (activity.checkSelfPermission(permission) === 0) {
40
- return 'granted'
41
- }
42
-
43
- return preferences().getBoolean(kind, false)
44
- ? activity.shouldShowRequestPermissionRationale(permission)
45
- ? 'denied'
46
- : 'blocked'
47
- : 'notDetermined'
34
+ const activity = Application.android.foregroundActivity ?? Application.android.startActivity
35
+
36
+ if (!activity) {
37
+ return 'unavailable'
38
+ }
39
+
40
+ const permission = permissionName(kind)
41
+
42
+ if (activity.checkSelfPermission(permission) === 0) {
43
+ return 'granted'
44
+ }
45
+
46
+ return preferences().getBoolean(kind, false)
47
+ ? activity.shouldShowRequestPermissionRationale(permission)
48
+ ? 'denied'
49
+ : 'blocked'
50
+ : 'notDetermined'
48
51
  }
49
52
 
50
53
  function requestPermission(kind: CameraPermissionKind): Promise<CameraPermissionStatus> {
51
- const result = permissionChain.then(async () => {
52
- const status = await checkPermission(kind)
53
- if (status !== 'notDetermined') {
54
- return status
55
- }
56
-
57
- const activity = Application.android.foregroundActivity ?? Application.android.startActivity
58
- if (!activity) {
59
- return 'unavailable' as const
60
- }
61
-
62
- return new Promise<CameraPermissionStatus>((resolve) => {
63
- const code = requestCode++
64
- const finish = (value: CameraPermissionStatus) => {
65
- clearTimeout(timer)
66
- Application.android.off(Application.android.activityRequestPermissionsEvent, onResult)
67
- resolve(value)
68
- }
69
-
70
- const onResult = (args: any) => {
71
- if (args.requestCode !== code) {
72
- return
73
- }
74
-
75
- if (!args.grantResults?.length) {
76
- finish('unknown')
77
- return
78
- }
79
-
80
- preferences().edit().putBoolean(kind, true).apply()
81
- finish(
82
- args.grantResults[0] === 0
83
- ? 'granted'
84
- : activity.shouldShowRequestPermissionRationale(permissionName(kind))
85
- ? 'denied'
86
- : 'blocked',
87
- )
88
- }
89
-
90
- const timer = setTimeout(() => finish('unknown'), 120_000)
91
- Application.android.on(Application.android.activityRequestPermissionsEvent, onResult)
92
- try {
93
- activity.requestPermissions([permissionName(kind)], code)
94
- } catch {
95
- finish('unavailable')
96
- }
97
- })
98
- })
99
-
100
- permissionChain = result.catch(() => {})
101
- return result
54
+ const result = permissionChain.then(async () => {
55
+ const status = await checkPermission(kind)
56
+
57
+ if (status !== 'notDetermined') {
58
+ return status
59
+ }
60
+
61
+ const activity = Application.android.foregroundActivity ?? Application.android.startActivity
62
+
63
+ if (!activity) {
64
+ return 'unavailable' as const
65
+ }
66
+
67
+ return new Promise<CameraPermissionStatus>((resolve) => {
68
+ const code = requestCode++
69
+ const finish = (value: CameraPermissionStatus) => {
70
+ clearTimeout(timer)
71
+ Application.android.off(Application.android.activityRequestPermissionsEvent, onResult)
72
+ resolve(value)
73
+ }
74
+
75
+ const onResult = (args: any) => {
76
+ if (args.requestCode !== code) {
77
+ return
78
+ }
79
+
80
+ if (!args.grantResults?.length) {
81
+ finish('unknown')
82
+ return
83
+ }
84
+
85
+ preferences().edit().putBoolean(kind, true).apply()
86
+ finish(
87
+ args.grantResults[0] === 0
88
+ ? 'granted'
89
+ : activity.shouldShowRequestPermissionRationale(permissionName(kind))
90
+ ? 'denied'
91
+ : 'blocked',
92
+ )
93
+ }
94
+
95
+ const timer = setTimeout(() => finish('unknown'), 120_000)
96
+
97
+ Application.android.on(Application.android.activityRequestPermissionsEvent, onResult)
98
+ try {
99
+ activity.requestPermissions([permissionName(kind)], code)
100
+ } catch {
101
+ finish('unavailable')
102
+ }
103
+ })
104
+ })
105
+
106
+ permissionChain = result.catch(() => {})
107
+ return result
102
108
  }
103
109
 
104
110
  export function createSessionBackend(config: CameraSessionConfig): CameraSessionBackend {
105
- let currentConfig = { ...config }
106
- let observer: BackendObserver | undefined
107
- let bridge: any
108
- let host: any
109
- let listener: BackendPreviewListener | undefined
110
- let sink: BackendCaptureSink | undefined
111
- let released = false
112
- const lease = {}
113
- const selected = () =>
114
- typeof currentConfig.camera === 'object'
115
- ? `id:${currentConfig.camera.deviceId}`
116
- : (currentConfig.camera ?? 'default')
117
-
118
- const releaseLease = () => {
119
- if (owner === lease) {
120
- owner = undefined
121
- }
122
- }
123
-
124
- const onSuspend = () => bridge?.background()
125
- const onResume = () => bridge?.foreground()
126
- const ensureBridge = () => {
127
- if (bridge) {
128
- return
129
- }
130
-
131
- const Bridge = nativeBridge()
132
- if (!Bridge) {
133
- throw error(
134
- 'unsupportedPlatform',
135
- 'preview',
136
- 'CameraX video bridge is missing from the native build',
137
- )
138
- }
139
-
140
- bridge = new Bridge(
141
- context(),
142
- new Bridge.Listener({
143
- event(type: string, payload: string) {
144
- if (type === 'ready') {
145
- observer?.previewReady(payload === 'true')
146
- if (payload === 'true') {
147
- listener?.onReady?.()
148
- }
149
- } else if (type === 'availability') {
150
- observer?.availability(payload === 'true')
151
- } else if (type === 'interruption') {
152
- observer?.interruption('began', payload as any)
153
- } else if (type === 'recovered') {
154
- observer?.interruption('ended', payload as any)
155
- } else if (type === 'previewError') {
156
- observer?.availability(false)
157
- listener?.onError?.(error('unavailable', 'preview', payload))
158
- if (!host) {
159
- releaseLease()
160
- }
161
- } else if (type === 'finishing') {
162
- sink?.finishing(payload ? (payload as any) : undefined)
163
- } else if (type === 'started') {
164
- sink?.started(JSON.parse(payload))
165
- } else if (type === 'finished' || type === 'failed') {
166
- const target = sink
167
- sink = undefined
168
- if (!host) {
169
- releaseLease()
170
- }
171
-
172
- const result = JSON.parse(payload)
173
- target?.settled(
174
- type === 'finished'
175
- ? result
176
- : {
177
- kind: 'failed',
178
- stage: result.stage,
179
- issue: error(result.kind, result.stage, result.message),
180
- },
181
- )
182
- }
183
- },
184
- }),
185
- )
186
-
187
- Application.on(Application.suspendEvent, onSuspend)
188
- Application.on(Application.resumeEvent, onResume)
189
- }
190
-
191
- return {
192
- platform: 'android',
193
- get supported() {
194
- return !!nativeBridge()
195
- },
196
- checkPermission,
197
- requestPermission: async (kind) => {
198
- const status = await requestPermission(kind)
199
- if (
200
- kind === 'camera' &&
201
- status === 'granted' &&
202
- host &&
203
- !sink &&
204
- !released &&
205
- !bridge?.isReady()
206
- ) {
207
- try {
208
- ensureBridge()
209
- bridge.attach(host, selected())
210
- } catch (cause) {
211
- observer?.availability(false)
212
- listener?.onError?.(
213
- error(
214
- 'unavailable',
215
- 'preview',
216
- 'Could not activate CameraX after permission approval',
217
- cause,
218
- ),
219
- )
220
- }
221
- }
222
-
223
- return status
224
- },
225
- getCapabilities: async () => {
226
- const value = bridge ? JSON.parse(bridge.capabilities()) : { cameras: [], profiles: [] }
227
- const supported = !!nativeBridge()
228
- return {
229
- supported,
230
- available: !!bridge?.isReady(),
231
- reason: !supported
232
- ? 'CameraX video bridge is missing from the native build'
233
- : !bridge?.isReady()
234
- ? 'An active permitted preview is required'
235
- : undefined,
236
- cameras: value.cameras,
237
- profiles: value.profiles,
238
- audio: context().getPackageManager().hasSystemFeature('android.hardware.microphone'),
239
- // The bridge only reports metering support once a camera is
240
- // bound — absent fields read as unsupported, which is honest
241
- // for the current acquisition state.
242
- focusPointOfInterest: value.focusPointOfInterest === true,
243
- exposurePointOfInterest: value.exposurePointOfInterest === true,
244
- orientations: [],
245
- durationLimit: 'native',
246
- elapsedTime: 'nativeMedia',
247
- output: {
248
- mimeType: 'video/mp4',
249
- container: 'mp4',
250
- storage: 'appPrivateFile',
251
- destinationFileUrl: true,
252
- },
253
- }
254
- },
255
- previewReady: () => !!bridge?.isReady(),
256
- validateStart: (options) => {
257
- if (
258
- options.maximumDurationMs !== undefined &&
259
- options.maximumDurationMs > 9_223_372_036_854
260
- ) {
261
- throw error(
262
- 'unsupportedConfiguration',
263
- 'startRecording',
264
- 'The duration exceeds CameraX media-time range',
265
- )
266
- }
267
-
268
- if (options.orientation && options.orientation !== 'unspecified') {
269
- throw error(
270
- 'unsupportedConfiguration',
271
- 'startRecording',
272
- 'Fixed cardinal orientation has not been qualified on this Android source',
273
- )
274
- }
275
- },
276
- attachPreview: (target, callbacks) => {
277
- if (released || sink) {
278
- throw error('invalidState', 'attachPreview', 'The camera is disposed or finalizing')
279
- }
280
-
281
- if (owner && owner !== lease) {
282
- throw error('busy', 'attachPreview', 'Another camera session is still finalizing')
283
- }
284
-
285
- owner = lease
286
- host = target
287
- listener = callbacks
288
- try {
289
- ensureBridge()
290
- } catch (cause) {
291
- host = undefined
292
- listener = undefined
293
- releaseLease()
294
- throw error(
295
- 'unavailable',
296
- 'attachPreview',
297
- 'Could not construct the CameraX native bridge',
298
- cause,
299
- )
300
- }
301
-
302
- void checkPermission('camera').then((status) => {
303
- if (released || !host) {
304
- return
305
- }
306
-
307
- if (status !== 'granted') {
308
- listener?.onError?.(
309
- error(
310
- 'permissionDenied',
311
- 'preview',
312
- 'Request camera permission before activating this preview',
313
- ),
314
- )
315
-
316
- return
317
- }
318
-
319
- try {
320
- bridge.attach(host, selected())
321
- } catch (cause) {
322
- listener?.onError?.(
323
- error('unavailable', 'preview', 'Could not bind shared CameraX preview', cause),
324
- )
325
- }
326
- })
327
-
328
- return () => {
329
- host = undefined
330
- listener = undefined
331
- bridge.detach()
332
- if (!sink) {
333
- releaseLease()
334
- }
335
- }
336
- },
337
- configure: (next) => {
338
- const sourceChanged =
339
- JSON.stringify(next.camera) !== JSON.stringify(currentConfig.camera) ||
340
- next.profile !== currentConfig.profile
341
-
342
- currentConfig = { ...next }
343
- if (host && sourceChanged) {
344
- bridge.detach()
345
- bridge.attach(host, selected())
346
- }
347
- },
348
- focusAtPoint: (point) => {
349
- try {
350
- bridge?.focusAtPoint?.(point.x, point.y)
351
- } catch {
352
- // A missed metering pass must not fault the session.
353
- }
354
- },
355
- startCapture: (request, target) => {
356
- sink = target
357
- if (request.destinationPath) {
358
- // Durable output stays app-private like every other leaf —
359
- // canonicalize so '..' cannot escape the files root.
360
- const destination = canonicalizePath(request.destinationPath)
361
- let filesRoot = ''
362
- try {
363
- filesRoot = context()?.getFilesDir?.().getAbsolutePath?.() ?? ''
364
- } catch {
365
- filesRoot = ''
366
- }
367
-
368
- if (!filesRoot || !destination.startsWith(`${filesRoot}/`)) {
369
- sink = undefined
370
- target.settled({
371
- kind: 'failed',
372
- stage: 'preparation',
373
- issue: error(
374
- 'destinationUnavailable',
375
- 'startRecording',
376
- 'destinationFileUrl must resolve inside the app-private files directory',
377
- ),
378
- })
379
-
380
- return
381
- }
382
-
383
- request = { ...request, destinationPath: destination }
384
- }
385
-
386
- try {
387
- bridge.start(
388
- request.audio,
389
- request.destinationPath ?? '',
390
- request.maximumDurationMs === undefined
391
- ? 0
392
- : Math.max(1, Math.ceil(request.maximumDurationMs)),
393
- )
394
- } catch (cause) {
395
- sink = undefined
396
- target.settled({
397
- kind: 'failed',
398
- stage: 'preparation',
399
- issue: error(
400
- 'captureFailed',
401
- 'startRecording',
402
- 'CameraX could not begin recording',
403
- cause,
404
- ),
405
- })
406
- }
407
- },
408
- stopCapture: () => bridge?.stop(),
409
- elapsedMs: () => Number(bridge?.elapsedMs() ?? 0),
410
- openOutput: async (output) => {
411
- if (output.kind !== 'nativeFile' || output.synthetic) {
412
- throw error('invalidArgument', 'openOutput', 'Expected a native Android movie reference')
413
- }
414
-
415
- try {
416
- const url = nativeBridge().openOutput(output.resourceId, output.fileUrl)
417
- return { url, fileUrl: url, release: () => {} }
418
- } catch (cause) {
419
- throw error(
420
- 'destinationUnavailable',
421
- 'openOutput',
422
- 'The stored Android movie cannot be reopened',
423
- cause,
424
- )
425
- }
426
- },
427
- release: async () => {
428
- released = true
429
- Application.off(Application.suspendEvent, onSuspend)
430
- Application.off(Application.resumeEvent, onResume)
431
- bridge?.release()
432
- host = undefined
433
- releaseLease()
434
- },
435
- setObserver: (value) => {
436
- observer = value
437
- },
438
- }
111
+ type PendingCameraSwitch = {
112
+ resolve: (camera: CameraDeviceInfo) => void
113
+ reject: (issue: Error) => void
114
+ acquired?: CameraDeviceInfo
115
+ }
116
+
117
+ let currentConfig = { ...config }
118
+ let observer: BackendObserver | undefined
119
+ let bridge: any
120
+ let host: any
121
+ let listener: BackendPreviewListener | undefined
122
+ let sink: BackendCaptureSink | undefined
123
+ let switchWarning: CaptureIssue | undefined
124
+ let released = false
125
+ let cameraSwitch: PendingCameraSwitch | undefined
126
+ const lease = {}
127
+ const selected = () =>
128
+ typeof currentConfig.camera === 'object'
129
+ ? `id:${currentConfig.camera.deviceId}`
130
+ : (currentConfig.camera ?? 'default')
131
+
132
+ const releaseLease = () => {
133
+ if (owner === lease) {
134
+ owner = undefined
135
+ }
136
+ }
137
+
138
+ const onSuspend = () => bridge?.background()
139
+ const onResume = () => bridge?.foreground()
140
+ const ensureBridge = () => {
141
+ if (bridge) {
142
+ return
143
+ }
144
+
145
+ const Bridge = nativeBridge()
146
+
147
+ if (!Bridge) {
148
+ throw error(
149
+ 'unsupportedPlatform',
150
+ 'preview',
151
+ 'CameraX video bridge is missing from the native build',
152
+ )
153
+ }
154
+
155
+ bridge = new Bridge(
156
+ context(),
157
+ new Bridge.Listener({
158
+ event(type: string, payload: string) {
159
+ if (type === 'switchFinished' || type === 'switchFailed') {
160
+ const pending = cameraSwitch
161
+
162
+ if (type === 'switchFinished') {
163
+ try {
164
+ if (pending && !pending.acquired) {
165
+ pending.acquired = JSON.parse(payload)
166
+ pending.resolve(pending.acquired!)
167
+ }
168
+ } catch (cause) {
169
+ cameraSwitch = undefined
170
+ bridge?.cancelCameraSwitch?.()
171
+ pending?.reject(
172
+ error('captureFailed', 'switchCamera', 'Invalid native camera selection', cause),
173
+ )
174
+ }
175
+ } else {
176
+ cameraSwitch = undefined
177
+ pending?.reject(error('unavailable', 'switchCamera', payload))
178
+ }
179
+ } else if (type === 'ready') {
180
+ observer?.previewReady(payload === 'true')
181
+ if (payload === 'true') {
182
+ listener?.onReady?.()
183
+ }
184
+ } else if (type === 'displayed') {
185
+ listener?.onDisplayReady?.()
186
+ } else if (type === 'availability') {
187
+ observer?.availability(payload === 'true')
188
+ } else if (type === 'interruption') {
189
+ observer?.interruption('began', payload as any)
190
+ } else if (type === 'recovered') {
191
+ observer?.interruption('ended', payload as any)
192
+ } else if (type === 'previewError') {
193
+ observer?.availability(false)
194
+ listener?.onError?.(error('unavailable', 'preview', payload))
195
+ if (!host) {
196
+ releaseLease()
197
+ }
198
+ } else if (type === 'finishing') {
199
+ sink?.finishing(payload ? (payload as any) : undefined)
200
+ } else if (type === 'started') {
201
+ sink?.started(JSON.parse(payload))
202
+ } else if (type === 'finished' || type === 'failed') {
203
+ const target = sink
204
+
205
+ sink = undefined
206
+ if (!host) {
207
+ releaseLease()
208
+ }
209
+
210
+ const result = JSON.parse(payload)
211
+
212
+ target?.settled(
213
+ type === 'finished'
214
+ ? { ...result, warning: result.warning ?? switchWarning }
215
+ : {
216
+ kind: 'failed',
217
+ stage: result.stage,
218
+ issue: error(result.kind, result.stage, result.message),
219
+ },
220
+ )
221
+ }
222
+ },
223
+ }),
224
+ )
225
+
226
+ Application.on(Application.suspendEvent, onSuspend)
227
+ Application.on(Application.resumeEvent, onResume)
228
+ }
229
+
230
+ return {
231
+ platform: 'android',
232
+ get supported() {
233
+ return !!nativeBridge()
234
+ },
235
+ checkPermission,
236
+ requestPermission: async (kind) => {
237
+ const status = await requestPermission(kind)
238
+
239
+ if (
240
+ kind === 'camera' &&
241
+ status === 'granted' &&
242
+ host &&
243
+ !sink &&
244
+ !released &&
245
+ !bridge?.isReady()
246
+ ) {
247
+ try {
248
+ ensureBridge()
249
+ bridge.attach(host, selected())
250
+ } catch (cause) {
251
+ observer?.availability(false)
252
+ listener?.onError?.(
253
+ error(
254
+ 'unavailable',
255
+ 'preview',
256
+ 'Could not activate CameraX after permission approval',
257
+ cause,
258
+ ),
259
+ )
260
+ }
261
+ }
262
+
263
+ return status
264
+ },
265
+ getCapabilities: async () => {
266
+ const value = bridge ? JSON.parse(bridge.capabilities()) : { cameras: [], profiles: [] }
267
+ const supported = !!nativeBridge()
268
+
269
+ return {
270
+ supported,
271
+ available: !!bridge?.isReady(),
272
+ reason: !supported
273
+ ? 'CameraX video bridge is missing from the native build'
274
+ : !bridge?.isReady()
275
+ ? 'An active permitted preview is required'
276
+ : undefined,
277
+ cameras: value.cameras,
278
+ profiles: value.profiles,
279
+ audio: context().getPackageManager().hasSystemFeature('android.hardware.microphone'),
280
+ // The bridge only reports metering support once a camera is
281
+ // bound — absent fields read as unsupported, which is honest
282
+ // for the current acquisition state.
283
+ focusPointOfInterest: value.focusPointOfInterest === true,
284
+ exposurePointOfInterest: value.exposurePointOfInterest === true,
285
+ zoom: value.zoom === true,
286
+ orientations: [],
287
+ cameraSwitchDuringRecording:
288
+ typeof bridge?.switchCamera === 'function' &&
289
+ typeof bridge?.confirmCameraSwitch === 'function',
290
+ durationLimit: 'native',
291
+ elapsedTime: 'nativeMedia',
292
+ output: {
293
+ mimeType: 'video/mp4',
294
+ container: 'mp4',
295
+ storage: 'appPrivateFile',
296
+ destinationFileUrl: true,
297
+ },
298
+ }
299
+ },
300
+ previewReady: () => !!bridge?.isReady(),
301
+ validateStart: (options) => {
302
+ if (
303
+ options.maximumDurationMs !== undefined &&
304
+ options.maximumDurationMs > 9_223_372_036_854
305
+ ) {
306
+ throw error(
307
+ 'unsupportedConfiguration',
308
+ 'startRecording',
309
+ 'The duration exceeds CameraX media-time range',
310
+ )
311
+ }
312
+
313
+ if (options.orientation && options.orientation !== 'unspecified') {
314
+ throw error(
315
+ 'unsupportedConfiguration',
316
+ 'startRecording',
317
+ 'Fixed cardinal orientation has not been qualified on this Android source',
318
+ )
319
+ }
320
+ },
321
+ attachPreview: (target, callbacks) => {
322
+ if (released || sink) {
323
+ throw error('invalidState', 'attachPreview', 'The camera is disposed or finalizing')
324
+ }
325
+
326
+ if (owner && owner !== lease) {
327
+ throw error('busy', 'attachPreview', 'Another camera session is still finalizing')
328
+ }
329
+
330
+ owner = lease
331
+ host = target
332
+ listener = callbacks
333
+ try {
334
+ ensureBridge()
335
+ } catch (cause) {
336
+ host = undefined
337
+ listener = undefined
338
+ releaseLease()
339
+ throw error(
340
+ 'unavailable',
341
+ 'attachPreview',
342
+ 'Could not construct the CameraX native bridge',
343
+ cause,
344
+ )
345
+ }
346
+
347
+ void checkPermission('camera').then((status) => {
348
+ if (released || !host) {
349
+ return
350
+ }
351
+
352
+ if (status !== 'granted') {
353
+ listener?.onError?.(
354
+ error(
355
+ 'permissionDenied',
356
+ 'preview',
357
+ 'Request camera permission before activating this preview',
358
+ ),
359
+ )
360
+
361
+ return
362
+ }
363
+
364
+ try {
365
+ bridge.attach(host, selected())
366
+ } catch (cause) {
367
+ listener?.onError?.(
368
+ error('unavailable', 'preview', 'Could not bind shared CameraX preview', cause),
369
+ )
370
+ }
371
+ })
372
+
373
+ return () => {
374
+ host = undefined
375
+ listener = undefined
376
+ bridge.detach()
377
+ if (!sink) {
378
+ releaseLease()
379
+ }
380
+ }
381
+ },
382
+ configure: (next) => {
383
+ const sourceChanged =
384
+ JSON.stringify(next.camera) !== JSON.stringify(currentConfig.camera) ||
385
+ next.profile !== currentConfig.profile
386
+
387
+ currentConfig = { ...next }
388
+ if (host && sourceChanged) {
389
+ bridge.detach()
390
+ bridge.attach(host, selected())
391
+ }
392
+ },
393
+ focusAtPoint: (point) => {
394
+ try {
395
+ bridge?.focusAtPoint?.(point.x, point.y)
396
+ } catch {
397
+ // A missed metering pass must not fault the session.
398
+ }
399
+ },
400
+ zoomState: () => {
401
+ try {
402
+ const raw = bridge?.zoom?.()
403
+ const value = typeof raw === 'string' ? JSON.parse(raw) : undefined
404
+
405
+ if (
406
+ typeof value?.zoom !== 'number' ||
407
+ typeof value?.minZoom !== 'number' ||
408
+ typeof value?.maxZoom !== 'number'
409
+ ) {
410
+ return undefined
411
+ }
412
+
413
+ return { zoom: value.zoom, minZoom: value.minZoom, maxZoom: value.maxZoom }
414
+ } catch {
415
+ return undefined
416
+ }
417
+ },
418
+ setZoom: (ratio) => {
419
+ try {
420
+ bridge?.setZoom?.(ratio)
421
+ } catch {
422
+ // A refused zoom write must not fault the session.
423
+ }
424
+ },
425
+ switchCamera: (camera) => {
426
+ if (!sink || cameraSwitch || typeof bridge?.confirmCameraSwitch !== 'function') {
427
+ throw error('invalidState', 'switchCamera', 'The native recording cannot switch now')
428
+ }
429
+
430
+ let cancelled = false
431
+ let acquired: CameraDeviceInfo | undefined
432
+ let pending!: PendingCameraSwitch
433
+ const completion = new Promise<CameraDeviceInfo>((resolve, reject) => {
434
+ pending = { resolve, reject }
435
+ cameraSwitch = pending
436
+ try {
437
+ bridge.switchCamera(typeof camera === 'object' ? `id:${camera.deviceId}` : camera)
438
+ } catch (cause) {
439
+ cameraSwitch = undefined
440
+ reject(error('unavailable', 'switchCamera', 'CameraX could not change camera', cause))
441
+ }
442
+ }).then((selected) => {
443
+ if (cancelled) {
444
+ throw error('invalidState', 'switchCamera', 'Camera switching was cancelled')
445
+ }
446
+
447
+ acquired = selected
448
+ return selected
449
+ })
450
+
451
+ return {
452
+ completion,
453
+ commit: () => {
454
+ if (cancelled || cameraSwitch !== pending || !acquired || !sink) {
455
+ throw error(
456
+ 'invalidState',
457
+ 'switchCamera',
458
+ 'Camera switching was cancelled before commit',
459
+ )
460
+ }
461
+
462
+ try {
463
+ bridge.confirmCameraSwitch(acquired.id)
464
+ } catch (cause) {
465
+ switchWarning = error(
466
+ 'unavailable',
467
+ 'switchCamera',
468
+ 'Camera acquisition could not be committed; the take was finalized',
469
+ cause,
470
+ )
471
+
472
+ // This cancellation can occur without a user stop. Restore the
473
+ // prior selection and finalize rather than keep an uncommitted lens.
474
+ sink.finishing('cameraUnavailable')
475
+ bridge.stop()
476
+ throw switchWarning
477
+ }
478
+
479
+ currentConfig = { ...currentConfig, camera }
480
+ cameraSwitch = undefined
481
+ },
482
+ cancel: () => {
483
+ if (cameraSwitch !== pending) {
484
+ return
485
+ }
486
+
487
+ cancelled = true
488
+ cameraSwitch = undefined
489
+ pending.reject(error('invalidState', 'switchCamera', 'Camera switching was cancelled'))
490
+ bridge?.cancelCameraSwitch?.()
491
+ },
492
+ }
493
+ },
494
+ startCapture: (request, target) => {
495
+ sink = target
496
+ switchWarning = undefined
497
+ if (request.destinationPath) {
498
+ // Durable output stays app-private like every other leaf —
499
+ // canonicalize so '..' cannot escape the files root.
500
+ const destination = canonicalizePath(request.destinationPath)
501
+ let filesRoot = ''
502
+
503
+ try {
504
+ filesRoot = context()?.getFilesDir?.().getAbsolutePath?.() ?? ''
505
+ } catch {
506
+ filesRoot = ''
507
+ }
508
+
509
+ if (!filesRoot || !destination.startsWith(`${filesRoot}/`)) {
510
+ sink = undefined
511
+ target.settled({
512
+ kind: 'failed',
513
+ stage: 'preparation',
514
+ issue: error(
515
+ 'destinationUnavailable',
516
+ 'startRecording',
517
+ 'destinationFileUrl must resolve inside the app-private files directory',
518
+ ),
519
+ })
520
+
521
+ return
522
+ }
523
+
524
+ request = { ...request, destinationPath: destination }
525
+ }
526
+
527
+ try {
528
+ bridge.start(
529
+ request.audio,
530
+ request.destinationPath ?? '',
531
+ request.maximumDurationMs === undefined
532
+ ? 0
533
+ : Math.max(1, Math.ceil(request.maximumDurationMs)),
534
+ )
535
+ } catch (cause) {
536
+ sink = undefined
537
+ target.settled({
538
+ kind: 'failed',
539
+ stage: 'preparation',
540
+ issue: error(
541
+ 'captureFailed',
542
+ 'startRecording',
543
+ 'CameraX could not begin recording',
544
+ cause,
545
+ ),
546
+ })
547
+ }
548
+ },
549
+ stopCapture: () => bridge?.stop(),
550
+ elapsedMs: () => Number(bridge?.elapsedMs() ?? 0),
551
+ openOutput: async (output) => {
552
+ if (output.kind !== 'nativeFile' || output.synthetic) {
553
+ throw error('invalidArgument', 'openOutput', 'Expected a native Android movie reference')
554
+ }
555
+
556
+ try {
557
+ const url = nativeBridge().openOutput(output.resourceId, output.fileUrl)
558
+
559
+ return { url, fileUrl: url, release: () => {} }
560
+ } catch (cause) {
561
+ throw error(
562
+ 'destinationUnavailable',
563
+ 'openOutput',
564
+ 'The stored Android movie cannot be reopened',
565
+ cause,
566
+ )
567
+ }
568
+ },
569
+ release: async () => {
570
+ released = true
571
+ Application.off(Application.suspendEvent, onSuspend)
572
+ Application.off(Application.resumeEvent, onResume)
573
+ bridge?.release()
574
+ host = undefined
575
+ releaseLease()
576
+ },
577
+ setObserver: (value) => {
578
+ observer = value
579
+ },
580
+ }
439
581
  }