@octane-xplat/camera 0.18.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/README.md +2 -132
  2. package/package.json +108 -103
  3. package/platforms/android/java/com/octanexplat/camera/CameraPreviewView.java +24 -0
  4. package/platforms/android/java/com/octanexplat/camera/CameraSessionBridge.java +153 -21
  5. package/platforms/ios/src/XplatSwitchingMovieWriter.swift +557 -0
  6. package/src/CameraView.android.tsrx +194 -118
  7. package/src/CameraView.ios.tsrx +129 -76
  8. package/src/CameraView.macos.tsrx +108 -70
  9. package/src/CameraView.tsrx +2 -0
  10. package/src/CameraView.web.tsrx +160 -125
  11. package/src/CameraView.windows.tsrx +141 -92
  12. package/src/camera-host.macos.ts +1059 -0
  13. package/src/camera-permission.mobile.ts +85 -81
  14. package/src/camera-permission.windows.ts +56 -53
  15. package/src/camera-session.ios.ts +89 -61
  16. package/src/camera-session.macos.ts +51 -49
  17. package/src/camera-session.windows.ts +113 -105
  18. package/src/host-movie.web.ts +266 -222
  19. package/src/index.ts +28 -26
  20. package/src/index.web.ts +27 -25
  21. package/src/layout-child.ts +88 -79
  22. package/src/layout-child.web.ts +57 -51
  23. package/src/layout-child.windows.ts +82 -71
  24. package/src/movie-metadata.web.ts +87 -74
  25. package/src/movie-storage.web.ts +142 -135
  26. package/src/movie-writer.ios.ts +170 -0
  27. package/src/photo-lifecycle.macos.ts +60 -0
  28. package/src/photo-sheet.macos.ts +505 -0
  29. package/src/preview-display.ios.ts +69 -0
  30. package/src/preview-pinch.ts +41 -0
  31. package/src/preview-tap.ts +22 -21
  32. package/src/props.ts +118 -68
  33. package/src/recording-haptics.ios.ts +39 -0
  34. package/src/recording-source.web.ts +159 -0
  35. package/src/session-backend.android.ts +552 -410
  36. package/src/session-backend.ios.ts +1500 -1148
  37. package/src/session-backend.linux.ts +886 -860
  38. package/src/session-backend.macos.ts +697 -679
  39. package/src/session-backend.ts +51 -49
  40. package/src/session-backend.web.ts +1181 -867
  41. package/src/session-backend.windows.ts +1556 -1467
  42. package/src/session-core.ts +925 -711
  43. package/src/session.ts +12 -12
  44. package/src/style-merge.ts +43 -43
  45. package/src/synthetic-session.ts +392 -333
  46. package/src/types.ts +384 -239
  47. package/types/generated/.tsrx-typegen-manifest.json +18 -0
  48. package/types/generated/CameraView.d.ts +2 -0
  49. package/types/generated/CameraView.web.d.ts +4 -0
  50. package/types/generated/camera-host.macos.d.ts +33 -0
  51. package/types/generated/index.d.ts +34 -0
  52. package/types/generated/layout-child.web.d.ts +7 -0
  53. package/types/generated/photo-lifecycle.macos.d.ts +12 -0
  54. package/types/generated/photo-sheet.macos.d.ts +36 -0
  55. package/types/generated/props.d.ts +111 -0
  56. package/types/generated/session-backend.d.ts +6 -0
  57. package/types/{session-core.d.ts → generated/session-core.d.ts} +30 -1
  58. package/types/generated/session.d.ts +16 -0
  59. package/types/{synthetic-session.d.ts → generated/synthetic-session.d.ts} +15 -1
  60. package/types/{types.d.ts → generated/types.d.ts} +145 -2
  61. package/LICENSE +0 -21
  62. package/platforms/macos/src/CameraOwnership.swift +0 -22
  63. package/platforms/macos/src/PhotoCaptureLifecycle.swift +0 -34
  64. package/platforms/macos/src/XplatCameraHost.swift +0 -639
  65. package/platforms/macos/src/XplatPhotoCaptureSheet.swift +0 -192
  66. package/types/index.d.ts +0 -48
  67. package/types/props.d.ts +0 -61
