@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,4 +1,5 @@
1
1
  import '@nativescript/macos-node-api'
2
+ import { createCameraHost } from './camera-host.macos.ts'
2
3
 
3
4
  import { CameraCaptureError } from './types'
4
5
  import { canonicalizePath } from './session-core'
@@ -6,702 +7,719 @@ import type { BackendCaptureRequest, BackendCaptureSink, BackendObserver } from
6
7
  import type { CameraSessionBackend } from './session-core'
7
8
  import type { BackendPreviewListener } from './session-core'
8
9
  import type {
9
- CameraDeviceInfo,
10
- CameraOrientation,
11
- CameraPermissionKind,
12
- CameraPermissionStatus,
13
- CameraSessionCapabilities,
14
- CameraSessionConfig,
15
- CaptureIssue,
16
- EffectiveCaptureConfig,
17
- MovieOutputHandle,
10
+ CameraDeviceInfo,
11
+ CameraOrientation,
12
+ CameraPermissionKind,
13
+ CameraPermissionStatus,
14
+ CameraSessionCapabilities,
15
+ CameraSessionConfig,
16
+ CaptureIssue,
17
+ EffectiveCaptureConfig,
18
+ MovieOutputHandle,
18
19
  } from './types'
19
20
 
20
21
  declare const NSFileManager: any
21
22
 
22
23
  interface CameraHost {
23
- attachPreview(view: object): string | null
24
- detachPreview(): void
25
- installObserver(emit: (message: string) => void): void
26
- permissionStatus(kind: string): string
27
- requestPermissionReply(kind: string, reply: (status: string) => void): void
28
- devices(): string
29
- audioDeviceAvailable(): boolean
30
- audioInputAttached(): boolean
31
- activeDeviceId(): string | null
32
- configure(options: { cameraId?: string; audio?: boolean; rotationAngle?: number }): string | null
33
- /** Optional so a host built before the metering leaf shipped degrades
34
- * to a no-op instead of a selector error. */
35
- focusAtPoint?(point: { x: number; y: number }): boolean
36
- supportsRotationAngles(): boolean
37
- movieDirectory(): string | null
38
- startRecording(path: string, maximumDurationMs: number): string | null
39
- stopRecording(): void
40
- recording(): boolean
41
- recordedMs(): number
42
- previewSize(): string
43
- dispose(): void
44
- }
45
-
46
- declare const XplatCameraHost: {
47
- alloc(): { init(): CameraHost }
24
+ attachPreview(view: object): string | null
25
+ detachPreview(): void
26
+ installObserver(emit: (message: string) => void): void
27
+ permissionStatus(kind: string): string
28
+ requestPermissionReply(kind: string, reply: (status: string) => void): void
29
+ devices(): string
30
+ audioDeviceAvailable(): boolean
31
+ audioInputAttached(): boolean
32
+ activeDeviceId(): string | null
33
+ configure(options: { cameraId?: string; audio?: boolean; rotationAngle?: number }): string | null
34
+ /** Optional so a host built before the metering leaf shipped degrades
35
+ * to a no-op instead of a selector error. */
36
+ focusAtPoint?(point: { x: number; y: number }): boolean
37
+ supportsRotationAngles(): boolean
38
+ movieDirectory(): string | null
39
+ startRecording(path: string, maximumDurationMs: number): string | null
40
+ stopRecording(): void
41
+ recording(): boolean
42
+ recordedMs(): number
43
+ previewSize(): string
44
+ dispose(): void
48
45
  }
49
46
 
50
47
  type HostEvent =
51
- | { type: 'recordingStarted'; fileUrl: string; audio: boolean }
52
- | {
53
- type: 'recordingFinished'
54
- fileUrl: string
55
- succeeded: boolean
56
- limitReached: boolean
57
- clip?: {
58
- fileUrl: string
59
- durationMs: number
60
- width: number
61
- height: number
62
- rotationAngle: number
63
- fileSize: number
64
- hasAudio: boolean
65
- videoCodec?: string
66
- }
67
- error?: { domain: string; code: number; message: string }
68
- }
69
- | { type: 'interrupted'; cause: string }
70
- | { type: 'interruptionEnded' }
71
- | { type: 'availability'; available: boolean }
72
- | { type: 'previewReady'; ready: boolean }
48
+ | { type: 'recordingStarted'; fileUrl: string; audio: boolean }
49
+ | {
50
+ type: 'recordingFinished'
51
+ fileUrl: string
52
+ succeeded: boolean
53
+ limitReached: boolean
54
+ clip?: {
55
+ fileUrl: string
56
+ durationMs: number
57
+ width: number
58
+ height: number
59
+ rotationAngle: number
60
+ fileSize: number
61
+ hasAudio: boolean
62
+ videoCodec?: string
63
+ }
64
+ error?: { domain: string; code: number; message: string }
65
+ }
66
+ | { type: 'interrupted'; cause: string }
67
+ | { type: 'interruptionEnded' }
68
+ | { type: 'availability'; available: boolean }
69
+ | { type: 'previewReady'; ready: boolean }
73
70
 
74
71
  const orientationToRotationAngle = (orientation: CameraOrientation): number | undefined =>
75
- orientation === 'portrait'
76
- ? 90
77
- : orientation === 'portraitUpsideDown'
78
- ? 270
79
- : orientation === 'landscapeLeft'
80
- ? 180
81
- : orientation === 'landscapeRight'
82
- ? 0
83
- : undefined
72
+ orientation === 'portrait'
73
+ ? 90
74
+ : orientation === 'portraitUpsideDown'
75
+ ? 270
76
+ : orientation === 'landscapeLeft'
77
+ ? 180
78
+ : orientation === 'landscapeRight'
79
+ ? 0
80
+ : undefined
84
81
 
85
82
  const orientationFromRotationAngle = (angle: number): CameraOrientation =>
