@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,20 +1,21 @@
1
1
  import { SharedCameraSession } from './session-core'
2
2
  import type {
3
- BackendCaptureRequest,
4
- BackendCaptureSink,
5
- BackendObserver,
6
- BackendSettle,
7
- CameraSessionBackend,
3
+ BackendCaptureRequest,
4
+ BackendCaptureSink,
5
+ BackendObserver,
6
+ BackendSettle,
7
+ CameraSessionBackend,
8
8
  } from './session-core'
9
9
 
10
10
  import type {
11
- CameraInterruptionReason,
12
- CameraPermissionStatus,
13
- CameraPreviewPoint,
14
- CameraSession,
15
- CameraSessionCapabilities,
16
- CameraSessionConfig,
17
- MovieOutput,
11
+ CameraInterruptionReason,
12
+ CameraPermissionStatus,
13
+ CameraPreviewPoint,
14
+ CameraSession,
15
+ CameraSessionCapabilities,
16
+ CameraSessionConfig,
17
+ CameraSelection,
18
+ MovieOutput,
18
19
  } from './types'
19
20
 
20
21
  /** Development/testing seam — a deterministic camera source that drives
@@ -27,358 +28,409 @@ import type {
27
28
  * partial completions, and failures.
28
29
  */
29
30
  export interface SyntheticCameraScript {
30
- /** Storage access state. */
31
- permission: {
32
- camera: CameraPermissionStatus
33
- microphone: CameraPermissionStatus
34
- }
35
- /** Camera hardware availability observation. */
36
- available: boolean
37
- /** Delay before `started` reports; models slow native activation. */
38
- startDelayMs: number
39
- /** Finalized clip duration reported by the seam. */
40
- clipDurationMs: number
41
- /** Produce a usable clip on stop; false settles `noMedia`. */
42
- produceMedia: boolean
43
- /** When set, the attempt settles failed at this stage. */
44
- failAt?: 'start' | 'capture' | 'finalize' | 'storage'
45
- /** Emit an interruption after this many ms of recording; the take
46
- * ends with the mapped end reason and a partial clip. */
47
- interruption?: {
48
- afterMs: number
49
- reason: CameraInterruptionReason
50
- endsAfterMs?: number
51
- }
52
- /** When set, each `focusAtPoint` call pushes its normalized point
53
- * here so a spec can observe metering requests. */
54
- focusRequests?: CameraPreviewPoint[]
31
+ /** Storage access state. */
32
+ permission: {
33
+ camera: CameraPermissionStatus
34
+ microphone: CameraPermissionStatus
35
+ }
36
+ /** Camera hardware availability observation. */
37
+ available: boolean
38
+ /** Delay before `started` reports; models slow native activation. */
39
+ startDelayMs: number
40
+ /** Finalized clip duration reported by the seam. */
41
+ clipDurationMs: number
42
+ /** Produce a usable clip on stop; false settles `noMedia`. */
43
+ produceMedia: boolean
44
+ /** When set, the attempt settles failed at this stage. */
45
+ failAt?: 'start' | 'capture' | 'finalize' | 'storage'
46
+ /** Emit an interruption after this many ms of recording; the take
47
+ * ends with the mapped end reason and a partial clip. */
48
+ interruption?: {
49
+ afterMs: number
50
+ reason: CameraInterruptionReason
51
+ endsAfterMs?: number
52
+ }
53
+ /** When set, each `focusAtPoint` call pushes its normalized point
54
+ * here so a spec can observe metering requests. */
55
+ focusRequests?: CameraPreviewPoint[]
56
+ /** When set, the seam reports zoom control: `zoomState()` returns a
57
+ * copy and `setZoom` writes `zoom` here so specs observe requests. */
58
+ zoom?: { zoom: number; minZoom: number; maxZoom: number }
55
59
  }
56
60
 
57
61
  /** Storage backing for synthetic/test camera clips. */
