@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
@@ -1,131 +1,157 @@
1
1
  import { CameraCaptureError } from './types'
2
2
  import type {
3
- CameraInterruptionReason,
4
- CameraPermissionKind,
5
- CameraPermissionStatus,
6
- CameraPreviewPoint,
7
- CameraSession,
8
- CameraSessionCapabilities,
9
- CameraSessionConfig,
10
- CameraSessionEvent,
11
- CameraSessionSnapshot,
12
- CameraSelection,
13
- CaptureIssue,
14
- EffectiveCaptureConfig,
15
- MovieEndReason,
16
- MovieOutcome,
17
- MovieOutput,
18
- MovieOutputHandle,
19
- MovieTake,
20
- StartRecordingOptions,
3
+ CameraInterruptionReason,
4
+ CameraDeviceInfo,
5
+ CameraPermissionKind,
6
+ CameraPermissionStatus,
7
+ CameraPreviewPoint,
8
+ CameraSession,
9
+ CameraSessionCapabilities,
10
+ CameraSessionConfig,
11
+ CameraSessionEvent,
12
+ CameraSessionSnapshot,
13
+ CameraSelection,
14
+ CameraZoomState,
15
+ CaptureIssue,
16
+ EffectiveCaptureConfig,
17
+ MovieEndReason,
18
+ MovieOutcome,
19
+ MovieOutput,
20
+ MovieOutputHandle,
21
+ MovieTake,
22
+ StartRecordingOptions,
21
23
  } from './types'
22
24
 
23
25
  /** Result an adapter reports when a capture attempt settles. Media
24
26
  * metadata is already read from the finalized movie by the adapter. */
25
27
  export type BackendSettle =
26
- | {
27
- kind: 'clip'
28
- output: MovieOutput
29
- mimeType: string
30
- durationMs: number
31
- width: number
32
- height: number
33
- orientation: EffectiveCaptureConfig['orientation']
34
- hasAudio: boolean
35
- /** Native duration-limit enforcement ended the take. */
36
- limitReached?: boolean
37
- /** Adapter-driven endings when no earlier app/lifecycle cause exists. */
38
- endReason?: MovieEndReason
39
- warning?: CaptureIssue
40
- }
41
- | {
42
- kind: 'failed'
43
- stage: 'preparation' | 'capture' | 'finalization' | 'storage'
44
- issue: CaptureIssue
45
- }
28
+ | {
29
+ kind: 'clip'
30
+ output: MovieOutput
31
+ mimeType: string
32
+ durationMs: number
33
+ width: number
34
+ height: number
35
+ orientation: EffectiveCaptureConfig['orientation']
36
+ hasAudio: boolean
37
+ /** Native duration-limit enforcement ended the take. */
38
+ limitReached?: boolean
39
+ /** Adapter-driven endings when no earlier app/lifecycle cause exists. */
40
+ endReason?: MovieEndReason
41
+ warning?: CaptureIssue
42
+ }
43
+ | {
44
+ kind: 'failed'
45
+ stage: 'preparation' | 'capture' | 'finalization' | 'storage'
46
+ issue: CaptureIssue
47
+ }
46
48
 
47
49
  /** Per-attempt callbacks handed to `startCapture`. */
48
50
  export interface BackendCaptureSink {
49
- /** Native capture actually began; exactly once per settled attempt. */
50
- started(config: EffectiveCaptureConfig): void
51
- /** Capture has ended; metadata verification and storage still own the attempt. */
52
- finishing(reason?: MovieEndReason): void
53
- /** Terminal result; exactly once per admitted attempt. */
54
- settled(result: BackendSettle): void
51
+ /** Native capture actually began; exactly once per settled attempt. */
52
+ started(config: EffectiveCaptureConfig): void
53
+ /** Capture has ended; metadata verification and storage still own the attempt. */
54
+ finishing(reason?: MovieEndReason): void
55
+ /** Terminal result; exactly once per admitted attempt. */
56
+ settled(result: BackendSettle): void
55
57
  }
56
58
 
57
59
  export interface BackendCaptureRequest {
58
- audio: boolean
59
- orientation: EffectiveCaptureConfig['orientation'] | undefined
60
- maximumDurationMs: number | undefined
61
- /** Resolved writable path for native adapters. */
62
- destinationPath: string | undefined
60
+ audio: boolean
61
+ orientation: EffectiveCaptureConfig['orientation'] | undefined
62
+ maximumDurationMs: number | undefined
63
+ /** Resolved writable path for native adapters. */
64
+ destinationPath: string | undefined
63
65
  }
64
66
 
65
67
  /** Adapter-owned preview attach. `listener` reports preview lifecycle;
66
68
  * returns the detach function. */
67
69
  export interface BackendPreviewListener {
68
- onReady?: () => void
69
- onError?: (issue: CaptureIssue) => void
70
+ /** The session can admit `startRecording` — recording-admission
71
+ * readiness, not a displayed-frame signal. */
72
+ onReady?: () => void
73
+ /** The attached surface displayed its first live camera frame — a
74
+ * display-readiness signal, separate from `onReady` admission.
75
+ * Adapters fire it on each transition into displayed state; hosts
76
+ * without a distinct display signal never fire it. */
77
+ onDisplayReady?: () => void
78
+ onError?: (issue: CaptureIssue) => void
70
79
  }
71
80
 
72
81
  /** Platform adapter surface driven by the shared session core. Adapters
73
82
  * own permission policy, capability discovery, capture, and local output
74
83
  * access; the core owns states, ordering, causes, and outcomes. */