@@ -1,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,351 +28,409 @@ import type {
27
28
  * partial completions, and failures.
28
29
  */
29
30
  export interface SyntheticCameraScript {
30
- permission: {
31
- camera: CameraPermissionStatus
32
- microphone: CameraPermissionStatus
33
- }
34
- /** Camera hardware availability observation. */
35
- available: boolean
36
- /** Delay before `started` reports; models slow native activation. */
37
- startDelayMs: number
38
- /** Finalized clip duration reported by the seam. */
39
- clipDurationMs: number
40
- /** Produce a usable clip on stop; false settles `noMedia`. */
41
- produceMedia: boolean
42
- /** When set, the attempt settles failed at this stage. */
43
- failAt?: 'start' | 'capture' | 'finalize' | 'storage'
44
- /** Emit an interruption after this many ms of recording; the take
45
- * ends with the mapped end reason and a partial clip. */
46
- interruption?: {
47
- afterMs: number
48
- reason: CameraInterruptionReason
49
- endsAfterMs?: number
50
- }
51
- /** When set, each `focusAtPoint` call pushes its normalized point
52
- * here so a spec can observe metering requests. */
53
- 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 }
54
59
  }
55
60
 
61
+ /** Storage backing for synthetic/test camera clips. */
56
62
  export interface SyntheticCameraStorage {
57
- write(path: string, bytes: Uint8Array): void | Promise<void>
58
- read(path: string): Uint8Array | undefined | Promise<Uint8Array | undefined>
59
- delete?(path: string): void | Promise<void>
60
- 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>
61
71
  }
62
72
 
63
73
  /** In-memory storage for the seam — a `fileUrl`-shaped map so outcomes
64
74
  * exercise the same reopen path without touching a real filesystem. */
65
75
  export function createMemoryCameraStorage(): SyntheticCameraStorage & {
66
- files: Map<string, Uint8Array>
76
+ /** Stored clip bytes keyed by path — specs assert on this map directly. */
77
+ files: Map<string, Uint8Array>
67
78
  } {
68
- const files = new Map<string, Uint8Array>()
69
- return {
70
- files,
71
- write: (path, bytes) => {
72
- files.set(path, bytes)
73
- },
74
- read: (path) => files.get(path),
75
- delete: (path) => {
76
- files.delete(path)
77
- },
78
- exists: (path) => files.has(path),
79
- }
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
+ }
80
92
  }
81
93
 
82
94
  const defaultScript = (): SyntheticCameraScript => ({
83
- permission: { camera: 'granted', microphone: 'granted' },
84
- available: true,
85
- startDelayMs: 20,
86
- clipDurationMs: 3000,
87
- produceMedia: true,
95
+ permission: { camera: 'granted', microphone: 'granted' },
96
+ available: true,
97
+ startDelayMs: 20,
98
+ clipDurationMs: 3000,
99
+ produceMedia: true,
88
100
  })
89
101
 
90
102
  const capabilities: CameraSessionCapabilities = {
91
- supported: true,
92
- available: true,
93
- cameras: [
94
- { id: 'synthetic-back', label: 'Synthetic back camera', facing: 'back' },
95
- { id: 'synthetic-front', label: 'Synthetic front camera', facing: 'front' },
96
- ],
97
- profiles: [{ profile: 'standard', width: 1280, height: 720, frameRate: 30 }],
98
- audio: true,
99
- // The seam accepts metering points so tests exercise the supported path.
100
- focusPointOfInterest: true,
101
- exposurePointOfInterest: true,
102
- orientations: ['portrait', 'portraitUpsideDown', 'landscapeLeft', 'landscapeRight'],
103
- durationLimit: 'native',
104
- elapsedTime: 'nativeMedia',
105
- output: {
106
- mimeType: 'video/quicktime',
107
- container: 'mov',
108
- storage: 'appPrivateFile',
109
- destinationFileUrl: true,
110
- },
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
+ },
111
125
  }
112
126
 
113
127
  /** Create a `CameraSession` backed by the deterministic synthetic source.
114
128
  * Marked for development and testing — never present this as live
115
129
  * capture to users. */