58
62
  export interface SyntheticCameraStorage {
59
- /** Write a synthetic clip to storage. */
60
- write(path: string, bytes: Uint8Array): void | Promise<void>
61
- /** Read a stored clip. */
62
- read(path: string): Uint8Array | undefined | Promise<Uint8Array | undefined>
63
- /** Remove a stored clip; optional — reopen paths degrade gracefully without it. */
64
- delete?(path: string): void | Promise<void>
65
- /** Probe for a stored clip without reading it. */
66
- exists?(path: string): boolean | Promise<boolean>
63
+ /** Write a synthetic clip to storage. */
64
+ write(path: string, bytes: Uint8Array): void | Promise<void>
65
+ /** Read a stored clip. */
66
+ read(path: string): Uint8Array | undefined | Promise<Uint8Array | undefined>
67
+ /** Remove a stored clip; optional — reopen paths degrade gracefully without it. */
68
+ delete?(path: string): void | Promise<void>
69
+ /** Probe for a stored clip without reading it. */
70
+ exists?(path: string): boolean | Promise<boolean>
67
71
  }
68
72
 
69
73
  /** In-memory storage for the seam — a `fileUrl`-shaped map so outcomes
70
74
  * exercise the same reopen path without touching a real filesystem. */
71
75
  export function createMemoryCameraStorage(): SyntheticCameraStorage & {
72
- /** Stored clip bytes keyed by path — specs assert on this map directly. */
73
- files: Map<string, Uint8Array>
76
+ /** Stored clip bytes keyed by path — specs assert on this map directly. */
77
+ files: Map<string, Uint8Array>
74
78
  } {
75
- const files = new Map<string, Uint8Array>()
76
- return {
77
- files,
78
- write: (path, bytes) => {
79
- files.set(path, bytes)
80
- },
81
- read: (path) => files.get(path),
82
- delete: (path) => {
83
- files.delete(path)
84
- },
85
- exists: (path) => files.has(path),
86
- }
79
+ const files = new Map<string, Uint8Array>()
80
+
81
+ return {
82
+ files,
83
+ write: (path, bytes) => {
84
+ files.set(path, bytes)
85
+ },
86
+ read: (path) => files.get(path),
87
+ delete: (path) => {
88
+ files.delete(path)
89
+ },
90
+ exists: (path) => files.has(path),
91
+ }
87
92
  }
88
93
 
89
94
  const defaultScript = (): SyntheticCameraScript => ({
90
- permission: { camera: 'granted', microphone: 'granted' },
91
- available: true,
92
- startDelayMs: 20,
93
- clipDurationMs: 3000,
94
- produceMedia: true,
95
+ permission: { camera: 'granted', microphone: 'granted' },
96
+ available: true,
97
+ startDelayMs: 20,
98
+ clipDurationMs: 3000,
99
+ produceMedia: true,
95
100
  })
96
101
 