75
84
  export interface CameraSessionBackend {
76
- readonly platform: string
77
- /** False when the adapter cannot capture on this host; the core
78
- * rejects `startRecording` with `unsupportedPlatform`. */
79
- readonly supported: boolean
80
- checkPermission(kind: CameraPermissionKind): Promise<CameraPermissionStatus>
81
- requestPermission(kind: CameraPermissionKind): Promise<CameraPermissionStatus>
82
- getCapabilities(): Promise<CameraSessionCapabilities>
83
- /** An active, ready preview is attached and the camera source is
84
- * running — the admission requirement for `startRecording`. */
85
- previewReady(): boolean
86
- /** Attach the shared-source preview to a platform view. */
87
- attachPreview(host: unknown, listener?: BackendPreviewListener): () => void
88
- /** Replace configuration while idle; throws CameraCaptureError. */
89
- configure?(config: CameraSessionConfig): void
90
- /** Meter one autofocus/auto-exposure pass at a normalized preview-space
91
- * point — the tap-to-focus primitive. Absent means the adapter cannot
92
- * meter at a point; the core turns it into a no-op. */
93
- focusAtPoint?(point: CameraPreviewPoint): void
94
- /** Synchronous platform-specific admission checks; creates no attempt on failure. */
95
- validateStart?(options: StartRecordingOptions): void
96
- /** Begin capture for an admitted attempt. Async failures settle via
97
- * `sink.settled`; a synchronous throw settles as a preparation failure. */
98
- startCapture(request: BackendCaptureRequest, sink: BackendCaptureSink): void
99
- /** Request capture stop; settlement still arrives via the sink. */
100
- stopCapture(): void
101
- /** Elapsed capture time in ms for the in-flight attempt. */
102
- elapsedMs(): number
103
- openOutput(output: MovieOutput): Promise<MovieOutputHandle>
104
- /** Release camera ownership. The core calls this only after any
105
- * in-flight attempt has settled. */
106
- release(): Promise<void>
107
- /** Reattach/reconfigure bookkeeping when the preview view is detached
108
- * while an attempt is settling — the adapter keeps hardware until
109
- * settlement, then stops. */
110
- onPreviewDetached?(): void
111
- /** Lifecycle observations the adapter emits at any time. */
112
- setObserver(observer: BackendObserver | undefined): void
85
+ readonly platform: string
86
+ /** False when the adapter cannot capture on this host; the core
87
+ * rejects `startRecording` with `unsupportedPlatform`. */
88
+ readonly supported: boolean
89
+ checkPermission(kind: CameraPermissionKind): Promise<CameraPermissionStatus>
90
+ requestPermission(kind: CameraPermissionKind): Promise<CameraPermissionStatus>
91
+ getCapabilities(): Promise<CameraSessionCapabilities>
92
+ /** An active, ready preview is attached and the camera source is
93
+ * running — the admission requirement for `startRecording`. */
94
+ previewReady(): boolean
95
+ /** Attach the shared-source preview to a platform view. */
96
+ attachPreview(host: unknown, listener?: BackendPreviewListener): () => void
97
+ /** Replace configuration while idle; throws CameraCaptureError. */
98
+ configure?(config: CameraSessionConfig): void
99
+ /** Live camera-only swap. The adapter holds recorded video and keeps
100
+ * audio/output alive. Cancellation must retire late hardware callbacks. */
101
+ switchCamera?(camera: CameraSelection): BackendCameraSwitch
102
+ /** Meter one autofocus/auto-exposure pass at a normalized preview-space
103
+ * point — the tap-to-focus primitive. Absent means the adapter cannot
104
+ * meter at a point; the core turns it into a no-op. */
105
+ focusAtPoint?(point: CameraPreviewPoint): void
106
+ /** Live zoom state of the bound device; absent or `undefined` means the
107
+ * adapter exposes no zoom control. */
108
+ zoomState?(): CameraZoomState | undefined
109
+ /** Write a zoom ratio already clamped by the core. Absent means the
110
+ * adapter exposes no zoom control. */
111
+ setZoom?(ratio: number): void
112
+ /** Synchronous platform-specific admission checks; creates no attempt on failure. */
113
+ validateStart?(options: StartRecordingOptions): void
114
+ /** Begin capture for an admitted attempt. Async failures settle via
115
+ * `sink.settled`; a synchronous throw settles as a preparation failure. */
116
+ startCapture(request: BackendCaptureRequest, sink: BackendCaptureSink): void
117
+ /** Request capture stop; settlement still arrives via the sink. */
118
+ stopCapture(): void
119
+ /** Elapsed capture time in ms for the in-flight attempt. */
120
+ elapsedMs(): number
121
+ openOutput(output: MovieOutput): Promise<MovieOutputHandle>
122
+ /** Release camera ownership. The core calls this only after any
123
+ * in-flight attempt has settled. */
124
+ release(): Promise<void>
125
+ /** Reattach/reconfigure bookkeeping when the preview view is detached
126
+ * while an attempt is settling — the adapter keeps hardware until
127
+ * settlement, then stops. */
128
+ onPreviewDetached?(): void
129
+ /** Lifecycle observations the adapter emits at any time. */
130
+ setObserver(observer: BackendObserver | undefined): void
131
+ }
132
+
133
+ export interface BackendCameraSwitch {
134
+ completion: Promise<CameraDeviceInfo>
135
+ /** Commit a provisionally acquired source after the lifecycle recheck.
136
+ * Cancellation must remain effective until this synchronous handoff. */
137
+ commit?(): void
138
+ cancel(): void
113
139
  }
114
140
 
115
141
  export interface BackendObserver {
116
- interruption(phase: 'began' | 'ended', reason?: CameraInterruptionReason): void
117
- availability(available: boolean): void
118
- /** Preview became ready/unready (session running state changed). */
119
- previewReady(ready: boolean): void
142
+ interruption(phase: 'began' | 'ended', reason?: CameraInterruptionReason): void
143
+ availability(available: boolean): void
144
+ /** Preview became ready/unready (session running state changed). */
145
+ previewReady(ready: boolean): void
120
146
  }
121
147
 
122
148
  let attemptCounter = 0
123
149
 
124
150
  const issue = (
125
- kind: CaptureIssue['kind'],
126
- operation: string,
127
- message: string,
128
- extra?: Partial<CaptureIssue>,
151
+ kind: CaptureIssue['kind'],
152
+ operation: string,
153
+ message: string,
154
+ extra?: Partial<CaptureIssue>,
129
155
  ): CameraCaptureError => new CameraCaptureError({ kind, operation, message, ...extra })
130
156
 
131
157
  /** Collapse '.' and '..' segments without touching the filesystem — the
@@ -133,627 +159,812 @@ const issue = (
133
159
  * form, so a '..' inside the requested path can never keep the root
134
160
  * prefix while escaping it. */
135
161
  export const canonicalizePath = (raw: string, separator = '/'): string => {
136
- const rooted = raw.startsWith(separator)
137
- const parts: string[] = []
138
- for (const part of raw.split(separator)) {
139
- if (part === '' || part === '.') {
140
- continue
141
- }
142
-
143
- if (part === '..') {
144
- if (parts.length > 0 && parts[parts.length - 1] !== '..') {
145
- parts.pop()
146
- } else if (!rooted) {
147
- parts.push(part)
148
- }
149
-
150
- continue
151
- }
152
-
153
- parts.push(part)
154
- }
155
-
156
- return (rooted ? separator : '') + parts.join(separator)
162
+ const rooted = raw.startsWith(separator)
163
+ const parts: string[] = []
164
+
165
+ for (const part of raw.split(separator)) {
166
+ if (part === '' || part === '.') {
167
+ continue
168
+ }
169
+
170
+ if (part === '..') {
171
+ if (parts.length > 0 && parts[parts.length - 1] !== '..') {
172
+ parts.pop()
173
+ } else if (!rooted) {
174
+ parts.push(part)
175
+ }
176
+
177
+ continue
178
+ }
179
+
180
+ parts.push(part)
181
+ }
182
+
183
+ return (rooted ? separator : '') + parts.join(separator)
157
184
  }
158
185
 
159
186
  /** The concrete session object wrapping a platform backend. Internal to
160
187
  * the package; `CameraSession` is the public shape. */