116
130
  export function createSyntheticCameraSession(
117
- config: CameraSessionConfig = {},
118
- script: Partial<SyntheticCameraScript> = {},
119
- storage: SyntheticCameraStorage = createMemoryCameraStorage(),
131
+ config: CameraSessionConfig = {},
132
+ script: Partial<SyntheticCameraScript> = {},
133
+ storage: SyntheticCameraStorage = createMemoryCameraStorage(),
120
134
  ): CameraSession {
121
- const controls: SyntheticCameraScript = { ...defaultScript(), ...script }
122
- return new SharedCameraSession(createSyntheticBackend(controls, storage), config)
135
+ const controls: SyntheticCameraScript = { ...defaultScript(), ...script }
136
+
137
+ return new SharedCameraSession(createSyntheticBackend(controls, storage, config), config)
123
138
  }
124
139
 
125
140
  function createSyntheticBackend(
126
- script: SyntheticCameraScript,
127
- storage: SyntheticCameraStorage,
141
+ script: SyntheticCameraScript,
142
+ storage: SyntheticCameraStorage,
143
+ config: CameraSessionConfig,
128
144
  ): CameraSessionBackend {
129
- let observer: BackendObserver | undefined
130
- let attached = false
131
- let sink: BackendCaptureSink | undefined
132
- let startedAt: number | undefined
133
- let timers: ReturnType<typeof setTimeout>[] = []
134
- let pendingRequest: BackendCaptureRequest | undefined
135
-
136
- const later = (ms: number, fn: () => void) => {
137
- timers.push(setTimeout(fn, ms))
138
- }
139
-
140
- const clearTimers = () => {
141
- for (const timer of timers) {
142
- clearTimeout(timer)
143
- }
144
-
145
- timers = []
146
- }
147
-
148
- const settleClip = async (request: BackendCaptureRequest, limitReached: boolean) => {
149
- const path =
150
- request.destinationPath ??
151
- `/synthetic/clip-${Date.now()}-${Math.random().toString(36).slice(2)}.mov`
152
-
153
- if (!script.produceMedia) {
154
- sink?.settled({
155
- kind: 'failed',
156
- stage: 'capture',
157
- issue: {
158
- kind: 'noMedia',
159
- operation: 'finalize',
160
- message: 'Synthetic source produced no media',
161
- },
162
- })
163
-
164
- return
165
- }
166
-
167
- if (script.failAt === 'finalize') {
168
- sink?.settled({
169
- kind: 'failed',
170
- stage: 'finalization',
171
- issue: {
172
- kind: 'finalizationFailed',
173
- operation: 'finalize',
174
- message: 'Synthetic finalization failure',
175
- },
176
- })
177
-
178
- return
179
- }
180
-
181
- if (script.failAt === 'storage') {
182
- sink?.settled({
183
- kind: 'failed',
184
- stage: 'storage',
185
- issue: {
186
- kind: 'storageFailed',
187
- operation: 'store',
188
- message: 'Synthetic storage failure',
189
- },
190
- })
191
-
192
- return
193
- }
194
-
195
- try {
196
- // Not playable media — seam bytes stand in for a fixture. The
197
- // output is marked `synthetic` so nothing mistakes it for real
198
- // capture.
199
- await storage.write(path, new Uint8Array([0x78, 0x70, 0x6c, 0x61, 0x74]))
200
- } catch (cause) {
201
- sink?.settled({
202
- kind: 'failed',
203
- stage: 'storage',
204
- issue: {
205
- kind: 'storageFailed',
206
- operation: 'store',
207
- message: cause instanceof Error ? cause.message : String(cause),
208
- cause,
209
- },
210
- })
211
-
212
- return
213
- }
214
-
215
- const output: MovieOutput = {
216
- kind: 'nativeFile',
217
- resourceId: `synthetic:${path}`,
218
- fileUrl: `file://${path}`,
219
- synthetic: true,
220
- }
221
-
222
- const settle: BackendSettle = {
223
- kind: 'clip',
224
- output,
225
- mimeType: 'video/quicktime',
226
- durationMs: script.clipDurationMs,
227
- width: 1280,
228
- height: 720,
229
- orientation: request.orientation ?? 'portrait',
230
- hasAudio: request.audio,
231
- limitReached,
232
- }
233
-
234
- sink?.settled(settle)
235
- }
236
-
237
- return {
238
- platform: 'synthetic',
239
- supported: true,
240
- checkPermission: async (kind) => script.permission[kind],
241
- requestPermission: async (kind) => script.permission[kind],
242
- getCapabilities: async () => ({
243
- ...capabilities,
244
- available: script.available,
245
- reason: script.available ? undefined : 'Synthetic camera is unavailable',
246
- }),
247
- previewReady: () => attached && script.available,
248
- focusAtPoint: (point) => {
249
- script.focusRequests?.push(point)
250
- },
251
- attachPreview: (_host, listener) => {
252
- attached = true
253
- queueMicrotask(() => {
254
- listener?.onReady?.()
255
- observer?.previewReady(true)
256
- })
257
-
258
- return () => {
259
- attached = false
260
- observer?.previewReady(false)
261
- }
262
- },
263
- startCapture: (request, attemptSink) => {
264
- sink = attemptSink
265
- pendingRequest = request
266
- if (!script.available) {
267
- attemptSink.settled({
268
- kind: 'failed',
269
- stage: 'preparation',
270
- issue: {
271
- kind: 'unavailable',
272
- operation: 'startRecording',
273
- message: 'Synthetic camera is unavailable',
274
- },
275
- })
276
-
277
- return
278
- }
279
-
280
- if (script.failAt === 'start') {
281
- later(script.startDelayMs, () => {
282
- attemptSink.settled({
283
- kind: 'failed',
284
- stage: 'preparation',
285
- issue: {
286
- kind: 'captureFailed',
287
- operation: 'startRecording',
288
- message: 'Synthetic start failure',
289
- },
290
- })
291
- })
292
-
293
- return
294
- }
295
-
296
- later(script.startDelayMs, () => {
297
- startedAt = Date.now()
298
- attemptSink.started({
299
- cameraId: 'synthetic-back',
300
- facing: 'back',
301
- audio: request.audio,
302
- width: 1280,
303
- height: 720,
304
- frameRate: 30,
305
- orientation: request.orientation ?? 'portrait',
306
- mimeType: 'video/quicktime',
307
- container: 'mov',
308
- })
309
-
310
- if (script.interruption) {
311
- later(script.interruption.afterMs, () => {
312
- observer?.interruption('began', script.interruption?.reason)
313
- if (script.interruption?.endsAfterMs !== undefined) {
314
- later(script.interruption.endsAfterMs, () => {
315
- observer?.interruption('ended', script.interruption?.reason)
316
- })
317
- }
318
- })
319
- }
320
-
321
- if (request.maximumDurationMs !== undefined) {
322
- later(request.maximumDurationMs, () => {
323
- void settleClip(request, true)
324
- })
325
- }
326
-
327
- if (script.failAt === 'capture') {
328
- later(50, () => {
329
- attemptSink.settled({
330
- kind: 'failed',
331
- stage: 'capture',
332
- issue: {
333
- kind: 'captureFailed',
334
- operation: 'record',
335
- message: 'Synthetic capture failure',
336
- },
337
- })
338
- })
339
- }
340
- })
341
- },
342
- stopCapture: () => {
343
- // Settle asynchronously — native stop is async too.
344
- const request = pendingRequest
345
- later(5, () => {
346
- if (request) {
347
- void settleClip(request, false)
348
- }
349
- })
350
- },
351
- elapsedMs: () => (startedAt === undefined ? 0 : Date.now() - startedAt),
352
- openOutput: async (output) => {
353
- const path = output.kind === 'nativeFile' ? output.fileUrl.slice('file://'.length) : ''
354
- const exists = storage.exists ? await storage.exists(path) : !!(await storage.read(path))
355
- if (!exists) {
356
- throw new Error(`Synthetic clip is missing at ${output.resourceId}`)
357
- }
358
-
359
- return {
360
- url: output.kind === 'nativeFile' ? output.fileUrl : output.resourceId,
361
- fileUrl: output.kind === 'nativeFile' ? output.fileUrl : undefined,
362
- release: () => {},
363
- }
364
- },
365
- release: async () => {
366
- attached = false
367
- clearTimers()
368
- sink = undefined
369
- startedAt = undefined
370
- pendingRequest = undefined
371
- },
372
- onPreviewDetached: () => {},
373
- setObserver: (next) => {
374
- observer = next
375
- },
376
- }
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
+ }
377
436
  }