97
102
  const capabilities: CameraSessionCapabilities = {
98
- supported: true,
99
- available: true,
100
- cameras: [
101
- { id: 'synthetic-back', label: 'Synthetic back camera', facing: 'back' },
102
- { id: 'synthetic-front', label: 'Synthetic front camera', facing: 'front' },
103
- ],
104
- profiles: [{ profile: 'standard', width: 1280, height: 720, frameRate: 30 }],
105
- audio: true,
106
- // The seam accepts metering points so tests exercise the supported path.
107
- focusPointOfInterest: true,
108
- exposurePointOfInterest: true,
109
- orientations: ['portrait', 'portraitUpsideDown', 'landscapeLeft', 'landscapeRight'],
110
- durationLimit: 'native',
111
- elapsedTime: 'nativeMedia',
112
- output: {
113
- mimeType: 'video/quicktime',
114
- container: 'mov',
115
- storage: 'appPrivateFile',
116
- destinationFileUrl: true,
117
- },
103
+ supported: true,
104
+ available: true,
105
+ cameras: [
106
+ { id: 'synthetic-back', label: 'Synthetic back camera', facing: 'back' },
107
+ { id: 'synthetic-front', label: 'Synthetic front camera', facing: 'front' },
108
+ ],
109
+ profiles: [{ profile: 'standard', width: 1280, height: 720, frameRate: 30 }],
110
+ audio: true,
111
+ // The seam accepts metering points so tests exercise the supported path.
112
+ focusPointOfInterest: true,
113
+ exposurePointOfInterest: true,
114
+ zoom: false,
115
+ orientations: ['portrait', 'portraitUpsideDown', 'landscapeLeft', 'landscapeRight'],
116
+ cameraSwitchDuringRecording: true,
117
+ durationLimit: 'native',
118
+ elapsedTime: 'nativeMedia',
119
+ output: {
120
+ mimeType: 'video/quicktime',
121
+ container: 'mov',
122
+ storage: 'appPrivateFile',
123
+ destinationFileUrl: true,
124
+ },
118
125
  }
119
126
 
120
127
  /** Create a `CameraSession` backed by the deterministic synthetic source.
121
128
  * Marked for development and testing — never present this as live
122
129
  * capture to users. */
123
130
  export function createSyntheticCameraSession(
124
- config: CameraSessionConfig = {},
125
- script: Partial<SyntheticCameraScript> = {},
126
- storage: SyntheticCameraStorage = createMemoryCameraStorage(),
131
+ config: CameraSessionConfig = {},
132
+ script: Partial<SyntheticCameraScript> = {},
133
+ storage: SyntheticCameraStorage = createMemoryCameraStorage(),
127
134
  ): CameraSession {
128
- const controls: SyntheticCameraScript = { ...defaultScript(), ...script }
129
- return new SharedCameraSession(createSyntheticBackend(controls, storage), config)
135
+ const controls: SyntheticCameraScript = { ...defaultScript(), ...script }
136
+
137
+ return new SharedCameraSession(createSyntheticBackend(controls, storage, config), config)
130
138
  }
131
139
 