161
188
  export class SharedCameraSession implements CameraSession {
162
- private backend: CameraSessionBackend
163
- private config: CameraSessionConfig
164
- private listeners = new Set<(event: CameraSessionEvent) => void>()
165
- private state: CameraSessionSnapshot['state'] = 'idle'
166
- private permission: Record<CameraPermissionKind, CameraPermissionStatus> = {
167
- camera: 'unknown',
168
- microphone: 'unknown',
169
- }
170
- private cameraAvailable = true
171
- private previewAttached = false
172
- private interrupted = false
173
- private pendingOnReady: (() => void) | undefined
174
- private disposeRequested = false
175
- private disposed = false
176
- private lastCapabilities: CameraSessionCapabilities | undefined
177
- private requestChains = new Map<CameraPermissionKind, Promise<CameraPermissionStatus>>()
178
-
179
- private attempt:
180
- | {
181
- id: string
182
- state: 'starting' | 'recording' | 'finalizing' | 'settled'
183
- stopRequested: boolean
184
- cause?: MovieEndReason
185
- startedAt?: number
186
- configuration?: EffectiveCaptureConfig
187
- resolve: (outcome: MovieOutcome) => void
188
- completion: Promise<MovieOutcome>
189
- limitTimer?: ReturnType<typeof setTimeout>
190
- }
191
- | undefined
192
-
193
- constructor(backend: CameraSessionBackend, config: CameraSessionConfig) {
194
- this.backend = backend
195
- this.config = { ...config }
196
- backend.setObserver({
197
- interruption: (phase, reason) => this.handleInterruption(phase, reason),
198
- availability: (available) => this.handleAvailability(available),
199
- previewReady: (ready) => {
200
- // A retracted readiness signal invalidates a pending onReady;
201
- // a delivered one retries admission.
202
- if (!ready) {
203
- this.pendingOnReady = undefined
204
- }
205
-
206
- this.flushPendingReady()
207
- this.emit({ type: 'stateChanged', snapshot: this.snapshot() })
208
- },
209
- })
210
- }
211
-
212
- /** Package-internal: attach a preview host to this session. */
213
- attach(host: unknown, listener?: BackendPreviewListener): () => void {
214
- if (this.disposed || this.disposeRequested) {
215
- throw issue('invalidState', 'attachPreview', 'CameraSession is disposed')
216
- }
217
-
218
- if (this.previewAttached) {
219
- throw issue('invalidState', 'attachPreview', 'CameraSession already has a preview')
220
- }
221
-
222
- const detach = this.backend.attachPreview(host, {
223
- onReady: listener?.onReady
224
- ? () => {
225
- this.pendingOnReady = listener.onReady
226
- this.flushPendingReady()
227
- }
228
- : undefined,
229
- onError: (captureIssue) => {
230
- listener?.onError?.(captureIssue)
231
- },
232
- })
233
-
234
- this.previewAttached = true
235
- this.emit({ type: 'stateChanged', snapshot: this.snapshot() })
236
- return () => {
237
- this.detachInternal(detach)
238
- }
239
- }
240
-
241
- get attached(): boolean {
242
- return this.previewAttached
243
- }
244
-
245
- private detachInternal(detach: () => void) {
246
- if (!this.previewAttached) {
247
- return
248
- }
249
-
250
- this.previewAttached = false
251
- this.pendingOnReady = undefined
252
- const attempt = this.attempt
253
- if (attempt && (attempt.state === 'starting' || attempt.state === 'recording')) {
254
- this.requestStop('previewReleased')
255
- }
256
-
257
- detach()
258
- this.backend.onPreviewDetached?.()
259
- this.emit({ type: 'stateChanged', snapshot: this.snapshot() })
260
- }
261
-
262
- /** `onReady` means "recording can start": it is delivered only while
263
- * the session would actually admit `startRecording`. Adapters emit
264
- * their availability/interruption observations in their own order, so
265
- * a ready signal that arrives before those updates settles pends
266
- * until the next lifecycle event makes admission possible — or is
267
- * dropped if readiness is retracted first. */
268
- private flushPendingReady() {
269
- const pending = this.pendingOnReady
270
- if (!pending || this.interrupted || !this.cameraAvailable || !this.backend.previewReady()) {
271
- return
272
- }
273
-
274
- this.pendingOnReady = undefined
275
- pending()
276
- }
277
-
278
- private emit(event: CameraSessionEvent) {
279
- for (const listener of this.listeners) {
280
- try {
281
- listener(event)
282
- } catch {
283
- // Listener exceptions must not change capture behavior.
284
- }
285
- }
286
- }
287
-
288
- private setState(state: CameraSessionSnapshot['state']) {
289
- if (this.state === state) {
290
- return
291
- }
292
-
293
- this.state = state
294
- this.emit({ type: 'stateChanged', snapshot: this.snapshot() })
295
- }
296
-
297
- snapshot(): CameraSessionSnapshot {
298
- const attempt = this.attempt
299
- return {
300
- state: this.state,
301
- permission: { ...this.permission },
302
- cameraAvailable: this.cameraAvailable,
303
- previewAttached: this.previewAttached,
304
- interrupted: this.interrupted,
305
- attempt:
306
- attempt && attempt.state !== 'settled'
307
- ? {
308
- id: attempt.id,
309
- state: attempt.state,
310
- elapsedMs: this.backend.elapsedMs(),
311
- configuration: attempt.configuration,
312
- }
313
- : undefined,
314
- }
315
- }
316
-
317
- subscribe(listener: (event: CameraSessionEvent) => void): () => void {
318
- this.listeners.add(listener)
319
- return () => {
320
- this.listeners.delete(listener)
321
- }
322
- }
323
-
324
- async permissions(): Promise<{
325
- camera: CameraPermissionStatus
326
- microphone: CameraPermissionStatus
327
- }> {
328
- const [camera, microphone] = await Promise.all([
329
- this.backend.checkPermission('camera'),
330
- this.backend.checkPermission('microphone'),
331
- ])
332
-
333
- this.permission = { camera, microphone }
334
- this.emit({ type: 'stateChanged', snapshot: this.snapshot() })
335
- return { ...this.permission }
336
- }
337
-
338
- requestPermission(kind: CameraPermissionKind): Promise<CameraPermissionStatus> {
339
- const chain = (
340
- this.requestChains.get(kind) ?? Promise.resolve('unknown' as CameraPermissionStatus)
341
- ).then(async () => {
342
- if (this.disposed) {
343
- return this.permission[kind]
344
- }
345
-
346
- const status = await this.backend.requestPermission(kind)
347
- this.permission = { ...this.permission, [kind]: status }
348
- this.emit({ type: 'stateChanged', snapshot: this.snapshot() })
349
- return status
350
- })
351
-
352
- // Store a swallowed continuation — a rejected backend call must not
353
- // poison the chain and refuse every later request with the original
354
- // error. The caller still receives the real rejection.
355
- this.requestChains.set(
356
- kind,
357
- chain.catch(() => 'unknown' as CameraPermissionStatus),
358
- )
359
-
360
- return chain
361
- }
362
-
363
- async capabilities(): Promise<CameraSessionCapabilities> {
364
- const capabilities = await this.backend.getCapabilities()
365
- this.lastCapabilities = capabilities
366
- return capabilities
367
- }
368
-
369
- focusAtPoint(point: CameraPreviewPoint): void {
370
- if (!point || !Number.isFinite(point.x) || !Number.isFinite(point.y)) {
371
- throw issue('invalidArgument', 'focusAtPoint', 'point.x and point.y must be finite numbers')
372
- }
373
-
374
- if (this.disposed || this.disposeRequested) {
375
- return
376
- }
377
-
378
- this.backend.focusAtPoint?.({
379
- x: Math.min(1, Math.max(0, point.x)),
380
- y: Math.min(1, Math.max(0, point.y)),
381
- })
382
- }
383
-
384
- async configure(next: Partial<CameraSessionConfig>): Promise<void> {
385
- if (this.disposed || this.disposeRequested) {
386
- throw issue('invalidState', 'configure', 'CameraSession is disposed')
387
- }
388
-
389
- if (this.state !== 'idle') {
390
- throw issue('invalidState', 'configure', `CameraSession cannot configure while ${this.state}`)
391
- }
392
-
393
- const merged: CameraSessionConfig = { ...this.config, ...next }
394
- const capabilities = await this.capabilities()
395
- this.validateCameraSelection(merged.camera, capabilities)
396
- this.config = merged
397
- this.backend.configure?.(merged)
398
- }
399
-
400
- private validateCameraSelection(
401
- camera: CameraSelection | undefined,
402
- capabilities: CameraSessionCapabilities,
403
- ) {
404
- if (camera && typeof camera === 'object' && 'deviceId' in camera) {
405
- const known = capabilities.cameras.some((entry) => entry.id === camera.deviceId)
406
- if (!known) {
407
- throw issue(
408
- 'unsupportedConfiguration',
409
- 'configure',
410
- `Camera device '${camera.deviceId}' is not available`,
411
- )
412
- }
413
- } else if (camera === 'front' || camera === 'back') {
414
- const known = capabilities.cameras.some((entry) => entry.facing === camera)
415
- if (!known && capabilities.cameras.length > 0) {
416
- throw issue(
417
- 'unsupportedConfiguration',
418
- 'configure',
419
- `No ${camera}-facing camera is available`,
420
- )
421
- }
422
- }
423
- }
424
-
425
- private requestStop(cause: MovieEndReason) {
426
- const attempt = this.attempt
427
- if (!attempt || attempt.state === 'finalizing' || attempt.state === 'settled') {
428
- return
429
- }
430
-
431
- attempt.stopRequested = true
432
- attempt.cause ??= cause
433
- if (attempt.state === 'recording') {
434
- this.setState('finalizing')
435
- attempt.state = 'finalizing'
436
- try {
437
- this.backend.stopCapture()
438
- } catch {
439
- // A stop failure still resolves through the settle path or a
440
- // backend timeout; nothing more to do here.
441
- }
442
- }
443
- }
444
-
445
- private handleInterruption(phase: 'began' | 'ended', reason?: CameraInterruptionReason) {
446
- this.interrupted = phase === 'began'
447
- this.emit({ type: 'interruption', phase, reason })
448
- if (phase === 'began') {
449
- const cause: MovieEndReason =
450
- reason === 'background'
451
- ? 'backgrounded'
452
- : reason === 'cameraInUse'
453
- ? 'cameraUnavailable'
454
- : 'interrupted'
455
-
456
- this.requestStop(cause)
457
- }
458
-
459
- this.flushPendingReady()
460
- this.emit({ type: 'stateChanged', snapshot: this.snapshot() })
461
- }
462
-
463
- private handleAvailability(available: boolean) {
464
- if (this.cameraAvailable === available) {
465
- return
466
- }
467
-
468
- this.cameraAvailable = available
469
- this.emit({ type: 'availability', available })
470
- if (!available) {
471
- this.requestStop('cameraUnavailable')
472
- }
473
-
474
- this.flushPendingReady()
475
- this.emit({ type: 'stateChanged', snapshot: this.snapshot() })
476
- }
477
-
478
- startRecording(options: StartRecordingOptions = {}): MovieTake {
479
- const operation = 'startRecording'
480
- if (this.disposed || this.disposeRequested) {
481
- throw issue('invalidState', operation, 'CameraSession is disposed')
482
- }
483
-
484
- if (!this.backend.supported) {
485
- throw issue(
486
- 'unsupportedPlatform',
487
- operation,
488
- 'Movie recording is unsupported on this platform',
489
- )
490
- }
491
-
492
- if (this.state !== 'idle' || this.attempt) {
493
- throw issue('busy', operation, `CameraSession is ${this.state}`)
494
- }
495
-
496
- if (options.maximumDurationMs !== undefined) {
497
- const value = options.maximumDurationMs
498
- if (!Number.isFinite(value) || value <= 0) {
499
- throw issue(
500
- 'invalidArgument',
501
- operation,
502
- 'maximumDurationMs must be a positive finite number of milliseconds',
503
- )
504
- }
505
- }
506
-
507
- let destinationPath: string | undefined
508
- if (options.destinationFileUrl !== undefined) {
509
- if (!options.destinationFileUrl.startsWith('file://')) {
510
- throw issue('invalidArgument', operation, 'destinationFileUrl must be a local file:// URL')
511
- }
512
-
513
- try {
514
- destinationPath = decodeURIComponent(options.destinationFileUrl.slice('file://'.length))
515
- } catch (cause) {
516
- throw issue(
517
- 'invalidArgument',
518
- operation,
519
- 'destinationFileUrl is not valid percent-encoding',
520
- { cause },
521
- )
522
- }
523
- }
524
-
525
- if (
526
- options.orientation !== undefined &&
527
- options.orientation !== 'unspecified' &&
528
- this.lastCapabilities &&
529
- !this.lastCapabilities.orientations.includes(options.orientation)
530
- ) {
531
- throw issue(
532
- 'unsupportedConfiguration',
533
- 'startRecording',
534
- `Orientation '${options.orientation}' is not advertised by this camera`,
535
- )
536
- }
537
-
538
- if (this.interrupted || !this.cameraAvailable || !this.backend.previewReady()) {
539
- throw issue(
540
- 'unavailable',
541
- operation,
542
- this.interrupted
543
- ? 'Camera session is interrupted'
544
- : !this.cameraAvailable
545
- ? 'Camera is unavailable'
546
- : 'An active, ready preview is required before recording',
547
- )
548
- }
549
-
550
- this.backend.validateStart?.(options)
551
-
552
- attemptCounter += 1
553
- const id = `take-${Date.now()}-${attemptCounter}`
554
- let resolveCompletion!: (outcome: MovieOutcome) => void
555
- const completion = new Promise<MovieOutcome>((resolve) => {
556
- resolveCompletion = resolve
557
- })
558
-
559
- const attempt: {
560
- id: string
561
- state: 'starting' | 'recording' | 'finalizing' | 'settled'
562
- stopRequested: boolean
563
- cause?: MovieEndReason
564
- startedAt?: number
565
- configuration?: EffectiveCaptureConfig
566
- resolve: (outcome: MovieOutcome) => void
567
- completion: Promise<MovieOutcome>
568
- limitTimer?: ReturnType<typeof setTimeout>
569
- } = {
570
- id,
571
- state: 'starting',
572
- stopRequested: false,
573
- resolve: resolveCompletion,
574
- completion,
575
- }
576
-
577
- this.attempt = attempt
578
- this.setState('starting')
579
-
580
- const capabilities = this.lastCapabilities
581
- const sink: BackendCaptureSink = {
582
- started: (configuration) => {
583
- const current = this.attempt
584
- if (!current || current.id !== id || current.state === 'settled') {
585
- return
586
- }
587
-
588
- current.configuration = configuration
589
- current.startedAt = Date.now()
590
- if (current.state === 'starting') {
591
- current.state = 'recording'
592
- this.setState('recording')
593
- this.emit({ type: 'started', attemptId: id, configuration })
594
- if (
595
- options.maximumDurationMs !== undefined &&
596
- capabilities?.durationLimit === 'bestEffort'
597
- ) {
598
- const limit = options.maximumDurationMs
599
- const checkLimit = () => {
600
- if (this.attempt?.id !== id || current.state !== 'recording') {
601
- return
602
- }
603
-
604
- const remaining = limit - this.backend.elapsedMs()
605
- if (remaining > 0) {
606
- current.limitTimer = setTimeout(checkLimit, Math.min(remaining, 2_147_483_647))
607
- } else {
608
- this.requestStop('maximumDuration')
609
- }
610
- }
611
-
612
- current.limitTimer = setTimeout(checkLimit, Math.min(limit, 2_147_483_647))
613
- }
614
-
615
- if (current.stopRequested) {
616
- this.requestStop(current.cause ?? 'stopped')
617
- }
618
- }
619
- },
620
- finishing: (reason) => {
621
- const current = this.attempt
622
- if (!current || current.id !== id || current.state === 'settled') {
623
- return
624
- }
625
-
626
- current.cause ??= reason
627
- current.state = 'finalizing'
628
- this.setState('finalizing')
629
- },
630
- settled: (result) => {
631
- const current = this.attempt
632
- if (!current || current.id !== id || current.state === 'settled') {
633
- return
634
- }
635
-
636
- if (current.limitTimer) {
637
- clearTimeout(current.limitTimer)
638
- }
639
-
640
- current.state = 'settled'
641
- const cause = current.cause ?? (result.kind === 'clip' ? result.endReason : undefined)
642
- const outcome: MovieOutcome =
643
- result.kind === 'clip'
644
- ? {
645
- kind: 'clip',
646
- clip: {
647
- output: result.output,
648
- mimeType: result.mimeType,
649
- durationMs: result.durationMs,
650
- width: result.width,
651
- height: result.height,
652
- orientation: result.orientation,
653
- hasAudio: result.hasAudio,
654
- },
655
- endReason: cause ?? (result.limitReached ? 'maximumDuration' : 'stopped'),
656
- partial: cause !== undefined && cause !== 'stopped' && cause !== 'maximumDuration',
657
- warning: result.warning,
658
- }
659
- : {
660
- kind: 'failed',
661
- endReason: cause ?? 'captureError',
662
- stage: result.stage,
663
- error: new CameraCaptureError(result.issue),
664
- }
665
-
666
- this.attempt = undefined
667
- current.resolve(outcome)
668
- this.emit({ type: 'finished', attemptId: id, outcome })
669
- if (this.disposeRequested) {
670
- void this.finishDispose()
671
- } else {
672
- this.setState('idle')
673
- }
674
- },
675
- }
676
-
677
- const request: BackendCaptureRequest = {
678
- audio: this.config.audio === true,
679
- orientation: options.orientation,
680
- maximumDurationMs: options.maximumDurationMs,
681
- destinationPath,
682
- }
683
-
684
- try {
685
- this.backend.startCapture(request, sink)
686
- } catch (cause) {
687
- sink.settled({
688
- kind: 'failed',
689
- stage: 'preparation',
690
- issue:
691
- cause instanceof CameraCaptureError
692
- ? cause
693
- : {
694
- kind: 'captureFailed',
695
- operation: 'startRecording',
696
- message: cause instanceof Error ? cause.message : String(cause),
697
- cause,
698
- },
699
- })
700
- }
701
-
702
- const backend = this.backend
703
- const take: MovieTake = {
704
- id,
705
- get state() {
706
- return attempt.state
707
- },
708
- get elapsedMs() {
709
- return attempt.state === 'recording' || attempt.state === 'finalizing'
710
- ? backend.elapsedMs()
711
- : 0
712
- },
713
- completion,
714
- stop: () => {
715
- if (this.attempt?.id === id) {
716
- this.requestStop('stopped')
717
- }
718
-
719
- return completion
720
- },
721
- }
722
-
723
- return take
724
- }
725
-
726
- openOutput(output: MovieOutput): Promise<MovieOutputHandle> {
727
- return this.backend.openOutput(output)
728
- }
729
-
730
- async dispose(): Promise<void> {
731
- if (this.disposed) {
732
- return
733
- }
734
-
735
- this.disposeRequested = true
736
- const attempt = this.attempt
737
- if (attempt && attempt.state !== 'settled') {
738
- this.requestStop('disposed')
739
- await attempt.completion
740
- }
741
-
742
- await this.finishDispose()
743
- }
744
-
745
- private async finishDispose() {
746
- if (this.disposed) {
747
- return
748
- }
749
-
750
- this.disposed = true
751
- this.pendingOnReady = undefined
752
- this.backend.setObserver(undefined)
753
- try {
754
- await this.backend.release()
755
- } finally {
756
- this.setState('disposed')
757
- }
758
- }
189
+ private backend: CameraSessionBackend
190
+ private config: CameraSessionConfig
191
+ private listeners = new Set<(event: CameraSessionEvent) => void>()
192
+ private state: CameraSessionSnapshot['state'] = 'idle'
193
+ private permission: Record<CameraPermissionKind, CameraPermissionStatus> = {
194
+ camera: 'unknown',
195
+ microphone: 'unknown',
196
+ }
197
+ private cameraAvailable = true
198
+ private previewAttached = false
199
+ private interrupted = false
200
+ private pendingOnReady: (() => void) | undefined
201
+ private disposeRequested = false
202
+ private disposed = false
203
+ private lastCapabilities: CameraSessionCapabilities | undefined
204
+ private requestChains = new Map<CameraPermissionKind, Promise<CameraPermissionStatus>>()
205
+ private activeCamera: CameraDeviceInfo | undefined
206
+ private cameraSwitch: { cancelled: boolean; cancel?: () => void; abort: () => void } | undefined
207
+
208
+ private attempt:
209
+ | {
210
+ id: string
211
+ state: 'starting' | 'recording' | 'finalizing' | 'settled'
212
+ stopRequested: boolean
213
+ cause?: MovieEndReason
214
+ startedAt?: number
215
+ configuration?: EffectiveCaptureConfig
216
+ resolve: (outcome: MovieOutcome) => void
217
+ completion: Promise<MovieOutcome>
218
+ limitTimer?: ReturnType<typeof setTimeout>
219
+ }
220
+ | undefined
221
+
222
+ constructor(backend: CameraSessionBackend, config: CameraSessionConfig) {
223
+ this.backend = backend
224
+ this.config = { ...config }
225
+ backend.setObserver({
226
+ interruption: (phase, reason) => this.handleInterruption(phase, reason),
227
+ availability: (available) => this.handleAvailability(available),
228
+ previewReady: (ready) => {
229
+ // A retracted readiness signal invalidates a pending onReady;
230
+ // a delivered one retries admission.
231
+ if (!ready) {
232
+ this.pendingOnReady = undefined
233
+ }
234
+
235
+ this.flushPendingReady()
236
+ this.emit({ type: 'stateChanged', snapshot: this.snapshot() })
237
+ },
238
+ })
239
+ }
240
+
241
+ /** Package-internal: attach a preview host to this session. */
242
+ attach(host: unknown, listener?: BackendPreviewListener): () => void {
243
+ if (this.disposed || this.disposeRequested) {
244
+ throw issue('invalidState', 'attachPreview', 'CameraSession is disposed')
245
+ }
246
+
247
+ if (this.previewAttached) {
248
+ throw issue('invalidState', 'attachPreview', 'CameraSession already has a preview')
249
+ }
250
+
251
+ const detach = this.backend.attachPreview(host, {
252
+ onReady: listener?.onReady
253
+ ? () => {
254
+ if (this.state !== 'idle' || this.cameraSwitch) {
255
+ return
256
+ }
257
+
258
+ this.pendingOnReady = listener.onReady
259
+ this.flushPendingReady()
260
+ }
261
+ : undefined,
262
+ onError: (captureIssue) => {
263
+ listener?.onError?.(captureIssue)
264
+ },
265
+ onDisplayReady: listener?.onDisplayReady
266
+ ? () => {
267
+ if (!this.disposed) {
268
+ listener.onDisplayReady!()
269
+ }
270
+ }
271
+ : undefined,
272
+ })
273
+
274
+ this.previewAttached = true
275
+ this.emit({ type: 'stateChanged', snapshot: this.snapshot() })
276
+ return () => {
277
+ this.detachInternal(detach)
278
+ }
279
+ }
280
+
281
+ get attached(): boolean {
282
+ return this.previewAttached
283
+ }
284
+
285
+ private detachInternal(detach: () => void) {
286
+ if (!this.previewAttached) {
287
+ return
288
+ }
289
+
290
+ this.previewAttached = false
291
+ this.pendingOnReady = undefined
292
+
293
+ const attempt = this.attempt
294
+
295
+ if (attempt && (attempt.state === 'starting' || attempt.state === 'recording')) {
296
+ this.requestStop('previewReleased')
297
+ }
298
+
299
+ detach()
300
+ this.backend.onPreviewDetached?.()
301
+ this.emit({ type: 'stateChanged', snapshot: this.snapshot() })
302
+ }
303
+
304
+ /** `onReady` means "recording can start": it is delivered only while
305
+ * the session would actually admit `startRecording`. Adapters emit
306
+ * their availability/interruption observations in their own order, so
307
+ * a ready signal that arrives before those updates settles pends
308
+ * until the next lifecycle event makes admission possible — or is
309
+ * dropped if readiness is retracted first. */
310
+ private flushPendingReady() {
311
+ const pending = this.pendingOnReady
312
+
313
+ if (!pending || this.interrupted || !this.cameraAvailable || !this.backend.previewReady()) {
314
+ return
315
+ }
316
+
317
+ this.pendingOnReady = undefined
318
+ pending()
319
+ }
320
+
321
+ private emit(event: CameraSessionEvent) {
322
+ for (const listener of this.listeners) {
323
+ try {
324
+ listener(event)
325
+ } catch {
326
+ // Listener exceptions must not change capture behavior.
327
+ }
328
+ }
329
+ }
330
+
331
+ private setState(state: CameraSessionSnapshot['state']) {
332
+ if (this.state === state) {
333
+ return
334
+ }
335
+
336
+ this.state = state
337
+ this.emit({ type: 'stateChanged', snapshot: this.snapshot() })
338
+ }
339
+
340
+ snapshot(): CameraSessionSnapshot {
341
+ const attempt = this.attempt
342
+
343
+ return {
344
+ switchingCamera: this.cameraSwitch !== undefined,
345
+ activeCamera: this.activeCamera ? { ...this.activeCamera } : undefined,
346
+ state: this.state,
347
+ permission: { ...this.permission },
348
+ cameraAvailable: this.cameraAvailable,
349
+ previewAttached: this.previewAttached,
350
+ interrupted: this.interrupted,
351
+ attempt:
352
+ attempt && attempt.state !== 'settled'
353
+ ? {
354
+ id: attempt.id,
355
+ state: attempt.state,
356
+ elapsedMs: this.backend.elapsedMs(),
357
+ configuration: attempt.configuration,
358
+ }
359
+ : undefined,
360
+ }
361
+ }
362
+
363
+ subscribe(listener: (event: CameraSessionEvent) => void): () => void {
364
+ this.listeners.add(listener)
365
+ return () => {
366
+ this.listeners.delete(listener)
367
+ }
368
+ }
369
+
370
+ async permissions(): Promise<{
371
+ camera: CameraPermissionStatus
372
+ microphone: CameraPermissionStatus
373
+ }> {
374
+ const [camera, microphone] = await Promise.all([
375
+ this.backend.checkPermission('camera'),
376
+ this.backend.checkPermission('microphone'),
377
+ ])
378
+
379
+ this.permission = { camera, microphone }
380
+ this.emit({ type: 'stateChanged', snapshot: this.snapshot() })
381
+ return { ...this.permission }
382
+ }
383
+
384
+ requestPermission(kind: CameraPermissionKind): Promise<CameraPermissionStatus> {
385
+ const chain = (
386
+ this.requestChains.get(kind) ?? Promise.resolve('unknown' as CameraPermissionStatus)
387
+ ).then(async () => {
388
+ if (this.disposed) {
389
+ return this.permission[kind]
390
+ }
391
+
392
+ const status = await this.backend.requestPermission(kind)
393
+
394
+ this.permission = { ...this.permission, [kind]: status }
395
+ this.emit({ type: 'stateChanged', snapshot: this.snapshot() })
396
+ return status
397
+ })
398
+
399
+ // Store a swallowed continuation — a rejected backend call must not
400
+ // poison the chain and refuse every later request with the original
401
+ // error. The caller still receives the real rejection.
402
+ this.requestChains.set(
403
+ kind,
404
+ chain.catch(() => 'unknown' as CameraPermissionStatus),
405
+ )
406
+
407
+ return chain
408
+ }
409
+
410
+ async capabilities(): Promise<CameraSessionCapabilities> {
411
+ const capabilities = await this.backend.getCapabilities()
412
+
413
+ this.lastCapabilities = capabilities
414
+ return capabilities
415
+ }
416
+
417
+ focusAtPoint(point: CameraPreviewPoint): void {
418
+ if (!point || !Number.isFinite(point.x) || !Number.isFinite(point.y)) {
419
+ throw issue('invalidArgument', 'focusAtPoint', 'point.x and point.y must be finite numbers')
420
+ }
421
+
422
+ if (this.disposed || this.disposeRequested) {
423
+ return
424
+ }
425
+
426
+ this.backend.focusAtPoint?.({
427
+ x: Math.min(1, Math.max(0, point.x)),
428
+ y: Math.min(1, Math.max(0, point.y)),
429
+ })
430
+ }
431
+
432
+ zoomState(): CameraZoomState | undefined {
433
+ if (this.disposed || this.disposeRequested) {
434
+ return undefined
435
+ }
436
+
437
+ return this.backend.zoomState?.()
438
+ }
439
+
440
+ setZoom(ratio: number): void {
441
+ if (!Number.isFinite(ratio)) {
442
+ throw issue('invalidArgument', 'setZoom', 'ratio must be a finite number')
443
+ }
444
+
445
+ const state = this.zoomState()
446
+
447
+ if (!state || !this.backend.setZoom) {
448
+ return
449
+ }
450
+
451
+ this.backend.setZoom(Math.min(state.maxZoom, Math.max(state.minZoom, ratio)))
452
+ }
453
+
454
+ private assertConfigurable() {
455
+ if (this.cameraSwitch) {
456
+ throw issue('busy', 'configure', 'A camera switch is still settling')
457
+ }
458
+
459
+ if (this.disposed || this.disposeRequested) {
460
+ throw issue('invalidState', 'configure', 'CameraSession is disposed')
461
+ }
462
+
463
+ if (this.state !== 'idle') {
464
+ throw issue('invalidState', 'configure', `CameraSession cannot configure while ${this.state}`)
465
+ }
466
+ }
467
+
468
+ async switchCamera(camera: CameraSelection): Promise<void> {
469
+ const attempt = this.attempt
470
+
471
+ if (this.disposeRequested || this.disposed || this.state !== 'recording' || !attempt) {
472
+ throw issue('invalidState', 'switchCamera', 'Camera switching requires an active recording')
473
+ }
474
+
475
+ if (this.cameraSwitch) {
476
+ throw issue('busy', 'switchCamera', 'A camera switch is already pending')
477
+ }
478
+
479
+ const pending = {
480
+ cancelled: false,
481
+ cancel: undefined as (() => void) | undefined,
482
+ abort: () => {},
483
+ }
484
+
485
+ const aborted = new Promise<never>((_resolve, reject) => {
486
+ pending.abort = () => {
487
+ if (pending.cancelled) {
488
+ return
489
+ }
490
+
491
+ pending.cancelled = true
492
+ try {
493
+ pending.cancel?.()
494
+ } catch {
495
+ // Cancellation cannot prevent stop/finalization ownership.
496
+ }
497
+
498
+ reject(issue('invalidState', 'switchCamera', 'Camera switching was cancelled'))
499
+ }
500
+ })
501
+
502
+ this.cameraSwitch = pending
503
+ this.emit({ type: 'stateChanged', snapshot: this.snapshot() })
504
+
505
+ const check = () => {
506
+ if (pending.cancelled || this.attempt !== attempt || this.state !== 'recording') {
507
+ throw issue('invalidState', 'switchCamera', 'The recording is no longer active')
508
+ }
509
+ }
510
+
511
+ try {
512
+ await Promise.race([
513
+ (async () => {
514
+ const capabilities = await this.capabilities()
515
+
516
+ check()
517
+ if (!capabilities.cameraSwitchDuringRecording || !this.backend.switchCamera) {
518
+ throw issue(
519
+ 'unsupportedConfiguration',
520
+ 'switchCamera',
521
+ 'Live camera switching is unavailable on this host',
522
+ )
523
+ }
524
+
525
+ this.validateCameraSelection(camera, capabilities, 'switchCamera')
526
+ if (
527
+ (typeof camera === 'object' && camera.deviceId === this.activeCamera?.id) ||
528
+ (camera !== 'default' && camera === this.activeCamera?.facing)
529
+ ) {
530
+ return
531
+ }
532
+
533
+ const operation = this.backend.switchCamera(camera)
534
+
535
+ pending.cancel = () => operation.cancel()
536
+ if (pending.cancelled) {
537
+ operation.cancel()
538
+ }
539
+
540
+ const selected = await operation.completion
541
+
542
+ check()
543
+ try {
544
+ operation.commit?.()
545
+ } catch (error) {
546
+ try {
547
+ operation.cancel()
548
+ } catch {
549
+ /* Preserve the original commit error. */
550
+ }
551
+
552
+ throw error
553
+ }
554
+
555
+ this.config = { ...this.config, camera }
556
+ this.activeCamera = selected
557
+ })(),
558
+ aborted,
559
+ ])
560
+ } finally {
561
+ if (this.cameraSwitch === pending) {
562
+ this.cameraSwitch = undefined
563
+ this.emit({ type: 'stateChanged', snapshot: this.snapshot() })
564
+ }
565
+ }
566
+ }
567
+
568
+ async configure(next: Partial<CameraSessionConfig>): Promise<void> {
569
+ this.assertConfigurable()
570
+
571
+ const merged: CameraSessionConfig = { ...this.config, ...next }
572
+ const capabilities = await this.capabilities()
573
+
574
+ // Preview readiness can admit auto-recording (or the owner can
575
+ // dispose) while capability discovery is pending. Never reconfigure
576
+ // that live attempt using an earlier idle-state observation.
577
+ this.assertConfigurable()
578
+ this.validateCameraSelection(merged.camera, capabilities)
579
+ this.config = merged
580
+ this.backend.configure?.(merged)
581
+ }
582
+
583
+ private validateCameraSelection(
584
+ camera: CameraSelection | undefined,
585
+ capabilities: CameraSessionCapabilities,
586
+ operation = 'configure',
587
+ ) {
588
+ if (camera && typeof camera === 'object' && 'deviceId' in camera) {
589
+ const known = capabilities.cameras.some((entry) => entry.id === camera.deviceId)
590
+
591
+ if (!known) {
592
+ throw issue(
593
+ 'unsupportedConfiguration',
594
+ operation,
595
+ `Camera device '${camera.deviceId}' is not available`,
596
+ )
597
+ }
598
+ } else if (camera === 'front' || camera === 'back') {
599
+ const known = capabilities.cameras.some((entry) => entry.facing === camera)
600
+
601
+ if (!known && capabilities.cameras.some((entry) => entry.facing !== undefined)) {
602
+ throw issue(
603
+ 'unsupportedConfiguration',
604
+ operation,
605
+ `No ${camera}-facing camera is available`,
606
+ )
607
+ }
608
+ }
609
+ }
610
+
611
+ private requestStop(cause: MovieEndReason) {
612
+ this.cameraSwitch?.abort()
613
+
614
+ const attempt = this.attempt
615
+
616
+ if (!attempt || attempt.state === 'finalizing' || attempt.state === 'settled') {
617
+ return
618
+ }
619
+
620
+ attempt.stopRequested = true
621
+ attempt.cause ??= cause
622
+ if (attempt.state === 'recording') {
623
+ this.setState('finalizing')
624
+ attempt.state = 'finalizing'
625
+ try {
626
+ this.backend.stopCapture()
627
+ } catch {
628
+ // A stop failure still resolves through the settle path or a
629
+ // backend timeout; nothing more to do here.
630
+ }
631
+ }
632
+ }
633
+
634
+ private handleInterruption(phase: 'began' | 'ended', reason?: CameraInterruptionReason) {
635
+ this.interrupted = phase === 'began'
636
+ this.emit({ type: 'interruption', phase, reason })
637
+ if (phase === 'began') {
638
+ const cause: MovieEndReason =
639
+ reason === 'background'
640
+ ? 'backgrounded'
641
+ : reason === 'cameraInUse'
642
+ ? 'cameraUnavailable'
643
+ : 'interrupted'
644
+
645
+ this.requestStop(cause)
646
+ }
647
+
648
+ this.flushPendingReady()
649
+ this.emit({ type: 'stateChanged', snapshot: this.snapshot() })
650
+ }
651
+
652
+ private handleAvailability(available: boolean) {
653
+ if (this.cameraAvailable === available) {
654
+ return
655
+ }
656
+
657
+ this.cameraAvailable = available
658
+ this.emit({ type: 'availability', available })
659
+ if (!available) {
660
+ this.requestStop('cameraUnavailable')
661
+ }
662
+
663
+ this.flushPendingReady()
664
+ this.emit({ type: 'stateChanged', snapshot: this.snapshot() })
665
+ }
666
+
667
+ startRecording(options: StartRecordingOptions = {}): MovieTake {
668
+ const operation = 'startRecording'
669
+
670
+ if (this.disposed || this.disposeRequested) {
671
+ throw issue('invalidState', operation, 'CameraSession is disposed')
672
+ }
673
+
674
+ if (!this.backend.supported) {
675
+ throw issue(
676
+ 'unsupportedPlatform',
677
+ operation,
678
+ 'Movie recording is unsupported on this platform',
679
+ )
680
+ }
681
+
682
+ if (this.state !== 'idle' || this.attempt || this.cameraSwitch) {
683
+ throw issue('busy', operation, `CameraSession is ${this.state}`)
684
+ }
685
+
686
+ if (options.maximumDurationMs !== undefined) {
687
+ const value = options.maximumDurationMs
688
+
689
+ if (!Number.isFinite(value) || value <= 0) {
690
+ throw issue(
691
+ 'invalidArgument',
692
+ operation,
693
+ 'maximumDurationMs must be a positive finite number of milliseconds',
694
+ )
695
+ }
696
+ }
697
+
698
+ let destinationPath: string | undefined
699
+
700
+ if (options.destinationFileUrl !== undefined) {
701
+ if (!options.destinationFileUrl.startsWith('file://')) {
702
+ throw issue('invalidArgument', operation, 'destinationFileUrl must be a local file:// URL')
703
+ }
704
+
705
+ try {
706
+ destinationPath = decodeURIComponent(options.destinationFileUrl.slice('file://'.length))
707
+ } catch (cause) {
708
+ throw issue(
709
+ 'invalidArgument',
710
+ operation,
711
+ 'destinationFileUrl is not valid percent-encoding',
712
+ { cause },
713
+ )
714
+ }
715
+ }
716
+
717
+ if (
718
+ options.orientation !== undefined &&
719
+ options.orientation !== 'unspecified' &&
720
+ this.lastCapabilities &&
721
+ !this.lastCapabilities.orientations.includes(options.orientation)
722
+ ) {
723
+ throw issue(
724
+ 'unsupportedConfiguration',
725
+ 'startRecording',
726
+ `Orientation '${options.orientation}' is not advertised by this camera`,
727
+ )
728
+ }
729
+
730
+ if (this.interrupted || !this.cameraAvailable || !this.backend.previewReady()) {
731
+ throw issue(
732
+ 'unavailable',
733
+ operation,
734
+ this.interrupted
735
+ ? 'Camera session is interrupted'
736
+ : !this.cameraAvailable
737
+ ? 'Camera is unavailable'
738
+ : 'An active, ready preview is required before recording',
739
+ )
740
+ }
741
+
742
+ this.backend.validateStart?.(options)
743
+
744
+ attemptCounter += 1
745
+
746
+ const id = `take-${Date.now()}-${attemptCounter}`
747
+ let resolveCompletion!: (outcome: MovieOutcome) => void
748
+ const completion = new Promise<MovieOutcome>((resolve) => {
749
+ resolveCompletion = resolve
750
+ })
751
+
752
+ const attempt: {
753
+ id: string
754
+ state: 'starting' | 'recording' | 'finalizing' | 'settled'
755
+ stopRequested: boolean
756
+ cause?: MovieEndReason
757
+ startedAt?: number
758
+ configuration?: EffectiveCaptureConfig
759
+ resolve: (outcome: MovieOutcome) => void
760
+ completion: Promise<MovieOutcome>
761
+ limitTimer?: ReturnType<typeof setTimeout>
762
+ } = {
763
+ id,
764
+ state: 'starting',
765
+ stopRequested: false,
766
+ resolve: resolveCompletion,
767
+ completion,
768
+ }
769
+
770
+ this.attempt = attempt
771
+ this.setState('starting')
772
+
773
+ const capabilities = this.lastCapabilities
774
+ const sink: BackendCaptureSink = {
775
+ started: (configuration) => {
776
+ const current = this.attempt
777
+
778
+ if (!current || current.id !== id || current.state === 'settled') {
779
+ return
780
+ }
781
+
782
+ current.configuration = configuration
783
+ this.activeCamera = {
784
+ id: configuration.cameraId,
785
+ label:
786
+ this.lastCapabilities?.cameras.find((camera) => camera.id === configuration.cameraId)
787
+ ?.label ?? configuration.cameraId,
788
+ facing: configuration.facing,
789
+ }
790
+
791
+ current.startedAt = Date.now()
792
+ if (current.state === 'starting') {
793
+ current.state = 'recording'
794
+ this.setState('recording')
795
+ this.emit({ type: 'started', attemptId: id, configuration })
796
+ if (
797
+ options.maximumDurationMs !== undefined &&
798
+ capabilities?.durationLimit === 'bestEffort'
799
+ ) {
800
+ const limit = options.maximumDurationMs
801
+ const checkLimit = () => {
802
+ if (this.attempt?.id !== id || current.state !== 'recording') {
803
+ return
804
+ }
805
+
806
+ const remaining = limit - this.backend.elapsedMs()
807
+
808
+ if (remaining > 0) {
809
+ current.limitTimer = setTimeout(checkLimit, Math.min(remaining, 2_147_483_647))
810
+ } else {
811
+ this.requestStop('maximumDuration')
812
+ }
813
+ }
814
+
815
+ current.limitTimer = setTimeout(checkLimit, Math.min(limit, 2_147_483_647))
816
+ }
817
+
818
+ if (current.stopRequested) {
819
+ this.requestStop(current.cause ?? 'stopped')
820
+ }
821
+ }
822
+ },
823
+ finishing: (reason) => {
824
+ const current = this.attempt
825
+
826
+ if (!current || current.id !== id || current.state === 'settled') {
827
+ return
828
+ }
829
+
830
+ this.cameraSwitch?.abort()
831
+ current.cause ??= reason
832
+ current.state = 'finalizing'
833
+ this.setState('finalizing')
834
+ },
835
+ settled: (result) => {
836
+ const current = this.attempt
837
+
838
+ if (!current || current.id !== id || current.state === 'settled') {
839
+ return
840
+ }
841
+
842
+ this.cameraSwitch?.abort()
843
+
844
+ if (current.limitTimer) {
845
+ clearTimeout(current.limitTimer)
846
+ }
847
+
848
+ current.state = 'settled'
849
+
850
+ const cause = current.cause ?? (result.kind === 'clip' ? result.endReason : undefined)
851
+ const outcome: MovieOutcome =
852
+ result.kind === 'clip'
853
+ ? {
854
+ kind: 'clip',
855
+ clip: {
856
+ output: result.output,
857
+ mimeType: result.mimeType,
858
+ durationMs: result.durationMs,
859
+ width: result.width,
860
+ height: result.height,
861
+ orientation: result.orientation,
862
+ hasAudio: result.hasAudio,
863
+ },
864
+ endReason: cause ?? (result.limitReached ? 'maximumDuration' : 'stopped'),
865
+ partial: cause !== undefined && cause !== 'stopped' && cause !== 'maximumDuration',
866
+ warning: result.warning,
867
+ }
868
+ : {
869
+ kind: 'failed',
870
+ endReason: cause ?? 'captureError',
871
+ stage: result.stage,
872
+ error: new CameraCaptureError(result.issue),
873
+ }
874
+
875
+ this.attempt = undefined
876
+ current.resolve(outcome)
877
+ this.emit({ type: 'finished', attemptId: id, outcome })
878
+ if (this.disposeRequested) {
879
+ void this.finishDispose()
880
+ } else {
881
+ this.setState('idle')
882
+ }
883
+ },
884
+ }
885
+
886
+ const request: BackendCaptureRequest = {
887
+ audio: this.config.audio === true,
888
+ orientation: options.orientation,
889
+ maximumDurationMs: options.maximumDurationMs,
890
+ destinationPath,
891
+ }
892
+
893
+ try {
894
+ this.backend.startCapture(request, sink)
895
+ } catch (cause) {
896
+ sink.settled({
897
+ kind: 'failed',
898
+ stage: 'preparation',
899
+ issue:
900
+ cause instanceof CameraCaptureError
901
+ ? cause
902
+ : {
903
+ kind: 'captureFailed',
904
+ operation: 'startRecording',
905
+ message: cause instanceof Error ? cause.message : String(cause),
906
+ cause,
907
+ },
908
+ })
909
+ }
910
+
911
+ const backend = this.backend
912
+ const take: MovieTake = {
913
+ id,
914
+ get state() {
915
+ return attempt.state
916
+ },
917
+ get elapsedMs() {
918
+ return attempt.state === 'recording' || attempt.state === 'finalizing'
919
+ ? backend.elapsedMs()
920
+ : 0
921
+ },
922
+ completion,
923
+ stop: () => {
924
+ if (this.attempt?.id === id) {
925
+ this.requestStop('stopped')
926
+ }
927
+
928
+ return completion
929
+ },
930
+ }
931
+
932
+ return take
933
+ }
934
+
935
+ openOutput(output: MovieOutput): Promise<MovieOutputHandle> {
936
+ return this.backend.openOutput(output)
937
+ }
938
+
939
+ async dispose(): Promise<void> {
940
+ if (this.disposed) {
941
+ return
942
+ }
943
+
944
+ this.disposeRequested = true
945
+
946
+ const attempt = this.attempt
947
+
948
+ if (attempt && attempt.state !== 'settled') {
949
+ this.requestStop('disposed')
950
+ await attempt.completion
951
+ }
952
+
953
+ await this.finishDispose()
954
+ }
955
+
956
+ private async finishDispose() {
957
+ if (this.disposed) {
958
+ return
959
+ }
960
+
961
+ this.disposed = true
962
+ this.pendingOnReady = undefined
963
+ this.backend.setObserver(undefined)
964
+ try {
965
+ await this.backend.release()
966
+ } finally {
967
+ this.setState('disposed')
968
+ }
969
+ }
759
970
  }