@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
@@ -0,0 +1,1059 @@
1
+ // TypeScript port of the removed Swift XplatCameraHost. The bridge wraps
2
+ // AVFoundation instances as untyped NativeObject — re-pointing the prototype
3
+ // (same idiom as the packaged host's WebSocket shim) binds the class members.
4
+ // Serial session operations are preserved: the JS thread serializes calls,
5
+ // while start/stopRunning dispatch natively on detached threads through
6
+ // performSelectorInBackground — gated by the session-op queue below because
7
+ // detached threads carry no ordering.
8
+ declare const objc: { import(framework: string): void }
9
+ declare const NSObject: any
10
+ declare const NativeClass: (cls: unknown) => void
11
+ declare const interop: any
12
+
13
+ const g = globalThis as any
14
+
15
+ declare const AVCaptureSession: any
16
+ declare const AVCaptureDevice: any
17
+ declare const AVCaptureDeviceInput: any
18
+ declare const AVCaptureDeviceDiscoverySession: any
19
+ declare const AVCaptureMovieFileOutput: any
20
+ declare const AVCapturePhotoOutput: any
21
+ declare const AVCapturePhotoSettings: any
22
+ declare const AVCapturePhoto: any
23
+ declare const AVCaptureVideoPreviewLayer: any
24
+ declare const AVCaptureConnection: any
25
+ declare const AVCaptureFileOutputRecordingDelegate: any
26
+ declare const AVCapturePhotoCaptureDelegate: any
27
+ declare const AVURLAsset: any
28
+ declare const AVAssetTrack: any
29
+ declare const NSError: any
30
+ declare const NSBundle: any
31
+ declare const NSFileManager: any
32
+ declare const NSMutableDictionary: any
33
+ declare const NSNotificationCenter: any
34
+ declare const NSOperationQueue: any
35
+ declare const NSURL: any
36
+ declare const NSNumber: any
37
+
38
+ declare const AVMediaTypeVideo: string
39
+ declare const AVMediaTypeAudio: string
40
+ declare const AVCaptureDeviceTypeBuiltInWideAngleCamera: string
41
+ declare const AVCaptureDeviceTypeExternalUnknown: string
42
+ declare const AVCaptureSessionPreset1280x720: string
43
+ declare const AVCaptureSessionWasInterruptedNotification: string
44
+ declare const AVCaptureSessionInterruptionEndedNotification: string
45
+ declare const AVCaptureSessionRuntimeErrorNotification: string
46
+ declare const AVCaptureSessionDidStartRunningNotification: string
47
+ declare const AVCaptureSessionDidStopRunningNotification: string
48
+ declare const AVCaptureDeviceWasDisconnectedNotification: string
49
+ declare const AVCaptureDeviceWasConnectedNotification: string
50
+ declare const AVVideoCodecKey: string
51
+ declare const AVVideoCodecTypeJPEG: string
52
+ declare const AVErrorRecordingSuccessfullyFinishedKey: string
53
+
54
+ declare const CMTimeGetSeconds: (time: unknown) => number
55
+ declare const CMTimeMakeWithSeconds: (seconds: number, timescale: number) => unknown
56
+ declare const CMVideoFormatDescriptionGetDimensions: (desc: unknown) => {
57
+ width: number
58
+ height: number
59
+ }
60
+
61
+ declare const CMFormatDescriptionGetMediaSubType: (desc: unknown) => number
62
+
63
+ // AVAuthorizationStatus.
64
+ const authNotDetermined = 0
65
+ const authRestricted = 1
66
+ const authDenied = 2
67
+ const authAuthorized = 3
68
+
69
+ // AVErrorMaximumDurationReached — the constant is absent from the bridge
70
+ // metadata; the numeric value is stable ABI in AVFoundation/AVError.h.
71
+ const avErrorMaximumDurationReached = -11847
72
+
73
+ const typed = (object: any, cls: any): any =>
74
+ object == null ? object : Object.setPrototypeOf(object, cls.prototype)
75
+
76
+ let RecordingDelegateClass: any
77
+ const recordingDelegateClass = () => {
78
+ // captureOutput:didStartRecordingToOutputFileAtURL:fromConnections: is
79
+ // deliberately absent: delivering it to a JS delegate crashes the host —
80
+ // it fires re-entrantly while startRecording is still returning. Start
81
+ // confirmation is synthesized from isRecording polling instead (see
82
+ // startRecording), which preserves the recordingStarted contract.
83
+ RecordingDelegateClass ??= NSObject.extend(
84
+ {
85
+ captureOutputDidFinishRecordingToOutputFileAtURLFromConnectionsError(
86
+ output: any,
87
+ url: any,
88
+ _connections: any,
89
+ error: any,
90
+ ) {
91
+ ;(this as any).onFinish?.(output, url, error)
92
+ },
93
+ },
94
+ {
95
+ protocols: [AVCaptureFileOutputRecordingDelegate],
96
+ exposedMethods: {
97
+ 'captureOutput:didFinishRecordingToOutputFileURL:fromConnections:error:': {
98
+ params: [interop.types.id, interop.types.id, interop.types.id, interop.types.id],
99
+ returns: interop.types.void,
100
+ },
101
+ },
102
+ },
103
+ )
104
+
105
+ return RecordingDelegateClass
106
+ }
107
+
108
+ let PhotoDelegateClass: any
109
+ const photoDelegateClass = () => {
110
+ PhotoDelegateClass ??= NSObject.extend(
111
+ {
112
+ captureOutputDidFinishProcessingPhotoError(_output: any, photo: any, error: any) {
113
+ ;(this as any).onPhoto?.(photo, error)
114
+ },
115
+ },
116
+ {
117
+ protocols: [AVCapturePhotoCaptureDelegate],
118
+ exposedMethods: {
119
+ 'captureOutput:didFinishProcessingPhoto:error:': {
120
+ params: [interop.types.id, interop.types.id, interop.types.id],
121
+ returns: interop.types.void,
122
+ },
123
+ },
124
+ },
125
+ )
126
+
127
+ return PhotoDelegateClass
128
+ }
129
+
130
+ // Shared across preview, movie and still-photo hosts: a busy source is never
131
+ // stolen. Single-threaded JS makes the Swift NSLock unnecessary.
132
+ const cameraOwners = new Map<string, object>()
133
+ const claimCamera = (id: string, owner: object): boolean => {
134
+ const current = cameraOwners.get(id)
135
+
136
+ if (current !== undefined && current !== owner) {
137
+ return false
138
+ }
139
+
140
+ cameraOwners.set(id, owner)
141
+ return true
142
+ }
143
+
144
+ const releaseCamera = (id: string, owner: object): void => {
145
+ if (cameraOwners.get(id) === owner) {
146
+ cameraOwners.delete(id)
147
+ }
148
+ }
149
+
150
+ // Degrees → AVCaptureVideoOrientation (landscapeRight native = 0).
151
+ const orientationForAngle = (angle: number): number | undefined =>
152
+ angle === 0 ? 3 : angle === 90 ? 1 : angle === 180 ? 4 : angle === 270 ? 2 : undefined
153
+
154
+ const fourCharCode = (value: number): string =>
155
+ String.fromCharCode(
156
+ (value >>> 24) & 0xff,
157
+ (value >>> 16) & 0xff,
158
+ (value >>> 8) & 0xff,
159
+ value & 0xff,
160
+ )
161
+
162
+ export interface CameraHost {
163
+ attachPreview(view: object): string | null
164
+ detachPreview(): void
165
+ installObserver(listener: (message: string) => void): void
166
+ permissionStatus(kind: string): string
167
+ requestPermissionReply(kind: string, reply: (status: string) => void): void
168
+ devices(): string
169
+ audioDeviceAvailable(): boolean
170
+ audioInputAttached(): boolean
171
+ activeDeviceId(): string | null
172
+ configure(options: {
173
+ cameraId?: string
174
+ photo?: boolean
175
+ audio?: boolean
176
+ rotationAngle?: number
177
+ }): string | null
178
+ focusAtPoint(point: { x: number; y: number }): boolean
179
+ supportsRotationAngles(): boolean
180
+ movieDirectory(): string | null
181
+ startRecording(path: string, maximumDurationMs: number): string | null
182
+ stopRecording(): void
183
+ recording(): boolean
184
+ recordedMs(): number
185
+ previewSize(): string
186
+ capturePhoto(reply: (data: unknown) => void): string | null
187
+ dispose(): void
188
+ }
189
+
190
+ /** One capture host: an AVCaptureSession shared by an optional preview layer,
191
+ * one still-photo output and one movie-file output at a time. */
192
+ export function createCameraHost(): CameraHost {
193
+ objc.import('AVFoundation')
194
+ objc.import('CoreMedia')
195
+ objc.import('QuartzCore')
196
+ objc.import('AppKit')
197
+
198
+ let session: any
199
+ let videoInput: any
200
+ let audioInput: any
201
+ let movieOutput: any
202
+ let photoOutput: any
203
+ let photoReply: ((data: any) => void) | undefined
204
+ let photoDelegate: any
205
+ let claimedCameraIds = new Set<string>()
206
+ let previewLayer: any
207
+ let previewView: WeakRef<any> | null = null
208
+ let configuredCameraId: string | undefined
209
+ let rotationAngle: number | undefined
210
+ let emit: ((message: string) => void) | undefined
211
+ let observers: any[] = []
212
+ let disposed = false
213
+ let recordingPath: string | undefined
214
+ let recordingDelegate: any
215
+ let startPollTimer: ReturnType<typeof setInterval> | undefined
216
+
217
+ // Serial session operations: detached ops (start/stopRunning) run one at a
218
+ // time; synchronous ops wait behind any in-flight detached op, matching the
219
+ // Swift private serial queue.
220
+ type DetachedKind = 'start' | 'stop'
221
+ interface InFlightOp {
222
+ id: number
223
+ kind: DetachedKind
224
+ }
225
+
226
+ let opInFlight: InFlightOp | undefined
227
+ let nextOpId = 0
228
+ const opQueue: Array<{ kind: DetachedKind; run: () => void }> = []
229
+ const drainOps = () => {
230
+ if (opInFlight || !opQueue.length) {
231
+ return
232
+ }
233
+
234
+ const op = opQueue.shift()!
235
+
236
+ op.run()
237
+ }
238
+
239
+ const enqueueOp = (kind: DetachedKind, run: () => void) => {
240
+ opQueue.push({ kind, run })
241
+ drainOps()
242
+ }
243
+
244
+ const detached = (kind: DetachedKind, fn: () => void) => {
245
+ const current: InFlightOp = { id: ++nextOpId, kind }
246
+
247
+ opInFlight = current
248
+ fn()
249
+ // Detached native dispatch has no completion callback; the paired
250
+ // session notification releases the queue. A generation-scoped stall
251
+ // guard keeps a lost notification from wedging later operations without
252
+ // releasing a successor's gate.
253
+ setTimeout(() => {
254
+ if (opInFlight === current) {
255
+ opInFlight = undefined
256
+ drainOps()
257
+ }
258
+ }, 2000)
259
+ }
260
+
261
+ const releaseOp = (kind?: DetachedKind) => {
262
+ if (opInFlight && (kind === undefined || opInFlight.kind === kind)) {
263
+ opInFlight = undefined
264
+ drainOps()
265
+ }
266
+ }
267
+
268
+ const send = (payload: Record<string, unknown>) => {
269
+ try {
270
+ emit?.(JSON.stringify(payload))
271
+ } catch {
272
+ // A failed listener must not fault the session.
273
+ }
274
+ }
275
+
276
+ const statusFor = (mediaType: string): string => {
277
+ switch (AVCaptureDevice.authorizationStatusForMediaType(mediaType)) {
278
+ case authAuthorized:
279
+ return 'granted'
280
+ case authDenied:
281
+ return 'denied'
282
+ case authRestricted:
283
+ return 'restricted'
284
+ case authNotDetermined:
285
+ return 'notDetermined'
286
+ default:
287
+ return 'unknown'
288
+ }
289
+ }
290
+
291
+ const mediaKind = (kind: string) => (kind === 'microphone' ? AVMediaTypeAudio : AVMediaTypeVideo)
292
+ const declared = (mediaType: string) => {
293
+ const key =
294
+ mediaType === AVMediaTypeAudio ? 'NSMicrophoneUsageDescription' : 'NSCameraUsageDescription'
295
+
296
+ return NSBundle.mainBundle.objectForInfoDictionaryKey(key) != null
297
+ }
298
+
299
+ const cameraDevices = (): any[] => {
300
+ const discovery =
301
+ AVCaptureDeviceDiscoverySession.discoverySessionWithDeviceTypesMediaTypePosition(
302
+ [AVCaptureDeviceTypeBuiltInWideAngleCamera, AVCaptureDeviceTypeExternalUnknown],
303
+ AVMediaTypeVideo,
304
+ 0,
305
+ )
306
+
307
+ typed(discovery, AVCaptureDeviceDiscoverySession)
308
+
309
+ const found: any[] = []
310
+ const list = discovery.devices
311
+
312
+ for (let i = 0; i < (list?.count ?? 0); i++) {
313
+ found.push(list.objectAtIndex(i))
314
+ }
315
+
316
+ // The discovery session is authoritative; keep the legacy enumerator as
317
+ // a merge source for devices on older system builds.
318
+ const legacy = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo)
319
+
320
+ for (let i = 0; i < (legacy?.count ?? 0); i++) {
321
+ const device = legacy.objectAtIndex(i)
322
+
323
+ if (!found.some((entry) => entry === device || entry.isEqual?.(device))) {
324
+ found.push(device)
325
+ }
326
+ }
327
+
328
+ for (const device of found) {
329
+ typed(device, AVCaptureDevice)
330
+ }
331
+
332
+ return found
333
+ }
334
+
335
+ const movieClipInfo = (url: any) => {
336
+ const asset = typed(AVURLAsset.alloc().initWithURL(url), AVURLAsset)
337
+ let width = 0,
338
+ height = 0,
339
+ rotation = 0
340
+
341
+ let videoCodec: string | undefined
342
+ const videoTracks = asset.tracksWithMediaType(AVMediaTypeVideo)
343
+
344
+ if (videoTracks.count > 0) {
345
+ const track = typed(videoTracks.objectAtIndex(0), AVAssetTrack)
346
+ const size = track.naturalSize
347
+ const t = track.preferredTransform
348
+
349
+ width = Math.abs(size.width * t.a + size.height * t.c)
350
+ height = Math.abs(size.width * t.b + size.height * t.d)
351
+ rotation = (Math.atan2(t.b, t.a) * 180) / Math.PI
352
+ if (rotation < 0) {
353
+ rotation += 360
354
+ }
355
+
356
+ const descriptions = track.formatDescriptions
357
+
358
+ if (descriptions.count > 0) {
359
+ const subtype = fourCharCode(
360
+ CMFormatDescriptionGetMediaSubType(descriptions.objectAtIndex(0)),
361
+ )
362
+
363
+ if (subtype === 'avc1') {
364
+ videoCodec = 'avc1'
365
+ } else if (subtype === 'hvc1' || subtype === 'hev1') {
366
+ videoCodec = 'hvc1'
367
+ }
368
+ }
369
+ }
370
+
371
+ const duration = CMTimeGetSeconds(asset.duration)
372
+ const attrs = NSFileManager.defaultManager.attributesOfItemAtPathError(String(url.path), null)
373
+ const size = Number(attrs?.objectForKey?.('NSFileSize') ?? 0)
374
+ const info: Record<string, unknown> = {
375
+ fileUrl: String(url.absoluteString),
376
+ durationMs: Number.isFinite(duration) ? duration * 1000 : 0,
377
+ width,
378
+ height,
379
+ rotationAngle: (Math.round(rotation / 90) * 90) % 360,
380
+ fileSize: Number.isFinite(size) ? size : 0,
381
+ hasAudio: asset.tracksWithMediaType(AVMediaTypeAudio).count > 0,
382
+ mimeType: 'video/quicktime',
383
+ container: 'mov',
384
+ }
385
+
386
+ if (videoCodec) {
387
+ info.videoCodec = videoCodec
388
+ }
389
+
390
+ return info
391
+ }
392
+
393
+ const handleSessionNotification = (name: string) => {
394
+ switch (name) {
395
+ case AVCaptureSessionWasInterruptedNotification:
396
+ // macOS publishes no interruption-reason keys.
397
+ send({ type: 'interrupted', cause: 'unknown' })
398
+ return
399
+ case AVCaptureSessionInterruptionEndedNotification:
400
+ send({ type: 'interruptionEnded' })
401
+ return
402
+ case AVCaptureSessionRuntimeErrorNotification:
403
+ releaseOp()
404
+ send({ type: 'availability', available: false })
405
+ send({ type: 'interrupted', cause: 'cameraInUse' })
406
+ return
407
+ case AVCaptureSessionDidStartRunningNotification:
408
+ releaseOp('start')
409
+ send({ type: 'previewReady', ready: true })
410
+ return
411
+ case AVCaptureSessionDidStopRunningNotification:
412
+ releaseOp('stop')
413
+ send({ type: 'previewReady', ready: false })
414
+ return
415
+ }
416
+ }
417
+
418
+ const ensureSession = (): any => {
419
+ if (session) {
420
+ return session
421
+ }
422
+
423
+ if (statusFor(AVMediaTypeVideo) !== 'granted') {
424
+ return undefined
425
+ }
426
+
427
+ const created = typed(AVCaptureSession.alloc().init(), AVCaptureSession)
428
+
429
+ if (created.canSetSessionPreset(AVCaptureSessionPreset1280x720)) {
430
+ created.sessionPreset = AVCaptureSessionPreset1280x720
431
+ }
432
+
433
+ session = created
434
+
435
+ const center = NSNotificationCenter.defaultCenter
436
+
437
+ for (const name of [
438
+ AVCaptureSessionWasInterruptedNotification,
439
+ AVCaptureSessionInterruptionEndedNotification,
440
+ AVCaptureSessionRuntimeErrorNotification,
441
+ AVCaptureSessionDidStartRunningNotification,
442
+ AVCaptureSessionDidStopRunningNotification,
443
+ ]) {
444
+ observers.push(
445
+ center.addObserverForNameObjectQueueUsingBlock(
446
+ name,
447
+ created,
448
+ NSOperationQueue.mainQueue,
449
+ () => handleSessionNotification(name),
450
+ ),
451
+ )
452
+ }
453
+
454
+ for (const [name, available] of [
455
+ [AVCaptureDeviceWasDisconnectedNotification, false],
456
+ [AVCaptureDeviceWasConnectedNotification, true],
457
+ ] as const) {
458
+ observers.push(
459
+ center.addObserverForNameObjectQueueUsingBlock(name, null, NSOperationQueue.mainQueue, () =>
460
+ send({ type: 'availability', available }),
461
+ ),
462
+ )
463
+ }
464
+
465
+ return created
466
+ }
467
+
468
+ const applyOrientation = (connection: any) => {
469
+ if (connection == null || rotationAngle === undefined) {
470
+ return
471
+ }
472
+
473
+ typed(connection, AVCaptureConnection)
474
+
475
+ const orientation = orientationForAngle(rotationAngle)
476
+
477
+ if (orientation !== undefined && connection.isVideoOrientationSupported()) {
478
+ connection.videoOrientation = orientation
479
+ }
480
+ }
481
+
482
+ const configure = (options: {
483
+ cameraId?: string
484
+ photo?: boolean
485
+ audio?: boolean
486
+ rotationAngle?: number
487
+ }): string | null => {
488
+ if (disposed) {
489
+ return 'unavailable'
490
+ }
491
+
492
+ const current = ensureSession()
493
+
494
+ if (!current) {
495
+ return 'permissionDenied'
496
+ }
497
+
498
+ // Synchronous on the JS thread — identical blocking semantics to the
499
+ // Swift queue.sync. begin/commit mutations are legal while a detached
500
+ // start/stop is in flight (AVFoundation's designed use), so a configure
501
+ // issued behind a detached op may overlap it; detached start/stop ops
502
+ // themselves stay strictly serialized.
503
+ return configureNow(options)
504
+ }
505
+
506
+ const configureNow = (options: {
507
+ cameraId?: string
508
+ photo?: boolean
509
+ audio?: boolean
510
+ rotationAngle?: number
511
+ }): string | null => {
512
+ if (disposed) {
513
+ return 'unavailable'
514
+ }
515
+
516
+ const cameraId = options.cameraId
517
+ const photo = options.photo === true
518
+ const audio = !photo && options.audio === true
519
+
520
+ rotationAngle = typeof options.rotationAngle === 'number' ? options.rotationAngle : undefined
521
+
522
+ const devices = cameraDevices()
523
+ const device =
524
+ cameraId != null
525
+ ? devices.find((entry) => String(entry.uniqueID) === cameraId)
526
+ : (devices[0] ??
527
+ typed(AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo), AVCaptureDevice))
528
+
529
+ if (!device) {
530
+ return 'unavailable'
531
+ }
532
+
533
+ const deviceId = String(device.uniqueID)
534
+
535
+ if (!claimCamera(deviceId, host)) {
536
+ return 'busy'
537
+ }
538
+
539
+ claimedCameraIds.add(deviceId)
540
+
541
+ let failure: string | null = null
542
+ let videoConnection: any
543
+
544
+ try {
545
+ session.beginConfiguration()
546
+ if (videoInput == null || String(videoInput.device.uniqueID) !== deviceId) {
547
+ const alloc = typed(AVCaptureDeviceInput.alloc(), AVCaptureDeviceInput)
548
+ const input = typed(alloc.initWithDeviceError(device, null), AVCaptureDeviceInput)
549
+
550
+ if (input == null) {
551
+ throw new Error('input')
552
+ }
553
+
554
+ if (videoInput != null) {
555
+ session.removeInput(videoInput)
556
+ }
557
+
558
+ videoInput = input
559
+ if (session.canAddInput(input)) {
560
+ session.addInput(input)
561
+ } else {
562
+ failure = 'unavailable'
563
+ }
564
+ }
565
+
566
+ if (audio && audioInput == null) {
567
+ const microphone = typed(
568
+ AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeAudio),
569
+ AVCaptureDevice,
570
+ )
571
+
572
+ if (microphone) {
573
+ const alloc = typed(AVCaptureDeviceInput.alloc(), AVCaptureDeviceInput)
574
+ const input = typed(alloc.initWithDeviceError(microphone, null), AVCaptureDeviceInput)
575
+
576
+ if (input != null && session.canAddInput(input)) {
577
+ audioInput = input
578
+ session.addInput(input)
579
+ }
580
+ }
581
+ } else if (!audio && audioInput != null) {
582
+ session.removeInput(audioInput)
583
+ audioInput = undefined
584
+ }
585
+
586
+ if (photo && photoOutput == null) {
587
+ const output = AVCapturePhotoOutput.new()
588
+
589
+ if (session.canAddOutput(output)) {
590
+ session.addOutput(output)
591
+ photoOutput = typed(output, AVCapturePhotoOutput)
592
+ } else {
593
+ failure = 'unavailable'
594
+ }
595
+ }
596
+
597
+ if (!photo && movieOutput == null) {
598
+ const output = AVCaptureMovieFileOutput.new()
599
+
600
+ if (session.canAddOutput(output)) {
601
+ session.addOutput(output)
602
+ movieOutput = typed(output, AVCaptureMovieFileOutput)
603
+ }
604
+ }
605
+
606
+ session.commitConfiguration()
607
+ if (rotationAngle !== undefined) {
608
+ videoConnection = typed(
609
+ movieOutput?.connectionWithMediaType(AVMediaTypeVideo),
610
+ AVCaptureConnection,
611
+ )
612
+
613
+ const supported =
614
+ videoConnection != null &&
615
+ orientationForAngle(rotationAngle) !== undefined &&
616
+ videoConnection.isVideoOrientationSupported() === true
617
+
618
+ if (!supported) {
619
+ failure = 'unsupportedConfiguration'
620
+ }
621
+ }
622
+ } catch {
623
+ try {
624
+ session.commitConfiguration()
625
+ } catch {
626
+ // A committed-partial configuration is already consistent.
627
+ }
628
+
629
+ return 'unavailable'
630
+ }
631
+
632
+ if (failure != null) {
633
+ return failure
634
+ }
635
+
636
+ // Failed reconfiguration may retain either input. Hold both claims until
637
+ // disposal rather than admitting an overlapping session.
638
+ for (const old of claimedCameraIds) {
639
+ if (old !== deviceId) {
640
+ releaseCamera(old, host)
641
+ }
642
+ }
643
+
644
+ claimedCameraIds = new Set([deviceId])
645
+ configuredCameraId = deviceId
646
+ applyOrientation(videoConnection)
647
+ applyOrientation(previewLayer?.connection)
648
+ return null
649
+ }
650
+
651
+ const host = {
652
+ attachPreview(view: object): string | null {
653
+ const current = ensureSession()
654
+
655
+ if (!current) {
656
+ return 'permissionDenied'
657
+ }
658
+
659
+ previewView = new WeakRef(view as any)
660
+ previewLayer = typed(
661
+ AVCaptureVideoPreviewLayer.layerWithSession(current),
662
+ AVCaptureVideoPreviewLayer,
663
+ )
664
+
665
+ previewLayer.videoGravity = 'AVLayerVideoGravityResizeAspectFill'
666
+
667
+ ;(view as any).wantsLayer = true
668
+ previewLayer.frame = {
669
+ origin: { x: 0, y: 0 },
670
+ size: (view as any).bounds?.size ?? { width: 0, height: 0 },
671
+ }
672
+
673
+ previewLayer.autoresizingMask = (1 << 4) | (1 << 2)
674
+
675
+ ;(view as any).layer?.addSublayer(previewLayer)
676
+ applyOrientation(previewLayer.connection)
677
+ enqueueOp('start', () =>
678
+ detached('start', () => {
679
+ if (!disposed && !session.isRunning()) {
680
+ session.performSelectorInBackgroundWithObject('startRunning', null)
681
+ } else {
682
+ releaseOp()
683
+ }
684
+ }),
685
+ )
686
+
687
+ return null
688
+ },
689
+ detachPreview(): void {
690
+ previewLayer?.removeFromSuperlayer()
691
+ previewLayer = undefined
692
+ previewView = null
693
+ enqueueOp('stop', () =>
694
+ detached('stop', () => {
695
+ session?.performSelectorInBackgroundWithObject('stopRunning', null)
696
+ }),
697
+ )
698
+ },
699
+ installObserver(listener: (message: string) => void): void {
700
+ emit = listener
701
+ },
702
+ permissionStatus(kind: string): string {
703
+ const mediaType = mediaKind(kind)
704
+
705
+ return declared(mediaType) ? statusFor(mediaType) : 'undeclared'
706
+ },
707
+ requestPermissionReply(kind: string, reply: (status: string) => void): void {
708
+ const mediaType = mediaKind(kind)
709
+
710
+ if (!declared(mediaType)) {
711
+ reply('undeclared')
712
+ return
713
+ }
714
+
715
+ const current = statusFor(mediaType)
716
+
717
+ if (current !== 'notDetermined') {
718
+ reply(current)
719
+ return
720
+ }
721
+
722
+ AVCaptureDevice.requestAccessForMediaTypeCompletionHandler(mediaType, () => {
723
+ NSOperationQueue.mainQueue.addOperationWithBlock(() => reply(statusFor(mediaType)))
724
+ })
725
+ },
726
+ devices(): string {
727
+ try {
728
+ return JSON.stringify(
729
+ cameraDevices().map((device) => ({
730
+ id: String(device.uniqueID),
731
+ name: String(device.localizedName),
732
+ facing: null,
733
+ focusPointOfInterest: device.isFocusPointOfInterestSupported?.() === true,
734
+ exposurePointOfInterest: device.isExposurePointOfInterestSupported?.() === true,
735
+ })),
736
+ )
737
+ } catch {
738
+ return '[]'
739
+ }
740
+ },
741
+ audioDeviceAvailable(): boolean {
742
+ return (AVCaptureDevice.devicesWithMediaType(AVMediaTypeAudio)?.count ?? 0) > 0
743
+ },
744
+ audioInputAttached(): boolean {
745
+ return audioInput != null
746
+ },
747
+ activeDeviceId(): string | null {
748
+ return videoInput != null ? String(videoInput.device.uniqueID) : null
749
+ },
750
+ configure(options: {
751
+ cameraId?: string
752
+ photo?: boolean
753
+ audio?: boolean
754
+ rotationAngle?: number
755
+ }): string | null {
756
+ return configure(options)
757
+ },
758
+ /** Meters one autofocus/auto-exposure pass at a normalized preview point
759
+ * (0-1, top-left origin as the user sees it). */
760
+ focusAtPoint(point: { x: number; y: number }): boolean {
761
+ if (disposed || previewLayer == null) {
762
+ return false
763
+ }
764
+
765
+ const bounds = previewLayer.bounds
766
+ const layerPoint = {
767
+ x: Math.min(Math.max(point.x, 0), 1) * bounds.size.width,
768
+ y: Math.min(Math.max(point.y, 0), 1) * bounds.size.height,
769
+ }
770
+
771
+ const view = previewView?.deref()
772
+
773
+ if (view != null && view.isFlipped?.() === false) {
774
+ layerPoint.y = bounds.size.height - layerPoint.y
775
+ }
776
+
777
+ const devicePoint = previewLayer.captureDevicePointOfInterestForPoint(layerPoint)
778
+ const device = videoInput?.device
779
+
780
+ if (device == null) {
781
+ return false
782
+ }
783
+
784
+ const focus =
785
+ device.isFocusPointOfInterestSupported?.() === true &&
786
+ device.isFocusModeSupported?.(1) === true
787
+
788
+ const expose =
789
+ device.isExposurePointOfInterestSupported?.() === true &&
790
+ device.isExposureModeSupported?.(1) === true
791
+
792
+ if (!focus && !expose) {
793
+ return false
794
+ }
795
+
796
+ try {
797
+ if (!device.lockForConfiguration(null)) {
798
+ return false
799
+ }
800
+
801
+ if (focus) {
802
+ device.focusPointOfInterest = devicePoint
803
+ device.focusMode = 1 // autoFocus
804
+ }
805
+
806
+ if (expose) {
807
+ device.exposurePointOfInterest = devicePoint
808
+ device.exposureMode = 1 // autoExpose
809
+ }
810
+
811
+ device.unlockForConfiguration()
812
+ return true
813
+ } catch {
814
+ return false
815
+ }
816
+ },
817
+ supportsRotationAngles(): boolean {
818
+ return (
819
+ typeof AVCaptureConnection.instancesRespondToSelector === 'function' &&
820
+ AVCaptureConnection.instancesRespondToSelector('isVideoOrientationSupported') === true
821
+ )
822
+ },
823
+ movieDirectory(): string | null {
824
+ const urls = NSFileManager.defaultManager.URLsForDirectoryInDomains(14, 1)
825
+ const base = urls?.count > 0 ? urls.objectAtIndex(0) : null
826
+
827
+ if (base == null) {
828
+ return null
829
+ }
830
+
831
+ const identifier = NSBundle.mainBundle.bundleIdentifier
832
+ const bundleId = identifier == null ? 'org.octane.xplat' : String(identifier)
833
+ const directory = base
834
+ .URLByAppendingPathComponent(bundleId)
835
+ .URLByAppendingPathComponent('octane-camera')
836
+
837
+ const manager = NSFileManager.defaultManager
838
+
839
+ if (
840
+ !manager.createDirectoryAtURLWithIntermediateDirectoriesAttributesError(
841
+ directory,
842
+ true,
843
+ null,
844
+ null,
845
+ )
846
+ ) {
847
+ return null
848
+ }
849
+
850
+ return String(directory.absoluteString)
851
+ },
852
+ startRecording(path: string, maximumDurationMs: number): string | null {
853
+ // Recording without active connections raises an ObjC exception —
854
+ // fatal to the host. The session must be running.
855
+ if (session == null || movieOutput == null || session.isRunning() !== true) {
856
+ return 'unavailable'
857
+ }
858
+
859
+ const url = NSURL.fileURLWithPath(path)
860
+
861
+ recordingPath = path
862
+ movieOutput.maxRecordedDuration =
863
+ maximumDurationMs > 0
864
+ ? CMTimeMakeWithSeconds(maximumDurationMs / 1000, 1000)
865
+ : ({ seconds: 0, timescale: 0, flags: 0, epoch: 0 } as any)
866
+
867
+ recordingDelegate = recordingDelegateClass().new()
868
+ recordingDelegate.onFinish = (_output: any, fileUrl: any, failure: any) => {
869
+ const succeeded =
870
+ failure == null ||
871
+ failure.userInfo?.objectForKey?.(AVErrorRecordingSuccessfullyFinishedKey) === true
872
+
873
+ const limitReached = failure != null && failure.code === avErrorMaximumDurationReached
874
+ const payload: Record<string, unknown> = {
875
+ type: 'recordingFinished',
876
+ fileUrl: String(fileUrl.absoluteString),
877
+ succeeded,
878
+ limitReached,
879
+ }
880
+
881
+ const filePath = String(fileUrl.path)
882
+
883
+ if (succeeded && NSFileManager.defaultManager.fileExistsAtPath(filePath)) {
884
+ payload.clip = movieClipInfo(fileUrl)
885
+ } else {
886
+ try {
887
+ NSFileManager.defaultManager.removeItemAtURLError(fileUrl, null)
888
+ } catch {
889
+ // Reclaim only the file this attempt created.
890
+ }
891
+
892
+ payload.error = {
893
+ domain: failure != null ? String(failure.domain) : 'XplatCamera',
894
+ code: failure != null ? Number(failure.code) : -1,
895
+ message:
896
+ failure != null
897
+ ? String(failure.localizedDescription)
898
+ : 'Movie recording did not complete',
899
+ }
900
+ }
901
+
902
+ send(payload)
903
+ }
904
+
905
+ movieOutput.startRecordingToOutputFileURLRecordingDelegate(url, recordingDelegate)
906
+ // didStart cannot reach a JS delegate (host crash — see
907
+ // recordingDelegateClass). Poll isRecording to emit the same event.
908
+ if (startPollTimer !== undefined) {
909
+ clearInterval(startPollTimer)
910
+ }
911
+
912
+ let polls = 0
913
+
914
+ startPollTimer = setInterval(() => {
915
+ polls += 1
916
+ if (disposed || movieOutput == null || polls > 100) {
917
+ clearInterval(startPollTimer!)
918
+ startPollTimer = undefined
919
+ return
920
+ }
921
+
922
+ if (movieOutput.isRecording()) {
923
+ clearInterval(startPollTimer!)
924
+ startPollTimer = undefined
925
+ send({
926
+ type: 'recordingStarted',
927
+ fileUrl: String(url.absoluteString),
928
+ audio: audioInput != null,
929
+ })
930
+ }
931
+ }, 50)
932
+
933
+ return null
934
+ },
935
+ stopRecording(): void {
936
+ movieOutput?.stopRecording()
937
+ },
938
+ recording(): boolean {
939
+ return movieOutput?.isRecording() === true
940
+ },
941
+ recordedMs(): number {
942
+ const duration = movieOutput?.recordedDuration
943
+
944
+ if (duration == null) {
945
+ return 0
946
+ }
947
+
948
+ const seconds = CMTimeGetSeconds(duration)
949
+
950
+ return Number.isFinite(seconds) ? seconds * 1000 : 0
951
+ },
952
+ previewSize(): string {
953
+ const device = videoInput?.device
954
+
955
+ if (device == null) {
956
+ return '{}'
957
+ }
958
+
959
+ const format = typed(device.activeFormat, g.AVCaptureDeviceFormat)
960
+
961
+ if (format == null) {
962
+ return '{}'
963
+ }
964
+
965
+ const dimensions = CMVideoFormatDescriptionGetDimensions(format.formatDescription)
966
+
967
+ return `{"width":${dimensions.width},"height":${dimensions.height}}`
968
+ },
969
+ capturePhoto(reply: (data: any) => void): string | null {
970
+ if (disposed || photoReply != null || photoOutput == null || session?.isRunning() !== true) {
971
+ return 'unavailable'
972
+ }
973
+
974
+ const codecs = photoOutput.availablePhotoCodecTypes
975
+
976
+ if (codecs == null || !codecs.containsObject(AVVideoCodecTypeJPEG)) {
977
+ return 'unavailable'
978
+ }
979
+
980
+ const delegate = photoDelegateClass().new()
981
+
982
+ photoDelegate = delegate
983
+ delegate.onPhoto = (photo: any, error: any) => {
984
+ const callback = photoReply
985
+
986
+ photoReply = undefined
987
+ photoDelegate = undefined
988
+ callback?.(
989
+ error == null && photo != null
990
+ ? typed(photo, AVCapturePhoto).fileDataRepresentation()
991
+ : null,
992
+ )
993
+ }
994
+
995
+ photoReply = reply
996
+
997
+ const format = NSMutableDictionary.dictionary()
998
+
999
+ format.setObjectForKey(AVVideoCodecTypeJPEG, AVVideoCodecKey)
1000
+
1001
+ const settings = AVCapturePhotoSettings.photoSettingsWithFormat(format)
1002
+
1003
+ photoOutput.capturePhotoWithSettingsDelegate(settings, delegate)
1004
+ return null
1005
+ },
1006
+ dispose(): void {
1007
+ if (disposed) {
1008
+ return
1009
+ }
1010
+
1011
+ disposed = true
1012
+
1013
+ const center = NSNotificationCenter.defaultCenter
1014
+
1015
+ for (const observer of observers) {
1016
+ center.removeObserver(observer)
1017
+ }
1018
+
1019
+ observers = []
1020
+ previewLayer?.removeFromSuperlayer()
1021
+ previewLayer = undefined
1022
+ previewView = null
1023
+ photoReply = undefined
1024
+ photoDelegate = undefined
1025
+ if (startPollTimer !== undefined) {
1026
+ clearInterval(startPollTimer)
1027
+ startPollTimer = undefined
1028
+ }
1029
+
1030
+ const ending = session
1031
+ const claims = [...claimedCameraIds]
1032
+
1033
+ enqueueOp('stop', () =>
1034
+ detached('stop', () => {
1035
+ ending?.performSelectorInBackgroundWithObject('stopRunning', null)
1036
+ // Keep the claims until the session stop is dispatched: releasing
1037
+ // sooner could admit another host while AVFoundation still holds
1038
+ // the hardware.
1039
+ for (const id of claims) {
1040
+ releaseCamera(id, host)
1041
+ }
1042
+
1043
+ releaseOp()
1044
+ }),
1045
+ )
1046
+
1047
+ claimedCameraIds = new Set()
1048
+ session = undefined
1049
+ videoInput = undefined
1050
+ audioInput = undefined
1051
+ movieOutput = undefined
1052
+ photoOutput = undefined
1053
+ recordingDelegate = undefined
1054
+ emit = undefined
1055
+ },
1056
+ }
1057
+
1058
+ return host
1059
+ }