86
- angle === 90
87
- ? 'portrait'
88
- : angle === 270
89
- ? 'portraitUpsideDown'
90
- : angle === 180
91
- ? 'landscapeLeft'
92
- : angle === 0
93
- ? 'landscapeRight'
94
- : 'unspecified'
83
+ angle === 90
84
+ ? 'portrait'
85
+ : angle === 270
86
+ ? 'portraitUpsideDown'
87
+ : angle === 180
88
+ ? 'landscapeLeft'
89
+ : angle === 0
90
+ ? 'landscapeRight'
91
+ : 'unspecified'
95
92
 
96
93
  const usageKey = (kind: CameraPermissionKind) =>
97
- kind === 'camera' ? 'NSCameraUsageDescription' : 'NSMicrophoneUsageDescription'
94
+ kind === 'camera' ? 'NSCameraUsageDescription' : 'NSMicrophoneUsageDescription'
98
95
 
99
96
  /** AppKit adapter: one XplatCameraHost (AVCaptureSession) shared between the
100
97
  * attached preview and a single AVCaptureMovieFileOutput capture attempt.
101
- * The Swift leaf owns the session, inputs, preview layer, and recording
98
+ * The TS host owns the session, inputs, preview layer, and recording
102
99
  * delegate; this adapter owns admission, semantics, and contract mapping. */