132
140
  function createSyntheticBackend(
133
- script: SyntheticCameraScript,
134
- storage: SyntheticCameraStorage,
141
+ script: SyntheticCameraScript,
142
+ storage: SyntheticCameraStorage,
143
+ config: CameraSessionConfig,
135
144
  ): CameraSessionBackend {
136
- let observer: BackendObserver | undefined
137
- let attached = false
138
- let sink: BackendCaptureSink | undefined
139
- let startedAt: number | undefined
140
- let timers: ReturnType<typeof setTimeout>[] = []
141
- let pendingRequest: BackendCaptureRequest | undefined
142
-
143
- const later = (ms: number, fn: () => void) => {
144
- timers.push(setTimeout(fn, ms))
145
- }
146
-
147
- const clearTimers = () => {
148
- for (const timer of timers) {
149
- clearTimeout(timer)
150
- }
151
-
152
- timers = []
153
- }
154
-
155
- const settleClip = async (request: BackendCaptureRequest, limitReached: boolean) => {
156
- const path =
157
- request.destinationPath ??
158
- `/synthetic/clip-${Date.now()}-${Math.random().toString(36).slice(2)}.mov`
159
-
160
- if (!script.produceMedia) {
161
- sink?.settled({
162
- kind: 'failed',
163
- stage: 'capture',
164
- issue: {
165
- kind: 'noMedia',
166
- operation: 'finalize',
167
- message: 'Synthetic source produced no media',
168
- },
169
- })
170
-
171
- return
172
- }
173
-
174
- if (script.failAt === 'finalize') {
175
- sink?.settled({
176
- kind: 'failed',
177
- stage: 'finalization',
178
- issue: {
179
- kind: 'finalizationFailed',
180
- operation: 'finalize',
181
- message: 'Synthetic finalization failure',
182
- },
183
- })
184
-
185
- return
186
- }
187
-
188
- if (script.failAt === 'storage') {
189
- sink?.settled({
190
- kind: 'failed',
191
- stage: 'storage',
192
- issue: {
193
- kind: 'storageFailed',
194
- operation: 'store',
195
- message: 'Synthetic storage failure',
196
- },
197
- })
198
-
199
- return
200
- }
201
-
202
- try {
203
- // Not playable media — seam bytes stand in for a fixture. The
204
- // output is marked `synthetic` so nothing mistakes it for real
205
- // capture.
206
- await storage.write(path, new Uint8Array([0x78, 0x70, 0x6c, 0x61, 0x74]))
207
- } catch (cause) {
208
- sink?.settled({
209
- kind: 'failed',
210
- stage: 'storage',
211
- issue: {
212
- kind: 'storageFailed',
213
- operation: 'store',
214
- message: cause instanceof Error ? cause.message : String(cause),
215
- cause,
216
- },
217
- })
218
-
219
- return
220
- }
221
-
222
- const output: MovieOutput = {
223
- kind: 'nativeFile',
224
- resourceId: `synthetic:${path}`,
225
- fileUrl: `file://${path}`,
226
- synthetic: true,
227
- }
228
-
229
- const settle: BackendSettle = {
230
- kind: 'clip',
231
- output,
232
- mimeType: 'video/quicktime',
233
- durationMs: script.clipDurationMs,
234
- width: 1280,
235
- height: 720,
236
- orientation: request.orientation ?? 'portrait',
237
- hasAudio: request.audio,
238
- limitReached,
239
- }
240
-
241
- sink?.settled(settle)
242
- }
243
-
244
- return {
245
- platform: 'synthetic',
246
- supported: true,
247
- checkPermission: async (kind) => script.permission[kind],
248
- requestPermission: async (kind) => script.permission[kind],
249
- getCapabilities: async () => ({
250
- ...capabilities,
251
- available: script.available,
252
- reason: script.available ? undefined : 'Synthetic camera is unavailable',
253
- }),
254
- previewReady: () => attached && script.available,
255
- focusAtPoint: (point) => {
256
- script.focusRequests?.push(point)
257
- },
258
- attachPreview: (_host, listener) => {
259
- attached = true
260
- queueMicrotask(() => {
261
- listener?.onReady?.()
262
- observer?.previewReady(true)
263
- })
264
-
265
- return () => {
266
- attached = false
267
- observer?.previewReady(false)
268
- }
269
- },
270
- startCapture: (request, attemptSink) => {
271
- sink = attemptSink
272
- pendingRequest = request
273
- if (!script.available) {
274
- attemptSink.settled({
275
- kind: 'failed',
276
- stage: 'preparation',
277
- issue: {
278
- kind: 'unavailable',
279
- operation: 'startRecording',
280
- message: 'Synthetic camera is unavailable',
281
- },
282
- })
283
-
284
- return
285
- }
286
-
287
- if (script.failAt === 'start') {
288
- later(script.startDelayMs, () => {
289
- attemptSink.settled({
290
- kind: 'failed',
291
- stage: 'preparation',
292
- issue: {
293
- kind: 'captureFailed',
294
- operation: 'startRecording',
295
- message: 'Synthetic start failure',
296
- },
297
- })
298
- })
299
-
300
- return
301
- }
302
-
303
- later(script.startDelayMs, () => {
304
- startedAt = Date.now()
305
- attemptSink.started({
306
- cameraId: 'synthetic-back',
307
- facing: 'back',
308
- audio: request.audio,
309
- width: 1280,
310
- height: 720,
311
- frameRate: 30,
312
- orientation: request.orientation ?? 'portrait',
313
- mimeType: 'video/quicktime',
314
- container: 'mov',
315
- })
316
-
317
- if (script.interruption) {
318
- later(script.interruption.afterMs, () => {
319
- observer?.interruption('began', script.interruption?.reason)
320
- if (script.interruption?.endsAfterMs !== undefined) {
321
- later(script.interruption.endsAfterMs, () => {
322
- observer?.interruption('ended', script.interruption?.reason)
323
- })
324
- }
325
- })
326
- }
327
-
328
- if (request.maximumDurationMs !== undefined) {
329
- later(request.maximumDurationMs, () => {
330
- void settleClip(request, true)
331
- })
332
- }
333
-
334
- if (script.failAt === 'capture') {
335
- later(50, () => {
336
- attemptSink.settled({
337
- kind: 'failed',
338
- stage: 'capture',
339
- issue: {
340
- kind: 'captureFailed',
341
- operation: 'record',
342
- message: 'Synthetic capture failure',
343
- },
344
- })
345
- })
346
- }
347
- })
348
- },
349
- stopCapture: () => {
350
- // Settle asynchronously — native stop is async too.
351
- const request = pendingRequest
352
- later(5, () => {
353
- if (request) {
354
- void settleClip(request, false)
355
- }
356
- })
357
- },
358
- elapsedMs: () => (startedAt === undefined ? 0 : Date.now() - startedAt),
359
- openOutput: async (output) => {
360
- const path = output.kind === 'nativeFile' ? output.fileUrl.slice('file://'.length) : ''
361
- const exists = storage.exists ? await storage.exists(path) : !!(await storage.read(path))
362
- if (!exists) {
363
- throw new Error(`Synthetic clip is missing at ${output.resourceId}`)
364
- }
365
-
366
- return {
367
- url: output.kind === 'nativeFile' ? output.fileUrl : output.resourceId,
368
- fileUrl: output.kind === 'nativeFile' ? output.fileUrl : undefined,
369
- release: () => {},
370
- }
371
- },
372
- release: async () => {
373
- attached = false
374
- clearTimers()
375
- sink = undefined
376
- startedAt = undefined
377
- pendingRequest = undefined
378
- },
379
- onPreviewDetached: () => {},
380
- setObserver: (next) => {
381
- observer = next
382
- },
383
- }
145
+ const selection = (camera: CameraSelection | undefined) =>
146
+ capabilities.cameras.find((entry) =>
147
+ typeof camera === 'object' ? entry.id === camera.deviceId : entry.facing === camera,
148
+ ) ?? capabilities.cameras[0]!
149
+
150
+ let selected = selection(config.camera)
151
+ let observer: BackendObserver | undefined
152
+ let attached = false
153
+ let sink: BackendCaptureSink | undefined
154
+ let startedAt: number | undefined
155
+ let timers: ReturnType<typeof setTimeout>[] = []
156
+ let pendingRequest: BackendCaptureRequest | undefined
157
+
158
+ const later = (ms: number, fn: () => void) => {
159
+ timers.push(setTimeout(fn, ms))
160
+ }
161
+
162
+ const clearTimers = () => {
163
+ for (const timer of timers) {
164
+ clearTimeout(timer)
165
+ }
166
+
167
+ timers = []
168
+ }
169
+
170
+ const settleClip = async (request: BackendCaptureRequest, limitReached: boolean) => {
171
+ const path =
172
+ request.destinationPath ??
173
+ `/synthetic/clip-${Date.now()}-${Math.random().toString(36).slice(2)}.mov`
174
+
175
+ if (!script.produceMedia) {
176
+ sink?.settled({
177
+ kind: 'failed',
178
+ stage: 'capture',
179
+ issue: {
180
+ kind: 'noMedia',
181
+ operation: 'finalize',
182
+ message: 'Synthetic source produced no media',
183
+ },
184
+ })
185
+
186
+ return
187
+ }
188
+
189
+ if (script.failAt === 'finalize') {
190
+ sink?.settled({
191
+ kind: 'failed',
192
+ stage: 'finalization',
193
+ issue: {
194
+ kind: 'finalizationFailed',
195
+ operation: 'finalize',
196
+ message: 'Synthetic finalization failure',
197
+ },
198
+ })
199
+
200
+ return
201
+ }
202
+
203
+ if (script.failAt === 'storage') {
204
+ sink?.settled({
205
+ kind: 'failed',
206
+ stage: 'storage',
207
+ issue: {
208
+ kind: 'storageFailed',
209
+ operation: 'store',
210
+ message: 'Synthetic storage failure',
211
+ },
212
+ })
213
+
214
+ return
215
+ }
216
+
217
+ try {
218
+ // Not playable media — seam bytes stand in for a fixture. The
219
+ // output is marked `synthetic` so nothing mistakes it for real
220
+ // capture.
221
+ await storage.write(path, new Uint8Array([0x78, 0x70, 0x6c, 0x61, 0x74]))
222
+ } catch (cause) {
223
+ sink?.settled({
224
+ kind: 'failed',
225
+ stage: 'storage',
226
+ issue: {
227
+ kind: 'storageFailed',
228
+ operation: 'store',
229
+ message: cause instanceof Error ? cause.message : String(cause),
230
+ cause,
231
+ },
232
+ })
233
+
234
+ return
235
+ }
236
+
237
+ const output: MovieOutput = {
238
+ kind: 'nativeFile',
239
+ resourceId: `synthetic:${path}`,
240
+ fileUrl: `file://${path}`,
241
+ synthetic: true,
242
+ }
243
+
244
+ const settle: BackendSettle = {
245
+ kind: 'clip',
246
+ output,
247
+ mimeType: 'video/quicktime',
248
+ durationMs: script.clipDurationMs,
249
+ width: 1280,
250
+ height: 720,
251
+ orientation: request.orientation ?? 'portrait',
252
+ hasAudio: request.audio,
253
+ limitReached,
254
+ }
255
+
256
+ sink?.settled(settle)
257
+ }
258
+
259
+ return {
260
+ platform: 'synthetic',
261
+ supported: true,
262
+ checkPermission: async (kind) => script.permission[kind],
263
+ requestPermission: async (kind) => script.permission[kind],
264
+ getCapabilities: async () => ({
265
+ ...capabilities,
266
+ available: script.available,
267
+ reason: script.available ? undefined : 'Synthetic camera is unavailable',
268
+ zoom: script.zoom != null && script.zoom.maxZoom > script.zoom.minZoom,
269
+ }),
270
+ previewReady: () => attached && script.available,
271
+ configure: (next) => {
272
+ selected = selection(next.camera)
273
+ },
274
+ switchCamera: (camera) => {
275
+ let cancelled = false
276
+ const next = selection(camera)
277
+
278
+ return {
279
+ completion: Promise.resolve().then(() => {
280
+ if (cancelled) {
281
+ throw new Error('Synthetic camera switch cancelled')
282
+ }
283
+
284
+ return { ...next }
285
+ }),
286
+ commit: () => {
287
+ if (cancelled) {
288
+ throw new Error('Synthetic camera switch cancelled')
289
+ }
290
+
291
+ selected = next
292
+ },
293
+ cancel: () => {
294
+ cancelled = true
295
+ },
296
+ }
297
+ },
298
+ focusAtPoint: (point) => {
299
+ script.focusRequests?.push(point)
300
+ },
301
+ zoomState: () => (script.zoom ? { ...script.zoom } : undefined),
302
+ setZoom: (ratio) => {
303
+ if (script.zoom) {
304
+ script.zoom.zoom = ratio
305
+ }
306
+ },
307
+ attachPreview: (_host, listener) => {
308
+ attached = true
309
+ queueMicrotask(() => {
310
+ listener?.onReady?.()
311
+ listener?.onDisplayReady?.()
312
+ observer?.previewReady(true)
313
+ })
314
+
315
+ return () => {
316
+ attached = false
317
+ observer?.previewReady(false)
318
+ }
319
+ },
320
+ startCapture: (request, attemptSink) => {
321
+ sink = attemptSink
322
+ pendingRequest = request
323
+ if (!script.available) {
324
+ attemptSink.settled({
325
+ kind: 'failed',
326
+ stage: 'preparation',
327
+ issue: {
328
+ kind: 'unavailable',
329
+ operation: 'startRecording',
330
+ message: 'Synthetic camera is unavailable',
331
+ },
332
+ })
333
+
334
+ return
335
+ }
336
+
337
+ if (script.failAt === 'start') {
338
+ later(script.startDelayMs, () => {
339
+ attemptSink.settled({
340
+ kind: 'failed',
341
+ stage: 'preparation',
342
+ issue: {
343
+ kind: 'captureFailed',
344
+ operation: 'startRecording',
345
+ message: 'Synthetic start failure',
346
+ },
347
+ })
348
+ })
349
+
350
+ return
351
+ }
352
+
353
+ later(script.startDelayMs, () => {
354
+ startedAt = Date.now()
355
+ attemptSink.started({
356
+ cameraId: selected.id,
357
+ facing: selected.facing,
358
+ audio: request.audio,
359
+ width: 1280,
360
+ height: 720,
361
+ frameRate: 30,
362
+ orientation: request.orientation ?? 'portrait',
363
+ mimeType: 'video/quicktime',
364
+ container: 'mov',
365
+ })
366
+
367
+ if (script.interruption) {
368
+ later(script.interruption.afterMs, () => {
369
+ observer?.interruption('began', script.interruption?.reason)
370
+ if (script.interruption?.endsAfterMs !== undefined) {
371
+ later(script.interruption.endsAfterMs, () => {
372
+ observer?.interruption('ended', script.interruption?.reason)
373
+ })
374
+ }
375
+ })
376
+ }
377
+
378
+ if (request.maximumDurationMs !== undefined) {
379
+ later(request.maximumDurationMs, () => {
380
+ void settleClip(request, true)
381
+ })
382
+ }
383
+
384
+ if (script.failAt === 'capture') {
385
+ later(50, () => {
386
+ attemptSink.settled({
387
+ kind: 'failed',
388
+ stage: 'capture',
389
+ issue: {
390
+ kind: 'captureFailed',
391
+ operation: 'record',
392
+ message: 'Synthetic capture failure',
393
+ },
394
+ })
395
+ })
396
+ }
397
+ })
398
+ },
399
+ stopCapture: () => {
400
+ // Settle asynchronously — native stop is async too.
401
+ const request = pendingRequest
402
+
403
+ later(5, () => {
404
+ if (request) {
405
+ void settleClip(request, false)
406
+ }
407
+ })
408
+ },
409
+ elapsedMs: () => (startedAt === undefined ? 0 : Date.now() - startedAt),
410
+ openOutput: async (output) => {
411
+ const path = output.kind === 'nativeFile' ? output.fileUrl.slice('file://'.length) : ''
412
+ const exists = storage.exists ? await storage.exists(path) : !!(await storage.read(path))
413
+
414
+ if (!exists) {
415
+ throw new Error(`Synthetic clip is missing at ${output.resourceId}`)
416
+ }
417
+
418
+ return {
419
+ url: output.kind === 'nativeFile' ? output.fileUrl : output.resourceId,
420
+ fileUrl: output.kind === 'nativeFile' ? output.fileUrl : undefined,
421
+ release: () => {},
422
+ }
423
+ },
424
+ release: async () => {
425
+ attached = false
426
+ clearTimers()
427
+ sink = undefined
428
+ startedAt = undefined
429
+ pendingRequest = undefined
430
+ },
431
+ onPreviewDetached: () => {},
432
+ setObserver: (next) => {
433
+ observer = next
434
+ },
435
+ }
384
436
  }