103
100
  export function createSessionBackend(config: CameraSessionConfig): CameraSessionBackend {
104
- const host = XplatCameraHost.alloc().init()
105
- let currentConfig = { ...config }
106
- let previewReadyFlag = false
107
- let observer: BackendObserver | undefined
108
- let captureSink: BackendCaptureSink | undefined
109
- let captureRequest: BackendCaptureRequest | undefined
110
- let captureFilePath = ''
111
- let released = false
112
-
113
- const emitIssue = (
114
- kind: CaptureIssue['kind'],
115
- operation: string,
116
- message: string,
117
- cause?: unknown,
118
- ): CaptureIssue => ({ kind, operation, message, cause })
119
-
120
- const error = (kind: CaptureIssue['kind'], operation: string, message: string, cause?: unknown) =>
121
- new CameraCaptureError({ kind, operation, message, cause })
122
-
123
- const devices = (): CameraDeviceInfo[] => {
124
- try {
125
- return (
126
- JSON.parse(host.devices()) as {
127
- id: string
128
- name: string
129
- facing?: 'front' | 'back' | null
130
- }[]
131
- ).map((entry) => ({
132
- id: entry.id,
133
- label: entry.name,
134
- facing: entry.facing ?? undefined,
135
- }))
136
- } catch {
137
- return []
138
- }
139
- }
140
-
141
- const previewSize = (): { width: number; height: number } | undefined => {
142
- try {
143
- const size = JSON.parse(host.previewSize())
144
- return size.width > 0 ? { width: size.width, height: size.height } : undefined
145
- } catch {
146
- return undefined
147
- }
148
- }
149
-
150
- /** Point-of-interest metering support on the selected device, read
151
- * from the same device list `devices()` reports. */
152
- const pointOfInterestSupport = (): { focus: boolean; exposure: boolean } => {
153
- try {
154
- const list = JSON.parse(host.devices()) as {
155
- id: string
156
- focusPointOfInterest?: boolean
157
- exposurePointOfInterest?: boolean
158
- }[]
159
-
160
- const selected = selectedCameraId()
161
- const device = list.find((entry) => entry.id === selected) ?? list[0]
162
- return {
163
- focus: device?.focusPointOfInterest === true,
164
- exposure: device?.exposurePointOfInterest === true,
165
- }
166
- } catch {
167
- return { focus: false, exposure: false }
168
- }
169
- }
170
-
171
- const selectedCameraId = (config: CameraSessionConfig = currentConfig): string | undefined => {
172
- const selection = config.camera
173
- if (selection && typeof selection === 'object' && 'deviceId' in selection) {
174
- return selection.deviceId
175
- }
176
-
177
- // 'default'/'front'/'back' resolve to the first available device —
178
- // macOS cameras carry no front/back facing semantics.
179
- return devices()[0]?.id
180
- }
181
-
182
- host.installObserver((message) => {
183
- let event: HostEvent
184
- try {
185
- event = JSON.parse(message)
186
- } catch {
187
- return
188
- }
189
-
190
- switch (event.type) {
191
- case 'recordingStarted': {
192
- if (!sameFile(event.fileUrl, captureFilePath) || !captureSink || !captureRequest) {
193
- return
194
- }
195
-
196
- const size = previewSize()
197
- const configuration: EffectiveCaptureConfig = {
198
- cameraId: host.activeDeviceId() ?? selectedCameraId() ?? '',
199
- audio: event.audio,
200
- width: size?.width ?? 1280,
201
- height: size?.height ?? 720,
202
- frameRate: 30,
203
- orientation: captureRequest.orientation ?? 'unspecified',
204
- mimeType: 'video/quicktime',
205
- container: 'mov',
206
- }
207
-
208
- captureSink.started(configuration)
209
- return
210
- }
211
- case 'recordingFinished': {
212
- if (!sameFile(event.fileUrl, captureFilePath) || !captureSink || !captureRequest) {
213
- return
214
- }
215
-
216
- const sink = captureSink
217
- const request = captureRequest
218
- captureSink = undefined
219
- captureRequest = undefined
220
-
221
- if (!event.succeeded || !event.clip) {
222
- sink.settled({
223
- kind: 'failed',
224
- stage: 'capture',
225
- issue: emitIssue(
226
- 'captureFailed',
227
- 'finalize',
228
- event.error?.message ?? 'Movie recording did not complete',
229
- ),
230
- })
231
-
232
- return
233
- }
234
-
235
- if (!(event.clip.durationMs > 0) || !(event.clip.width > 0) || !(event.clip.height > 0)) {
236
- sink.settled({
237
- kind: 'failed',
238
- stage: 'capture',
239
- issue: emitIssue(
240
- 'captureFailed',
241
- 'finalize',
242
- 'The finalized movie has no usable video media',
243
- ),
244
- })
245
-
246
- return
247
- }
248
-
249
- if (request.audio && !event.clip.hasAudio) {
250
- sink.settled({
251
- kind: 'failed',
252
- stage: 'capture',
253
- issue: emitIssue(
254
- 'captureFailed',
255
- 'finalize',
256
- 'Requested audio track is missing from the finalized movie',
257
- ),
258
- })
259
-
260
- return
261
- }
262
-
263
- sink.settled({
264
- kind: 'clip',
265
- output: {
266
- kind: 'nativeFile',
267
- resourceId: event.fileUrl,
268
- fileUrl: event.fileUrl,
269
- },
270
- mimeType: 'video/quicktime',
271
- durationMs: event.clip.durationMs,
272
- width: event.clip.width,
273
- height: event.clip.height,
274
- orientation:
275
- request.orientation ?? orientationFromRotationAngle(event.clip.rotationAngle),
276
- hasAudio: request.audio && event.clip.hasAudio,
277
- limitReached: event.limitReached,
278
- })
279
-
280
- return
281
- }
282
- case 'interrupted':
283
- observer?.interruption(
284
- 'began',
285
- (event.cause as Parameters<BackendObserver['interruption']>[1]) ?? 'unknown',
286
- )
287
-
288
- observer?.previewReady(previewReadyFlag)
289
- return
290
- case 'interruptionEnded':
291
- observer?.interruption('ended')
292
- observer?.previewReady(previewReadyFlag)
293
- return
294
- case 'availability':
295
- observer?.availability(event.available)
296
- return
297
- case 'previewReady':
298
- previewReadyFlag = event.ready
299
- observer?.previewReady(previewReadyFlag)
300
- return
301
- }
302
- })
303
-
304
- const checkPermission = async (kind: CameraPermissionKind): Promise<CameraPermissionStatus> => {
305
- const status = host.permissionStatus(kind)
306
- return (status === 'undeclared' ? 'unknown' : status) as CameraPermissionStatus
307
- }
308
-
309
- const requestPermission = async (kind: CameraPermissionKind): Promise<CameraPermissionStatus> => {
310
- if (host.permissionStatus(kind) === 'undeclared') {
311
- throw error(
312
- 'configurationMissing',
313
- 'requestPermission',
314
- `Missing ${usageKey(kind)} in the app Info.plist`,
315
- )
316
- }
317
-
318
- const status = await new Promise<string>((resolve) =>
319
- host.requestPermissionReply(kind, resolve),
320
- )
321
-
322
- return (status === 'undeclared' ? 'unknown' : status) as CameraPermissionStatus
323
- }
324
-
325
- const recordingsDirectory = (): string => {
326
- const root = host.movieDirectory()
327
- if (!root) {
328
- throw error(
329
- 'destinationUnavailable',
330
- 'startRecording',
331
- 'The app has no writable private camera directory',
332
- )
333
- }
334
-
335
- return decodeURIComponent(root.replace(/^file:\/\//, '').replace(/\/$/, ''))
336
- }
337
-
338
- // Durable output must stay app-private: destinations resolve inside the
339
- // app's own Application Support root — the recordings directory's parent.
340
- const appPrivateRoot = () =>
341
- recordingsDirectory().slice(0, recordingsDirectory().lastIndexOf('/'))
342
-
343
- const pathExists = (path: string): boolean =>
344
- Boolean(NSFileManager.defaultManager.fileExistsAtPath(path))
345
-
346
- // Correlate capture events by path, not serialized URL — Foundation's
347
- // URL(fileURLWithPath:).absoluteString escapes differently than
348
- // encodeURIComponent, so URL equality drops real start/finish events.
349
- const sameFile = (fileUrl: string | undefined, filePath: string): boolean => {
350
- if (!fileUrl || !filePath) {
351
- return false
352
- }
353
-
354
- const raw = fileUrl.startsWith('file://') ? fileUrl.slice('file://'.length) : fileUrl
355
- try {
356
- return decodeURIComponent(raw) === filePath
357
- } catch {
358
- return raw === filePath
359
- }
360
- }
361
-
362
- return {
363
- platform: 'macos',
364
- get supported() {
365
- return !released
366
- },
367
- checkPermission,
368
- requestPermission,
369
- getCapabilities: async (): Promise<CameraSessionCapabilities> => {
370
- const list = devices()
371
- const available = list.length > 0
372
- const size = previewSize()
373
- const pointOfInterest = pointOfInterestSupport()
374
- return {
375
- supported: available,
376
- reason: available ? undefined : 'No camera device is available on this host',
377
- available,
378
- cameras: list,
379
- profiles: [
380
- {
381
- profile: 'standard',
382
- width: size?.width ?? 1280,
383
- height: size?.height ?? 720,
384
- frameRate: 30,
385
- },
386
- ],
387
- audio: host.audioDeviceAvailable(),
388
- focusPointOfInterest: pointOfInterest.focus,
389
- exposurePointOfInterest: pointOfInterest.exposure,
390
- // AVCaptureConnection rotation angles exist on macOS 14+;
391
- // earlier hosts cannot lock a take's orientation.
392
- orientations: host.supportsRotationAngles()
393
- ? ['landscapeLeft', 'landscapeRight', 'portrait', 'portraitUpsideDown']
394
- : [],
395
- durationLimit: 'native',
396
- elapsedTime: 'nativeMedia',
397
- output: {
398
- mimeType: 'video/quicktime',
399
- container: 'mov',
400
- storage: 'appPrivateFile',
401
- destinationFileUrl: true,
402
- },
403
- }
404
- },
405
- previewReady: () => previewReadyFlag,
406
- attachPreview: (target, listener?: BackendPreviewListener) => {
407
- if (released) {
408
- throw error('unavailable', 'attachPreview', 'CameraSession is disposed')
409
- }
410
-
411
- if (host.permissionStatus('camera') !== 'granted') {
412
- throw error(
413
- 'permissionDenied',
414
- 'attachPreview',
415
- 'Camera preview requires an explicit granted camera permission',
416
- )
417
- }
418
-
419
- if (!devices().length) {
420
- throw error('unavailable', 'attachPreview', 'No camera device is available on this host')
421
- }
422
-
423
- const configured = host.configure({
424
- cameraId: selectedCameraId(),
425
- audio: currentConfig.audio ?? false,
426
- })
427
-
428
- if (configured) {
429
- throw error(
430
- configured === 'busy'
431
- ? 'busy'
432
- : configured === 'permissionDenied'
433
- ? 'permissionDenied'
434
- : 'unavailable',
435
- 'attachPreview',
436
- `Failed to configure the capture session: ${configured}`,
437
- )
438
- }
439
-
440
- const failure = host.attachPreview(target as object)
441
- if (failure) {
442
- throw error(
443
- failure === 'permissionDenied' ? 'permissionDenied' : 'unavailable',
444
- 'attachPreview',
445
- `Failed to start camera preview: ${failure}`,
446
- )
447
- }
448
-
449
- listener?.onReady?.()
450
- return () => {
451
- previewReadyFlag = false
452
- observer?.previewReady(false)
453
- host.detachPreview()
454
- }
455
- },
456
- configure: (next) => {
457
- const configured = host.configure({
458
- cameraId: selectedCameraId(next),
459
- audio: next.audio ?? false,
460
- })
461
-
462
- if (configured) {
463
- throw error(
464
- configured === 'busy'
465
- ? 'busy'
466
- : configured === 'permissionDenied'
467
- ? 'permissionDenied'
468
- : configured === 'unsupportedConfiguration'
469
- ? 'unsupportedConfiguration'
470
- : 'unavailable',
471
- 'configure',
472
- `Failed to configure the capture session: ${configured}`,
473
- )
474
- }
475
-
476
- currentConfig = { ...next }
477
- },
478
- focusAtPoint: (point) => {
479
- try {
480
- host.focusAtPoint?.({ x: point.x, y: point.y })
481
- } catch {
482
- // A missed metering pass must not fault the session.
483
- }
484
- },
485
- startCapture: (request, sink) => {
486
- if (host.permissionStatus('camera') === 'undeclared') {
487
- sink.settled({
488
- kind: 'failed',
489
- stage: 'preparation',
490
- issue: emitIssue(
491
- 'configurationMissing',
492
- 'startRecording',
493
- "Missing NSCameraUsageDescription in the host app's Info.plist",
494
- ),
495
- })
496
-
497
- return
498
- }
499
-
500
- if (request.audio) {
501
- if (host.permissionStatus('microphone') === 'undeclared') {
502
- sink.settled({
503
- kind: 'failed',
504
- stage: 'preparation',
505
- issue: emitIssue(
506
- 'configurationMissing',
507
- 'startRecording',
508
- "Missing NSMicrophoneUsageDescription in the host app's Info.plist",
509
- ),
510
- })
511
-
512
- return
513
- }
514
-
515
- const mic = host.permissionStatus('microphone')
516
- if (mic !== 'granted') {
517
- sink.settled({
518
- kind: 'failed',
519
- stage: 'preparation',
520
- issue: emitIssue(
521
- mic === 'restricted' ? 'permissionRestricted' : 'permissionDenied',
522
- 'startRecording',
523
- `Microphone permission is ${mic}`,
524
- ),
525
- })
526
-
527
- return
528
- }
529
-
530
- if (!host.audioDeviceAvailable()) {
531
- sink.settled({
532
- kind: 'failed',
533
- stage: 'preparation',
534
- issue: emitIssue('unavailable', 'startRecording', 'No audio input device is available'),
535
- })
536
-
537
- return
538
- }
539
- }
540
-
541
- const rotationAngle =
542
- request.orientation !== undefined
543
- ? orientationToRotationAngle(request.orientation)
544
- : undefined
545
-
546
- if (request.orientation !== undefined && rotationAngle === undefined) {
547
- sink.settled({
548
- kind: 'failed',
549
- stage: 'preparation',
550
- issue: emitIssue(
551
- 'unsupportedConfiguration',
552
- 'startRecording',
553
- `Orientation '${request.orientation}' is not supported by this connection`,
554
- ),
555
- })
556
-
557
- return
558
- }
559
-
560
- const configured = host.configure({
561
- cameraId: selectedCameraId(),
562
- audio: request.audio || (currentConfig.audio ?? false),
563
- rotationAngle,
564
- })
565
-
566
- if (configured) {
567
- sink.settled({
568
- kind: 'failed',
569
- stage: 'preparation',
570
- issue: emitIssue(
571
- configured === 'unsupportedConfiguration' ? 'unsupportedConfiguration' : 'unavailable',
572
- 'startRecording',
573
- configured === 'unsupportedConfiguration'
574
- ? `Orientation '${request.orientation}' is not supported by this connection`
575
- : 'The requested capture configuration is unavailable',
576
- ),
577
- })
578
-
579
- return
580
- }
581
-
582
- let filePath: string
583
- if (request.destinationPath) {
584
- // Canonicalize before the prefix check — a '..' segment keeps
585
- // the root prefix on a raw string while resolving outside it.
586
- const destination = canonicalizePath(request.destinationPath)
587
- const inside = destination.startsWith(`${appPrivateRoot()}/`)
588
- const directory = destination.slice(0, destination.lastIndexOf('/'))
589
-
590
- const directoryExists = inside && pathExists(directory)
591
- const fileExists = inside && pathExists(destination)
592
- if (!inside || !directoryExists || fileExists) {
593
- sink.settled({
594
- kind: 'failed',
595
- stage: 'preparation',
596
- issue: emitIssue(
597
- 'destinationUnavailable',
598
- 'startRecording',
599
- !inside
600
- ? 'destinationFileUrl must resolve inside the app-private recordings directory'
601
- : fileExists
602
- ? 'destinationFileUrl already exists'
603
- : 'destinationFileUrl directory does not exist',
604
- ),
605
- })
606
-
607
- return
608
- }
609
-
610
- if (!/\.mov$/i.test(destination)) {
611
- sink.settled({
612
- kind: 'failed',
613
- stage: 'preparation',
614
- issue: emitIssue(
615
- 'destinationUnavailable',
616
- 'startRecording',
617
- 'destinationFileUrl must use a .mov file name',
618
- ),
619
- })
620
-
621
- return
622
- }
623
-
624
- filePath = destination
625
- } else {
626
- try {
627
- filePath = `${recordingsDirectory()}/clip-${Date.now()}-${Math.random()
628
- .toString(36)
629
- .slice(2, 8)}.mov`
630
- } catch (cause) {
631
- sink.settled({
632
- kind: 'failed',
633
- stage: 'preparation',
634
- issue: emitIssue(
635
- 'destinationUnavailable',
636
- 'startRecording',
637
- cause instanceof Error ? cause.message : String(cause),
638
- cause,
639
- ),
640
- })
641
-
642
- return
643
- }
644
- }
645
-
646
- captureFilePath = filePath
647
-
648
- captureSink = sink
649
- captureRequest = request
650
- const failure = host.startRecording(filePath, request.maximumDurationMs ?? 0)
651
- if (failure) {
652
- captureSink = undefined
653
- captureRequest = undefined
654
- captureFilePath = ''
655
- sink.settled({
656
- kind: 'failed',
657
- stage: 'preparation',
658
- issue: emitIssue(
659
- 'unavailable',
660
- 'startRecording',
661
- `Failed to start movie capture: ${failure}`,
662
- ),
663
- })
664
- }
665
- },
666
- stopCapture: () => {
667
- host.stopRecording()
668
- },
669
- elapsedMs: () => host.recordedMs(),
670
- openOutput: async (output) => {
671
- if (output.kind !== 'nativeFile' || !output.fileUrl) {
672
- throw error(
673
- 'invalidArgument',
674
- 'openOutput',
675
- 'Only file-backed output can be opened on macOS',
676
- )
677
- }
678
-
679
- const filePath = decodeURIComponent(output.fileUrl.slice('file://'.length))
680
- if (!pathExists(filePath)) {
681
- throw error('unavailable', 'openOutput', `Movie file is missing at ${output.fileUrl}`)
682
- }
683
-
684
- const handle: MovieOutputHandle = {
685
- url: output.fileUrl,
686
- fileUrl: output.fileUrl,
687
- release: () => {},
688
- }
689
-
690
- return handle
691
- },
692
- release: async () => {
693
- released = true
694
- previewReadyFlag = false
695
- captureSink = undefined
696
- captureRequest = undefined
697
- host.dispose()
698
- },
699
- onPreviewDetached: () => {
700
- // The view went away while a take settles; the Swift side keeps the
701
- // session alive until recordingFinished arrives.
702
- },
703
- setObserver: (next) => {
704
- observer = next
705
- },
706
- }
101
+ const host = createCameraHost()
102
+ let currentConfig = { ...config }
103
+ let previewReadyFlag = false
104
+ let observer: BackendObserver | undefined
105
+ let captureSink: BackendCaptureSink | undefined
106
+ let captureRequest: BackendCaptureRequest | undefined
107
+ let captureFilePath = ''
108
+ let released = false
109
+
110
+ const emitIssue = (
111
+ kind: CaptureIssue['kind'],
112
+ operation: string,
113
+ message: string,
114
+ cause?: unknown,
115
+ ): CaptureIssue => ({ kind, operation, message, cause })
116
+
117
+ const error = (kind: CaptureIssue['kind'], operation: string, message: string, cause?: unknown) =>
118
+ new CameraCaptureError({ kind, operation, message, cause })
119
+
120
+ /** Entries in the bridge's devices() JSON list. */
121
+ interface DeviceEntry {
122
+ id: string
123
+ name: string
124
+ facing?: 'front' | 'back' | null
125
+ focusPointOfInterest?: boolean
126
+ exposurePointOfInterest?: boolean
127
+ }
128
+
129
+ const devices = (): CameraDeviceInfo[] => {
130
+ try {
131
+ const parsed: unknown = JSON.parse(host.devices())
132
+
133
+ return (Array.isArray(parsed) ? (parsed as DeviceEntry[]) : []).map((entry) => ({
134
+ id: entry.id,
135
+ label: entry.name,
136
+ facing: entry.facing ?? undefined,
137
+ }))
138
+ } catch {
139
+ return []
140
+ }
141
+ }
142
+
143
+ const previewSize = (): { width: number; height: number } | undefined => {
144
+ try {
145
+ const size = JSON.parse(host.previewSize())
146
+
147
+ return size.width > 0 ? { width: size.width, height: size.height } : undefined
148
+ } catch {
149
+ return undefined
150
+ }
151
+ }
152
+
153
+ /** Point-of-interest metering support on the selected device, read
154
+ * from the same device list `devices()` reports. */
155
+ const pointOfInterestSupport = (): { focus: boolean; exposure: boolean } => {
156
+ try {
157
+ const parsed: unknown = JSON.parse(host.devices())
158
+ const list = Array.isArray(parsed) ? (parsed as DeviceEntry[]) : []
159
+
160
+ const selected = selectedCameraId()
161
+ const device = list.find((entry) => entry.id === selected) ?? list[0]
162
+
163
+ return {
164
+ focus: device?.focusPointOfInterest === true,
165
+ exposure: device?.exposurePointOfInterest === true,
166
+ }
167
+ } catch {
168
+ return { focus: false, exposure: false }
169
+ }
170
+ }
171
+
172
+ const selectedCameraId = (config: CameraSessionConfig = currentConfig): string | undefined => {
173
+ const selection = config.camera
174
+
175
+ if (selection && typeof selection === 'object' && 'deviceId' in selection) {
176
+ return selection.deviceId
177
+ }
178
+
179
+ // 'default'/'front'/'back' resolve to the first available device —
180
+ // macOS cameras carry no front/back facing semantics.
181
+ return devices()[0]?.id
182
+ }
183
+
184
+ host.installObserver((message) => {
185
+ let event: HostEvent
186
+
187
+ try {
188
+ event = JSON.parse(message)
189
+ } catch {
190
+ return
191
+ }
192
+
193
+ switch (event.type) {
194
+ case 'recordingStarted': {
195
+ if (!sameFile(event.fileUrl, captureFilePath) || !captureSink || !captureRequest) {
196
+ return
197
+ }
198
+
199
+ const size = previewSize()
200
+ const configuration: EffectiveCaptureConfig = {
201
+ cameraId: host.activeDeviceId() ?? selectedCameraId() ?? '',
202
+ audio: event.audio,
203
+ width: size?.width ?? 1280,
204
+ height: size?.height ?? 720,
205
+ frameRate: 30,
206
+ orientation: captureRequest.orientation ?? 'unspecified',
207
+ mimeType: 'video/quicktime',
208
+ container: 'mov',
209
+ }
210
+
211
+ captureSink.started(configuration)
212
+ return
213
+ }
214
+ case 'recordingFinished': {
215
+ if (!sameFile(event.fileUrl, captureFilePath) || !captureSink || !captureRequest) {
216
+ return
217
+ }
218
+
219
+ const sink = captureSink
220
+ const request = captureRequest
221
+
222
+ captureSink = undefined
223
+ captureRequest = undefined
224
+
225
+ if (!event.succeeded || !event.clip) {
226
+ sink.settled({
227
+ kind: 'failed',
228
+ stage: 'capture',
229
+ issue: emitIssue(
230
+ 'captureFailed',
231
+ 'finalize',
232
+ event.error?.message ?? 'Movie recording did not complete',
233
+ ),
234
+ })
235
+
236
+ return
237
+ }
238
+
239
+ if (!(event.clip.durationMs > 0) || !(event.clip.width > 0) || !(event.clip.height > 0)) {
240
+ sink.settled({
241
+ kind: 'failed',
242
+ stage: 'capture',
243
+ issue: emitIssue(
244
+ 'captureFailed',
245
+ 'finalize',
246
+ 'The finalized movie has no usable video media',
247
+ ),
248
+ })
249
+
250
+ return
251
+ }
252
+
253
+ if (request.audio && !event.clip.hasAudio) {
254
+ sink.settled({
255
+ kind: 'failed',
256
+ stage: 'capture',
257
+ issue: emitIssue(
258
+ 'captureFailed',
259
+ 'finalize',
260
+ 'Requested audio track is missing from the finalized movie',
261
+ ),
262
+ })
263
+
264
+ return
265
+ }
266
+
267
+ sink.settled({
268
+ kind: 'clip',
269
+ output: {
270
+ kind: 'nativeFile',
271
+ resourceId: event.fileUrl,
272
+ fileUrl: event.fileUrl,
273
+ },
274
+ mimeType: 'video/quicktime',
275
+ durationMs: event.clip.durationMs,
276
+ width: event.clip.width,
277
+ height: event.clip.height,
278
+ orientation:
279
+ request.orientation ?? orientationFromRotationAngle(event.clip.rotationAngle),
280
+ hasAudio: request.audio && event.clip.hasAudio,
281
+ limitReached: event.limitReached,
282
+ })
283
+
284
+ return
285
+ }
286
+ case 'interrupted':
287
+ observer?.interruption(
288
+ 'began',
289
+ (event.cause as Parameters<BackendObserver['interruption']>[1]) ?? 'unknown',
290
+ )
291
+
292
+ observer?.previewReady(previewReadyFlag)
293
+ return
294
+ case 'interruptionEnded':
295
+ observer?.interruption('ended')
296
+ observer?.previewReady(previewReadyFlag)
297
+ return
298
+ case 'availability':
299
+ observer?.availability(event.available)
300
+ return
301
+ case 'previewReady':
302
+ previewReadyFlag = event.ready
303
+ observer?.previewReady(previewReadyFlag)
304
+ return
305
+ }
306
+ })
307
+
308
+ const checkPermission = async (kind: CameraPermissionKind): Promise<CameraPermissionStatus> => {
309
+ const status = host.permissionStatus(kind)
310
+
311
+ return (status === 'undeclared' ? 'unknown' : status) as CameraPermissionStatus
312
+ }
313
+
314
+ const requestPermission = async (kind: CameraPermissionKind): Promise<CameraPermissionStatus> => {
315
+ if (host.permissionStatus(kind) === 'undeclared') {
316
+ throw error(
317
+ 'configurationMissing',
318
+ 'requestPermission',
319
+ `Missing ${usageKey(kind)} in the app Info.plist`,
320
+ )
321
+ }
322
+
323
+ const status = await new Promise<string>((resolve) =>
324
+ host.requestPermissionReply(kind, resolve),
325
+ )
326
+
327
+ return (status === 'undeclared' ? 'unknown' : status) as CameraPermissionStatus
328
+ }
329
+
330
+ const recordingsDirectory = (): string => {
331
+ const root = host.movieDirectory()
332
+
333
+ if (!root) {
334
+ throw error(
335
+ 'destinationUnavailable',
336
+ 'startRecording',
337
+ 'The app has no writable private camera directory',
338
+ )
339
+ }
340
+
341
+ return decodeURIComponent(root.replace(/^file:\/\//, '').replace(/\/$/, ''))
342
+ }
343
+
344
+ // Durable output must stay app-private: destinations resolve inside the
345
+ // app's own Application Support root — the recordings directory's parent.
346
+ const appPrivateRoot = () =>
347
+ recordingsDirectory().slice(0, recordingsDirectory().lastIndexOf('/'))
348
+
349
+ const pathExists = (path: string): boolean =>
350
+ Boolean(NSFileManager.defaultManager.fileExistsAtPath(path))
351
+
352
+ // Correlate capture events by path, not serialized URL — Foundation's
353
+ // URL(fileURLWithPath:).absoluteString escapes differently than
354
+ // encodeURIComponent, so URL equality drops real start/finish events.
355
+ const sameFile = (fileUrl: string | undefined, filePath: string): boolean => {
356
+ if (!fileUrl || !filePath) {
357
+ return false
358
+ }
359
+
360
+ const raw = fileUrl.startsWith('file://') ? fileUrl.slice('file://'.length) : fileUrl
361
+
362
+ try {
363
+ return decodeURIComponent(raw) === filePath
364
+ } catch {
365
+ return raw === filePath
366
+ }
367
+ }
368
+
369
+ return {
370
+ platform: 'macos',
371
+ get supported() {
372
+ return !released
373
+ },
374
+ checkPermission,
375
+ requestPermission,
376
+ getCapabilities: async (): Promise<CameraSessionCapabilities> => {
377
+ const list = devices()
378
+ const available = list.length > 0
379
+ const size = previewSize()
380
+ const pointOfInterest = pointOfInterestSupport()
381
+
382
+ return {
383
+ supported: available,
384
+ reason: available ? undefined : 'No camera device is available on this host',
385
+ available,
386
+ cameras: list,
387
+ profiles: [
388
+ {
389
+ profile: 'standard',
390
+ width: size?.width ?? 1280,
391
+ height: size?.height ?? 720,
392
+ frameRate: 30,
393
+ },
394
+ ],
395
+ audio: host.audioDeviceAvailable(),
396
+ focusPointOfInterest: pointOfInterest.focus,
397
+ exposurePointOfInterest: pointOfInterest.exposure,
398
+ // AVCaptureDevice zoom properties are iOS-only in AVFoundation.
399
+ zoom: false,
400
+ // AVCaptureConnection rotation angles exist on macOS 14+;
401
+ // earlier hosts cannot lock a take's orientation.
402
+ orientations: host.supportsRotationAngles()
403
+ ? ['landscapeLeft', 'landscapeRight', 'portrait', 'portraitUpsideDown']
404
+ : [],
405
+ cameraSwitchDuringRecording: false,
406
+ durationLimit: 'native',
407
+ elapsedTime: 'nativeMedia',
408
+ output: {
409
+ mimeType: 'video/quicktime',
410
+ container: 'mov',
411
+ storage: 'appPrivateFile',
412
+ destinationFileUrl: true,
413
+ },
414
+ }
415
+ },
416
+ previewReady: () => previewReadyFlag,
417
+ attachPreview: (target, listener?: BackendPreviewListener) => {
418
+ if (released) {
419
+ throw error('unavailable', 'attachPreview', 'CameraSession is disposed')
420
+ }
421
+
422
+ if (host.permissionStatus('camera') !== 'granted') {
423
+ throw error(
424
+ 'permissionDenied',
425
+ 'attachPreview',
426
+ 'Camera preview requires an explicit granted camera permission',
427
+ )
428
+ }
429
+
430
+ if (!devices().length) {
431
+ throw error('unavailable', 'attachPreview', 'No camera device is available on this host')
432
+ }
433
+
434
+ const configured = host.configure({
435
+ cameraId: selectedCameraId(),
436
+ audio: currentConfig.audio ?? false,
437
+ })
438
+
439
+ if (configured) {
440
+ throw error(
441
+ configured === 'busy'
442
+ ? 'busy'
443
+ : configured === 'permissionDenied'
444
+ ? 'permissionDenied'
445
+ : 'unavailable',
446
+ 'attachPreview',
447
+ `Failed to configure the capture session: ${configured}`,
448
+ )
449
+ }
450
+
451
+ const failure = host.attachPreview(target as object)
452
+
453
+ if (failure) {
454
+ throw error(
455
+ failure === 'permissionDenied' ? 'permissionDenied' : 'unavailable',
456
+ 'attachPreview',
457
+ `Failed to start camera preview: ${failure}`,
458
+ )
459
+ }
460
+
461
+ listener?.onReady?.()
462
+ return () => {
463
+ previewReadyFlag = false
464
+ observer?.previewReady(false)
465
+ host.detachPreview()
466
+ }
467
+ },
468
+ configure: (next) => {
469
+ const configured = host.configure({
470
+ cameraId: selectedCameraId(next),
471
+ audio: next.audio ?? false,
472
+ })
473
+
474
+ if (configured) {
475
+ throw error(
476
+ configured === 'busy'
477
+ ? 'busy'
478
+ : configured === 'permissionDenied'
479
+ ? 'permissionDenied'
480
+ : configured === 'unsupportedConfiguration'
481
+ ? 'unsupportedConfiguration'
482
+ : 'unavailable',
483
+ 'configure',
484
+ `Failed to configure the capture session: ${configured}`,
485
+ )
486
+ }
487
+
488
+ currentConfig = { ...next }
489
+ },
490
+ focusAtPoint: (point) => {
491
+ try {
492
+ host.focusAtPoint?.({ x: point.x, y: point.y })
493
+ } catch {
494
+ // A missed metering pass must not fault the session.
495
+ }
496
+ },
497
+ startCapture: (request, sink) => {
498
+ if (host.permissionStatus('camera') === 'undeclared') {
499
+ sink.settled({
500
+ kind: 'failed',
501
+ stage: 'preparation',
502
+ issue: emitIssue(
503
+ 'configurationMissing',
504
+ 'startRecording',
505
+ "Missing NSCameraUsageDescription in the host app's Info.plist",
506
+ ),
507
+ })
508
+
509
+ return
510
+ }
511
+
512
+ if (request.audio) {
513
+ if (host.permissionStatus('microphone') === 'undeclared') {
514
+ sink.settled({
515
+ kind: 'failed',
516
+ stage: 'preparation',
517
+ issue: emitIssue(
518
+ 'configurationMissing',
519
+ 'startRecording',
520
+ "Missing NSMicrophoneUsageDescription in the host app's Info.plist",
521
+ ),
522
+ })
523
+
524
+ return
525
+ }
526
+
527
+ const mic = host.permissionStatus('microphone')
528
+
529
+ if (mic !== 'granted') {
530
+ sink.settled({
531
+ kind: 'failed',
532
+ stage: 'preparation',
533
+ issue: emitIssue(
534
+ mic === 'restricted' ? 'permissionRestricted' : 'permissionDenied',
535
+ 'startRecording',
536
+ `Microphone permission is ${mic}`,
537
+ ),
538
+ })
539
+
540
+ return
541
+ }
542
+
543
+ if (!host.audioDeviceAvailable()) {
544
+ sink.settled({
545
+ kind: 'failed',
546
+ stage: 'preparation',
547
+ issue: emitIssue('unavailable', 'startRecording', 'No audio input device is available'),
548
+ })
549
+
550
+ return
551
+ }
552
+ }
553
+
554
+ const rotationAngle =
555
+ request.orientation !== undefined
556
+ ? orientationToRotationAngle(request.orientation)
557
+ : undefined
558
+
559
+ if (request.orientation !== undefined && rotationAngle === undefined) {
560
+ sink.settled({
561
+ kind: 'failed',
562
+ stage: 'preparation',
563
+ issue: emitIssue(
564
+ 'unsupportedConfiguration',
565
+ 'startRecording',
566
+ `Orientation '${request.orientation}' is not supported by this connection`,
567
+ ),
568
+ })
569
+
570
+ return
571
+ }
572
+
573
+ const configured = host.configure({
574
+ cameraId: selectedCameraId(),
575
+ audio: request.audio || (currentConfig.audio ?? false),
576
+ rotationAngle,
577
+ })
578
+
579
+ if (configured) {
580
+ sink.settled({
581
+ kind: 'failed',
582
+ stage: 'preparation',
583
+ issue: emitIssue(
584
+ configured === 'unsupportedConfiguration' ? 'unsupportedConfiguration' : 'unavailable',
585
+ 'startRecording',
586
+ configured === 'unsupportedConfiguration'
587
+ ? `Orientation '${request.orientation}' is not supported by this connection`
588
+ : 'The requested capture configuration is unavailable',
589
+ ),
590
+ })
591
+
592
+ return
593
+ }
594
+
595
+ let filePath: string
596
+
597
+ if (request.destinationPath) {
598
+ // Canonicalize before the prefix check — a '..' segment keeps
599
+ // the root prefix on a raw string while resolving outside it.
600
+ const destination = canonicalizePath(request.destinationPath)
601
+ const inside = destination.startsWith(`${appPrivateRoot()}/`)
602
+ const directory = destination.slice(0, destination.lastIndexOf('/'))
603
+
604
+ const directoryExists = inside && pathExists(directory)
605
+ const fileExists = inside && pathExists(destination)
606
+
607
+ if (!inside || !directoryExists || fileExists) {
608
+ sink.settled({
609
+ kind: 'failed',
610
+ stage: 'preparation',
611
+ issue: emitIssue(
612
+ 'destinationUnavailable',
613
+ 'startRecording',
614
+ !inside
615
+ ? 'destinationFileUrl must resolve inside the app-private recordings directory'
616
+ : fileExists
617
+ ? 'destinationFileUrl already exists'
618
+ : 'destinationFileUrl directory does not exist',
619
+ ),
620
+ })
621
+
622
+ return
623
+ }
624
+
625
+ if (!/\.mov$/i.test(destination)) {
626
+ sink.settled({
627
+ kind: 'failed',
628
+ stage: 'preparation',
629
+ issue: emitIssue(
630
+ 'destinationUnavailable',
631
+ 'startRecording',
632
+ 'destinationFileUrl must use a .mov file name',
633
+ ),
634
+ })
635
+
636
+ return
637
+ }
638
+
639
+ filePath = destination
640
+ } else {
641
+ try {
642
+ filePath = `${recordingsDirectory()}/clip-${Date.now()}-${Math.random()
643
+ .toString(36)
644
+ .slice(2, 8)}.mov`
645
+ } catch (cause) {
646
+ sink.settled({
647
+ kind: 'failed',
648
+ stage: 'preparation',
649
+ issue: emitIssue(
650
+ 'destinationUnavailable',
651
+ 'startRecording',
652
+ cause instanceof Error ? cause.message : String(cause),
653
+ cause,
654
+ ),
655
+ })
656
+
657
+ return
658
+ }
659
+ }
660
+
661
+ captureFilePath = filePath
662
+
663
+ captureSink = sink
664
+ captureRequest = request
665
+
666
+ const failure = host.startRecording(filePath, request.maximumDurationMs ?? 0)
667
+
668
+ if (failure) {
669
+ captureSink = undefined
670
+ captureRequest = undefined
671
+ captureFilePath = ''
672
+ sink.settled({
673
+ kind: 'failed',
674
+ stage: 'preparation',
675
+ issue: emitIssue(
676
+ 'unavailable',
677
+ 'startRecording',
678
+ `Failed to start movie capture: ${failure}`,
679
+ ),
680
+ })
681
+ }
682
+ },
683
+ stopCapture: () => {
684
+ host.stopRecording()
685
+ },
686
+ elapsedMs: () => host.recordedMs(),
687
+ openOutput: async (output) => {
688
+ if (output.kind !== 'nativeFile' || !output.fileUrl) {
689
+ throw error(
690
+ 'invalidArgument',
691
+ 'openOutput',
692
+ 'Only file-backed output can be opened on macOS',
693
+ )
694
+ }
695
+
696
+ const filePath = decodeURIComponent(output.fileUrl.slice('file://'.length))
697
+
698
+ if (!pathExists(filePath)) {
699
+ throw error('unavailable', 'openOutput', `Movie file is missing at ${output.fileUrl}`)
700
+ }
701
+
702
+ const handle: MovieOutputHandle = {
703
+ url: output.fileUrl,
704
+ fileUrl: output.fileUrl,
705
+ release: () => {},
706
+ }
707
+
708
+ return handle
709
+ },
710
+ release: async () => {
711
+ released = true
712
+ previewReadyFlag = false
713
+ captureSink = undefined
714
+ captureRequest = undefined
715
+ host.dispose()
716
+ },
717
+ onPreviewDetached: () => {
718
+ // The view went away while a take settles; the Swift side keeps the
719
+ // session alive until recordingFinished arrives.
720
+ },
721
+ setObserver: (next) => {
722
+ observer = next
723
+ },
724
+ }
707
725
  }